python_code
stringlengths
0
1.8M
repo_name
stringclasses
7 values
file_path
stringlengths
5
99
// SPDX-License-Identifier: GPL-2.0+ /* * Originally from efivars.c * * Copyright (C) 2001,2003,2004 Dell <[email protected]> * Copyright (C) 2004 Intel Corporation <[email protected]> */ #define pr_fmt(fmt) "efivars: " fmt #include <linux/types.h> #include <linux/sizes.h> #include <linux/errno.h> #include <linux/init.h> #include <linux/module.h> #include <linux/string.h> #include <linux/smp.h> #include <linux/efi.h> #include <linux/ucs2_string.h> /* Private pointer to registered efivars */ static struct efivars *__efivars; static DEFINE_SEMAPHORE(efivars_lock, 1); static efi_status_t check_var_size(bool nonblocking, u32 attributes, unsigned long size) { const struct efivar_operations *fops; efi_status_t status; fops = __efivars->ops; if (!fops->query_variable_store) status = EFI_UNSUPPORTED; else status = fops->query_variable_store(attributes, size, nonblocking); if (status == EFI_UNSUPPORTED) return (size <= SZ_64K) ? EFI_SUCCESS : EFI_OUT_OF_RESOURCES; return status; } /** * efivar_is_available - check if efivars is available * * @return true iff evivars is currently registered */ bool efivar_is_available(void) { return __efivars != NULL; } EXPORT_SYMBOL_GPL(efivar_is_available); /** * efivars_register - register an efivars * @efivars: efivars to register * @ops: efivars operations * * Only a single efivars can be registered at any time. */ int efivars_register(struct efivars *efivars, const struct efivar_operations *ops) { int rv; if (down_interruptible(&efivars_lock)) return -EINTR; if (__efivars) { pr_warn("efivars already registered\n"); rv = -EBUSY; goto out; } efivars->ops = ops; __efivars = efivars; pr_info("Registered efivars operations\n"); rv = 0; out: up(&efivars_lock); return rv; } EXPORT_SYMBOL_GPL(efivars_register); /** * efivars_unregister - unregister an efivars * @efivars: efivars to unregister * * The caller must have already removed every entry from the list, * failure to do so is an error. */ int efivars_unregister(struct efivars *efivars) { int rv; if (down_interruptible(&efivars_lock)) return -EINTR; if (!__efivars) { pr_err("efivars not registered\n"); rv = -EINVAL; goto out; } if (__efivars != efivars) { rv = -EINVAL; goto out; } pr_info("Unregistered efivars operations\n"); __efivars = NULL; rv = 0; out: up(&efivars_lock); return rv; } EXPORT_SYMBOL_GPL(efivars_unregister); bool efivar_supports_writes(void) { return __efivars && __efivars->ops->set_variable; } EXPORT_SYMBOL_GPL(efivar_supports_writes); /* * efivar_lock() - obtain the efivar lock, wait for it if needed * @return 0 on success, error code on failure */ int efivar_lock(void) { if (down_interruptible(&efivars_lock)) return -EINTR; if (!__efivars->ops) { up(&efivars_lock); return -ENODEV; } return 0; } EXPORT_SYMBOL_NS_GPL(efivar_lock, EFIVAR); /* * efivar_lock() - obtain the efivar lock if it is free * @return 0 on success, error code on failure */ int efivar_trylock(void) { if (down_trylock(&efivars_lock)) return -EBUSY; if (!__efivars->ops) { up(&efivars_lock); return -ENODEV; } return 0; } EXPORT_SYMBOL_NS_GPL(efivar_trylock, EFIVAR); /* * efivar_unlock() - release the efivar lock */ void efivar_unlock(void) { up(&efivars_lock); } EXPORT_SYMBOL_NS_GPL(efivar_unlock, EFIVAR); /* * efivar_get_variable() - retrieve a variable identified by name/vendor * * Must be called with efivars_lock held. */ efi_status_t efivar_get_variable(efi_char16_t *name, efi_guid_t *vendor, u32 *attr, unsigned long *size, void *data) { return __efivars->ops->get_variable(name, vendor, attr, size, data); } EXPORT_SYMBOL_NS_GPL(efivar_get_variable, EFIVAR); /* * efivar_get_next_variable() - enumerate the next name/vendor pair * * Must be called with efivars_lock held. */ efi_status_t efivar_get_next_variable(unsigned long *name_size, efi_char16_t *name, efi_guid_t *vendor) { return __efivars->ops->get_next_variable(name_size, name, vendor); } EXPORT_SYMBOL_NS_GPL(efivar_get_next_variable, EFIVAR); /* * efivar_set_variable_locked() - set a variable identified by name/vendor * * Must be called with efivars_lock held. If @nonblocking is set, it will use * non-blocking primitives so it is guaranteed not to sleep. */ efi_status_t efivar_set_variable_locked(efi_char16_t *name, efi_guid_t *vendor, u32 attr, unsigned long data_size, void *data, bool nonblocking) { efi_set_variable_t *setvar; efi_status_t status; if (data_size > 0) { status = check_var_size(nonblocking, attr, data_size + ucs2_strsize(name, 1024)); if (status != EFI_SUCCESS) return status; } /* * If no _nonblocking variant exists, the ordinary one * is assumed to be non-blocking. */ setvar = __efivars->ops->set_variable_nonblocking; if (!setvar || !nonblocking) setvar = __efivars->ops->set_variable; return setvar(name, vendor, attr, data_size, data); } EXPORT_SYMBOL_NS_GPL(efivar_set_variable_locked, EFIVAR); /* * efivar_set_variable() - set a variable identified by name/vendor * * Can be called without holding the efivars_lock. Will sleep on obtaining the * lock, or on obtaining other locks that are needed in order to complete the * call. */ efi_status_t efivar_set_variable(efi_char16_t *name, efi_guid_t *vendor, u32 attr, unsigned long data_size, void *data) { efi_status_t status; if (efivar_lock()) return EFI_ABORTED; status = efivar_set_variable_locked(name, vendor, attr, data_size, data, false); efivar_unlock(); return status; } EXPORT_SYMBOL_NS_GPL(efivar_set_variable, EFIVAR); efi_status_t efivar_query_variable_info(u32 attr, u64 *storage_space, u64 *remaining_space, u64 *max_variable_size) { if (!__efivars->ops->query_variable_info) return EFI_UNSUPPORTED; return __efivars->ops->query_variable_info(attr, storage_space, remaining_space, max_variable_size); } EXPORT_SYMBOL_NS_GPL(efivar_query_variable_info, EFIVAR);
linux-master
drivers/firmware/efi/vars.c
// SPDX-License-Identifier: GPL-2.0 /* * Extensible Firmware Interface * * Based on Extensible Firmware Interface Specification version 2.4 * * Copyright (C) 2013, 2014 Linaro Ltd. */ #include <linux/dmi.h> #include <linux/efi.h> #include <linux/io.h> #include <linux/memblock.h> #include <linux/mm_types.h> #include <linux/preempt.h> #include <linux/rbtree.h> #include <linux/rwsem.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/pgtable.h> #include <asm/cacheflush.h> #include <asm/efi.h> #include <asm/mmu.h> #include <asm/pgalloc.h> #if defined(CONFIG_PTDUMP_DEBUGFS) || defined(CONFIG_ARM_PTDUMP_DEBUGFS) #include <asm/ptdump.h> static struct ptdump_info efi_ptdump_info = { .mm = &efi_mm, .markers = (struct addr_marker[]){ { 0, "UEFI runtime start" }, { EFI_RUNTIME_MAP_END, "UEFI runtime end" }, { -1, NULL } }, .base_addr = 0, }; static int __init ptdump_init(void) { if (efi_enabled(EFI_RUNTIME_SERVICES)) ptdump_debugfs_register(&efi_ptdump_info, "efi_page_tables"); return 0; } device_initcall(ptdump_init); #endif static bool __init efi_virtmap_init(void) { efi_memory_desc_t *md; efi_mm.pgd = pgd_alloc(&efi_mm); mm_init_cpumask(&efi_mm); init_new_context(NULL, &efi_mm); for_each_efi_memory_desc(md) { phys_addr_t phys = md->phys_addr; int ret; if (!(md->attribute & EFI_MEMORY_RUNTIME)) continue; if (md->virt_addr == U64_MAX) return false; ret = efi_create_mapping(&efi_mm, md); if (ret) { pr_warn(" EFI remap %pa: failed to create mapping (%d)\n", &phys, ret); return false; } } if (efi_memattr_apply_permissions(&efi_mm, efi_set_mapping_permissions)) return false; return true; } /* * Enable the UEFI Runtime Services if all prerequisites are in place, i.e., * non-early mapping of the UEFI system table and virtual mappings for all * EFI_MEMORY_RUNTIME regions. */ static int __init arm_enable_runtime_services(void) { u64 mapsize; if (!efi_enabled(EFI_BOOT)) { pr_info("EFI services will not be available.\n"); return 0; } efi_memmap_unmap(); mapsize = efi.memmap.desc_size * efi.memmap.nr_map; if (efi_memmap_init_late(efi.memmap.phys_map, mapsize)) { pr_err("Failed to remap EFI memory map\n"); return 0; } if (efi_soft_reserve_enabled()) { efi_memory_desc_t *md; for_each_efi_memory_desc(md) { int md_size = md->num_pages << EFI_PAGE_SHIFT; struct resource *res; if (!(md->attribute & EFI_MEMORY_SP)) continue; res = kzalloc(sizeof(*res), GFP_KERNEL); if (WARN_ON(!res)) break; res->start = md->phys_addr; res->end = md->phys_addr + md_size - 1; res->name = "Soft Reserved"; res->flags = IORESOURCE_MEM; res->desc = IORES_DESC_SOFT_RESERVED; insert_resource(&iomem_resource, res); } } if (efi_runtime_disabled()) { pr_info("EFI runtime services will be disabled.\n"); return 0; } if (efi_enabled(EFI_RUNTIME_SERVICES)) { pr_info("EFI runtime services access via paravirt.\n"); return 0; } pr_info("Remapping and enabling EFI services.\n"); if (!efi_virtmap_init()) { pr_err("UEFI virtual mapping missing or invalid -- runtime services will not be available\n"); return -ENOMEM; } /* Set up runtime services function pointers */ efi_native_runtime_setup(); set_bit(EFI_RUNTIME_SERVICES, &efi.flags); return 0; } early_initcall(arm_enable_runtime_services); void efi_virtmap_load(void) { preempt_disable(); efi_set_pgd(&efi_mm); } void efi_virtmap_unload(void) { efi_set_pgd(current->active_mm); preempt_enable(); } static int __init arm_dmi_init(void) { /* * On arm64/ARM, DMI depends on UEFI, and dmi_setup() needs to * be called early because dmi_id_init(), which is an arch_initcall * itself, depends on dmi_scan_machine() having been called already. */ dmi_setup(); return 0; } core_initcall(arm_dmi_init);
linux-master
drivers/firmware/efi/arm-runtime.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2016 Linaro Ltd. <[email protected]> */ #define pr_fmt(fmt) "efi: memattr: " fmt #include <linux/efi.h> #include <linux/init.h> #include <linux/io.h> #include <linux/memblock.h> #include <asm/early_ioremap.h> static int __initdata tbl_size; unsigned long __ro_after_init efi_mem_attr_table = EFI_INVALID_TABLE_ADDR; /* * Reserve the memory associated with the Memory Attributes configuration * table, if it exists. */ int __init efi_memattr_init(void) { efi_memory_attributes_table_t *tbl; if (efi_mem_attr_table == EFI_INVALID_TABLE_ADDR) return 0; tbl = early_memremap(efi_mem_attr_table, sizeof(*tbl)); if (!tbl) { pr_err("Failed to map EFI Memory Attributes table @ 0x%lx\n", efi_mem_attr_table); return -ENOMEM; } if (tbl->version > 2) { pr_warn("Unexpected EFI Memory Attributes table version %d\n", tbl->version); goto unmap; } tbl_size = sizeof(*tbl) + tbl->num_entries * tbl->desc_size; memblock_reserve(efi_mem_attr_table, tbl_size); set_bit(EFI_MEM_ATTR, &efi.flags); unmap: early_memunmap(tbl, sizeof(*tbl)); return 0; } /* * Returns a copy @out of the UEFI memory descriptor @in if it is covered * entirely by a UEFI memory map entry with matching attributes. The virtual * address of @out is set according to the matching entry that was found. */ static bool entry_is_valid(const efi_memory_desc_t *in, efi_memory_desc_t *out) { u64 in_paddr = in->phys_addr; u64 in_size = in->num_pages << EFI_PAGE_SHIFT; efi_memory_desc_t *md; *out = *in; if (in->type != EFI_RUNTIME_SERVICES_CODE && in->type != EFI_RUNTIME_SERVICES_DATA) { pr_warn("Entry type should be RuntimeServiceCode/Data\n"); return false; } if (PAGE_SIZE > EFI_PAGE_SIZE && (!PAGE_ALIGNED(in->phys_addr) || !PAGE_ALIGNED(in->num_pages << EFI_PAGE_SHIFT))) { /* * Since arm64 may execute with page sizes of up to 64 KB, the * UEFI spec mandates that RuntimeServices memory regions must * be 64 KB aligned. We need to validate this here since we will * not be able to tighten permissions on such regions without * affecting adjacent regions. */ pr_warn("Entry address region misaligned\n"); return false; } for_each_efi_memory_desc(md) { u64 md_paddr = md->phys_addr; u64 md_size = md->num_pages << EFI_PAGE_SHIFT; if (!(md->attribute & EFI_MEMORY_RUNTIME)) continue; if (md->virt_addr == 0 && md->phys_addr != 0) { /* no virtual mapping has been installed by the stub */ break; } if (md_paddr > in_paddr || (in_paddr - md_paddr) >= md_size) continue; /* * This entry covers the start of @in, check whether * it covers the end as well. */ if (md_paddr + md_size < in_paddr + in_size) { pr_warn("Entry covers multiple EFI memory map regions\n"); return false; } if (md->type != in->type) { pr_warn("Entry type deviates from EFI memory map region type\n"); return false; } out->virt_addr = in_paddr + (md->virt_addr - md_paddr); return true; } pr_warn("No matching entry found in the EFI memory map\n"); return false; } /* * To be called after the EFI page tables have been populated. If a memory * attributes table is available, its contents will be used to update the * mappings with tightened permissions as described by the table. * This requires the UEFI memory map to have already been populated with * virtual addresses. */ int __init efi_memattr_apply_permissions(struct mm_struct *mm, efi_memattr_perm_setter fn) { efi_memory_attributes_table_t *tbl; bool has_bti = false; int i, ret; if (tbl_size <= sizeof(*tbl)) return 0; /* * We need the EFI memory map to be setup so we can use it to * lookup the virtual addresses of all entries in the of EFI * Memory Attributes table. If it isn't available, this * function should not be called. */ if (WARN_ON(!efi_enabled(EFI_MEMMAP))) return 0; tbl = memremap(efi_mem_attr_table, tbl_size, MEMREMAP_WB); if (!tbl) { pr_err("Failed to map EFI Memory Attributes table @ 0x%lx\n", efi_mem_attr_table); return -ENOMEM; } if (tbl->version > 1 && (tbl->flags & EFI_MEMORY_ATTRIBUTES_FLAGS_RT_FORWARD_CONTROL_FLOW_GUARD)) has_bti = true; if (efi_enabled(EFI_DBG)) pr_info("Processing EFI Memory Attributes table:\n"); for (i = ret = 0; ret == 0 && i < tbl->num_entries; i++) { efi_memory_desc_t md; unsigned long size; bool valid; char buf[64]; valid = entry_is_valid((void *)tbl->entry + i * tbl->desc_size, &md); size = md.num_pages << EFI_PAGE_SHIFT; if (efi_enabled(EFI_DBG) || !valid) pr_info("%s 0x%012llx-0x%012llx %s\n", valid ? "" : "!", md.phys_addr, md.phys_addr + size - 1, efi_md_typeattr_format(buf, sizeof(buf), &md)); if (valid) { ret = fn(mm, &md, has_bti); if (ret) pr_err("Error updating mappings, skipping subsequent md's\n"); } } memunmap(tbl); return ret; }
linux-master
drivers/firmware/efi/memattr.c
// SPDX-License-Identifier: GPL-2.0+ /* * esrt.c * * This module exports EFI System Resource Table (ESRT) entries into userspace * through the sysfs file system. The ESRT provides a read-only catalog of * system components for which the system accepts firmware upgrades via UEFI's * "Capsule Update" feature. This module allows userland utilities to evaluate * what firmware updates can be applied to this system, and potentially arrange * for those updates to occur. * * Data is currently found below /sys/firmware/efi/esrt/... */ #define pr_fmt(fmt) "esrt: " fmt #include <linux/capability.h> #include <linux/device.h> #include <linux/efi.h> #include <linux/init.h> #include <linux/io.h> #include <linux/kernel.h> #include <linux/kobject.h> #include <linux/list.h> #include <linux/memblock.h> #include <linux/slab.h> #include <linux/types.h> #include <asm/io.h> #include <asm/early_ioremap.h> struct efi_system_resource_entry_v1 { efi_guid_t fw_class; u32 fw_type; u32 fw_version; u32 lowest_supported_fw_version; u32 capsule_flags; u32 last_attempt_version; u32 last_attempt_status; }; /* * _count and _version are what they seem like. _max is actually just * accounting info for the firmware when creating the table; it should never * have been exposed to us. To wit, the spec says: * The maximum number of resource array entries that can be within the * table without reallocating the table, must not be zero. * Since there's no guidance about what that means in terms of memory layout, * it means nothing to us. */ struct efi_system_resource_table { u32 fw_resource_count; u32 fw_resource_count_max; u64 fw_resource_version; u8 entries[]; }; static phys_addr_t esrt_data; static size_t esrt_data_size; static struct efi_system_resource_table *esrt; struct esre_entry { union { struct efi_system_resource_entry_v1 *esre1; } esre; struct kobject kobj; struct list_head list; }; /* global list of esre_entry. */ static LIST_HEAD(entry_list); /* entry attribute */ struct esre_attribute { struct attribute attr; ssize_t (*show)(struct esre_entry *entry, char *buf); ssize_t (*store)(struct esre_entry *entry, const char *buf, size_t count); }; static struct esre_entry *to_entry(struct kobject *kobj) { return container_of(kobj, struct esre_entry, kobj); } static struct esre_attribute *to_attr(struct attribute *attr) { return container_of(attr, struct esre_attribute, attr); } static ssize_t esre_attr_show(struct kobject *kobj, struct attribute *_attr, char *buf) { struct esre_entry *entry = to_entry(kobj); struct esre_attribute *attr = to_attr(_attr); return attr->show(entry, buf); } static const struct sysfs_ops esre_attr_ops = { .show = esre_attr_show, }; /* Generic ESRT Entry ("ESRE") support. */ static ssize_t fw_class_show(struct esre_entry *entry, char *buf) { char *str = buf; efi_guid_to_str(&entry->esre.esre1->fw_class, str); str += strlen(str); str += sprintf(str, "\n"); return str - buf; } static struct esre_attribute esre_fw_class = __ATTR_RO_MODE(fw_class, 0400); #define esre_attr_decl(name, size, fmt) \ static ssize_t name##_show(struct esre_entry *entry, char *buf) \ { \ return sprintf(buf, fmt "\n", \ le##size##_to_cpu(entry->esre.esre1->name)); \ } \ \ static struct esre_attribute esre_##name = __ATTR_RO_MODE(name, 0400) esre_attr_decl(fw_type, 32, "%u"); esre_attr_decl(fw_version, 32, "%u"); esre_attr_decl(lowest_supported_fw_version, 32, "%u"); esre_attr_decl(capsule_flags, 32, "0x%x"); esre_attr_decl(last_attempt_version, 32, "%u"); esre_attr_decl(last_attempt_status, 32, "%u"); static struct attribute *esre1_attrs[] = { &esre_fw_class.attr, &esre_fw_type.attr, &esre_fw_version.attr, &esre_lowest_supported_fw_version.attr, &esre_capsule_flags.attr, &esre_last_attempt_version.attr, &esre_last_attempt_status.attr, NULL }; ATTRIBUTE_GROUPS(esre1); static void esre_release(struct kobject *kobj) { struct esre_entry *entry = to_entry(kobj); list_del(&entry->list); kfree(entry); } static const struct kobj_type esre1_ktype = { .release = esre_release, .sysfs_ops = &esre_attr_ops, .default_groups = esre1_groups, }; static struct kobject *esrt_kobj; static struct kset *esrt_kset; static int esre_create_sysfs_entry(void *esre, int entry_num) { struct esre_entry *entry; entry = kzalloc(sizeof(*entry), GFP_KERNEL); if (!entry) return -ENOMEM; entry->kobj.kset = esrt_kset; if (esrt->fw_resource_version == 1) { int rc = 0; entry->esre.esre1 = esre; rc = kobject_init_and_add(&entry->kobj, &esre1_ktype, NULL, "entry%d", entry_num); if (rc) { kobject_put(&entry->kobj); return rc; } } list_add_tail(&entry->list, &entry_list); return 0; } /* support for displaying ESRT fields at the top level */ #define esrt_attr_decl(name, size, fmt) \ static ssize_t name##_show(struct kobject *kobj, \ struct kobj_attribute *attr, char *buf)\ { \ return sprintf(buf, fmt "\n", le##size##_to_cpu(esrt->name)); \ } \ \ static struct kobj_attribute esrt_##name = __ATTR_RO_MODE(name, 0400) esrt_attr_decl(fw_resource_count, 32, "%u"); esrt_attr_decl(fw_resource_count_max, 32, "%u"); esrt_attr_decl(fw_resource_version, 64, "%llu"); static struct attribute *esrt_attrs[] = { &esrt_fw_resource_count.attr, &esrt_fw_resource_count_max.attr, &esrt_fw_resource_version.attr, NULL, }; static inline int esrt_table_exists(void) { if (!efi_enabled(EFI_CONFIG_TABLES)) return 0; if (efi.esrt == EFI_INVALID_TABLE_ADDR) return 0; return 1; } static umode_t esrt_attr_is_visible(struct kobject *kobj, struct attribute *attr, int n) { if (!esrt_table_exists()) return 0; return attr->mode; } static const struct attribute_group esrt_attr_group = { .attrs = esrt_attrs, .is_visible = esrt_attr_is_visible, }; /* * remap the table, validate it, mark it reserved and unmap it. */ void __init efi_esrt_init(void) { void *va; struct efi_system_resource_table tmpesrt; size_t size, max, entry_size, entries_size; efi_memory_desc_t md; int rc; phys_addr_t end; if (!efi_enabled(EFI_MEMMAP) && !efi_enabled(EFI_PARAVIRT)) return; pr_debug("esrt-init: loading.\n"); if (!esrt_table_exists()) return; rc = efi_mem_desc_lookup(efi.esrt, &md); if (rc < 0 || (!(md.attribute & EFI_MEMORY_RUNTIME) && md.type != EFI_BOOT_SERVICES_DATA && md.type != EFI_RUNTIME_SERVICES_DATA && md.type != EFI_ACPI_RECLAIM_MEMORY && md.type != EFI_ACPI_MEMORY_NVS)) { pr_warn("ESRT header is not in the memory map.\n"); return; } max = efi_mem_desc_end(&md) - efi.esrt; size = sizeof(*esrt); if (max < size) { pr_err("ESRT header doesn't fit on single memory map entry. (size: %zu max: %zu)\n", size, max); return; } va = early_memremap(efi.esrt, size); if (!va) { pr_err("early_memremap(%p, %zu) failed.\n", (void *)efi.esrt, size); return; } memcpy(&tmpesrt, va, sizeof(tmpesrt)); early_memunmap(va, size); if (tmpesrt.fw_resource_version != 1) { pr_err("Unsupported ESRT version %lld.\n", tmpesrt.fw_resource_version); return; } entry_size = sizeof(struct efi_system_resource_entry_v1); if (tmpesrt.fw_resource_count > 0 && max - size < entry_size) { pr_err("ESRT memory map entry can only hold the header. (max: %zu size: %zu)\n", max - size, entry_size); return; } /* * The format doesn't really give us any boundary to test here, * so I'm making up 128 as the max number of individually updatable * components we support. * 128 should be pretty excessive, but there's still some chance * somebody will do that someday and we'll need to raise this. */ if (tmpesrt.fw_resource_count > 128) { pr_err("ESRT says fw_resource_count has very large value %d.\n", tmpesrt.fw_resource_count); return; } /* * We know it can't be larger than N * sizeof() here, and N is limited * by the previous test to a small number, so there's no overflow. */ entries_size = tmpesrt.fw_resource_count * entry_size; if (max < size + entries_size) { pr_err("ESRT does not fit on single memory map entry (size: %zu max: %zu)\n", size, max); return; } size += entries_size; esrt_data = (phys_addr_t)efi.esrt; esrt_data_size = size; end = esrt_data + size; pr_info("Reserving ESRT space from %pa to %pa.\n", &esrt_data, &end); if (md.type == EFI_BOOT_SERVICES_DATA) efi_mem_reserve(esrt_data, esrt_data_size); pr_debug("esrt-init: loaded.\n"); } static int __init register_entries(void) { struct efi_system_resource_entry_v1 *v1_entries = (void *)esrt->entries; int i, rc; if (!esrt_table_exists()) return 0; for (i = 0; i < le32_to_cpu(esrt->fw_resource_count); i++) { void *esre = NULL; if (esrt->fw_resource_version == 1) { esre = &v1_entries[i]; } else { pr_err("Unsupported ESRT version %lld.\n", esrt->fw_resource_version); return -EINVAL; } rc = esre_create_sysfs_entry(esre, i); if (rc < 0) { pr_err("ESRT entry creation failed with error %d.\n", rc); return rc; } } return 0; } static void cleanup_entry_list(void) { struct esre_entry *entry, *next; list_for_each_entry_safe(entry, next, &entry_list, list) { kobject_put(&entry->kobj); } } static int __init esrt_sysfs_init(void) { int error; pr_debug("esrt-sysfs: loading.\n"); if (!esrt_data || !esrt_data_size) return -ENOSYS; esrt = memremap(esrt_data, esrt_data_size, MEMREMAP_WB); if (!esrt) { pr_err("memremap(%pa, %zu) failed.\n", &esrt_data, esrt_data_size); return -ENOMEM; } esrt_kobj = kobject_create_and_add("esrt", efi_kobj); if (!esrt_kobj) { pr_err("Firmware table registration failed.\n"); error = -ENOMEM; goto err; } error = sysfs_create_group(esrt_kobj, &esrt_attr_group); if (error) { pr_err("Sysfs attribute export failed with error %d.\n", error); goto err_remove_esrt; } esrt_kset = kset_create_and_add("entries", NULL, esrt_kobj); if (!esrt_kset) { pr_err("kset creation failed.\n"); error = -ENOMEM; goto err_remove_group; } error = register_entries(); if (error) goto err_cleanup_list; pr_debug("esrt-sysfs: loaded.\n"); return 0; err_cleanup_list: cleanup_entry_list(); kset_unregister(esrt_kset); err_remove_group: sysfs_remove_group(esrt_kobj, &esrt_attr_group); err_remove_esrt: kobject_put(esrt_kobj); err: memunmap(esrt); esrt = NULL; return error; } device_initcall(esrt_sysfs_init); /* MODULE_AUTHOR("Peter Jones <[email protected]>"); MODULE_DESCRIPTION("EFI System Resource Table support"); MODULE_LICENSE("GPL"); */
linux-master
drivers/firmware/efi/esrt.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2014 Intel Corporation; author Matt Fleming * Copyright (c) 2014 Red Hat, Inc., Mark Salter <[email protected]> */ #include <linux/efi.h> #include <linux/reboot.h> static struct sys_off_handler *efi_sys_off_handler; int efi_reboot_quirk_mode = -1; void efi_reboot(enum reboot_mode reboot_mode, const char *__unused) { const char *str[] = { "cold", "warm", "shutdown", "platform" }; int efi_mode, cap_reset_mode; if (!efi_rt_services_supported(EFI_RT_SUPPORTED_RESET_SYSTEM)) return; switch (reboot_mode) { case REBOOT_WARM: case REBOOT_SOFT: efi_mode = EFI_RESET_WARM; break; default: efi_mode = EFI_RESET_COLD; break; } /* * If a quirk forced an EFI reset mode, always use that. */ if (efi_reboot_quirk_mode != -1) efi_mode = efi_reboot_quirk_mode; if (efi_capsule_pending(&cap_reset_mode)) { if (efi_mode != cap_reset_mode) printk(KERN_CRIT "efi: %s reset requested but pending " "capsule update requires %s reset... Performing " "%s reset.\n", str[efi_mode], str[cap_reset_mode], str[cap_reset_mode]); efi_mode = cap_reset_mode; } efi.reset_system(efi_mode, EFI_SUCCESS, 0, NULL); } bool __weak efi_poweroff_required(void) { return false; } static int efi_power_off(struct sys_off_data *data) { efi.reset_system(EFI_RESET_SHUTDOWN, EFI_SUCCESS, 0, NULL); return NOTIFY_DONE; } static int __init efi_shutdown_init(void) { if (!efi_rt_services_supported(EFI_RT_SUPPORTED_RESET_SYSTEM)) return -ENODEV; if (efi_poweroff_required()) { /* SYS_OFF_PRIO_FIRMWARE + 1 so that it runs before acpi_power_off */ efi_sys_off_handler = register_sys_off_handler(SYS_OFF_MODE_POWER_OFF, SYS_OFF_PRIO_FIRMWARE + 1, efi_power_off, NULL); if (IS_ERR(efi_sys_off_handler)) return PTR_ERR(efi_sys_off_handler); } return 0; } late_initcall(efi_shutdown_init);
linux-master
drivers/firmware/efi/reboot.c
// SPDX-License-Identifier: GPL-2.0-only /* * efi.c - EFI subsystem * * Copyright (C) 2001,2003,2004 Dell <[email protected]> * Copyright (C) 2004 Intel Corporation <[email protected]> * Copyright (C) 2013 Tom Gundersen <[email protected]> * * This code registers /sys/firmware/efi{,/efivars} when EFI is supported, * allowing the efivarfs to be mounted or the efivars module to be loaded. * The existance of /sys/firmware/efi may also be used by userspace to * determine that the system supports EFI. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kobject.h> #include <linux/module.h> #include <linux/init.h> #include <linux/debugfs.h> #include <linux/device.h> #include <linux/efi.h> #include <linux/of.h> #include <linux/initrd.h> #include <linux/io.h> #include <linux/kexec.h> #include <linux/platform_device.h> #include <linux/random.h> #include <linux/reboot.h> #include <linux/slab.h> #include <linux/acpi.h> #include <linux/ucs2_string.h> #include <linux/memblock.h> #include <linux/security.h> #include <asm/early_ioremap.h> struct efi __read_mostly efi = { .runtime_supported_mask = EFI_RT_SUPPORTED_ALL, .acpi = EFI_INVALID_TABLE_ADDR, .acpi20 = EFI_INVALID_TABLE_ADDR, .smbios = EFI_INVALID_TABLE_ADDR, .smbios3 = EFI_INVALID_TABLE_ADDR, .esrt = EFI_INVALID_TABLE_ADDR, .tpm_log = EFI_INVALID_TABLE_ADDR, .tpm_final_log = EFI_INVALID_TABLE_ADDR, #ifdef CONFIG_LOAD_UEFI_KEYS .mokvar_table = EFI_INVALID_TABLE_ADDR, #endif #ifdef CONFIG_EFI_COCO_SECRET .coco_secret = EFI_INVALID_TABLE_ADDR, #endif #ifdef CONFIG_UNACCEPTED_MEMORY .unaccepted = EFI_INVALID_TABLE_ADDR, #endif }; EXPORT_SYMBOL(efi); unsigned long __ro_after_init efi_rng_seed = EFI_INVALID_TABLE_ADDR; static unsigned long __initdata mem_reserve = EFI_INVALID_TABLE_ADDR; static unsigned long __initdata rt_prop = EFI_INVALID_TABLE_ADDR; static unsigned long __initdata initrd = EFI_INVALID_TABLE_ADDR; extern unsigned long screen_info_table; struct mm_struct efi_mm = { .mm_mt = MTREE_INIT_EXT(mm_mt, MM_MT_FLAGS, efi_mm.mmap_lock), .mm_users = ATOMIC_INIT(2), .mm_count = ATOMIC_INIT(1), .write_protect_seq = SEQCNT_ZERO(efi_mm.write_protect_seq), MMAP_LOCK_INITIALIZER(efi_mm) .page_table_lock = __SPIN_LOCK_UNLOCKED(efi_mm.page_table_lock), .mmlist = LIST_HEAD_INIT(efi_mm.mmlist), .cpu_bitmap = { [BITS_TO_LONGS(NR_CPUS)] = 0}, }; struct workqueue_struct *efi_rts_wq; static bool disable_runtime = IS_ENABLED(CONFIG_EFI_DISABLE_RUNTIME); static int __init setup_noefi(char *arg) { disable_runtime = true; return 0; } early_param("noefi", setup_noefi); bool efi_runtime_disabled(void) { return disable_runtime; } bool __pure __efi_soft_reserve_enabled(void) { return !efi_enabled(EFI_MEM_NO_SOFT_RESERVE); } static int __init parse_efi_cmdline(char *str) { if (!str) { pr_warn("need at least one option\n"); return -EINVAL; } if (parse_option_str(str, "debug")) set_bit(EFI_DBG, &efi.flags); if (parse_option_str(str, "noruntime")) disable_runtime = true; if (parse_option_str(str, "runtime")) disable_runtime = false; if (parse_option_str(str, "nosoftreserve")) set_bit(EFI_MEM_NO_SOFT_RESERVE, &efi.flags); return 0; } early_param("efi", parse_efi_cmdline); struct kobject *efi_kobj; /* * Let's not leave out systab information that snuck into * the efivars driver * Note, do not add more fields in systab sysfs file as it breaks sysfs * one value per file rule! */ static ssize_t systab_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { char *str = buf; if (!kobj || !buf) return -EINVAL; if (efi.acpi20 != EFI_INVALID_TABLE_ADDR) str += sprintf(str, "ACPI20=0x%lx\n", efi.acpi20); if (efi.acpi != EFI_INVALID_TABLE_ADDR) str += sprintf(str, "ACPI=0x%lx\n", efi.acpi); /* * If both SMBIOS and SMBIOS3 entry points are implemented, the * SMBIOS3 entry point shall be preferred, so we list it first to * let applications stop parsing after the first match. */ if (efi.smbios3 != EFI_INVALID_TABLE_ADDR) str += sprintf(str, "SMBIOS3=0x%lx\n", efi.smbios3); if (efi.smbios != EFI_INVALID_TABLE_ADDR) str += sprintf(str, "SMBIOS=0x%lx\n", efi.smbios); if (IS_ENABLED(CONFIG_IA64) || IS_ENABLED(CONFIG_X86)) str = efi_systab_show_arch(str); return str - buf; } static struct kobj_attribute efi_attr_systab = __ATTR_RO_MODE(systab, 0400); static ssize_t fw_platform_size_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return sprintf(buf, "%d\n", efi_enabled(EFI_64BIT) ? 64 : 32); } extern __weak struct kobj_attribute efi_attr_fw_vendor; extern __weak struct kobj_attribute efi_attr_runtime; extern __weak struct kobj_attribute efi_attr_config_table; static struct kobj_attribute efi_attr_fw_platform_size = __ATTR_RO(fw_platform_size); static struct attribute *efi_subsys_attrs[] = { &efi_attr_systab.attr, &efi_attr_fw_platform_size.attr, &efi_attr_fw_vendor.attr, &efi_attr_runtime.attr, &efi_attr_config_table.attr, NULL, }; umode_t __weak efi_attr_is_visible(struct kobject *kobj, struct attribute *attr, int n) { return attr->mode; } static const struct attribute_group efi_subsys_attr_group = { .attrs = efi_subsys_attrs, .is_visible = efi_attr_is_visible, }; static struct efivars generic_efivars; static struct efivar_operations generic_ops; static bool generic_ops_supported(void) { unsigned long name_size; efi_status_t status; efi_char16_t name; efi_guid_t guid; name_size = sizeof(name); status = efi.get_next_variable(&name_size, &name, &guid); if (status == EFI_UNSUPPORTED) return false; return true; } static int generic_ops_register(void) { if (!generic_ops_supported()) return 0; generic_ops.get_variable = efi.get_variable; generic_ops.get_next_variable = efi.get_next_variable; generic_ops.query_variable_store = efi_query_variable_store; generic_ops.query_variable_info = efi.query_variable_info; if (efi_rt_services_supported(EFI_RT_SUPPORTED_SET_VARIABLE)) { generic_ops.set_variable = efi.set_variable; generic_ops.set_variable_nonblocking = efi.set_variable_nonblocking; } return efivars_register(&generic_efivars, &generic_ops); } static void generic_ops_unregister(void) { if (!generic_ops.get_variable) return; efivars_unregister(&generic_efivars); } #ifdef CONFIG_EFI_CUSTOM_SSDT_OVERLAYS #define EFIVAR_SSDT_NAME_MAX 16UL static char efivar_ssdt[EFIVAR_SSDT_NAME_MAX] __initdata; static int __init efivar_ssdt_setup(char *str) { int ret = security_locked_down(LOCKDOWN_ACPI_TABLES); if (ret) return ret; if (strlen(str) < sizeof(efivar_ssdt)) memcpy(efivar_ssdt, str, strlen(str)); else pr_warn("efivar_ssdt: name too long: %s\n", str); return 1; } __setup("efivar_ssdt=", efivar_ssdt_setup); static __init int efivar_ssdt_load(void) { unsigned long name_size = 256; efi_char16_t *name = NULL; efi_status_t status; efi_guid_t guid; if (!efivar_ssdt[0]) return 0; name = kzalloc(name_size, GFP_KERNEL); if (!name) return -ENOMEM; for (;;) { char utf8_name[EFIVAR_SSDT_NAME_MAX]; unsigned long data_size = 0; void *data; int limit; status = efi.get_next_variable(&name_size, name, &guid); if (status == EFI_NOT_FOUND) { break; } else if (status == EFI_BUFFER_TOO_SMALL) { name = krealloc(name, name_size, GFP_KERNEL); if (!name) return -ENOMEM; continue; } limit = min(EFIVAR_SSDT_NAME_MAX, name_size); ucs2_as_utf8(utf8_name, name, limit - 1); if (strncmp(utf8_name, efivar_ssdt, limit) != 0) continue; pr_info("loading SSDT from variable %s-%pUl\n", efivar_ssdt, &guid); status = efi.get_variable(name, &guid, NULL, &data_size, NULL); if (status != EFI_BUFFER_TOO_SMALL || !data_size) return -EIO; data = kmalloc(data_size, GFP_KERNEL); if (!data) return -ENOMEM; status = efi.get_variable(name, &guid, NULL, &data_size, data); if (status == EFI_SUCCESS) { acpi_status ret = acpi_load_table(data, NULL); if (ret) pr_err("failed to load table: %u\n", ret); else continue; } else { pr_err("failed to get var data: 0x%lx\n", status); } kfree(data); } return 0; } #else static inline int efivar_ssdt_load(void) { return 0; } #endif #ifdef CONFIG_DEBUG_FS #define EFI_DEBUGFS_MAX_BLOBS 32 static struct debugfs_blob_wrapper debugfs_blob[EFI_DEBUGFS_MAX_BLOBS]; static void __init efi_debugfs_init(void) { struct dentry *efi_debugfs; efi_memory_desc_t *md; char name[32]; int type_count[EFI_BOOT_SERVICES_DATA + 1] = {}; int i = 0; efi_debugfs = debugfs_create_dir("efi", NULL); if (IS_ERR_OR_NULL(efi_debugfs)) return; for_each_efi_memory_desc(md) { switch (md->type) { case EFI_BOOT_SERVICES_CODE: snprintf(name, sizeof(name), "boot_services_code%d", type_count[md->type]++); break; case EFI_BOOT_SERVICES_DATA: snprintf(name, sizeof(name), "boot_services_data%d", type_count[md->type]++); break; default: continue; } if (i >= EFI_DEBUGFS_MAX_BLOBS) { pr_warn("More then %d EFI boot service segments, only showing first %d in debugfs\n", EFI_DEBUGFS_MAX_BLOBS, EFI_DEBUGFS_MAX_BLOBS); break; } debugfs_blob[i].size = md->num_pages << EFI_PAGE_SHIFT; debugfs_blob[i].data = memremap(md->phys_addr, debugfs_blob[i].size, MEMREMAP_WB); if (!debugfs_blob[i].data) continue; debugfs_create_blob(name, 0400, efi_debugfs, &debugfs_blob[i]); i++; } } #else static inline void efi_debugfs_init(void) {} #endif /* * We register the efi subsystem with the firmware subsystem and the * efivars subsystem with the efi subsystem, if the system was booted with * EFI. */ static int __init efisubsys_init(void) { int error; if (!efi_enabled(EFI_RUNTIME_SERVICES)) efi.runtime_supported_mask = 0; if (!efi_enabled(EFI_BOOT)) return 0; if (efi.runtime_supported_mask) { /* * Since we process only one efi_runtime_service() at a time, an * ordered workqueue (which creates only one execution context) * should suffice for all our needs. */ efi_rts_wq = alloc_ordered_workqueue("efi_rts_wq", 0); if (!efi_rts_wq) { pr_err("Creating efi_rts_wq failed, EFI runtime services disabled.\n"); clear_bit(EFI_RUNTIME_SERVICES, &efi.flags); efi.runtime_supported_mask = 0; return 0; } } if (efi_rt_services_supported(EFI_RT_SUPPORTED_TIME_SERVICES)) platform_device_register_simple("rtc-efi", 0, NULL, 0); /* We register the efi directory at /sys/firmware/efi */ efi_kobj = kobject_create_and_add("efi", firmware_kobj); if (!efi_kobj) { pr_err("efi: Firmware registration failed.\n"); error = -ENOMEM; goto err_destroy_wq; } if (efi_rt_services_supported(EFI_RT_SUPPORTED_GET_VARIABLE | EFI_RT_SUPPORTED_GET_NEXT_VARIABLE_NAME)) { error = generic_ops_register(); if (error) goto err_put; efivar_ssdt_load(); platform_device_register_simple("efivars", 0, NULL, 0); } error = sysfs_create_group(efi_kobj, &efi_subsys_attr_group); if (error) { pr_err("efi: Sysfs attribute export failed with error %d.\n", error); goto err_unregister; } /* and the standard mountpoint for efivarfs */ error = sysfs_create_mount_point(efi_kobj, "efivars"); if (error) { pr_err("efivars: Subsystem registration failed.\n"); goto err_remove_group; } if (efi_enabled(EFI_DBG) && efi_enabled(EFI_PRESERVE_BS_REGIONS)) efi_debugfs_init(); #ifdef CONFIG_EFI_COCO_SECRET if (efi.coco_secret != EFI_INVALID_TABLE_ADDR) platform_device_register_simple("efi_secret", 0, NULL, 0); #endif return 0; err_remove_group: sysfs_remove_group(efi_kobj, &efi_subsys_attr_group); err_unregister: if (efi_rt_services_supported(EFI_RT_SUPPORTED_GET_VARIABLE | EFI_RT_SUPPORTED_GET_NEXT_VARIABLE_NAME)) generic_ops_unregister(); err_put: kobject_put(efi_kobj); efi_kobj = NULL; err_destroy_wq: if (efi_rts_wq) destroy_workqueue(efi_rts_wq); return error; } subsys_initcall(efisubsys_init); void __init efi_find_mirror(void) { efi_memory_desc_t *md; u64 mirror_size = 0, total_size = 0; if (!efi_enabled(EFI_MEMMAP)) return; for_each_efi_memory_desc(md) { unsigned long long start = md->phys_addr; unsigned long long size = md->num_pages << EFI_PAGE_SHIFT; total_size += size; if (md->attribute & EFI_MEMORY_MORE_RELIABLE) { memblock_mark_mirror(start, size); mirror_size += size; } } if (mirror_size) pr_info("Memory: %lldM/%lldM mirrored memory\n", mirror_size>>20, total_size>>20); } /* * Find the efi memory descriptor for a given physical address. Given a * physical address, determine if it exists within an EFI Memory Map entry, * and if so, populate the supplied memory descriptor with the appropriate * data. */ int __efi_mem_desc_lookup(u64 phys_addr, efi_memory_desc_t *out_md) { efi_memory_desc_t *md; if (!efi_enabled(EFI_MEMMAP)) { pr_err_once("EFI_MEMMAP is not enabled.\n"); return -EINVAL; } if (!out_md) { pr_err_once("out_md is null.\n"); return -EINVAL; } for_each_efi_memory_desc(md) { u64 size; u64 end; /* skip bogus entries (including empty ones) */ if ((md->phys_addr & (EFI_PAGE_SIZE - 1)) || (md->num_pages <= 0) || (md->num_pages > (U64_MAX - md->phys_addr) >> EFI_PAGE_SHIFT)) continue; size = md->num_pages << EFI_PAGE_SHIFT; end = md->phys_addr + size; if (phys_addr >= md->phys_addr && phys_addr < end) { memcpy(out_md, md, sizeof(*out_md)); return 0; } } return -ENOENT; } extern int efi_mem_desc_lookup(u64 phys_addr, efi_memory_desc_t *out_md) __weak __alias(__efi_mem_desc_lookup); /* * Calculate the highest address of an efi memory descriptor. */ u64 __init efi_mem_desc_end(efi_memory_desc_t *md) { u64 size = md->num_pages << EFI_PAGE_SHIFT; u64 end = md->phys_addr + size; return end; } void __init __weak efi_arch_mem_reserve(phys_addr_t addr, u64 size) {} /** * efi_mem_reserve - Reserve an EFI memory region * @addr: Physical address to reserve * @size: Size of reservation * * Mark a region as reserved from general kernel allocation and * prevent it being released by efi_free_boot_services(). * * This function should be called drivers once they've parsed EFI * configuration tables to figure out where their data lives, e.g. * efi_esrt_init(). */ void __init efi_mem_reserve(phys_addr_t addr, u64 size) { /* efi_mem_reserve() does not work under Xen */ if (WARN_ON_ONCE(efi_enabled(EFI_PARAVIRT))) return; if (!memblock_is_region_reserved(addr, size)) memblock_reserve(addr, size); /* * Some architectures (x86) reserve all boot services ranges * until efi_free_boot_services() because of buggy firmware * implementations. This means the above memblock_reserve() is * superfluous on x86 and instead what it needs to do is * ensure the @start, @size is not freed. */ efi_arch_mem_reserve(addr, size); } static const efi_config_table_type_t common_tables[] __initconst = { {ACPI_20_TABLE_GUID, &efi.acpi20, "ACPI 2.0" }, {ACPI_TABLE_GUID, &efi.acpi, "ACPI" }, {SMBIOS_TABLE_GUID, &efi.smbios, "SMBIOS" }, {SMBIOS3_TABLE_GUID, &efi.smbios3, "SMBIOS 3.0" }, {EFI_SYSTEM_RESOURCE_TABLE_GUID, &efi.esrt, "ESRT" }, {EFI_MEMORY_ATTRIBUTES_TABLE_GUID, &efi_mem_attr_table, "MEMATTR" }, {LINUX_EFI_RANDOM_SEED_TABLE_GUID, &efi_rng_seed, "RNG" }, {LINUX_EFI_TPM_EVENT_LOG_GUID, &efi.tpm_log, "TPMEventLog" }, {LINUX_EFI_TPM_FINAL_LOG_GUID, &efi.tpm_final_log, "TPMFinalLog" }, {LINUX_EFI_MEMRESERVE_TABLE_GUID, &mem_reserve, "MEMRESERVE" }, {LINUX_EFI_INITRD_MEDIA_GUID, &initrd, "INITRD" }, {EFI_RT_PROPERTIES_TABLE_GUID, &rt_prop, "RTPROP" }, #ifdef CONFIG_EFI_RCI2_TABLE {DELLEMC_EFI_RCI2_TABLE_GUID, &rci2_table_phys }, #endif #ifdef CONFIG_LOAD_UEFI_KEYS {LINUX_EFI_MOK_VARIABLE_TABLE_GUID, &efi.mokvar_table, "MOKvar" }, #endif #ifdef CONFIG_EFI_COCO_SECRET {LINUX_EFI_COCO_SECRET_AREA_GUID, &efi.coco_secret, "CocoSecret" }, #endif #ifdef CONFIG_UNACCEPTED_MEMORY {LINUX_EFI_UNACCEPTED_MEM_TABLE_GUID, &efi.unaccepted, "Unaccepted" }, #endif #ifdef CONFIG_EFI_GENERIC_STUB {LINUX_EFI_SCREEN_INFO_TABLE_GUID, &screen_info_table }, #endif {}, }; static __init int match_config_table(const efi_guid_t *guid, unsigned long table, const efi_config_table_type_t *table_types) { int i; for (i = 0; efi_guidcmp(table_types[i].guid, NULL_GUID); i++) { if (efi_guidcmp(*guid, table_types[i].guid)) continue; if (!efi_config_table_is_usable(guid, table)) { if (table_types[i].name[0]) pr_cont("(%s=0x%lx unusable) ", table_types[i].name, table); return 1; } *(table_types[i].ptr) = table; if (table_types[i].name[0]) pr_cont("%s=0x%lx ", table_types[i].name, table); return 1; } return 0; } /** * reserve_unaccepted - Map and reserve unaccepted configuration table * @unaccepted: Pointer to unaccepted memory table * * memblock_add() makes sure that the table is mapped in direct mapping. During * normal boot it happens automatically because the table is allocated from * usable memory. But during crashkernel boot only memory specifically reserved * for crash scenario is mapped. memblock_add() forces the table to be mapped * in crashkernel case. * * Align the range to the nearest page borders. Ranges smaller than page size * are not going to be mapped. * * memblock_reserve() makes sure that future allocations will not touch the * table. */ static __init void reserve_unaccepted(struct efi_unaccepted_memory *unaccepted) { phys_addr_t start, size; start = PAGE_ALIGN_DOWN(efi.unaccepted); size = PAGE_ALIGN(sizeof(*unaccepted) + unaccepted->size); memblock_add(start, size); memblock_reserve(start, size); } int __init efi_config_parse_tables(const efi_config_table_t *config_tables, int count, const efi_config_table_type_t *arch_tables) { const efi_config_table_64_t *tbl64 = (void *)config_tables; const efi_config_table_32_t *tbl32 = (void *)config_tables; const efi_guid_t *guid; unsigned long table; int i; pr_info(""); for (i = 0; i < count; i++) { if (!IS_ENABLED(CONFIG_X86)) { guid = &config_tables[i].guid; table = (unsigned long)config_tables[i].table; } else if (efi_enabled(EFI_64BIT)) { guid = &tbl64[i].guid; table = tbl64[i].table; if (IS_ENABLED(CONFIG_X86_32) && tbl64[i].table > U32_MAX) { pr_cont("\n"); pr_err("Table located above 4GB, disabling EFI.\n"); return -EINVAL; } } else { guid = &tbl32[i].guid; table = tbl32[i].table; } if (!match_config_table(guid, table, common_tables) && arch_tables) match_config_table(guid, table, arch_tables); } pr_cont("\n"); set_bit(EFI_CONFIG_TABLES, &efi.flags); if (efi_rng_seed != EFI_INVALID_TABLE_ADDR) { struct linux_efi_random_seed *seed; u32 size = 0; seed = early_memremap(efi_rng_seed, sizeof(*seed)); if (seed != NULL) { size = min_t(u32, seed->size, SZ_1K); // sanity check early_memunmap(seed, sizeof(*seed)); } else { pr_err("Could not map UEFI random seed!\n"); } if (size > 0) { seed = early_memremap(efi_rng_seed, sizeof(*seed) + size); if (seed != NULL) { add_bootloader_randomness(seed->bits, size); memzero_explicit(seed->bits, size); early_memunmap(seed, sizeof(*seed) + size); } else { pr_err("Could not map UEFI random seed!\n"); } } } if (!IS_ENABLED(CONFIG_X86_32) && efi_enabled(EFI_MEMMAP)) efi_memattr_init(); efi_tpm_eventlog_init(); if (mem_reserve != EFI_INVALID_TABLE_ADDR) { unsigned long prsv = mem_reserve; while (prsv) { struct linux_efi_memreserve *rsv; u8 *p; /* * Just map a full page: that is what we will get * anyway, and it permits us to map the entire entry * before knowing its size. */ p = early_memremap(ALIGN_DOWN(prsv, PAGE_SIZE), PAGE_SIZE); if (p == NULL) { pr_err("Could not map UEFI memreserve entry!\n"); return -ENOMEM; } rsv = (void *)(p + prsv % PAGE_SIZE); /* reserve the entry itself */ memblock_reserve(prsv, struct_size(rsv, entry, rsv->size)); for (i = 0; i < atomic_read(&rsv->count); i++) { memblock_reserve(rsv->entry[i].base, rsv->entry[i].size); } prsv = rsv->next; early_memunmap(p, PAGE_SIZE); } } if (rt_prop != EFI_INVALID_TABLE_ADDR) { efi_rt_properties_table_t *tbl; tbl = early_memremap(rt_prop, sizeof(*tbl)); if (tbl) { efi.runtime_supported_mask &= tbl->runtime_services_supported; early_memunmap(tbl, sizeof(*tbl)); } } if (IS_ENABLED(CONFIG_BLK_DEV_INITRD) && initrd != EFI_INVALID_TABLE_ADDR && phys_initrd_size == 0) { struct linux_efi_initrd *tbl; tbl = early_memremap(initrd, sizeof(*tbl)); if (tbl) { phys_initrd_start = tbl->base; phys_initrd_size = tbl->size; early_memunmap(tbl, sizeof(*tbl)); } } if (IS_ENABLED(CONFIG_UNACCEPTED_MEMORY) && efi.unaccepted != EFI_INVALID_TABLE_ADDR) { struct efi_unaccepted_memory *unaccepted; unaccepted = early_memremap(efi.unaccepted, sizeof(*unaccepted)); if (unaccepted) { if (unaccepted->version == 1) { reserve_unaccepted(unaccepted); } else { efi.unaccepted = EFI_INVALID_TABLE_ADDR; } early_memunmap(unaccepted, sizeof(*unaccepted)); } } return 0; } int __init efi_systab_check_header(const efi_table_hdr_t *systab_hdr) { if (systab_hdr->signature != EFI_SYSTEM_TABLE_SIGNATURE) { pr_err("System table signature incorrect!\n"); return -EINVAL; } return 0; } #ifndef CONFIG_IA64 static const efi_char16_t *__init map_fw_vendor(unsigned long fw_vendor, size_t size) { const efi_char16_t *ret; ret = early_memremap_ro(fw_vendor, size); if (!ret) pr_err("Could not map the firmware vendor!\n"); return ret; } static void __init unmap_fw_vendor(const void *fw_vendor, size_t size) { early_memunmap((void *)fw_vendor, size); } #else #define map_fw_vendor(p, s) __va(p) #define unmap_fw_vendor(v, s) #endif void __init efi_systab_report_header(const efi_table_hdr_t *systab_hdr, unsigned long fw_vendor) { char vendor[100] = "unknown"; const efi_char16_t *c16; size_t i; u16 rev; c16 = map_fw_vendor(fw_vendor, sizeof(vendor) * sizeof(efi_char16_t)); if (c16) { for (i = 0; i < sizeof(vendor) - 1 && c16[i]; ++i) vendor[i] = c16[i]; vendor[i] = '\0'; unmap_fw_vendor(c16, sizeof(vendor) * sizeof(efi_char16_t)); } rev = (u16)systab_hdr->revision; pr_info("EFI v%u.%u", systab_hdr->revision >> 16, rev / 10); rev %= 10; if (rev) pr_cont(".%u", rev); pr_cont(" by %s\n", vendor); if (IS_ENABLED(CONFIG_X86_64) && systab_hdr->revision > EFI_1_10_SYSTEM_TABLE_REVISION && !strcmp(vendor, "Apple")) { pr_info("Apple Mac detected, using EFI v1.10 runtime services only\n"); efi.runtime_version = EFI_1_10_SYSTEM_TABLE_REVISION; } } static __initdata char memory_type_name[][13] = { "Reserved", "Loader Code", "Loader Data", "Boot Code", "Boot Data", "Runtime Code", "Runtime Data", "Conventional", "Unusable", "ACPI Reclaim", "ACPI Mem NVS", "MMIO", "MMIO Port", "PAL Code", "Persistent", "Unaccepted", }; char * __init efi_md_typeattr_format(char *buf, size_t size, const efi_memory_desc_t *md) { char *pos; int type_len; u64 attr; pos = buf; if (md->type >= ARRAY_SIZE(memory_type_name)) type_len = snprintf(pos, size, "[type=%u", md->type); else type_len = snprintf(pos, size, "[%-*s", (int)(sizeof(memory_type_name[0]) - 1), memory_type_name[md->type]); if (type_len >= size) return buf; pos += type_len; size -= type_len; attr = md->attribute; if (attr & ~(EFI_MEMORY_UC | EFI_MEMORY_WC | EFI_MEMORY_WT | EFI_MEMORY_WB | EFI_MEMORY_UCE | EFI_MEMORY_RO | EFI_MEMORY_WP | EFI_MEMORY_RP | EFI_MEMORY_XP | EFI_MEMORY_NV | EFI_MEMORY_SP | EFI_MEMORY_CPU_CRYPTO | EFI_MEMORY_RUNTIME | EFI_MEMORY_MORE_RELIABLE)) snprintf(pos, size, "|attr=0x%016llx]", (unsigned long long)attr); else snprintf(pos, size, "|%3s|%2s|%2s|%2s|%2s|%2s|%2s|%2s|%2s|%3s|%2s|%2s|%2s|%2s]", attr & EFI_MEMORY_RUNTIME ? "RUN" : "", attr & EFI_MEMORY_MORE_RELIABLE ? "MR" : "", attr & EFI_MEMORY_CPU_CRYPTO ? "CC" : "", attr & EFI_MEMORY_SP ? "SP" : "", attr & EFI_MEMORY_NV ? "NV" : "", attr & EFI_MEMORY_XP ? "XP" : "", attr & EFI_MEMORY_RP ? "RP" : "", attr & EFI_MEMORY_WP ? "WP" : "", attr & EFI_MEMORY_RO ? "RO" : "", attr & EFI_MEMORY_UCE ? "UCE" : "", attr & EFI_MEMORY_WB ? "WB" : "", attr & EFI_MEMORY_WT ? "WT" : "", attr & EFI_MEMORY_WC ? "WC" : "", attr & EFI_MEMORY_UC ? "UC" : ""); return buf; } /* * IA64 has a funky EFI memory map that doesn't work the same way as * other architectures. */ #ifndef CONFIG_IA64 /* * efi_mem_attributes - lookup memmap attributes for physical address * @phys_addr: the physical address to lookup * * Search in the EFI memory map for the region covering * @phys_addr. Returns the EFI memory attributes if the region * was found in the memory map, 0 otherwise. */ u64 efi_mem_attributes(unsigned long phys_addr) { efi_memory_desc_t *md; if (!efi_enabled(EFI_MEMMAP)) return 0; for_each_efi_memory_desc(md) { if ((md->phys_addr <= phys_addr) && (phys_addr < (md->phys_addr + (md->num_pages << EFI_PAGE_SHIFT)))) return md->attribute; } return 0; } /* * efi_mem_type - lookup memmap type for physical address * @phys_addr: the physical address to lookup * * Search in the EFI memory map for the region covering @phys_addr. * Returns the EFI memory type if the region was found in the memory * map, -EINVAL otherwise. */ int efi_mem_type(unsigned long phys_addr) { const efi_memory_desc_t *md; if (!efi_enabled(EFI_MEMMAP)) return -ENOTSUPP; for_each_efi_memory_desc(md) { if ((md->phys_addr <= phys_addr) && (phys_addr < (md->phys_addr + (md->num_pages << EFI_PAGE_SHIFT)))) return md->type; } return -EINVAL; } #endif int efi_status_to_err(efi_status_t status) { int err; switch (status) { case EFI_SUCCESS: err = 0; break; case EFI_INVALID_PARAMETER: err = -EINVAL; break; case EFI_OUT_OF_RESOURCES: err = -ENOSPC; break; case EFI_DEVICE_ERROR: err = -EIO; break; case EFI_WRITE_PROTECTED: err = -EROFS; break; case EFI_SECURITY_VIOLATION: err = -EACCES; break; case EFI_NOT_FOUND: err = -ENOENT; break; case EFI_ABORTED: err = -EINTR; break; default: err = -EINVAL; } return err; } EXPORT_SYMBOL_GPL(efi_status_to_err); static DEFINE_SPINLOCK(efi_mem_reserve_persistent_lock); static struct linux_efi_memreserve *efi_memreserve_root __ro_after_init; static int __init efi_memreserve_map_root(void) { if (mem_reserve == EFI_INVALID_TABLE_ADDR) return -ENODEV; efi_memreserve_root = memremap(mem_reserve, sizeof(*efi_memreserve_root), MEMREMAP_WB); if (WARN_ON_ONCE(!efi_memreserve_root)) return -ENOMEM; return 0; } static int efi_mem_reserve_iomem(phys_addr_t addr, u64 size) { struct resource *res, *parent; int ret; res = kzalloc(sizeof(struct resource), GFP_ATOMIC); if (!res) return -ENOMEM; res->name = "reserved"; res->flags = IORESOURCE_MEM; res->start = addr; res->end = addr + size - 1; /* we expect a conflict with a 'System RAM' region */ parent = request_resource_conflict(&iomem_resource, res); ret = parent ? request_resource(parent, res) : 0; /* * Given that efi_mem_reserve_iomem() can be called at any * time, only call memblock_reserve() if the architecture * keeps the infrastructure around. */ if (IS_ENABLED(CONFIG_ARCH_KEEP_MEMBLOCK) && !ret) memblock_reserve(addr, size); return ret; } int __ref efi_mem_reserve_persistent(phys_addr_t addr, u64 size) { struct linux_efi_memreserve *rsv; unsigned long prsv; int rc, index; if (efi_memreserve_root == (void *)ULONG_MAX) return -ENODEV; if (!efi_memreserve_root) { rc = efi_memreserve_map_root(); if (rc) return rc; } /* first try to find a slot in an existing linked list entry */ for (prsv = efi_memreserve_root->next; prsv; ) { rsv = memremap(prsv, sizeof(*rsv), MEMREMAP_WB); if (!rsv) return -ENOMEM; index = atomic_fetch_add_unless(&rsv->count, 1, rsv->size); if (index < rsv->size) { rsv->entry[index].base = addr; rsv->entry[index].size = size; memunmap(rsv); return efi_mem_reserve_iomem(addr, size); } prsv = rsv->next; memunmap(rsv); } /* no slot found - allocate a new linked list entry */ rsv = (struct linux_efi_memreserve *)__get_free_page(GFP_ATOMIC); if (!rsv) return -ENOMEM; rc = efi_mem_reserve_iomem(__pa(rsv), SZ_4K); if (rc) { free_page((unsigned long)rsv); return rc; } /* * The memremap() call above assumes that a linux_efi_memreserve entry * never crosses a page boundary, so let's ensure that this remains true * even when kexec'ing a 4k pages kernel from a >4k pages kernel, by * using SZ_4K explicitly in the size calculation below. */ rsv->size = EFI_MEMRESERVE_COUNT(SZ_4K); atomic_set(&rsv->count, 1); rsv->entry[0].base = addr; rsv->entry[0].size = size; spin_lock(&efi_mem_reserve_persistent_lock); rsv->next = efi_memreserve_root->next; efi_memreserve_root->next = __pa(rsv); spin_unlock(&efi_mem_reserve_persistent_lock); return efi_mem_reserve_iomem(addr, size); } static int __init efi_memreserve_root_init(void) { if (efi_memreserve_root) return 0; if (efi_memreserve_map_root()) efi_memreserve_root = (void *)ULONG_MAX; return 0; } early_initcall(efi_memreserve_root_init); #ifdef CONFIG_KEXEC static int update_efi_random_seed(struct notifier_block *nb, unsigned long code, void *unused) { struct linux_efi_random_seed *seed; u32 size = 0; if (!kexec_in_progress) return NOTIFY_DONE; seed = memremap(efi_rng_seed, sizeof(*seed), MEMREMAP_WB); if (seed != NULL) { size = min(seed->size, EFI_RANDOM_SEED_SIZE); memunmap(seed); } else { pr_err("Could not map UEFI random seed!\n"); } if (size > 0) { seed = memremap(efi_rng_seed, sizeof(*seed) + size, MEMREMAP_WB); if (seed != NULL) { seed->size = size; get_random_bytes(seed->bits, seed->size); memunmap(seed); } else { pr_err("Could not map UEFI random seed!\n"); } } return NOTIFY_DONE; } static struct notifier_block efi_random_seed_nb = { .notifier_call = update_efi_random_seed, }; static int __init register_update_efi_random_seed(void) { if (efi_rng_seed == EFI_INVALID_TABLE_ADDR) return 0; return register_reboot_notifier(&efi_random_seed_nb); } late_initcall(register_update_efi_random_seed); #endif
linux-master
drivers/firmware/efi/efi.c
// SPDX-License-Identifier: GPL-2.0 /* * Extensible Firmware Interface * * Copyright (C) 2020 Western Digital Corporation or its affiliates. * * Based on Extensible Firmware Interface Specification version 2.4 * Adapted from drivers/firmware/efi/arm-runtime.c * */ #include <linux/dmi.h> #include <linux/efi.h> #include <linux/io.h> #include <linux/memblock.h> #include <linux/mm_types.h> #include <linux/preempt.h> #include <linux/rbtree.h> #include <linux/rwsem.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/pgtable.h> #include <asm/cacheflush.h> #include <asm/efi.h> #include <asm/mmu.h> #include <asm/pgalloc.h> static bool __init efi_virtmap_init(void) { efi_memory_desc_t *md; efi_mm.pgd = pgd_alloc(&efi_mm); mm_init_cpumask(&efi_mm); init_new_context(NULL, &efi_mm); for_each_efi_memory_desc(md) { phys_addr_t phys = md->phys_addr; int ret; if (!(md->attribute & EFI_MEMORY_RUNTIME)) continue; if (md->virt_addr == U64_MAX) return false; ret = efi_create_mapping(&efi_mm, md); if (ret) { pr_warn(" EFI remap %pa: failed to create mapping (%d)\n", &phys, ret); return false; } } if (efi_memattr_apply_permissions(&efi_mm, efi_set_mapping_permissions)) return false; return true; } /* * Enable the UEFI Runtime Services if all prerequisites are in place, i.e., * non-early mapping of the UEFI system table and virtual mappings for all * EFI_MEMORY_RUNTIME regions. */ static int __init riscv_enable_runtime_services(void) { u64 mapsize; if (!efi_enabled(EFI_BOOT)) { pr_info("EFI services will not be available.\n"); return 0; } efi_memmap_unmap(); mapsize = efi.memmap.desc_size * efi.memmap.nr_map; if (efi_memmap_init_late(efi.memmap.phys_map, mapsize)) { pr_err("Failed to remap EFI memory map\n"); return 0; } if (efi_soft_reserve_enabled()) { efi_memory_desc_t *md; for_each_efi_memory_desc(md) { int md_size = md->num_pages << EFI_PAGE_SHIFT; struct resource *res; if (!(md->attribute & EFI_MEMORY_SP)) continue; res = kzalloc(sizeof(*res), GFP_KERNEL); if (WARN_ON(!res)) break; res->start = md->phys_addr; res->end = md->phys_addr + md_size - 1; res->name = "Soft Reserved"; res->flags = IORESOURCE_MEM; res->desc = IORES_DESC_SOFT_RESERVED; insert_resource(&iomem_resource, res); } } if (efi_runtime_disabled()) { pr_info("EFI runtime services will be disabled.\n"); return 0; } if (efi_enabled(EFI_RUNTIME_SERVICES)) { pr_info("EFI runtime services access via paravirt.\n"); return 0; } pr_info("Remapping and enabling EFI services.\n"); if (!efi_virtmap_init()) { pr_err("UEFI virtual mapping missing or invalid -- runtime services will not be available\n"); return -ENOMEM; } /* Set up runtime services function pointers */ efi_native_runtime_setup(); set_bit(EFI_RUNTIME_SERVICES, &efi.flags); return 0; } early_initcall(riscv_enable_runtime_services); static void efi_virtmap_load(void) { preempt_disable(); switch_mm(current->active_mm, &efi_mm, NULL); } static void efi_virtmap_unload(void) { switch_mm(&efi_mm, current->active_mm, NULL); preempt_enable(); } void arch_efi_call_virt_setup(void) { sync_kernel_mappings(efi_mm.pgd); efi_virtmap_load(); } void arch_efi_call_virt_teardown(void) { efi_virtmap_unload(); }
linux-master
drivers/firmware/efi/riscv-runtime.c
// SPDX-License-Identifier: GPL-2.0 /* * efibc: control EFI bootloaders which obey LoaderEntryOneShot var * Copyright (c) 2013-2016, Intel Corporation. */ #define pr_fmt(fmt) "efibc: " fmt #include <linux/efi.h> #include <linux/module.h> #include <linux/reboot.h> #include <linux/slab.h> #include <linux/ucs2_string.h> #define MAX_DATA_LEN 512 static int efibc_set_variable(efi_char16_t *name, efi_char16_t *value, unsigned long len) { efi_status_t status; status = efi.set_variable(name, &LINUX_EFI_LOADER_ENTRY_GUID, EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, len * sizeof(efi_char16_t), value); if (status != EFI_SUCCESS) { pr_err("failed to set EFI variable: 0x%lx\n", status); return -EIO; } return 0; } static int efibc_reboot_notifier_call(struct notifier_block *notifier, unsigned long event, void *data) { efi_char16_t *reason = event == SYS_RESTART ? L"reboot" : L"shutdown"; const u8 *str = data; efi_char16_t *wdata; unsigned long l; int ret; ret = efibc_set_variable(L"LoaderEntryRebootReason", reason, ucs2_strlen(reason)); if (ret || !data) return NOTIFY_DONE; wdata = kmalloc(MAX_DATA_LEN * sizeof(efi_char16_t), GFP_KERNEL); if (!wdata) return NOTIFY_DONE; for (l = 0; l < MAX_DATA_LEN - 1 && str[l] != '\0'; l++) wdata[l] = str[l]; wdata[l] = L'\0'; efibc_set_variable(L"LoaderEntryOneShot", wdata, l); kfree(wdata); return NOTIFY_DONE; } static struct notifier_block efibc_reboot_notifier = { .notifier_call = efibc_reboot_notifier_call, }; static int __init efibc_init(void) { int ret; if (!efi_rt_services_supported(EFI_RT_SUPPORTED_SET_VARIABLE)) return -ENODEV; ret = register_reboot_notifier(&efibc_reboot_notifier); if (ret) pr_err("unable to register reboot notifier\n"); return ret; } module_init(efibc_init); static void __exit efibc_exit(void) { unregister_reboot_notifier(&efibc_reboot_notifier); } module_exit(efibc_exit); MODULE_AUTHOR("Jeremy Compostella <[email protected]>"); MODULE_AUTHOR("Matt Gumbel <[email protected]"); MODULE_DESCRIPTION("EFI Bootloader Control"); MODULE_LICENSE("GPL v2");
linux-master
drivers/firmware/efi/efibc.c
// SPDX-License-Identifier: GPL-2.0-only #define pr_fmt(fmt) "efi: " fmt #include <linux/module.h> #include <linux/init.h> #include <linux/efi.h> #include <linux/libfdt.h> #include <linux/of_fdt.h> #include <asm/unaligned.h> enum { SYSTAB, MMBASE, MMSIZE, DCSIZE, DCVERS, PARAMCOUNT }; static __initconst const char name[][22] = { [SYSTAB] = "System Table ", [MMBASE] = "MemMap Address ", [MMSIZE] = "MemMap Size ", [DCSIZE] = "MemMap Desc. Size ", [DCVERS] = "MemMap Desc. Version ", }; static __initconst const struct { const char path[17]; u8 paravirt; const char params[PARAMCOUNT][26]; } dt_params[] = { { #ifdef CONFIG_XEN // <-------17------> .path = "/hypervisor/uefi", .paravirt = 1, .params = { [SYSTAB] = "xen,uefi-system-table", [MMBASE] = "xen,uefi-mmap-start", [MMSIZE] = "xen,uefi-mmap-size", [DCSIZE] = "xen,uefi-mmap-desc-size", [DCVERS] = "xen,uefi-mmap-desc-ver", } }, { #endif .path = "/chosen", .params = { // <-----------26-----------> [SYSTAB] = "linux,uefi-system-table", [MMBASE] = "linux,uefi-mmap-start", [MMSIZE] = "linux,uefi-mmap-size", [DCSIZE] = "linux,uefi-mmap-desc-size", [DCVERS] = "linux,uefi-mmap-desc-ver", } } }; static int __init efi_get_fdt_prop(const void *fdt, int node, const char *pname, const char *rname, void *var, int size) { const void *prop; int len; u64 val; prop = fdt_getprop(fdt, node, pname, &len); if (!prop) return 1; val = (len == 4) ? (u64)be32_to_cpup(prop) : get_unaligned_be64(prop); if (size == 8) *(u64 *)var = val; else *(u32 *)var = (val < U32_MAX) ? val : U32_MAX; // saturate if (efi_enabled(EFI_DBG)) pr_info(" %s: 0x%0*llx\n", rname, size * 2, val); return 0; } u64 __init efi_get_fdt_params(struct efi_memory_map_data *mm) { const void *fdt = initial_boot_params; unsigned long systab; int i, j, node; struct { void *var; int size; } target[] = { [SYSTAB] = { &systab, sizeof(systab) }, [MMBASE] = { &mm->phys_map, sizeof(mm->phys_map) }, [MMSIZE] = { &mm->size, sizeof(mm->size) }, [DCSIZE] = { &mm->desc_size, sizeof(mm->desc_size) }, [DCVERS] = { &mm->desc_version, sizeof(mm->desc_version) }, }; BUILD_BUG_ON(ARRAY_SIZE(target) != ARRAY_SIZE(name)); BUILD_BUG_ON(ARRAY_SIZE(target) != ARRAY_SIZE(dt_params[0].params)); if (!fdt) return 0; for (i = 0; i < ARRAY_SIZE(dt_params); i++) { node = fdt_path_offset(fdt, dt_params[i].path); if (node < 0) continue; if (efi_enabled(EFI_DBG)) pr_info("Getting UEFI parameters from %s in DT:\n", dt_params[i].path); for (j = 0; j < ARRAY_SIZE(target); j++) { const char *pname = dt_params[i].params[j]; if (!efi_get_fdt_prop(fdt, node, pname, name[j], target[j].var, target[j].size)) continue; if (!j) goto notfound; pr_err("Can't find property '%s' in DT!\n", pname); return 0; } if (dt_params[i].paravirt) set_bit(EFI_PARAVIRT, &efi.flags); return systab; } notfound: pr_info("UEFI not found.\n"); return 0; }
linux-master
drivers/firmware/efi/fdtparams.c
// SPDX-License-Identifier: GPL-2.0 /* * EFI capsule loader driver. * * Copyright 2015 Intel Corporation */ #define pr_fmt(fmt) "efi: " fmt #include <linux/kernel.h> #include <linux/module.h> #include <linux/miscdevice.h> #include <linux/highmem.h> #include <linux/io.h> #include <linux/slab.h> #include <linux/mutex.h> #include <linux/efi.h> #include <linux/vmalloc.h> #define NO_FURTHER_WRITE_ACTION -1 /** * efi_free_all_buff_pages - free all previous allocated buffer pages * @cap_info: pointer to current instance of capsule_info structure * * In addition to freeing buffer pages, it flags NO_FURTHER_WRITE_ACTION * to cease processing data in subsequent write(2) calls until close(2) * is called. **/ static void efi_free_all_buff_pages(struct capsule_info *cap_info) { while (cap_info->index > 0) __free_page(cap_info->pages[--cap_info->index]); cap_info->index = NO_FURTHER_WRITE_ACTION; } int __efi_capsule_setup_info(struct capsule_info *cap_info) { size_t pages_needed; int ret; void *temp_page; pages_needed = ALIGN(cap_info->total_size, PAGE_SIZE) / PAGE_SIZE; if (pages_needed == 0) { pr_err("invalid capsule size\n"); return -EINVAL; } /* Check if the capsule binary supported */ ret = efi_capsule_supported(cap_info->header.guid, cap_info->header.flags, cap_info->header.imagesize, &cap_info->reset_type); if (ret) { pr_err("capsule not supported\n"); return ret; } temp_page = krealloc(cap_info->pages, pages_needed * sizeof(void *), GFP_KERNEL | __GFP_ZERO); if (!temp_page) return -ENOMEM; cap_info->pages = temp_page; temp_page = krealloc(cap_info->phys, pages_needed * sizeof(phys_addr_t *), GFP_KERNEL | __GFP_ZERO); if (!temp_page) return -ENOMEM; cap_info->phys = temp_page; return 0; } /** * efi_capsule_setup_info - obtain the efi capsule header in the binary and * setup capsule_info structure * @cap_info: pointer to current instance of capsule_info structure * @kbuff: a mapped first page buffer pointer * @hdr_bytes: the total received number of bytes for efi header * * Platforms with non-standard capsule update mechanisms can override * this __weak function so they can perform any required capsule * image munging. See quark_quirk_function() for an example. **/ int __weak efi_capsule_setup_info(struct capsule_info *cap_info, void *kbuff, size_t hdr_bytes) { /* Only process data block that is larger than efi header size */ if (hdr_bytes < sizeof(efi_capsule_header_t)) return 0; memcpy(&cap_info->header, kbuff, sizeof(cap_info->header)); cap_info->total_size = cap_info->header.imagesize; return __efi_capsule_setup_info(cap_info); } /** * efi_capsule_submit_update - invoke the efi_capsule_update API once binary * upload done * @cap_info: pointer to current instance of capsule_info structure **/ static ssize_t efi_capsule_submit_update(struct capsule_info *cap_info) { bool do_vunmap = false; int ret; /* * cap_info->capsule may have been assigned already by a quirk * handler, so only overwrite it if it is NULL */ if (!cap_info->capsule) { cap_info->capsule = vmap(cap_info->pages, cap_info->index, VM_MAP, PAGE_KERNEL); if (!cap_info->capsule) return -ENOMEM; do_vunmap = true; } ret = efi_capsule_update(cap_info->capsule, cap_info->phys); if (do_vunmap) vunmap(cap_info->capsule); if (ret) { pr_err("capsule update failed\n"); return ret; } /* Indicate capsule binary uploading is done */ cap_info->index = NO_FURTHER_WRITE_ACTION; if (cap_info->header.flags & EFI_CAPSULE_PERSIST_ACROSS_RESET) { pr_info("Successfully uploaded capsule file with reboot type '%s'\n", !cap_info->reset_type ? "RESET_COLD" : cap_info->reset_type == 1 ? "RESET_WARM" : "RESET_SHUTDOWN"); } else { pr_info("Successfully processed capsule file\n"); } return 0; } /** * efi_capsule_write - store the capsule binary and pass it to * efi_capsule_update() API * @file: file pointer * @buff: buffer pointer * @count: number of bytes in @buff * @offp: not used * * Expectation: * - A user space tool should start at the beginning of capsule binary and * pass data in sequentially. * - Users should close and re-open this file note in order to upload more * capsules. * - After an error returned, user should close the file and restart the * operation for the next try otherwise -EIO will be returned until the * file is closed. * - An EFI capsule header must be located at the beginning of capsule * binary file and passed in as first block data of write operation. **/ static ssize_t efi_capsule_write(struct file *file, const char __user *buff, size_t count, loff_t *offp) { int ret; struct capsule_info *cap_info = file->private_data; struct page *page; void *kbuff = NULL; size_t write_byte; if (count == 0) return 0; /* Return error while NO_FURTHER_WRITE_ACTION is flagged */ if (cap_info->index < 0) return -EIO; /* Only alloc a new page when previous page is full */ if (!cap_info->page_bytes_remain) { page = alloc_page(GFP_KERNEL); if (!page) { ret = -ENOMEM; goto failed; } cap_info->pages[cap_info->index] = page; cap_info->phys[cap_info->index] = page_to_phys(page); cap_info->page_bytes_remain = PAGE_SIZE; cap_info->index++; } else { page = cap_info->pages[cap_info->index - 1]; } kbuff = kmap(page); kbuff += PAGE_SIZE - cap_info->page_bytes_remain; /* Copy capsule binary data from user space to kernel space buffer */ write_byte = min_t(size_t, count, cap_info->page_bytes_remain); if (copy_from_user(kbuff, buff, write_byte)) { ret = -EFAULT; goto fail_unmap; } cap_info->page_bytes_remain -= write_byte; /* Setup capsule binary info structure */ if (cap_info->header.headersize == 0) { ret = efi_capsule_setup_info(cap_info, kbuff - cap_info->count, cap_info->count + write_byte); if (ret) goto fail_unmap; } cap_info->count += write_byte; kunmap(page); /* Submit the full binary to efi_capsule_update() API */ if (cap_info->header.headersize > 0 && cap_info->count >= cap_info->total_size) { if (cap_info->count > cap_info->total_size) { pr_err("capsule upload size exceeded header defined size\n"); ret = -EINVAL; goto failed; } ret = efi_capsule_submit_update(cap_info); if (ret) goto failed; } return write_byte; fail_unmap: kunmap(page); failed: efi_free_all_buff_pages(cap_info); return ret; } /** * efi_capsule_release - called by file close * @inode: not used * @file: file pointer * * We will not free successfully submitted pages since efi update * requires data to be maintained across system reboot. **/ static int efi_capsule_release(struct inode *inode, struct file *file) { struct capsule_info *cap_info = file->private_data; if (cap_info->index > 0 && (cap_info->header.headersize == 0 || cap_info->count < cap_info->total_size)) { pr_err("capsule upload not complete\n"); efi_free_all_buff_pages(cap_info); } kfree(cap_info->pages); kfree(cap_info->phys); kfree(file->private_data); file->private_data = NULL; return 0; } /** * efi_capsule_open - called by file open * @inode: not used * @file: file pointer * * Will allocate each capsule_info memory for each file open call. * This provided the capability to support multiple file open feature * where user is not needed to wait for others to finish in order to * upload their capsule binary. **/ static int efi_capsule_open(struct inode *inode, struct file *file) { struct capsule_info *cap_info; cap_info = kzalloc(sizeof(*cap_info), GFP_KERNEL); if (!cap_info) return -ENOMEM; cap_info->pages = kzalloc(sizeof(void *), GFP_KERNEL); if (!cap_info->pages) { kfree(cap_info); return -ENOMEM; } cap_info->phys = kzalloc(sizeof(void *), GFP_KERNEL); if (!cap_info->phys) { kfree(cap_info->pages); kfree(cap_info); return -ENOMEM; } file->private_data = cap_info; return 0; } static const struct file_operations efi_capsule_fops = { .owner = THIS_MODULE, .open = efi_capsule_open, .write = efi_capsule_write, .release = efi_capsule_release, .llseek = no_llseek, }; static struct miscdevice efi_capsule_misc = { .minor = MISC_DYNAMIC_MINOR, .name = "efi_capsule_loader", .fops = &efi_capsule_fops, }; static int __init efi_capsule_loader_init(void) { int ret; if (!efi_enabled(EFI_RUNTIME_SERVICES)) return -ENODEV; ret = misc_register(&efi_capsule_misc); if (ret) pr_err("Unable to register capsule loader device\n"); return ret; } module_init(efi_capsule_loader_init); static void __exit efi_capsule_loader_exit(void) { misc_deregister(&efi_capsule_misc); } module_exit(efi_capsule_loader_exit); MODULE_DESCRIPTION("EFI capsule firmware binary loader"); MODULE_LICENSE("GPL v2");
linux-master
drivers/firmware/efi/capsule-loader.c
// SPDX-License-Identifier: GPL-2.0 /* * Extensible Firmware Interface * * Based on Extensible Firmware Interface Specification version 2.4 * * Copyright (C) 2013 - 2015 Linaro Ltd. */ #define pr_fmt(fmt) "efi: " fmt #include <linux/efi.h> #include <linux/fwnode.h> #include <linux/init.h> #include <linux/memblock.h> #include <linux/mm_types.h> #include <linux/of.h> #include <linux/of_address.h> #include <linux/of_fdt.h> #include <linux/platform_device.h> #include <linux/screen_info.h> #include <asm/efi.h> unsigned long __initdata screen_info_table = EFI_INVALID_TABLE_ADDR; static int __init is_memory(efi_memory_desc_t *md) { if (md->attribute & (EFI_MEMORY_WB|EFI_MEMORY_WT|EFI_MEMORY_WC)) return 1; return 0; } /* * Translate a EFI virtual address into a physical address: this is necessary, * as some data members of the EFI system table are virtually remapped after * SetVirtualAddressMap() has been called. */ static phys_addr_t __init efi_to_phys(unsigned long addr) { efi_memory_desc_t *md; for_each_efi_memory_desc(md) { if (!(md->attribute & EFI_MEMORY_RUNTIME)) continue; if (md->virt_addr == 0) /* no virtual mapping has been installed by the stub */ break; if (md->virt_addr <= addr && (addr - md->virt_addr) < (md->num_pages << EFI_PAGE_SHIFT)) return md->phys_addr + addr - md->virt_addr; } return addr; } extern __weak const efi_config_table_type_t efi_arch_tables[]; static void __init init_screen_info(void) { struct screen_info *si; if (screen_info_table != EFI_INVALID_TABLE_ADDR) { si = early_memremap(screen_info_table, sizeof(*si)); if (!si) { pr_err("Could not map screen_info config table\n"); return; } screen_info = *si; memset(si, 0, sizeof(*si)); early_memunmap(si, sizeof(*si)); if (memblock_is_map_memory(screen_info.lfb_base)) memblock_mark_nomap(screen_info.lfb_base, screen_info.lfb_size); if (IS_ENABLED(CONFIG_EFI_EARLYCON)) efi_earlycon_reprobe(); } } static int __init uefi_init(u64 efi_system_table) { efi_config_table_t *config_tables; efi_system_table_t *systab; size_t table_size; int retval; systab = early_memremap_ro(efi_system_table, sizeof(efi_system_table_t)); if (systab == NULL) { pr_warn("Unable to map EFI system table.\n"); return -ENOMEM; } set_bit(EFI_BOOT, &efi.flags); if (IS_ENABLED(CONFIG_64BIT)) set_bit(EFI_64BIT, &efi.flags); retval = efi_systab_check_header(&systab->hdr); if (retval) goto out; efi.runtime = systab->runtime; efi.runtime_version = systab->hdr.revision; efi_systab_report_header(&systab->hdr, efi_to_phys(systab->fw_vendor)); table_size = sizeof(efi_config_table_t) * systab->nr_tables; config_tables = early_memremap_ro(efi_to_phys(systab->tables), table_size); if (config_tables == NULL) { pr_warn("Unable to map EFI config table array.\n"); retval = -ENOMEM; goto out; } retval = efi_config_parse_tables(config_tables, systab->nr_tables, efi_arch_tables); early_memunmap(config_tables, table_size); out: early_memunmap(systab, sizeof(efi_system_table_t)); return retval; } /* * Return true for regions that can be used as System RAM. */ static __init int is_usable_memory(efi_memory_desc_t *md) { switch (md->type) { case EFI_LOADER_CODE: case EFI_LOADER_DATA: case EFI_ACPI_RECLAIM_MEMORY: case EFI_BOOT_SERVICES_CODE: case EFI_BOOT_SERVICES_DATA: case EFI_CONVENTIONAL_MEMORY: case EFI_PERSISTENT_MEMORY: /* * Special purpose memory is 'soft reserved', which means it * is set aside initially, but can be hotplugged back in or * be assigned to the dax driver after boot. */ if (efi_soft_reserve_enabled() && (md->attribute & EFI_MEMORY_SP)) return false; /* * According to the spec, these regions are no longer reserved * after calling ExitBootServices(). However, we can only use * them as System RAM if they can be mapped writeback cacheable. */ return (md->attribute & EFI_MEMORY_WB); default: break; } return false; } static __init void reserve_regions(void) { efi_memory_desc_t *md; u64 paddr, npages, size; if (efi_enabled(EFI_DBG)) pr_info("Processing EFI memory map:\n"); /* * Discard memblocks discovered so far: if there are any at this * point, they originate from memory nodes in the DT, and UEFI * uses its own memory map instead. */ memblock_dump_all(); memblock_remove(0, PHYS_ADDR_MAX); for_each_efi_memory_desc(md) { paddr = md->phys_addr; npages = md->num_pages; if (efi_enabled(EFI_DBG)) { char buf[64]; pr_info(" 0x%012llx-0x%012llx %s\n", paddr, paddr + (npages << EFI_PAGE_SHIFT) - 1, efi_md_typeattr_format(buf, sizeof(buf), md)); } memrange_efi_to_native(&paddr, &npages); size = npages << PAGE_SHIFT; if (is_memory(md)) { early_init_dt_add_memory_arch(paddr, size); if (!is_usable_memory(md)) memblock_mark_nomap(paddr, size); /* keep ACPI reclaim memory intact for kexec etc. */ if (md->type == EFI_ACPI_RECLAIM_MEMORY) memblock_reserve(paddr, size); } } } void __init efi_init(void) { struct efi_memory_map_data data; u64 efi_system_table; /* Grab UEFI information placed in FDT by stub */ efi_system_table = efi_get_fdt_params(&data); if (!efi_system_table) return; if (efi_memmap_init_early(&data) < 0) { /* * If we are booting via UEFI, the UEFI memory map is the only * description of memory we have, so there is little point in * proceeding if we cannot access it. */ panic("Unable to map EFI memory map.\n"); } WARN(efi.memmap.desc_version != 1, "Unexpected EFI_MEMORY_DESCRIPTOR version %ld", efi.memmap.desc_version); if (uefi_init(efi_system_table) < 0) { efi_memmap_unmap(); return; } reserve_regions(); /* * For memblock manipulation, the cap should come after the memblock_add(). * And now, memblock is fully populated, it is time to do capping. */ early_init_dt_check_for_usable_mem_range(); efi_find_mirror(); efi_esrt_init(); efi_mokvar_table_init(); memblock_reserve(data.phys_map & PAGE_MASK, PAGE_ALIGN(data.size + (data.phys_map & ~PAGE_MASK))); init_screen_info(); }
linux-master
drivers/firmware/efi/efi-init.c
// SPDX-License-Identifier: GPL-2.0 /* * UEFI Common Platform Error Record (CPER) support * * Copyright (C) 2010, Intel Corp. * Author: Huang Ying <[email protected]> * * CPER is the format used to describe platform hardware error by * various tables, such as ERST, BERT and HEST etc. * * For more information about CPER, please refer to Appendix N of UEFI * Specification version 2.4. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/time.h> #include <linux/cper.h> #include <linux/dmi.h> #include <linux/acpi.h> #include <linux/pci.h> #include <linux/aer.h> #include <linux/printk.h> #include <linux/bcd.h> #include <acpi/ghes.h> #include <ras/ras_event.h> #include "cper_cxl.h" /* * CPER record ID need to be unique even after reboot, because record * ID is used as index for ERST storage, while CPER records from * multiple boot may co-exist in ERST. */ u64 cper_next_record_id(void) { static atomic64_t seq; if (!atomic64_read(&seq)) { time64_t time = ktime_get_real_seconds(); /* * This code is unlikely to still be needed in year 2106, * but just in case, let's use a few more bits for timestamps * after y2038 to be sure they keep increasing monotonically * for the next few hundred years... */ if (time < 0x80000000) atomic64_set(&seq, (ktime_get_real_seconds()) << 32); else atomic64_set(&seq, 0x8000000000000000ull | ktime_get_real_seconds() << 24); } return atomic64_inc_return(&seq); } EXPORT_SYMBOL_GPL(cper_next_record_id); static const char * const severity_strs[] = { "recoverable", "fatal", "corrected", "info", }; const char *cper_severity_str(unsigned int severity) { return severity < ARRAY_SIZE(severity_strs) ? severity_strs[severity] : "unknown"; } EXPORT_SYMBOL_GPL(cper_severity_str); /* * cper_print_bits - print strings for set bits * @pfx: prefix for each line, including log level and prefix string * @bits: bit mask * @strs: string array, indexed by bit position * @strs_size: size of the string array: @strs * * For each set bit in @bits, print the corresponding string in @strs. * If the output length is longer than 80, multiple line will be * printed, with @pfx is printed at the beginning of each line. */ void cper_print_bits(const char *pfx, unsigned int bits, const char * const strs[], unsigned int strs_size) { int i, len = 0; const char *str; char buf[84]; for (i = 0; i < strs_size; i++) { if (!(bits & (1U << i))) continue; str = strs[i]; if (!str) continue; if (len && len + strlen(str) + 2 > 80) { printk("%s\n", buf); len = 0; } if (!len) len = snprintf(buf, sizeof(buf), "%s%s", pfx, str); else len += scnprintf(buf+len, sizeof(buf)-len, ", %s", str); } if (len) printk("%s\n", buf); } static const char * const proc_type_strs[] = { "IA32/X64", "IA64", "ARM", }; static const char * const proc_isa_strs[] = { "IA32", "IA64", "X64", "ARM A32/T32", "ARM A64", }; const char * const cper_proc_error_type_strs[] = { "cache error", "TLB error", "bus error", "micro-architectural error", }; static const char * const proc_op_strs[] = { "unknown or generic", "data read", "data write", "instruction execution", }; static const char * const proc_flag_strs[] = { "restartable", "precise IP", "overflow", "corrected", }; static void cper_print_proc_generic(const char *pfx, const struct cper_sec_proc_generic *proc) { if (proc->validation_bits & CPER_PROC_VALID_TYPE) printk("%s""processor_type: %d, %s\n", pfx, proc->proc_type, proc->proc_type < ARRAY_SIZE(proc_type_strs) ? proc_type_strs[proc->proc_type] : "unknown"); if (proc->validation_bits & CPER_PROC_VALID_ISA) printk("%s""processor_isa: %d, %s\n", pfx, proc->proc_isa, proc->proc_isa < ARRAY_SIZE(proc_isa_strs) ? proc_isa_strs[proc->proc_isa] : "unknown"); if (proc->validation_bits & CPER_PROC_VALID_ERROR_TYPE) { printk("%s""error_type: 0x%02x\n", pfx, proc->proc_error_type); cper_print_bits(pfx, proc->proc_error_type, cper_proc_error_type_strs, ARRAY_SIZE(cper_proc_error_type_strs)); } if (proc->validation_bits & CPER_PROC_VALID_OPERATION) printk("%s""operation: %d, %s\n", pfx, proc->operation, proc->operation < ARRAY_SIZE(proc_op_strs) ? proc_op_strs[proc->operation] : "unknown"); if (proc->validation_bits & CPER_PROC_VALID_FLAGS) { printk("%s""flags: 0x%02x\n", pfx, proc->flags); cper_print_bits(pfx, proc->flags, proc_flag_strs, ARRAY_SIZE(proc_flag_strs)); } if (proc->validation_bits & CPER_PROC_VALID_LEVEL) printk("%s""level: %d\n", pfx, proc->level); if (proc->validation_bits & CPER_PROC_VALID_VERSION) printk("%s""version_info: 0x%016llx\n", pfx, proc->cpu_version); if (proc->validation_bits & CPER_PROC_VALID_ID) printk("%s""processor_id: 0x%016llx\n", pfx, proc->proc_id); if (proc->validation_bits & CPER_PROC_VALID_TARGET_ADDRESS) printk("%s""target_address: 0x%016llx\n", pfx, proc->target_addr); if (proc->validation_bits & CPER_PROC_VALID_REQUESTOR_ID) printk("%s""requestor_id: 0x%016llx\n", pfx, proc->requestor_id); if (proc->validation_bits & CPER_PROC_VALID_RESPONDER_ID) printk("%s""responder_id: 0x%016llx\n", pfx, proc->responder_id); if (proc->validation_bits & CPER_PROC_VALID_IP) printk("%s""IP: 0x%016llx\n", pfx, proc->ip); } static const char * const mem_err_type_strs[] = { "unknown", "no error", "single-bit ECC", "multi-bit ECC", "single-symbol chipkill ECC", "multi-symbol chipkill ECC", "master abort", "target abort", "parity error", "watchdog timeout", "invalid address", "mirror Broken", "memory sparing", "scrub corrected error", "scrub uncorrected error", "physical memory map-out event", }; const char *cper_mem_err_type_str(unsigned int etype) { return etype < ARRAY_SIZE(mem_err_type_strs) ? mem_err_type_strs[etype] : "unknown"; } EXPORT_SYMBOL_GPL(cper_mem_err_type_str); const char *cper_mem_err_status_str(u64 status) { switch ((status >> 8) & 0xff) { case 1: return "Error detected internal to the component"; case 4: return "Storage error in DRAM memory"; case 5: return "Storage error in TLB"; case 6: return "Storage error in cache"; case 7: return "Error in one or more functional units"; case 8: return "Component failed self test"; case 9: return "Overflow or undervalue of internal queue"; case 16: return "Error detected in the bus"; case 17: return "Virtual address not found on IO-TLB or IO-PDIR"; case 18: return "Improper access error"; case 19: return "Access to a memory address which is not mapped to any component"; case 20: return "Loss of Lockstep"; case 21: return "Response not associated with a request"; case 22: return "Bus parity error - must also set the A, C, or D Bits"; case 23: return "Detection of a protocol error"; case 24: return "Detection of a PATH_ERROR"; case 25: return "Bus operation timeout"; case 26: return "A read was issued to data that has been poisoned"; default: return "Reserved"; } } EXPORT_SYMBOL_GPL(cper_mem_err_status_str); int cper_mem_err_location(struct cper_mem_err_compact *mem, char *msg) { u32 len, n; if (!msg) return 0; n = 0; len = CPER_REC_LEN; if (mem->validation_bits & CPER_MEM_VALID_NODE) n += scnprintf(msg + n, len - n, "node:%d ", mem->node); if (mem->validation_bits & CPER_MEM_VALID_CARD) n += scnprintf(msg + n, len - n, "card:%d ", mem->card); if (mem->validation_bits & CPER_MEM_VALID_MODULE) n += scnprintf(msg + n, len - n, "module:%d ", mem->module); if (mem->validation_bits & CPER_MEM_VALID_RANK_NUMBER) n += scnprintf(msg + n, len - n, "rank:%d ", mem->rank); if (mem->validation_bits & CPER_MEM_VALID_BANK) n += scnprintf(msg + n, len - n, "bank:%d ", mem->bank); if (mem->validation_bits & CPER_MEM_VALID_BANK_GROUP) n += scnprintf(msg + n, len - n, "bank_group:%d ", mem->bank >> CPER_MEM_BANK_GROUP_SHIFT); if (mem->validation_bits & CPER_MEM_VALID_BANK_ADDRESS) n += scnprintf(msg + n, len - n, "bank_address:%d ", mem->bank & CPER_MEM_BANK_ADDRESS_MASK); if (mem->validation_bits & CPER_MEM_VALID_DEVICE) n += scnprintf(msg + n, len - n, "device:%d ", mem->device); if (mem->validation_bits & (CPER_MEM_VALID_ROW | CPER_MEM_VALID_ROW_EXT)) { u32 row = mem->row; row |= cper_get_mem_extension(mem->validation_bits, mem->extended); n += scnprintf(msg + n, len - n, "row:%d ", row); } if (mem->validation_bits & CPER_MEM_VALID_COLUMN) n += scnprintf(msg + n, len - n, "column:%d ", mem->column); if (mem->validation_bits & CPER_MEM_VALID_BIT_POSITION) n += scnprintf(msg + n, len - n, "bit_position:%d ", mem->bit_pos); if (mem->validation_bits & CPER_MEM_VALID_REQUESTOR_ID) n += scnprintf(msg + n, len - n, "requestor_id:0x%016llx ", mem->requestor_id); if (mem->validation_bits & CPER_MEM_VALID_RESPONDER_ID) n += scnprintf(msg + n, len - n, "responder_id:0x%016llx ", mem->responder_id); if (mem->validation_bits & CPER_MEM_VALID_TARGET_ID) n += scnprintf(msg + n, len - n, "target_id:0x%016llx ", mem->target_id); if (mem->validation_bits & CPER_MEM_VALID_CHIP_ID) n += scnprintf(msg + n, len - n, "chip_id:%d ", mem->extended >> CPER_MEM_CHIP_ID_SHIFT); return n; } EXPORT_SYMBOL_GPL(cper_mem_err_location); int cper_dimm_err_location(struct cper_mem_err_compact *mem, char *msg) { u32 len, n; const char *bank = NULL, *device = NULL; if (!msg || !(mem->validation_bits & CPER_MEM_VALID_MODULE_HANDLE)) return 0; len = CPER_REC_LEN; dmi_memdev_name(mem->mem_dev_handle, &bank, &device); if (bank && device) n = snprintf(msg, len, "DIMM location: %s %s ", bank, device); else n = snprintf(msg, len, "DIMM location: not present. DMI handle: 0x%.4x ", mem->mem_dev_handle); return n; } EXPORT_SYMBOL_GPL(cper_dimm_err_location); void cper_mem_err_pack(const struct cper_sec_mem_err *mem, struct cper_mem_err_compact *cmem) { cmem->validation_bits = mem->validation_bits; cmem->node = mem->node; cmem->card = mem->card; cmem->module = mem->module; cmem->bank = mem->bank; cmem->device = mem->device; cmem->row = mem->row; cmem->column = mem->column; cmem->bit_pos = mem->bit_pos; cmem->requestor_id = mem->requestor_id; cmem->responder_id = mem->responder_id; cmem->target_id = mem->target_id; cmem->extended = mem->extended; cmem->rank = mem->rank; cmem->mem_array_handle = mem->mem_array_handle; cmem->mem_dev_handle = mem->mem_dev_handle; } EXPORT_SYMBOL_GPL(cper_mem_err_pack); const char *cper_mem_err_unpack(struct trace_seq *p, struct cper_mem_err_compact *cmem) { const char *ret = trace_seq_buffer_ptr(p); char rcd_decode_str[CPER_REC_LEN]; if (cper_mem_err_location(cmem, rcd_decode_str)) trace_seq_printf(p, "%s", rcd_decode_str); if (cper_dimm_err_location(cmem, rcd_decode_str)) trace_seq_printf(p, "%s", rcd_decode_str); trace_seq_putc(p, '\0'); return ret; } static void cper_print_mem(const char *pfx, const struct cper_sec_mem_err *mem, int len) { struct cper_mem_err_compact cmem; char rcd_decode_str[CPER_REC_LEN]; /* Don't trust UEFI 2.1/2.2 structure with bad validation bits */ if (len == sizeof(struct cper_sec_mem_err_old) && (mem->validation_bits & ~(CPER_MEM_VALID_RANK_NUMBER - 1))) { pr_err(FW_WARN "valid bits set for fields beyond structure\n"); return; } if (mem->validation_bits & CPER_MEM_VALID_ERROR_STATUS) printk("%s error_status: %s (0x%016llx)\n", pfx, cper_mem_err_status_str(mem->error_status), mem->error_status); if (mem->validation_bits & CPER_MEM_VALID_PA) printk("%s""physical_address: 0x%016llx\n", pfx, mem->physical_addr); if (mem->validation_bits & CPER_MEM_VALID_PA_MASK) printk("%s""physical_address_mask: 0x%016llx\n", pfx, mem->physical_addr_mask); cper_mem_err_pack(mem, &cmem); if (cper_mem_err_location(&cmem, rcd_decode_str)) printk("%s%s\n", pfx, rcd_decode_str); if (mem->validation_bits & CPER_MEM_VALID_ERROR_TYPE) { u8 etype = mem->error_type; printk("%s""error_type: %d, %s\n", pfx, etype, cper_mem_err_type_str(etype)); } if (cper_dimm_err_location(&cmem, rcd_decode_str)) printk("%s%s\n", pfx, rcd_decode_str); } static const char * const pcie_port_type_strs[] = { "PCIe end point", "legacy PCI end point", "unknown", "unknown", "root port", "upstream switch port", "downstream switch port", "PCIe to PCI/PCI-X bridge", "PCI/PCI-X to PCIe bridge", "root complex integrated endpoint device", "root complex event collector", }; static void cper_print_pcie(const char *pfx, const struct cper_sec_pcie *pcie, const struct acpi_hest_generic_data *gdata) { if (pcie->validation_bits & CPER_PCIE_VALID_PORT_TYPE) printk("%s""port_type: %d, %s\n", pfx, pcie->port_type, pcie->port_type < ARRAY_SIZE(pcie_port_type_strs) ? pcie_port_type_strs[pcie->port_type] : "unknown"); if (pcie->validation_bits & CPER_PCIE_VALID_VERSION) printk("%s""version: %d.%d\n", pfx, pcie->version.major, pcie->version.minor); if (pcie->validation_bits & CPER_PCIE_VALID_COMMAND_STATUS) printk("%s""command: 0x%04x, status: 0x%04x\n", pfx, pcie->command, pcie->status); if (pcie->validation_bits & CPER_PCIE_VALID_DEVICE_ID) { const __u8 *p; printk("%s""device_id: %04x:%02x:%02x.%x\n", pfx, pcie->device_id.segment, pcie->device_id.bus, pcie->device_id.device, pcie->device_id.function); printk("%s""slot: %d\n", pfx, pcie->device_id.slot >> CPER_PCIE_SLOT_SHIFT); printk("%s""secondary_bus: 0x%02x\n", pfx, pcie->device_id.secondary_bus); printk("%s""vendor_id: 0x%04x, device_id: 0x%04x\n", pfx, pcie->device_id.vendor_id, pcie->device_id.device_id); p = pcie->device_id.class_code; printk("%s""class_code: %02x%02x%02x\n", pfx, p[2], p[1], p[0]); } if (pcie->validation_bits & CPER_PCIE_VALID_SERIAL_NUMBER) printk("%s""serial number: 0x%04x, 0x%04x\n", pfx, pcie->serial_number.lower, pcie->serial_number.upper); if (pcie->validation_bits & CPER_PCIE_VALID_BRIDGE_CONTROL_STATUS) printk( "%s""bridge: secondary_status: 0x%04x, control: 0x%04x\n", pfx, pcie->bridge.secondary_status, pcie->bridge.control); /* Fatal errors call __ghes_panic() before AER handler prints this */ if ((pcie->validation_bits & CPER_PCIE_VALID_AER_INFO) && (gdata->error_severity & CPER_SEV_FATAL)) { struct aer_capability_regs *aer; aer = (struct aer_capability_regs *)pcie->aer_info; printk("%saer_uncor_status: 0x%08x, aer_uncor_mask: 0x%08x\n", pfx, aer->uncor_status, aer->uncor_mask); printk("%saer_uncor_severity: 0x%08x\n", pfx, aer->uncor_severity); printk("%sTLP Header: %08x %08x %08x %08x\n", pfx, aer->header_log.dw0, aer->header_log.dw1, aer->header_log.dw2, aer->header_log.dw3); } } static const char * const fw_err_rec_type_strs[] = { "IPF SAL Error Record", "SOC Firmware Error Record Type1 (Legacy CrashLog Support)", "SOC Firmware Error Record Type2", }; static void cper_print_fw_err(const char *pfx, struct acpi_hest_generic_data *gdata, const struct cper_sec_fw_err_rec_ref *fw_err) { void *buf = acpi_hest_get_payload(gdata); u32 offset, length = gdata->error_data_length; printk("%s""Firmware Error Record Type: %s\n", pfx, fw_err->record_type < ARRAY_SIZE(fw_err_rec_type_strs) ? fw_err_rec_type_strs[fw_err->record_type] : "unknown"); printk("%s""Revision: %d\n", pfx, fw_err->revision); /* Record Type based on UEFI 2.7 */ if (fw_err->revision == 0) { printk("%s""Record Identifier: %08llx\n", pfx, fw_err->record_identifier); } else if (fw_err->revision == 2) { printk("%s""Record Identifier: %pUl\n", pfx, &fw_err->record_identifier_guid); } /* * The FW error record may contain trailing data beyond the * structure defined by the specification. As the fields * defined (and hence the offset of any trailing data) vary * with the revision, set the offset to account for this * variation. */ if (fw_err->revision == 0) { /* record_identifier_guid not defined */ offset = offsetof(struct cper_sec_fw_err_rec_ref, record_identifier_guid); } else if (fw_err->revision == 1) { /* record_identifier not defined */ offset = offsetof(struct cper_sec_fw_err_rec_ref, record_identifier); } else { offset = sizeof(*fw_err); } buf += offset; length -= offset; print_hex_dump(pfx, "", DUMP_PREFIX_OFFSET, 16, 4, buf, length, true); } static void cper_print_tstamp(const char *pfx, struct acpi_hest_generic_data_v300 *gdata) { __u8 hour, min, sec, day, mon, year, century, *timestamp; if (gdata->validation_bits & ACPI_HEST_GEN_VALID_TIMESTAMP) { timestamp = (__u8 *)&(gdata->time_stamp); sec = bcd2bin(timestamp[0]); min = bcd2bin(timestamp[1]); hour = bcd2bin(timestamp[2]); day = bcd2bin(timestamp[4]); mon = bcd2bin(timestamp[5]); year = bcd2bin(timestamp[6]); century = bcd2bin(timestamp[7]); printk("%s%ststamp: %02d%02d-%02d-%02d %02d:%02d:%02d\n", pfx, (timestamp[3] & 0x1 ? "precise " : "imprecise "), century, year, mon, day, hour, min, sec); } } static void cper_estatus_print_section(const char *pfx, struct acpi_hest_generic_data *gdata, int sec_no) { guid_t *sec_type = (guid_t *)gdata->section_type; __u16 severity; char newpfx[64]; if (acpi_hest_get_version(gdata) >= 3) cper_print_tstamp(pfx, (struct acpi_hest_generic_data_v300 *)gdata); severity = gdata->error_severity; printk("%s""Error %d, type: %s\n", pfx, sec_no, cper_severity_str(severity)); if (gdata->validation_bits & CPER_SEC_VALID_FRU_ID) printk("%s""fru_id: %pUl\n", pfx, gdata->fru_id); if (gdata->validation_bits & CPER_SEC_VALID_FRU_TEXT) printk("%s""fru_text: %.20s\n", pfx, gdata->fru_text); snprintf(newpfx, sizeof(newpfx), "%s ", pfx); if (guid_equal(sec_type, &CPER_SEC_PROC_GENERIC)) { struct cper_sec_proc_generic *proc_err = acpi_hest_get_payload(gdata); printk("%s""section_type: general processor error\n", newpfx); if (gdata->error_data_length >= sizeof(*proc_err)) cper_print_proc_generic(newpfx, proc_err); else goto err_section_too_small; } else if (guid_equal(sec_type, &CPER_SEC_PLATFORM_MEM)) { struct cper_sec_mem_err *mem_err = acpi_hest_get_payload(gdata); printk("%s""section_type: memory error\n", newpfx); if (gdata->error_data_length >= sizeof(struct cper_sec_mem_err_old)) cper_print_mem(newpfx, mem_err, gdata->error_data_length); else goto err_section_too_small; } else if (guid_equal(sec_type, &CPER_SEC_PCIE)) { struct cper_sec_pcie *pcie = acpi_hest_get_payload(gdata); printk("%s""section_type: PCIe error\n", newpfx); if (gdata->error_data_length >= sizeof(*pcie)) cper_print_pcie(newpfx, pcie, gdata); else goto err_section_too_small; #if defined(CONFIG_ARM64) || defined(CONFIG_ARM) } else if (guid_equal(sec_type, &CPER_SEC_PROC_ARM)) { struct cper_sec_proc_arm *arm_err = acpi_hest_get_payload(gdata); printk("%ssection_type: ARM processor error\n", newpfx); if (gdata->error_data_length >= sizeof(*arm_err)) cper_print_proc_arm(newpfx, arm_err); else goto err_section_too_small; #endif #if defined(CONFIG_UEFI_CPER_X86) } else if (guid_equal(sec_type, &CPER_SEC_PROC_IA)) { struct cper_sec_proc_ia *ia_err = acpi_hest_get_payload(gdata); printk("%ssection_type: IA32/X64 processor error\n", newpfx); if (gdata->error_data_length >= sizeof(*ia_err)) cper_print_proc_ia(newpfx, ia_err); else goto err_section_too_small; #endif } else if (guid_equal(sec_type, &CPER_SEC_FW_ERR_REC_REF)) { struct cper_sec_fw_err_rec_ref *fw_err = acpi_hest_get_payload(gdata); printk("%ssection_type: Firmware Error Record Reference\n", newpfx); /* The minimal FW Error Record contains 16 bytes */ if (gdata->error_data_length >= SZ_16) cper_print_fw_err(newpfx, gdata, fw_err); else goto err_section_too_small; } else if (guid_equal(sec_type, &CPER_SEC_CXL_PROT_ERR)) { struct cper_sec_prot_err *prot_err = acpi_hest_get_payload(gdata); printk("%ssection_type: CXL Protocol Error\n", newpfx); if (gdata->error_data_length >= sizeof(*prot_err)) cper_print_prot_err(newpfx, prot_err); else goto err_section_too_small; } else { const void *err = acpi_hest_get_payload(gdata); printk("%ssection type: unknown, %pUl\n", newpfx, sec_type); printk("%ssection length: %#x\n", newpfx, gdata->error_data_length); print_hex_dump(newpfx, "", DUMP_PREFIX_OFFSET, 16, 4, err, gdata->error_data_length, true); } return; err_section_too_small: pr_err(FW_WARN "error section length is too small\n"); } void cper_estatus_print(const char *pfx, const struct acpi_hest_generic_status *estatus) { struct acpi_hest_generic_data *gdata; int sec_no = 0; char newpfx[64]; __u16 severity; severity = estatus->error_severity; if (severity == CPER_SEV_CORRECTED) printk("%s%s\n", pfx, "It has been corrected by h/w " "and requires no further action"); printk("%s""event severity: %s\n", pfx, cper_severity_str(severity)); snprintf(newpfx, sizeof(newpfx), "%s ", pfx); apei_estatus_for_each_section(estatus, gdata) { cper_estatus_print_section(newpfx, gdata, sec_no); sec_no++; } } EXPORT_SYMBOL_GPL(cper_estatus_print); int cper_estatus_check_header(const struct acpi_hest_generic_status *estatus) { if (estatus->data_length && estatus->data_length < sizeof(struct acpi_hest_generic_data)) return -EINVAL; if (estatus->raw_data_length && estatus->raw_data_offset < sizeof(*estatus) + estatus->data_length) return -EINVAL; return 0; } EXPORT_SYMBOL_GPL(cper_estatus_check_header); int cper_estatus_check(const struct acpi_hest_generic_status *estatus) { struct acpi_hest_generic_data *gdata; unsigned int data_len, record_size; int rc; rc = cper_estatus_check_header(estatus); if (rc) return rc; data_len = estatus->data_length; apei_estatus_for_each_section(estatus, gdata) { if (acpi_hest_get_size(gdata) > data_len) return -EINVAL; record_size = acpi_hest_get_record_size(gdata); if (record_size > data_len) return -EINVAL; data_len -= record_size; } if (data_len) return -EINVAL; return 0; } EXPORT_SYMBOL_GPL(cper_estatus_check);
linux-master
drivers/firmware/efi/cper.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Generic System Framebuffers * Copyright (c) 2012-2013 David Herrmann <[email protected]> * * EFI Quirks Copyright (c) 2006 Edgar Hucek <[email protected]> */ /* * EFI Quirks * Several EFI systems do not correctly advertise their boot framebuffers. * Hence, we use this static table of known broken machines and fix up the * information so framebuffer drivers can load correctly. */ #include <linux/dmi.h> #include <linux/err.h> #include <linux/efi.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/of_address.h> #include <linux/pci.h> #include <linux/platform_device.h> #include <linux/screen_info.h> #include <linux/sysfb.h> #include <video/vga.h> enum { OVERRIDE_NONE = 0x0, OVERRIDE_BASE = 0x1, OVERRIDE_STRIDE = 0x2, OVERRIDE_HEIGHT = 0x4, OVERRIDE_WIDTH = 0x8, }; struct efifb_dmi_info efifb_dmi_list[] = { [M_I17] = { "i17", 0x80010000, 1472 * 4, 1440, 900, OVERRIDE_NONE }, [M_I20] = { "i20", 0x80010000, 1728 * 4, 1680, 1050, OVERRIDE_NONE }, /* guess */ [M_I20_SR] = { "imac7", 0x40010000, 1728 * 4, 1680, 1050, OVERRIDE_NONE }, [M_I24] = { "i24", 0x80010000, 2048 * 4, 1920, 1200, OVERRIDE_NONE }, /* guess */ [M_I24_8_1] = { "imac8", 0xc0060000, 2048 * 4, 1920, 1200, OVERRIDE_NONE }, [M_I24_10_1] = { "imac10", 0xc0010000, 2048 * 4, 1920, 1080, OVERRIDE_NONE }, [M_I27_11_1] = { "imac11", 0xc0010000, 2560 * 4, 2560, 1440, OVERRIDE_NONE }, [M_MINI]= { "mini", 0x80000000, 2048 * 4, 1024, 768, OVERRIDE_NONE }, [M_MINI_3_1] = { "mini31", 0x40010000, 1024 * 4, 1024, 768, OVERRIDE_NONE }, [M_MINI_4_1] = { "mini41", 0xc0010000, 2048 * 4, 1920, 1200, OVERRIDE_NONE }, [M_MB] = { "macbook", 0x80000000, 2048 * 4, 1280, 800, OVERRIDE_NONE }, [M_MB_5_1] = { "macbook51", 0x80010000, 2048 * 4, 1280, 800, OVERRIDE_NONE }, [M_MB_6_1] = { "macbook61", 0x80010000, 2048 * 4, 1280, 800, OVERRIDE_NONE }, [M_MB_7_1] = { "macbook71", 0x80010000, 2048 * 4, 1280, 800, OVERRIDE_NONE }, [M_MBA] = { "mba", 0x80000000, 2048 * 4, 1280, 800, OVERRIDE_NONE }, /* 11" Macbook Air 3,1 passes the wrong stride */ [M_MBA_3] = { "mba3", 0, 2048 * 4, 0, 0, OVERRIDE_STRIDE }, [M_MBP] = { "mbp", 0x80010000, 1472 * 4, 1440, 900, OVERRIDE_NONE }, [M_MBP_2] = { "mbp2", 0, 0, 0, 0, OVERRIDE_NONE }, /* placeholder */ [M_MBP_2_2] = { "mbp22", 0x80010000, 1472 * 4, 1440, 900, OVERRIDE_NONE }, [M_MBP_SR] = { "mbp3", 0x80030000, 2048 * 4, 1440, 900, OVERRIDE_NONE }, [M_MBP_4] = { "mbp4", 0xc0060000, 2048 * 4, 1920, 1200, OVERRIDE_NONE }, [M_MBP_5_1] = { "mbp51", 0xc0010000, 2048 * 4, 1440, 900, OVERRIDE_NONE }, [M_MBP_5_2] = { "mbp52", 0xc0010000, 2048 * 4, 1920, 1200, OVERRIDE_NONE }, [M_MBP_5_3] = { "mbp53", 0xd0010000, 2048 * 4, 1440, 900, OVERRIDE_NONE }, [M_MBP_6_1] = { "mbp61", 0x90030000, 2048 * 4, 1920, 1200, OVERRIDE_NONE }, [M_MBP_6_2] = { "mbp62", 0x90030000, 2048 * 4, 1680, 1050, OVERRIDE_NONE }, [M_MBP_7_1] = { "mbp71", 0xc0010000, 2048 * 4, 1280, 800, OVERRIDE_NONE }, [M_MBP_8_2] = { "mbp82", 0x90010000, 1472 * 4, 1440, 900, OVERRIDE_NONE }, [M_UNKNOWN] = { NULL, 0, 0, 0, 0, OVERRIDE_NONE } }; void efifb_setup_from_dmi(struct screen_info *si, const char *opt) { int i; for (i = 0; i < M_UNKNOWN; i++) { if (efifb_dmi_list[i].base != 0 && !strcmp(opt, efifb_dmi_list[i].optname)) { si->lfb_base = efifb_dmi_list[i].base; si->lfb_linelength = efifb_dmi_list[i].stride; si->lfb_width = efifb_dmi_list[i].width; si->lfb_height = efifb_dmi_list[i].height; } } } #define choose_value(dmivalue, fwvalue, field, flags) ({ \ typeof(fwvalue) _ret_ = fwvalue; \ if ((flags) & (field)) \ _ret_ = dmivalue; \ else if ((fwvalue) == 0) \ _ret_ = dmivalue; \ _ret_; \ }) static int __init efifb_set_system(const struct dmi_system_id *id) { struct efifb_dmi_info *info = id->driver_data; if (info->base == 0 && info->height == 0 && info->width == 0 && info->stride == 0) return 0; /* Trust the bootloader over the DMI tables */ if (screen_info.lfb_base == 0) { #if defined(CONFIG_PCI) struct pci_dev *dev = NULL; int found_bar = 0; #endif if (info->base) { screen_info.lfb_base = choose_value(info->base, screen_info.lfb_base, OVERRIDE_BASE, info->flags); #if defined(CONFIG_PCI) /* make sure that the address in the table is actually * on a VGA device's PCI BAR */ for_each_pci_dev(dev) { int i; if ((dev->class >> 8) != PCI_CLASS_DISPLAY_VGA) continue; for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) { resource_size_t start, end; unsigned long flags; flags = pci_resource_flags(dev, i); if (!(flags & IORESOURCE_MEM)) continue; if (flags & IORESOURCE_UNSET) continue; if (pci_resource_len(dev, i) == 0) continue; start = pci_resource_start(dev, i); end = pci_resource_end(dev, i); if (screen_info.lfb_base >= start && screen_info.lfb_base < end) { found_bar = 1; break; } } } if (!found_bar) screen_info.lfb_base = 0; #endif } } if (screen_info.lfb_base) { screen_info.lfb_linelength = choose_value(info->stride, screen_info.lfb_linelength, OVERRIDE_STRIDE, info->flags); screen_info.lfb_width = choose_value(info->width, screen_info.lfb_width, OVERRIDE_WIDTH, info->flags); screen_info.lfb_height = choose_value(info->height, screen_info.lfb_height, OVERRIDE_HEIGHT, info->flags); if (screen_info.orig_video_isVGA == 0) screen_info.orig_video_isVGA = VIDEO_TYPE_EFI; } else { screen_info.lfb_linelength = 0; screen_info.lfb_width = 0; screen_info.lfb_height = 0; screen_info.orig_video_isVGA = 0; return 0; } printk(KERN_INFO "efifb: dmi detected %s - framebuffer at 0x%08x " "(%dx%d, stride %d)\n", id->ident, screen_info.lfb_base, screen_info.lfb_width, screen_info.lfb_height, screen_info.lfb_linelength); return 1; } #define EFIFB_DMI_SYSTEM_ID(vendor, name, enumid) \ { \ efifb_set_system, \ name, \ { \ DMI_MATCH(DMI_BIOS_VENDOR, vendor), \ DMI_MATCH(DMI_PRODUCT_NAME, name) \ }, \ &efifb_dmi_list[enumid] \ } static const struct dmi_system_id efifb_dmi_system_table[] __initconst = { EFIFB_DMI_SYSTEM_ID("Apple Computer, Inc.", "iMac4,1", M_I17), /* At least one of these two will be right; maybe both? */ EFIFB_DMI_SYSTEM_ID("Apple Computer, Inc.", "iMac5,1", M_I20), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "iMac5,1", M_I20), /* At least one of these two will be right; maybe both? */ EFIFB_DMI_SYSTEM_ID("Apple Computer, Inc.", "iMac6,1", M_I24), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "iMac6,1", M_I24), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "iMac7,1", M_I20_SR), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "iMac8,1", M_I24_8_1), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "iMac10,1", M_I24_10_1), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "iMac11,1", M_I27_11_1), EFIFB_DMI_SYSTEM_ID("Apple Computer, Inc.", "Macmini1,1", M_MINI), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "Macmini3,1", M_MINI_3_1), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "Macmini4,1", M_MINI_4_1), EFIFB_DMI_SYSTEM_ID("Apple Computer, Inc.", "MacBook1,1", M_MB), /* At least one of these two will be right; maybe both? */ EFIFB_DMI_SYSTEM_ID("Apple Computer, Inc.", "MacBook2,1", M_MB), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "MacBook2,1", M_MB), /* At least one of these two will be right; maybe both? */ EFIFB_DMI_SYSTEM_ID("Apple Computer, Inc.", "MacBook3,1", M_MB), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "MacBook3,1", M_MB), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "MacBook4,1", M_MB), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "MacBook5,1", M_MB_5_1), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "MacBook6,1", M_MB_6_1), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "MacBook7,1", M_MB_7_1), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "MacBookAir1,1", M_MBA), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "MacBookAir3,1", M_MBA_3), EFIFB_DMI_SYSTEM_ID("Apple Computer, Inc.", "MacBookPro1,1", M_MBP), EFIFB_DMI_SYSTEM_ID("Apple Computer, Inc.", "MacBookPro2,1", M_MBP_2), EFIFB_DMI_SYSTEM_ID("Apple Computer, Inc.", "MacBookPro2,2", M_MBP_2_2), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "MacBookPro2,1", M_MBP_2), EFIFB_DMI_SYSTEM_ID("Apple Computer, Inc.", "MacBookPro3,1", M_MBP_SR), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "MacBookPro3,1", M_MBP_SR), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "MacBookPro4,1", M_MBP_4), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "MacBookPro5,1", M_MBP_5_1), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "MacBookPro5,2", M_MBP_5_2), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "MacBookPro5,3", M_MBP_5_3), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "MacBookPro6,1", M_MBP_6_1), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "MacBookPro6,2", M_MBP_6_2), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "MacBookPro7,1", M_MBP_7_1), EFIFB_DMI_SYSTEM_ID("Apple Inc.", "MacBookPro8,2", M_MBP_8_2), {}, }; /* * Some devices have a portrait LCD but advertise a landscape resolution (and * pitch). We simply swap width and height for these devices so that we can * correctly deal with some of them coming with multiple resolutions. */ static const struct dmi_system_id efifb_dmi_swap_width_height[] __initconst = { { /* * Lenovo MIIX310-10ICR, only some batches have the troublesome * 800x1280 portrait screen. Luckily the portrait version has * its own BIOS version, so we match on that. */ .matches = { DMI_EXACT_MATCH(DMI_SYS_VENDOR, "LENOVO"), DMI_EXACT_MATCH(DMI_PRODUCT_VERSION, "MIIX 310-10ICR"), DMI_EXACT_MATCH(DMI_BIOS_VERSION, "1HCN44WW"), }, }, { /* Lenovo MIIX 320-10ICR with 800x1280 portrait screen */ .matches = { DMI_EXACT_MATCH(DMI_SYS_VENDOR, "LENOVO"), DMI_EXACT_MATCH(DMI_PRODUCT_VERSION, "Lenovo MIIX 320-10ICR"), }, }, { /* Lenovo D330 with 800x1280 or 1200x1920 portrait screen */ .matches = { DMI_EXACT_MATCH(DMI_SYS_VENDOR, "LENOVO"), DMI_EXACT_MATCH(DMI_PRODUCT_VERSION, "Lenovo ideapad D330-10IGM"), }, }, { /* Lenovo IdeaPad Duet 3 10IGL5 with 1200x1920 portrait screen */ .matches = { DMI_EXACT_MATCH(DMI_SYS_VENDOR, "LENOVO"), DMI_EXACT_MATCH(DMI_PRODUCT_VERSION, "IdeaPad Duet 3 10IGL5"), }, }, { /* Lenovo Yoga Book X91F / X91L */ .matches = { DMI_EXACT_MATCH(DMI_SYS_VENDOR, "LENOVO"), /* Non exact match to match F + L versions */ DMI_MATCH(DMI_PRODUCT_NAME, "Lenovo YB1-X91"), }, }, {}, }; static bool efifb_overlaps_pci_range(const struct of_pci_range *range) { u64 fb_base = screen_info.lfb_base; if (screen_info.capabilities & VIDEO_CAPABILITY_64BIT_BASE) fb_base |= (u64)(unsigned long)screen_info.ext_lfb_base << 32; return fb_base >= range->cpu_addr && fb_base < (range->cpu_addr + range->size); } static struct device_node *find_pci_overlap_node(void) { struct device_node *np; for_each_node_by_type(np, "pci") { struct of_pci_range_parser parser; struct of_pci_range range; int err; err = of_pci_range_parser_init(&parser, np); if (err) { pr_warn("of_pci_range_parser_init() failed: %d\n", err); continue; } for_each_of_pci_range(&parser, &range) if (efifb_overlaps_pci_range(&range)) return np; } return NULL; } /* * If the efifb framebuffer is backed by a PCI graphics controller, we have * to ensure that this relation is expressed using a device link when * running in DT mode, or the probe order may be reversed, resulting in a * resource reservation conflict on the memory window that the efifb * framebuffer steals from the PCIe host bridge. */ static int efifb_add_links(struct fwnode_handle *fwnode) { struct device_node *sup_np; sup_np = find_pci_overlap_node(); /* * If there's no PCI graphics controller backing the efifb, we are * done here. */ if (!sup_np) return 0; fwnode_link_add(fwnode, of_fwnode_handle(sup_np)); of_node_put(sup_np); return 0; } static const struct fwnode_operations efifb_fwnode_ops = { .add_links = efifb_add_links, }; #ifdef CONFIG_EFI static struct fwnode_handle efifb_fwnode; __init void sysfb_apply_efi_quirks(void) { if (screen_info.orig_video_isVGA != VIDEO_TYPE_EFI || !(screen_info.capabilities & VIDEO_CAPABILITY_SKIP_QUIRKS)) dmi_check_system(efifb_dmi_system_table); if (screen_info.orig_video_isVGA == VIDEO_TYPE_EFI && dmi_check_system(efifb_dmi_swap_width_height)) { u16 temp = screen_info.lfb_width; screen_info.lfb_width = screen_info.lfb_height; screen_info.lfb_height = temp; screen_info.lfb_linelength = 4 * screen_info.lfb_width; } } __init void sysfb_set_efifb_fwnode(struct platform_device *pd) { if (screen_info.orig_video_isVGA == VIDEO_TYPE_EFI && IS_ENABLED(CONFIG_PCI)) { fwnode_init(&efifb_fwnode, &efifb_fwnode_ops); pd->dev.fwnode = &efifb_fwnode; } } #endif
linux-master
drivers/firmware/efi/sysfb_efi.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2013 Intel Corporation; author Matt Fleming */ #include <linux/console.h> #include <linux/efi.h> #include <linux/font.h> #include <linux/io.h> #include <linux/kernel.h> #include <linux/serial_core.h> #include <linux/screen_info.h> #include <linux/string.h> #include <asm/early_ioremap.h> static const struct console *earlycon_console __initdata; static const struct font_desc *font; static u16 cur_line_y, max_line_y; static u32 efi_x_array[1024]; static u32 efi_x, efi_y; static u64 fb_base; static bool fb_wb; static void *efi_fb; /* * EFI earlycon needs to use early_memremap() to map the framebuffer. * But early_memremap() is not usable for 'earlycon=efifb keep_bootcon', * memremap() should be used instead. memremap() will be available after * paging_init() which is earlier than initcall callbacks. Thus adding this * early initcall function early_efi_map_fb() to map the whole EFI framebuffer. */ static int __init efi_earlycon_remap_fb(void) { /* bail if there is no bootconsole or it was unregistered already */ if (!earlycon_console || !console_is_registered(earlycon_console)) return 0; efi_fb = memremap(fb_base, screen_info.lfb_size, fb_wb ? MEMREMAP_WB : MEMREMAP_WC); return efi_fb ? 0 : -ENOMEM; } early_initcall(efi_earlycon_remap_fb); static int __init efi_earlycon_unmap_fb(void) { /* unmap the bootconsole fb unless keep_bootcon left it registered */ if (efi_fb && !console_is_registered(earlycon_console)) memunmap(efi_fb); return 0; } late_initcall(efi_earlycon_unmap_fb); static __ref void *efi_earlycon_map(unsigned long start, unsigned long len) { pgprot_t fb_prot; if (efi_fb) return efi_fb + start; fb_prot = fb_wb ? PAGE_KERNEL : pgprot_writecombine(PAGE_KERNEL); return early_memremap_prot(fb_base + start, len, pgprot_val(fb_prot)); } static __ref void efi_earlycon_unmap(void *addr, unsigned long len) { if (efi_fb) return; early_memunmap(addr, len); } static void efi_earlycon_clear_scanline(unsigned int y) { unsigned long *dst; u16 len; len = screen_info.lfb_linelength; dst = efi_earlycon_map(y*len, len); if (!dst) return; memset(dst, 0, len); efi_earlycon_unmap(dst, len); } static void efi_earlycon_scroll_up(void) { unsigned long *dst, *src; u16 maxlen = 0; u16 len; u32 i, height; /* Find the cached maximum x coordinate */ for (i = 0; i < max_line_y; i++) { if (efi_x_array[i] > maxlen) maxlen = efi_x_array[i]; } maxlen *= 4; len = screen_info.lfb_linelength; height = screen_info.lfb_height; for (i = 0; i < height - font->height; i++) { dst = efi_earlycon_map(i*len, len); if (!dst) return; src = efi_earlycon_map((i + font->height) * len, len); if (!src) { efi_earlycon_unmap(dst, len); return; } memmove(dst, src, maxlen); efi_earlycon_unmap(src, len); efi_earlycon_unmap(dst, len); } } static void efi_earlycon_write_char(u32 *dst, unsigned char c, unsigned int h) { const u32 color_black = 0x00000000; const u32 color_white = 0x00ffffff; const u8 *src; int m, n, bytes; u8 x; bytes = BITS_TO_BYTES(font->width); src = font->data + c * font->height * bytes + h * bytes; for (m = 0; m < font->width; m++) { n = m % 8; x = *(src + m / 8); if ((x >> (7 - n)) & 1) *dst = color_white; else *dst = color_black; dst++; } } static void efi_earlycon_write(struct console *con, const char *str, unsigned int num) { struct screen_info *si; u32 cur_efi_x = efi_x; unsigned int len; const char *s; void *dst; si = &screen_info; len = si->lfb_linelength; while (num) { unsigned int linemax = (si->lfb_width - efi_x) / font->width; unsigned int h, count; count = strnchrnul(str, num, '\n') - str; if (count > linemax) count = linemax; for (h = 0; h < font->height; h++) { unsigned int n, x; dst = efi_earlycon_map((efi_y + h) * len, len); if (!dst) return; s = str; n = count; x = efi_x; while (n-- > 0) { efi_earlycon_write_char(dst + x*4, *s, h); x += font->width; s++; } efi_earlycon_unmap(dst, len); } num -= count; efi_x += count * font->width; str += count; if (num > 0 && *s == '\n') { cur_efi_x = efi_x; efi_x = 0; efi_y += font->height; str++; num--; } if (efi_x + font->width > si->lfb_width) { cur_efi_x = efi_x; efi_x = 0; efi_y += font->height; } if (efi_y + font->height > si->lfb_height) { u32 i; efi_x_array[cur_line_y] = cur_efi_x; cur_line_y = (cur_line_y + 1) % max_line_y; efi_y -= font->height; efi_earlycon_scroll_up(); for (i = 0; i < font->height; i++) efi_earlycon_clear_scanline(efi_y + i); } } } static bool __initdata fb_probed; void __init efi_earlycon_reprobe(void) { if (fb_probed) setup_earlycon("efifb"); } static int __init efi_earlycon_setup(struct earlycon_device *device, const char *opt) { struct screen_info *si; u16 xres, yres; u32 i; fb_wb = opt && !strcmp(opt, "ram"); if (screen_info.orig_video_isVGA != VIDEO_TYPE_EFI) { fb_probed = true; return -ENODEV; } fb_base = screen_info.lfb_base; if (screen_info.capabilities & VIDEO_CAPABILITY_64BIT_BASE) fb_base |= (u64)screen_info.ext_lfb_base << 32; si = &screen_info; xres = si->lfb_width; yres = si->lfb_height; /* * efi_earlycon_write_char() implicitly assumes a framebuffer with * 32 bits per pixel. */ if (si->lfb_depth != 32) return -ENODEV; font = get_default_font(xres, yres, -1, -1); if (!font) return -ENODEV; /* Fill the cache with maximum possible value of x coordinate */ memset32(efi_x_array, rounddown(xres, font->width), ARRAY_SIZE(efi_x_array)); efi_y = rounddown(yres, font->height); /* Make sure we have cache for the x coordinate for the full screen */ max_line_y = efi_y / font->height + 1; cur_line_y = 0; efi_y -= font->height; for (i = 0; i < (yres - efi_y) / font->height; i++) efi_earlycon_scroll_up(); device->con->write = efi_earlycon_write; earlycon_console = device->con; return 0; } EARLYCON_DECLARE(efifb, efi_earlycon_setup);
linux-master
drivers/firmware/efi/earlycon.c
// SPDX-License-Identifier: GPL-2.0-only /* * UEFI Common Platform Error Record (CPER) support for CXL Section. * * Copyright (C) 2022 Advanced Micro Devices, Inc. * * Author: Smita Koralahalli <[email protected]> */ #include <linux/cper.h> #include "cper_cxl.h" #define PROT_ERR_VALID_AGENT_TYPE BIT_ULL(0) #define PROT_ERR_VALID_AGENT_ADDRESS BIT_ULL(1) #define PROT_ERR_VALID_DEVICE_ID BIT_ULL(2) #define PROT_ERR_VALID_SERIAL_NUMBER BIT_ULL(3) #define PROT_ERR_VALID_CAPABILITY BIT_ULL(4) #define PROT_ERR_VALID_DVSEC BIT_ULL(5) #define PROT_ERR_VALID_ERROR_LOG BIT_ULL(6) /* CXL RAS Capability Structure, CXL v3.0 sec 8.2.4.16 */ struct cxl_ras_capability_regs { u32 uncor_status; u32 uncor_mask; u32 uncor_severity; u32 cor_status; u32 cor_mask; u32 cap_control; u32 header_log[16]; }; static const char * const prot_err_agent_type_strs[] = { "Restricted CXL Device", "Restricted CXL Host Downstream Port", "CXL Device", "CXL Logical Device", "CXL Fabric Manager managed Logical Device", "CXL Root Port", "CXL Downstream Switch Port", "CXL Upstream Switch Port", }; /* * The layout of the enumeration and the values matches CXL Agent Type * field in the UEFI 2.10 Section N.2.13, */ enum { RCD, /* Restricted CXL Device */ RCH_DP, /* Restricted CXL Host Downstream Port */ DEVICE, /* CXL Device */ LD, /* CXL Logical Device */ FMLD, /* CXL Fabric Manager managed Logical Device */ RP, /* CXL Root Port */ DSP, /* CXL Downstream Switch Port */ USP, /* CXL Upstream Switch Port */ }; void cper_print_prot_err(const char *pfx, const struct cper_sec_prot_err *prot_err) { if (prot_err->valid_bits & PROT_ERR_VALID_AGENT_TYPE) pr_info("%s agent_type: %d, %s\n", pfx, prot_err->agent_type, prot_err->agent_type < ARRAY_SIZE(prot_err_agent_type_strs) ? prot_err_agent_type_strs[prot_err->agent_type] : "unknown"); if (prot_err->valid_bits & PROT_ERR_VALID_AGENT_ADDRESS) { switch (prot_err->agent_type) { /* * According to UEFI 2.10 Section N.2.13, the term CXL Device * is used to refer to Restricted CXL Device, CXL Device, CXL * Logical Device or a CXL Fabric Manager Managed Logical * Device. */ case RCD: case DEVICE: case LD: case FMLD: case RP: case DSP: case USP: pr_info("%s agent_address: %04x:%02x:%02x.%x\n", pfx, prot_err->agent_addr.segment, prot_err->agent_addr.bus, prot_err->agent_addr.device, prot_err->agent_addr.function); break; case RCH_DP: pr_info("%s rcrb_base_address: 0x%016llx\n", pfx, prot_err->agent_addr.rcrb_base_addr); break; default: break; } } if (prot_err->valid_bits & PROT_ERR_VALID_DEVICE_ID) { const __u8 *class_code; switch (prot_err->agent_type) { case RCD: case DEVICE: case LD: case FMLD: case RP: case DSP: case USP: pr_info("%s slot: %d\n", pfx, prot_err->device_id.slot >> CPER_PCIE_SLOT_SHIFT); pr_info("%s vendor_id: 0x%04x, device_id: 0x%04x\n", pfx, prot_err->device_id.vendor_id, prot_err->device_id.device_id); pr_info("%s sub_vendor_id: 0x%04x, sub_device_id: 0x%04x\n", pfx, prot_err->device_id.subsystem_vendor_id, prot_err->device_id.subsystem_id); class_code = prot_err->device_id.class_code; pr_info("%s class_code: %02x%02x\n", pfx, class_code[1], class_code[0]); break; default: break; } } if (prot_err->valid_bits & PROT_ERR_VALID_SERIAL_NUMBER) { switch (prot_err->agent_type) { case RCD: case DEVICE: case LD: case FMLD: pr_info("%s lower_dw: 0x%08x, upper_dw: 0x%08x\n", pfx, prot_err->dev_serial_num.lower_dw, prot_err->dev_serial_num.upper_dw); break; default: break; } } if (prot_err->valid_bits & PROT_ERR_VALID_CAPABILITY) { switch (prot_err->agent_type) { case RCD: case DEVICE: case LD: case FMLD: case RP: case DSP: case USP: print_hex_dump(pfx, "", DUMP_PREFIX_OFFSET, 16, 4, prot_err->capability, sizeof(prot_err->capability), 0); break; default: break; } } if (prot_err->valid_bits & PROT_ERR_VALID_DVSEC) { pr_info("%s DVSEC length: 0x%04x\n", pfx, prot_err->dvsec_len); pr_info("%s CXL DVSEC:\n", pfx); print_hex_dump(pfx, "", DUMP_PREFIX_OFFSET, 16, 4, (prot_err + 1), prot_err->dvsec_len, 0); } if (prot_err->valid_bits & PROT_ERR_VALID_ERROR_LOG) { size_t size = sizeof(*prot_err) + prot_err->dvsec_len; struct cxl_ras_capability_regs *cxl_ras; pr_info("%s Error log length: 0x%04x\n", pfx, prot_err->err_len); pr_info("%s CXL Error Log:\n", pfx); cxl_ras = (struct cxl_ras_capability_regs *)((long)prot_err + size); pr_info("%s cxl_ras_uncor_status: 0x%08x", pfx, cxl_ras->uncor_status); pr_info("%s cxl_ras_uncor_mask: 0x%08x\n", pfx, cxl_ras->uncor_mask); pr_info("%s cxl_ras_uncor_severity: 0x%08x\n", pfx, cxl_ras->uncor_severity); pr_info("%s cxl_ras_cor_status: 0x%08x", pfx, cxl_ras->cor_status); pr_info("%s cxl_ras_cor_mask: 0x%08x\n", pfx, cxl_ras->cor_mask); pr_info("%s cap_control: 0x%08x\n", pfx, cxl_ras->cap_control); pr_info("%s Header Log Registers:\n", pfx); print_hex_dump(pfx, "", DUMP_PREFIX_OFFSET, 16, 4, cxl_ras->header_log, sizeof(cxl_ras->header_log), 0); } }
linux-master
drivers/firmware/efi/cper_cxl.c
// SPDX-License-Identifier: GPL-2.0+ #include <linux/efi.h> #include <linux/module.h> #include <linux/pstore.h> #include <linux/slab.h> #include <linux/ucs2_string.h> MODULE_IMPORT_NS(EFIVAR); #define DUMP_NAME_LEN 66 static unsigned int record_size = 1024; module_param(record_size, uint, 0444); MODULE_PARM_DESC(record_size, "size of each pstore UEFI var (in bytes, min/default=1024)"); static bool efivars_pstore_disable = IS_ENABLED(CONFIG_EFI_VARS_PSTORE_DEFAULT_DISABLE); module_param_named(pstore_disable, efivars_pstore_disable, bool, 0644); #define PSTORE_EFI_ATTRIBUTES \ (EFI_VARIABLE_NON_VOLATILE | \ EFI_VARIABLE_BOOTSERVICE_ACCESS | \ EFI_VARIABLE_RUNTIME_ACCESS) static int efi_pstore_open(struct pstore_info *psi) { int err; err = efivar_lock(); if (err) return err; psi->data = kzalloc(record_size, GFP_KERNEL); if (!psi->data) return -ENOMEM; return 0; } static int efi_pstore_close(struct pstore_info *psi) { efivar_unlock(); kfree(psi->data); return 0; } static inline u64 generic_id(u64 timestamp, unsigned int part, int count) { return (timestamp * 100 + part) * 1000 + count; } static int efi_pstore_read_func(struct pstore_record *record, efi_char16_t *varname) { unsigned long wlen, size = record_size; char name[DUMP_NAME_LEN], data_type; efi_status_t status; int cnt; unsigned int part; u64 time; ucs2_as_utf8(name, varname, DUMP_NAME_LEN); if (sscanf(name, "dump-type%u-%u-%d-%llu-%c", &record->type, &part, &cnt, &time, &data_type) == 5) { record->id = generic_id(time, part, cnt); record->part = part; record->count = cnt; record->time.tv_sec = time; record->time.tv_nsec = 0; if (data_type == 'C') record->compressed = true; else record->compressed = false; record->ecc_notice_size = 0; } else if (sscanf(name, "dump-type%u-%u-%d-%llu", &record->type, &part, &cnt, &time) == 4) { record->id = generic_id(time, part, cnt); record->part = part; record->count = cnt; record->time.tv_sec = time; record->time.tv_nsec = 0; record->compressed = false; record->ecc_notice_size = 0; } else if (sscanf(name, "dump-type%u-%u-%llu", &record->type, &part, &time) == 3) { /* * Check if an old format, * which doesn't support holding * multiple logs, remains. */ record->id = generic_id(time, part, 0); record->part = part; record->count = 0; record->time.tv_sec = time; record->time.tv_nsec = 0; record->compressed = false; record->ecc_notice_size = 0; } else return 0; record->buf = kmalloc(size, GFP_KERNEL); if (!record->buf) return -ENOMEM; status = efivar_get_variable(varname, &LINUX_EFI_CRASH_GUID, NULL, &size, record->buf); if (status != EFI_SUCCESS) { kfree(record->buf); return -EIO; } /* * Store the name of the variable in the pstore_record priv field, so * we can reuse it later if we need to delete the EFI variable from the * variable store. */ wlen = (ucs2_strnlen(varname, DUMP_NAME_LEN) + 1) * sizeof(efi_char16_t); record->priv = kmemdup(varname, wlen, GFP_KERNEL); if (!record->priv) { kfree(record->buf); return -ENOMEM; } return size; } static ssize_t efi_pstore_read(struct pstore_record *record) { efi_char16_t *varname = record->psi->data; efi_guid_t guid = LINUX_EFI_CRASH_GUID; unsigned long varname_size; efi_status_t status; for (;;) { varname_size = 1024; /* * If this is the first read() call in the pstore enumeration, * varname will be the empty string, and the GetNextVariable() * runtime service call will return the first EFI variable in * its own enumeration order, ignoring the guid argument. * * Subsequent calls to GetNextVariable() must pass the name and * guid values returned by the previous call, which is why we * store varname in record->psi->data. Given that we only * enumerate variables with the efi-pstore GUID, there is no * need to record the guid return value. */ status = efivar_get_next_variable(&varname_size, varname, &guid); if (status == EFI_NOT_FOUND) return 0; if (status != EFI_SUCCESS) return -EIO; /* skip variables that don't concern us */ if (efi_guidcmp(guid, LINUX_EFI_CRASH_GUID)) continue; return efi_pstore_read_func(record, varname); } } static int efi_pstore_write(struct pstore_record *record) { char name[DUMP_NAME_LEN]; efi_char16_t efi_name[DUMP_NAME_LEN]; efi_status_t status; int i; record->id = generic_id(record->time.tv_sec, record->part, record->count); /* Since we copy the entire length of name, make sure it is wiped. */ memset(name, 0, sizeof(name)); snprintf(name, sizeof(name), "dump-type%u-%u-%d-%lld-%c", record->type, record->part, record->count, (long long)record->time.tv_sec, record->compressed ? 'C' : 'D'); for (i = 0; i < DUMP_NAME_LEN; i++) efi_name[i] = name[i]; if (efivar_trylock()) return -EBUSY; status = efivar_set_variable_locked(efi_name, &LINUX_EFI_CRASH_GUID, PSTORE_EFI_ATTRIBUTES, record->size, record->psi->buf, true); efivar_unlock(); return status == EFI_SUCCESS ? 0 : -EIO; }; static int efi_pstore_erase(struct pstore_record *record) { efi_status_t status; status = efivar_set_variable(record->priv, &LINUX_EFI_CRASH_GUID, PSTORE_EFI_ATTRIBUTES, 0, NULL); if (status != EFI_SUCCESS && status != EFI_NOT_FOUND) return -EIO; return 0; } static struct pstore_info efi_pstore_info = { .owner = THIS_MODULE, .name = KBUILD_MODNAME, .flags = PSTORE_FLAGS_DMESG, .open = efi_pstore_open, .close = efi_pstore_close, .read = efi_pstore_read, .write = efi_pstore_write, .erase = efi_pstore_erase, }; static __init int efivars_pstore_init(void) { if (!efivar_supports_writes()) return 0; if (efivars_pstore_disable) return 0; /* * Notice that 1024 is the minimum here to prevent issues with * decompression algorithms that were spotted during tests; * even in the case of not using compression, smaller values would * just pollute more the pstore FS with many small collected files. */ if (record_size < 1024) record_size = 1024; efi_pstore_info.buf = kmalloc(record_size, GFP_KERNEL); if (!efi_pstore_info.buf) return -ENOMEM; efi_pstore_info.bufsize = record_size; if (pstore_register(&efi_pstore_info)) { kfree(efi_pstore_info.buf); efi_pstore_info.buf = NULL; efi_pstore_info.bufsize = 0; } return 0; } static __exit void efivars_pstore_exit(void) { if (!efi_pstore_info.bufsize) return; pstore_unregister(&efi_pstore_info); kfree(efi_pstore_info.buf); efi_pstore_info.buf = NULL; efi_pstore_info.bufsize = 0; } module_init(efivars_pstore_init); module_exit(efivars_pstore_exit); MODULE_DESCRIPTION("EFI variable backend for pstore"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:efivars");
linux-master
drivers/firmware/efi/efi-pstore.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright 2012 Intel Corporation * Author: Josh Triplett <[email protected]> * * Based on the bgrt driver: * Copyright 2012 Red Hat, Inc <[email protected]> * Author: Matthew Garrett */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/init.h> #include <linux/acpi.h> #include <linux/efi.h> #include <linux/efi-bgrt.h> struct acpi_table_bgrt bgrt_tab; size_t bgrt_image_size; struct bmp_header { u16 id; u32 size; } __packed; void __init efi_bgrt_init(struct acpi_table_header *table) { void *image; struct bmp_header bmp_header; struct acpi_table_bgrt *bgrt = &bgrt_tab; if (acpi_disabled) return; if (!efi_enabled(EFI_MEMMAP)) return; if (table->length < sizeof(bgrt_tab)) { pr_notice("Ignoring BGRT: invalid length %u (expected %zu)\n", table->length, sizeof(bgrt_tab)); return; } *bgrt = *(struct acpi_table_bgrt *)table; /* * Only version 1 is defined but some older laptops (seen on Lenovo * Ivy Bridge models) have a correct version 1 BGRT table with the * version set to 0, so we accept version 0 and 1. */ if (bgrt->version > 1) { pr_notice("Ignoring BGRT: invalid version %u (expected 1)\n", bgrt->version); goto out; } if (bgrt->image_type != 0) { pr_notice("Ignoring BGRT: invalid image type %u (expected 0)\n", bgrt->image_type); goto out; } if (!bgrt->image_address) { pr_notice("Ignoring BGRT: null image address\n"); goto out; } if (efi_mem_type(bgrt->image_address) != EFI_BOOT_SERVICES_DATA) { pr_notice("Ignoring BGRT: invalid image address\n"); goto out; } image = early_memremap(bgrt->image_address, sizeof(bmp_header)); if (!image) { pr_notice("Ignoring BGRT: failed to map image header memory\n"); goto out; } memcpy(&bmp_header, image, sizeof(bmp_header)); early_memunmap(image, sizeof(bmp_header)); if (bmp_header.id != 0x4d42) { pr_notice("Ignoring BGRT: Incorrect BMP magic number 0x%x (expected 0x4d42)\n", bmp_header.id); goto out; } bgrt_image_size = bmp_header.size; efi_mem_reserve(bgrt->image_address, bgrt_image_size); return; out: memset(bgrt, 0, sizeof(bgrt_tab)); }
linux-master
drivers/firmware/efi/efi-bgrt.c
// SPDX-License-Identifier: GPL-2.0+ /* * EFI Test Driver for Runtime Services * * Copyright(C) 2012-2016 Canonical Ltd. * * This driver exports EFI runtime services interfaces into userspace, which * allow to use and test UEFI runtime services provided by firmware. * */ #include <linux/miscdevice.h> #include <linux/module.h> #include <linux/init.h> #include <linux/proc_fs.h> #include <linux/efi.h> #include <linux/security.h> #include <linux/slab.h> #include <linux/uaccess.h> #include "efi_test.h" MODULE_AUTHOR("Ivan Hu <[email protected]>"); MODULE_DESCRIPTION("EFI Test Driver"); MODULE_LICENSE("GPL"); /* * Count the bytes in 'str', including the terminating NULL. * * Note this function returns the number of *bytes*, not the number of * ucs2 characters. */ static inline size_t user_ucs2_strsize(efi_char16_t __user *str) { efi_char16_t *s = str, c; size_t len; if (!str) return 0; /* Include terminating NULL */ len = sizeof(efi_char16_t); if (get_user(c, s++)) { /* Can't read userspace memory for size */ return 0; } while (c != 0) { if (get_user(c, s++)) { /* Can't read userspace memory for size */ return 0; } len += sizeof(efi_char16_t); } return len; } /* * Allocate a buffer and copy a ucs2 string from user space into it. */ static inline int copy_ucs2_from_user_len(efi_char16_t **dst, efi_char16_t __user *src, size_t len) { efi_char16_t *buf; if (!src) { *dst = NULL; return 0; } buf = memdup_user(src, len); if (IS_ERR(buf)) { *dst = NULL; return PTR_ERR(buf); } *dst = buf; return 0; } /* * Count the bytes in 'str', including the terminating NULL. * * Just a wrap for user_ucs2_strsize */ static inline int get_ucs2_strsize_from_user(efi_char16_t __user *src, size_t *len) { *len = user_ucs2_strsize(src); if (*len == 0) return -EFAULT; return 0; } /* * Calculate the required buffer allocation size and copy a ucs2 string * from user space into it. * * This function differs from copy_ucs2_from_user_len() because it * calculates the size of the buffer to allocate by taking the length of * the string 'src'. * * If a non-zero value is returned, the caller MUST NOT access 'dst'. * * It is the caller's responsibility to free 'dst'. */ static inline int copy_ucs2_from_user(efi_char16_t **dst, efi_char16_t __user *src) { size_t len; len = user_ucs2_strsize(src); if (len == 0) return -EFAULT; return copy_ucs2_from_user_len(dst, src, len); } /* * Copy a ucs2 string to a user buffer. * * This function is a simple wrapper around copy_to_user() that does * nothing if 'src' is NULL, which is useful for reducing the amount of * NULL checking the caller has to do. * * 'len' specifies the number of bytes to copy. */ static inline int copy_ucs2_to_user_len(efi_char16_t __user *dst, efi_char16_t *src, size_t len) { if (!src) return 0; return copy_to_user(dst, src, len); } static long efi_runtime_get_variable(unsigned long arg) { struct efi_getvariable __user *getvariable_user; struct efi_getvariable getvariable; unsigned long datasize = 0, prev_datasize, *dz; efi_guid_t vendor_guid, *vd = NULL; efi_status_t status; efi_char16_t *name = NULL; u32 attr, *at; void *data = NULL; int rv = 0; getvariable_user = (struct efi_getvariable __user *)arg; if (copy_from_user(&getvariable, getvariable_user, sizeof(getvariable))) return -EFAULT; if (getvariable.data_size && get_user(datasize, getvariable.data_size)) return -EFAULT; if (getvariable.vendor_guid) { if (copy_from_user(&vendor_guid, getvariable.vendor_guid, sizeof(vendor_guid))) return -EFAULT; vd = &vendor_guid; } if (getvariable.variable_name) { rv = copy_ucs2_from_user(&name, getvariable.variable_name); if (rv) return rv; } at = getvariable.attributes ? &attr : NULL; dz = getvariable.data_size ? &datasize : NULL; if (getvariable.data_size && getvariable.data) { data = kmalloc(datasize, GFP_KERNEL); if (!data) { kfree(name); return -ENOMEM; } } prev_datasize = datasize; status = efi.get_variable(name, vd, at, dz, data); kfree(name); if (put_user(status, getvariable.status)) { rv = -EFAULT; goto out; } if (status != EFI_SUCCESS) { if (status == EFI_BUFFER_TOO_SMALL) { if (dz && put_user(datasize, getvariable.data_size)) { rv = -EFAULT; goto out; } } rv = -EINVAL; goto out; } if (prev_datasize < datasize) { rv = -EINVAL; goto out; } if (data) { if (copy_to_user(getvariable.data, data, datasize)) { rv = -EFAULT; goto out; } } if (at && put_user(attr, getvariable.attributes)) { rv = -EFAULT; goto out; } if (dz && put_user(datasize, getvariable.data_size)) rv = -EFAULT; out: kfree(data); return rv; } static long efi_runtime_set_variable(unsigned long arg) { struct efi_setvariable __user *setvariable_user; struct efi_setvariable setvariable; efi_guid_t vendor_guid; efi_status_t status; efi_char16_t *name = NULL; void *data; int rv = 0; setvariable_user = (struct efi_setvariable __user *)arg; if (copy_from_user(&setvariable, setvariable_user, sizeof(setvariable))) return -EFAULT; if (copy_from_user(&vendor_guid, setvariable.vendor_guid, sizeof(vendor_guid))) return -EFAULT; if (setvariable.variable_name) { rv = copy_ucs2_from_user(&name, setvariable.variable_name); if (rv) return rv; } data = memdup_user(setvariable.data, setvariable.data_size); if (IS_ERR(data)) { kfree(name); return PTR_ERR(data); } status = efi.set_variable(name, &vendor_guid, setvariable.attributes, setvariable.data_size, data); if (put_user(status, setvariable.status)) { rv = -EFAULT; goto out; } rv = status == EFI_SUCCESS ? 0 : -EINVAL; out: kfree(data); kfree(name); return rv; } static long efi_runtime_get_time(unsigned long arg) { struct efi_gettime __user *gettime_user; struct efi_gettime gettime; efi_status_t status; efi_time_cap_t cap; efi_time_t efi_time; gettime_user = (struct efi_gettime __user *)arg; if (copy_from_user(&gettime, gettime_user, sizeof(gettime))) return -EFAULT; status = efi.get_time(gettime.time ? &efi_time : NULL, gettime.capabilities ? &cap : NULL); if (put_user(status, gettime.status)) return -EFAULT; if (status != EFI_SUCCESS) return -EINVAL; if (gettime.capabilities) { efi_time_cap_t __user *cap_local; cap_local = (efi_time_cap_t *)gettime.capabilities; if (put_user(cap.resolution, &(cap_local->resolution)) || put_user(cap.accuracy, &(cap_local->accuracy)) || put_user(cap.sets_to_zero, &(cap_local->sets_to_zero))) return -EFAULT; } if (gettime.time) { if (copy_to_user(gettime.time, &efi_time, sizeof(efi_time_t))) return -EFAULT; } return 0; } static long efi_runtime_set_time(unsigned long arg) { struct efi_settime __user *settime_user; struct efi_settime settime; efi_status_t status; efi_time_t efi_time; settime_user = (struct efi_settime __user *)arg; if (copy_from_user(&settime, settime_user, sizeof(settime))) return -EFAULT; if (copy_from_user(&efi_time, settime.time, sizeof(efi_time_t))) return -EFAULT; status = efi.set_time(&efi_time); if (put_user(status, settime.status)) return -EFAULT; return status == EFI_SUCCESS ? 0 : -EINVAL; } static long efi_runtime_get_waketime(unsigned long arg) { struct efi_getwakeuptime __user *getwakeuptime_user; struct efi_getwakeuptime getwakeuptime; efi_bool_t enabled, pending; efi_status_t status; efi_time_t efi_time; getwakeuptime_user = (struct efi_getwakeuptime __user *)arg; if (copy_from_user(&getwakeuptime, getwakeuptime_user, sizeof(getwakeuptime))) return -EFAULT; status = efi.get_wakeup_time( getwakeuptime.enabled ? (efi_bool_t *)&enabled : NULL, getwakeuptime.pending ? (efi_bool_t *)&pending : NULL, getwakeuptime.time ? &efi_time : NULL); if (put_user(status, getwakeuptime.status)) return -EFAULT; if (status != EFI_SUCCESS) return -EINVAL; if (getwakeuptime.enabled && put_user(enabled, getwakeuptime.enabled)) return -EFAULT; if (getwakeuptime.time) { if (copy_to_user(getwakeuptime.time, &efi_time, sizeof(efi_time_t))) return -EFAULT; } return 0; } static long efi_runtime_set_waketime(unsigned long arg) { struct efi_setwakeuptime __user *setwakeuptime_user; struct efi_setwakeuptime setwakeuptime; efi_bool_t enabled; efi_status_t status; efi_time_t efi_time; setwakeuptime_user = (struct efi_setwakeuptime __user *)arg; if (copy_from_user(&setwakeuptime, setwakeuptime_user, sizeof(setwakeuptime))) return -EFAULT; enabled = setwakeuptime.enabled; if (setwakeuptime.time) { if (copy_from_user(&efi_time, setwakeuptime.time, sizeof(efi_time_t))) return -EFAULT; status = efi.set_wakeup_time(enabled, &efi_time); } else status = efi.set_wakeup_time(enabled, NULL); if (put_user(status, setwakeuptime.status)) return -EFAULT; return status == EFI_SUCCESS ? 0 : -EINVAL; } static long efi_runtime_get_nextvariablename(unsigned long arg) { struct efi_getnextvariablename __user *getnextvariablename_user; struct efi_getnextvariablename getnextvariablename; unsigned long name_size, prev_name_size = 0, *ns = NULL; efi_status_t status; efi_guid_t *vd = NULL; efi_guid_t vendor_guid; efi_char16_t *name = NULL; int rv = 0; getnextvariablename_user = (struct efi_getnextvariablename __user *)arg; if (copy_from_user(&getnextvariablename, getnextvariablename_user, sizeof(getnextvariablename))) return -EFAULT; if (getnextvariablename.variable_name_size) { if (get_user(name_size, getnextvariablename.variable_name_size)) return -EFAULT; ns = &name_size; prev_name_size = name_size; } if (getnextvariablename.vendor_guid) { if (copy_from_user(&vendor_guid, getnextvariablename.vendor_guid, sizeof(vendor_guid))) return -EFAULT; vd = &vendor_guid; } if (getnextvariablename.variable_name) { size_t name_string_size = 0; rv = get_ucs2_strsize_from_user( getnextvariablename.variable_name, &name_string_size); if (rv) return rv; /* * The name_size may be smaller than the real buffer size where * variable name located in some use cases. The most typical * case is passing a 0 to get the required buffer size for the * 1st time call. So we need to copy the content from user * space for at least the string size of variable name, or else * the name passed to UEFI may not be terminated as we expected. */ rv = copy_ucs2_from_user_len(&name, getnextvariablename.variable_name, prev_name_size > name_string_size ? prev_name_size : name_string_size); if (rv) return rv; } status = efi.get_next_variable(ns, name, vd); if (put_user(status, getnextvariablename.status)) { rv = -EFAULT; goto out; } if (status != EFI_SUCCESS) { if (status == EFI_BUFFER_TOO_SMALL) { if (ns && put_user(*ns, getnextvariablename.variable_name_size)) { rv = -EFAULT; goto out; } } rv = -EINVAL; goto out; } if (name) { if (copy_ucs2_to_user_len(getnextvariablename.variable_name, name, prev_name_size)) { rv = -EFAULT; goto out; } } if (ns) { if (put_user(*ns, getnextvariablename.variable_name_size)) { rv = -EFAULT; goto out; } } if (vd) { if (copy_to_user(getnextvariablename.vendor_guid, vd, sizeof(efi_guid_t))) rv = -EFAULT; } out: kfree(name); return rv; } static long efi_runtime_get_nexthighmonocount(unsigned long arg) { struct efi_getnexthighmonotoniccount __user *getnexthighmonocount_user; struct efi_getnexthighmonotoniccount getnexthighmonocount; efi_status_t status; u32 count; getnexthighmonocount_user = (struct efi_getnexthighmonotoniccount __user *)arg; if (copy_from_user(&getnexthighmonocount, getnexthighmonocount_user, sizeof(getnexthighmonocount))) return -EFAULT; status = efi.get_next_high_mono_count( getnexthighmonocount.high_count ? &count : NULL); if (put_user(status, getnexthighmonocount.status)) return -EFAULT; if (status != EFI_SUCCESS) return -EINVAL; if (getnexthighmonocount.high_count && put_user(count, getnexthighmonocount.high_count)) return -EFAULT; return 0; } static long efi_runtime_reset_system(unsigned long arg) { struct efi_resetsystem __user *resetsystem_user; struct efi_resetsystem resetsystem; void *data = NULL; resetsystem_user = (struct efi_resetsystem __user *)arg; if (copy_from_user(&resetsystem, resetsystem_user, sizeof(resetsystem))) return -EFAULT; if (resetsystem.data_size != 0) { data = memdup_user((void *)resetsystem.data, resetsystem.data_size); if (IS_ERR(data)) return PTR_ERR(data); } efi.reset_system(resetsystem.reset_type, resetsystem.status, resetsystem.data_size, (efi_char16_t *)data); kfree(data); return 0; } static long efi_runtime_query_variableinfo(unsigned long arg) { struct efi_queryvariableinfo __user *queryvariableinfo_user; struct efi_queryvariableinfo queryvariableinfo; efi_status_t status; u64 max_storage, remaining, max_size; queryvariableinfo_user = (struct efi_queryvariableinfo __user *)arg; if (copy_from_user(&queryvariableinfo, queryvariableinfo_user, sizeof(queryvariableinfo))) return -EFAULT; status = efi.query_variable_info(queryvariableinfo.attributes, &max_storage, &remaining, &max_size); if (put_user(status, queryvariableinfo.status)) return -EFAULT; if (status != EFI_SUCCESS) return -EINVAL; if (put_user(max_storage, queryvariableinfo.maximum_variable_storage_size)) return -EFAULT; if (put_user(remaining, queryvariableinfo.remaining_variable_storage_size)) return -EFAULT; if (put_user(max_size, queryvariableinfo.maximum_variable_size)) return -EFAULT; return 0; } static long efi_runtime_query_capsulecaps(unsigned long arg) { struct efi_querycapsulecapabilities __user *qcaps_user; struct efi_querycapsulecapabilities qcaps; efi_capsule_header_t *capsules; efi_status_t status; u64 max_size; int i, reset_type; int rv = 0; qcaps_user = (struct efi_querycapsulecapabilities __user *)arg; if (copy_from_user(&qcaps, qcaps_user, sizeof(qcaps))) return -EFAULT; if (qcaps.capsule_count == ULONG_MAX) return -EINVAL; capsules = kcalloc(qcaps.capsule_count + 1, sizeof(efi_capsule_header_t), GFP_KERNEL); if (!capsules) return -ENOMEM; for (i = 0; i < qcaps.capsule_count; i++) { efi_capsule_header_t *c; /* * We cannot dereference qcaps.capsule_header_array directly to * obtain the address of the capsule as it resides in the * user space */ if (get_user(c, qcaps.capsule_header_array + i)) { rv = -EFAULT; goto out; } if (copy_from_user(&capsules[i], c, sizeof(efi_capsule_header_t))) { rv = -EFAULT; goto out; } } qcaps.capsule_header_array = &capsules; status = efi.query_capsule_caps((efi_capsule_header_t **) qcaps.capsule_header_array, qcaps.capsule_count, &max_size, &reset_type); if (put_user(status, qcaps.status)) { rv = -EFAULT; goto out; } if (status != EFI_SUCCESS) { rv = -EINVAL; goto out; } if (put_user(max_size, qcaps.maximum_capsule_size)) { rv = -EFAULT; goto out; } if (put_user(reset_type, qcaps.reset_type)) rv = -EFAULT; out: kfree(capsules); return rv; } static long efi_runtime_get_supported_mask(unsigned long arg) { unsigned int __user *supported_mask; int rv = 0; supported_mask = (unsigned int *)arg; if (put_user(efi.runtime_supported_mask, supported_mask)) rv = -EFAULT; return rv; } static long efi_test_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { switch (cmd) { case EFI_RUNTIME_GET_VARIABLE: return efi_runtime_get_variable(arg); case EFI_RUNTIME_SET_VARIABLE: return efi_runtime_set_variable(arg); case EFI_RUNTIME_GET_TIME: return efi_runtime_get_time(arg); case EFI_RUNTIME_SET_TIME: return efi_runtime_set_time(arg); case EFI_RUNTIME_GET_WAKETIME: return efi_runtime_get_waketime(arg); case EFI_RUNTIME_SET_WAKETIME: return efi_runtime_set_waketime(arg); case EFI_RUNTIME_GET_NEXTVARIABLENAME: return efi_runtime_get_nextvariablename(arg); case EFI_RUNTIME_GET_NEXTHIGHMONOTONICCOUNT: return efi_runtime_get_nexthighmonocount(arg); case EFI_RUNTIME_QUERY_VARIABLEINFO: return efi_runtime_query_variableinfo(arg); case EFI_RUNTIME_QUERY_CAPSULECAPABILITIES: return efi_runtime_query_capsulecaps(arg); case EFI_RUNTIME_RESET_SYSTEM: return efi_runtime_reset_system(arg); case EFI_RUNTIME_GET_SUPPORTED_MASK: return efi_runtime_get_supported_mask(arg); } return -ENOTTY; } static int efi_test_open(struct inode *inode, struct file *file) { int ret = security_locked_down(LOCKDOWN_EFI_TEST); if (ret) return ret; if (!capable(CAP_SYS_ADMIN)) return -EACCES; /* * nothing special to do here * We do accept multiple open files at the same time as we * synchronize on the per call operation. */ return 0; } static int efi_test_close(struct inode *inode, struct file *file) { return 0; } /* * The various file operations we support. */ static const struct file_operations efi_test_fops = { .owner = THIS_MODULE, .unlocked_ioctl = efi_test_ioctl, .open = efi_test_open, .release = efi_test_close, .llseek = no_llseek, }; static struct miscdevice efi_test_dev = { MISC_DYNAMIC_MINOR, "efi_test", &efi_test_fops }; static int __init efi_test_init(void) { int ret; ret = misc_register(&efi_test_dev); if (ret) { pr_err("efi_test: can't misc_register on minor=%d\n", MISC_DYNAMIC_MINOR); return ret; } return 0; } static void __exit efi_test_exit(void) { misc_deregister(&efi_test_dev); } module_init(efi_test_init); module_exit(efi_test_exit);
linux-master
drivers/firmware/efi/test/efi_test.c
// SPDX-License-Identifier: GPL-2.0-only /* ----------------------------------------------------------------------- * * Copyright 2011 Intel Corporation; author Matt Fleming * * ----------------------------------------------------------------------- */ #include <linux/efi.h> #include <linux/pci.h> #include <linux/stddef.h> #include <asm/efi.h> #include <asm/e820/types.h> #include <asm/setup.h> #include <asm/desc.h> #include <asm/boot.h> #include <asm/kaslr.h> #include <asm/sev.h> #include "efistub.h" #include "x86-stub.h" const efi_system_table_t *efi_system_table; const efi_dxe_services_table_t *efi_dxe_table; static efi_loaded_image_t *image = NULL; static efi_memory_attribute_protocol_t *memattr; typedef union sev_memory_acceptance_protocol sev_memory_acceptance_protocol_t; union sev_memory_acceptance_protocol { struct { efi_status_t (__efiapi * allow_unaccepted_memory)( sev_memory_acceptance_protocol_t *); }; struct { u32 allow_unaccepted_memory; } mixed_mode; }; static efi_status_t preserve_pci_rom_image(efi_pci_io_protocol_t *pci, struct pci_setup_rom **__rom) { struct pci_setup_rom *rom = NULL; efi_status_t status; unsigned long size; uint64_t romsize; void *romimage; /* * Some firmware images contain EFI function pointers at the place where * the romimage and romsize fields are supposed to be. Typically the EFI * code is mapped at high addresses, translating to an unrealistically * large romsize. The UEFI spec limits the size of option ROMs to 16 * MiB so we reject any ROMs over 16 MiB in size to catch this. */ romimage = efi_table_attr(pci, romimage); romsize = efi_table_attr(pci, romsize); if (!romimage || !romsize || romsize > SZ_16M) return EFI_INVALID_PARAMETER; size = romsize + sizeof(*rom); status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, size, (void **)&rom); if (status != EFI_SUCCESS) { efi_err("Failed to allocate memory for 'rom'\n"); return status; } memset(rom, 0, sizeof(*rom)); rom->data.type = SETUP_PCI; rom->data.len = size - sizeof(struct setup_data); rom->data.next = 0; rom->pcilen = romsize; *__rom = rom; status = efi_call_proto(pci, pci.read, EfiPciIoWidthUint16, PCI_VENDOR_ID, 1, &rom->vendor); if (status != EFI_SUCCESS) { efi_err("Failed to read rom->vendor\n"); goto free_struct; } status = efi_call_proto(pci, pci.read, EfiPciIoWidthUint16, PCI_DEVICE_ID, 1, &rom->devid); if (status != EFI_SUCCESS) { efi_err("Failed to read rom->devid\n"); goto free_struct; } status = efi_call_proto(pci, get_location, &rom->segment, &rom->bus, &rom->device, &rom->function); if (status != EFI_SUCCESS) goto free_struct; memcpy(rom->romdata, romimage, romsize); return status; free_struct: efi_bs_call(free_pool, rom); return status; } /* * There's no way to return an informative status from this function, * because any analysis (and printing of error messages) needs to be * done directly at the EFI function call-site. * * For example, EFI_INVALID_PARAMETER could indicate a bug or maybe we * just didn't find any PCI devices, but there's no way to tell outside * the context of the call. */ static void setup_efi_pci(struct boot_params *params) { efi_status_t status; void **pci_handle = NULL; efi_guid_t pci_proto = EFI_PCI_IO_PROTOCOL_GUID; unsigned long size = 0; struct setup_data *data; efi_handle_t h; int i; status = efi_bs_call(locate_handle, EFI_LOCATE_BY_PROTOCOL, &pci_proto, NULL, &size, pci_handle); if (status == EFI_BUFFER_TOO_SMALL) { status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, size, (void **)&pci_handle); if (status != EFI_SUCCESS) { efi_err("Failed to allocate memory for 'pci_handle'\n"); return; } status = efi_bs_call(locate_handle, EFI_LOCATE_BY_PROTOCOL, &pci_proto, NULL, &size, pci_handle); } if (status != EFI_SUCCESS) goto free_handle; data = (struct setup_data *)(unsigned long)params->hdr.setup_data; while (data && data->next) data = (struct setup_data *)(unsigned long)data->next; for_each_efi_handle(h, pci_handle, size, i) { efi_pci_io_protocol_t *pci = NULL; struct pci_setup_rom *rom; status = efi_bs_call(handle_protocol, h, &pci_proto, (void **)&pci); if (status != EFI_SUCCESS || !pci) continue; status = preserve_pci_rom_image(pci, &rom); if (status != EFI_SUCCESS) continue; if (data) data->next = (unsigned long)rom; else params->hdr.setup_data = (unsigned long)rom; data = (struct setup_data *)rom; } free_handle: efi_bs_call(free_pool, pci_handle); } static void retrieve_apple_device_properties(struct boot_params *boot_params) { efi_guid_t guid = APPLE_PROPERTIES_PROTOCOL_GUID; struct setup_data *data, *new; efi_status_t status; u32 size = 0; apple_properties_protocol_t *p; status = efi_bs_call(locate_protocol, &guid, NULL, (void **)&p); if (status != EFI_SUCCESS) return; if (efi_table_attr(p, version) != 0x10000) { efi_err("Unsupported properties proto version\n"); return; } efi_call_proto(p, get_all, NULL, &size); if (!size) return; do { status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, size + sizeof(struct setup_data), (void **)&new); if (status != EFI_SUCCESS) { efi_err("Failed to allocate memory for 'properties'\n"); return; } status = efi_call_proto(p, get_all, new->data, &size); if (status == EFI_BUFFER_TOO_SMALL) efi_bs_call(free_pool, new); } while (status == EFI_BUFFER_TOO_SMALL); new->type = SETUP_APPLE_PROPERTIES; new->len = size; new->next = 0; data = (struct setup_data *)(unsigned long)boot_params->hdr.setup_data; if (!data) { boot_params->hdr.setup_data = (unsigned long)new; } else { while (data->next) data = (struct setup_data *)(unsigned long)data->next; data->next = (unsigned long)new; } } void efi_adjust_memory_range_protection(unsigned long start, unsigned long size) { efi_status_t status; efi_gcd_memory_space_desc_t desc; unsigned long end, next; unsigned long rounded_start, rounded_end; unsigned long unprotect_start, unprotect_size; rounded_start = rounddown(start, EFI_PAGE_SIZE); rounded_end = roundup(start + size, EFI_PAGE_SIZE); if (memattr != NULL) { efi_call_proto(memattr, clear_memory_attributes, rounded_start, rounded_end - rounded_start, EFI_MEMORY_XP); return; } if (efi_dxe_table == NULL) return; /* * Don't modify memory region attributes, they are * already suitable, to lower the possibility to * encounter firmware bugs. */ for (end = start + size; start < end; start = next) { status = efi_dxe_call(get_memory_space_descriptor, start, &desc); if (status != EFI_SUCCESS) return; next = desc.base_address + desc.length; /* * Only system memory is suitable for trampoline/kernel image placement, * so only this type of memory needs its attributes to be modified. */ if (desc.gcd_memory_type != EfiGcdMemoryTypeSystemMemory || (desc.attributes & (EFI_MEMORY_RO | EFI_MEMORY_XP)) == 0) continue; unprotect_start = max(rounded_start, (unsigned long)desc.base_address); unprotect_size = min(rounded_end, next) - unprotect_start; status = efi_dxe_call(set_memory_space_attributes, unprotect_start, unprotect_size, EFI_MEMORY_WB); if (status != EFI_SUCCESS) { efi_warn("Unable to unprotect memory range [%08lx,%08lx]: %lx\n", unprotect_start, unprotect_start + unprotect_size, status); } } } static void setup_unaccepted_memory(void) { efi_guid_t mem_acceptance_proto = OVMF_SEV_MEMORY_ACCEPTANCE_PROTOCOL_GUID; sev_memory_acceptance_protocol_t *proto; efi_status_t status; if (!IS_ENABLED(CONFIG_UNACCEPTED_MEMORY)) return; /* * Enable unaccepted memory before calling exit boot services in order * for the UEFI to not accept all memory on EBS. */ status = efi_bs_call(locate_protocol, &mem_acceptance_proto, NULL, (void **)&proto); if (status != EFI_SUCCESS) return; status = efi_call_proto(proto, allow_unaccepted_memory); if (status != EFI_SUCCESS) efi_err("Memory acceptance protocol failed\n"); } static const efi_char16_t apple[] = L"Apple"; static void setup_quirks(struct boot_params *boot_params) { efi_char16_t *fw_vendor = (efi_char16_t *)(unsigned long) efi_table_attr(efi_system_table, fw_vendor); if (!memcmp(fw_vendor, apple, sizeof(apple))) { if (IS_ENABLED(CONFIG_APPLE_PROPERTIES)) retrieve_apple_device_properties(boot_params); } } /* * See if we have Universal Graphics Adapter (UGA) protocol */ static efi_status_t setup_uga(struct screen_info *si, efi_guid_t *uga_proto, unsigned long size) { efi_status_t status; u32 width, height; void **uga_handle = NULL; efi_uga_draw_protocol_t *uga = NULL, *first_uga; efi_handle_t handle; int i; status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, size, (void **)&uga_handle); if (status != EFI_SUCCESS) return status; status = efi_bs_call(locate_handle, EFI_LOCATE_BY_PROTOCOL, uga_proto, NULL, &size, uga_handle); if (status != EFI_SUCCESS) goto free_handle; height = 0; width = 0; first_uga = NULL; for_each_efi_handle(handle, uga_handle, size, i) { efi_guid_t pciio_proto = EFI_PCI_IO_PROTOCOL_GUID; u32 w, h, depth, refresh; void *pciio; status = efi_bs_call(handle_protocol, handle, uga_proto, (void **)&uga); if (status != EFI_SUCCESS) continue; pciio = NULL; efi_bs_call(handle_protocol, handle, &pciio_proto, &pciio); status = efi_call_proto(uga, get_mode, &w, &h, &depth, &refresh); if (status == EFI_SUCCESS && (!first_uga || pciio)) { width = w; height = h; /* * Once we've found a UGA supporting PCIIO, * don't bother looking any further. */ if (pciio) break; first_uga = uga; } } if (!width && !height) goto free_handle; /* EFI framebuffer */ si->orig_video_isVGA = VIDEO_TYPE_EFI; si->lfb_depth = 32; si->lfb_width = width; si->lfb_height = height; si->red_size = 8; si->red_pos = 16; si->green_size = 8; si->green_pos = 8; si->blue_size = 8; si->blue_pos = 0; si->rsvd_size = 8; si->rsvd_pos = 24; free_handle: efi_bs_call(free_pool, uga_handle); return status; } static void setup_graphics(struct boot_params *boot_params) { efi_guid_t graphics_proto = EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID; struct screen_info *si; efi_guid_t uga_proto = EFI_UGA_PROTOCOL_GUID; efi_status_t status; unsigned long size; void **gop_handle = NULL; void **uga_handle = NULL; si = &boot_params->screen_info; memset(si, 0, sizeof(*si)); size = 0; status = efi_bs_call(locate_handle, EFI_LOCATE_BY_PROTOCOL, &graphics_proto, NULL, &size, gop_handle); if (status == EFI_BUFFER_TOO_SMALL) status = efi_setup_gop(si, &graphics_proto, size); if (status != EFI_SUCCESS) { size = 0; status = efi_bs_call(locate_handle, EFI_LOCATE_BY_PROTOCOL, &uga_proto, NULL, &size, uga_handle); if (status == EFI_BUFFER_TOO_SMALL) setup_uga(si, &uga_proto, size); } } static void __noreturn efi_exit(efi_handle_t handle, efi_status_t status) { efi_bs_call(exit, handle, status, 0, NULL); for(;;) asm("hlt"); } void __noreturn efi_stub_entry(efi_handle_t handle, efi_system_table_t *sys_table_arg, struct boot_params *boot_params); /* * Because the x86 boot code expects to be passed a boot_params we * need to create one ourselves (usually the bootloader would create * one for us). */ efi_status_t __efiapi efi_pe_entry(efi_handle_t handle, efi_system_table_t *sys_table_arg) { struct boot_params *boot_params; struct setup_header *hdr; void *image_base; efi_guid_t proto = LOADED_IMAGE_PROTOCOL_GUID; int options_size = 0; efi_status_t status; char *cmdline_ptr; efi_system_table = sys_table_arg; /* Check if we were booted by the EFI firmware */ if (efi_system_table->hdr.signature != EFI_SYSTEM_TABLE_SIGNATURE) efi_exit(handle, EFI_INVALID_PARAMETER); status = efi_bs_call(handle_protocol, handle, &proto, (void **)&image); if (status != EFI_SUCCESS) { efi_err("Failed to get handle for LOADED_IMAGE_PROTOCOL\n"); efi_exit(handle, status); } image_base = efi_table_attr(image, image_base); status = efi_allocate_pages(sizeof(struct boot_params), (unsigned long *)&boot_params, ULONG_MAX); if (status != EFI_SUCCESS) { efi_err("Failed to allocate lowmem for boot params\n"); efi_exit(handle, status); } memset(boot_params, 0x0, sizeof(struct boot_params)); hdr = &boot_params->hdr; /* Copy the setup header from the second sector to boot_params */ memcpy(&hdr->jump, image_base + 512, sizeof(struct setup_header) - offsetof(struct setup_header, jump)); /* * Fill out some of the header fields ourselves because the * EFI firmware loader doesn't load the first sector. */ hdr->root_flags = 1; hdr->vid_mode = 0xffff; hdr->boot_flag = 0xAA55; hdr->type_of_loader = 0x21; /* Convert unicode cmdline to ascii */ cmdline_ptr = efi_convert_cmdline(image, &options_size); if (!cmdline_ptr) goto fail; efi_set_u64_split((unsigned long)cmdline_ptr, &hdr->cmd_line_ptr, &boot_params->ext_cmd_line_ptr); hdr->ramdisk_image = 0; hdr->ramdisk_size = 0; /* * Disregard any setup data that was provided by the bootloader: * setup_data could be pointing anywhere, and we have no way of * authenticating or validating the payload. */ hdr->setup_data = 0; efi_stub_entry(handle, sys_table_arg, boot_params); /* not reached */ fail: efi_free(sizeof(struct boot_params), (unsigned long)boot_params); efi_exit(handle, status); } static void add_e820ext(struct boot_params *params, struct setup_data *e820ext, u32 nr_entries) { struct setup_data *data; e820ext->type = SETUP_E820_EXT; e820ext->len = nr_entries * sizeof(struct boot_e820_entry); e820ext->next = 0; data = (struct setup_data *)(unsigned long)params->hdr.setup_data; while (data && data->next) data = (struct setup_data *)(unsigned long)data->next; if (data) data->next = (unsigned long)e820ext; else params->hdr.setup_data = (unsigned long)e820ext; } static efi_status_t setup_e820(struct boot_params *params, struct setup_data *e820ext, u32 e820ext_size) { struct boot_e820_entry *entry = params->e820_table; struct efi_info *efi = &params->efi_info; struct boot_e820_entry *prev = NULL; u32 nr_entries; u32 nr_desc; int i; nr_entries = 0; nr_desc = efi->efi_memmap_size / efi->efi_memdesc_size; for (i = 0; i < nr_desc; i++) { efi_memory_desc_t *d; unsigned int e820_type = 0; unsigned long m = efi->efi_memmap; #ifdef CONFIG_X86_64 m |= (u64)efi->efi_memmap_hi << 32; #endif d = efi_early_memdesc_ptr(m, efi->efi_memdesc_size, i); switch (d->type) { case EFI_RESERVED_TYPE: case EFI_RUNTIME_SERVICES_CODE: case EFI_RUNTIME_SERVICES_DATA: case EFI_MEMORY_MAPPED_IO: case EFI_MEMORY_MAPPED_IO_PORT_SPACE: case EFI_PAL_CODE: e820_type = E820_TYPE_RESERVED; break; case EFI_UNUSABLE_MEMORY: e820_type = E820_TYPE_UNUSABLE; break; case EFI_ACPI_RECLAIM_MEMORY: e820_type = E820_TYPE_ACPI; break; case EFI_LOADER_CODE: case EFI_LOADER_DATA: case EFI_BOOT_SERVICES_CODE: case EFI_BOOT_SERVICES_DATA: case EFI_CONVENTIONAL_MEMORY: if (efi_soft_reserve_enabled() && (d->attribute & EFI_MEMORY_SP)) e820_type = E820_TYPE_SOFT_RESERVED; else e820_type = E820_TYPE_RAM; break; case EFI_ACPI_MEMORY_NVS: e820_type = E820_TYPE_NVS; break; case EFI_PERSISTENT_MEMORY: e820_type = E820_TYPE_PMEM; break; case EFI_UNACCEPTED_MEMORY: if (!IS_ENABLED(CONFIG_UNACCEPTED_MEMORY)) { efi_warn_once( "The system has unaccepted memory, but kernel does not support it\nConsider enabling CONFIG_UNACCEPTED_MEMORY\n"); continue; } e820_type = E820_TYPE_RAM; process_unaccepted_memory(d->phys_addr, d->phys_addr + PAGE_SIZE * d->num_pages); break; default: continue; } /* Merge adjacent mappings */ if (prev && prev->type == e820_type && (prev->addr + prev->size) == d->phys_addr) { prev->size += d->num_pages << 12; continue; } if (nr_entries == ARRAY_SIZE(params->e820_table)) { u32 need = (nr_desc - i) * sizeof(struct e820_entry) + sizeof(struct setup_data); if (!e820ext || e820ext_size < need) return EFI_BUFFER_TOO_SMALL; /* boot_params map full, switch to e820 extended */ entry = (struct boot_e820_entry *)e820ext->data; } entry->addr = d->phys_addr; entry->size = d->num_pages << PAGE_SHIFT; entry->type = e820_type; prev = entry++; nr_entries++; } if (nr_entries > ARRAY_SIZE(params->e820_table)) { u32 nr_e820ext = nr_entries - ARRAY_SIZE(params->e820_table); add_e820ext(params, e820ext, nr_e820ext); nr_entries -= nr_e820ext; } params->e820_entries = (u8)nr_entries; return EFI_SUCCESS; } static efi_status_t alloc_e820ext(u32 nr_desc, struct setup_data **e820ext, u32 *e820ext_size) { efi_status_t status; unsigned long size; size = sizeof(struct setup_data) + sizeof(struct e820_entry) * nr_desc; if (*e820ext) { efi_bs_call(free_pool, *e820ext); *e820ext = NULL; *e820ext_size = 0; } status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, size, (void **)e820ext); if (status == EFI_SUCCESS) *e820ext_size = size; return status; } static efi_status_t allocate_e820(struct boot_params *params, struct setup_data **e820ext, u32 *e820ext_size) { struct efi_boot_memmap *map; efi_status_t status; __u32 nr_desc; status = efi_get_memory_map(&map, false); if (status != EFI_SUCCESS) return status; nr_desc = map->map_size / map->desc_size; if (nr_desc > ARRAY_SIZE(params->e820_table) - EFI_MMAP_NR_SLACK_SLOTS) { u32 nr_e820ext = nr_desc - ARRAY_SIZE(params->e820_table) + EFI_MMAP_NR_SLACK_SLOTS; status = alloc_e820ext(nr_e820ext, e820ext, e820ext_size); } if (IS_ENABLED(CONFIG_UNACCEPTED_MEMORY) && status == EFI_SUCCESS) status = allocate_unaccepted_bitmap(nr_desc, map); efi_bs_call(free_pool, map); return status; } struct exit_boot_struct { struct boot_params *boot_params; struct efi_info *efi; }; static efi_status_t exit_boot_func(struct efi_boot_memmap *map, void *priv) { const char *signature; struct exit_boot_struct *p = priv; signature = efi_is_64bit() ? EFI64_LOADER_SIGNATURE : EFI32_LOADER_SIGNATURE; memcpy(&p->efi->efi_loader_signature, signature, sizeof(__u32)); efi_set_u64_split((unsigned long)efi_system_table, &p->efi->efi_systab, &p->efi->efi_systab_hi); p->efi->efi_memdesc_size = map->desc_size; p->efi->efi_memdesc_version = map->desc_ver; efi_set_u64_split((unsigned long)map->map, &p->efi->efi_memmap, &p->efi->efi_memmap_hi); p->efi->efi_memmap_size = map->map_size; return EFI_SUCCESS; } static efi_status_t exit_boot(struct boot_params *boot_params, void *handle) { struct setup_data *e820ext = NULL; __u32 e820ext_size = 0; efi_status_t status; struct exit_boot_struct priv; priv.boot_params = boot_params; priv.efi = &boot_params->efi_info; status = allocate_e820(boot_params, &e820ext, &e820ext_size); if (status != EFI_SUCCESS) return status; /* Might as well exit boot services now */ status = efi_exit_boot_services(handle, &priv, exit_boot_func); if (status != EFI_SUCCESS) return status; /* Historic? */ boot_params->alt_mem_k = 32 * 1024; status = setup_e820(boot_params, e820ext, e820ext_size); if (status != EFI_SUCCESS) return status; return EFI_SUCCESS; } static bool have_unsupported_snp_features(void) { u64 unsupported; unsupported = snp_get_unsupported_features(sev_get_status()); if (unsupported) { efi_err("Unsupported SEV-SNP features detected: 0x%llx\n", unsupported); return true; } return false; } static void efi_get_seed(void *seed, int size) { efi_get_random_bytes(size, seed); /* * This only updates seed[0] when running on 32-bit, but in that case, * seed[1] is not used anyway, as there is no virtual KASLR on 32-bit. */ *(unsigned long *)seed ^= kaslr_get_random_long("EFI"); } static void error(char *str) { efi_warn("Decompression failed: %s\n", str); } static efi_status_t efi_decompress_kernel(unsigned long *kernel_entry) { unsigned long virt_addr = LOAD_PHYSICAL_ADDR; unsigned long addr, alloc_size, entry; efi_status_t status; u32 seed[2] = {}; /* determine the required size of the allocation */ alloc_size = ALIGN(max_t(unsigned long, output_len, kernel_total_size), MIN_KERNEL_ALIGN); if (IS_ENABLED(CONFIG_RANDOMIZE_BASE) && !efi_nokaslr) { u64 range = KERNEL_IMAGE_SIZE - LOAD_PHYSICAL_ADDR - kernel_total_size; efi_get_seed(seed, sizeof(seed)); virt_addr += (range * seed[1]) >> 32; virt_addr &= ~(CONFIG_PHYSICAL_ALIGN - 1); } status = efi_random_alloc(alloc_size, CONFIG_PHYSICAL_ALIGN, &addr, seed[0], EFI_LOADER_CODE, EFI_X86_KERNEL_ALLOC_LIMIT); if (status != EFI_SUCCESS) return status; entry = decompress_kernel((void *)addr, virt_addr, error); if (entry == ULONG_MAX) { efi_free(alloc_size, addr); return EFI_LOAD_ERROR; } *kernel_entry = addr + entry; efi_adjust_memory_range_protection(addr, kernel_total_size); return EFI_SUCCESS; } static void __noreturn enter_kernel(unsigned long kernel_addr, struct boot_params *boot_params) { /* enter decompressed kernel with boot_params pointer in RSI/ESI */ asm("jmp *%0"::"r"(kernel_addr), "S"(boot_params)); unreachable(); } /* * On success, this routine will jump to the relocated image directly and never * return. On failure, it will exit to the firmware via efi_exit() instead of * returning. */ void __noreturn efi_stub_entry(efi_handle_t handle, efi_system_table_t *sys_table_arg, struct boot_params *boot_params) { efi_guid_t guid = EFI_MEMORY_ATTRIBUTE_PROTOCOL_GUID; struct setup_header *hdr = &boot_params->hdr; const struct linux_efi_initrd *initrd = NULL; unsigned long kernel_entry; efi_status_t status; efi_system_table = sys_table_arg; /* Check if we were booted by the EFI firmware */ if (efi_system_table->hdr.signature != EFI_SYSTEM_TABLE_SIGNATURE) efi_exit(handle, EFI_INVALID_PARAMETER); if (have_unsupported_snp_features()) efi_exit(handle, EFI_UNSUPPORTED); if (IS_ENABLED(CONFIG_EFI_DXE_MEM_ATTRIBUTES)) { efi_dxe_table = get_efi_config_table(EFI_DXE_SERVICES_TABLE_GUID); if (efi_dxe_table && efi_dxe_table->hdr.signature != EFI_DXE_SERVICES_TABLE_SIGNATURE) { efi_warn("Ignoring DXE services table: invalid signature\n"); efi_dxe_table = NULL; } } /* grab the memory attributes protocol if it exists */ efi_bs_call(locate_protocol, &guid, NULL, (void **)&memattr); status = efi_setup_5level_paging(); if (status != EFI_SUCCESS) { efi_err("efi_setup_5level_paging() failed!\n"); goto fail; } #ifdef CONFIG_CMDLINE_BOOL status = efi_parse_options(CONFIG_CMDLINE); if (status != EFI_SUCCESS) { efi_err("Failed to parse options\n"); goto fail; } #endif if (!IS_ENABLED(CONFIG_CMDLINE_OVERRIDE)) { unsigned long cmdline_paddr = ((u64)hdr->cmd_line_ptr | ((u64)boot_params->ext_cmd_line_ptr << 32)); status = efi_parse_options((char *)cmdline_paddr); if (status != EFI_SUCCESS) { efi_err("Failed to parse options\n"); goto fail; } } status = efi_decompress_kernel(&kernel_entry); if (status != EFI_SUCCESS) { efi_err("Failed to decompress kernel\n"); goto fail; } /* * At this point, an initrd may already have been loaded by the * bootloader and passed via bootparams. We permit an initrd loaded * from the LINUX_EFI_INITRD_MEDIA_GUID device path to supersede it. * * If the device path is not present, any command-line initrd= * arguments will be processed only if image is not NULL, which will be * the case only if we were loaded via the PE entry point. */ status = efi_load_initrd(image, hdr->initrd_addr_max, ULONG_MAX, &initrd); if (status != EFI_SUCCESS) goto fail; if (initrd && initrd->size > 0) { efi_set_u64_split(initrd->base, &hdr->ramdisk_image, &boot_params->ext_ramdisk_image); efi_set_u64_split(initrd->size, &hdr->ramdisk_size, &boot_params->ext_ramdisk_size); } /* * If the boot loader gave us a value for secure_boot then we use that, * otherwise we ask the BIOS. */ if (boot_params->secure_boot == efi_secureboot_mode_unset) boot_params->secure_boot = efi_get_secureboot(); /* Ask the firmware to clear memory on unclean shutdown */ efi_enable_reset_attack_mitigation(); efi_random_get_seed(); efi_retrieve_tpm2_eventlog(); setup_graphics(boot_params); setup_efi_pci(boot_params); setup_quirks(boot_params); setup_unaccepted_memory(); status = exit_boot(boot_params, handle); if (status != EFI_SUCCESS) { efi_err("exit_boot() failed!\n"); goto fail; } /* * Call the SEV init code while still running with the firmware's * GDT/IDT, so #VC exceptions will be handled by EFI. */ sev_enable(boot_params); efi_5level_switch(); enter_kernel(kernel_entry, boot_params); fail: efi_err("efi_stub_entry() failed!\n"); efi_exit(handle, status); } #ifdef CONFIG_EFI_HANDOVER_PROTOCOL void efi_handover_entry(efi_handle_t handle, efi_system_table_t *sys_table_arg, struct boot_params *boot_params) { extern char _bss[], _ebss[]; memset(_bss, 0, _ebss - _bss); efi_stub_entry(handle, sys_table_arg, boot_params); } #ifndef CONFIG_EFI_MIXED extern __alias(efi_handover_entry) void efi32_stub_entry(efi_handle_t handle, efi_system_table_t *sys_table_arg, struct boot_params *boot_params); extern __alias(efi_handover_entry) void efi64_stub_entry(efi_handle_t handle, efi_system_table_t *sys_table_arg, struct boot_params *boot_params); #endif #endif
linux-master
drivers/firmware/efi/libstub/x86-stub.c
// SPDX-License-Identifier: GPL-2.0 /* * Secure boot handling. * * Copyright (C) 2013,2014 Linaro Limited * Roy Franz <[email protected] * Copyright (C) 2013 Red Hat, Inc. * Mark Salter <[email protected]> */ #include <linux/efi.h> #include <asm/efi.h> #include "efistub.h" /* SHIM variables */ static const efi_guid_t shim_guid = EFI_SHIM_LOCK_GUID; static const efi_char16_t shim_MokSBState_name[] = L"MokSBStateRT"; static efi_status_t get_var(efi_char16_t *name, efi_guid_t *vendor, u32 *attr, unsigned long *data_size, void *data) { return get_efi_var(name, vendor, attr, data_size, data); } /* * Determine whether we're in secure boot mode. */ enum efi_secureboot_mode efi_get_secureboot(void) { u32 attr; unsigned long size; enum efi_secureboot_mode mode; efi_status_t status; u8 moksbstate; mode = efi_get_secureboot_mode(get_var); if (mode == efi_secureboot_mode_unknown) { efi_err("Could not determine UEFI Secure Boot status.\n"); return efi_secureboot_mode_unknown; } if (mode != efi_secureboot_mode_enabled) return mode; /* * See if a user has put the shim into insecure mode. If so, and if the * variable doesn't have the non-volatile attribute set, we might as * well honor that. */ size = sizeof(moksbstate); status = get_efi_var(shim_MokSBState_name, &shim_guid, &attr, &size, &moksbstate); /* If it fails, we don't care why. Default to secure */ if (status != EFI_SUCCESS) goto secure_boot_enabled; if (!(attr & EFI_VARIABLE_NON_VOLATILE) && moksbstate == 1) return efi_secureboot_mode_disabled; secure_boot_enabled: efi_info("UEFI Secure Boot is enabled.\n"); return efi_secureboot_mode_enabled; }
linux-master
drivers/firmware/efi/libstub/secureboot.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/efi.h> #include <asm/efi.h> #include "efistub.h" /** * efi_allocate_pages_aligned() - Allocate memory pages * @size: minimum number of bytes to allocate * @addr: On return the address of the first allocated page. The first * allocated page has alignment EFI_ALLOC_ALIGN which is an * architecture dependent multiple of the page size. * @max: the address that the last allocated memory page shall not * exceed * @align: minimum alignment of the base of the allocation * * Allocate pages as EFI_LOADER_DATA. The allocated pages are aligned according * to @align, which should be >= EFI_ALLOC_ALIGN. The last allocated page will * not exceed the address given by @max. * * Return: status code */ efi_status_t efi_allocate_pages_aligned(unsigned long size, unsigned long *addr, unsigned long max, unsigned long align, int memory_type) { efi_physical_addr_t alloc_addr; efi_status_t status; int slack; max = min(max, EFI_ALLOC_LIMIT); if (align < EFI_ALLOC_ALIGN) align = EFI_ALLOC_ALIGN; alloc_addr = ALIGN_DOWN(max + 1, align) - 1; size = round_up(size, EFI_ALLOC_ALIGN); slack = align / EFI_PAGE_SIZE - 1; status = efi_bs_call(allocate_pages, EFI_ALLOCATE_MAX_ADDRESS, memory_type, size / EFI_PAGE_SIZE + slack, &alloc_addr); if (status != EFI_SUCCESS) return status; *addr = ALIGN((unsigned long)alloc_addr, align); if (slack > 0) { int l = (alloc_addr & (align - 1)) / EFI_PAGE_SIZE; if (l) { efi_bs_call(free_pages, alloc_addr, slack - l + 1); slack = l - 1; } if (slack) efi_bs_call(free_pages, *addr + size, slack); } return EFI_SUCCESS; }
linux-master
drivers/firmware/efi/libstub/alignedmem.c
// SPDX-License-Identifier: GPL-2.0 /* * TPM handling. * * Copyright (C) 2016 CoreOS, Inc * Copyright (C) 2017 Google, Inc. * Matthew Garrett <[email protected]> * Thiebaud Weksteen <[email protected]> */ #include <linux/efi.h> #include <linux/tpm_eventlog.h> #include <asm/efi.h> #include "efistub.h" #ifdef CONFIG_RESET_ATTACK_MITIGATION static const efi_char16_t efi_MemoryOverWriteRequest_name[] = L"MemoryOverwriteRequestControl"; #define MEMORY_ONLY_RESET_CONTROL_GUID \ EFI_GUID(0xe20939be, 0x32d4, 0x41be, 0xa1, 0x50, 0x89, 0x7f, 0x85, 0xd4, 0x98, 0x29) /* * Enable reboot attack mitigation. This requests that the firmware clear the * RAM on next reboot before proceeding with boot, ensuring that any secrets * are cleared. If userland has ensured that all secrets have been removed * from RAM before reboot it can simply reset this variable. */ void efi_enable_reset_attack_mitigation(void) { u8 val = 1; efi_guid_t var_guid = MEMORY_ONLY_RESET_CONTROL_GUID; efi_status_t status; unsigned long datasize = 0; status = get_efi_var(efi_MemoryOverWriteRequest_name, &var_guid, NULL, &datasize, NULL); if (status == EFI_NOT_FOUND) return; set_efi_var(efi_MemoryOverWriteRequest_name, &var_guid, EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, sizeof(val), &val); } #endif void efi_retrieve_tpm2_eventlog(void) { efi_guid_t tcg2_guid = EFI_TCG2_PROTOCOL_GUID; efi_guid_t linux_eventlog_guid = LINUX_EFI_TPM_EVENT_LOG_GUID; efi_status_t status; efi_physical_addr_t log_location = 0, log_last_entry = 0; struct linux_efi_tpm_eventlog *log_tbl = NULL; struct efi_tcg2_final_events_table *final_events_table = NULL; unsigned long first_entry_addr, last_entry_addr; size_t log_size, last_entry_size; efi_bool_t truncated; int version = EFI_TCG2_EVENT_LOG_FORMAT_TCG_2; efi_tcg2_protocol_t *tcg2_protocol = NULL; int final_events_size = 0; status = efi_bs_call(locate_protocol, &tcg2_guid, NULL, (void **)&tcg2_protocol); if (status != EFI_SUCCESS) return; status = efi_call_proto(tcg2_protocol, get_event_log, version, &log_location, &log_last_entry, &truncated); if (status != EFI_SUCCESS || !log_location) { version = EFI_TCG2_EVENT_LOG_FORMAT_TCG_1_2; status = efi_call_proto(tcg2_protocol, get_event_log, version, &log_location, &log_last_entry, &truncated); if (status != EFI_SUCCESS || !log_location) return; } first_entry_addr = (unsigned long) log_location; /* * We populate the EFI table even if the logs are empty. */ if (!log_last_entry) { log_size = 0; } else { last_entry_addr = (unsigned long) log_last_entry; /* * get_event_log only returns the address of the last entry. * We need to calculate its size to deduce the full size of * the logs. */ if (version == EFI_TCG2_EVENT_LOG_FORMAT_TCG_2) { /* * The TCG2 log format has variable length entries, * and the information to decode the hash algorithms * back into a size is contained in the first entry - * pass a pointer to the final entry (to calculate its * size) and the first entry (so we know how long each * digest is) */ last_entry_size = __calc_tpm2_event_size((void *)last_entry_addr, (void *)(long)log_location, false); } else { last_entry_size = sizeof(struct tcpa_event) + ((struct tcpa_event *) last_entry_addr)->event_size; } log_size = log_last_entry - log_location + last_entry_size; } /* Allocate space for the logs and copy them. */ status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, sizeof(*log_tbl) + log_size, (void **)&log_tbl); if (status != EFI_SUCCESS) { efi_err("Unable to allocate memory for event log\n"); return; } /* * Figure out whether any events have already been logged to the * final events structure, and if so how much space they take up */ if (version == EFI_TCG2_EVENT_LOG_FORMAT_TCG_2) final_events_table = get_efi_config_table(LINUX_EFI_TPM_FINAL_LOG_GUID); if (final_events_table && final_events_table->nr_events) { struct tcg_pcr_event2_head *header; int offset; void *data; int event_size; int i = final_events_table->nr_events; data = (void *)final_events_table; offset = sizeof(final_events_table->version) + sizeof(final_events_table->nr_events); while (i > 0) { header = data + offset + final_events_size; event_size = __calc_tpm2_event_size(header, (void *)(long)log_location, false); final_events_size += event_size; i--; } } memset(log_tbl, 0, sizeof(*log_tbl) + log_size); log_tbl->size = log_size; log_tbl->final_events_preboot_size = final_events_size; log_tbl->version = version; memcpy(log_tbl->log, (void *) first_entry_addr, log_size); status = efi_bs_call(install_configuration_table, &linux_eventlog_guid, log_tbl); if (status != EFI_SUCCESS) goto err_free; return; err_free: efi_bs_call(free_pool, log_tbl); }
linux-master
drivers/firmware/efi/libstub/tpm.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2020 Western Digital Corporation or its affiliates. */ #include <linux/efi.h> #include <linux/libfdt.h> #include <asm/efi.h> #include <asm/unaligned.h> #include "efistub.h" typedef void __noreturn (*jump_kernel_func)(unsigned long, unsigned long); static unsigned long hartid; static int get_boot_hartid_from_fdt(void) { const void *fdt; int chosen_node, len; const void *prop; fdt = get_efi_config_table(DEVICE_TREE_GUID); if (!fdt) return -EINVAL; chosen_node = fdt_path_offset(fdt, "/chosen"); if (chosen_node < 0) return -EINVAL; prop = fdt_getprop((void *)fdt, chosen_node, "boot-hartid", &len); if (!prop) return -EINVAL; if (len == sizeof(u32)) hartid = (unsigned long) fdt32_to_cpu(*(fdt32_t *)prop); else if (len == sizeof(u64)) hartid = (unsigned long) fdt64_to_cpu(__get_unaligned_t(fdt64_t, prop)); else return -EINVAL; return 0; } static efi_status_t get_boot_hartid_from_efi(void) { efi_guid_t boot_protocol_guid = RISCV_EFI_BOOT_PROTOCOL_GUID; struct riscv_efi_boot_protocol *boot_protocol; efi_status_t status; status = efi_bs_call(locate_protocol, &boot_protocol_guid, NULL, (void **)&boot_protocol); if (status != EFI_SUCCESS) return status; return efi_call_proto(boot_protocol, get_boot_hartid, &hartid); } efi_status_t check_platform_features(void) { efi_status_t status; int ret; status = get_boot_hartid_from_efi(); if (status != EFI_SUCCESS) { ret = get_boot_hartid_from_fdt(); if (ret) { efi_err("Failed to get boot hartid!\n"); return EFI_UNSUPPORTED; } } return EFI_SUCCESS; } unsigned long __weak stext_offset(void) { /* * This fallback definition is used by the EFI zboot stub, which loads * the entire image so it can branch via the image header at offset #0. */ return 0; } void __noreturn efi_enter_kernel(unsigned long entrypoint, unsigned long fdt, unsigned long fdt_size) { unsigned long kernel_entry = entrypoint + stext_offset(); jump_kernel_func jump_kernel = (jump_kernel_func)kernel_entry; /* * Jump to real kernel here with following constraints. * 1. MMU should be disabled. * 2. a0 should contain hartid * 3. a1 should DT address */ csr_write(CSR_SATP, 0); jump_kernel(hartid, fdt); }
linux-master
drivers/firmware/efi/libstub/riscv.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2013, 2014 Linaro Ltd; <[email protected]> * * This file implements the EFI boot stub for the arm64 kernel. * Adapted from ARM version by Mark Salter <[email protected]> */ #include <linux/efi.h> #include <asm/efi.h> #include <asm/memory.h> #include <asm/sections.h> #include "efistub.h" efi_status_t handle_kernel_image(unsigned long *image_addr, unsigned long *image_size, unsigned long *reserve_addr, unsigned long *reserve_size, efi_loaded_image_t *image, efi_handle_t image_handle) { efi_status_t status; unsigned long kernel_size, kernel_codesize, kernel_memsize; if (image->image_base != _text) { efi_err("FIRMWARE BUG: efi_loaded_image_t::image_base has bogus value\n"); image->image_base = _text; } if (!IS_ALIGNED((u64)_text, SEGMENT_ALIGN)) efi_err("FIRMWARE BUG: kernel image not aligned on %dk boundary\n", SEGMENT_ALIGN >> 10); kernel_size = _edata - _text; kernel_codesize = __inittext_end - _text; kernel_memsize = kernel_size + (_end - _edata); *reserve_size = kernel_memsize; *image_addr = (unsigned long)_text; status = efi_kaslr_relocate_kernel(image_addr, reserve_addr, reserve_size, kernel_size, kernel_codesize, kernel_memsize, efi_kaslr_get_phys_seed(image_handle)); if (status != EFI_SUCCESS) return status; return EFI_SUCCESS; } asmlinkage void primary_entry(void); unsigned long primary_entry_offset(void) { /* * When built as part of the kernel, the EFI stub cannot branch to the * kernel proper via the image header, as the PE/COFF header is * strictly not part of the in-memory presentation of the image, only * of the file representation. So instead, we need to jump to the * actual entrypoint in the .text region of the image. */ return (char *)primary_entry - _text; } void efi_icache_sync(unsigned long start, unsigned long end) { caches_clean_inval_pou(start, end); }
linux-master
drivers/firmware/efi/libstub/arm64-stub.c
// SPDX-License-Identifier: GPL-2.0 /* ----------------------------------------------------------------------- * * Copyright 2011 Intel Corporation; author Matt Fleming * * ----------------------------------------------------------------------- */ #include <linux/bitops.h> #include <linux/ctype.h> #include <linux/efi.h> #include <linux/screen_info.h> #include <linux/string.h> #include <asm/efi.h> #include <asm/setup.h> #include "efistub.h" enum efi_cmdline_option { EFI_CMDLINE_NONE, EFI_CMDLINE_MODE_NUM, EFI_CMDLINE_RES, EFI_CMDLINE_AUTO, EFI_CMDLINE_LIST }; static struct { enum efi_cmdline_option option; union { u32 mode; struct { u32 width, height; int format; u8 depth; } res; }; } cmdline = { .option = EFI_CMDLINE_NONE }; static bool parse_modenum(char *option, char **next) { u32 m; if (!strstarts(option, "mode=")) return false; option += strlen("mode="); m = simple_strtoull(option, &option, 0); if (*option && *option++ != ',') return false; cmdline.option = EFI_CMDLINE_MODE_NUM; cmdline.mode = m; *next = option; return true; } static bool parse_res(char *option, char **next) { u32 w, h, d = 0; int pf = -1; if (!isdigit(*option)) return false; w = simple_strtoull(option, &option, 10); if (*option++ != 'x' || !isdigit(*option)) return false; h = simple_strtoull(option, &option, 10); if (*option == '-') { option++; if (strstarts(option, "rgb")) { option += strlen("rgb"); pf = PIXEL_RGB_RESERVED_8BIT_PER_COLOR; } else if (strstarts(option, "bgr")) { option += strlen("bgr"); pf = PIXEL_BGR_RESERVED_8BIT_PER_COLOR; } else if (isdigit(*option)) d = simple_strtoull(option, &option, 10); else return false; } if (*option && *option++ != ',') return false; cmdline.option = EFI_CMDLINE_RES; cmdline.res.width = w; cmdline.res.height = h; cmdline.res.format = pf; cmdline.res.depth = d; *next = option; return true; } static bool parse_auto(char *option, char **next) { if (!strstarts(option, "auto")) return false; option += strlen("auto"); if (*option && *option++ != ',') return false; cmdline.option = EFI_CMDLINE_AUTO; *next = option; return true; } static bool parse_list(char *option, char **next) { if (!strstarts(option, "list")) return false; option += strlen("list"); if (*option && *option++ != ',') return false; cmdline.option = EFI_CMDLINE_LIST; *next = option; return true; } void efi_parse_option_graphics(char *option) { while (*option) { if (parse_modenum(option, &option)) continue; if (parse_res(option, &option)) continue; if (parse_auto(option, &option)) continue; if (parse_list(option, &option)) continue; while (*option && *option++ != ',') ; } } static u32 choose_mode_modenum(efi_graphics_output_protocol_t *gop) { efi_status_t status; efi_graphics_output_protocol_mode_t *mode; efi_graphics_output_mode_info_t *info; unsigned long info_size; u32 max_mode, cur_mode; int pf; mode = efi_table_attr(gop, mode); cur_mode = efi_table_attr(mode, mode); if (cmdline.mode == cur_mode) return cur_mode; max_mode = efi_table_attr(mode, max_mode); if (cmdline.mode >= max_mode) { efi_err("Requested mode is invalid\n"); return cur_mode; } status = efi_call_proto(gop, query_mode, cmdline.mode, &info_size, &info); if (status != EFI_SUCCESS) { efi_err("Couldn't get mode information\n"); return cur_mode; } pf = info->pixel_format; efi_bs_call(free_pool, info); if (pf == PIXEL_BLT_ONLY || pf >= PIXEL_FORMAT_MAX) { efi_err("Invalid PixelFormat\n"); return cur_mode; } return cmdline.mode; } static u8 pixel_bpp(int pixel_format, efi_pixel_bitmask_t pixel_info) { if (pixel_format == PIXEL_BIT_MASK) { u32 mask = pixel_info.red_mask | pixel_info.green_mask | pixel_info.blue_mask | pixel_info.reserved_mask; if (!mask) return 0; return __fls(mask) - __ffs(mask) + 1; } else return 32; } static u32 choose_mode_res(efi_graphics_output_protocol_t *gop) { efi_status_t status; efi_graphics_output_protocol_mode_t *mode; efi_graphics_output_mode_info_t *info; unsigned long info_size; u32 max_mode, cur_mode; int pf; efi_pixel_bitmask_t pi; u32 m, w, h; mode = efi_table_attr(gop, mode); cur_mode = efi_table_attr(mode, mode); info = efi_table_attr(mode, info); pf = info->pixel_format; pi = info->pixel_information; w = info->horizontal_resolution; h = info->vertical_resolution; if (w == cmdline.res.width && h == cmdline.res.height && (cmdline.res.format < 0 || cmdline.res.format == pf) && (!cmdline.res.depth || cmdline.res.depth == pixel_bpp(pf, pi))) return cur_mode; max_mode = efi_table_attr(mode, max_mode); for (m = 0; m < max_mode; m++) { if (m == cur_mode) continue; status = efi_call_proto(gop, query_mode, m, &info_size, &info); if (status != EFI_SUCCESS) continue; pf = info->pixel_format; pi = info->pixel_information; w = info->horizontal_resolution; h = info->vertical_resolution; efi_bs_call(free_pool, info); if (pf == PIXEL_BLT_ONLY || pf >= PIXEL_FORMAT_MAX) continue; if (w == cmdline.res.width && h == cmdline.res.height && (cmdline.res.format < 0 || cmdline.res.format == pf) && (!cmdline.res.depth || cmdline.res.depth == pixel_bpp(pf, pi))) return m; } efi_err("Couldn't find requested mode\n"); return cur_mode; } static u32 choose_mode_auto(efi_graphics_output_protocol_t *gop) { efi_status_t status; efi_graphics_output_protocol_mode_t *mode; efi_graphics_output_mode_info_t *info; unsigned long info_size; u32 max_mode, cur_mode, best_mode, area; u8 depth; int pf; efi_pixel_bitmask_t pi; u32 m, w, h, a; u8 d; mode = efi_table_attr(gop, mode); cur_mode = efi_table_attr(mode, mode); max_mode = efi_table_attr(mode, max_mode); info = efi_table_attr(mode, info); pf = info->pixel_format; pi = info->pixel_information; w = info->horizontal_resolution; h = info->vertical_resolution; best_mode = cur_mode; area = w * h; depth = pixel_bpp(pf, pi); for (m = 0; m < max_mode; m++) { if (m == cur_mode) continue; status = efi_call_proto(gop, query_mode, m, &info_size, &info); if (status != EFI_SUCCESS) continue; pf = info->pixel_format; pi = info->pixel_information; w = info->horizontal_resolution; h = info->vertical_resolution; efi_bs_call(free_pool, info); if (pf == PIXEL_BLT_ONLY || pf >= PIXEL_FORMAT_MAX) continue; a = w * h; if (a < area) continue; d = pixel_bpp(pf, pi); if (a > area || d > depth) { best_mode = m; area = a; depth = d; } } return best_mode; } static u32 choose_mode_list(efi_graphics_output_protocol_t *gop) { efi_status_t status; efi_graphics_output_protocol_mode_t *mode; efi_graphics_output_mode_info_t *info; unsigned long info_size; u32 max_mode, cur_mode; int pf; efi_pixel_bitmask_t pi; u32 m, w, h; u8 d; const char *dstr; bool valid; efi_input_key_t key; mode = efi_table_attr(gop, mode); cur_mode = efi_table_attr(mode, mode); max_mode = efi_table_attr(mode, max_mode); efi_printk("Available graphics modes are 0-%u\n", max_mode-1); efi_puts(" * = current mode\n" " - = unusable mode\n"); for (m = 0; m < max_mode; m++) { status = efi_call_proto(gop, query_mode, m, &info_size, &info); if (status != EFI_SUCCESS) continue; pf = info->pixel_format; pi = info->pixel_information; w = info->horizontal_resolution; h = info->vertical_resolution; efi_bs_call(free_pool, info); valid = !(pf == PIXEL_BLT_ONLY || pf >= PIXEL_FORMAT_MAX); d = 0; switch (pf) { case PIXEL_RGB_RESERVED_8BIT_PER_COLOR: dstr = "rgb"; break; case PIXEL_BGR_RESERVED_8BIT_PER_COLOR: dstr = "bgr"; break; case PIXEL_BIT_MASK: dstr = ""; d = pixel_bpp(pf, pi); break; case PIXEL_BLT_ONLY: dstr = "blt"; break; default: dstr = "xxx"; break; } efi_printk("Mode %3u %c%c: Resolution %ux%u-%s%.0hhu\n", m, m == cur_mode ? '*' : ' ', !valid ? '-' : ' ', w, h, dstr, d); } efi_puts("\nPress any key to continue (or wait 10 seconds)\n"); status = efi_wait_for_key(10 * EFI_USEC_PER_SEC, &key); if (status != EFI_SUCCESS && status != EFI_TIMEOUT) { efi_err("Unable to read key, continuing in 10 seconds\n"); efi_bs_call(stall, 10 * EFI_USEC_PER_SEC); } return cur_mode; } static void set_mode(efi_graphics_output_protocol_t *gop) { efi_graphics_output_protocol_mode_t *mode; u32 cur_mode, new_mode; switch (cmdline.option) { case EFI_CMDLINE_MODE_NUM: new_mode = choose_mode_modenum(gop); break; case EFI_CMDLINE_RES: new_mode = choose_mode_res(gop); break; case EFI_CMDLINE_AUTO: new_mode = choose_mode_auto(gop); break; case EFI_CMDLINE_LIST: new_mode = choose_mode_list(gop); break; default: return; } mode = efi_table_attr(gop, mode); cur_mode = efi_table_attr(mode, mode); if (new_mode == cur_mode) return; if (efi_call_proto(gop, set_mode, new_mode) != EFI_SUCCESS) efi_err("Failed to set requested mode\n"); } static void find_bits(u32 mask, u8 *pos, u8 *size) { if (!mask) { *pos = *size = 0; return; } /* UEFI spec guarantees that the set bits are contiguous */ *pos = __ffs(mask); *size = __fls(mask) - *pos + 1; } static void setup_pixel_info(struct screen_info *si, u32 pixels_per_scan_line, efi_pixel_bitmask_t pixel_info, int pixel_format) { if (pixel_format == PIXEL_BIT_MASK) { find_bits(pixel_info.red_mask, &si->red_pos, &si->red_size); find_bits(pixel_info.green_mask, &si->green_pos, &si->green_size); find_bits(pixel_info.blue_mask, &si->blue_pos, &si->blue_size); find_bits(pixel_info.reserved_mask, &si->rsvd_pos, &si->rsvd_size); si->lfb_depth = si->red_size + si->green_size + si->blue_size + si->rsvd_size; si->lfb_linelength = (pixels_per_scan_line * si->lfb_depth) / 8; } else { if (pixel_format == PIXEL_RGB_RESERVED_8BIT_PER_COLOR) { si->red_pos = 0; si->blue_pos = 16; } else /* PIXEL_BGR_RESERVED_8BIT_PER_COLOR */ { si->blue_pos = 0; si->red_pos = 16; } si->green_pos = 8; si->rsvd_pos = 24; si->red_size = si->green_size = si->blue_size = si->rsvd_size = 8; si->lfb_depth = 32; si->lfb_linelength = pixels_per_scan_line * 4; } } static efi_graphics_output_protocol_t * find_gop(efi_guid_t *proto, unsigned long size, void **handles) { efi_graphics_output_protocol_t *first_gop; efi_handle_t h; int i; first_gop = NULL; for_each_efi_handle(h, handles, size, i) { efi_status_t status; efi_graphics_output_protocol_t *gop; efi_graphics_output_protocol_mode_t *mode; efi_graphics_output_mode_info_t *info; efi_guid_t conout_proto = EFI_CONSOLE_OUT_DEVICE_GUID; void *dummy = NULL; status = efi_bs_call(handle_protocol, h, proto, (void **)&gop); if (status != EFI_SUCCESS) continue; mode = efi_table_attr(gop, mode); info = efi_table_attr(mode, info); if (info->pixel_format == PIXEL_BLT_ONLY || info->pixel_format >= PIXEL_FORMAT_MAX) continue; /* * Systems that use the UEFI Console Splitter may * provide multiple GOP devices, not all of which are * backed by real hardware. The workaround is to search * for a GOP implementing the ConOut protocol, and if * one isn't found, to just fall back to the first GOP. * * Once we've found a GOP supporting ConOut, * don't bother looking any further. */ status = efi_bs_call(handle_protocol, h, &conout_proto, &dummy); if (status == EFI_SUCCESS) return gop; if (!first_gop) first_gop = gop; } return first_gop; } static efi_status_t setup_gop(struct screen_info *si, efi_guid_t *proto, unsigned long size, void **handles) { efi_graphics_output_protocol_t *gop; efi_graphics_output_protocol_mode_t *mode; efi_graphics_output_mode_info_t *info; gop = find_gop(proto, size, handles); /* Did we find any GOPs? */ if (!gop) return EFI_NOT_FOUND; /* Change mode if requested */ set_mode(gop); /* EFI framebuffer */ mode = efi_table_attr(gop, mode); info = efi_table_attr(mode, info); si->orig_video_isVGA = VIDEO_TYPE_EFI; si->lfb_width = info->horizontal_resolution; si->lfb_height = info->vertical_resolution; efi_set_u64_split(efi_table_attr(mode, frame_buffer_base), &si->lfb_base, &si->ext_lfb_base); if (si->ext_lfb_base) si->capabilities |= VIDEO_CAPABILITY_64BIT_BASE; si->pages = 1; setup_pixel_info(si, info->pixels_per_scan_line, info->pixel_information, info->pixel_format); si->lfb_size = si->lfb_linelength * si->lfb_height; si->capabilities |= VIDEO_CAPABILITY_SKIP_QUIRKS; return EFI_SUCCESS; } /* * See if we have Graphics Output Protocol */ efi_status_t efi_setup_gop(struct screen_info *si, efi_guid_t *proto, unsigned long size) { efi_status_t status; void **gop_handle = NULL; status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, size, (void **)&gop_handle); if (status != EFI_SUCCESS) return status; status = efi_bs_call(locate_handle, EFI_LOCATE_BY_PROTOCOL, proto, NULL, &size, gop_handle); if (status != EFI_SUCCESS) goto free_handle; status = setup_gop(si, proto, size, gop_handle); free_handle: efi_bs_call(free_pool, gop_handle); return status; }
linux-master
drivers/firmware/efi/libstub/gop.c
// SPDX-License-Identifier: GPL-2.0-only #include <linux/efi.h> #include <asm/efi.h> #include "efistub.h" struct efi_unaccepted_memory *unaccepted_table; efi_status_t allocate_unaccepted_bitmap(__u32 nr_desc, struct efi_boot_memmap *map) { efi_guid_t unaccepted_table_guid = LINUX_EFI_UNACCEPTED_MEM_TABLE_GUID; u64 unaccepted_start = ULLONG_MAX, unaccepted_end = 0, bitmap_size; efi_status_t status; int i; /* Check if the table is already installed */ unaccepted_table = get_efi_config_table(unaccepted_table_guid); if (unaccepted_table) { if (unaccepted_table->version != 1) { efi_err("Unknown version of unaccepted memory table\n"); return EFI_UNSUPPORTED; } return EFI_SUCCESS; } /* Check if there's any unaccepted memory and find the max address */ for (i = 0; i < nr_desc; i++) { efi_memory_desc_t *d; unsigned long m = (unsigned long)map->map; d = efi_early_memdesc_ptr(m, map->desc_size, i); if (d->type != EFI_UNACCEPTED_MEMORY) continue; unaccepted_start = min(unaccepted_start, d->phys_addr); unaccepted_end = max(unaccepted_end, d->phys_addr + d->num_pages * PAGE_SIZE); } if (unaccepted_start == ULLONG_MAX) return EFI_SUCCESS; unaccepted_start = round_down(unaccepted_start, EFI_UNACCEPTED_UNIT_SIZE); unaccepted_end = round_up(unaccepted_end, EFI_UNACCEPTED_UNIT_SIZE); /* * If unaccepted memory is present, allocate a bitmap to track what * memory has to be accepted before access. * * One bit in the bitmap represents 2MiB in the address space: * A 4k bitmap can track 64GiB of physical address space. * * In the worst case scenario -- a huge hole in the middle of the * address space -- It needs 256MiB to handle 4PiB of the address * space. * * The bitmap will be populated in setup_e820() according to the memory * map after efi_exit_boot_services(). */ bitmap_size = DIV_ROUND_UP(unaccepted_end - unaccepted_start, EFI_UNACCEPTED_UNIT_SIZE * BITS_PER_BYTE); status = efi_bs_call(allocate_pool, EFI_ACPI_RECLAIM_MEMORY, sizeof(*unaccepted_table) + bitmap_size, (void **)&unaccepted_table); if (status != EFI_SUCCESS) { efi_err("Failed to allocate unaccepted memory config table\n"); return status; } unaccepted_table->version = 1; unaccepted_table->unit_size = EFI_UNACCEPTED_UNIT_SIZE; unaccepted_table->phys_base = unaccepted_start; unaccepted_table->size = bitmap_size; memset(unaccepted_table->bitmap, 0, bitmap_size); status = efi_bs_call(install_configuration_table, &unaccepted_table_guid, unaccepted_table); if (status != EFI_SUCCESS) { efi_bs_call(free_pool, unaccepted_table); efi_err("Failed to install unaccepted memory config table!\n"); } return status; } /* * The accepted memory bitmap only works at unit_size granularity. Take * unaligned start/end addresses and either: * 1. Accepts the memory immediately and in its entirety * 2. Accepts unaligned parts, and marks *some* aligned part unaccepted * * The function will never reach the bitmap_set() with zero bits to set. */ void process_unaccepted_memory(u64 start, u64 end) { u64 unit_size = unaccepted_table->unit_size; u64 unit_mask = unaccepted_table->unit_size - 1; u64 bitmap_size = unaccepted_table->size; /* * Ensure that at least one bit will be set in the bitmap by * immediately accepting all regions under 2*unit_size. This is * imprecise and may immediately accept some areas that could * have been represented in the bitmap. But, results in simpler * code below * * Consider case like this (assuming unit_size == 2MB): * * | 4k | 2044k | 2048k | * ^ 0x0 ^ 2MB ^ 4MB * * Only the first 4k has been accepted. The 0MB->2MB region can not be * represented in the bitmap. The 2MB->4MB region can be represented in * the bitmap. But, the 0MB->4MB region is <2*unit_size and will be * immediately accepted in its entirety. */ if (end - start < 2 * unit_size) { arch_accept_memory(start, end); return; } /* * No matter how the start and end are aligned, at least one unaccepted * unit_size area will remain to be marked in the bitmap. */ /* Immediately accept a <unit_size piece at the start: */ if (start & unit_mask) { arch_accept_memory(start, round_up(start, unit_size)); start = round_up(start, unit_size); } /* Immediately accept a <unit_size piece at the end: */ if (end & unit_mask) { arch_accept_memory(round_down(end, unit_size), end); end = round_down(end, unit_size); } /* * Accept part of the range that before phys_base and cannot be recorded * into the bitmap. */ if (start < unaccepted_table->phys_base) { arch_accept_memory(start, min(unaccepted_table->phys_base, end)); start = unaccepted_table->phys_base; } /* Nothing to record */ if (end < unaccepted_table->phys_base) return; /* Translate to offsets from the beginning of the bitmap */ start -= unaccepted_table->phys_base; end -= unaccepted_table->phys_base; /* Accept memory that doesn't fit into bitmap */ if (end > bitmap_size * unit_size * BITS_PER_BYTE) { unsigned long phys_start, phys_end; phys_start = bitmap_size * unit_size * BITS_PER_BYTE + unaccepted_table->phys_base; phys_end = end + unaccepted_table->phys_base; arch_accept_memory(phys_start, phys_end); end = bitmap_size * unit_size * BITS_PER_BYTE; } /* * 'start' and 'end' are now both unit_size-aligned. * Record the range as being unaccepted: */ bitmap_set(unaccepted_table->bitmap, start / unit_size, (end - start) / unit_size); } void accept_memory(phys_addr_t start, phys_addr_t end) { unsigned long range_start, range_end; unsigned long bitmap_size; u64 unit_size; if (!unaccepted_table) return; unit_size = unaccepted_table->unit_size; /* * Only care for the part of the range that is represented * in the bitmap. */ if (start < unaccepted_table->phys_base) start = unaccepted_table->phys_base; if (end < unaccepted_table->phys_base) return; /* Translate to offsets from the beginning of the bitmap */ start -= unaccepted_table->phys_base; end -= unaccepted_table->phys_base; /* Make sure not to overrun the bitmap */ if (end > unaccepted_table->size * unit_size * BITS_PER_BYTE) end = unaccepted_table->size * unit_size * BITS_PER_BYTE; range_start = start / unit_size; bitmap_size = DIV_ROUND_UP(end, unit_size); for_each_set_bitrange_from(range_start, range_end, unaccepted_table->bitmap, bitmap_size) { unsigned long phys_start, phys_end; phys_start = range_start * unit_size + unaccepted_table->phys_base; phys_end = range_end * unit_size + unaccepted_table->phys_base; arch_accept_memory(phys_start, phys_end); bitmap_clear(unaccepted_table->bitmap, range_start, range_end - range_start); } }
linux-master
drivers/firmware/efi/libstub/unaccepted_memory.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2013, 2014 Linaro Ltd; <[email protected]> * * This file implements the EFI boot stub for the arm64 kernel. * Adapted from ARM version by Mark Salter <[email protected]> */ #include <linux/efi.h> #include <asm/efi.h> #include <asm/image.h> #include <asm/memory.h> #include <asm/sysreg.h> #include "efistub.h" static bool system_needs_vamap(void) { const struct efi_smbios_type4_record *record; const u32 __aligned(1) *socid; const u8 *version; /* * Ampere eMAG, Altra, and Altra Max machines crash in SetTime() if * SetVirtualAddressMap() has not been called prior. Most Altra systems * can be identified by the SMCCC soc ID, which is conveniently exposed * via the type 4 SMBIOS records. Otherwise, test the processor version * field. eMAG systems all appear to have the processor version field * set to "eMAG". */ record = (struct efi_smbios_type4_record *)efi_get_smbios_record(4); if (!record) return false; socid = (u32 *)record->processor_id; switch (*socid & 0xffff000f) { static char const altra[] = "Ampere(TM) Altra(TM) Processor"; static char const emag[] = "eMAG"; default: version = efi_get_smbios_string(&record->header, 4, processor_version); if (!version || (strncmp(version, altra, sizeof(altra) - 1) && strncmp(version, emag, sizeof(emag) - 1))) break; fallthrough; case 0x0a160001: // Altra case 0x0a160002: // Altra Max efi_warn("Working around broken SetVirtualAddressMap()\n"); return true; } return false; } efi_status_t check_platform_features(void) { u64 tg; /* * If we have 48 bits of VA space for TTBR0 mappings, we can map the * UEFI runtime regions 1:1 and so calling SetVirtualAddressMap() is * unnecessary. */ if (VA_BITS_MIN >= 48 && !system_needs_vamap()) efi_novamap = true; /* UEFI mandates support for 4 KB granularity, no need to check */ if (IS_ENABLED(CONFIG_ARM64_4K_PAGES)) return EFI_SUCCESS; tg = (read_cpuid(ID_AA64MMFR0_EL1) >> ID_AA64MMFR0_EL1_TGRAN_SHIFT) & 0xf; if (tg < ID_AA64MMFR0_EL1_TGRAN_SUPPORTED_MIN || tg > ID_AA64MMFR0_EL1_TGRAN_SUPPORTED_MAX) { if (IS_ENABLED(CONFIG_ARM64_64K_PAGES)) efi_err("This 64 KB granular kernel is not supported by your CPU\n"); else efi_err("This 16 KB granular kernel is not supported by your CPU\n"); return EFI_UNSUPPORTED; } return EFI_SUCCESS; } #ifdef CONFIG_ARM64_WORKAROUND_CLEAN_CACHE #define DCTYPE "civac" #else #define DCTYPE "cvau" #endif u32 __weak code_size; void efi_cache_sync_image(unsigned long image_base, unsigned long alloc_size) { u32 ctr = read_cpuid_effective_cachetype(); u64 lsize = 4 << cpuid_feature_extract_unsigned_field(ctr, CTR_EL0_DminLine_SHIFT); /* only perform the cache maintenance if needed for I/D coherency */ if (!(ctr & BIT(CTR_EL0_IDC_SHIFT))) { unsigned long base = image_base; unsigned long size = code_size; do { asm("dc " DCTYPE ", %0" :: "r"(base)); base += lsize; size -= lsize; } while (size >= lsize); } asm("ic ialluis"); dsb(ish); isb(); efi_remap_image(image_base, alloc_size, code_size); } unsigned long __weak primary_entry_offset(void) { /* * By default, we can invoke the kernel via the branch instruction in * the image header, so offset #0. This will be overridden by the EFI * stub build that is linked into the core kernel, as in that case, the * image header may not have been loaded into memory, or may be mapped * with non-executable permissions. */ return 0; } void __noreturn efi_enter_kernel(unsigned long entrypoint, unsigned long fdt_addr, unsigned long fdt_size) { void (* __noreturn enter_kernel)(u64, u64, u64, u64); enter_kernel = (void *)entrypoint + primary_entry_offset(); enter_kernel(fdt_addr, 0, 0, 0); }
linux-master
drivers/firmware/efi/libstub/arm64.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/efi.h> #include <asm/efi.h> #include "efistub.h" const efi_system_table_t *efi_system_table;
linux-master
drivers/firmware/efi/libstub/systable.c
#include <linux/bitmap.h> void __bitmap_set(unsigned long *map, unsigned int start, int len) { unsigned long *p = map + BIT_WORD(start); const unsigned int size = start + len; int bits_to_set = BITS_PER_LONG - (start % BITS_PER_LONG); unsigned long mask_to_set = BITMAP_FIRST_WORD_MASK(start); while (len - bits_to_set >= 0) { *p |= mask_to_set; len -= bits_to_set; bits_to_set = BITS_PER_LONG; mask_to_set = ~0UL; p++; } if (len) { mask_to_set &= BITMAP_LAST_WORD_MASK(size); *p |= mask_to_set; } } void __bitmap_clear(unsigned long *map, unsigned int start, int len) { unsigned long *p = map + BIT_WORD(start); const unsigned int size = start + len; int bits_to_clear = BITS_PER_LONG - (start % BITS_PER_LONG); unsigned long mask_to_clear = BITMAP_FIRST_WORD_MASK(start); while (len - bits_to_clear >= 0) { *p &= ~mask_to_clear; len -= bits_to_clear; bits_to_clear = BITS_PER_LONG; mask_to_clear = ~0UL; p++; } if (len) { mask_to_clear &= BITMAP_LAST_WORD_MASK(size); *p &= ~mask_to_clear; } }
linux-master
drivers/firmware/efi/libstub/bitmap.c
// SPDX-License-Identifier: GPL-2.0 /* * PCI-related functions used by the EFI stub on multiple * architectures. * * Copyright 2019 Google, LLC */ #include <linux/efi.h> #include <linux/pci.h> #include <asm/efi.h> #include "efistub.h" void efi_pci_disable_bridge_busmaster(void) { efi_guid_t pci_proto = EFI_PCI_IO_PROTOCOL_GUID; unsigned long pci_handle_size = 0; efi_handle_t *pci_handle = NULL; efi_handle_t handle; efi_status_t status; u16 class, command; int i; status = efi_bs_call(locate_handle, EFI_LOCATE_BY_PROTOCOL, &pci_proto, NULL, &pci_handle_size, NULL); if (status != EFI_BUFFER_TOO_SMALL) { if (status != EFI_SUCCESS && status != EFI_NOT_FOUND) efi_err("Failed to locate PCI I/O handles'\n"); return; } status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, pci_handle_size, (void **)&pci_handle); if (status != EFI_SUCCESS) { efi_err("Failed to allocate memory for 'pci_handle'\n"); return; } status = efi_bs_call(locate_handle, EFI_LOCATE_BY_PROTOCOL, &pci_proto, NULL, &pci_handle_size, pci_handle); if (status != EFI_SUCCESS) { efi_err("Failed to locate PCI I/O handles'\n"); goto free_handle; } for_each_efi_handle(handle, pci_handle, pci_handle_size, i) { efi_pci_io_protocol_t *pci; unsigned long segment_nr, bus_nr, device_nr, func_nr; status = efi_bs_call(handle_protocol, handle, &pci_proto, (void **)&pci); if (status != EFI_SUCCESS) continue; /* * Disregard devices living on bus 0 - these are not behind a * bridge so no point in disconnecting them from their drivers. */ status = efi_call_proto(pci, get_location, &segment_nr, &bus_nr, &device_nr, &func_nr); if (status != EFI_SUCCESS || bus_nr == 0) continue; /* * Don't disconnect VGA controllers so we don't risk losing * access to the framebuffer. Drivers for true PCIe graphics * controllers that are behind a PCIe root port do not use * DMA to implement the GOP framebuffer anyway [although they * may use it in their implementation of Gop->Blt()], and so * disabling DMA in the PCI bridge should not interfere with * normal operation of the device. */ status = efi_call_proto(pci, pci.read, EfiPciIoWidthUint16, PCI_CLASS_DEVICE, 1, &class); if (status != EFI_SUCCESS || class == PCI_CLASS_DISPLAY_VGA) continue; /* Disconnect this handle from all its drivers */ efi_bs_call(disconnect_controller, handle, NULL, NULL); } for_each_efi_handle(handle, pci_handle, pci_handle_size, i) { efi_pci_io_protocol_t *pci; status = efi_bs_call(handle_protocol, handle, &pci_proto, (void **)&pci); if (status != EFI_SUCCESS || !pci) continue; status = efi_call_proto(pci, pci.read, EfiPciIoWidthUint16, PCI_CLASS_DEVICE, 1, &class); if (status != EFI_SUCCESS || class != PCI_CLASS_BRIDGE_PCI) continue; /* Disable busmastering */ status = efi_call_proto(pci, pci.read, EfiPciIoWidthUint16, PCI_COMMAND, 1, &command); if (status != EFI_SUCCESS || !(command & PCI_COMMAND_MASTER)) continue; command &= ~PCI_COMMAND_MASTER; status = efi_call_proto(pci, pci.write, EfiPciIoWidthUint16, PCI_COMMAND, 1, &command); if (status != EFI_SUCCESS) efi_err("Failed to disable PCI busmastering\n"); } free_handle: efi_bs_call(free_pool, pci_handle); }
linux-master
drivers/firmware/efi/libstub/pci.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/efi.h> #include <asm/efi.h> #include "efistub.h" /** * efi_get_memory_map() - get memory map * @map: pointer to memory map pointer to which to assign the * newly allocated memory map * @install_cfg_tbl: whether or not to install the boot memory map as a * configuration table * * Retrieve the UEFI memory map. The allocated memory leaves room for * up to EFI_MMAP_NR_SLACK_SLOTS additional memory map entries. * * Return: status code */ efi_status_t efi_get_memory_map(struct efi_boot_memmap **map, bool install_cfg_tbl) { int memtype = install_cfg_tbl ? EFI_ACPI_RECLAIM_MEMORY : EFI_LOADER_DATA; efi_guid_t tbl_guid = LINUX_EFI_BOOT_MEMMAP_GUID; struct efi_boot_memmap *m, tmp; efi_status_t status; unsigned long size; tmp.map_size = 0; status = efi_bs_call(get_memory_map, &tmp.map_size, NULL, &tmp.map_key, &tmp.desc_size, &tmp.desc_ver); if (status != EFI_BUFFER_TOO_SMALL) return EFI_LOAD_ERROR; size = tmp.map_size + tmp.desc_size * EFI_MMAP_NR_SLACK_SLOTS; status = efi_bs_call(allocate_pool, memtype, sizeof(*m) + size, (void **)&m); if (status != EFI_SUCCESS) return status; if (install_cfg_tbl) { /* * Installing a configuration table might allocate memory, and * this may modify the memory map. This means we should install * the configuration table first, and re-install or delete it * as needed. */ status = efi_bs_call(install_configuration_table, &tbl_guid, m); if (status != EFI_SUCCESS) goto free_map; } m->buff_size = m->map_size = size; status = efi_bs_call(get_memory_map, &m->map_size, m->map, &m->map_key, &m->desc_size, &m->desc_ver); if (status != EFI_SUCCESS) goto uninstall_table; *map = m; return EFI_SUCCESS; uninstall_table: if (install_cfg_tbl) efi_bs_call(install_configuration_table, &tbl_guid, NULL); free_map: efi_bs_call(free_pool, m); return status; } /** * efi_allocate_pages() - Allocate memory pages * @size: minimum number of bytes to allocate * @addr: On return the address of the first allocated page. The first * allocated page has alignment EFI_ALLOC_ALIGN which is an * architecture dependent multiple of the page size. * @max: the address that the last allocated memory page shall not * exceed * * Allocate pages as EFI_LOADER_DATA. The allocated pages are aligned according * to EFI_ALLOC_ALIGN. The last allocated page will not exceed the address * given by @max. * * Return: status code */ efi_status_t efi_allocate_pages(unsigned long size, unsigned long *addr, unsigned long max) { efi_physical_addr_t alloc_addr; efi_status_t status; max = min(max, EFI_ALLOC_LIMIT); if (EFI_ALLOC_ALIGN > EFI_PAGE_SIZE) return efi_allocate_pages_aligned(size, addr, max, EFI_ALLOC_ALIGN, EFI_LOADER_DATA); alloc_addr = ALIGN_DOWN(max + 1, EFI_ALLOC_ALIGN) - 1; status = efi_bs_call(allocate_pages, EFI_ALLOCATE_MAX_ADDRESS, EFI_LOADER_DATA, DIV_ROUND_UP(size, EFI_PAGE_SIZE), &alloc_addr); if (status != EFI_SUCCESS) return status; *addr = alloc_addr; return EFI_SUCCESS; } /** * efi_free() - free memory pages * @size: size of the memory area to free in bytes * @addr: start of the memory area to free (must be EFI_PAGE_SIZE * aligned) * * @size is rounded up to a multiple of EFI_ALLOC_ALIGN which is an * architecture specific multiple of EFI_PAGE_SIZE. So this function should * only be used to return pages allocated with efi_allocate_pages() or * efi_low_alloc_above(). */ void efi_free(unsigned long size, unsigned long addr) { unsigned long nr_pages; if (!size) return; nr_pages = round_up(size, EFI_ALLOC_ALIGN) / EFI_PAGE_SIZE; efi_bs_call(free_pages, addr, nr_pages); }
linux-master
drivers/firmware/efi/libstub/mem.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/efi.h> #include <linux/pe.h> #include <asm/efi.h> #include <asm/unaligned.h> #include "efistub.h" static unsigned char zboot_heap[SZ_256K] __aligned(64); static unsigned long free_mem_ptr, free_mem_end_ptr; #define STATIC static #if defined(CONFIG_KERNEL_GZIP) #include "../../../../lib/decompress_inflate.c" #elif defined(CONFIG_KERNEL_LZ4) #include "../../../../lib/decompress_unlz4.c" #elif defined(CONFIG_KERNEL_LZMA) #include "../../../../lib/decompress_unlzma.c" #elif defined(CONFIG_KERNEL_LZO) #include "../../../../lib/decompress_unlzo.c" #elif defined(CONFIG_KERNEL_XZ) #undef memcpy #define memcpy memcpy #undef memmove #define memmove memmove #include "../../../../lib/decompress_unxz.c" #elif defined(CONFIG_KERNEL_ZSTD) #include "../../../../lib/decompress_unzstd.c" #endif extern char efi_zboot_header[]; extern char _gzdata_start[], _gzdata_end[]; static void error(char *x) { efi_err("EFI decompressor: %s\n", x); } static unsigned long alloc_preferred_address(unsigned long alloc_size) { #ifdef EFI_KIMG_PREFERRED_ADDRESS efi_physical_addr_t efi_addr = EFI_KIMG_PREFERRED_ADDRESS; if (efi_bs_call(allocate_pages, EFI_ALLOCATE_ADDRESS, EFI_LOADER_DATA, alloc_size / EFI_PAGE_SIZE, &efi_addr) == EFI_SUCCESS) return efi_addr; #endif return ULONG_MAX; } void __weak efi_cache_sync_image(unsigned long image_base, unsigned long alloc_size) { // Provided by the arch to perform the cache maintenance necessary for // executable code loaded into memory to be safe for execution. } struct screen_info *alloc_screen_info(void) { return __alloc_screen_info(); } asmlinkage efi_status_t __efiapi efi_zboot_entry(efi_handle_t handle, efi_system_table_t *systab) { unsigned long compressed_size = _gzdata_end - _gzdata_start; unsigned long image_base, alloc_size; efi_loaded_image_t *image; efi_status_t status; char *cmdline_ptr; int ret; WRITE_ONCE(efi_system_table, systab); free_mem_ptr = (unsigned long)&zboot_heap; free_mem_end_ptr = free_mem_ptr + sizeof(zboot_heap); status = efi_bs_call(handle_protocol, handle, &LOADED_IMAGE_PROTOCOL_GUID, (void **)&image); if (status != EFI_SUCCESS) { error("Failed to locate parent's loaded image protocol"); return status; } status = efi_handle_cmdline(image, &cmdline_ptr); if (status != EFI_SUCCESS) return status; efi_info("Decompressing Linux Kernel...\n"); // SizeOfImage from the compressee's PE/COFF header alloc_size = round_up(get_unaligned_le32(_gzdata_end - 4), EFI_ALLOC_ALIGN); // If the architecture has a preferred address for the image, // try that first. image_base = alloc_preferred_address(alloc_size); if (image_base == ULONG_MAX) { unsigned long min_kimg_align = efi_get_kimg_min_align(); u32 seed = U32_MAX; if (!IS_ENABLED(CONFIG_RANDOMIZE_BASE)) { // Setting the random seed to 0x0 is the same as // allocating as low as possible seed = 0; } else if (efi_nokaslr) { efi_info("KASLR disabled on kernel command line\n"); } else { status = efi_get_random_bytes(sizeof(seed), (u8 *)&seed); if (status == EFI_NOT_FOUND) { efi_info("EFI_RNG_PROTOCOL unavailable\n"); efi_nokaslr = true; } else if (status != EFI_SUCCESS) { efi_err("efi_get_random_bytes() failed (0x%lx)\n", status); efi_nokaslr = true; } } status = efi_random_alloc(alloc_size, min_kimg_align, &image_base, seed, EFI_LOADER_CODE, EFI_ALLOC_LIMIT); if (status != EFI_SUCCESS) { efi_err("Failed to allocate memory\n"); goto free_cmdline; } } // Decompress the payload into the newly allocated buffer. ret = __decompress(_gzdata_start, compressed_size, NULL, NULL, (void *)image_base, alloc_size, NULL, error); if (ret < 0) { error("Decompression failed"); status = EFI_DEVICE_ERROR; goto free_image; } efi_cache_sync_image(image_base, alloc_size); status = efi_stub_common(handle, image, image_base, cmdline_ptr); free_image: efi_free(alloc_size, image_base); free_cmdline: efi_bs_call(free_pool, cmdline_ptr); return status; }
linux-master
drivers/firmware/efi/libstub/zboot.c
// SPDX-License-Identifier: GPL-2.0 /* * FDT related Helper functions used by the EFI stub on multiple * architectures. This should be #included by the EFI stub * implementation files. * * Copyright 2013 Linaro Limited; author Roy Franz */ #include <linux/efi.h> #include <linux/libfdt.h> #include <asm/efi.h> #include "efistub.h" #define EFI_DT_ADDR_CELLS_DEFAULT 2 #define EFI_DT_SIZE_CELLS_DEFAULT 2 static void fdt_update_cell_size(void *fdt) { int offset; offset = fdt_path_offset(fdt, "/"); /* Set the #address-cells and #size-cells values for an empty tree */ fdt_setprop_u32(fdt, offset, "#address-cells", EFI_DT_ADDR_CELLS_DEFAULT); fdt_setprop_u32(fdt, offset, "#size-cells", EFI_DT_SIZE_CELLS_DEFAULT); } static efi_status_t update_fdt(void *orig_fdt, unsigned long orig_fdt_size, void *fdt, int new_fdt_size, char *cmdline_ptr) { int node, num_rsv; int status; u32 fdt_val32; u64 fdt_val64; /* Do some checks on provided FDT, if it exists: */ if (orig_fdt) { if (fdt_check_header(orig_fdt)) { efi_err("Device Tree header not valid!\n"); return EFI_LOAD_ERROR; } /* * We don't get the size of the FDT if we get if from a * configuration table: */ if (orig_fdt_size && fdt_totalsize(orig_fdt) > orig_fdt_size) { efi_err("Truncated device tree! foo!\n"); return EFI_LOAD_ERROR; } } if (orig_fdt) { status = fdt_open_into(orig_fdt, fdt, new_fdt_size); } else { status = fdt_create_empty_tree(fdt, new_fdt_size); if (status == 0) { /* * Any failure from the following function is * non-critical: */ fdt_update_cell_size(fdt); } } if (status != 0) goto fdt_set_fail; /* * Delete all memory reserve map entries. When booting via UEFI, * kernel will use the UEFI memory map to find reserved regions. */ num_rsv = fdt_num_mem_rsv(fdt); while (num_rsv-- > 0) fdt_del_mem_rsv(fdt, num_rsv); node = fdt_subnode_offset(fdt, 0, "chosen"); if (node < 0) { node = fdt_add_subnode(fdt, 0, "chosen"); if (node < 0) { /* 'node' is an error code when negative: */ status = node; goto fdt_set_fail; } } if (cmdline_ptr != NULL && strlen(cmdline_ptr) > 0) { status = fdt_setprop(fdt, node, "bootargs", cmdline_ptr, strlen(cmdline_ptr) + 1); if (status) goto fdt_set_fail; } /* Add FDT entries for EFI runtime services in chosen node. */ node = fdt_subnode_offset(fdt, 0, "chosen"); fdt_val64 = cpu_to_fdt64((u64)(unsigned long)efi_system_table); status = fdt_setprop_var(fdt, node, "linux,uefi-system-table", fdt_val64); if (status) goto fdt_set_fail; fdt_val64 = U64_MAX; /* placeholder */ status = fdt_setprop_var(fdt, node, "linux,uefi-mmap-start", fdt_val64); if (status) goto fdt_set_fail; fdt_val32 = U32_MAX; /* placeholder */ status = fdt_setprop_var(fdt, node, "linux,uefi-mmap-size", fdt_val32); if (status) goto fdt_set_fail; status = fdt_setprop_var(fdt, node, "linux,uefi-mmap-desc-size", fdt_val32); if (status) goto fdt_set_fail; status = fdt_setprop_var(fdt, node, "linux,uefi-mmap-desc-ver", fdt_val32); if (status) goto fdt_set_fail; if (IS_ENABLED(CONFIG_RANDOMIZE_BASE) && !efi_nokaslr) { efi_status_t efi_status; efi_status = efi_get_random_bytes(sizeof(fdt_val64), (u8 *)&fdt_val64); if (efi_status == EFI_SUCCESS) { status = fdt_setprop_var(fdt, node, "kaslr-seed", fdt_val64); if (status) goto fdt_set_fail; } } /* Shrink the FDT back to its minimum size: */ fdt_pack(fdt); return EFI_SUCCESS; fdt_set_fail: if (status == -FDT_ERR_NOSPACE) return EFI_BUFFER_TOO_SMALL; return EFI_LOAD_ERROR; } static efi_status_t update_fdt_memmap(void *fdt, struct efi_boot_memmap *map) { int node = fdt_path_offset(fdt, "/chosen"); u64 fdt_val64; u32 fdt_val32; int err; if (node < 0) return EFI_LOAD_ERROR; fdt_val64 = cpu_to_fdt64((unsigned long)map->map); err = fdt_setprop_inplace_var(fdt, node, "linux,uefi-mmap-start", fdt_val64); if (err) return EFI_LOAD_ERROR; fdt_val32 = cpu_to_fdt32(map->map_size); err = fdt_setprop_inplace_var(fdt, node, "linux,uefi-mmap-size", fdt_val32); if (err) return EFI_LOAD_ERROR; fdt_val32 = cpu_to_fdt32(map->desc_size); err = fdt_setprop_inplace_var(fdt, node, "linux,uefi-mmap-desc-size", fdt_val32); if (err) return EFI_LOAD_ERROR; fdt_val32 = cpu_to_fdt32(map->desc_ver); err = fdt_setprop_inplace_var(fdt, node, "linux,uefi-mmap-desc-ver", fdt_val32); if (err) return EFI_LOAD_ERROR; return EFI_SUCCESS; } struct exit_boot_struct { struct efi_boot_memmap *boot_memmap; efi_memory_desc_t *runtime_map; int runtime_entry_count; void *new_fdt_addr; }; static efi_status_t exit_boot_func(struct efi_boot_memmap *map, void *priv) { struct exit_boot_struct *p = priv; p->boot_memmap = map; /* * Update the memory map with virtual addresses. The function will also * populate @runtime_map with copies of just the EFI_MEMORY_RUNTIME * entries so that we can pass it straight to SetVirtualAddressMap() */ efi_get_virtmap(map->map, map->map_size, map->desc_size, p->runtime_map, &p->runtime_entry_count); return update_fdt_memmap(p->new_fdt_addr, map); } #ifndef MAX_FDT_SIZE # define MAX_FDT_SIZE SZ_2M #endif /* * Allocate memory for a new FDT, then add EFI and commandline related fields * to the FDT. This routine increases the FDT allocation size until the * allocated memory is large enough. EFI allocations are in EFI_PAGE_SIZE * granules, which are fixed at 4K bytes, so in most cases the first allocation * should succeed. EFI boot services are exited at the end of this function. * There must be no allocations between the get_memory_map() call and the * exit_boot_services() call, so the exiting of boot services is very tightly * tied to the creation of the FDT with the final memory map in it. */ static efi_status_t allocate_new_fdt_and_exit_boot(void *handle, efi_loaded_image_t *image, unsigned long *new_fdt_addr, char *cmdline_ptr) { unsigned long desc_size; u32 desc_ver; efi_status_t status; struct exit_boot_struct priv; unsigned long fdt_addr = 0; unsigned long fdt_size = 0; if (!efi_novamap) { status = efi_alloc_virtmap(&priv.runtime_map, &desc_size, &desc_ver); if (status != EFI_SUCCESS) { efi_err("Unable to retrieve UEFI memory map.\n"); return status; } } /* * Unauthenticated device tree data is a security hazard, so ignore * 'dtb=' unless UEFI Secure Boot is disabled. We assume that secure * boot is enabled if we can't determine its state. */ if (!IS_ENABLED(CONFIG_EFI_ARMSTUB_DTB_LOADER) || efi_get_secureboot() != efi_secureboot_mode_disabled) { if (strstr(cmdline_ptr, "dtb=")) efi_err("Ignoring DTB from command line.\n"); } else { status = efi_load_dtb(image, &fdt_addr, &fdt_size); if (status != EFI_SUCCESS && status != EFI_NOT_READY) { efi_err("Failed to load device tree!\n"); goto fail; } } if (fdt_addr) { efi_info("Using DTB from command line\n"); } else { /* Look for a device tree configuration table entry. */ fdt_addr = (uintptr_t)get_fdt(&fdt_size); if (fdt_addr) efi_info("Using DTB from configuration table\n"); } if (!fdt_addr) efi_info("Generating empty DTB\n"); efi_info("Exiting boot services...\n"); status = efi_allocate_pages(MAX_FDT_SIZE, new_fdt_addr, ULONG_MAX); if (status != EFI_SUCCESS) { efi_err("Unable to allocate memory for new device tree.\n"); goto fail; } status = update_fdt((void *)fdt_addr, fdt_size, (void *)*new_fdt_addr, MAX_FDT_SIZE, cmdline_ptr); if (status != EFI_SUCCESS) { efi_err("Unable to construct new device tree.\n"); goto fail_free_new_fdt; } priv.new_fdt_addr = (void *)*new_fdt_addr; status = efi_exit_boot_services(handle, &priv, exit_boot_func); if (status == EFI_SUCCESS) { efi_set_virtual_address_map_t *svam; if (efi_novamap) return EFI_SUCCESS; /* Install the new virtual address map */ svam = efi_system_table->runtime->set_virtual_address_map; status = svam(priv.runtime_entry_count * desc_size, desc_size, desc_ver, priv.runtime_map); /* * We are beyond the point of no return here, so if the call to * SetVirtualAddressMap() failed, we need to signal that to the * incoming kernel but proceed normally otherwise. */ if (status != EFI_SUCCESS) { efi_memory_desc_t *p; int l; /* * Set the virtual address field of all * EFI_MEMORY_RUNTIME entries to U64_MAX. This will * signal the incoming kernel that no virtual * translation has been installed. */ for (l = 0; l < priv.boot_memmap->map_size; l += priv.boot_memmap->desc_size) { p = (void *)priv.boot_memmap->map + l; if (p->attribute & EFI_MEMORY_RUNTIME) p->virt_addr = U64_MAX; } } return EFI_SUCCESS; } efi_err("Exit boot services failed.\n"); fail_free_new_fdt: efi_free(MAX_FDT_SIZE, *new_fdt_addr); fail: efi_free(fdt_size, fdt_addr); efi_bs_call(free_pool, priv.runtime_map); return EFI_LOAD_ERROR; } efi_status_t efi_boot_kernel(void *handle, efi_loaded_image_t *image, unsigned long kernel_addr, char *cmdline_ptr) { unsigned long fdt_addr; efi_status_t status; status = allocate_new_fdt_and_exit_boot(handle, image, &fdt_addr, cmdline_ptr); if (status != EFI_SUCCESS) { efi_err("Failed to update FDT and exit boot services\n"); return status; } if (IS_ENABLED(CONFIG_ARM)) efi_handle_post_ebs_state(); efi_enter_kernel(kernel_addr, fdt_addr, fdt_totalsize((void *)fdt_addr)); /* not reached */ } void *get_fdt(unsigned long *fdt_size) { void *fdt; fdt = get_efi_config_table(DEVICE_TREE_GUID); if (!fdt) return NULL; if (fdt_check_header(fdt) != 0) { efi_err("Invalid header detected on UEFI supplied FDT, ignoring ...\n"); return NULL; } *fdt_size = fdt_totalsize(fdt); return fdt; }
linux-master
drivers/firmware/efi/libstub/fdt.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/efi.h> #include <asm/efi.h> #include "efistub.h" /** * efi_low_alloc_above() - allocate pages at or above given address * @size: size of the memory area to allocate * @align: minimum alignment of the allocated memory area. It should * a power of two. * @addr: on exit the address of the allocated memory * @min: minimum address to used for the memory allocation * * Allocate at the lowest possible address that is not below @min as * EFI_LOADER_DATA. The allocated pages are aligned according to @align but at * least EFI_ALLOC_ALIGN. The first allocated page will not below the address * given by @min. * * Return: status code */ efi_status_t efi_low_alloc_above(unsigned long size, unsigned long align, unsigned long *addr, unsigned long min) { struct efi_boot_memmap *map; efi_status_t status; unsigned long nr_pages; int i; status = efi_get_memory_map(&map, false); if (status != EFI_SUCCESS) goto fail; /* * Enforce minimum alignment that EFI or Linux requires when * requesting a specific address. We are doing page-based (or * larger) allocations, and both the address and size must meet * alignment constraints. */ if (align < EFI_ALLOC_ALIGN) align = EFI_ALLOC_ALIGN; size = round_up(size, EFI_ALLOC_ALIGN); nr_pages = size / EFI_PAGE_SIZE; for (i = 0; i < map->map_size / map->desc_size; i++) { efi_memory_desc_t *desc; unsigned long m = (unsigned long)map->map; u64 start, end; desc = efi_early_memdesc_ptr(m, map->desc_size, i); if (desc->type != EFI_CONVENTIONAL_MEMORY) continue; if (efi_soft_reserve_enabled() && (desc->attribute & EFI_MEMORY_SP)) continue; if (desc->num_pages < nr_pages) continue; start = desc->phys_addr; end = start + desc->num_pages * EFI_PAGE_SIZE; if (start < min) start = min; start = round_up(start, align); if ((start + size) > end) continue; status = efi_bs_call(allocate_pages, EFI_ALLOCATE_ADDRESS, EFI_LOADER_DATA, nr_pages, &start); if (status == EFI_SUCCESS) { *addr = start; break; } } if (i == map->map_size / map->desc_size) status = EFI_NOT_FOUND; efi_bs_call(free_pool, map); fail: return status; } /** * efi_relocate_kernel() - copy memory area * @image_addr: pointer to address of memory area to copy * @image_size: size of memory area to copy * @alloc_size: minimum size of memory to allocate, must be greater or * equal to image_size * @preferred_addr: preferred target address * @alignment: minimum alignment of the allocated memory area. It * should be a power of two. * @min_addr: minimum target address * * Copy a memory area to a newly allocated memory area aligned according * to @alignment but at least EFI_ALLOC_ALIGN. If the preferred address * is not available, the allocated address will not be below @min_addr. * On exit, @image_addr is updated to the target copy address that was used. * * This function is used to copy the Linux kernel verbatim. It does not apply * any relocation changes. * * Return: status code */ efi_status_t efi_relocate_kernel(unsigned long *image_addr, unsigned long image_size, unsigned long alloc_size, unsigned long preferred_addr, unsigned long alignment, unsigned long min_addr) { unsigned long cur_image_addr; unsigned long new_addr = 0; efi_status_t status; unsigned long nr_pages; efi_physical_addr_t efi_addr = preferred_addr; if (!image_addr || !image_size || !alloc_size) return EFI_INVALID_PARAMETER; if (alloc_size < image_size) return EFI_INVALID_PARAMETER; cur_image_addr = *image_addr; /* * The EFI firmware loader could have placed the kernel image * anywhere in memory, but the kernel has restrictions on the * max physical address it can run at. Some architectures * also have a preferred address, so first try to relocate * to the preferred address. If that fails, allocate as low * as possible while respecting the required alignment. */ nr_pages = round_up(alloc_size, EFI_ALLOC_ALIGN) / EFI_PAGE_SIZE; status = efi_bs_call(allocate_pages, EFI_ALLOCATE_ADDRESS, EFI_LOADER_DATA, nr_pages, &efi_addr); new_addr = efi_addr; /* * If preferred address allocation failed allocate as low as * possible. */ if (status != EFI_SUCCESS) { status = efi_low_alloc_above(alloc_size, alignment, &new_addr, min_addr); } if (status != EFI_SUCCESS) { efi_err("Failed to allocate usable memory for kernel.\n"); return status; } /* * We know source/dest won't overlap since both memory ranges * have been allocated by UEFI, so we can safely use memcpy. */ memcpy((void *)new_addr, (void *)cur_image_addr, image_size); /* Return the new address of the relocated image. */ *image_addr = new_addr; return status; }
linux-master
drivers/firmware/efi/libstub/relocate.c
// SPDX-License-Identifier: GPL-2.0 /* * Author: Yun Liu <[email protected]> * Huacai Chen <[email protected]> * Copyright (C) 2020-2022 Loongson Technology Corporation Limited */ #include <asm/efi.h> #include <asm/addrspace.h> #include "efistub.h" typedef void __noreturn (*kernel_entry_t)(bool efi, unsigned long cmdline, unsigned long systab); efi_status_t check_platform_features(void) { return EFI_SUCCESS; } struct exit_boot_struct { efi_memory_desc_t *runtime_map; int runtime_entry_count; }; static efi_status_t exit_boot_func(struct efi_boot_memmap *map, void *priv) { struct exit_boot_struct *p = priv; /* * Update the memory map with virtual addresses. The function will also * populate @runtime_map with copies of just the EFI_MEMORY_RUNTIME * entries so that we can pass it straight to SetVirtualAddressMap() */ efi_get_virtmap(map->map, map->map_size, map->desc_size, p->runtime_map, &p->runtime_entry_count); return EFI_SUCCESS; } unsigned long __weak kernel_entry_address(void) { return *(unsigned long *)(PHYSADDR(VMLINUX_LOAD_ADDRESS) + 8); } efi_status_t efi_boot_kernel(void *handle, efi_loaded_image_t *image, unsigned long kernel_addr, char *cmdline_ptr) { kernel_entry_t real_kernel_entry; struct exit_boot_struct priv; unsigned long desc_size; efi_status_t status; u32 desc_ver; status = efi_alloc_virtmap(&priv.runtime_map, &desc_size, &desc_ver); if (status != EFI_SUCCESS) { efi_err("Unable to retrieve UEFI memory map.\n"); return status; } efi_info("Exiting boot services\n"); efi_novamap = false; status = efi_exit_boot_services(handle, &priv, exit_boot_func); if (status != EFI_SUCCESS) return status; /* Install the new virtual address map */ efi_rt_call(set_virtual_address_map, priv.runtime_entry_count * desc_size, desc_size, desc_ver, priv.runtime_map); /* Config Direct Mapping */ csr_write64(CSR_DMW0_INIT, LOONGARCH_CSR_DMWIN0); csr_write64(CSR_DMW1_INIT, LOONGARCH_CSR_DMWIN1); real_kernel_entry = (void *)kernel_entry_address(); real_kernel_entry(true, (unsigned long)cmdline_ptr, (unsigned long)efi_system_table); }
linux-master
drivers/firmware/efi/libstub/loongarch.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2020 Western Digital Corporation or its affiliates. */ #include <linux/efi.h> #include <asm/efi.h> #include <asm/sections.h> #include <asm/unaligned.h> #include "efistub.h" unsigned long stext_offset(void) { /* * When built as part of the kernel, the EFI stub cannot branch to the * kernel proper via the image header, as the PE/COFF header is * strictly not part of the in-memory presentation of the image, only * of the file representation. So instead, we need to jump to the * actual entrypoint in the .text region of the image. */ return _start_kernel - _start; } efi_status_t handle_kernel_image(unsigned long *image_addr, unsigned long *image_size, unsigned long *reserve_addr, unsigned long *reserve_size, efi_loaded_image_t *image, efi_handle_t image_handle) { unsigned long kernel_size, kernel_codesize, kernel_memsize; efi_status_t status; kernel_size = _edata - _start; kernel_codesize = __init_text_end - _start; kernel_memsize = kernel_size + (_end - _edata); *image_addr = (unsigned long)_start; *image_size = kernel_memsize; *reserve_size = *image_size; status = efi_kaslr_relocate_kernel(image_addr, reserve_addr, reserve_size, kernel_size, kernel_codesize, kernel_memsize, efi_kaslr_get_phys_seed(image_handle)); if (status != EFI_SUCCESS) { efi_err("Failed to relocate kernel\n"); *image_size = 0; } return status; } void efi_icache_sync(unsigned long start, unsigned long end) { asm volatile ("fence.i" ::: "memory"); }
linux-master
drivers/firmware/efi/libstub/riscv-stub.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/stdarg.h> #include <linux/ctype.h> #include <linux/efi.h> #include <linux/kernel.h> #include <linux/printk.h> /* For CONSOLE_LOGLEVEL_* */ #include <asm/efi.h> #include <asm/setup.h> #include "efistub.h" int efi_loglevel = CONSOLE_LOGLEVEL_DEFAULT; /** * efi_char16_puts() - Write a UCS-2 encoded string to the console * @str: UCS-2 encoded string */ void efi_char16_puts(efi_char16_t *str) { efi_call_proto(efi_table_attr(efi_system_table, con_out), output_string, str); } static u32 utf8_to_utf32(const u8 **s8) { u32 c32; u8 c0, cx; size_t clen, i; c0 = cx = *(*s8)++; /* * The position of the most-significant 0 bit gives us the length of * a multi-octet encoding. */ for (clen = 0; cx & 0x80; ++clen) cx <<= 1; /* * If the 0 bit is in position 8, this is a valid single-octet * encoding. If the 0 bit is in position 7 or positions 1-3, the * encoding is invalid. * In either case, we just return the first octet. */ if (clen < 2 || clen > 4) return c0; /* Get the bits from the first octet. */ c32 = cx >> clen--; for (i = 0; i < clen; ++i) { /* Trailing octets must have 10 in most significant bits. */ cx = (*s8)[i] ^ 0x80; if (cx & 0xc0) return c0; c32 = (c32 << 6) | cx; } /* * Check for validity: * - The character must be in the Unicode range. * - It must not be a surrogate. * - It must be encoded using the correct number of octets. */ if (c32 > 0x10ffff || (c32 & 0xf800) == 0xd800 || clen != (c32 >= 0x80) + (c32 >= 0x800) + (c32 >= 0x10000)) return c0; *s8 += clen; return c32; } /** * efi_puts() - Write a UTF-8 encoded string to the console * @str: UTF-8 encoded string */ void efi_puts(const char *str) { efi_char16_t buf[128]; size_t pos = 0, lim = ARRAY_SIZE(buf); const u8 *s8 = (const u8 *)str; u32 c32; while (*s8) { if (*s8 == '\n') buf[pos++] = L'\r'; c32 = utf8_to_utf32(&s8); if (c32 < 0x10000) { /* Characters in plane 0 use a single word. */ buf[pos++] = c32; } else { /* * Characters in other planes encode into a surrogate * pair. */ buf[pos++] = (0xd800 - (0x10000 >> 10)) + (c32 >> 10); buf[pos++] = 0xdc00 + (c32 & 0x3ff); } if (*s8 == '\0' || pos >= lim - 2) { buf[pos] = L'\0'; efi_char16_puts(buf); pos = 0; } } } /** * efi_printk() - Print a kernel message * @fmt: format string * * The first letter of the format string is used to determine the logging level * of the message. If the level is less then the current EFI logging level, the * message is suppressed. The message will be truncated to 255 bytes. * * Return: number of printed characters */ int efi_printk(const char *fmt, ...) { char printf_buf[256]; va_list args; int printed; int loglevel = printk_get_level(fmt); switch (loglevel) { case '0' ... '9': loglevel -= '0'; break; default: /* * Use loglevel -1 for cases where we just want to print to * the screen. */ loglevel = -1; break; } if (loglevel >= efi_loglevel) return 0; if (loglevel >= 0) efi_puts("EFI stub: "); fmt = printk_skip_level(fmt); va_start(args, fmt); printed = vsnprintf(printf_buf, sizeof(printf_buf), fmt, args); va_end(args); efi_puts(printf_buf); if (printed >= sizeof(printf_buf)) { efi_puts("[Message truncated]\n"); return -1; } return printed; }
linux-master
drivers/firmware/efi/libstub/printk.c
// SPDX-License-Identifier: GPL-2.0-only // Copyright 2022 Google LLC // Author: Ard Biesheuvel <[email protected]> #include <linux/efi.h> #include "efistub.h" typedef struct efi_smbios_protocol efi_smbios_protocol_t; struct efi_smbios_protocol { efi_status_t (__efiapi *add)(efi_smbios_protocol_t *, efi_handle_t, u16 *, struct efi_smbios_record *); efi_status_t (__efiapi *update_string)(efi_smbios_protocol_t *, u16 *, unsigned long *, u8 *); efi_status_t (__efiapi *remove)(efi_smbios_protocol_t *, u16); efi_status_t (__efiapi *get_next)(efi_smbios_protocol_t *, u16 *, u8 *, struct efi_smbios_record **, efi_handle_t *); u8 major_version; u8 minor_version; }; const struct efi_smbios_record *efi_get_smbios_record(u8 type) { struct efi_smbios_record *record; efi_smbios_protocol_t *smbios; efi_status_t status; u16 handle = 0xfffe; status = efi_bs_call(locate_protocol, &EFI_SMBIOS_PROTOCOL_GUID, NULL, (void **)&smbios) ?: efi_call_proto(smbios, get_next, &handle, &type, &record, NULL); if (status != EFI_SUCCESS) return NULL; return record; } const u8 *__efi_get_smbios_string(const struct efi_smbios_record *record, u8 type, int offset) { const u8 *strtable; if (!record) return NULL; strtable = (u8 *)record + record->length; for (int i = 1; i < ((u8 *)record)[offset]; i++) { int len = strlen(strtable); if (!len) return NULL; strtable += len + 1; } return strtable; }
linux-master
drivers/firmware/efi/libstub/smbios.c
// SPDX-License-Identifier: GPL-2.0-only /* -*- linux-c -*- ------------------------------------------------------- * * * Copyright (C) 1991, 1992 Linus Torvalds * Copyright 2007 rPath, Inc. - All Rights Reserved * * ----------------------------------------------------------------------- */ /* * Oh, it's a waste of space, but oh-so-yummy for debugging. */ #include <linux/stdarg.h> #include <linux/compiler.h> #include <linux/ctype.h> #include <linux/kernel.h> #include <linux/limits.h> #include <linux/string.h> #include <linux/types.h> static int skip_atoi(const char **s) { int i = 0; while (isdigit(**s)) i = i * 10 + *((*s)++) - '0'; return i; } /* * put_dec_full4 handles numbers in the range 0 <= r < 10000. * The multiplier 0xccd is round(2^15/10), and the approximation * r/10 == (r * 0xccd) >> 15 is exact for all r < 16389. */ static void put_dec_full4(char *end, unsigned int r) { int i; for (i = 0; i < 3; i++) { unsigned int q = (r * 0xccd) >> 15; *--end = '0' + (r - q * 10); r = q; } *--end = '0' + r; } /* put_dec is copied from lib/vsprintf.c with small modifications */ /* * Call put_dec_full4 on x % 10000, return x / 10000. * The approximation x/10000 == (x * 0x346DC5D7) >> 43 * holds for all x < 1,128,869,999. The largest value this * helper will ever be asked to convert is 1,125,520,955. * (second call in the put_dec code, assuming n is all-ones). */ static unsigned int put_dec_helper4(char *end, unsigned int x) { unsigned int q = (x * 0x346DC5D7ULL) >> 43; put_dec_full4(end, x - q * 10000); return q; } /* Based on code by Douglas W. Jones found at * <http://www.cs.uiowa.edu/~jones/bcd/decimal.html#sixtyfour> * (with permission from the author). * Performs no 64-bit division and hence should be fast on 32-bit machines. */ static char *put_dec(char *end, unsigned long long n) { unsigned int d3, d2, d1, q, h; char *p = end; d1 = ((unsigned int)n >> 16); /* implicit "& 0xffff" */ h = (n >> 32); d2 = (h ) & 0xffff; d3 = (h >> 16); /* implicit "& 0xffff" */ /* n = 2^48 d3 + 2^32 d2 + 2^16 d1 + d0 = 281_4749_7671_0656 d3 + 42_9496_7296 d2 + 6_5536 d1 + d0 */ q = 656 * d3 + 7296 * d2 + 5536 * d1 + ((unsigned int)n & 0xffff); q = put_dec_helper4(p, q); p -= 4; q += 7671 * d3 + 9496 * d2 + 6 * d1; q = put_dec_helper4(p, q); p -= 4; q += 4749 * d3 + 42 * d2; q = put_dec_helper4(p, q); p -= 4; q += 281 * d3; q = put_dec_helper4(p, q); p -= 4; put_dec_full4(p, q); p -= 4; /* strip off the extra 0's we printed */ while (p < end && *p == '0') ++p; return p; } static char *number(char *end, unsigned long long num, int base, char locase) { /* * locase = 0 or 0x20. ORing digits or letters with 'locase' * produces same digits or (maybe lowercased) letters */ /* we are called with base 8, 10 or 16, only, thus don't need "G..." */ static const char digits[16] = "0123456789ABCDEF"; /* "GHIJKLMNOPQRSTUVWXYZ"; */ switch (base) { case 10: if (num != 0) end = put_dec(end, num); break; case 8: for (; num != 0; num >>= 3) *--end = '0' + (num & 07); break; case 16: for (; num != 0; num >>= 4) *--end = digits[num & 0xf] | locase; break; default: unreachable(); } return end; } #define ZEROPAD 1 /* pad with zero */ #define SIGN 2 /* unsigned/signed long */ #define PLUS 4 /* show plus */ #define SPACE 8 /* space if plus */ #define LEFT 16 /* left justified */ #define SMALL 32 /* Must be 32 == 0x20 */ #define SPECIAL 64 /* 0x */ #define WIDE 128 /* UTF-16 string */ static int get_flags(const char **fmt) { int flags = 0; do { switch (**fmt) { case '-': flags |= LEFT; break; case '+': flags |= PLUS; break; case ' ': flags |= SPACE; break; case '#': flags |= SPECIAL; break; case '0': flags |= ZEROPAD; break; default: return flags; } ++(*fmt); } while (1); } static int get_int(const char **fmt, va_list *ap) { if (isdigit(**fmt)) return skip_atoi(fmt); if (**fmt == '*') { ++(*fmt); /* it's the next argument */ return va_arg(*ap, int); } return 0; } static unsigned long long get_number(int sign, int qualifier, va_list *ap) { if (sign) { switch (qualifier) { case 'L': return va_arg(*ap, long long); case 'l': return va_arg(*ap, long); case 'h': return (short)va_arg(*ap, int); case 'H': return (signed char)va_arg(*ap, int); default: return va_arg(*ap, int); }; } else { switch (qualifier) { case 'L': return va_arg(*ap, unsigned long long); case 'l': return va_arg(*ap, unsigned long); case 'h': return (unsigned short)va_arg(*ap, int); case 'H': return (unsigned char)va_arg(*ap, int); default: return va_arg(*ap, unsigned int); } } } static char get_sign(long long *num, int flags) { if (!(flags & SIGN)) return 0; if (*num < 0) { *num = -(*num); return '-'; } if (flags & PLUS) return '+'; if (flags & SPACE) return ' '; return 0; } static size_t utf16s_utf8nlen(const u16 *s16, size_t maxlen) { size_t len, clen; for (len = 0; len < maxlen && *s16; len += clen) { u16 c0 = *s16++; /* First, get the length for a BMP character */ clen = 1 + (c0 >= 0x80) + (c0 >= 0x800); if (len + clen > maxlen) break; /* * If this is a high surrogate, and we're already at maxlen, we * can't include the character if it's a valid surrogate pair. * Avoid accessing one extra word just to check if it's valid * or not. */ if ((c0 & 0xfc00) == 0xd800) { if (len + clen == maxlen) break; if ((*s16 & 0xfc00) == 0xdc00) { ++s16; ++clen; } } } return len; } static u32 utf16_to_utf32(const u16 **s16) { u16 c0, c1; c0 = *(*s16)++; /* not a surrogate */ if ((c0 & 0xf800) != 0xd800) return c0; /* invalid: low surrogate instead of high */ if (c0 & 0x0400) return 0xfffd; c1 = **s16; /* invalid: missing low surrogate */ if ((c1 & 0xfc00) != 0xdc00) return 0xfffd; /* valid surrogate pair */ ++(*s16); return (0x10000 - (0xd800 << 10) - 0xdc00) + (c0 << 10) + c1; } #define PUTC(c) \ do { \ if (pos < size) \ buf[pos] = (c); \ ++pos; \ } while (0); int vsnprintf(char *buf, size_t size, const char *fmt, va_list ap) { /* The maximum space required is to print a 64-bit number in octal */ char tmp[(sizeof(unsigned long long) * 8 + 2) / 3]; char *tmp_end = &tmp[ARRAY_SIZE(tmp)]; long long num; int base; const char *s; size_t len, pos; char sign; int flags; /* flags to number() */ int field_width; /* width of output field */ int precision; /* min. # of digits for integers; max number of chars for from string */ int qualifier; /* 'h', 'hh', 'l' or 'll' for integer fields */ va_list args; /* * We want to pass our input va_list to helper functions by reference, * but there's an annoying edge case. If va_list was originally passed * to us by value, we could just pass &ap down to the helpers. This is * the case on, for example, X86_32. * However, on X86_64 (and possibly others), va_list is actually a * size-1 array containing a structure. Our function parameter ap has * decayed from T[1] to T*, and &ap has type T** rather than T(*)[1], * which is what will be expected by a function taking a va_list * * parameter. * One standard way to solve this mess is by creating a copy in a local * variable of type va_list and then passing a pointer to that local * copy instead, which is what we do here. */ va_copy(args, ap); for (pos = 0; *fmt; ++fmt) { if (*fmt != '%' || *++fmt == '%') { PUTC(*fmt); continue; } /* process flags */ flags = get_flags(&fmt); /* get field width */ field_width = get_int(&fmt, &args); if (field_width < 0) { field_width = -field_width; flags |= LEFT; } if (flags & LEFT) flags &= ~ZEROPAD; /* get the precision */ precision = -1; if (*fmt == '.') { ++fmt; precision = get_int(&fmt, &args); if (precision >= 0) flags &= ~ZEROPAD; } /* get the conversion qualifier */ qualifier = -1; if (*fmt == 'h' || *fmt == 'l') { qualifier = *fmt; ++fmt; if (qualifier == *fmt) { qualifier -= 'a'-'A'; ++fmt; } } sign = 0; switch (*fmt) { case 'c': flags &= LEFT; s = tmp; if (qualifier == 'l') { ((u16 *)tmp)[0] = (u16)va_arg(args, unsigned int); ((u16 *)tmp)[1] = L'\0'; precision = INT_MAX; goto wstring; } else { tmp[0] = (unsigned char)va_arg(args, int); precision = len = 1; } goto output; case 's': flags &= LEFT; if (precision < 0) precision = INT_MAX; s = va_arg(args, void *); if (!s) s = precision < 6 ? "" : "(null)"; else if (qualifier == 'l') { wstring: flags |= WIDE; precision = len = utf16s_utf8nlen((const u16 *)s, precision); goto output; } precision = len = strnlen(s, precision); goto output; /* integer number formats - set up the flags and "break" */ case 'o': base = 8; break; case 'p': if (precision < 0) precision = 2 * sizeof(void *); fallthrough; case 'x': flags |= SMALL; fallthrough; case 'X': base = 16; break; case 'd': case 'i': flags |= SIGN; fallthrough; case 'u': flags &= ~SPECIAL; base = 10; break; default: /* * Bail out if the conversion specifier is invalid. * There's probably a typo in the format string and the * remaining specifiers are unlikely to match up with * the arguments. */ goto fail; } if (*fmt == 'p') { num = (unsigned long)va_arg(args, void *); } else { num = get_number(flags & SIGN, qualifier, &args); } sign = get_sign(&num, flags); if (sign) --field_width; s = number(tmp_end, num, base, flags & SMALL); len = tmp_end - s; /* default precision is 1 */ if (precision < 0) precision = 1; /* precision is minimum number of digits to print */ if (precision < len) precision = len; if (flags & SPECIAL) { /* * For octal, a leading 0 is printed only if necessary, * i.e. if it's not already there because of the * precision. */ if (base == 8 && precision == len) ++precision; /* * For hexadecimal, the leading 0x is skipped if the * output is empty, i.e. both the number and the * precision are 0. */ if (base == 16 && precision > 0) field_width -= 2; else flags &= ~SPECIAL; } /* * For zero padding, increase the precision to fill the field * width. */ if ((flags & ZEROPAD) && field_width > precision) precision = field_width; output: /* Calculate the padding necessary */ field_width -= precision; /* Leading padding with ' ' */ if (!(flags & LEFT)) while (field_width-- > 0) PUTC(' '); /* sign */ if (sign) PUTC(sign); /* 0x/0X for hexadecimal */ if (flags & SPECIAL) { PUTC('0'); PUTC( 'X' | (flags & SMALL)); } /* Zero padding and excess precision */ while (precision-- > len) PUTC('0'); /* Actual output */ if (flags & WIDE) { const u16 *ws = (const u16 *)s; while (len-- > 0) { u32 c32 = utf16_to_utf32(&ws); u8 *s8; size_t clen; if (c32 < 0x80) { PUTC(c32); continue; } /* Number of trailing octets */ clen = 1 + (c32 >= 0x800) + (c32 >= 0x10000); len -= clen; s8 = (u8 *)&buf[pos]; /* Avoid writing partial character */ PUTC('\0'); pos += clen; if (pos >= size) continue; /* Set high bits of leading octet */ *s8 = (0xf00 >> 1) >> clen; /* Write trailing octets in reverse order */ for (s8 += clen; clen; --clen, c32 >>= 6) *s8-- = 0x80 | (c32 & 0x3f); /* Set low bits of leading octet */ *s8 |= c32; } } else { while (len-- > 0) PUTC(*s++); } /* Trailing padding with ' ' */ while (field_width-- > 0) PUTC(' '); } fail: va_end(args); if (size) buf[min(pos, size-1)] = '\0'; return pos; } int snprintf(char *buf, size_t size, const char *fmt, ...) { va_list args; int i; va_start(args, fmt); i = vsnprintf(buf, size, fmt, args); va_end(args); return i; }
linux-master
drivers/firmware/efi/libstub/vsprintf.c
// SPDX-License-Identifier: GPL-2.0 /* * Taken from: * linux/lib/string.c * * Copyright (C) 1991, 1992 Linus Torvalds */ #include <linux/ctype.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/string.h> #ifndef EFI_HAVE_STRLEN /** * strlen - Find the length of a string * @s: The string to be sized */ size_t strlen(const char *s) { const char *sc; for (sc = s; *sc != '\0'; ++sc) /* nothing */; return sc - s; } #endif #ifndef EFI_HAVE_STRNLEN /** * strnlen - Find the length of a length-limited string * @s: The string to be sized * @count: The maximum number of bytes to search */ size_t strnlen(const char *s, size_t count) { const char *sc; for (sc = s; count-- && *sc != '\0'; ++sc) /* nothing */; return sc - s; } #endif /** * strstr - Find the first substring in a %NUL terminated string * @s1: The string to be searched * @s2: The string to search for */ char *strstr(const char *s1, const char *s2) { size_t l1, l2; l2 = strlen(s2); if (!l2) return (char *)s1; l1 = strlen(s1); while (l1 >= l2) { l1--; if (!memcmp(s1, s2, l2)) return (char *)s1; s1++; } return NULL; } #ifndef EFI_HAVE_STRCMP /** * strcmp - Compare two strings * @cs: One string * @ct: Another string */ int strcmp(const char *cs, const char *ct) { unsigned char c1, c2; while (1) { c1 = *cs++; c2 = *ct++; if (c1 != c2) return c1 < c2 ? -1 : 1; if (!c1) break; } return 0; } #endif /** * strncmp - Compare two length-limited strings * @cs: One string * @ct: Another string * @count: The maximum number of bytes to compare */ int strncmp(const char *cs, const char *ct, size_t count) { unsigned char c1, c2; while (count) { c1 = *cs++; c2 = *ct++; if (c1 != c2) return c1 < c2 ? -1 : 1; if (!c1) break; count--; } return 0; } /* Works only for digits and letters, but small and fast */ #define TOLOWER(x) ((x) | 0x20) static unsigned int simple_guess_base(const char *cp) { if (cp[0] == '0') { if (TOLOWER(cp[1]) == 'x' && isxdigit(cp[2])) return 16; else return 8; } else { return 10; } } /** * simple_strtoull - convert a string to an unsigned long long * @cp: The start of the string * @endp: A pointer to the end of the parsed string will be placed here * @base: The number base to use */ unsigned long long simple_strtoull(const char *cp, char **endp, unsigned int base) { unsigned long long result = 0; if (!base) base = simple_guess_base(cp); if (base == 16 && cp[0] == '0' && TOLOWER(cp[1]) == 'x') cp += 2; while (isxdigit(*cp)) { unsigned int value; value = isdigit(*cp) ? *cp - '0' : TOLOWER(*cp) - 'a' + 10; if (value >= base) break; result = result * base + value; cp++; } if (endp) *endp = (char *)cp; return result; } long simple_strtol(const char *cp, char **endp, unsigned int base) { if (*cp == '-') return -simple_strtoull(cp + 1, endp, base); return simple_strtoull(cp, endp, base); } #ifdef CONFIG_EFI_PARAMS_FROM_FDT #ifndef EFI_HAVE_STRRCHR /** * strrchr - Find the last occurrence of a character in a string * @s: The string to be searched * @c: The character to search for */ char *strrchr(const char *s, int c) { const char *last = NULL; do { if (*s == (char)c) last = s; } while (*s++); return (char *)last; } #endif #ifndef EFI_HAVE_MEMCHR /** * memchr - Find a character in an area of memory. * @s: The memory area * @c: The byte to search for * @n: The size of the area. * * returns the address of the first occurrence of @c, or %NULL * if @c is not found */ void *memchr(const void *s, int c, size_t n) { const unsigned char *p = s; while (n-- != 0) { if ((unsigned char)c == *p++) { return (void *)(p - 1); } } return NULL; } #endif #endif
linux-master
drivers/firmware/efi/libstub/string.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2016 Linaro Ltd; <[email protected]> */ #include <linux/efi.h> #include <asm/efi.h> #include "efistub.h" typedef union efi_rng_protocol efi_rng_protocol_t; union efi_rng_protocol { struct { efi_status_t (__efiapi *get_info)(efi_rng_protocol_t *, unsigned long *, efi_guid_t *); efi_status_t (__efiapi *get_rng)(efi_rng_protocol_t *, efi_guid_t *, unsigned long, u8 *out); }; struct { u32 get_info; u32 get_rng; } mixed_mode; }; /** * efi_get_random_bytes() - fill a buffer with random bytes * @size: size of the buffer * @out: caller allocated buffer to receive the random bytes * * The call will fail if either the firmware does not implement the * EFI_RNG_PROTOCOL or there are not enough random bytes available to fill * the buffer. * * Return: status code */ efi_status_t efi_get_random_bytes(unsigned long size, u8 *out) { efi_guid_t rng_proto = EFI_RNG_PROTOCOL_GUID; efi_status_t status; efi_rng_protocol_t *rng = NULL; status = efi_bs_call(locate_protocol, &rng_proto, NULL, (void **)&rng); if (status != EFI_SUCCESS) return status; return efi_call_proto(rng, get_rng, NULL, size, out); } /** * efi_random_get_seed() - provide random seed as configuration table * * The EFI_RNG_PROTOCOL is used to read random bytes. These random bytes are * saved as a configuration table which can be used as entropy by the kernel * for the initialization of its pseudo random number generator. * * If the EFI_RNG_PROTOCOL is not available or there are not enough random bytes * available, the configuration table will not be installed and an error code * will be returned. * * Return: status code */ efi_status_t efi_random_get_seed(void) { efi_guid_t rng_proto = EFI_RNG_PROTOCOL_GUID; efi_guid_t rng_algo_raw = EFI_RNG_ALGORITHM_RAW; efi_guid_t rng_table_guid = LINUX_EFI_RANDOM_SEED_TABLE_GUID; struct linux_efi_random_seed *prev_seed, *seed = NULL; int prev_seed_size = 0, seed_size = EFI_RANDOM_SEED_SIZE; unsigned long nv_seed_size = 0, offset = 0; efi_rng_protocol_t *rng = NULL; efi_status_t status; status = efi_bs_call(locate_protocol, &rng_proto, NULL, (void **)&rng); if (status != EFI_SUCCESS) seed_size = 0; // Call GetVariable() with a zero length buffer to obtain the size get_efi_var(L"RandomSeed", &rng_table_guid, NULL, &nv_seed_size, NULL); if (!seed_size && !nv_seed_size) return status; seed_size += nv_seed_size; /* * Check whether a seed was provided by a prior boot stage. In that * case, instead of overwriting it, let's create a new buffer that can * hold both, and concatenate the existing and the new seeds. * Note that we should read the seed size with caution, in case the * table got corrupted in memory somehow. */ prev_seed = get_efi_config_table(rng_table_guid); if (prev_seed && prev_seed->size <= 512U) { prev_seed_size = prev_seed->size; seed_size += prev_seed_size; } /* * Use EFI_ACPI_RECLAIM_MEMORY here so that it is guaranteed that the * allocation will survive a kexec reboot (although we refresh the seed * beforehand) */ status = efi_bs_call(allocate_pool, EFI_ACPI_RECLAIM_MEMORY, struct_size(seed, bits, seed_size), (void **)&seed); if (status != EFI_SUCCESS) { efi_warn("Failed to allocate memory for RNG seed.\n"); goto err_warn; } if (rng) { status = efi_call_proto(rng, get_rng, &rng_algo_raw, EFI_RANDOM_SEED_SIZE, seed->bits); if (status == EFI_UNSUPPORTED) /* * Use whatever algorithm we have available if the raw algorithm * is not implemented. */ status = efi_call_proto(rng, get_rng, NULL, EFI_RANDOM_SEED_SIZE, seed->bits); if (status == EFI_SUCCESS) offset = EFI_RANDOM_SEED_SIZE; } if (nv_seed_size) { status = get_efi_var(L"RandomSeed", &rng_table_guid, NULL, &nv_seed_size, seed->bits + offset); if (status == EFI_SUCCESS) /* * We delete the seed here, and /hope/ that this causes * EFI to also zero out its representation on disk. * This is somewhat idealistic, but overwriting the * variable with zeros is likely just as fraught too. * TODO: in the future, maybe we can hash it forward * instead, and write a new seed. */ status = set_efi_var(L"RandomSeed", &rng_table_guid, 0, 0, NULL); if (status == EFI_SUCCESS) offset += nv_seed_size; else memzero_explicit(seed->bits + offset, nv_seed_size); } if (!offset) goto err_freepool; if (prev_seed_size) { memcpy(seed->bits + offset, prev_seed->bits, prev_seed_size); offset += prev_seed_size; } seed->size = offset; status = efi_bs_call(install_configuration_table, &rng_table_guid, seed); if (status != EFI_SUCCESS) goto err_freepool; if (prev_seed_size) { /* wipe and free the old seed if we managed to install the new one */ memzero_explicit(prev_seed->bits, prev_seed_size); efi_bs_call(free_pool, prev_seed); } return EFI_SUCCESS; err_freepool: memzero_explicit(seed, struct_size(seed, bits, seed_size)); efi_bs_call(free_pool, seed); efi_warn("Failed to obtain seed from EFI_RNG_PROTOCOL or EFI variable\n"); err_warn: if (prev_seed) efi_warn("Retaining bootloader-supplied seed only"); return status; }
linux-master
drivers/firmware/efi/libstub/random.c
// SPDX-License-Identifier: GPL-2.0 /* * Author: Yun Liu <[email protected]> * Huacai Chen <[email protected]> * Copyright (C) 2020-2022 Loongson Technology Corporation Limited */ #include <asm/efi.h> #include <asm/addrspace.h> #include "efistub.h" extern int kernel_asize; extern int kernel_fsize; extern int kernel_offset; extern int kernel_entry; efi_status_t handle_kernel_image(unsigned long *image_addr, unsigned long *image_size, unsigned long *reserve_addr, unsigned long *reserve_size, efi_loaded_image_t *image, efi_handle_t image_handle) { efi_status_t status; unsigned long kernel_addr = 0; kernel_addr = (unsigned long)&kernel_offset - kernel_offset; status = efi_relocate_kernel(&kernel_addr, kernel_fsize, kernel_asize, EFI_KIMG_PREFERRED_ADDRESS, efi_get_kimg_min_align(), 0x0); *image_addr = kernel_addr; *image_size = kernel_asize; return status; } unsigned long kernel_entry_address(void) { unsigned long base = (unsigned long)&kernel_offset - kernel_offset; return (unsigned long)&kernel_entry - base + VMLINUX_LOAD_ADDRESS; }
linux-master
drivers/firmware/efi/libstub/loongarch-stub.c
// SPDX-License-Identifier: GPL-2.0-only /* * EFI stub implementation that is shared by arm and arm64 architectures. * This should be #included by the EFI stub implementation files. * * Copyright (C) 2013,2014 Linaro Limited * Roy Franz <[email protected] * Copyright (C) 2013 Red Hat, Inc. * Mark Salter <[email protected]> */ #include <linux/efi.h> #include <asm/efi.h> #include "efistub.h" /* * This is the base address at which to start allocating virtual memory ranges * for UEFI Runtime Services. * * For ARM/ARM64: * This is in the low TTBR0 range so that we can use * any allocation we choose, and eliminate the risk of a conflict after kexec. * The value chosen is the largest non-zero power of 2 suitable for this purpose * both on 32-bit and 64-bit ARM CPUs, to maximize the likelihood that it can * be mapped efficiently. * Since 32-bit ARM could potentially execute with a 1G/3G user/kernel split, * map everything below 1 GB. (512 MB is a reasonable upper bound for the * entire footprint of the UEFI runtime services memory regions) * * For RISC-V: * There is no specific reason for which, this address (512MB) can't be used * EFI runtime virtual address for RISC-V. It also helps to use EFI runtime * services on both RV32/RV64. Keep the same runtime virtual address for RISC-V * as well to minimize the code churn. */ #define EFI_RT_VIRTUAL_BASE SZ_512M /* * Some architectures map the EFI regions into the kernel's linear map using a * fixed offset. */ #ifndef EFI_RT_VIRTUAL_OFFSET #define EFI_RT_VIRTUAL_OFFSET 0 #endif static u64 virtmap_base = EFI_RT_VIRTUAL_BASE; static bool flat_va_mapping = (EFI_RT_VIRTUAL_OFFSET != 0); void __weak free_screen_info(struct screen_info *si) { } static struct screen_info *setup_graphics(void) { efi_guid_t gop_proto = EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID; efi_status_t status; unsigned long size; void **gop_handle = NULL; struct screen_info *si = NULL; size = 0; status = efi_bs_call(locate_handle, EFI_LOCATE_BY_PROTOCOL, &gop_proto, NULL, &size, gop_handle); if (status == EFI_BUFFER_TOO_SMALL) { si = alloc_screen_info(); if (!si) return NULL; status = efi_setup_gop(si, &gop_proto, size); if (status != EFI_SUCCESS) { free_screen_info(si); return NULL; } } return si; } static void install_memreserve_table(void) { struct linux_efi_memreserve *rsv; efi_guid_t memreserve_table_guid = LINUX_EFI_MEMRESERVE_TABLE_GUID; efi_status_t status; status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, sizeof(*rsv), (void **)&rsv); if (status != EFI_SUCCESS) { efi_err("Failed to allocate memreserve entry!\n"); return; } rsv->next = 0; rsv->size = 0; atomic_set(&rsv->count, 0); status = efi_bs_call(install_configuration_table, &memreserve_table_guid, rsv); if (status != EFI_SUCCESS) efi_err("Failed to install memreserve config table!\n"); } static u32 get_supported_rt_services(void) { const efi_rt_properties_table_t *rt_prop_table; u32 supported = EFI_RT_SUPPORTED_ALL; rt_prop_table = get_efi_config_table(EFI_RT_PROPERTIES_TABLE_GUID); if (rt_prop_table) supported &= rt_prop_table->runtime_services_supported; return supported; } efi_status_t efi_handle_cmdline(efi_loaded_image_t *image, char **cmdline_ptr) { int cmdline_size = 0; efi_status_t status; char *cmdline; /* * Get the command line from EFI, using the LOADED_IMAGE * protocol. We are going to copy the command line into the * device tree, so this can be allocated anywhere. */ cmdline = efi_convert_cmdline(image, &cmdline_size); if (!cmdline) { efi_err("getting command line via LOADED_IMAGE_PROTOCOL\n"); return EFI_OUT_OF_RESOURCES; } if (IS_ENABLED(CONFIG_CMDLINE_EXTEND) || IS_ENABLED(CONFIG_CMDLINE_FORCE) || cmdline_size == 0) { status = efi_parse_options(CONFIG_CMDLINE); if (status != EFI_SUCCESS) { efi_err("Failed to parse options\n"); goto fail_free_cmdline; } } if (!IS_ENABLED(CONFIG_CMDLINE_FORCE) && cmdline_size > 0) { status = efi_parse_options(cmdline); if (status != EFI_SUCCESS) { efi_err("Failed to parse options\n"); goto fail_free_cmdline; } } *cmdline_ptr = cmdline; return EFI_SUCCESS; fail_free_cmdline: efi_bs_call(free_pool, cmdline_ptr); return status; } efi_status_t efi_stub_common(efi_handle_t handle, efi_loaded_image_t *image, unsigned long image_addr, char *cmdline_ptr) { struct screen_info *si; efi_status_t status; status = check_platform_features(); if (status != EFI_SUCCESS) return status; si = setup_graphics(); efi_retrieve_tpm2_eventlog(); /* Ask the firmware to clear memory on unclean shutdown */ efi_enable_reset_attack_mitigation(); efi_load_initrd(image, ULONG_MAX, efi_get_max_initrd_addr(image_addr), NULL); efi_random_get_seed(); /* force efi_novamap if SetVirtualAddressMap() is unsupported */ efi_novamap |= !(get_supported_rt_services() & EFI_RT_SUPPORTED_SET_VIRTUAL_ADDRESS_MAP); install_memreserve_table(); status = efi_boot_kernel(handle, image, image_addr, cmdline_ptr); free_screen_info(si); return status; } /* * efi_allocate_virtmap() - create a pool allocation for the virtmap * * Create an allocation that is of sufficient size to hold all the memory * descriptors that will be passed to SetVirtualAddressMap() to inform the * firmware about the virtual mapping that will be used under the OS to call * into the firmware. */ efi_status_t efi_alloc_virtmap(efi_memory_desc_t **virtmap, unsigned long *desc_size, u32 *desc_ver) { unsigned long size, mmap_key; efi_status_t status; /* * Use the size of the current memory map as an upper bound for the * size of the buffer we need to pass to SetVirtualAddressMap() to * cover all EFI_MEMORY_RUNTIME regions. */ size = 0; status = efi_bs_call(get_memory_map, &size, NULL, &mmap_key, desc_size, desc_ver); if (status != EFI_BUFFER_TOO_SMALL) return EFI_LOAD_ERROR; return efi_bs_call(allocate_pool, EFI_LOADER_DATA, size, (void **)virtmap); } /* * efi_get_virtmap() - create a virtual mapping for the EFI memory map * * This function populates the virt_addr fields of all memory region descriptors * in @memory_map whose EFI_MEMORY_RUNTIME attribute is set. Those descriptors * are also copied to @runtime_map, and their total count is returned in @count. */ void efi_get_virtmap(efi_memory_desc_t *memory_map, unsigned long map_size, unsigned long desc_size, efi_memory_desc_t *runtime_map, int *count) { u64 efi_virt_base = virtmap_base; efi_memory_desc_t *in, *out = runtime_map; int l; *count = 0; for (l = 0; l < map_size; l += desc_size) { u64 paddr, size; in = (void *)memory_map + l; if (!(in->attribute & EFI_MEMORY_RUNTIME)) continue; paddr = in->phys_addr; size = in->num_pages * EFI_PAGE_SIZE; in->virt_addr = in->phys_addr + EFI_RT_VIRTUAL_OFFSET; if (efi_novamap) { continue; } /* * Make the mapping compatible with 64k pages: this allows * a 4k page size kernel to kexec a 64k page size kernel and * vice versa. */ if (!flat_va_mapping) { paddr = round_down(in->phys_addr, SZ_64K); size += in->phys_addr - paddr; /* * Avoid wasting memory on PTEs by choosing a virtual * base that is compatible with section mappings if this * region has the appropriate size and physical * alignment. (Sections are 2 MB on 4k granule kernels) */ if (IS_ALIGNED(in->phys_addr, SZ_2M) && size >= SZ_2M) efi_virt_base = round_up(efi_virt_base, SZ_2M); else efi_virt_base = round_up(efi_virt_base, SZ_64K); in->virt_addr += efi_virt_base - paddr; efi_virt_base += size; } memcpy(out, in, desc_size); out = (void *)out + desc_size; ++*count; } }
linux-master
drivers/firmware/efi/libstub/efi-stub.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2013 Linaro Ltd; <[email protected]> */ #include <linux/efi.h> #include <asm/efi.h> #include "efistub.h" static efi_guid_t cpu_state_guid = LINUX_EFI_ARM_CPU_STATE_TABLE_GUID; struct efi_arm_entry_state *efi_entry_state; static void get_cpu_state(u32 *cpsr, u32 *sctlr) { asm("mrs %0, cpsr" : "=r"(*cpsr)); if ((*cpsr & MODE_MASK) == HYP_MODE) asm("mrc p15, 4, %0, c1, c0, 0" : "=r"(*sctlr)); else asm("mrc p15, 0, %0, c1, c0, 0" : "=r"(*sctlr)); } efi_status_t check_platform_features(void) { efi_status_t status; u32 cpsr, sctlr; int block; get_cpu_state(&cpsr, &sctlr); efi_info("Entering in %s mode with MMU %sabled\n", ((cpsr & MODE_MASK) == HYP_MODE) ? "HYP" : "SVC", (sctlr & 1) ? "en" : "dis"); status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, sizeof(*efi_entry_state), (void **)&efi_entry_state); if (status != EFI_SUCCESS) { efi_err("allocate_pool() failed\n"); return status; } efi_entry_state->cpsr_before_ebs = cpsr; efi_entry_state->sctlr_before_ebs = sctlr; status = efi_bs_call(install_configuration_table, &cpu_state_guid, efi_entry_state); if (status != EFI_SUCCESS) { efi_err("install_configuration_table() failed\n"); goto free_state; } /* non-LPAE kernels can run anywhere */ if (!IS_ENABLED(CONFIG_ARM_LPAE)) return EFI_SUCCESS; /* LPAE kernels need compatible hardware */ block = cpuid_feature_extract(CPUID_EXT_MMFR0, 0); if (block < 5) { efi_err("This LPAE kernel is not supported by your CPU\n"); status = EFI_UNSUPPORTED; goto drop_table; } return EFI_SUCCESS; drop_table: efi_bs_call(install_configuration_table, &cpu_state_guid, NULL); free_state: efi_bs_call(free_pool, efi_entry_state); return status; } void efi_handle_post_ebs_state(void) { get_cpu_state(&efi_entry_state->cpsr_after_ebs, &efi_entry_state->sctlr_after_ebs); } efi_status_t handle_kernel_image(unsigned long *image_addr, unsigned long *image_size, unsigned long *reserve_addr, unsigned long *reserve_size, efi_loaded_image_t *image, efi_handle_t image_handle) { const int slack = TEXT_OFFSET - 5 * PAGE_SIZE; int alloc_size = MAX_UNCOMP_KERNEL_SIZE + EFI_PHYS_ALIGN; unsigned long alloc_base, kernel_base; efi_status_t status; /* * Allocate space for the decompressed kernel as low as possible. * The region should be 16 MiB aligned, but the first 'slack' bytes * are not used by Linux, so we allow those to be occupied by the * firmware. */ status = efi_low_alloc_above(alloc_size, EFI_PAGE_SIZE, &alloc_base, 0x0); if (status != EFI_SUCCESS) { efi_err("Unable to allocate memory for uncompressed kernel.\n"); return status; } if ((alloc_base % EFI_PHYS_ALIGN) > slack) { /* * More than 'slack' bytes are already occupied at the base of * the allocation, so we need to advance to the next 16 MiB block. */ kernel_base = round_up(alloc_base, EFI_PHYS_ALIGN); efi_info("Free memory starts at 0x%lx, setting kernel_base to 0x%lx\n", alloc_base, kernel_base); } else { kernel_base = round_down(alloc_base, EFI_PHYS_ALIGN); } *reserve_addr = kernel_base + slack; *reserve_size = MAX_UNCOMP_KERNEL_SIZE; /* now free the parts that we will not use */ if (*reserve_addr > alloc_base) { efi_bs_call(free_pages, alloc_base, (*reserve_addr - alloc_base) / EFI_PAGE_SIZE); alloc_size -= *reserve_addr - alloc_base; } efi_bs_call(free_pages, *reserve_addr + MAX_UNCOMP_KERNEL_SIZE, (alloc_size - MAX_UNCOMP_KERNEL_SIZE) / EFI_PAGE_SIZE); *image_addr = kernel_base + TEXT_OFFSET; *image_size = 0; efi_debug("image addr == 0x%lx, reserve_addr == 0x%lx\n", *image_addr, *reserve_addr); return EFI_SUCCESS; }
linux-master
drivers/firmware/efi/libstub/arm32-stub.c
// SPDX-License-Identifier: GPL-2.0-only #include <linux/efi.h> #include <asm/boot.h> #include <asm/desc.h> #include <asm/efi.h> #include "efistub.h" #include "x86-stub.h" bool efi_no5lvl; static void (*la57_toggle)(void *cr3); static const struct desc_struct gdt[] = { [GDT_ENTRY_KERNEL32_CS] = GDT_ENTRY_INIT(0xc09b, 0, 0xfffff), [GDT_ENTRY_KERNEL_CS] = GDT_ENTRY_INIT(0xa09b, 0, 0xfffff), }; /* * Enabling (or disabling) 5 level paging is tricky, because it can only be * done from 32-bit mode with paging disabled. This means not only that the * code itself must be running from 32-bit addressable physical memory, but * also that the root page table must be 32-bit addressable, as programming * a 64-bit value into CR3 when running in 32-bit mode is not supported. */ efi_status_t efi_setup_5level_paging(void) { u8 tmpl_size = (u8 *)&trampoline_ljmp_imm_offset - (u8 *)&trampoline_32bit_src; efi_status_t status; u8 *la57_code; if (!efi_is_64bit()) return EFI_SUCCESS; /* check for 5 level paging support */ if (native_cpuid_eax(0) < 7 || !(native_cpuid_ecx(7) & (1 << (X86_FEATURE_LA57 & 31)))) return EFI_SUCCESS; /* allocate some 32-bit addressable memory for code and a page table */ status = efi_allocate_pages(2 * PAGE_SIZE, (unsigned long *)&la57_code, U32_MAX); if (status != EFI_SUCCESS) return status; la57_toggle = memcpy(la57_code, trampoline_32bit_src, tmpl_size); memset(la57_code + tmpl_size, 0x90, PAGE_SIZE - tmpl_size); /* * To avoid the need to allocate a 32-bit addressable stack, the * trampoline uses a LJMP instruction to switch back to long mode. * LJMP takes an absolute destination address, which needs to be * fixed up at runtime. */ *(u32 *)&la57_code[trampoline_ljmp_imm_offset] += (unsigned long)la57_code; efi_adjust_memory_range_protection((unsigned long)la57_toggle, PAGE_SIZE); return EFI_SUCCESS; } void efi_5level_switch(void) { bool want_la57 = IS_ENABLED(CONFIG_X86_5LEVEL) && !efi_no5lvl; bool have_la57 = native_read_cr4() & X86_CR4_LA57; bool need_toggle = want_la57 ^ have_la57; u64 *pgt = (void *)la57_toggle + PAGE_SIZE; u64 *cr3 = (u64 *)__native_read_cr3(); u64 *new_cr3; if (!la57_toggle || !need_toggle) return; if (!have_la57) { /* * 5 level paging will be enabled, so a root level page needs * to be allocated from the 32-bit addressable physical region, * with its first entry referring to the existing hierarchy. */ new_cr3 = memset(pgt, 0, PAGE_SIZE); new_cr3[0] = (u64)cr3 | _PAGE_TABLE_NOENC; } else { /* take the new root table pointer from the current entry #0 */ new_cr3 = (u64 *)(cr3[0] & PAGE_MASK); /* copy the new root table if it is not 32-bit addressable */ if ((u64)new_cr3 > U32_MAX) new_cr3 = memcpy(pgt, new_cr3, PAGE_SIZE); } native_load_gdt(&(struct desc_ptr){ sizeof(gdt) - 1, (u64)gdt }); la57_toggle(new_cr3); }
linux-master
drivers/firmware/efi/libstub/x86-5lvl.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/efi.h> #include <linux/screen_info.h> #include <asm/efi.h> #include "efistub.h" /* * There are two ways of populating the core kernel's struct screen_info via the stub: * - using a configuration table, like below, which relies on the EFI init code * to locate the table and copy the contents; * - by linking directly to the core kernel's copy of the global symbol. * * The latter is preferred because it makes the EFIFB earlycon available very * early, but it only works if the EFI stub is part of the core kernel image * itself. The zboot decompressor can only use the configuration table * approach. */ static efi_guid_t screen_info_guid = LINUX_EFI_SCREEN_INFO_TABLE_GUID; struct screen_info *__alloc_screen_info(void) { struct screen_info *si; efi_status_t status; status = efi_bs_call(allocate_pool, EFI_ACPI_RECLAIM_MEMORY, sizeof(*si), (void **)&si); if (status != EFI_SUCCESS) return NULL; status = efi_bs_call(install_configuration_table, &screen_info_guid, si); if (status == EFI_SUCCESS) return si; efi_bs_call(free_pool, si); return NULL; } void free_screen_info(struct screen_info *si) { if (!si) return; efi_bs_call(install_configuration_table, &screen_info_guid, NULL); efi_bs_call(free_pool, si); }
linux-master
drivers/firmware/efi/libstub/screen_info.c
// SPDX-License-Identifier: GPL-2.0 /* * Helper functions used by the EFI stub on multiple * architectures. This should be #included by the EFI stub * implementation files. * * Copyright 2011 Intel Corporation; author Matt Fleming */ #include <linux/efi.h> #include <asm/efi.h> #include "efistub.h" #define MAX_FILENAME_SIZE 256 /* * Some firmware implementations have problems reading files in one go. * A read chunk size of 1MB seems to work for most platforms. * * Unfortunately, reading files in chunks triggers *other* bugs on some * platforms, so we provide a way to disable this workaround, which can * be done by passing "efi=nochunk" on the EFI boot stub command line. * * If you experience issues with initrd images being corrupt it's worth * trying efi=nochunk, but chunking is enabled by default on x86 because * there are far more machines that require the workaround than those that * break with it enabled. */ #define EFI_READ_CHUNK_SIZE SZ_1M struct finfo { efi_file_info_t info; efi_char16_t filename[MAX_FILENAME_SIZE]; }; static efi_status_t efi_open_file(efi_file_protocol_t *volume, struct finfo *fi, efi_file_protocol_t **handle, unsigned long *file_size) { efi_guid_t info_guid = EFI_FILE_INFO_ID; efi_file_protocol_t *fh; unsigned long info_sz; efi_status_t status; efi_char16_t *c; /* Replace UNIX dir separators with EFI standard ones */ for (c = fi->filename; *c != L'\0'; c++) { if (*c == L'/') *c = L'\\'; } status = efi_call_proto(volume, open, &fh, fi->filename, EFI_FILE_MODE_READ, 0); if (status != EFI_SUCCESS) { efi_err("Failed to open file: %ls\n", fi->filename); return status; } info_sz = sizeof(struct finfo); status = efi_call_proto(fh, get_info, &info_guid, &info_sz, fi); if (status != EFI_SUCCESS) { efi_err("Failed to get file info\n"); efi_call_proto(fh, close); return status; } *handle = fh; *file_size = fi->info.file_size; return EFI_SUCCESS; } static efi_status_t efi_open_volume(efi_loaded_image_t *image, efi_file_protocol_t **fh) { efi_guid_t fs_proto = EFI_FILE_SYSTEM_GUID; efi_simple_file_system_protocol_t *io; efi_status_t status; status = efi_bs_call(handle_protocol, efi_table_attr(image, device_handle), &fs_proto, (void **)&io); if (status != EFI_SUCCESS) { efi_err("Failed to handle fs_proto\n"); return status; } status = efi_call_proto(io, open_volume, fh); if (status != EFI_SUCCESS) efi_err("Failed to open volume\n"); return status; } static int find_file_option(const efi_char16_t *cmdline, int cmdline_len, const efi_char16_t *prefix, int prefix_size, efi_char16_t *result, int result_len) { int prefix_len = prefix_size / 2; bool found = false; int i; for (i = prefix_len; i < cmdline_len; i++) { if (!memcmp(&cmdline[i - prefix_len], prefix, prefix_size)) { found = true; break; } } if (!found) return 0; /* Skip any leading slashes */ while (i < cmdline_len && (cmdline[i] == L'/' || cmdline[i] == L'\\')) i++; while (--result_len > 0 && i < cmdline_len) { efi_char16_t c = cmdline[i++]; if (c == L'\0' || c == L'\n' || c == L' ') break; *result++ = c; } *result = L'\0'; return i; } static efi_status_t efi_open_device_path(efi_file_protocol_t **volume, struct finfo *fi) { efi_guid_t text_to_dp_guid = EFI_DEVICE_PATH_FROM_TEXT_PROTOCOL_GUID; static efi_device_path_from_text_protocol_t *text_to_dp = NULL; efi_guid_t fs_proto = EFI_FILE_SYSTEM_GUID; efi_device_path_protocol_t *initrd_dp; efi_simple_file_system_protocol_t *io; struct efi_file_path_dev_path *fpath; efi_handle_t handle; efi_status_t status; /* See if the text to device path protocol exists */ if (!text_to_dp && efi_bs_call(locate_protocol, &text_to_dp_guid, NULL, (void **)&text_to_dp) != EFI_SUCCESS) return EFI_UNSUPPORTED; /* Convert the filename wide string into a device path */ initrd_dp = efi_fn_call(text_to_dp, convert_text_to_device_path, fi->filename); /* Check whether the device path in question implements simple FS */ if ((efi_bs_call(locate_device_path, &fs_proto, &initrd_dp, &handle) ?: efi_bs_call(handle_protocol, handle, &fs_proto, (void **)&io)) != EFI_SUCCESS) return EFI_NOT_FOUND; /* Check whether the remaining device path is a file device path */ if (initrd_dp->type != EFI_DEV_MEDIA || initrd_dp->sub_type != EFI_DEV_MEDIA_FILE) { efi_warn("Unexpected device path node type: (%x, %x)\n", initrd_dp->type, initrd_dp->sub_type); return EFI_LOAD_ERROR; } /* Copy the remaining file path into the fi structure */ fpath = (struct efi_file_path_dev_path *)initrd_dp; memcpy(fi->filename, fpath->filename, min(sizeof(fi->filename), fpath->header.length - sizeof(fpath->header))); status = efi_call_proto(io, open_volume, volume); if (status != EFI_SUCCESS) efi_err("Failed to open volume\n"); return status; } /* * Check the cmdline for a LILO-style file= arguments. * * We only support loading a file from the same filesystem as * the kernel image. */ efi_status_t handle_cmdline_files(efi_loaded_image_t *image, const efi_char16_t *optstr, int optstr_size, unsigned long soft_limit, unsigned long hard_limit, unsigned long *load_addr, unsigned long *load_size) { const efi_char16_t *cmdline = efi_table_attr(image, load_options); u32 cmdline_len = efi_table_attr(image, load_options_size); unsigned long efi_chunk_size = ULONG_MAX; efi_file_protocol_t *volume = NULL; efi_file_protocol_t *file; unsigned long alloc_addr; unsigned long alloc_size; efi_status_t status; int offset; if (!load_addr || !load_size) return EFI_INVALID_PARAMETER; efi_apply_loadoptions_quirk((const void **)&cmdline, &cmdline_len); cmdline_len /= sizeof(*cmdline); if (IS_ENABLED(CONFIG_X86) && !efi_nochunk) efi_chunk_size = EFI_READ_CHUNK_SIZE; alloc_addr = alloc_size = 0; do { struct finfo fi; unsigned long size; void *addr; offset = find_file_option(cmdline, cmdline_len, optstr, optstr_size, fi.filename, ARRAY_SIZE(fi.filename)); if (!offset) break; cmdline += offset; cmdline_len -= offset; status = efi_open_device_path(&volume, &fi); if (status == EFI_UNSUPPORTED || status == EFI_NOT_FOUND) /* try the volume that holds the kernel itself */ status = efi_open_volume(image, &volume); if (status != EFI_SUCCESS) goto err_free_alloc; status = efi_open_file(volume, &fi, &file, &size); if (status != EFI_SUCCESS) goto err_close_volume; /* * Check whether the existing allocation can contain the next * file. This condition will also trigger naturally during the * first (and typically only) iteration of the loop, given that * alloc_size == 0 in that case. */ if (round_up(alloc_size + size, EFI_ALLOC_ALIGN) > round_up(alloc_size, EFI_ALLOC_ALIGN)) { unsigned long old_addr = alloc_addr; status = EFI_OUT_OF_RESOURCES; if (soft_limit < hard_limit) status = efi_allocate_pages(alloc_size + size, &alloc_addr, soft_limit); if (status == EFI_OUT_OF_RESOURCES) status = efi_allocate_pages(alloc_size + size, &alloc_addr, hard_limit); if (status != EFI_SUCCESS) { efi_err("Failed to allocate memory for files\n"); goto err_close_file; } if (old_addr != 0) { /* * This is not the first time we've gone * around this loop, and so we are loading * multiple files that need to be concatenated * and returned in a single buffer. */ memcpy((void *)alloc_addr, (void *)old_addr, alloc_size); efi_free(alloc_size, old_addr); } } addr = (void *)alloc_addr + alloc_size; alloc_size += size; while (size) { unsigned long chunksize = min(size, efi_chunk_size); status = efi_call_proto(file, read, &chunksize, addr); if (status != EFI_SUCCESS) { efi_err("Failed to read file\n"); goto err_close_file; } addr += chunksize; size -= chunksize; } efi_call_proto(file, close); efi_call_proto(volume, close); } while (offset > 0); *load_addr = alloc_addr; *load_size = alloc_size; if (*load_size == 0) return EFI_NOT_READY; return EFI_SUCCESS; err_close_file: efi_call_proto(file, close); err_close_volume: efi_call_proto(volume, close); err_free_alloc: efi_free(alloc_size, alloc_addr); return status; }
linux-master
drivers/firmware/efi/libstub/file.c
// SPDX-License-Identifier: GPL-2.0-only #include <linux/efi.h> #include <linux/screen_info.h> #include <asm/efi.h> #include "efistub.h" static unsigned long screen_info_offset; struct screen_info *alloc_screen_info(void) { if (IS_ENABLED(CONFIG_ARM)) return __alloc_screen_info(); return (void *)&screen_info + screen_info_offset; } /* * EFI entry point for the generic EFI stub used by ARM, arm64, RISC-V and * LoongArch. This is the entrypoint that is described in the PE/COFF header * of the core kernel. */ efi_status_t __efiapi efi_pe_entry(efi_handle_t handle, efi_system_table_t *systab) { efi_loaded_image_t *image; efi_status_t status; unsigned long image_addr; unsigned long image_size = 0; /* addr/point and size pairs for memory management*/ char *cmdline_ptr = NULL; efi_guid_t loaded_image_proto = LOADED_IMAGE_PROTOCOL_GUID; unsigned long reserve_addr = 0; unsigned long reserve_size = 0; WRITE_ONCE(efi_system_table, systab); /* Check if we were booted by the EFI firmware */ if (efi_system_table->hdr.signature != EFI_SYSTEM_TABLE_SIGNATURE) return EFI_INVALID_PARAMETER; /* * Get a handle to the loaded image protocol. This is used to get * information about the running image, such as size and the command * line. */ status = efi_bs_call(handle_protocol, handle, &loaded_image_proto, (void *)&image); if (status != EFI_SUCCESS) { efi_err("Failed to get loaded image protocol\n"); return status; } status = efi_handle_cmdline(image, &cmdline_ptr); if (status != EFI_SUCCESS) return status; efi_info("Booting Linux Kernel...\n"); status = handle_kernel_image(&image_addr, &image_size, &reserve_addr, &reserve_size, image, handle); if (status != EFI_SUCCESS) { efi_err("Failed to relocate kernel\n"); return status; } screen_info_offset = image_addr - (unsigned long)image->image_base; status = efi_stub_common(handle, image, image_addr, cmdline_ptr); efi_free(image_size, image_addr); efi_free(reserve_size, reserve_addr); return status; }
linux-master
drivers/firmware/efi/libstub/efi-stub-entry.c
// SPDX-License-Identifier: GPL-2.0 /* * Helper functions used by the EFI stub on multiple * architectures to deal with physical address space randomization. */ #include <linux/efi.h> #include "efistub.h" /** * efi_kaslr_get_phys_seed() - Get random seed for physical kernel KASLR * @image_handle: Handle to the image * * If KASLR is not disabled, obtain a random seed using EFI_RNG_PROTOCOL * that will be used to move the kernel physical mapping. * * Return: the random seed */ u32 efi_kaslr_get_phys_seed(efi_handle_t image_handle) { efi_status_t status; u32 phys_seed; efi_guid_t li_fixed_proto = LINUX_EFI_LOADED_IMAGE_FIXED_GUID; void *p; if (!IS_ENABLED(CONFIG_RANDOMIZE_BASE)) return 0; if (efi_nokaslr) { efi_info("KASLR disabled on kernel command line\n"); } else if (efi_bs_call(handle_protocol, image_handle, &li_fixed_proto, &p) == EFI_SUCCESS) { efi_info("Image placement fixed by loader\n"); } else { status = efi_get_random_bytes(sizeof(phys_seed), (u8 *)&phys_seed); if (status == EFI_SUCCESS) { return phys_seed; } else if (status == EFI_NOT_FOUND) { efi_info("EFI_RNG_PROTOCOL unavailable\n"); efi_nokaslr = true; } else if (status != EFI_SUCCESS) { efi_err("efi_get_random_bytes() failed (0x%lx)\n", status); efi_nokaslr = true; } } return 0; } /* * Distro versions of GRUB may ignore the BSS allocation entirely (i.e., fail * to provide space, and fail to zero it). Check for this condition by double * checking that the first and the last byte of the image are covered by the * same EFI memory map entry. */ static bool check_image_region(u64 base, u64 size) { struct efi_boot_memmap *map; efi_status_t status; bool ret = false; int map_offset; status = efi_get_memory_map(&map, false); if (status != EFI_SUCCESS) return false; for (map_offset = 0; map_offset < map->map_size; map_offset += map->desc_size) { efi_memory_desc_t *md = (void *)map->map + map_offset; u64 end = md->phys_addr + md->num_pages * EFI_PAGE_SIZE; /* * Find the region that covers base, and return whether * it covers base+size bytes. */ if (base >= md->phys_addr && base < end) { ret = (base + size) <= end; break; } } efi_bs_call(free_pool, map); return ret; } /** * efi_kaslr_relocate_kernel() - Relocate the kernel (random if KASLR enabled) * @image_addr: Pointer to the current kernel location * @reserve_addr: Pointer to the relocated kernel location * @reserve_size: Size of the relocated kernel * @kernel_size: Size of the text + data * @kernel_codesize: Size of the text * @kernel_memsize: Size of the text + data + bss * @phys_seed: Random seed used for the relocation * * If KASLR is not enabled, this function relocates the kernel to a fixed * address (or leave it as its current location). If KASLR is enabled, the * kernel physical location is randomized using the seed in parameter. * * Return: status code, EFI_SUCCESS if relocation is successful */ efi_status_t efi_kaslr_relocate_kernel(unsigned long *image_addr, unsigned long *reserve_addr, unsigned long *reserve_size, unsigned long kernel_size, unsigned long kernel_codesize, unsigned long kernel_memsize, u32 phys_seed) { efi_status_t status; u64 min_kimg_align = efi_get_kimg_min_align(); if (IS_ENABLED(CONFIG_RANDOMIZE_BASE) && phys_seed != 0) { /* * If KASLR is enabled, and we have some randomness available, * locate the kernel at a randomized offset in physical memory. */ status = efi_random_alloc(*reserve_size, min_kimg_align, reserve_addr, phys_seed, EFI_LOADER_CODE, EFI_ALLOC_LIMIT); if (status != EFI_SUCCESS) efi_warn("efi_random_alloc() failed: 0x%lx\n", status); } else { status = EFI_OUT_OF_RESOURCES; } if (status != EFI_SUCCESS) { if (!check_image_region(*image_addr, kernel_memsize)) { efi_err("FIRMWARE BUG: Image BSS overlaps adjacent EFI memory region\n"); } else if (IS_ALIGNED(*image_addr, min_kimg_align) && (unsigned long)_end < EFI_ALLOC_LIMIT) { /* * Just execute from wherever we were loaded by the * UEFI PE/COFF loader if the placement is suitable. */ *reserve_size = 0; return EFI_SUCCESS; } status = efi_allocate_pages_aligned(*reserve_size, reserve_addr, ULONG_MAX, min_kimg_align, EFI_LOADER_CODE); if (status != EFI_SUCCESS) { efi_err("Failed to relocate kernel\n"); *reserve_size = 0; return status; } } memcpy((void *)*reserve_addr, (void *)*image_addr, kernel_size); *image_addr = *reserve_addr; efi_icache_sync(*image_addr, *image_addr + kernel_codesize); efi_remap_image(*image_addr, *reserve_size, kernel_codesize); return status; }
linux-master
drivers/firmware/efi/libstub/kaslr.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/ctype.h> #include <linux/string.h> #include <linux/types.h> char *skip_spaces(const char *str) { while (isspace(*str)) ++str; return (char *)str; }
linux-master
drivers/firmware/efi/libstub/skip_spaces.c
// SPDX-License-Identifier: GPL-2.0-only #include <linux/bitmap.h> #include <linux/math.h> #include <linux/minmax.h> /* * Common helper for find_next_bit() function family * @FETCH: The expression that fetches and pre-processes each word of bitmap(s) * @MUNGE: The expression that post-processes a word containing found bit (may be empty) * @size: The bitmap size in bits * @start: The bitnumber to start searching at */ #define FIND_NEXT_BIT(FETCH, MUNGE, size, start) \ ({ \ unsigned long mask, idx, tmp, sz = (size), __start = (start); \ \ if (unlikely(__start >= sz)) \ goto out; \ \ mask = MUNGE(BITMAP_FIRST_WORD_MASK(__start)); \ idx = __start / BITS_PER_LONG; \ \ for (tmp = (FETCH) & mask; !tmp; tmp = (FETCH)) { \ if ((idx + 1) * BITS_PER_LONG >= sz) \ goto out; \ idx++; \ } \ \ sz = min(idx * BITS_PER_LONG + __ffs(MUNGE(tmp)), sz); \ out: \ sz; \ }) unsigned long _find_next_bit(const unsigned long *addr, unsigned long nbits, unsigned long start) { return FIND_NEXT_BIT(addr[idx], /* nop */, nbits, start); } unsigned long _find_next_zero_bit(const unsigned long *addr, unsigned long nbits, unsigned long start) { return FIND_NEXT_BIT(~addr[idx], /* nop */, nbits, start); }
linux-master
drivers/firmware/efi/libstub/find.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2016 Linaro Ltd; <[email protected]> */ #include <linux/efi.h> #include <linux/log2.h> #include <asm/efi.h> #include "efistub.h" /* * Return the number of slots covered by this entry, i.e., the number of * addresses it covers that are suitably aligned and supply enough room * for the allocation. */ static unsigned long get_entry_num_slots(efi_memory_desc_t *md, unsigned long size, unsigned long align_shift, u64 alloc_limit) { unsigned long align = 1UL << align_shift; u64 first_slot, last_slot, region_end; if (md->type != EFI_CONVENTIONAL_MEMORY) return 0; if (efi_soft_reserve_enabled() && (md->attribute & EFI_MEMORY_SP)) return 0; region_end = min(md->phys_addr + md->num_pages * EFI_PAGE_SIZE - 1, alloc_limit); if (region_end < size) return 0; first_slot = round_up(md->phys_addr, align); last_slot = round_down(region_end - size + 1, align); if (first_slot > last_slot) return 0; return ((unsigned long)(last_slot - first_slot) >> align_shift) + 1; } /* * The UEFI memory descriptors have a virtual address field that is only used * when installing the virtual mapping using SetVirtualAddressMap(). Since it * is unused here, we can reuse it to keep track of each descriptor's slot * count. */ #define MD_NUM_SLOTS(md) ((md)->virt_addr) efi_status_t efi_random_alloc(unsigned long size, unsigned long align, unsigned long *addr, unsigned long random_seed, int memory_type, unsigned long alloc_limit) { unsigned long total_slots = 0, target_slot; unsigned long total_mirrored_slots = 0; struct efi_boot_memmap *map; efi_status_t status; int map_offset; status = efi_get_memory_map(&map, false); if (status != EFI_SUCCESS) return status; if (align < EFI_ALLOC_ALIGN) align = EFI_ALLOC_ALIGN; size = round_up(size, EFI_ALLOC_ALIGN); /* count the suitable slots in each memory map entry */ for (map_offset = 0; map_offset < map->map_size; map_offset += map->desc_size) { efi_memory_desc_t *md = (void *)map->map + map_offset; unsigned long slots; slots = get_entry_num_slots(md, size, ilog2(align), alloc_limit); MD_NUM_SLOTS(md) = slots; total_slots += slots; if (md->attribute & EFI_MEMORY_MORE_RELIABLE) total_mirrored_slots += slots; } /* consider only mirrored slots for randomization if any exist */ if (total_mirrored_slots > 0) total_slots = total_mirrored_slots; /* find a random number between 0 and total_slots */ target_slot = (total_slots * (u64)(random_seed & U32_MAX)) >> 32; /* * target_slot is now a value in the range [0, total_slots), and so * it corresponds with exactly one of the suitable slots we recorded * when iterating over the memory map the first time around. * * So iterate over the memory map again, subtracting the number of * slots of each entry at each iteration, until we have found the entry * that covers our chosen slot. Use the residual value of target_slot * to calculate the randomly chosen address, and allocate it directly * using EFI_ALLOCATE_ADDRESS. */ status = EFI_OUT_OF_RESOURCES; for (map_offset = 0; map_offset < map->map_size; map_offset += map->desc_size) { efi_memory_desc_t *md = (void *)map->map + map_offset; efi_physical_addr_t target; unsigned long pages; if (total_mirrored_slots > 0 && !(md->attribute & EFI_MEMORY_MORE_RELIABLE)) continue; if (target_slot >= MD_NUM_SLOTS(md)) { target_slot -= MD_NUM_SLOTS(md); continue; } target = round_up(md->phys_addr, align) + target_slot * align; pages = size / EFI_PAGE_SIZE; status = efi_bs_call(allocate_pages, EFI_ALLOCATE_ADDRESS, memory_type, pages, &target); if (status == EFI_SUCCESS) *addr = target; break; } efi_bs_call(free_pool, map); return status; }
linux-master
drivers/firmware/efi/libstub/randomalloc.c
// SPDX-License-Identifier: GPL-2.0 /* * Helper functions used by the EFI stub on multiple * architectures. This should be #included by the EFI stub * implementation files. * * Copyright 2011 Intel Corporation; author Matt Fleming */ #include <linux/stdarg.h> #include <linux/efi.h> #include <linux/kernel.h> #include <asm/efi.h> #include <asm/setup.h> #include "efistub.h" bool efi_nochunk; bool efi_nokaslr = !IS_ENABLED(CONFIG_RANDOMIZE_BASE); bool efi_novamap; static bool efi_noinitrd; static bool efi_nosoftreserve; static bool efi_disable_pci_dma = IS_ENABLED(CONFIG_EFI_DISABLE_PCI_DMA); bool __pure __efi_soft_reserve_enabled(void) { return !efi_nosoftreserve; } /** * efi_parse_options() - Parse EFI command line options * @cmdline: kernel command line * * Parse the ASCII string @cmdline for EFI options, denoted by the efi= * option, e.g. efi=nochunk. * * It should be noted that efi= is parsed in two very different * environments, first in the early boot environment of the EFI boot * stub, and subsequently during the kernel boot. * * Return: status code */ efi_status_t efi_parse_options(char const *cmdline) { size_t len; efi_status_t status; char *str, *buf; if (!cmdline) return EFI_SUCCESS; len = strnlen(cmdline, COMMAND_LINE_SIZE - 1) + 1; status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, len, (void **)&buf); if (status != EFI_SUCCESS) return status; memcpy(buf, cmdline, len - 1); buf[len - 1] = '\0'; str = skip_spaces(buf); while (*str) { char *param, *val; str = next_arg(str, &param, &val); if (!val && !strcmp(param, "--")) break; if (!strcmp(param, "nokaslr")) { efi_nokaslr = true; } else if (!strcmp(param, "quiet")) { efi_loglevel = CONSOLE_LOGLEVEL_QUIET; } else if (!strcmp(param, "noinitrd")) { efi_noinitrd = true; } else if (IS_ENABLED(CONFIG_X86_64) && !strcmp(param, "no5lvl")) { efi_no5lvl = true; } else if (!strcmp(param, "efi") && val) { efi_nochunk = parse_option_str(val, "nochunk"); efi_novamap |= parse_option_str(val, "novamap"); efi_nosoftreserve = IS_ENABLED(CONFIG_EFI_SOFT_RESERVE) && parse_option_str(val, "nosoftreserve"); if (parse_option_str(val, "disable_early_pci_dma")) efi_disable_pci_dma = true; if (parse_option_str(val, "no_disable_early_pci_dma")) efi_disable_pci_dma = false; if (parse_option_str(val, "debug")) efi_loglevel = CONSOLE_LOGLEVEL_DEBUG; } else if (!strcmp(param, "video") && val && strstarts(val, "efifb:")) { efi_parse_option_graphics(val + strlen("efifb:")); } } efi_bs_call(free_pool, buf); return EFI_SUCCESS; } /* * The EFI_LOAD_OPTION descriptor has the following layout: * u32 Attributes; * u16 FilePathListLength; * u16 Description[]; * efi_device_path_protocol_t FilePathList[]; * u8 OptionalData[]; * * This function validates and unpacks the variable-size data fields. */ static bool efi_load_option_unpack(efi_load_option_unpacked_t *dest, const efi_load_option_t *src, size_t size) { const void *pos; u16 c; efi_device_path_protocol_t header; const efi_char16_t *description; const efi_device_path_protocol_t *file_path_list; if (size < offsetof(efi_load_option_t, variable_data)) return false; pos = src->variable_data; size -= offsetof(efi_load_option_t, variable_data); if ((src->attributes & ~EFI_LOAD_OPTION_MASK) != 0) return false; /* Scan description. */ description = pos; do { if (size < sizeof(c)) return false; c = *(const u16 *)pos; pos += sizeof(c); size -= sizeof(c); } while (c != L'\0'); /* Scan file_path_list. */ file_path_list = pos; do { if (size < sizeof(header)) return false; header = *(const efi_device_path_protocol_t *)pos; if (header.length < sizeof(header)) return false; if (size < header.length) return false; pos += header.length; size -= header.length; } while ((header.type != EFI_DEV_END_PATH && header.type != EFI_DEV_END_PATH2) || (header.sub_type != EFI_DEV_END_ENTIRE)); if (pos != (const void *)file_path_list + src->file_path_list_length) return false; dest->attributes = src->attributes; dest->file_path_list_length = src->file_path_list_length; dest->description = description; dest->file_path_list = file_path_list; dest->optional_data_size = size; dest->optional_data = size ? pos : NULL; return true; } /* * At least some versions of Dell firmware pass the entire contents of the * Boot#### variable, i.e. the EFI_LOAD_OPTION descriptor, rather than just the * OptionalData field. * * Detect this case and extract OptionalData. */ void efi_apply_loadoptions_quirk(const void **load_options, u32 *load_options_size) { const efi_load_option_t *load_option = *load_options; efi_load_option_unpacked_t load_option_unpacked; if (!IS_ENABLED(CONFIG_X86)) return; if (!load_option) return; if (*load_options_size < sizeof(*load_option)) return; if ((load_option->attributes & ~EFI_LOAD_OPTION_BOOT_MASK) != 0) return; if (!efi_load_option_unpack(&load_option_unpacked, load_option, *load_options_size)) return; efi_warn_once(FW_BUG "LoadOptions is an EFI_LOAD_OPTION descriptor\n"); efi_warn_once(FW_BUG "Using OptionalData as a workaround\n"); *load_options = load_option_unpacked.optional_data; *load_options_size = load_option_unpacked.optional_data_size; } enum efistub_event { EFISTUB_EVT_INITRD, EFISTUB_EVT_LOAD_OPTIONS, EFISTUB_EVT_COUNT, }; #define STR_WITH_SIZE(s) sizeof(s), s static const struct { u32 pcr_index; u32 event_id; u32 event_data_len; u8 event_data[52]; } events[] = { [EFISTUB_EVT_INITRD] = { 9, INITRD_EVENT_TAG_ID, STR_WITH_SIZE("Linux initrd") }, [EFISTUB_EVT_LOAD_OPTIONS] = { 9, LOAD_OPTIONS_EVENT_TAG_ID, STR_WITH_SIZE("LOADED_IMAGE::LoadOptions") }, }; static efi_status_t efi_measure_tagged_event(unsigned long load_addr, unsigned long load_size, enum efistub_event event) { efi_guid_t tcg2_guid = EFI_TCG2_PROTOCOL_GUID; efi_tcg2_protocol_t *tcg2 = NULL; efi_status_t status; efi_bs_call(locate_protocol, &tcg2_guid, NULL, (void **)&tcg2); if (tcg2) { struct efi_measured_event { efi_tcg2_event_t event_data; efi_tcg2_tagged_event_t tagged_event; u8 tagged_event_data[]; } *evt; int size = sizeof(*evt) + events[event].event_data_len; status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, size, (void **)&evt); if (status != EFI_SUCCESS) goto fail; evt->event_data = (struct efi_tcg2_event){ .event_size = size, .event_header.header_size = sizeof(evt->event_data.event_header), .event_header.header_version = EFI_TCG2_EVENT_HEADER_VERSION, .event_header.pcr_index = events[event].pcr_index, .event_header.event_type = EV_EVENT_TAG, }; evt->tagged_event = (struct efi_tcg2_tagged_event){ .tagged_event_id = events[event].event_id, .tagged_event_data_size = events[event].event_data_len, }; memcpy(evt->tagged_event_data, events[event].event_data, events[event].event_data_len); status = efi_call_proto(tcg2, hash_log_extend_event, 0, load_addr, load_size, &evt->event_data); efi_bs_call(free_pool, evt); if (status != EFI_SUCCESS) goto fail; return EFI_SUCCESS; } return EFI_UNSUPPORTED; fail: efi_warn("Failed to measure data for event %d: 0x%lx\n", event, status); return status; } /* * Convert the unicode UEFI command line to ASCII to pass to kernel. * Size of memory allocated return in *cmd_line_len. * Returns NULL on error. */ char *efi_convert_cmdline(efi_loaded_image_t *image, int *cmd_line_len) { const efi_char16_t *options = efi_table_attr(image, load_options); u32 options_size = efi_table_attr(image, load_options_size); int options_bytes = 0, safe_options_bytes = 0; /* UTF-8 bytes */ unsigned long cmdline_addr = 0; const efi_char16_t *s2; bool in_quote = false; efi_status_t status; u32 options_chars; if (options_size > 0) efi_measure_tagged_event((unsigned long)options, options_size, EFISTUB_EVT_LOAD_OPTIONS); efi_apply_loadoptions_quirk((const void **)&options, &options_size); options_chars = options_size / sizeof(efi_char16_t); if (options) { s2 = options; while (options_bytes < COMMAND_LINE_SIZE && options_chars--) { efi_char16_t c = *s2++; if (c < 0x80) { if (c == L'\0' || c == L'\n') break; if (c == L'"') in_quote = !in_quote; else if (!in_quote && isspace((char)c)) safe_options_bytes = options_bytes; options_bytes++; continue; } /* * Get the number of UTF-8 bytes corresponding to a * UTF-16 character. * The first part handles everything in the BMP. */ options_bytes += 2 + (c >= 0x800); /* * Add one more byte for valid surrogate pairs. Invalid * surrogates will be replaced with 0xfffd and take up * only 3 bytes. */ if ((c & 0xfc00) == 0xd800) { /* * If the very last word is a high surrogate, * we must ignore it since we can't access the * low surrogate. */ if (!options_chars) { options_bytes -= 3; } else if ((*s2 & 0xfc00) == 0xdc00) { options_bytes++; options_chars--; s2++; } } } if (options_bytes >= COMMAND_LINE_SIZE) { options_bytes = safe_options_bytes; efi_err("Command line is too long: truncated to %d bytes\n", options_bytes); } } options_bytes++; /* NUL termination */ status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, options_bytes, (void **)&cmdline_addr); if (status != EFI_SUCCESS) return NULL; snprintf((char *)cmdline_addr, options_bytes, "%.*ls", options_bytes - 1, options); *cmd_line_len = options_bytes; return (char *)cmdline_addr; } /** * efi_exit_boot_services() - Exit boot services * @handle: handle of the exiting image * @priv: argument to be passed to @priv_func * @priv_func: function to process the memory map before exiting boot services * * Handle calling ExitBootServices according to the requirements set out by the * spec. Obtains the current memory map, and returns that info after calling * ExitBootServices. The client must specify a function to perform any * processing of the memory map data prior to ExitBootServices. A client * specific structure may be passed to the function via priv. The client * function may be called multiple times. * * Return: status code */ efi_status_t efi_exit_boot_services(void *handle, void *priv, efi_exit_boot_map_processing priv_func) { struct efi_boot_memmap *map; efi_status_t status; if (efi_disable_pci_dma) efi_pci_disable_bridge_busmaster(); status = efi_get_memory_map(&map, true); if (status != EFI_SUCCESS) return status; status = priv_func(map, priv); if (status != EFI_SUCCESS) { efi_bs_call(free_pool, map); return status; } status = efi_bs_call(exit_boot_services, handle, map->map_key); if (status == EFI_INVALID_PARAMETER) { /* * The memory map changed between efi_get_memory_map() and * exit_boot_services(). Per the UEFI Spec v2.6, Section 6.4: * EFI_BOOT_SERVICES.ExitBootServices we need to get the * updated map, and try again. The spec implies one retry * should be sufficent, which is confirmed against the EDK2 * implementation. Per the spec, we can only invoke * get_memory_map() and exit_boot_services() - we cannot alloc * so efi_get_memory_map() cannot be used, and we must reuse * the buffer. For all practical purposes, the headroom in the * buffer should account for any changes in the map so the call * to get_memory_map() is expected to succeed here. */ map->map_size = map->buff_size; status = efi_bs_call(get_memory_map, &map->map_size, &map->map, &map->map_key, &map->desc_size, &map->desc_ver); /* exit_boot_services() was called, thus cannot free */ if (status != EFI_SUCCESS) return status; status = priv_func(map, priv); /* exit_boot_services() was called, thus cannot free */ if (status != EFI_SUCCESS) return status; status = efi_bs_call(exit_boot_services, handle, map->map_key); } return status; } /** * get_efi_config_table() - retrieve UEFI configuration table * @guid: GUID of the configuration table to be retrieved * Return: pointer to the configuration table or NULL */ void *get_efi_config_table(efi_guid_t guid) { unsigned long tables = efi_table_attr(efi_system_table, tables); int nr_tables = efi_table_attr(efi_system_table, nr_tables); int i; for (i = 0; i < nr_tables; i++) { efi_config_table_t *t = (void *)tables; if (efi_guidcmp(t->guid, guid) == 0) return efi_table_attr(t, table); tables += efi_is_native() ? sizeof(efi_config_table_t) : sizeof(efi_config_table_32_t); } return NULL; } /* * The LINUX_EFI_INITRD_MEDIA_GUID vendor media device path below provides a way * for the firmware or bootloader to expose the initrd data directly to the stub * via the trivial LoadFile2 protocol, which is defined in the UEFI spec, and is * very easy to implement. It is a simple Linux initrd specific conduit between * kernel and firmware, allowing us to put the EFI stub (being part of the * kernel) in charge of where and when to load the initrd, while leaving it up * to the firmware to decide whether it needs to expose its filesystem hierarchy * via EFI protocols. */ static const struct { struct efi_vendor_dev_path vendor; struct efi_generic_dev_path end; } __packed initrd_dev_path = { { { EFI_DEV_MEDIA, EFI_DEV_MEDIA_VENDOR, sizeof(struct efi_vendor_dev_path), }, LINUX_EFI_INITRD_MEDIA_GUID }, { EFI_DEV_END_PATH, EFI_DEV_END_ENTIRE, sizeof(struct efi_generic_dev_path) } }; /** * efi_load_initrd_dev_path() - load the initrd from the Linux initrd device path * @initrd: pointer of struct to store the address where the initrd was loaded * and the size of the loaded initrd * @max: upper limit for the initrd memory allocation * * Return: * * %EFI_SUCCESS if the initrd was loaded successfully, in which * case @load_addr and @load_size are assigned accordingly * * %EFI_NOT_FOUND if no LoadFile2 protocol exists on the initrd device path * * %EFI_OUT_OF_RESOURCES if memory allocation failed * * %EFI_LOAD_ERROR in all other cases */ static efi_status_t efi_load_initrd_dev_path(struct linux_efi_initrd *initrd, unsigned long max) { efi_guid_t lf2_proto_guid = EFI_LOAD_FILE2_PROTOCOL_GUID; efi_device_path_protocol_t *dp; efi_load_file2_protocol_t *lf2; efi_handle_t handle; efi_status_t status; dp = (efi_device_path_protocol_t *)&initrd_dev_path; status = efi_bs_call(locate_device_path, &lf2_proto_guid, &dp, &handle); if (status != EFI_SUCCESS) return status; status = efi_bs_call(handle_protocol, handle, &lf2_proto_guid, (void **)&lf2); if (status != EFI_SUCCESS) return status; initrd->size = 0; status = efi_call_proto(lf2, load_file, dp, false, &initrd->size, NULL); if (status != EFI_BUFFER_TOO_SMALL) return EFI_LOAD_ERROR; status = efi_allocate_pages(initrd->size, &initrd->base, max); if (status != EFI_SUCCESS) return status; status = efi_call_proto(lf2, load_file, dp, false, &initrd->size, (void *)initrd->base); if (status != EFI_SUCCESS) { efi_free(initrd->size, initrd->base); return EFI_LOAD_ERROR; } return EFI_SUCCESS; } static efi_status_t efi_load_initrd_cmdline(efi_loaded_image_t *image, struct linux_efi_initrd *initrd, unsigned long soft_limit, unsigned long hard_limit) { if (image == NULL) return EFI_UNSUPPORTED; return handle_cmdline_files(image, L"initrd=", sizeof(L"initrd=") - 2, soft_limit, hard_limit, &initrd->base, &initrd->size); } /** * efi_load_initrd() - Load initial RAM disk * @image: EFI loaded image protocol * @soft_limit: preferred address for loading the initrd * @hard_limit: upper limit address for loading the initrd * * Return: status code */ efi_status_t efi_load_initrd(efi_loaded_image_t *image, unsigned long soft_limit, unsigned long hard_limit, const struct linux_efi_initrd **out) { efi_guid_t tbl_guid = LINUX_EFI_INITRD_MEDIA_GUID; efi_status_t status = EFI_SUCCESS; struct linux_efi_initrd initrd, *tbl; if (!IS_ENABLED(CONFIG_BLK_DEV_INITRD) || efi_noinitrd) return EFI_SUCCESS; status = efi_load_initrd_dev_path(&initrd, hard_limit); if (status == EFI_SUCCESS) { efi_info("Loaded initrd from LINUX_EFI_INITRD_MEDIA_GUID device path\n"); if (initrd.size > 0 && efi_measure_tagged_event(initrd.base, initrd.size, EFISTUB_EVT_INITRD) == EFI_SUCCESS) efi_info("Measured initrd data into PCR 9\n"); } else if (status == EFI_NOT_FOUND) { status = efi_load_initrd_cmdline(image, &initrd, soft_limit, hard_limit); /* command line loader disabled or no initrd= passed? */ if (status == EFI_UNSUPPORTED || status == EFI_NOT_READY) return EFI_SUCCESS; if (status == EFI_SUCCESS) efi_info("Loaded initrd from command line option\n"); } if (status != EFI_SUCCESS) goto failed; status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, sizeof(initrd), (void **)&tbl); if (status != EFI_SUCCESS) goto free_initrd; *tbl = initrd; status = efi_bs_call(install_configuration_table, &tbl_guid, tbl); if (status != EFI_SUCCESS) goto free_tbl; if (out) *out = tbl; return EFI_SUCCESS; free_tbl: efi_bs_call(free_pool, tbl); free_initrd: efi_free(initrd.size, initrd.base); failed: efi_err("Failed to load initrd: 0x%lx\n", status); return status; } /** * efi_wait_for_key() - Wait for key stroke * @usec: number of microseconds to wait for key stroke * @key: key entered * * Wait for up to @usec microseconds for a key stroke. * * Return: status code, EFI_SUCCESS if key received */ efi_status_t efi_wait_for_key(unsigned long usec, efi_input_key_t *key) { efi_event_t events[2], timer; unsigned long index; efi_simple_text_input_protocol_t *con_in; efi_status_t status; con_in = efi_table_attr(efi_system_table, con_in); if (!con_in) return EFI_UNSUPPORTED; efi_set_event_at(events, 0, efi_table_attr(con_in, wait_for_key)); status = efi_bs_call(create_event, EFI_EVT_TIMER, 0, NULL, NULL, &timer); if (status != EFI_SUCCESS) return status; status = efi_bs_call(set_timer, timer, EfiTimerRelative, EFI_100NSEC_PER_USEC * usec); if (status != EFI_SUCCESS) return status; efi_set_event_at(events, 1, timer); status = efi_bs_call(wait_for_event, 2, events, &index); if (status == EFI_SUCCESS) { if (index == 0) status = efi_call_proto(con_in, read_keystroke, key); else status = EFI_TIMEOUT; } efi_bs_call(close_event, timer); return status; } /** * efi_remap_image - Remap a loaded image with the appropriate permissions * for code and data * * @image_base: the base of the image in memory * @alloc_size: the size of the area in memory occupied by the image * @code_size: the size of the leading part of the image containing code * and read-only data * * efi_remap_image() uses the EFI memory attribute protocol to remap the code * region of the loaded image read-only/executable, and the remainder * read-write/non-executable. The code region is assumed to start at the base * of the image, and will therefore cover the PE/COFF header as well. */ void efi_remap_image(unsigned long image_base, unsigned alloc_size, unsigned long code_size) { efi_guid_t guid = EFI_MEMORY_ATTRIBUTE_PROTOCOL_GUID; efi_memory_attribute_protocol_t *memattr; efi_status_t status; u64 attr; /* * If the firmware implements the EFI_MEMORY_ATTRIBUTE_PROTOCOL, let's * invoke it to remap the text/rodata region of the decompressed image * as read-only and the data/bss region as non-executable. */ status = efi_bs_call(locate_protocol, &guid, NULL, (void **)&memattr); if (status != EFI_SUCCESS) return; // Get the current attributes for the entire region status = memattr->get_memory_attributes(memattr, image_base, alloc_size, &attr); if (status != EFI_SUCCESS) { efi_warn("Failed to retrieve memory attributes for image region: 0x%lx\n", status); return; } // Mark the code region as read-only status = memattr->set_memory_attributes(memattr, image_base, code_size, EFI_MEMORY_RO); if (status != EFI_SUCCESS) { efi_warn("Failed to remap code region read-only\n"); return; } // If the entire region was already mapped as non-exec, clear the // attribute from the code region. Otherwise, set it on the data // region. if (attr & EFI_MEMORY_XP) { status = memattr->clear_memory_attributes(memattr, image_base, code_size, EFI_MEMORY_XP); if (status != EFI_SUCCESS) efi_warn("Failed to remap code region executable\n"); } else { status = memattr->set_memory_attributes(memattr, image_base + code_size, alloc_size - code_size, EFI_MEMORY_XP); if (status != EFI_SUCCESS) efi_warn("Failed to remap data region non-executable\n"); } }
linux-master
drivers/firmware/efi/libstub/efi-stub-helper.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/efi.h> #include <asm/efi.h> #include <asm/string.h> #include "efistub.h" #ifdef CONFIG_KASAN #undef memcpy #undef memmove #undef memset void *__memcpy(void *__dest, const void *__src, size_t __n) __alias(memcpy); void *__memmove(void *__dest, const void *__src, size_t count) __alias(memmove); void *__memset(void *s, int c, size_t count) __alias(memset); #endif void *memcpy(void *dst, const void *src, size_t len) { efi_bs_call(copy_mem, dst, src, len); return dst; } extern void *memmove(void *dst, const void *src, size_t len) __alias(memcpy); void *memset(void *dst, int c, size_t len) { efi_bs_call(set_mem, dst, len, c & U8_MAX); return dst; } /** * memcmp - Compare two areas of memory * @cs: One area of memory * @ct: Another area of memory * @count: The size of the area. */ #undef memcmp int memcmp(const void *cs, const void *ct, size_t count) { const unsigned char *su1, *su2; int res = 0; for (su1 = cs, su2 = ct; 0 < count; ++su1, ++su2, count--) if ((res = *su1 - *su2) != 0) break; return res; }
linux-master
drivers/firmware/efi/libstub/intrinsics.c
// SPDX-License-Identifier: GPL-2.0-only /* * generic display timing functions * * Copyright (c) 2012 Steffen Trumtrar <[email protected]>, Pengutronix */ #include <linux/export.h> #include <linux/slab.h> #include <video/display_timing.h> void display_timings_release(struct display_timings *disp) { if (disp->timings) { unsigned int i; for (i = 0; i < disp->num_timings; i++) kfree(disp->timings[i]); kfree(disp->timings); } kfree(disp); } EXPORT_SYMBOL_GPL(display_timings_release);
linux-master
drivers/video/display_timing.c
// SPDX-License-Identifier: GPL-2.0 #include <linux/module.h> #include <linux/types.h> #include <video/nomodeset.h> static bool video_nomodeset; bool video_firmware_drivers_only(void) { return video_nomodeset; } EXPORT_SYMBOL(video_firmware_drivers_only); static int __init disable_modeset(char *str) { video_nomodeset = true; pr_warn("Booted with the nomodeset parameter. Only the system framebuffer will be available\n"); return 1; } /* Disable kernel modesetting */ __setup("nomodeset", disable_modeset);
linux-master
drivers/video/nomodeset.c
/* * Copyright (C) 2012 Avionic Design GmbH * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sub license, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include <drm/display/drm_dp.h> #include <linux/bitops.h> #include <linux/bug.h> #include <linux/errno.h> #include <linux/export.h> #include <linux/hdmi.h> #include <linux/string.h> #include <linux/device.h> #define hdmi_log(fmt, ...) dev_printk(level, dev, fmt, ##__VA_ARGS__) static u8 hdmi_infoframe_checksum(const u8 *ptr, size_t size) { u8 csum = 0; size_t i; /* compute checksum */ for (i = 0; i < size; i++) csum += ptr[i]; return 256 - csum; } static void hdmi_infoframe_set_checksum(void *buffer, size_t size) { u8 *ptr = buffer; ptr[3] = hdmi_infoframe_checksum(buffer, size); } /** * hdmi_avi_infoframe_init() - initialize an HDMI AVI infoframe * @frame: HDMI AVI infoframe */ void hdmi_avi_infoframe_init(struct hdmi_avi_infoframe *frame) { memset(frame, 0, sizeof(*frame)); frame->type = HDMI_INFOFRAME_TYPE_AVI; frame->version = 2; frame->length = HDMI_AVI_INFOFRAME_SIZE; } EXPORT_SYMBOL(hdmi_avi_infoframe_init); static int hdmi_avi_infoframe_check_only(const struct hdmi_avi_infoframe *frame) { if (frame->type != HDMI_INFOFRAME_TYPE_AVI || frame->version != 2 || frame->length != HDMI_AVI_INFOFRAME_SIZE) return -EINVAL; if (frame->picture_aspect > HDMI_PICTURE_ASPECT_16_9) return -EINVAL; return 0; } /** * hdmi_avi_infoframe_check() - check a HDMI AVI infoframe * @frame: HDMI AVI infoframe * * Validates that the infoframe is consistent and updates derived fields * (eg. length) based on other fields. * * Returns 0 on success or a negative error code on failure. */ int hdmi_avi_infoframe_check(struct hdmi_avi_infoframe *frame) { return hdmi_avi_infoframe_check_only(frame); } EXPORT_SYMBOL(hdmi_avi_infoframe_check); /** * hdmi_avi_infoframe_pack_only() - write HDMI AVI infoframe to binary buffer * @frame: HDMI AVI infoframe * @buffer: destination buffer * @size: size of buffer * * Packs the information contained in the @frame structure into a binary * representation that can be written into the corresponding controller * registers. Also computes the checksum as required by section 5.3.5 of * the HDMI 1.4 specification. * * Returns the number of bytes packed into the binary buffer or a negative * error code on failure. */ ssize_t hdmi_avi_infoframe_pack_only(const struct hdmi_avi_infoframe *frame, void *buffer, size_t size) { u8 *ptr = buffer; size_t length; int ret; ret = hdmi_avi_infoframe_check_only(frame); if (ret) return ret; length = HDMI_INFOFRAME_HEADER_SIZE + frame->length; if (size < length) return -ENOSPC; memset(buffer, 0, size); ptr[0] = frame->type; ptr[1] = frame->version; ptr[2] = frame->length; ptr[3] = 0; /* checksum */ /* start infoframe payload */ ptr += HDMI_INFOFRAME_HEADER_SIZE; ptr[0] = ((frame->colorspace & 0x3) << 5) | (frame->scan_mode & 0x3); /* * Data byte 1, bit 4 has to be set if we provide the active format * aspect ratio */ if (frame->active_aspect & 0xf) ptr[0] |= BIT(4); /* Bit 3 and 2 indicate if we transmit horizontal/vertical bar data */ if (frame->top_bar || frame->bottom_bar) ptr[0] |= BIT(3); if (frame->left_bar || frame->right_bar) ptr[0] |= BIT(2); ptr[1] = ((frame->colorimetry & 0x3) << 6) | ((frame->picture_aspect & 0x3) << 4) | (frame->active_aspect & 0xf); ptr[2] = ((frame->extended_colorimetry & 0x7) << 4) | ((frame->quantization_range & 0x3) << 2) | (frame->nups & 0x3); if (frame->itc) ptr[2] |= BIT(7); ptr[3] = frame->video_code & 0x7f; ptr[4] = ((frame->ycc_quantization_range & 0x3) << 6) | ((frame->content_type & 0x3) << 4) | (frame->pixel_repeat & 0xf); ptr[5] = frame->top_bar & 0xff; ptr[6] = (frame->top_bar >> 8) & 0xff; ptr[7] = frame->bottom_bar & 0xff; ptr[8] = (frame->bottom_bar >> 8) & 0xff; ptr[9] = frame->left_bar & 0xff; ptr[10] = (frame->left_bar >> 8) & 0xff; ptr[11] = frame->right_bar & 0xff; ptr[12] = (frame->right_bar >> 8) & 0xff; hdmi_infoframe_set_checksum(buffer, length); return length; } EXPORT_SYMBOL(hdmi_avi_infoframe_pack_only); /** * hdmi_avi_infoframe_pack() - check a HDMI AVI infoframe, * and write it to binary buffer * @frame: HDMI AVI infoframe * @buffer: destination buffer * @size: size of buffer * * Validates that the infoframe is consistent and updates derived fields * (eg. length) based on other fields, after which it packs the information * contained in the @frame structure into a binary representation that * can be written into the corresponding controller registers. This function * also computes the checksum as required by section 5.3.5 of the HDMI 1.4 * specification. * * Returns the number of bytes packed into the binary buffer or a negative * error code on failure. */ ssize_t hdmi_avi_infoframe_pack(struct hdmi_avi_infoframe *frame, void *buffer, size_t size) { int ret; ret = hdmi_avi_infoframe_check(frame); if (ret) return ret; return hdmi_avi_infoframe_pack_only(frame, buffer, size); } EXPORT_SYMBOL(hdmi_avi_infoframe_pack); /** * hdmi_spd_infoframe_init() - initialize an HDMI SPD infoframe * @frame: HDMI SPD infoframe * @vendor: vendor string * @product: product string * * Returns 0 on success or a negative error code on failure. */ int hdmi_spd_infoframe_init(struct hdmi_spd_infoframe *frame, const char *vendor, const char *product) { size_t len; memset(frame, 0, sizeof(*frame)); frame->type = HDMI_INFOFRAME_TYPE_SPD; frame->version = 1; frame->length = HDMI_SPD_INFOFRAME_SIZE; len = strlen(vendor); memcpy(frame->vendor, vendor, min(len, sizeof(frame->vendor))); len = strlen(product); memcpy(frame->product, product, min(len, sizeof(frame->product))); return 0; } EXPORT_SYMBOL(hdmi_spd_infoframe_init); static int hdmi_spd_infoframe_check_only(const struct hdmi_spd_infoframe *frame) { if (frame->type != HDMI_INFOFRAME_TYPE_SPD || frame->version != 1 || frame->length != HDMI_SPD_INFOFRAME_SIZE) return -EINVAL; return 0; } /** * hdmi_spd_infoframe_check() - check a HDMI SPD infoframe * @frame: HDMI SPD infoframe * * Validates that the infoframe is consistent and updates derived fields * (eg. length) based on other fields. * * Returns 0 on success or a negative error code on failure. */ int hdmi_spd_infoframe_check(struct hdmi_spd_infoframe *frame) { return hdmi_spd_infoframe_check_only(frame); } EXPORT_SYMBOL(hdmi_spd_infoframe_check); /** * hdmi_spd_infoframe_pack_only() - write HDMI SPD infoframe to binary buffer * @frame: HDMI SPD infoframe * @buffer: destination buffer * @size: size of buffer * * Packs the information contained in the @frame structure into a binary * representation that can be written into the corresponding controller * registers. Also computes the checksum as required by section 5.3.5 of * the HDMI 1.4 specification. * * Returns the number of bytes packed into the binary buffer or a negative * error code on failure. */ ssize_t hdmi_spd_infoframe_pack_only(const struct hdmi_spd_infoframe *frame, void *buffer, size_t size) { u8 *ptr = buffer; size_t length; int ret; ret = hdmi_spd_infoframe_check_only(frame); if (ret) return ret; length = HDMI_INFOFRAME_HEADER_SIZE + frame->length; if (size < length) return -ENOSPC; memset(buffer, 0, size); ptr[0] = frame->type; ptr[1] = frame->version; ptr[2] = frame->length; ptr[3] = 0; /* checksum */ /* start infoframe payload */ ptr += HDMI_INFOFRAME_HEADER_SIZE; memcpy(ptr, frame->vendor, sizeof(frame->vendor)); memcpy(ptr + 8, frame->product, sizeof(frame->product)); ptr[24] = frame->sdi; hdmi_infoframe_set_checksum(buffer, length); return length; } EXPORT_SYMBOL(hdmi_spd_infoframe_pack_only); /** * hdmi_spd_infoframe_pack() - check a HDMI SPD infoframe, * and write it to binary buffer * @frame: HDMI SPD infoframe * @buffer: destination buffer * @size: size of buffer * * Validates that the infoframe is consistent and updates derived fields * (eg. length) based on other fields, after which it packs the information * contained in the @frame structure into a binary representation that * can be written into the corresponding controller registers. This function * also computes the checksum as required by section 5.3.5 of the HDMI 1.4 * specification. * * Returns the number of bytes packed into the binary buffer or a negative * error code on failure. */ ssize_t hdmi_spd_infoframe_pack(struct hdmi_spd_infoframe *frame, void *buffer, size_t size) { int ret; ret = hdmi_spd_infoframe_check(frame); if (ret) return ret; return hdmi_spd_infoframe_pack_only(frame, buffer, size); } EXPORT_SYMBOL(hdmi_spd_infoframe_pack); /** * hdmi_audio_infoframe_init() - initialize an HDMI audio infoframe * @frame: HDMI audio infoframe * * Returns 0 on success or a negative error code on failure. */ int hdmi_audio_infoframe_init(struct hdmi_audio_infoframe *frame) { memset(frame, 0, sizeof(*frame)); frame->type = HDMI_INFOFRAME_TYPE_AUDIO; frame->version = 1; frame->length = HDMI_AUDIO_INFOFRAME_SIZE; return 0; } EXPORT_SYMBOL(hdmi_audio_infoframe_init); static int hdmi_audio_infoframe_check_only(const struct hdmi_audio_infoframe *frame) { if (frame->type != HDMI_INFOFRAME_TYPE_AUDIO || frame->version != 1 || frame->length != HDMI_AUDIO_INFOFRAME_SIZE) return -EINVAL; return 0; } /** * hdmi_audio_infoframe_check() - check a HDMI audio infoframe * @frame: HDMI audio infoframe * * Validates that the infoframe is consistent and updates derived fields * (eg. length) based on other fields. * * Returns 0 on success or a negative error code on failure. */ int hdmi_audio_infoframe_check(const struct hdmi_audio_infoframe *frame) { return hdmi_audio_infoframe_check_only(frame); } EXPORT_SYMBOL(hdmi_audio_infoframe_check); static void hdmi_audio_infoframe_pack_payload(const struct hdmi_audio_infoframe *frame, u8 *buffer) { u8 channels; if (frame->channels >= 2) channels = frame->channels - 1; else channels = 0; buffer[0] = ((frame->coding_type & 0xf) << 4) | (channels & 0x7); buffer[1] = ((frame->sample_frequency & 0x7) << 2) | (frame->sample_size & 0x3); buffer[2] = frame->coding_type_ext & 0x1f; buffer[3] = frame->channel_allocation; buffer[4] = (frame->level_shift_value & 0xf) << 3; if (frame->downmix_inhibit) buffer[4] |= BIT(7); } /** * hdmi_audio_infoframe_pack_only() - write HDMI audio infoframe to binary buffer * @frame: HDMI audio infoframe * @buffer: destination buffer * @size: size of buffer * * Packs the information contained in the @frame structure into a binary * representation that can be written into the corresponding controller * registers. Also computes the checksum as required by section 5.3.5 of * the HDMI 1.4 specification. * * Returns the number of bytes packed into the binary buffer or a negative * error code on failure. */ ssize_t hdmi_audio_infoframe_pack_only(const struct hdmi_audio_infoframe *frame, void *buffer, size_t size) { u8 *ptr = buffer; size_t length; int ret; ret = hdmi_audio_infoframe_check_only(frame); if (ret) return ret; length = HDMI_INFOFRAME_HEADER_SIZE + frame->length; if (size < length) return -ENOSPC; memset(buffer, 0, size); ptr[0] = frame->type; ptr[1] = frame->version; ptr[2] = frame->length; ptr[3] = 0; /* checksum */ hdmi_audio_infoframe_pack_payload(frame, ptr + HDMI_INFOFRAME_HEADER_SIZE); hdmi_infoframe_set_checksum(buffer, length); return length; } EXPORT_SYMBOL(hdmi_audio_infoframe_pack_only); /** * hdmi_audio_infoframe_pack() - check a HDMI Audio infoframe, * and write it to binary buffer * @frame: HDMI Audio infoframe * @buffer: destination buffer * @size: size of buffer * * Validates that the infoframe is consistent and updates derived fields * (eg. length) based on other fields, after which it packs the information * contained in the @frame structure into a binary representation that * can be written into the corresponding controller registers. This function * also computes the checksum as required by section 5.3.5 of the HDMI 1.4 * specification. * * Returns the number of bytes packed into the binary buffer or a negative * error code on failure. */ ssize_t hdmi_audio_infoframe_pack(struct hdmi_audio_infoframe *frame, void *buffer, size_t size) { int ret; ret = hdmi_audio_infoframe_check(frame); if (ret) return ret; return hdmi_audio_infoframe_pack_only(frame, buffer, size); } EXPORT_SYMBOL(hdmi_audio_infoframe_pack); /** * hdmi_audio_infoframe_pack_for_dp - Pack a HDMI Audio infoframe for DisplayPort * * @frame: HDMI Audio infoframe * @sdp: Secondary data packet for DisplayPort. * @dp_version: DisplayPort version to be encoded in the header * * Packs a HDMI Audio Infoframe to be sent over DisplayPort. This function * fills the secondary data packet to be used for DisplayPort. * * Return: Number of total written bytes or a negative errno on failure. */ ssize_t hdmi_audio_infoframe_pack_for_dp(const struct hdmi_audio_infoframe *frame, struct dp_sdp *sdp, u8 dp_version) { int ret; ret = hdmi_audio_infoframe_check(frame); if (ret) return ret; memset(sdp->db, 0, sizeof(sdp->db)); /* Secondary-data packet header */ sdp->sdp_header.HB0 = 0; sdp->sdp_header.HB1 = frame->type; sdp->sdp_header.HB2 = DP_SDP_AUDIO_INFOFRAME_HB2; sdp->sdp_header.HB3 = (dp_version & 0x3f) << 2; hdmi_audio_infoframe_pack_payload(frame, sdp->db); /* Return size = frame length + four HB for sdp_header */ return frame->length + 4; } EXPORT_SYMBOL(hdmi_audio_infoframe_pack_for_dp); /** * hdmi_vendor_infoframe_init() - initialize an HDMI vendor infoframe * @frame: HDMI vendor infoframe * * Returns 0 on success or a negative error code on failure. */ int hdmi_vendor_infoframe_init(struct hdmi_vendor_infoframe *frame) { memset(frame, 0, sizeof(*frame)); frame->type = HDMI_INFOFRAME_TYPE_VENDOR; frame->version = 1; frame->oui = HDMI_IEEE_OUI; /* * 0 is a valid value for s3d_struct, so we use a special "not set" * value */ frame->s3d_struct = HDMI_3D_STRUCTURE_INVALID; frame->length = HDMI_VENDOR_INFOFRAME_SIZE; return 0; } EXPORT_SYMBOL(hdmi_vendor_infoframe_init); static int hdmi_vendor_infoframe_length(const struct hdmi_vendor_infoframe *frame) { /* for side by side (half) we also need to provide 3D_Ext_Data */ if (frame->s3d_struct >= HDMI_3D_STRUCTURE_SIDE_BY_SIDE_HALF) return 6; else if (frame->vic != 0 || frame->s3d_struct != HDMI_3D_STRUCTURE_INVALID) return 5; else return 4; } static int hdmi_vendor_infoframe_check_only(const struct hdmi_vendor_infoframe *frame) { if (frame->type != HDMI_INFOFRAME_TYPE_VENDOR || frame->version != 1 || frame->oui != HDMI_IEEE_OUI) return -EINVAL; /* only one of those can be supplied */ if (frame->vic != 0 && frame->s3d_struct != HDMI_3D_STRUCTURE_INVALID) return -EINVAL; if (frame->length != hdmi_vendor_infoframe_length(frame)) return -EINVAL; return 0; } /** * hdmi_vendor_infoframe_check() - check a HDMI vendor infoframe * @frame: HDMI infoframe * * Validates that the infoframe is consistent and updates derived fields * (eg. length) based on other fields. * * Returns 0 on success or a negative error code on failure. */ int hdmi_vendor_infoframe_check(struct hdmi_vendor_infoframe *frame) { frame->length = hdmi_vendor_infoframe_length(frame); return hdmi_vendor_infoframe_check_only(frame); } EXPORT_SYMBOL(hdmi_vendor_infoframe_check); /** * hdmi_vendor_infoframe_pack_only() - write a HDMI vendor infoframe to binary buffer * @frame: HDMI infoframe * @buffer: destination buffer * @size: size of buffer * * Packs the information contained in the @frame structure into a binary * representation that can be written into the corresponding controller * registers. Also computes the checksum as required by section 5.3.5 of * the HDMI 1.4 specification. * * Returns the number of bytes packed into the binary buffer or a negative * error code on failure. */ ssize_t hdmi_vendor_infoframe_pack_only(const struct hdmi_vendor_infoframe *frame, void *buffer, size_t size) { u8 *ptr = buffer; size_t length; int ret; ret = hdmi_vendor_infoframe_check_only(frame); if (ret) return ret; length = HDMI_INFOFRAME_HEADER_SIZE + frame->length; if (size < length) return -ENOSPC; memset(buffer, 0, size); ptr[0] = frame->type; ptr[1] = frame->version; ptr[2] = frame->length; ptr[3] = 0; /* checksum */ /* HDMI OUI */ ptr[4] = 0x03; ptr[5] = 0x0c; ptr[6] = 0x00; if (frame->s3d_struct != HDMI_3D_STRUCTURE_INVALID) { ptr[7] = 0x2 << 5; /* video format */ ptr[8] = (frame->s3d_struct & 0xf) << 4; if (frame->s3d_struct >= HDMI_3D_STRUCTURE_SIDE_BY_SIDE_HALF) ptr[9] = (frame->s3d_ext_data & 0xf) << 4; } else if (frame->vic) { ptr[7] = 0x1 << 5; /* video format */ ptr[8] = frame->vic; } else { ptr[7] = 0x0 << 5; /* video format */ } hdmi_infoframe_set_checksum(buffer, length); return length; } EXPORT_SYMBOL(hdmi_vendor_infoframe_pack_only); /** * hdmi_vendor_infoframe_pack() - check a HDMI Vendor infoframe, * and write it to binary buffer * @frame: HDMI Vendor infoframe * @buffer: destination buffer * @size: size of buffer * * Validates that the infoframe is consistent and updates derived fields * (eg. length) based on other fields, after which it packs the information * contained in the @frame structure into a binary representation that * can be written into the corresponding controller registers. This function * also computes the checksum as required by section 5.3.5 of the HDMI 1.4 * specification. * * Returns the number of bytes packed into the binary buffer or a negative * error code on failure. */ ssize_t hdmi_vendor_infoframe_pack(struct hdmi_vendor_infoframe *frame, void *buffer, size_t size) { int ret; ret = hdmi_vendor_infoframe_check(frame); if (ret) return ret; return hdmi_vendor_infoframe_pack_only(frame, buffer, size); } EXPORT_SYMBOL(hdmi_vendor_infoframe_pack); static int hdmi_vendor_any_infoframe_check_only(const union hdmi_vendor_any_infoframe *frame) { if (frame->any.type != HDMI_INFOFRAME_TYPE_VENDOR || frame->any.version != 1) return -EINVAL; return 0; } /** * hdmi_drm_infoframe_init() - initialize an HDMI Dynaminc Range and * mastering infoframe * @frame: HDMI DRM infoframe * * Returns 0 on success or a negative error code on failure. */ int hdmi_drm_infoframe_init(struct hdmi_drm_infoframe *frame) { memset(frame, 0, sizeof(*frame)); frame->type = HDMI_INFOFRAME_TYPE_DRM; frame->version = 1; frame->length = HDMI_DRM_INFOFRAME_SIZE; return 0; } EXPORT_SYMBOL(hdmi_drm_infoframe_init); static int hdmi_drm_infoframe_check_only(const struct hdmi_drm_infoframe *frame) { if (frame->type != HDMI_INFOFRAME_TYPE_DRM || frame->version != 1) return -EINVAL; if (frame->length != HDMI_DRM_INFOFRAME_SIZE) return -EINVAL; return 0; } /** * hdmi_drm_infoframe_check() - check a HDMI DRM infoframe * @frame: HDMI DRM infoframe * * Validates that the infoframe is consistent. * Returns 0 on success or a negative error code on failure. */ int hdmi_drm_infoframe_check(struct hdmi_drm_infoframe *frame) { return hdmi_drm_infoframe_check_only(frame); } EXPORT_SYMBOL(hdmi_drm_infoframe_check); /** * hdmi_drm_infoframe_pack_only() - write HDMI DRM infoframe to binary buffer * @frame: HDMI DRM infoframe * @buffer: destination buffer * @size: size of buffer * * Packs the information contained in the @frame structure into a binary * representation that can be written into the corresponding controller * registers. Also computes the checksum as required by section 5.3.5 of * the HDMI 1.4 specification. * * Returns the number of bytes packed into the binary buffer or a negative * error code on failure. */ ssize_t hdmi_drm_infoframe_pack_only(const struct hdmi_drm_infoframe *frame, void *buffer, size_t size) { u8 *ptr = buffer; size_t length; int i; length = HDMI_INFOFRAME_HEADER_SIZE + frame->length; if (size < length) return -ENOSPC; memset(buffer, 0, size); ptr[0] = frame->type; ptr[1] = frame->version; ptr[2] = frame->length; ptr[3] = 0; /* checksum */ /* start infoframe payload */ ptr += HDMI_INFOFRAME_HEADER_SIZE; *ptr++ = frame->eotf; *ptr++ = frame->metadata_type; for (i = 0; i < 3; i++) { *ptr++ = frame->display_primaries[i].x; *ptr++ = frame->display_primaries[i].x >> 8; *ptr++ = frame->display_primaries[i].y; *ptr++ = frame->display_primaries[i].y >> 8; } *ptr++ = frame->white_point.x; *ptr++ = frame->white_point.x >> 8; *ptr++ = frame->white_point.y; *ptr++ = frame->white_point.y >> 8; *ptr++ = frame->max_display_mastering_luminance; *ptr++ = frame->max_display_mastering_luminance >> 8; *ptr++ = frame->min_display_mastering_luminance; *ptr++ = frame->min_display_mastering_luminance >> 8; *ptr++ = frame->max_cll; *ptr++ = frame->max_cll >> 8; *ptr++ = frame->max_fall; *ptr++ = frame->max_fall >> 8; hdmi_infoframe_set_checksum(buffer, length); return length; } EXPORT_SYMBOL(hdmi_drm_infoframe_pack_only); /** * hdmi_drm_infoframe_pack() - check a HDMI DRM infoframe, * and write it to binary buffer * @frame: HDMI DRM infoframe * @buffer: destination buffer * @size: size of buffer * * Validates that the infoframe is consistent and updates derived fields * (eg. length) based on other fields, after which it packs the information * contained in the @frame structure into a binary representation that * can be written into the corresponding controller registers. This function * also computes the checksum as required by section 5.3.5 of the HDMI 1.4 * specification. * * Returns the number of bytes packed into the binary buffer or a negative * error code on failure. */ ssize_t hdmi_drm_infoframe_pack(struct hdmi_drm_infoframe *frame, void *buffer, size_t size) { int ret; ret = hdmi_drm_infoframe_check(frame); if (ret) return ret; return hdmi_drm_infoframe_pack_only(frame, buffer, size); } EXPORT_SYMBOL(hdmi_drm_infoframe_pack); /* * hdmi_vendor_any_infoframe_check() - check a vendor infoframe */ static int hdmi_vendor_any_infoframe_check(union hdmi_vendor_any_infoframe *frame) { int ret; ret = hdmi_vendor_any_infoframe_check_only(frame); if (ret) return ret; /* we only know about HDMI vendor infoframes */ if (frame->any.oui != HDMI_IEEE_OUI) return -EINVAL; return hdmi_vendor_infoframe_check(&frame->hdmi); } /* * hdmi_vendor_any_infoframe_pack_only() - write a vendor infoframe to binary buffer */ static ssize_t hdmi_vendor_any_infoframe_pack_only(const union hdmi_vendor_any_infoframe *frame, void *buffer, size_t size) { int ret; ret = hdmi_vendor_any_infoframe_check_only(frame); if (ret) return ret; /* we only know about HDMI vendor infoframes */ if (frame->any.oui != HDMI_IEEE_OUI) return -EINVAL; return hdmi_vendor_infoframe_pack_only(&frame->hdmi, buffer, size); } /* * hdmi_vendor_any_infoframe_pack() - check a vendor infoframe, * and write it to binary buffer */ static ssize_t hdmi_vendor_any_infoframe_pack(union hdmi_vendor_any_infoframe *frame, void *buffer, size_t size) { int ret; ret = hdmi_vendor_any_infoframe_check(frame); if (ret) return ret; return hdmi_vendor_any_infoframe_pack_only(frame, buffer, size); } /** * hdmi_infoframe_check() - check a HDMI infoframe * @frame: HDMI infoframe * * Validates that the infoframe is consistent and updates derived fields * (eg. length) based on other fields. * * Returns 0 on success or a negative error code on failure. */ int hdmi_infoframe_check(union hdmi_infoframe *frame) { switch (frame->any.type) { case HDMI_INFOFRAME_TYPE_AVI: return hdmi_avi_infoframe_check(&frame->avi); case HDMI_INFOFRAME_TYPE_SPD: return hdmi_spd_infoframe_check(&frame->spd); case HDMI_INFOFRAME_TYPE_AUDIO: return hdmi_audio_infoframe_check(&frame->audio); case HDMI_INFOFRAME_TYPE_VENDOR: return hdmi_vendor_any_infoframe_check(&frame->vendor); default: WARN(1, "Bad infoframe type %d\n", frame->any.type); return -EINVAL; } } EXPORT_SYMBOL(hdmi_infoframe_check); /** * hdmi_infoframe_pack_only() - write a HDMI infoframe to binary buffer * @frame: HDMI infoframe * @buffer: destination buffer * @size: size of buffer * * Packs the information contained in the @frame structure into a binary * representation that can be written into the corresponding controller * registers. Also computes the checksum as required by section 5.3.5 of * the HDMI 1.4 specification. * * Returns the number of bytes packed into the binary buffer or a negative * error code on failure. */ ssize_t hdmi_infoframe_pack_only(const union hdmi_infoframe *frame, void *buffer, size_t size) { ssize_t length; switch (frame->any.type) { case HDMI_INFOFRAME_TYPE_AVI: length = hdmi_avi_infoframe_pack_only(&frame->avi, buffer, size); break; case HDMI_INFOFRAME_TYPE_DRM: length = hdmi_drm_infoframe_pack_only(&frame->drm, buffer, size); break; case HDMI_INFOFRAME_TYPE_SPD: length = hdmi_spd_infoframe_pack_only(&frame->spd, buffer, size); break; case HDMI_INFOFRAME_TYPE_AUDIO: length = hdmi_audio_infoframe_pack_only(&frame->audio, buffer, size); break; case HDMI_INFOFRAME_TYPE_VENDOR: length = hdmi_vendor_any_infoframe_pack_only(&frame->vendor, buffer, size); break; default: WARN(1, "Bad infoframe type %d\n", frame->any.type); length = -EINVAL; } return length; } EXPORT_SYMBOL(hdmi_infoframe_pack_only); /** * hdmi_infoframe_pack() - check a HDMI infoframe, * and write it to binary buffer * @frame: HDMI infoframe * @buffer: destination buffer * @size: size of buffer * * Validates that the infoframe is consistent and updates derived fields * (eg. length) based on other fields, after which it packs the information * contained in the @frame structure into a binary representation that * can be written into the corresponding controller registers. This function * also computes the checksum as required by section 5.3.5 of the HDMI 1.4 * specification. * * Returns the number of bytes packed into the binary buffer or a negative * error code on failure. */ ssize_t hdmi_infoframe_pack(union hdmi_infoframe *frame, void *buffer, size_t size) { ssize_t length; switch (frame->any.type) { case HDMI_INFOFRAME_TYPE_AVI: length = hdmi_avi_infoframe_pack(&frame->avi, buffer, size); break; case HDMI_INFOFRAME_TYPE_DRM: length = hdmi_drm_infoframe_pack(&frame->drm, buffer, size); break; case HDMI_INFOFRAME_TYPE_SPD: length = hdmi_spd_infoframe_pack(&frame->spd, buffer, size); break; case HDMI_INFOFRAME_TYPE_AUDIO: length = hdmi_audio_infoframe_pack(&frame->audio, buffer, size); break; case HDMI_INFOFRAME_TYPE_VENDOR: length = hdmi_vendor_any_infoframe_pack(&frame->vendor, buffer, size); break; default: WARN(1, "Bad infoframe type %d\n", frame->any.type); length = -EINVAL; } return length; } EXPORT_SYMBOL(hdmi_infoframe_pack); static const char *hdmi_infoframe_type_get_name(enum hdmi_infoframe_type type) { if (type < 0x80 || type > 0x9f) return "Invalid"; switch (type) { case HDMI_INFOFRAME_TYPE_VENDOR: return "Vendor"; case HDMI_INFOFRAME_TYPE_AVI: return "Auxiliary Video Information (AVI)"; case HDMI_INFOFRAME_TYPE_SPD: return "Source Product Description (SPD)"; case HDMI_INFOFRAME_TYPE_AUDIO: return "Audio"; case HDMI_INFOFRAME_TYPE_DRM: return "Dynamic Range and Mastering"; } return "Reserved"; } static void hdmi_infoframe_log_header(const char *level, struct device *dev, const struct hdmi_any_infoframe *frame) { hdmi_log("HDMI infoframe: %s, version %u, length %u\n", hdmi_infoframe_type_get_name(frame->type), frame->version, frame->length); } static const char *hdmi_colorspace_get_name(enum hdmi_colorspace colorspace) { switch (colorspace) { case HDMI_COLORSPACE_RGB: return "RGB"; case HDMI_COLORSPACE_YUV422: return "YCbCr 4:2:2"; case HDMI_COLORSPACE_YUV444: return "YCbCr 4:4:4"; case HDMI_COLORSPACE_YUV420: return "YCbCr 4:2:0"; case HDMI_COLORSPACE_RESERVED4: return "Reserved (4)"; case HDMI_COLORSPACE_RESERVED5: return "Reserved (5)"; case HDMI_COLORSPACE_RESERVED6: return "Reserved (6)"; case HDMI_COLORSPACE_IDO_DEFINED: return "IDO Defined"; } return "Invalid"; } static const char *hdmi_scan_mode_get_name(enum hdmi_scan_mode scan_mode) { switch (scan_mode) { case HDMI_SCAN_MODE_NONE: return "No Data"; case HDMI_SCAN_MODE_OVERSCAN: return "Overscan"; case HDMI_SCAN_MODE_UNDERSCAN: return "Underscan"; case HDMI_SCAN_MODE_RESERVED: return "Reserved"; } return "Invalid"; } static const char *hdmi_colorimetry_get_name(enum hdmi_colorimetry colorimetry) { switch (colorimetry) { case HDMI_COLORIMETRY_NONE: return "No Data"; case HDMI_COLORIMETRY_ITU_601: return "ITU601"; case HDMI_COLORIMETRY_ITU_709: return "ITU709"; case HDMI_COLORIMETRY_EXTENDED: return "Extended"; } return "Invalid"; } static const char * hdmi_picture_aspect_get_name(enum hdmi_picture_aspect picture_aspect) { switch (picture_aspect) { case HDMI_PICTURE_ASPECT_NONE: return "No Data"; case HDMI_PICTURE_ASPECT_4_3: return "4:3"; case HDMI_PICTURE_ASPECT_16_9: return "16:9"; case HDMI_PICTURE_ASPECT_64_27: return "64:27"; case HDMI_PICTURE_ASPECT_256_135: return "256:135"; case HDMI_PICTURE_ASPECT_RESERVED: return "Reserved"; } return "Invalid"; } static const char * hdmi_active_aspect_get_name(enum hdmi_active_aspect active_aspect) { if (active_aspect < 0 || active_aspect > 0xf) return "Invalid"; switch (active_aspect) { case HDMI_ACTIVE_ASPECT_16_9_TOP: return "16:9 Top"; case HDMI_ACTIVE_ASPECT_14_9_TOP: return "14:9 Top"; case HDMI_ACTIVE_ASPECT_16_9_CENTER: return "16:9 Center"; case HDMI_ACTIVE_ASPECT_PICTURE: return "Same as Picture"; case HDMI_ACTIVE_ASPECT_4_3: return "4:3"; case HDMI_ACTIVE_ASPECT_16_9: return "16:9"; case HDMI_ACTIVE_ASPECT_14_9: return "14:9"; case HDMI_ACTIVE_ASPECT_4_3_SP_14_9: return "4:3 SP 14:9"; case HDMI_ACTIVE_ASPECT_16_9_SP_14_9: return "16:9 SP 14:9"; case HDMI_ACTIVE_ASPECT_16_9_SP_4_3: return "16:9 SP 4:3"; } return "Reserved"; } static const char * hdmi_extended_colorimetry_get_name(enum hdmi_extended_colorimetry ext_col) { switch (ext_col) { case HDMI_EXTENDED_COLORIMETRY_XV_YCC_601: return "xvYCC 601"; case HDMI_EXTENDED_COLORIMETRY_XV_YCC_709: return "xvYCC 709"; case HDMI_EXTENDED_COLORIMETRY_S_YCC_601: return "sYCC 601"; case HDMI_EXTENDED_COLORIMETRY_OPYCC_601: return "opYCC 601"; case HDMI_EXTENDED_COLORIMETRY_OPRGB: return "opRGB"; case HDMI_EXTENDED_COLORIMETRY_BT2020_CONST_LUM: return "BT.2020 Constant Luminance"; case HDMI_EXTENDED_COLORIMETRY_BT2020: return "BT.2020"; case HDMI_EXTENDED_COLORIMETRY_RESERVED: return "Reserved"; } return "Invalid"; } static const char * hdmi_quantization_range_get_name(enum hdmi_quantization_range qrange) { switch (qrange) { case HDMI_QUANTIZATION_RANGE_DEFAULT: return "Default"; case HDMI_QUANTIZATION_RANGE_LIMITED: return "Limited"; case HDMI_QUANTIZATION_RANGE_FULL: return "Full"; case HDMI_QUANTIZATION_RANGE_RESERVED: return "Reserved"; } return "Invalid"; } static const char *hdmi_nups_get_name(enum hdmi_nups nups) { switch (nups) { case HDMI_NUPS_UNKNOWN: return "Unknown Non-uniform Scaling"; case HDMI_NUPS_HORIZONTAL: return "Horizontally Scaled"; case HDMI_NUPS_VERTICAL: return "Vertically Scaled"; case HDMI_NUPS_BOTH: return "Horizontally and Vertically Scaled"; } return "Invalid"; } static const char * hdmi_ycc_quantization_range_get_name(enum hdmi_ycc_quantization_range qrange) { switch (qrange) { case HDMI_YCC_QUANTIZATION_RANGE_LIMITED: return "Limited"; case HDMI_YCC_QUANTIZATION_RANGE_FULL: return "Full"; } return "Invalid"; } static const char * hdmi_content_type_get_name(enum hdmi_content_type content_type) { switch (content_type) { case HDMI_CONTENT_TYPE_GRAPHICS: return "Graphics"; case HDMI_CONTENT_TYPE_PHOTO: return "Photo"; case HDMI_CONTENT_TYPE_CINEMA: return "Cinema"; case HDMI_CONTENT_TYPE_GAME: return "Game"; } return "Invalid"; } static void hdmi_avi_infoframe_log(const char *level, struct device *dev, const struct hdmi_avi_infoframe *frame) { hdmi_infoframe_log_header(level, dev, (const struct hdmi_any_infoframe *)frame); hdmi_log(" colorspace: %s\n", hdmi_colorspace_get_name(frame->colorspace)); hdmi_log(" scan mode: %s\n", hdmi_scan_mode_get_name(frame->scan_mode)); hdmi_log(" colorimetry: %s\n", hdmi_colorimetry_get_name(frame->colorimetry)); hdmi_log(" picture aspect: %s\n", hdmi_picture_aspect_get_name(frame->picture_aspect)); hdmi_log(" active aspect: %s\n", hdmi_active_aspect_get_name(frame->active_aspect)); hdmi_log(" itc: %s\n", frame->itc ? "IT Content" : "No Data"); hdmi_log(" extended colorimetry: %s\n", hdmi_extended_colorimetry_get_name(frame->extended_colorimetry)); hdmi_log(" quantization range: %s\n", hdmi_quantization_range_get_name(frame->quantization_range)); hdmi_log(" nups: %s\n", hdmi_nups_get_name(frame->nups)); hdmi_log(" video code: %u\n", frame->video_code); hdmi_log(" ycc quantization range: %s\n", hdmi_ycc_quantization_range_get_name(frame->ycc_quantization_range)); hdmi_log(" hdmi content type: %s\n", hdmi_content_type_get_name(frame->content_type)); hdmi_log(" pixel repeat: %u\n", frame->pixel_repeat); hdmi_log(" bar top %u, bottom %u, left %u, right %u\n", frame->top_bar, frame->bottom_bar, frame->left_bar, frame->right_bar); } static const char *hdmi_spd_sdi_get_name(enum hdmi_spd_sdi sdi) { if (sdi < 0 || sdi > 0xff) return "Invalid"; switch (sdi) { case HDMI_SPD_SDI_UNKNOWN: return "Unknown"; case HDMI_SPD_SDI_DSTB: return "Digital STB"; case HDMI_SPD_SDI_DVDP: return "DVD Player"; case HDMI_SPD_SDI_DVHS: return "D-VHS"; case HDMI_SPD_SDI_HDDVR: return "HDD Videorecorder"; case HDMI_SPD_SDI_DVC: return "DVC"; case HDMI_SPD_SDI_DSC: return "DSC"; case HDMI_SPD_SDI_VCD: return "Video CD"; case HDMI_SPD_SDI_GAME: return "Game"; case HDMI_SPD_SDI_PC: return "PC General"; case HDMI_SPD_SDI_BD: return "Blu-Ray Disc (BD)"; case HDMI_SPD_SDI_SACD: return "Super Audio CD"; case HDMI_SPD_SDI_HDDVD: return "HD DVD"; case HDMI_SPD_SDI_PMP: return "PMP"; } return "Reserved"; } static void hdmi_spd_infoframe_log(const char *level, struct device *dev, const struct hdmi_spd_infoframe *frame) { u8 buf[17]; hdmi_infoframe_log_header(level, dev, (const struct hdmi_any_infoframe *)frame); memset(buf, 0, sizeof(buf)); strncpy(buf, frame->vendor, 8); hdmi_log(" vendor: %s\n", buf); strncpy(buf, frame->product, 16); hdmi_log(" product: %s\n", buf); hdmi_log(" source device information: %s (0x%x)\n", hdmi_spd_sdi_get_name(frame->sdi), frame->sdi); } static const char * hdmi_audio_coding_type_get_name(enum hdmi_audio_coding_type coding_type) { switch (coding_type) { case HDMI_AUDIO_CODING_TYPE_STREAM: return "Refer to Stream Header"; case HDMI_AUDIO_CODING_TYPE_PCM: return "PCM"; case HDMI_AUDIO_CODING_TYPE_AC3: return "AC-3"; case HDMI_AUDIO_CODING_TYPE_MPEG1: return "MPEG1"; case HDMI_AUDIO_CODING_TYPE_MP3: return "MP3"; case HDMI_AUDIO_CODING_TYPE_MPEG2: return "MPEG2"; case HDMI_AUDIO_CODING_TYPE_AAC_LC: return "AAC"; case HDMI_AUDIO_CODING_TYPE_DTS: return "DTS"; case HDMI_AUDIO_CODING_TYPE_ATRAC: return "ATRAC"; case HDMI_AUDIO_CODING_TYPE_DSD: return "One Bit Audio"; case HDMI_AUDIO_CODING_TYPE_EAC3: return "Dolby Digital +"; case HDMI_AUDIO_CODING_TYPE_DTS_HD: return "DTS-HD"; case HDMI_AUDIO_CODING_TYPE_MLP: return "MAT (MLP)"; case HDMI_AUDIO_CODING_TYPE_DST: return "DST"; case HDMI_AUDIO_CODING_TYPE_WMA_PRO: return "WMA PRO"; case HDMI_AUDIO_CODING_TYPE_CXT: return "Refer to CXT"; } return "Invalid"; } static const char * hdmi_audio_sample_size_get_name(enum hdmi_audio_sample_size sample_size) { switch (sample_size) { case HDMI_AUDIO_SAMPLE_SIZE_STREAM: return "Refer to Stream Header"; case HDMI_AUDIO_SAMPLE_SIZE_16: return "16 bit"; case HDMI_AUDIO_SAMPLE_SIZE_20: return "20 bit"; case HDMI_AUDIO_SAMPLE_SIZE_24: return "24 bit"; } return "Invalid"; } static const char * hdmi_audio_sample_frequency_get_name(enum hdmi_audio_sample_frequency freq) { switch (freq) { case HDMI_AUDIO_SAMPLE_FREQUENCY_STREAM: return "Refer to Stream Header"; case HDMI_AUDIO_SAMPLE_FREQUENCY_32000: return "32 kHz"; case HDMI_AUDIO_SAMPLE_FREQUENCY_44100: return "44.1 kHz (CD)"; case HDMI_AUDIO_SAMPLE_FREQUENCY_48000: return "48 kHz"; case HDMI_AUDIO_SAMPLE_FREQUENCY_88200: return "88.2 kHz"; case HDMI_AUDIO_SAMPLE_FREQUENCY_96000: return "96 kHz"; case HDMI_AUDIO_SAMPLE_FREQUENCY_176400: return "176.4 kHz"; case HDMI_AUDIO_SAMPLE_FREQUENCY_192000: return "192 kHz"; } return "Invalid"; } static const char * hdmi_audio_coding_type_ext_get_name(enum hdmi_audio_coding_type_ext ctx) { if (ctx < 0 || ctx > 0x1f) return "Invalid"; switch (ctx) { case HDMI_AUDIO_CODING_TYPE_EXT_CT: return "Refer to CT"; case HDMI_AUDIO_CODING_TYPE_EXT_HE_AAC: return "HE AAC"; case HDMI_AUDIO_CODING_TYPE_EXT_HE_AAC_V2: return "HE AAC v2"; case HDMI_AUDIO_CODING_TYPE_EXT_MPEG_SURROUND: return "MPEG SURROUND"; case HDMI_AUDIO_CODING_TYPE_EXT_MPEG4_HE_AAC: return "MPEG-4 HE AAC"; case HDMI_AUDIO_CODING_TYPE_EXT_MPEG4_HE_AAC_V2: return "MPEG-4 HE AAC v2"; case HDMI_AUDIO_CODING_TYPE_EXT_MPEG4_AAC_LC: return "MPEG-4 AAC LC"; case HDMI_AUDIO_CODING_TYPE_EXT_DRA: return "DRA"; case HDMI_AUDIO_CODING_TYPE_EXT_MPEG4_HE_AAC_SURROUND: return "MPEG-4 HE AAC + MPEG Surround"; case HDMI_AUDIO_CODING_TYPE_EXT_MPEG4_AAC_LC_SURROUND: return "MPEG-4 AAC LC + MPEG Surround"; } return "Reserved"; } static void hdmi_audio_infoframe_log(const char *level, struct device *dev, const struct hdmi_audio_infoframe *frame) { hdmi_infoframe_log_header(level, dev, (const struct hdmi_any_infoframe *)frame); if (frame->channels) hdmi_log(" channels: %u\n", frame->channels - 1); else hdmi_log(" channels: Refer to stream header\n"); hdmi_log(" coding type: %s\n", hdmi_audio_coding_type_get_name(frame->coding_type)); hdmi_log(" sample size: %s\n", hdmi_audio_sample_size_get_name(frame->sample_size)); hdmi_log(" sample frequency: %s\n", hdmi_audio_sample_frequency_get_name(frame->sample_frequency)); hdmi_log(" coding type ext: %s\n", hdmi_audio_coding_type_ext_get_name(frame->coding_type_ext)); hdmi_log(" channel allocation: 0x%x\n", frame->channel_allocation); hdmi_log(" level shift value: %u dB\n", frame->level_shift_value); hdmi_log(" downmix inhibit: %s\n", frame->downmix_inhibit ? "Yes" : "No"); } static void hdmi_drm_infoframe_log(const char *level, struct device *dev, const struct hdmi_drm_infoframe *frame) { int i; hdmi_infoframe_log_header(level, dev, (struct hdmi_any_infoframe *)frame); hdmi_log("length: %d\n", frame->length); hdmi_log("metadata type: %d\n", frame->metadata_type); hdmi_log("eotf: %d\n", frame->eotf); for (i = 0; i < 3; i++) { hdmi_log("x[%d]: %d\n", i, frame->display_primaries[i].x); hdmi_log("y[%d]: %d\n", i, frame->display_primaries[i].y); } hdmi_log("white point x: %d\n", frame->white_point.x); hdmi_log("white point y: %d\n", frame->white_point.y); hdmi_log("max_display_mastering_luminance: %d\n", frame->max_display_mastering_luminance); hdmi_log("min_display_mastering_luminance: %d\n", frame->min_display_mastering_luminance); hdmi_log("max_cll: %d\n", frame->max_cll); hdmi_log("max_fall: %d\n", frame->max_fall); } static const char * hdmi_3d_structure_get_name(enum hdmi_3d_structure s3d_struct) { if (s3d_struct < 0 || s3d_struct > 0xf) return "Invalid"; switch (s3d_struct) { case HDMI_3D_STRUCTURE_FRAME_PACKING: return "Frame Packing"; case HDMI_3D_STRUCTURE_FIELD_ALTERNATIVE: return "Field Alternative"; case HDMI_3D_STRUCTURE_LINE_ALTERNATIVE: return "Line Alternative"; case HDMI_3D_STRUCTURE_SIDE_BY_SIDE_FULL: return "Side-by-side (Full)"; case HDMI_3D_STRUCTURE_L_DEPTH: return "L + Depth"; case HDMI_3D_STRUCTURE_L_DEPTH_GFX_GFX_DEPTH: return "L + Depth + Graphics + Graphics-depth"; case HDMI_3D_STRUCTURE_TOP_AND_BOTTOM: return "Top-and-Bottom"; case HDMI_3D_STRUCTURE_SIDE_BY_SIDE_HALF: return "Side-by-side (Half)"; default: break; } return "Reserved"; } static void hdmi_vendor_any_infoframe_log(const char *level, struct device *dev, const union hdmi_vendor_any_infoframe *frame) { const struct hdmi_vendor_infoframe *hvf = &frame->hdmi; hdmi_infoframe_log_header(level, dev, (const struct hdmi_any_infoframe *)frame); if (frame->any.oui != HDMI_IEEE_OUI) { hdmi_log(" not a HDMI vendor infoframe\n"); return; } if (hvf->vic == 0 && hvf->s3d_struct == HDMI_3D_STRUCTURE_INVALID) { hdmi_log(" empty frame\n"); return; } if (hvf->vic) hdmi_log(" HDMI VIC: %u\n", hvf->vic); if (hvf->s3d_struct != HDMI_3D_STRUCTURE_INVALID) { hdmi_log(" 3D structure: %s\n", hdmi_3d_structure_get_name(hvf->s3d_struct)); if (hvf->s3d_struct >= HDMI_3D_STRUCTURE_SIDE_BY_SIDE_HALF) hdmi_log(" 3D extension data: %d\n", hvf->s3d_ext_data); } } /** * hdmi_infoframe_log() - log info of HDMI infoframe * @level: logging level * @dev: device * @frame: HDMI infoframe */ void hdmi_infoframe_log(const char *level, struct device *dev, const union hdmi_infoframe *frame) { switch (frame->any.type) { case HDMI_INFOFRAME_TYPE_AVI: hdmi_avi_infoframe_log(level, dev, &frame->avi); break; case HDMI_INFOFRAME_TYPE_SPD: hdmi_spd_infoframe_log(level, dev, &frame->spd); break; case HDMI_INFOFRAME_TYPE_AUDIO: hdmi_audio_infoframe_log(level, dev, &frame->audio); break; case HDMI_INFOFRAME_TYPE_VENDOR: hdmi_vendor_any_infoframe_log(level, dev, &frame->vendor); break; case HDMI_INFOFRAME_TYPE_DRM: hdmi_drm_infoframe_log(level, dev, &frame->drm); break; } } EXPORT_SYMBOL(hdmi_infoframe_log); /** * hdmi_avi_infoframe_unpack() - unpack binary buffer to a HDMI AVI infoframe * @frame: HDMI AVI infoframe * @buffer: source buffer * @size: size of buffer * * Unpacks the information contained in binary @buffer into a structured * @frame of the HDMI Auxiliary Video (AVI) information frame. * Also verifies the checksum as required by section 5.3.5 of the HDMI 1.4 * specification. * * Returns 0 on success or a negative error code on failure. */ static int hdmi_avi_infoframe_unpack(struct hdmi_avi_infoframe *frame, const void *buffer, size_t size) { const u8 *ptr = buffer; if (size < HDMI_INFOFRAME_SIZE(AVI)) return -EINVAL; if (ptr[0] != HDMI_INFOFRAME_TYPE_AVI || ptr[1] != 2 || ptr[2] != HDMI_AVI_INFOFRAME_SIZE) return -EINVAL; if (hdmi_infoframe_checksum(buffer, HDMI_INFOFRAME_SIZE(AVI)) != 0) return -EINVAL; hdmi_avi_infoframe_init(frame); ptr += HDMI_INFOFRAME_HEADER_SIZE; frame->colorspace = (ptr[0] >> 5) & 0x3; if (ptr[0] & 0x10) frame->active_aspect = ptr[1] & 0xf; if (ptr[0] & 0x8) { frame->top_bar = (ptr[6] << 8) | ptr[5]; frame->bottom_bar = (ptr[8] << 8) | ptr[7]; } if (ptr[0] & 0x4) { frame->left_bar = (ptr[10] << 8) | ptr[9]; frame->right_bar = (ptr[12] << 8) | ptr[11]; } frame->scan_mode = ptr[0] & 0x3; frame->colorimetry = (ptr[1] >> 6) & 0x3; frame->picture_aspect = (ptr[1] >> 4) & 0x3; frame->active_aspect = ptr[1] & 0xf; frame->itc = ptr[2] & 0x80 ? true : false; frame->extended_colorimetry = (ptr[2] >> 4) & 0x7; frame->quantization_range = (ptr[2] >> 2) & 0x3; frame->nups = ptr[2] & 0x3; frame->video_code = ptr[3] & 0x7f; frame->ycc_quantization_range = (ptr[4] >> 6) & 0x3; frame->content_type = (ptr[4] >> 4) & 0x3; frame->pixel_repeat = ptr[4] & 0xf; return 0; } /** * hdmi_spd_infoframe_unpack() - unpack binary buffer to a HDMI SPD infoframe * @frame: HDMI SPD infoframe * @buffer: source buffer * @size: size of buffer * * Unpacks the information contained in binary @buffer into a structured * @frame of the HDMI Source Product Description (SPD) information frame. * Also verifies the checksum as required by section 5.3.5 of the HDMI 1.4 * specification. * * Returns 0 on success or a negative error code on failure. */ static int hdmi_spd_infoframe_unpack(struct hdmi_spd_infoframe *frame, const void *buffer, size_t size) { const u8 *ptr = buffer; int ret; if (size < HDMI_INFOFRAME_SIZE(SPD)) return -EINVAL; if (ptr[0] != HDMI_INFOFRAME_TYPE_SPD || ptr[1] != 1 || ptr[2] != HDMI_SPD_INFOFRAME_SIZE) { return -EINVAL; } if (hdmi_infoframe_checksum(buffer, HDMI_INFOFRAME_SIZE(SPD)) != 0) return -EINVAL; ptr += HDMI_INFOFRAME_HEADER_SIZE; ret = hdmi_spd_infoframe_init(frame, ptr, ptr + 8); if (ret) return ret; frame->sdi = ptr[24]; return 0; } /** * hdmi_audio_infoframe_unpack() - unpack binary buffer to a HDMI AUDIO infoframe * @frame: HDMI Audio infoframe * @buffer: source buffer * @size: size of buffer * * Unpacks the information contained in binary @buffer into a structured * @frame of the HDMI Audio information frame. * Also verifies the checksum as required by section 5.3.5 of the HDMI 1.4 * specification. * * Returns 0 on success or a negative error code on failure. */ static int hdmi_audio_infoframe_unpack(struct hdmi_audio_infoframe *frame, const void *buffer, size_t size) { const u8 *ptr = buffer; int ret; if (size < HDMI_INFOFRAME_SIZE(AUDIO)) return -EINVAL; if (ptr[0] != HDMI_INFOFRAME_TYPE_AUDIO || ptr[1] != 1 || ptr[2] != HDMI_AUDIO_INFOFRAME_SIZE) { return -EINVAL; } if (hdmi_infoframe_checksum(buffer, HDMI_INFOFRAME_SIZE(AUDIO)) != 0) return -EINVAL; ret = hdmi_audio_infoframe_init(frame); if (ret) return ret; ptr += HDMI_INFOFRAME_HEADER_SIZE; frame->channels = ptr[0] & 0x7; frame->coding_type = (ptr[0] >> 4) & 0xf; frame->sample_size = ptr[1] & 0x3; frame->sample_frequency = (ptr[1] >> 2) & 0x7; frame->coding_type_ext = ptr[2] & 0x1f; frame->channel_allocation = ptr[3]; frame->level_shift_value = (ptr[4] >> 3) & 0xf; frame->downmix_inhibit = ptr[4] & 0x80 ? true : false; return 0; } /** * hdmi_vendor_any_infoframe_unpack() - unpack binary buffer to a HDMI * vendor infoframe * @frame: HDMI Vendor infoframe * @buffer: source buffer * @size: size of buffer * * Unpacks the information contained in binary @buffer into a structured * @frame of the HDMI Vendor information frame. * Also verifies the checksum as required by section 5.3.5 of the HDMI 1.4 * specification. * * Returns 0 on success or a negative error code on failure. */ static int hdmi_vendor_any_infoframe_unpack(union hdmi_vendor_any_infoframe *frame, const void *buffer, size_t size) { const u8 *ptr = buffer; size_t length; int ret; u8 hdmi_video_format; struct hdmi_vendor_infoframe *hvf = &frame->hdmi; if (size < HDMI_INFOFRAME_HEADER_SIZE) return -EINVAL; if (ptr[0] != HDMI_INFOFRAME_TYPE_VENDOR || ptr[1] != 1 || (ptr[2] != 4 && ptr[2] != 5 && ptr[2] != 6)) return -EINVAL; length = ptr[2]; if (size < HDMI_INFOFRAME_HEADER_SIZE + length) return -EINVAL; if (hdmi_infoframe_checksum(buffer, HDMI_INFOFRAME_HEADER_SIZE + length) != 0) return -EINVAL; ptr += HDMI_INFOFRAME_HEADER_SIZE; /* HDMI OUI */ if ((ptr[0] != 0x03) || (ptr[1] != 0x0c) || (ptr[2] != 0x00)) return -EINVAL; hdmi_video_format = ptr[3] >> 5; if (hdmi_video_format > 0x2) return -EINVAL; ret = hdmi_vendor_infoframe_init(hvf); if (ret) return ret; hvf->length = length; if (hdmi_video_format == 0x2) { if (length != 5 && length != 6) return -EINVAL; hvf->s3d_struct = ptr[4] >> 4; if (hvf->s3d_struct >= HDMI_3D_STRUCTURE_SIDE_BY_SIDE_HALF) { if (length != 6) return -EINVAL; hvf->s3d_ext_data = ptr[5] >> 4; } } else if (hdmi_video_format == 0x1) { if (length != 5) return -EINVAL; hvf->vic = ptr[4]; } else { if (length != 4) return -EINVAL; } return 0; } /** * hdmi_drm_infoframe_unpack_only() - unpack binary buffer of CTA-861-G DRM * infoframe DataBytes to a HDMI DRM * infoframe * @frame: HDMI DRM infoframe * @buffer: source buffer * @size: size of buffer * * Unpacks CTA-861-G DRM infoframe DataBytes contained in the binary @buffer * into a structured @frame of the HDMI Dynamic Range and Mastering (DRM) * infoframe. * * Returns 0 on success or a negative error code on failure. */ int hdmi_drm_infoframe_unpack_only(struct hdmi_drm_infoframe *frame, const void *buffer, size_t size) { const u8 *ptr = buffer; const u8 *temp; u8 x_lsb, x_msb; u8 y_lsb, y_msb; int ret; int i; if (size < HDMI_DRM_INFOFRAME_SIZE) return -EINVAL; ret = hdmi_drm_infoframe_init(frame); if (ret) return ret; frame->eotf = ptr[0] & 0x7; frame->metadata_type = ptr[1] & 0x7; temp = ptr + 2; for (i = 0; i < 3; i++) { x_lsb = *temp++; x_msb = *temp++; frame->display_primaries[i].x = (x_msb << 8) | x_lsb; y_lsb = *temp++; y_msb = *temp++; frame->display_primaries[i].y = (y_msb << 8) | y_lsb; } frame->white_point.x = (ptr[15] << 8) | ptr[14]; frame->white_point.y = (ptr[17] << 8) | ptr[16]; frame->max_display_mastering_luminance = (ptr[19] << 8) | ptr[18]; frame->min_display_mastering_luminance = (ptr[21] << 8) | ptr[20]; frame->max_cll = (ptr[23] << 8) | ptr[22]; frame->max_fall = (ptr[25] << 8) | ptr[24]; return 0; } EXPORT_SYMBOL(hdmi_drm_infoframe_unpack_only); /** * hdmi_drm_infoframe_unpack() - unpack binary buffer to a HDMI DRM infoframe * @frame: HDMI DRM infoframe * @buffer: source buffer * @size: size of buffer * * Unpacks the CTA-861-G DRM infoframe contained in the binary @buffer into * a structured @frame of the HDMI Dynamic Range and Mastering (DRM) * infoframe. It also verifies the checksum as required by section 5.3.5 of * the HDMI 1.4 specification. * * Returns 0 on success or a negative error code on failure. */ static int hdmi_drm_infoframe_unpack(struct hdmi_drm_infoframe *frame, const void *buffer, size_t size) { const u8 *ptr = buffer; int ret; if (size < HDMI_INFOFRAME_SIZE(DRM)) return -EINVAL; if (ptr[0] != HDMI_INFOFRAME_TYPE_DRM || ptr[1] != 1 || ptr[2] != HDMI_DRM_INFOFRAME_SIZE) return -EINVAL; if (hdmi_infoframe_checksum(buffer, HDMI_INFOFRAME_SIZE(DRM)) != 0) return -EINVAL; ret = hdmi_drm_infoframe_unpack_only(frame, ptr + HDMI_INFOFRAME_HEADER_SIZE, size - HDMI_INFOFRAME_HEADER_SIZE); return ret; } /** * hdmi_infoframe_unpack() - unpack binary buffer to a HDMI infoframe * @frame: HDMI infoframe * @buffer: source buffer * @size: size of buffer * * Unpacks the information contained in binary buffer @buffer into a structured * @frame of a HDMI infoframe. * Also verifies the checksum as required by section 5.3.5 of the HDMI 1.4 * specification. * * Returns 0 on success or a negative error code on failure. */ int hdmi_infoframe_unpack(union hdmi_infoframe *frame, const void *buffer, size_t size) { int ret; const u8 *ptr = buffer; if (size < HDMI_INFOFRAME_HEADER_SIZE) return -EINVAL; switch (ptr[0]) { case HDMI_INFOFRAME_TYPE_AVI: ret = hdmi_avi_infoframe_unpack(&frame->avi, buffer, size); break; case HDMI_INFOFRAME_TYPE_DRM: ret = hdmi_drm_infoframe_unpack(&frame->drm, buffer, size); break; case HDMI_INFOFRAME_TYPE_SPD: ret = hdmi_spd_infoframe_unpack(&frame->spd, buffer, size); break; case HDMI_INFOFRAME_TYPE_AUDIO: ret = hdmi_audio_infoframe_unpack(&frame->audio, buffer, size); break; case HDMI_INFOFRAME_TYPE_VENDOR: ret = hdmi_vendor_any_infoframe_unpack(&frame->vendor, buffer, size); break; default: ret = -EINVAL; break; } return ret; } EXPORT_SYMBOL(hdmi_infoframe_unpack);
linux-master
drivers/video/hdmi.c
// SPDX-License-Identifier: GPL-2.0-only /* * generic videomode helper * * Copyright (c) 2012 Steffen Trumtrar <[email protected]>, Pengutronix */ #include <linux/errno.h> #include <linux/export.h> #include <linux/of.h> #include <video/display_timing.h> #include <video/of_display_timing.h> #include <video/of_videomode.h> #include <video/videomode.h> /** * of_get_videomode - get the videomode #<index> from devicetree * @np: devicenode with the display_timings * @vm: set to return value * @index: index into list of display_timings * (Set this to OF_USE_NATIVE_MODE to use whatever mode is * specified as native mode in the DT.) * * DESCRIPTION: * Get a list of all display timings and put the one * specified by index into *vm. This function should only be used, if * only one videomode is to be retrieved. A driver that needs to work * with multiple/all videomodes should work with * of_get_display_timings instead. **/ int of_get_videomode(struct device_node *np, struct videomode *vm, int index) { struct display_timings *disp; int ret; disp = of_get_display_timings(np); if (!disp) { pr_err("%pOF: no timings specified\n", np); return -EINVAL; } if (index == OF_USE_NATIVE_MODE) index = disp->native_mode; ret = videomode_from_timings(disp, vm, index); display_timings_release(disp); return ret; } EXPORT_SYMBOL_GPL(of_get_videomode);
linux-master
drivers/video/of_videomode.c
// SPDX-License-Identifier: GPL-2.0-only /* * generic display timing functions * * Copyright (c) 2012 Steffen Trumtrar <[email protected]>, Pengutronix */ #include <linux/errno.h> #include <linux/export.h> #include <video/display_timing.h> #include <video/videomode.h> void videomode_from_timing(const struct display_timing *dt, struct videomode *vm) { vm->pixelclock = dt->pixelclock.typ; vm->hactive = dt->hactive.typ; vm->hfront_porch = dt->hfront_porch.typ; vm->hback_porch = dt->hback_porch.typ; vm->hsync_len = dt->hsync_len.typ; vm->vactive = dt->vactive.typ; vm->vfront_porch = dt->vfront_porch.typ; vm->vback_porch = dt->vback_porch.typ; vm->vsync_len = dt->vsync_len.typ; vm->flags = dt->flags; } EXPORT_SYMBOL_GPL(videomode_from_timing); int videomode_from_timings(const struct display_timings *disp, struct videomode *vm, unsigned int index) { struct display_timing *dt; dt = display_timings_get(disp, index); if (!dt) return -EINVAL; videomode_from_timing(dt, vm); return 0; } EXPORT_SYMBOL_GPL(videomode_from_timings);
linux-master
drivers/video/videomode.c
// SPDX-License-Identifier: MIT #include <linux/aperture.h> #include <linux/device.h> #include <linux/list.h> #include <linux/mutex.h> #include <linux/pci.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/sysfb.h> #include <linux/types.h> #include <linux/vgaarb.h> #include <video/vga.h> /** * DOC: overview * * A graphics device might be supported by different drivers, but only one * driver can be active at any given time. Many systems load a generic * graphics drivers, such as EFI-GOP or VESA, early during the boot process. * During later boot stages, they replace the generic driver with a dedicated, * hardware-specific driver. To take over the device, the dedicated driver * first has to remove the generic driver. Aperture functions manage * ownership of framebuffer memory and hand-over between drivers. * * Graphics drivers should call aperture_remove_conflicting_devices() * at the top of their probe function. The function removes any generic * driver that is currently associated with the given framebuffer memory. * An example for a graphics device on the platform bus is shown below. * * .. code-block:: c * * static int example_probe(struct platform_device *pdev) * { * struct resource *mem; * resource_size_t base, size; * int ret; * * mem = platform_get_resource(pdev, IORESOURCE_MEM, 0); * if (!mem) * return -ENODEV; * base = mem->start; * size = resource_size(mem); * * ret = aperture_remove_conflicting_devices(base, size, "example"); * if (ret) * return ret; * * // Initialize the hardware * ... * * return 0; * } * * static const struct platform_driver example_driver = { * .probe = example_probe, * ... * }; * * The given example reads the platform device's I/O-memory range from the * device instance. An active framebuffer will be located within this range. * The call to aperture_remove_conflicting_devices() releases drivers that * have previously claimed ownership of the range and are currently driving * output on the framebuffer. If successful, the new driver can take over * the device. * * While the given example uses a platform device, the aperture helpers work * with every bus that has an addressable framebuffer. In the case of PCI, * device drivers can also call aperture_remove_conflicting_pci_devices() and * let the function detect the apertures automatically. Device drivers without * knowledge of the framebuffer's location can call * aperture_remove_all_conflicting_devices(), which removes all known devices. * * Drivers that are susceptible to being removed by other drivers, such as * generic EFI or VESA drivers, have to register themselves as owners of their * framebuffer apertures. Ownership of the framebuffer memory is achieved * by calling devm_aperture_acquire_for_platform_device(). If successful, the * driver is the owner of the framebuffer range. The function fails if the * framebuffer is already owned by another driver. See below for an example. * * .. code-block:: c * * static int generic_probe(struct platform_device *pdev) * { * struct resource *mem; * resource_size_t base, size; * * mem = platform_get_resource(pdev, IORESOURCE_MEM, 0); * if (!mem) * return -ENODEV; * base = mem->start; * size = resource_size(mem); * * ret = devm_aperture_acquire_for_platform_device(pdev, base, size); * if (ret) * return ret; * * // Initialize the hardware * ... * * return 0; * } * * static int generic_remove(struct platform_device *) * { * // Hot-unplug the device * ... * * return 0; * } * * static const struct platform_driver generic_driver = { * .probe = generic_probe, * .remove = generic_remove, * ... * }; * * The similar to the previous example, the generic driver claims ownership * of the framebuffer memory from its probe function. This will fail if the * memory range, or parts of it, is already owned by another driver. * * If successful, the generic driver is now subject to forced removal by * another driver. This only works for platform drivers that support hot * unplugging. When a driver calls aperture_remove_conflicting_devices() * et al for the registered framebuffer range, the aperture helpers call * platform_device_unregister() and the generic driver unloads itself. The * generic driver also has to provide a remove function to make this work. * Once hot unplugged from hardware, it may not access the device's * registers, framebuffer memory, ROM, etc afterwards. */ struct aperture_range { struct device *dev; resource_size_t base; resource_size_t size; struct list_head lh; void (*detach)(struct device *dev); }; static LIST_HEAD(apertures); static DEFINE_MUTEX(apertures_lock); static bool overlap(resource_size_t base1, resource_size_t end1, resource_size_t base2, resource_size_t end2) { return (base1 < end2) && (end1 > base2); } static void devm_aperture_acquire_release(void *data) { struct aperture_range *ap = data; bool detached = !ap->dev; if (detached) return; mutex_lock(&apertures_lock); list_del(&ap->lh); mutex_unlock(&apertures_lock); } static int devm_aperture_acquire(struct device *dev, resource_size_t base, resource_size_t size, void (*detach)(struct device *)) { size_t end = base + size; struct list_head *pos; struct aperture_range *ap; mutex_lock(&apertures_lock); list_for_each(pos, &apertures) { ap = container_of(pos, struct aperture_range, lh); if (overlap(base, end, ap->base, ap->base + ap->size)) { mutex_unlock(&apertures_lock); return -EBUSY; } } ap = devm_kzalloc(dev, sizeof(*ap), GFP_KERNEL); if (!ap) { mutex_unlock(&apertures_lock); return -ENOMEM; } ap->dev = dev; ap->base = base; ap->size = size; ap->detach = detach; INIT_LIST_HEAD(&ap->lh); list_add(&ap->lh, &apertures); mutex_unlock(&apertures_lock); return devm_add_action_or_reset(dev, devm_aperture_acquire_release, ap); } static void aperture_detach_platform_device(struct device *dev) { struct platform_device *pdev = to_platform_device(dev); /* * Remove the device from the device hierarchy. This is the right thing * to do for firmware-based fb drivers, such as EFI, VESA or VGA. After * the new driver takes over the hardware, the firmware device's state * will be lost. * * For non-platform devices, a new callback would be required. * * If the aperture helpers ever need to handle native drivers, this call * would only have to unplug the DRM device, so that the hardware device * stays around after detachment. */ platform_device_unregister(pdev); } /** * devm_aperture_acquire_for_platform_device - Acquires ownership of an aperture * on behalf of a platform device. * @pdev: the platform device to own the aperture * @base: the aperture's byte offset in physical memory * @size: the aperture size in bytes * * Installs the given device as the new owner of the aperture. The function * expects the aperture to be provided by a platform device. If another * driver takes over ownership of the aperture, aperture helpers will then * unregister the platform device automatically. All acquired apertures are * released automatically when the underlying device goes away. * * The function fails if the aperture, or parts of it, is currently * owned by another device. To evict current owners, callers should use * remove_conflicting_devices() et al. before calling this function. * * Returns: * 0 on success, or a negative errno value otherwise. */ int devm_aperture_acquire_for_platform_device(struct platform_device *pdev, resource_size_t base, resource_size_t size) { return devm_aperture_acquire(&pdev->dev, base, size, aperture_detach_platform_device); } EXPORT_SYMBOL(devm_aperture_acquire_for_platform_device); static void aperture_detach_devices(resource_size_t base, resource_size_t size) { resource_size_t end = base + size; struct list_head *pos, *n; mutex_lock(&apertures_lock); list_for_each_safe(pos, n, &apertures) { struct aperture_range *ap = container_of(pos, struct aperture_range, lh); struct device *dev = ap->dev; if (WARN_ON_ONCE(!dev)) continue; if (!overlap(base, end, ap->base, ap->base + ap->size)) continue; ap->dev = NULL; /* detach from device */ list_del(&ap->lh); ap->detach(dev); } mutex_unlock(&apertures_lock); } /** * aperture_remove_conflicting_devices - remove devices in the given range * @base: the aperture's base address in physical memory * @size: aperture size in bytes * @name: a descriptive name of the requesting driver * * This function removes devices that own apertures within @base and @size. * * Returns: * 0 on success, or a negative errno code otherwise */ int aperture_remove_conflicting_devices(resource_size_t base, resource_size_t size, const char *name) { /* * If a driver asked to unregister a platform device registered by * sysfb, then can be assumed that this is a driver for a display * that is set up by the system firmware and has a generic driver. * * Drivers for devices that don't have a generic driver will never * ask for this, so let's assume that a real driver for the display * was already probed and prevent sysfb to register devices later. */ sysfb_disable(); aperture_detach_devices(base, size); return 0; } EXPORT_SYMBOL(aperture_remove_conflicting_devices); /** * __aperture_remove_legacy_vga_devices - remove legacy VGA devices of a PCI devices * @pdev: PCI device * * This function removes VGA devices provided by @pdev, such as a VGA * framebuffer or a console. This is useful if you have a VGA-compatible * PCI graphics device with framebuffers in non-BAR locations. Drivers * should acquire ownership of those memory areas and afterwards call * this helper to release remaining VGA devices. * * If your hardware has its framebuffers accessible via PCI BARS, use * aperture_remove_conflicting_pci_devices() instead. The function will * release any VGA devices automatically. * * WARNING: Apparently we must remove graphics drivers before calling * this helper. Otherwise the vga fbdev driver falls over if * we have vgacon configured. * * Returns: * 0 on success, or a negative errno code otherwise */ int __aperture_remove_legacy_vga_devices(struct pci_dev *pdev) { /* VGA framebuffer */ aperture_detach_devices(VGA_FB_PHYS_BASE, VGA_FB_PHYS_SIZE); /* VGA textmode console */ return vga_remove_vgacon(pdev); } EXPORT_SYMBOL(__aperture_remove_legacy_vga_devices); /** * aperture_remove_conflicting_pci_devices - remove existing framebuffers for PCI devices * @pdev: PCI device * @name: a descriptive name of the requesting driver * * This function removes devices that own apertures within any of @pdev's * memory bars. The function assumes that PCI device with shadowed ROM * drives a primary display and therefore kicks out vga16fb as well. * * Returns: * 0 on success, or a negative errno code otherwise */ int aperture_remove_conflicting_pci_devices(struct pci_dev *pdev, const char *name) { bool primary = false; resource_size_t base, size; int bar, ret = 0; if (pdev == vga_default_device()) primary = true; if (primary) sysfb_disable(); for (bar = 0; bar < PCI_STD_NUM_BARS; ++bar) { if (!(pci_resource_flags(pdev, bar) & IORESOURCE_MEM)) continue; base = pci_resource_start(pdev, bar); size = pci_resource_len(pdev, bar); aperture_detach_devices(base, size); } /* * If this is the primary adapter, there could be a VGA device * that consumes the VGA framebuffer I/O range. Remove this * device as well. */ if (primary) ret = __aperture_remove_legacy_vga_devices(pdev); return ret; } EXPORT_SYMBOL(aperture_remove_conflicting_pci_devices);
linux-master
drivers/video/aperture.c
// SPDX-License-Identifier: GPL-2.0 /* * Based on the fbdev code in drivers/video/fbdev/core/fb_cmdline: * * Copyright (C) 2014 Intel Corp * Copyright (C) 1994 Martin Schaller * * 2001 - Documented with DocBook * - Brad Douglas <[email protected]> * * This file is subject to the terms and conditions of the GNU General Public * License. See the file COPYING in the main directory of this archive * for more details. * * Authors: * Daniel Vetter <[email protected]> */ #include <linux/fb.h> /* for FB_MAX */ #include <linux/init.h> #include <video/cmdline.h> /* * FB_MAX is the maximum number of framebuffer devices and also * the maximum number of video= parameters. Although not directly * related to each other, it makes sense to keep it that way. */ static const char *video_options[FB_MAX] __read_mostly; static const char *video_option __read_mostly; static int video_of_only __read_mostly; static const char *__video_get_option_string(const char *name) { const char *options = NULL; size_t name_len = 0; if (name) name_len = strlen(name); if (name_len) { unsigned int i; const char *opt; for (i = 0; i < ARRAY_SIZE(video_options); ++i) { if (!video_options[i]) continue; if (video_options[i][0] == '\0') continue; opt = video_options[i]; if (!strncmp(opt, name, name_len) && opt[name_len] == ':') options = opt + name_len + 1; } } /* No match, return global options */ if (!options) options = video_option; return options; } /** * video_get_options - get kernel boot parameters * @name: name of the output as it would appear in the boot parameter * line (video=<name>:<options>) * * Looks up the video= options for the given name. Names are connector * names with DRM, or driver names with fbdev. If no video option for * the name has been specified, the function returns the global video= * setting. A @name of NULL always returns the global video setting. * * Returns: * The string of video options for the given name, or NULL if no video * option has been specified. */ const char *video_get_options(const char *name) { return __video_get_option_string(name); } EXPORT_SYMBOL(video_get_options); bool __video_get_options(const char *name, const char **options, bool is_of) { bool enabled = true; const char *opt = NULL; if (video_of_only && !is_of) enabled = false; opt = __video_get_option_string(name); if (options) *options = opt; return enabled; } EXPORT_SYMBOL(__video_get_options); /* * Process command line options for video adapters. This function is * a __setup and __init function. It only stores the options. Drivers * have to call video_get_options() as necessary. */ static int __init video_setup(char *options) { if (!options || !*options) goto out; if (!strncmp(options, "ofonly", 6)) { video_of_only = true; goto out; } if (strchr(options, ':')) { /* named */ size_t i; for (i = 0; i < ARRAY_SIZE(video_options); i++) { if (!video_options[i]) { video_options[i] = options; break; } } } else { /* global */ video_option = options; } out: return 1; } __setup("video=", video_setup);
linux-master
drivers/video/cmdline.c
// SPDX-License-Identifier: GPL-2.0-only /* * OF helpers for parsing display timings * * Copyright (c) 2012 Steffen Trumtrar <[email protected]>, Pengutronix * * based on of_videomode.c by Sascha Hauer <[email protected]> */ #include <linux/export.h> #include <linux/of.h> #include <linux/slab.h> #include <video/display_timing.h> #include <video/of_display_timing.h> /** * parse_timing_property - parse timing_entry from device_node * @np: device_node with the property * @name: name of the property * @result: will be set to the return value * * DESCRIPTION: * Every display_timing can be specified with either just the typical value or * a range consisting of min/typ/max. This function helps handling this **/ static int parse_timing_property(const struct device_node *np, const char *name, struct timing_entry *result) { struct property *prop; int length, cells, ret; prop = of_find_property(np, name, &length); if (!prop) { pr_err("%pOF: could not find property %s\n", np, name); return -EINVAL; } cells = length / sizeof(u32); if (cells == 1) { ret = of_property_read_u32(np, name, &result->typ); result->min = result->typ; result->max = result->typ; } else if (cells == 3) { ret = of_property_read_u32_array(np, name, &result->min, cells); } else { pr_err("%pOF: illegal timing specification in %s\n", np, name); return -EINVAL; } return ret; } /** * of_parse_display_timing - parse display_timing entry from device_node * @np: device_node with the properties * @dt: display_timing that contains the result. I may be partially written in case of errors **/ static int of_parse_display_timing(const struct device_node *np, struct display_timing *dt) { u32 val = 0; int ret = 0; memset(dt, 0, sizeof(*dt)); ret |= parse_timing_property(np, "hback-porch", &dt->hback_porch); ret |= parse_timing_property(np, "hfront-porch", &dt->hfront_porch); ret |= parse_timing_property(np, "hactive", &dt->hactive); ret |= parse_timing_property(np, "hsync-len", &dt->hsync_len); ret |= parse_timing_property(np, "vback-porch", &dt->vback_porch); ret |= parse_timing_property(np, "vfront-porch", &dt->vfront_porch); ret |= parse_timing_property(np, "vactive", &dt->vactive); ret |= parse_timing_property(np, "vsync-len", &dt->vsync_len); ret |= parse_timing_property(np, "clock-frequency", &dt->pixelclock); dt->flags = 0; if (!of_property_read_u32(np, "vsync-active", &val)) dt->flags |= val ? DISPLAY_FLAGS_VSYNC_HIGH : DISPLAY_FLAGS_VSYNC_LOW; if (!of_property_read_u32(np, "hsync-active", &val)) dt->flags |= val ? DISPLAY_FLAGS_HSYNC_HIGH : DISPLAY_FLAGS_HSYNC_LOW; if (!of_property_read_u32(np, "de-active", &val)) dt->flags |= val ? DISPLAY_FLAGS_DE_HIGH : DISPLAY_FLAGS_DE_LOW; if (!of_property_read_u32(np, "pixelclk-active", &val)) dt->flags |= val ? DISPLAY_FLAGS_PIXDATA_POSEDGE : DISPLAY_FLAGS_PIXDATA_NEGEDGE; if (!of_property_read_u32(np, "syncclk-active", &val)) dt->flags |= val ? DISPLAY_FLAGS_SYNC_POSEDGE : DISPLAY_FLAGS_SYNC_NEGEDGE; else if (dt->flags & (DISPLAY_FLAGS_PIXDATA_POSEDGE | DISPLAY_FLAGS_PIXDATA_NEGEDGE)) dt->flags |= dt->flags & DISPLAY_FLAGS_PIXDATA_POSEDGE ? DISPLAY_FLAGS_SYNC_POSEDGE : DISPLAY_FLAGS_SYNC_NEGEDGE; if (of_property_read_bool(np, "interlaced")) dt->flags |= DISPLAY_FLAGS_INTERLACED; if (of_property_read_bool(np, "doublescan")) dt->flags |= DISPLAY_FLAGS_DOUBLESCAN; if (of_property_read_bool(np, "doubleclk")) dt->flags |= DISPLAY_FLAGS_DOUBLECLK; if (ret) { pr_err("%pOF: error reading timing properties\n", np); return -EINVAL; } return 0; } /** * of_get_display_timing - parse a display_timing entry * @np: device_node with the timing subnode * @name: name of the timing node * @dt: display_timing struct to fill **/ int of_get_display_timing(const struct device_node *np, const char *name, struct display_timing *dt) { struct device_node *timing_np; int ret; if (!np) return -EINVAL; timing_np = of_get_child_by_name(np, name); if (!timing_np) return -ENOENT; ret = of_parse_display_timing(timing_np, dt); of_node_put(timing_np); return ret; } EXPORT_SYMBOL_GPL(of_get_display_timing); /** * of_get_display_timings - parse all display_timing entries from a device_node * @np: device_node with the subnodes **/ struct display_timings *of_get_display_timings(const struct device_node *np) { struct device_node *timings_np; struct device_node *entry; struct device_node *native_mode; struct display_timings *disp; if (!np) return NULL; timings_np = of_get_child_by_name(np, "display-timings"); if (!timings_np) { pr_err("%pOF: could not find display-timings node\n", np); return NULL; } disp = kzalloc(sizeof(*disp), GFP_KERNEL); if (!disp) { pr_err("%pOF: could not allocate struct disp'\n", np); goto dispfail; } entry = of_parse_phandle(timings_np, "native-mode", 0); /* assume first child as native mode if none provided */ if (!entry) entry = of_get_next_child(timings_np, NULL); /* if there is no child, it is useless to go on */ if (!entry) { pr_err("%pOF: no timing specifications given\n", np); goto entryfail; } pr_debug("%pOF: using %pOFn as default timing\n", np, entry); native_mode = entry; disp->num_timings = of_get_child_count(timings_np); if (disp->num_timings == 0) { /* should never happen, as entry was already found above */ pr_err("%pOF: no timings specified\n", np); goto entryfail; } disp->timings = kcalloc(disp->num_timings, sizeof(struct display_timing *), GFP_KERNEL); if (!disp->timings) { pr_err("%pOF: could not allocate timings array\n", np); goto entryfail; } disp->num_timings = 0; disp->native_mode = 0; for_each_child_of_node(timings_np, entry) { struct display_timing *dt; int r; dt = kmalloc(sizeof(*dt), GFP_KERNEL); if (!dt) { pr_err("%pOF: could not allocate display_timing struct\n", np); goto timingfail; } r = of_parse_display_timing(entry, dt); if (r) { /* * to not encourage wrong devicetrees, fail in case of * an error */ pr_err("%pOF: error in timing %d\n", np, disp->num_timings + 1); kfree(dt); goto timingfail; } if (native_mode == entry) disp->native_mode = disp->num_timings; disp->timings[disp->num_timings] = dt; disp->num_timings++; } of_node_put(timings_np); /* * native_mode points to the device_node returned by of_parse_phandle * therefore call of_node_put on it */ of_node_put(native_mode); pr_debug("%pOF: got %d timings. Using timing #%d as default\n", np, disp->num_timings, disp->native_mode + 1); return disp; timingfail: of_node_put(native_mode); display_timings_release(disp); disp = NULL; entryfail: kfree(disp); dispfail: of_node_put(timings_np); return NULL; } EXPORT_SYMBOL_GPL(of_get_display_timings);
linux-master
drivers/video/of_display_timing.c
/* * linux/drivers/video/vgastate.c -- VGA state save/restore * * Copyright 2002 James Simmons * * Copyright history from vga16fb.c: * Copyright 1999 Ben Pfaff and Petr Vandrovec * Based on VGA info at http://www.goodnet.com/~tinara/FreeVGA/home.htm * Based on VESA framebuffer (c) 1998 Gerd Knorr * * This file is subject to the terms and conditions of the GNU General * Public License. See the file COPYING in the main directory of this * archive for more details. * */ #include <linux/module.h> #include <linux/slab.h> #include <linux/fb.h> #include <linux/vmalloc.h> #include <video/vga.h> struct regstate { __u8 *vga_font0; __u8 *vga_font1; __u8 *vga_text; __u8 *vga_cmap; __u8 *attr; __u8 *crtc; __u8 *gfx; __u8 *seq; __u8 misc; }; static inline unsigned char vga_rcrtcs(void __iomem *regbase, unsigned short iobase, unsigned char reg) { vga_w(regbase, iobase + 0x4, reg); return vga_r(regbase, iobase + 0x5); } static inline void vga_wcrtcs(void __iomem *regbase, unsigned short iobase, unsigned char reg, unsigned char val) { vga_w(regbase, iobase + 0x4, reg); vga_w(regbase, iobase + 0x5, val); } static void save_vga_text(struct vgastate *state, void __iomem *fbbase) { struct regstate *saved = (struct regstate *) state->vidstate; int i; u8 misc, attr10, gr4, gr5, gr6, seq1, seq2, seq4; unsigned short iobase; /* if in graphics mode, no need to save */ misc = vga_r(state->vgabase, VGA_MIS_R); iobase = (misc & 1) ? 0x3d0 : 0x3b0; vga_r(state->vgabase, iobase + 0xa); vga_w(state->vgabase, VGA_ATT_W, 0x00); attr10 = vga_rattr(state->vgabase, 0x10); vga_r(state->vgabase, iobase + 0xa); vga_w(state->vgabase, VGA_ATT_W, 0x20); if (attr10 & 1) return; /* save regs */ gr4 = vga_rgfx(state->vgabase, VGA_GFX_PLANE_READ); gr5 = vga_rgfx(state->vgabase, VGA_GFX_MODE); gr6 = vga_rgfx(state->vgabase, VGA_GFX_MISC); seq2 = vga_rseq(state->vgabase, VGA_SEQ_PLANE_WRITE); seq4 = vga_rseq(state->vgabase, VGA_SEQ_MEMORY_MODE); /* blank screen */ seq1 = vga_rseq(state->vgabase, VGA_SEQ_CLOCK_MODE); vga_wseq(state->vgabase, VGA_SEQ_RESET, 0x1); vga_wseq(state->vgabase, VGA_SEQ_CLOCK_MODE, seq1 | 1 << 5); vga_wseq(state->vgabase, VGA_SEQ_RESET, 0x3); /* save font at plane 2 */ if (state->flags & VGA_SAVE_FONT0) { vga_wseq(state->vgabase, VGA_SEQ_PLANE_WRITE, 0x4); vga_wseq(state->vgabase, VGA_SEQ_MEMORY_MODE, 0x6); vga_wgfx(state->vgabase, VGA_GFX_PLANE_READ, 0x2); vga_wgfx(state->vgabase, VGA_GFX_MODE, 0x0); vga_wgfx(state->vgabase, VGA_GFX_MISC, 0x5); for (i = 0; i < 4 * 8192; i++) saved->vga_font0[i] = vga_r(fbbase, i); } /* save font at plane 3 */ if (state->flags & VGA_SAVE_FONT1) { vga_wseq(state->vgabase, VGA_SEQ_PLANE_WRITE, 0x8); vga_wseq(state->vgabase, VGA_SEQ_MEMORY_MODE, 0x6); vga_wgfx(state->vgabase, VGA_GFX_PLANE_READ, 0x3); vga_wgfx(state->vgabase, VGA_GFX_MODE, 0x0); vga_wgfx(state->vgabase, VGA_GFX_MISC, 0x5); for (i = 0; i < state->memsize; i++) saved->vga_font1[i] = vga_r(fbbase, i); } /* save font at plane 0/1 */ if (state->flags & VGA_SAVE_TEXT) { vga_wseq(state->vgabase, VGA_SEQ_PLANE_WRITE, 0x1); vga_wseq(state->vgabase, VGA_SEQ_MEMORY_MODE, 0x6); vga_wgfx(state->vgabase, VGA_GFX_PLANE_READ, 0x0); vga_wgfx(state->vgabase, VGA_GFX_MODE, 0x0); vga_wgfx(state->vgabase, VGA_GFX_MISC, 0x5); for (i = 0; i < 8192; i++) saved->vga_text[i] = vga_r(fbbase, i); vga_wseq(state->vgabase, VGA_SEQ_PLANE_WRITE, 0x2); vga_wseq(state->vgabase, VGA_SEQ_MEMORY_MODE, 0x6); vga_wgfx(state->vgabase, VGA_GFX_PLANE_READ, 0x1); vga_wgfx(state->vgabase, VGA_GFX_MODE, 0x0); vga_wgfx(state->vgabase, VGA_GFX_MISC, 0x5); for (i = 0; i < 8192; i++) saved->vga_text[8192+i] = vga_r(fbbase + 2 * 8192, i); } /* restore regs */ vga_wseq(state->vgabase, VGA_SEQ_PLANE_WRITE, seq2); vga_wseq(state->vgabase, VGA_SEQ_MEMORY_MODE, seq4); vga_wgfx(state->vgabase, VGA_GFX_PLANE_READ, gr4); vga_wgfx(state->vgabase, VGA_GFX_MODE, gr5); vga_wgfx(state->vgabase, VGA_GFX_MISC, gr6); /* unblank screen */ vga_wseq(state->vgabase, VGA_SEQ_RESET, 0x1); vga_wseq(state->vgabase, VGA_SEQ_CLOCK_MODE, seq1 & ~(1 << 5)); vga_wseq(state->vgabase, VGA_SEQ_RESET, 0x3); vga_wseq(state->vgabase, VGA_SEQ_CLOCK_MODE, seq1); } static void restore_vga_text(struct vgastate *state, void __iomem *fbbase) { struct regstate *saved = (struct regstate *) state->vidstate; int i; u8 gr1, gr3, gr4, gr5, gr6, gr8; u8 seq1, seq2, seq4; /* save regs */ gr1 = vga_rgfx(state->vgabase, VGA_GFX_SR_ENABLE); gr3 = vga_rgfx(state->vgabase, VGA_GFX_DATA_ROTATE); gr4 = vga_rgfx(state->vgabase, VGA_GFX_PLANE_READ); gr5 = vga_rgfx(state->vgabase, VGA_GFX_MODE); gr6 = vga_rgfx(state->vgabase, VGA_GFX_MISC); gr8 = vga_rgfx(state->vgabase, VGA_GFX_BIT_MASK); seq2 = vga_rseq(state->vgabase, VGA_SEQ_PLANE_WRITE); seq4 = vga_rseq(state->vgabase, VGA_SEQ_MEMORY_MODE); /* blank screen */ seq1 = vga_rseq(state->vgabase, VGA_SEQ_CLOCK_MODE); vga_wseq(state->vgabase, VGA_SEQ_RESET, 0x1); vga_wseq(state->vgabase, VGA_SEQ_CLOCK_MODE, seq1 | 1 << 5); vga_wseq(state->vgabase, VGA_SEQ_RESET, 0x3); if (state->depth == 4) { vga_wgfx(state->vgabase, VGA_GFX_DATA_ROTATE, 0x0); vga_wgfx(state->vgabase, VGA_GFX_BIT_MASK, 0xff); vga_wgfx(state->vgabase, VGA_GFX_SR_ENABLE, 0x00); } /* restore font at plane 2 */ if (state->flags & VGA_SAVE_FONT0) { vga_wseq(state->vgabase, VGA_SEQ_PLANE_WRITE, 0x4); vga_wseq(state->vgabase, VGA_SEQ_MEMORY_MODE, 0x6); vga_wgfx(state->vgabase, VGA_GFX_PLANE_READ, 0x2); vga_wgfx(state->vgabase, VGA_GFX_MODE, 0x0); vga_wgfx(state->vgabase, VGA_GFX_MISC, 0x5); for (i = 0; i < 4 * 8192; i++) vga_w(fbbase, i, saved->vga_font0[i]); } /* restore font at plane 3 */ if (state->flags & VGA_SAVE_FONT1) { vga_wseq(state->vgabase, VGA_SEQ_PLANE_WRITE, 0x8); vga_wseq(state->vgabase, VGA_SEQ_MEMORY_MODE, 0x6); vga_wgfx(state->vgabase, VGA_GFX_PLANE_READ, 0x3); vga_wgfx(state->vgabase, VGA_GFX_MODE, 0x0); vga_wgfx(state->vgabase, VGA_GFX_MISC, 0x5); for (i = 0; i < state->memsize; i++) vga_w(fbbase, i, saved->vga_font1[i]); } /* restore font at plane 0/1 */ if (state->flags & VGA_SAVE_TEXT) { vga_wseq(state->vgabase, VGA_SEQ_PLANE_WRITE, 0x1); vga_wseq(state->vgabase, VGA_SEQ_MEMORY_MODE, 0x6); vga_wgfx(state->vgabase, VGA_GFX_PLANE_READ, 0x0); vga_wgfx(state->vgabase, VGA_GFX_MODE, 0x0); vga_wgfx(state->vgabase, VGA_GFX_MISC, 0x5); for (i = 0; i < 8192; i++) vga_w(fbbase, i, saved->vga_text[i]); vga_wseq(state->vgabase, VGA_SEQ_PLANE_WRITE, 0x2); vga_wseq(state->vgabase, VGA_SEQ_MEMORY_MODE, 0x6); vga_wgfx(state->vgabase, VGA_GFX_PLANE_READ, 0x1); vga_wgfx(state->vgabase, VGA_GFX_MODE, 0x0); vga_wgfx(state->vgabase, VGA_GFX_MISC, 0x5); for (i = 0; i < 8192; i++) vga_w(fbbase, i, saved->vga_text[8192+i]); } /* unblank screen */ vga_wseq(state->vgabase, VGA_SEQ_RESET, 0x1); vga_wseq(state->vgabase, VGA_SEQ_CLOCK_MODE, seq1 & ~(1 << 5)); vga_wseq(state->vgabase, VGA_SEQ_RESET, 0x3); /* restore regs */ vga_wgfx(state->vgabase, VGA_GFX_SR_ENABLE, gr1); vga_wgfx(state->vgabase, VGA_GFX_DATA_ROTATE, gr3); vga_wgfx(state->vgabase, VGA_GFX_PLANE_READ, gr4); vga_wgfx(state->vgabase, VGA_GFX_MODE, gr5); vga_wgfx(state->vgabase, VGA_GFX_MISC, gr6); vga_wgfx(state->vgabase, VGA_GFX_BIT_MASK, gr8); vga_wseq(state->vgabase, VGA_SEQ_CLOCK_MODE, seq1); vga_wseq(state->vgabase, VGA_SEQ_PLANE_WRITE, seq2); vga_wseq(state->vgabase, VGA_SEQ_MEMORY_MODE, seq4); } static void save_vga_mode(struct vgastate *state) { struct regstate *saved = (struct regstate *) state->vidstate; unsigned short iobase; int i; saved->misc = vga_r(state->vgabase, VGA_MIS_R); if (saved->misc & 1) iobase = 0x3d0; else iobase = 0x3b0; for (i = 0; i < state->num_crtc; i++) saved->crtc[i] = vga_rcrtcs(state->vgabase, iobase, i); vga_r(state->vgabase, iobase + 0xa); vga_w(state->vgabase, VGA_ATT_W, 0x00); for (i = 0; i < state->num_attr; i++) { vga_r(state->vgabase, iobase + 0xa); saved->attr[i] = vga_rattr(state->vgabase, i); } vga_r(state->vgabase, iobase + 0xa); vga_w(state->vgabase, VGA_ATT_W, 0x20); for (i = 0; i < state->num_gfx; i++) saved->gfx[i] = vga_rgfx(state->vgabase, i); for (i = 0; i < state->num_seq; i++) saved->seq[i] = vga_rseq(state->vgabase, i); } static void restore_vga_mode(struct vgastate *state) { struct regstate *saved = (struct regstate *) state->vidstate; unsigned short iobase; int i; vga_w(state->vgabase, VGA_MIS_W, saved->misc); if (saved->misc & 1) iobase = 0x3d0; else iobase = 0x3b0; /* turn off display */ vga_wseq(state->vgabase, VGA_SEQ_CLOCK_MODE, saved->seq[VGA_SEQ_CLOCK_MODE] | 0x20); /* disable sequencer */ vga_wseq(state->vgabase, VGA_SEQ_RESET, 0x01); /* enable palette addressing */ vga_r(state->vgabase, iobase + 0xa); vga_w(state->vgabase, VGA_ATT_W, 0x00); for (i = 2; i < state->num_seq; i++) vga_wseq(state->vgabase, i, saved->seq[i]); /* unprotect vga regs */ vga_wcrtcs(state->vgabase, iobase, 17, saved->crtc[17] & ~0x80); for (i = 0; i < state->num_crtc; i++) vga_wcrtcs(state->vgabase, iobase, i, saved->crtc[i]); for (i = 0; i < state->num_gfx; i++) vga_wgfx(state->vgabase, i, saved->gfx[i]); for (i = 0; i < state->num_attr; i++) { vga_r(state->vgabase, iobase + 0xa); vga_wattr(state->vgabase, i, saved->attr[i]); } /* reenable sequencer */ vga_wseq(state->vgabase, VGA_SEQ_RESET, 0x03); /* turn display on */ vga_wseq(state->vgabase, VGA_SEQ_CLOCK_MODE, saved->seq[VGA_SEQ_CLOCK_MODE] & ~(1 << 5)); /* disable video/palette source */ vga_r(state->vgabase, iobase + 0xa); vga_w(state->vgabase, VGA_ATT_W, 0x20); } static void save_vga_cmap(struct vgastate *state) { struct regstate *saved = (struct regstate *) state->vidstate; int i; vga_w(state->vgabase, VGA_PEL_MSK, 0xff); /* assumes DAC is readable and writable */ vga_w(state->vgabase, VGA_PEL_IR, 0x00); for (i = 0; i < 768; i++) saved->vga_cmap[i] = vga_r(state->vgabase, VGA_PEL_D); } static void restore_vga_cmap(struct vgastate *state) { struct regstate *saved = (struct regstate *) state->vidstate; int i; vga_w(state->vgabase, VGA_PEL_MSK, 0xff); /* assumes DAC is readable and writable */ vga_w(state->vgabase, VGA_PEL_IW, 0x00); for (i = 0; i < 768; i++) vga_w(state->vgabase, VGA_PEL_D, saved->vga_cmap[i]); } static void vga_cleanup(struct vgastate *state) { if (state->vidstate != NULL) { struct regstate *saved = (struct regstate *) state->vidstate; vfree(saved->vga_font0); vfree(saved->vga_font1); vfree(saved->vga_text); vfree(saved->vga_cmap); vfree(saved->attr); kfree(saved); state->vidstate = NULL; } } int save_vga(struct vgastate *state) { struct regstate *saved; saved = kzalloc(sizeof(struct regstate), GFP_KERNEL); if (saved == NULL) return 1; state->vidstate = (void *)saved; if (state->flags & VGA_SAVE_CMAP) { saved->vga_cmap = vmalloc(768); if (!saved->vga_cmap) { vga_cleanup(state); return 1; } save_vga_cmap(state); } if (state->flags & VGA_SAVE_MODE) { int total; if (state->num_attr < 21) state->num_attr = 21; if (state->num_crtc < 25) state->num_crtc = 25; if (state->num_gfx < 9) state->num_gfx = 9; if (state->num_seq < 5) state->num_seq = 5; total = state->num_attr + state->num_crtc + state->num_gfx + state->num_seq; saved->attr = vmalloc(total); if (!saved->attr) { vga_cleanup(state); return 1; } saved->crtc = saved->attr + state->num_attr; saved->gfx = saved->crtc + state->num_crtc; saved->seq = saved->gfx + state->num_gfx; save_vga_mode(state); } if (state->flags & VGA_SAVE_FONTS) { void __iomem *fbbase; /* exit if window is less than 32K */ if (state->memsize && state->memsize < 4 * 8192) { vga_cleanup(state); return 1; } if (!state->memsize) state->memsize = 8 * 8192; if (!state->membase) state->membase = 0xA0000; fbbase = ioremap(state->membase, state->memsize); if (!fbbase) { vga_cleanup(state); return 1; } /* * save only first 32K used by vgacon */ if (state->flags & VGA_SAVE_FONT0) { saved->vga_font0 = vmalloc(4 * 8192); if (!saved->vga_font0) { iounmap(fbbase); vga_cleanup(state); return 1; } } /* * largely unused, but if required by the caller * we'll just save everything. */ if (state->flags & VGA_SAVE_FONT1) { saved->vga_font1 = vmalloc(state->memsize); if (!saved->vga_font1) { iounmap(fbbase); vga_cleanup(state); return 1; } } /* * Save 8K at plane0[0], and 8K at plane1[16K] */ if (state->flags & VGA_SAVE_TEXT) { saved->vga_text = vmalloc(8192 * 2); if (!saved->vga_text) { iounmap(fbbase); vga_cleanup(state); return 1; } } save_vga_text(state, fbbase); iounmap(fbbase); } return 0; } int restore_vga(struct vgastate *state) { if (state->vidstate == NULL) return 1; if (state->flags & VGA_SAVE_MODE) restore_vga_mode(state); if (state->flags & VGA_SAVE_FONTS) { void __iomem *fbbase = ioremap(state->membase, state->memsize); if (!fbbase) { vga_cleanup(state); return 1; } restore_vga_text(state, fbbase); iounmap(fbbase); } if (state->flags & VGA_SAVE_CMAP) restore_vga_cmap(state); vga_cleanup(state); return 0; } EXPORT_SYMBOL(save_vga); EXPORT_SYMBOL(restore_vga); MODULE_AUTHOR("James Simmons <[email protected]>"); MODULE_DESCRIPTION("VGA State Save/Restore"); MODULE_LICENSE("GPL");
linux-master
drivers/video/vgastate.c
// SPDX-License-Identifier: GPL-2.0-only /* * linux/drivers/video/console/sticore.c - * core code for console driver using HP's STI firmware * * Copyright (C) 2000 Philipp Rumpf <[email protected]> * Copyright (C) 2001-2023 Helge Deller <[email protected]> * Copyright (C) 2001-2002 Thomas Bogendoerfer <[email protected]> * * TODO: * - call STI in virtual mode rather than in real mode * - screen blanking with state_mgmt() in text mode STI ? * - try to make it work on m68k hp workstations ;) * */ #define pr_fmt(fmt) "%s: " fmt, KBUILD_MODNAME #include <linux/module.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/pci.h> #include <linux/font.h> #include <asm/hardware.h> #include <asm/page.h> #include <asm/parisc-device.h> #include <asm/pdc.h> #include <asm/cacheflush.h> #include <asm/grfioctl.h> #include <video/sticore.h> #define STI_DRIVERVERSION "Version 0.9c" static struct sti_struct *default_sti __read_mostly; /* number of STI ROMS found and their ptrs to each struct */ static int num_sti_roms __read_mostly; static struct sti_struct *sti_roms[MAX_STI_ROMS] __read_mostly; static void *store_sti_val(struct sti_struct *sti, void *ptr, unsigned long val) { u32 *ptr32 = ptr; if (IS_ENABLED(CONFIG_64BIT) && sti->do_call64) { /* used for 64-bit STI ROM */ unsigned long *ptr64 = ptr; ptr64 = PTR_ALIGN(ptr64, sizeof(void *)); *ptr64++ = val; return ptr64; } /* used for 32-bit STI ROM */ *ptr32++ = val; return ptr32; } #define store_sti_ptr(sti, dest, ptr) \ store_sti_val(sti, dest, STI_PTR(ptr)) /* The colour indices used by STI are * 0 - Black * 1 - White * 2 - Red * 3 - Yellow/Brown * 4 - Green * 5 - Cyan * 6 - Blue * 7 - Magenta * * So we have the same colours as VGA (basically one bit each for R, G, B), * but have to translate them, anyway. */ static const u8 col_trans[8] = { 0, 6, 4, 5, 2, 7, 3, 1 }; #define c_fg(sti, c) col_trans[((c>> 8) & 7)] #define c_bg(sti, c) col_trans[((c>>11) & 7)] #define c_index(sti, c) ((c) & 0xff) static const struct sti_init_flags default_init_flags = { .wait = STI_WAIT, .reset = 1, .text = 1, .nontext = 1, .no_chg_bet = 1, .no_chg_bei = 1, .init_cmap_tx = 1, }; static int sti_init_graph(struct sti_struct *sti) { struct sti_init_inptr *inptr = &sti->sti_data->init_inptr; struct sti_init_inptr_ext *inptr_ext = &sti->sti_data->init_inptr_ext; struct sti_init_outptr *outptr = &sti->sti_data->init_outptr; unsigned long flags; int ret, err; spin_lock_irqsave(&sti->lock, flags); memset(inptr, 0, sizeof(*inptr)); inptr->text_planes = 3; /* # of text planes (max 3 for STI) */ memset(inptr_ext, 0, sizeof(*inptr_ext)); store_sti_ptr(sti, &inptr->ext_ptr, inptr_ext); outptr->errno = 0; ret = sti_call(sti, sti->init_graph, &default_init_flags, inptr, outptr, sti->glob_cfg); if (ret >= 0) sti->text_planes = outptr->text_planes; err = outptr->errno; spin_unlock_irqrestore(&sti->lock, flags); if (ret < 0) { pr_err("STI init_graph failed (ret %d, errno %d)\n", ret, err); return -1; } return 0; } static const struct sti_conf_flags default_conf_flags = { .wait = STI_WAIT, }; static void sti_inq_conf(struct sti_struct *sti) { struct sti_conf_inptr *inptr = &sti->sti_data->inq_inptr; struct sti_conf_outptr *outptr = &sti->sti_data->inq_outptr; unsigned long flags; s32 ret; store_sti_ptr(sti, &outptr->ext_ptr, &sti->sti_data->inq_outptr_ext); do { spin_lock_irqsave(&sti->lock, flags); memset(inptr, 0, sizeof(*inptr)); ret = sti_call(sti, sti->inq_conf, &default_conf_flags, inptr, outptr, sti->glob_cfg); spin_unlock_irqrestore(&sti->lock, flags); } while (ret == 1); } static const struct sti_font_flags default_font_flags = { .wait = STI_WAIT, .non_text = 0, }; void sti_putc(struct sti_struct *sti, int c, int y, int x, struct sti_cooked_font *font) { struct sti_font_inptr *inptr; struct sti_font_inptr inptr_default = { .font_start_addr = (void *)STI_PTR(font->raw), .index = c_index(sti, c), .fg_color = c_fg(sti, c), .bg_color = c_bg(sti, c), .dest_x = x * font->width, .dest_y = y * font->height, }; struct sti_font_outptr *outptr = &sti->sti_data->font_outptr; s32 ret; unsigned long flags; do { spin_lock_irqsave(&sti->lock, flags); inptr = &inptr_default; if (IS_ENABLED(CONFIG_64BIT) && !sti->do_call64) { /* copy below 4G if calling 32-bit on LP64 kernel */ inptr = &sti->sti_data->font_inptr; *inptr = inptr_default; /* skip first 4 bytes for 32-bit STI call */ inptr = (void *)(((unsigned long)inptr) + sizeof(u32)); } ret = sti_call(sti, sti->font_unpmv, &default_font_flags, inptr, outptr, sti->glob_cfg); spin_unlock_irqrestore(&sti->lock, flags); } while (ret == 1); } static const struct sti_blkmv_flags clear_blkmv_flags = { .wait = STI_WAIT, .color = 1, .clear = 1, }; void sti_set(struct sti_struct *sti, int src_y, int src_x, int height, int width, u8 color) { struct sti_blkmv_inptr *inptr; struct sti_blkmv_inptr inptr_default = { .fg_color = color, .bg_color = color, .src_x = src_x, .src_y = src_y, .dest_x = src_x, .dest_y = src_y, .width = width, .height = height, }; struct sti_blkmv_outptr *outptr = &sti->sti_data->blkmv_outptr; s32 ret; unsigned long flags; do { spin_lock_irqsave(&sti->lock, flags); inptr = &inptr_default; if (IS_ENABLED(CONFIG_64BIT) && !sti->do_call64) { /* copy below 4G if calling 32-bit on LP64 kernel */ inptr = &sti->sti_data->blkmv_inptr; *inptr = inptr_default; } ret = sti_call(sti, sti->block_move, &clear_blkmv_flags, inptr, outptr, sti->glob_cfg); spin_unlock_irqrestore(&sti->lock, flags); } while (ret == 1); } void sti_clear(struct sti_struct *sti, int src_y, int src_x, int height, int width, int c, struct sti_cooked_font *font) { struct sti_blkmv_inptr *inptr; struct sti_blkmv_inptr inptr_default = { .fg_color = c_fg(sti, c), .bg_color = c_bg(sti, c), .src_x = src_x * font->width, .src_y = src_y * font->height, .dest_x = src_x * font->width, .dest_y = src_y * font->height, .width = width * font->width, .height = height * font->height, }; struct sti_blkmv_outptr *outptr = &sti->sti_data->blkmv_outptr; s32 ret; unsigned long flags; do { spin_lock_irqsave(&sti->lock, flags); inptr = &inptr_default; if (IS_ENABLED(CONFIG_64BIT) && !sti->do_call64) { /* copy below 4G if calling 32-bit on LP64 kernel */ inptr = &sti->sti_data->blkmv_inptr; *inptr = inptr_default; } ret = sti_call(sti, sti->block_move, &clear_blkmv_flags, inptr, outptr, sti->glob_cfg); spin_unlock_irqrestore(&sti->lock, flags); } while (ret == 1); } static const struct sti_blkmv_flags default_blkmv_flags = { .wait = STI_WAIT, }; void sti_bmove(struct sti_struct *sti, int src_y, int src_x, int dst_y, int dst_x, int height, int width, struct sti_cooked_font *font) { struct sti_blkmv_inptr *inptr; struct sti_blkmv_inptr inptr_default = { .src_x = src_x * font->width, .src_y = src_y * font->height, .dest_x = dst_x * font->width, .dest_y = dst_y * font->height, .width = width * font->width, .height = height * font->height, }; struct sti_blkmv_outptr *outptr = &sti->sti_data->blkmv_outptr; s32 ret; unsigned long flags; do { spin_lock_irqsave(&sti->lock, flags); inptr = &inptr_default; if (IS_ENABLED(CONFIG_64BIT) && !sti->do_call64) { /* copy below 4G if calling 32-bit on LP64 kernel */ inptr = &sti->sti_data->blkmv_inptr; *inptr = inptr_default; } ret = sti_call(sti, sti->block_move, &default_blkmv_flags, inptr, outptr, sti->glob_cfg); spin_unlock_irqrestore(&sti->lock, flags); } while (ret == 1); } static void sti_flush(unsigned long start, unsigned long end) { flush_icache_range(start, end); } static void sti_rom_copy(unsigned long base, unsigned long count, void *dest) { unsigned long dest_start = (unsigned long) dest; /* this still needs to be revisited (see arch/parisc/mm/init.c:246) ! */ while (count >= 4) { count -= 4; *(u32 *)dest = gsc_readl(base); base += 4; dest += 4; } while (count) { count--; *(u8 *)dest = gsc_readb(base); base++; dest++; } sti_flush(dest_start, (unsigned long)dest); } static char default_sti_path[21] __read_mostly; #ifndef MODULE static int __init sti_setup(char *str) { if (str) strscpy(default_sti_path, str, sizeof(default_sti_path)); return 1; } /* Assuming the machine has multiple STI consoles (=graphic cards) which * all get detected by sticon, the user may define with the linux kernel * parameter sti=<x> which of them will be the initial boot-console. * <x> is a number between 0 and MAX_STI_ROMS, with 0 as the default * STI screen. */ __setup("sti=", sti_setup); #endif static char *font_name; static int font_index, font_height, font_width; #ifndef MODULE static int sti_font_setup(char *str) { /* * The default font can be selected in various ways. * a) sti_font=VGA8x16, sti_font=10x20, sti_font=10*20 selects * an built-in Linux framebuffer font. * b) sti_font=<index>, where index is (1..x) with 1 selecting * the first HP STI ROM built-in font.. */ if (*str >= '0' && *str <= '9') { char *x; if ((x = strchr(str, 'x')) || (x = strchr(str, '*'))) { font_height = simple_strtoul(str, NULL, 0); font_width = simple_strtoul(x+1, NULL, 0); } else { font_index = simple_strtoul(str, NULL, 0); } } else { font_name = str; /* fb font name */ } return 1; } /* The optional linux kernel parameter "sti_font" defines which font * should be used by the sticon driver to draw characters to the screen. * Possible values are: * - sti_font=<fb_fontname>: * <fb_fontname> is the name of one of the linux-kernel built-in * framebuffer font names (e.g. VGA8x16, SUN22x18). * This is only available if the fonts have been statically compiled * in with e.g. the CONFIG_FONT_8x16 or CONFIG_FONT_SUN12x22 options. * - sti_font=<number> (<number> = 1,2,3,...) * most STI ROMs have built-in HP specific fonts, which can be selected * by giving the desired number to the sticon driver. * NOTE: This number is machine and STI ROM dependend. * - sti_font=<height>x<width> (e.g. sti_font=16x8) * <height> and <width> gives hints to the height and width of the * font which the user wants. The sticon driver will try to use * a font with this height and width, but if no suitable font is * found, sticon will use the default 8x8 font. */ __setup("sti_font=", sti_font_setup); #endif static void sti_dump_globcfg(struct sti_struct *sti) { struct sti_glob_cfg *glob_cfg = sti->glob_cfg; struct sti_glob_cfg_ext *cfg = &sti->sti_data->glob_cfg_ext; pr_debug("%d text planes\n" "%4d x %4d screen resolution\n" "%4d x %4d offscreen\n" "%4d x %4d layout\n", glob_cfg->text_planes, glob_cfg->onscreen_x, glob_cfg->onscreen_y, glob_cfg->offscreen_x, glob_cfg->offscreen_y, glob_cfg->total_x, glob_cfg->total_y); /* dump extended cfg */ pr_debug("monitor %d\n" "in friendly mode: %d\n" "power consumption %d watts\n" "freq ref %d\n" "sti_mem_addr %px (size=%d bytes)\n", cfg->curr_mon, cfg->friendly_boot, cfg->power, cfg->freq_ref, cfg->sti_mem_addr, sti->sti_mem_request); } static void sti_dump_outptr(struct sti_struct *sti) { pr_debug("%d bits per pixel\n" "%d used bits\n" "%d planes\n" "attributes %08x\n", sti->sti_data->inq_outptr.bits_per_pixel, sti->sti_data->inq_outptr.bits_used, sti->sti_data->inq_outptr.planes, sti->sti_data->inq_outptr.attributes); } static int sti_init_glob_cfg(struct sti_struct *sti, unsigned long rom_address, unsigned long hpa) { struct sti_glob_cfg *glob_cfg; struct sti_glob_cfg_ext *glob_cfg_ext; void *save_addr, *ptr; void *sti_mem_addr; int i, size; if (sti->sti_mem_request < 256) sti->sti_mem_request = 256; /* STI default */ size = sizeof(struct sti_all_data) + sti->sti_mem_request - 256; sti->sti_data = kzalloc(size, STI_LOWMEM); if (!sti->sti_data) return -ENOMEM; glob_cfg = &sti->sti_data->glob_cfg; glob_cfg_ext = &sti->sti_data->glob_cfg_ext; save_addr = &sti->sti_data->save_addr; sti_mem_addr = &sti->sti_data->sti_mem_addr; for (i = 0; i < STI_REGION_MAX; i++) { unsigned long newhpa, len; if (sti->pd) { unsigned char offs = sti->rm_entry[i]; if (offs == 0) continue; if (offs != PCI_ROM_ADDRESS && (offs < PCI_BASE_ADDRESS_0 || offs > PCI_BASE_ADDRESS_5)) { pr_warn("STI pci region mapping for region %d (%02x) can't be mapped\n", i,sti->rm_entry[i]); continue; } newhpa = pci_resource_start (sti->pd, (offs - PCI_BASE_ADDRESS_0) / 4); } else newhpa = (i == 0) ? rom_address : hpa; sti->regions_phys[i] = REGION_OFFSET_TO_PHYS(sti->regions[i], newhpa); len = sti->regions[i].region_desc.length * 4096; pr_debug("region #%d: phys %08lx, len=%lukB, " "btlb=%d, sysonly=%d, cache=%d, last=%d\n", i, sti->regions_phys[i], len / 1024, sti->regions[i].region_desc.btlb, sti->regions[i].region_desc.sys_only, sti->regions[i].region_desc.cache, sti->regions[i].region_desc.last); /* last entry reached ? */ if (sti->regions[i].region_desc.last) break; } ptr = &glob_cfg->region_ptrs; for (i = 0; i < STI_REGION_MAX; i++) ptr = store_sti_val(sti, ptr, sti->regions_phys[i]); *(s32 *)ptr = 0; /* set reent_lvl */ ptr += sizeof(s32); ptr = store_sti_ptr(sti, ptr, save_addr); ptr = store_sti_ptr(sti, ptr, glob_cfg_ext); store_sti_ptr(sti, &glob_cfg_ext->sti_mem_addr, sti_mem_addr); sti->glob_cfg = glob_cfg; return 0; } #ifdef CONFIG_FONT_SUPPORT static struct sti_cooked_font * sti_select_fbfont(struct sti_cooked_rom *cooked_rom, const char *fbfont_name) { const struct font_desc *fbfont = NULL; unsigned int size, bpc; void *dest; struct sti_rom_font *nf; struct sti_cooked_font *cooked_font; if (fbfont_name && strlen(fbfont_name)) fbfont = find_font(fbfont_name); if (!fbfont) fbfont = get_default_font(1024,768, ~(u32)0, ~(u32)0); if (!fbfont) return NULL; pr_info(" using %ux%u framebuffer font %s\n", fbfont->width, fbfont->height, fbfont->name); bpc = ((fbfont->width+7)/8) * fbfont->height; size = bpc * fbfont->charcount; size += sizeof(struct sti_rom_font); nf = kzalloc(size, STI_LOWMEM); if (!nf) return NULL; nf->first_char = 0; nf->last_char = fbfont->charcount - 1; nf->width = fbfont->width; nf->height = fbfont->height; nf->font_type = STI_FONT_HPROMAN8; nf->bytes_per_char = bpc; nf->next_font = 0; nf->underline_height = 1; nf->underline_pos = fbfont->height - nf->underline_height; dest = nf; dest += sizeof(struct sti_rom_font); memcpy(dest, fbfont->data, bpc * fbfont->charcount); cooked_font = kzalloc(sizeof(*cooked_font), GFP_KERNEL); if (!cooked_font) { kfree(nf); return NULL; } cooked_font->raw = nf; cooked_font->raw_ptr = nf; cooked_font->next_font = NULL; cooked_rom->font_start = cooked_font; return cooked_font; } #else static struct sti_cooked_font * sti_select_fbfont(struct sti_cooked_rom *cooked_rom, const char *fbfont_name) { return NULL; } #endif static void sti_dump_font(struct sti_cooked_font *font) { #ifdef STI_DUMP_FONT unsigned char *p = (unsigned char *)font->raw; int n; p += sizeof(struct sti_rom_font); pr_debug(" w %d h %d bpc %d\n", font->width, font->height, font->raw->bytes_per_char); for (n = 0; n < 256 * font->raw->bytes_per_char; n += 16, p += 16) { pr_debug(" 0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x," " 0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x," " 0x%02x, 0x%02x, 0x%02x, 0x%02x,\n", p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]); } #endif } static int sti_search_font(struct sti_cooked_rom *rom, int height, int width) { struct sti_cooked_font *font; int i = 0; for (font = rom->font_start; font; font = font->next_font, i++) { if ((font->raw->width == width) && (font->raw->height == height)) return i; } return 0; } static struct sti_cooked_font *sti_select_font(struct sti_cooked_rom *rom) { struct sti_cooked_font *font; int i; /* check for framebuffer-font first */ if (!font_index) { font = sti_select_fbfont(rom, font_name); if (font) return font; } if (font_width && font_height) font_index = sti_search_font(rom, font_height, font_width); for (font = rom->font_start, i = font_index - 1; font && (i > 0); font = font->next_font, i--); if (font) return font; else return rom->font_start; } static void sti_dump_rom(struct sti_struct *sti) { struct sti_rom *rom = sti->rom->raw; struct sti_cooked_font *font_start; int nr; pr_info(" id %04x-%04x, conforms to spec rev. %d.%02x\n", rom->graphics_id[0], rom->graphics_id[1], rom->revno[0] >> 4, rom->revno[0] & 0x0f); pr_debug(" supports %d monitors\n", rom->num_mons); pr_debug(" font start %08x\n", rom->font_start); pr_debug(" region list %08x\n", rom->region_list); pr_debug(" init_graph %08x\n", rom->init_graph); pr_debug(" bus support %02x\n", rom->bus_support); pr_debug(" ext bus support %02x\n", rom->ext_bus_support); pr_debug(" alternate code type %d\n", rom->alt_code_type); font_start = sti->rom->font_start; nr = 0; while (font_start) { struct sti_rom_font *f = font_start->raw; pr_info(" built-in font #%d: size %dx%d, chars %d-%d, bpc %d\n", ++nr, f->width, f->height, f->first_char, f->last_char, f->bytes_per_char); font_start = font_start->next_font; } } static int sti_cook_fonts(struct sti_cooked_rom *cooked_rom, struct sti_rom *raw_rom) { struct sti_rom_font *raw_font, *font_start; struct sti_cooked_font *cooked_font; cooked_font = kzalloc(sizeof(*cooked_font), GFP_KERNEL); if (!cooked_font) return 0; cooked_rom->font_start = cooked_font; raw_font = ((void *)raw_rom) + (raw_rom->font_start); font_start = raw_font; cooked_font->raw = raw_font; while (raw_font->next_font) { raw_font = ((void *)font_start) + (raw_font->next_font); cooked_font->next_font = kzalloc(sizeof(*cooked_font), GFP_KERNEL); if (!cooked_font->next_font) return 1; cooked_font = cooked_font->next_font; cooked_font->raw = raw_font; } cooked_font->next_font = NULL; return 1; } #define BMODE_RELOCATE(offset) offset = (offset) / 4; #define BMODE_LAST_ADDR_OFFS 0x50 void sti_font_convert_bytemode(struct sti_struct *sti, struct sti_cooked_font *f) { unsigned char *n, *p, *q; int size = f->raw->bytes_per_char * (f->raw->last_char + 1) + sizeof(struct sti_rom_font); struct sti_rom_font *old_font; if (sti->wordmode) return; old_font = f->raw_ptr; n = kcalloc(4, size, STI_LOWMEM); f->raw_ptr = n; if (!n) return; p = n + 3; q = (unsigned char *) f->raw; while (size--) { *p = *q++; p += 4; } /* store new ptr to byte-mode font and delete old font */ f->raw = (struct sti_rom_font *) (n + 3); kfree(old_font); } EXPORT_SYMBOL(sti_font_convert_bytemode); static void sti_bmode_rom_copy(unsigned long base, unsigned long count, void *dest) { unsigned long dest_start = (unsigned long) dest; while (count) { count--; *(u8 *)dest = gsc_readl(base); base += 4; dest++; } sti_flush(dest_start, (unsigned long)dest); } static struct sti_rom *sti_get_bmode_rom (unsigned long address) { struct sti_rom *raw; u32 size; struct sti_rom_font *raw_font, *font_start; sti_bmode_rom_copy(address + BMODE_LAST_ADDR_OFFS, sizeof(size), &size); size = (size+3) / 4; raw = kmalloc(size, STI_LOWMEM); if (raw) { sti_bmode_rom_copy(address, size, raw); memmove (&raw->res004, &raw->type[0], 0x3c); raw->type[3] = raw->res004; BMODE_RELOCATE (raw->region_list); BMODE_RELOCATE (raw->font_start); BMODE_RELOCATE (raw->init_graph); BMODE_RELOCATE (raw->state_mgmt); BMODE_RELOCATE (raw->font_unpmv); BMODE_RELOCATE (raw->block_move); BMODE_RELOCATE (raw->inq_conf); raw_font = ((void *)raw) + raw->font_start; font_start = raw_font; while (raw_font->next_font) { BMODE_RELOCATE (raw_font->next_font); raw_font = ((void *)font_start) + raw_font->next_font; } } return raw; } static struct sti_rom *sti_get_wmode_rom(unsigned long address) { struct sti_rom *raw; unsigned long size; /* read the ROM size directly from the struct in ROM */ size = gsc_readl(address + offsetof(struct sti_rom,last_addr)); raw = kmalloc(size, STI_LOWMEM); if (raw) sti_rom_copy(address, size, raw); return raw; } static int sti_read_rom(int wordmode, struct sti_struct *sti, unsigned long address) { struct sti_cooked_rom *cooked; struct sti_rom *raw = NULL; unsigned long revno; cooked = kmalloc(sizeof *cooked, GFP_KERNEL); if (!cooked) goto out_err; if (wordmode) raw = sti_get_wmode_rom (address); else raw = sti_get_bmode_rom (address); if (!raw) goto out_err; if (!sti_cook_fonts(cooked, raw)) { pr_warn("No font found for STI at %08lx\n", address); goto out_err; } if (raw->region_list) memcpy(sti->regions, ((void *)raw)+raw->region_list, sizeof(sti->regions)); address = (unsigned long) STI_PTR(raw); pr_info("STI %s ROM supports 32 %sbit firmware functions.\n", wordmode ? "word mode" : "byte mode", raw->alt_code_type == ALT_CODE_TYPE_PA_RISC_64 ? "and 64 " : ""); if (IS_ENABLED(CONFIG_64BIT) && raw->alt_code_type == ALT_CODE_TYPE_PA_RISC_64) { sti->do_call64 = 1; sti->font_unpmv = address + (raw->font_unp_addr & 0x03ffffff); sti->block_move = address + (raw->block_move_addr & 0x03ffffff); sti->init_graph = address + (raw->init_graph_addr & 0x03ffffff); sti->inq_conf = address + (raw->inq_conf_addr & 0x03ffffff); } else { sti->font_unpmv = address + (raw->font_unpmv & 0x03ffffff); sti->block_move = address + (raw->block_move & 0x03ffffff); sti->init_graph = address + (raw->init_graph & 0x03ffffff); sti->inq_conf = address + (raw->inq_conf & 0x03ffffff); } sti->rom = cooked; sti->rom->raw = raw; sti_dump_rom(sti); sti->wordmode = wordmode; sti->font = sti_select_font(sti->rom); sti->font->width = sti->font->raw->width; sti->font->height = sti->font->raw->height; sti_font_convert_bytemode(sti, sti->font); sti_dump_font(sti->font); pr_info(" using %d-bit STI ROM functions\n", (IS_ENABLED(CONFIG_64BIT) && sti->do_call64) ? 64 : 32); sti->sti_mem_request = raw->sti_mem_req; pr_debug(" mem_request = %d, reentsize %d\n", sti->sti_mem_request, raw->reentsize); sti->graphics_id[0] = raw->graphics_id[0]; sti->graphics_id[1] = raw->graphics_id[1]; /* check if the ROM routines in this card are compatible */ if (wordmode || sti->graphics_id[1] != 0x09A02587) goto ok; revno = (raw->revno[0] << 8) | raw->revno[1]; switch (sti->graphics_id[0]) { case S9000_ID_HCRX: /* HyperA or HyperB ? */ if (revno == 0x8408 || revno == 0x840b) goto msg_not_supported; break; case CRT_ID_THUNDER: if (revno == 0x8509) goto msg_not_supported; break; case CRT_ID_THUNDER2: if (revno == 0x850c) goto msg_not_supported; } ok: return 1; msg_not_supported: pr_warn("Sorry, this GSC/STI card is not yet supported.\n"); pr_warn("Please see https://parisc.wiki.kernel.org/" "index.php/Graphics_howto for more info.\n"); /* fall through */ out_err: kfree(raw); kfree(cooked); return 0; } static struct sti_struct *sti_try_rom_generic(unsigned long address, unsigned long hpa, struct pci_dev *pd) { struct sti_struct *sti; int ok; u32 sig; if (num_sti_roms >= MAX_STI_ROMS) { pr_warn("maximum number of STI ROMS reached !\n"); return NULL; } sti = kzalloc(sizeof(*sti), GFP_KERNEL); if (!sti) return NULL; spin_lock_init(&sti->lock); test_rom: /* pdc_add_valid() works only on 32-bit kernels */ if ((!IS_ENABLED(CONFIG_64BIT) || (boot_cpu_data.pdc.capabilities & PDC_MODEL_OS32)) && pdc_add_valid(address)) { goto out_err; } sig = gsc_readl(address); /* check for a PCI ROM structure */ if ((le32_to_cpu(sig)==0xaa55)) { unsigned int i, rm_offset; u32 *rm; i = gsc_readl(address+0x04); if (i != 1) { /* The ROM could have multiple architecture * dependent images (e.g. i386, parisc,...) */ pr_warn("PCI ROM is not a STI ROM type image (0x%8x)\n", i); goto out_err; } sti->pd = pd; i = gsc_readl(address+0x0c); pr_debug("PCI ROM size (from header) = %d kB\n", le16_to_cpu(i>>16)*512/1024); rm_offset = le16_to_cpu(i & 0xffff); if (rm_offset) { /* read 16 bytes from the pci region mapper array */ rm = (u32*) &sti->rm_entry; *rm++ = gsc_readl(address+rm_offset+0x00); *rm++ = gsc_readl(address+rm_offset+0x04); *rm++ = gsc_readl(address+rm_offset+0x08); *rm++ = gsc_readl(address+rm_offset+0x0c); } address += le32_to_cpu(gsc_readl(address+8)); pr_debug("sig %04x, PCI STI ROM at %08lx\n", sig, address); goto test_rom; } ok = 0; if ((sig & 0xff) == 0x01) { pr_debug(" byte mode ROM at %08lx, hpa at %08lx\n", address, hpa); ok = sti_read_rom(0, sti, address); } if ((sig & 0xffff) == 0x0303) { pr_debug(" word mode ROM at %08lx, hpa at %08lx\n", address, hpa); ok = sti_read_rom(1, sti, address); } if (!ok) goto out_err; if (sti_init_glob_cfg(sti, address, hpa)) goto out_err; /* not enough memory */ /* disable STI PCI ROM. ROM and card RAM overlap and * leaving it enabled would force HPMCs */ if (sti->pd) { unsigned long rom_base; rom_base = pci_resource_start(sti->pd, PCI_ROM_RESOURCE); pci_write_config_dword(sti->pd, PCI_ROM_ADDRESS, rom_base & ~PCI_ROM_ADDRESS_ENABLE); pr_debug("STI PCI ROM disabled\n"); } if (sti_init_graph(sti)) goto out_err; sti_inq_conf(sti); sti_dump_globcfg(sti); sti_dump_outptr(sti); pr_info(" graphics card name: %s\n", sti->sti_data->inq_outptr.dev_name); sti_roms[num_sti_roms] = sti; num_sti_roms++; return sti; out_err: kfree(sti); return NULL; } static void sticore_check_for_default_sti(struct sti_struct *sti, char *path) { pr_info(" located at [%s]\n", sti->pa_path); if (strcmp (path, default_sti_path) == 0) default_sti = sti; } /* * on newer systems PDC gives the address of the ROM * in the additional address field addr[1] while on * older Systems the PDC stores it in page0->proc_sti */ static int __init sticore_pa_init(struct parisc_device *dev) { struct sti_struct *sti = NULL; int hpa = dev->hpa.start; if (dev->num_addrs && dev->addr[0]) sti = sti_try_rom_generic(dev->addr[0], hpa, NULL); if (!sti) sti = sti_try_rom_generic(hpa, hpa, NULL); if (!sti) sti = sti_try_rom_generic(PAGE0->proc_sti, hpa, NULL); if (!sti) return 1; print_pa_hwpath(dev, sti->pa_path); sticore_check_for_default_sti(sti, sti->pa_path); return 0; } static int sticore_pci_init(struct pci_dev *pd, const struct pci_device_id *ent) { #ifdef CONFIG_PCI unsigned long fb_base, rom_base; unsigned int fb_len, rom_len; int err; struct sti_struct *sti; err = pci_enable_device(pd); if (err < 0) { dev_err(&pd->dev, "Cannot enable PCI device\n"); return err; } fb_base = pci_resource_start(pd, 0); fb_len = pci_resource_len(pd, 0); rom_base = pci_resource_start(pd, PCI_ROM_RESOURCE); rom_len = pci_resource_len(pd, PCI_ROM_RESOURCE); if (rom_base) { pci_write_config_dword(pd, PCI_ROM_ADDRESS, rom_base | PCI_ROM_ADDRESS_ENABLE); pr_debug("STI PCI ROM enabled at 0x%08lx\n", rom_base); } pr_info("STI PCI graphic ROM found at %08lx (%u kB), fb at %08lx (%u MB)\n", rom_base, rom_len/1024, fb_base, fb_len/1024/1024); pr_debug("Trying PCI STI ROM at %08lx, PCI hpa at %08lx\n", rom_base, fb_base); sti = sti_try_rom_generic(rom_base, fb_base, pd); if (sti) { print_pci_hwpath(pd, sti->pa_path); sticore_check_for_default_sti(sti, sti->pa_path); } if (!sti) { pr_warn("Unable to handle STI device '%s'\n", pci_name(pd)); return -ENODEV; } #endif /* CONFIG_PCI */ return 0; } static void __exit sticore_pci_remove(struct pci_dev *pd) { BUG(); } static struct pci_device_id sti_pci_tbl[] = { { PCI_DEVICE(PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_VISUALIZE_EG) }, { PCI_DEVICE(PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_VISUALIZE_FX6) }, { PCI_DEVICE(PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_VISUALIZE_FX4) }, { PCI_DEVICE(PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_VISUALIZE_FX2) }, { PCI_DEVICE(PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_VISUALIZE_FXE) }, { 0, } /* terminate list */ }; MODULE_DEVICE_TABLE(pci, sti_pci_tbl); static struct pci_driver pci_sti_driver = { .name = "sti", .id_table = sti_pci_tbl, .probe = sticore_pci_init, .remove = __exit_p(sticore_pci_remove), }; static struct parisc_device_id sti_pa_tbl[] = { { HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x00077 }, { HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x00085 }, { 0, } }; MODULE_DEVICE_TABLE(parisc, sti_pa_tbl); static struct parisc_driver pa_sti_driver __refdata = { .name = "sti", .id_table = sti_pa_tbl, .probe = sticore_pa_init, }; /* * sti_init_roms() - detects all STI ROMs and stores them in sti_roms[] */ static int sticore_initialized __read_mostly; static void sti_init_roms(void) { if (sticore_initialized) return; sticore_initialized = 1; pr_info("STI GSC/PCI core graphics driver " STI_DRIVERVERSION "\n"); /* Register drivers for native & PCI cards */ register_parisc_driver(&pa_sti_driver); WARN_ON(pci_register_driver(&pci_sti_driver)); /* if we didn't find the given default sti, take the first one */ if (!default_sti) default_sti = sti_roms[0]; } /* * index = 0 gives default sti * index > 0 gives other stis in detection order */ struct sti_struct * sti_get_rom(unsigned int index) { if (!sticore_initialized) sti_init_roms(); if (index == 0) return default_sti; if (index > num_sti_roms) return NULL; return sti_roms[index-1]; } EXPORT_SYMBOL(sti_get_rom); int sti_call(const struct sti_struct *sti, unsigned long func, const void *flags, void *inptr, void *outptr, struct sti_glob_cfg *glob_cfg) { unsigned long _flags = STI_PTR(flags); unsigned long _inptr = STI_PTR(inptr); unsigned long _outptr = STI_PTR(outptr); unsigned long _glob_cfg = STI_PTR(glob_cfg); int ret; /* Check for overflow when using 32bit STI on 64bit kernel. */ if (WARN_ONCE(IS_ENABLED(CONFIG_64BIT) && !sti->do_call64 && (upper_32_bits(_flags) || upper_32_bits(_inptr) || upper_32_bits(_outptr) || upper_32_bits(_glob_cfg)), "Out of 32bit-range pointers!")) return -1; ret = pdc_sti_call(func, _flags, _inptr, _outptr, _glob_cfg, sti->do_call64); return ret; } MODULE_AUTHOR("Philipp Rumpf, Helge Deller, Thomas Bogendoerfer"); MODULE_DESCRIPTION("Core STI driver for HP's NGLE series graphics cards in HP PARISC machines"); MODULE_LICENSE("GPL v2");
linux-master
drivers/video/sticore.c
// SPDX-License-Identifier: GPL-2.0-only /* * Convert a logo in ASCII PNM format to C source suitable for inclusion in * the Linux kernel * * (C) Copyright 2001-2003 by Geert Uytterhoeven <[email protected]> */ #include <ctype.h> #include <errno.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> static const char *programname; static const char *filename; static const char *logoname = "linux_logo"; static const char *outputname; static FILE *out; #define LINUX_LOGO_MONO 1 /* monochrome black/white */ #define LINUX_LOGO_VGA16 2 /* 16 colors VGA text palette */ #define LINUX_LOGO_CLUT224 3 /* 224 colors */ #define LINUX_LOGO_GRAY256 4 /* 256 levels grayscale */ static const char *logo_types[LINUX_LOGO_GRAY256+1] = { [LINUX_LOGO_MONO] = "LINUX_LOGO_MONO", [LINUX_LOGO_VGA16] = "LINUX_LOGO_VGA16", [LINUX_LOGO_CLUT224] = "LINUX_LOGO_CLUT224", [LINUX_LOGO_GRAY256] = "LINUX_LOGO_GRAY256" }; #define MAX_LINUX_LOGO_COLORS 224 struct color { unsigned char red; unsigned char green; unsigned char blue; }; static const struct color clut_vga16[16] = { { 0x00, 0x00, 0x00 }, { 0x00, 0x00, 0xaa }, { 0x00, 0xaa, 0x00 }, { 0x00, 0xaa, 0xaa }, { 0xaa, 0x00, 0x00 }, { 0xaa, 0x00, 0xaa }, { 0xaa, 0x55, 0x00 }, { 0xaa, 0xaa, 0xaa }, { 0x55, 0x55, 0x55 }, { 0x55, 0x55, 0xff }, { 0x55, 0xff, 0x55 }, { 0x55, 0xff, 0xff }, { 0xff, 0x55, 0x55 }, { 0xff, 0x55, 0xff }, { 0xff, 0xff, 0x55 }, { 0xff, 0xff, 0xff }, }; static int logo_type = LINUX_LOGO_CLUT224; static unsigned int logo_width; static unsigned int logo_height; static struct color **logo_data; static struct color logo_clut[MAX_LINUX_LOGO_COLORS]; static unsigned int logo_clutsize; static int is_plain_pbm = 0; static void die(const char *fmt, ...) __attribute__((noreturn)) __attribute((format (printf, 1, 2))); static void usage(void) __attribute((noreturn)); static unsigned int get_number(FILE *fp) { int c, val; /* Skip leading whitespace */ do { c = fgetc(fp); if (c == EOF) die("%s: end of file\n", filename); if (c == '#') { /* Ignore comments 'till end of line */ do { c = fgetc(fp); if (c == EOF) die("%s: end of file\n", filename); } while (c != '\n'); } } while (isspace(c)); /* Parse decimal number */ val = 0; while (isdigit(c)) { val = 10*val+c-'0'; /* some PBM are 'broken'; GiMP for example exports a PBM without space * between the digits. This is Ok cause we know a PBM can only have a '1' * or a '0' for the digit. */ if (is_plain_pbm) break; c = fgetc(fp); if (c == EOF) die("%s: end of file\n", filename); } return val; } static unsigned int get_number255(FILE *fp, unsigned int maxval) { unsigned int val = get_number(fp); return (255*val+maxval/2)/maxval; } static void read_image(void) { FILE *fp; unsigned int i, j; int magic; unsigned int maxval; /* open image file */ fp = fopen(filename, "r"); if (!fp) die("Cannot open file %s: %s\n", filename, strerror(errno)); /* check file type and read file header */ magic = fgetc(fp); if (magic != 'P') die("%s is not a PNM file\n", filename); magic = fgetc(fp); switch (magic) { case '1': case '2': case '3': /* Plain PBM/PGM/PPM */ break; case '4': case '5': case '6': /* Binary PBM/PGM/PPM */ die("%s: Binary PNM is not supported\n" "Use pnmnoraw(1) to convert it to ASCII PNM\n", filename); default: die("%s is not a PNM file\n", filename); } logo_width = get_number(fp); logo_height = get_number(fp); /* allocate image data */ logo_data = (struct color **)malloc(logo_height*sizeof(struct color *)); if (!logo_data) die("%s\n", strerror(errno)); for (i = 0; i < logo_height; i++) { logo_data[i] = malloc(logo_width*sizeof(struct color)); if (!logo_data[i]) die("%s\n", strerror(errno)); } /* read image data */ switch (magic) { case '1': /* Plain PBM */ is_plain_pbm = 1; for (i = 0; i < logo_height; i++) for (j = 0; j < logo_width; j++) logo_data[i][j].red = logo_data[i][j].green = logo_data[i][j].blue = 255*(1-get_number(fp)); break; case '2': /* Plain PGM */ maxval = get_number(fp); for (i = 0; i < logo_height; i++) for (j = 0; j < logo_width; j++) logo_data[i][j].red = logo_data[i][j].green = logo_data[i][j].blue = get_number255(fp, maxval); break; case '3': /* Plain PPM */ maxval = get_number(fp); for (i = 0; i < logo_height; i++) for (j = 0; j < logo_width; j++) { logo_data[i][j].red = get_number255(fp, maxval); logo_data[i][j].green = get_number255(fp, maxval); logo_data[i][j].blue = get_number255(fp, maxval); } break; } /* close file */ fclose(fp); } static inline int is_black(struct color c) { return c.red == 0 && c.green == 0 && c.blue == 0; } static inline int is_white(struct color c) { return c.red == 255 && c.green == 255 && c.blue == 255; } static inline int is_gray(struct color c) { return c.red == c.green && c.red == c.blue; } static inline int is_equal(struct color c1, struct color c2) { return c1.red == c2.red && c1.green == c2.green && c1.blue == c2.blue; } static void write_header(void) { /* open logo file */ if (outputname) { out = fopen(outputname, "w"); if (!out) die("Cannot create file %s: %s\n", outputname, strerror(errno)); } else { out = stdout; } fputs("/*\n", out); fputs(" * DO NOT EDIT THIS FILE!\n", out); fputs(" *\n", out); fprintf(out, " * It was automatically generated from %s\n", filename); fputs(" *\n", out); fprintf(out, " * Linux logo %s\n", logoname); fputs(" */\n\n", out); fputs("#include <linux/linux_logo.h>\n\n", out); fprintf(out, "static unsigned char %s_data[] __initdata = {\n", logoname); } static void write_footer(void) { fputs("\n};\n\n", out); fprintf(out, "const struct linux_logo %s __initconst = {\n", logoname); fprintf(out, "\t.type\t\t= %s,\n", logo_types[logo_type]); fprintf(out, "\t.width\t\t= %d,\n", logo_width); fprintf(out, "\t.height\t\t= %d,\n", logo_height); if (logo_type == LINUX_LOGO_CLUT224) { fprintf(out, "\t.clutsize\t= %d,\n", logo_clutsize); fprintf(out, "\t.clut\t\t= %s_clut,\n", logoname); } fprintf(out, "\t.data\t\t= %s_data\n", logoname); fputs("};\n\n", out); /* close logo file */ if (outputname) fclose(out); } static int write_hex_cnt; static void write_hex(unsigned char byte) { if (write_hex_cnt % 12) fprintf(out, ", 0x%02x", byte); else if (write_hex_cnt) fprintf(out, ",\n\t0x%02x", byte); else fprintf(out, "\t0x%02x", byte); write_hex_cnt++; } static void write_logo_mono(void) { unsigned int i, j; unsigned char val, bit; /* validate image */ for (i = 0; i < logo_height; i++) for (j = 0; j < logo_width; j++) if (!is_black(logo_data[i][j]) && !is_white(logo_data[i][j])) die("Image must be monochrome\n"); /* write file header */ write_header(); /* write logo data */ for (i = 0; i < logo_height; i++) { for (j = 0; j < logo_width;) { for (val = 0, bit = 0x80; bit && j < logo_width; j++, bit >>= 1) if (logo_data[i][j].red) val |= bit; write_hex(val); } } /* write logo structure and file footer */ write_footer(); } static void write_logo_vga16(void) { unsigned int i, j, k; unsigned char val; /* validate image */ for (i = 0; i < logo_height; i++) for (j = 0; j < logo_width; j++) { for (k = 0; k < 16; k++) if (is_equal(logo_data[i][j], clut_vga16[k])) break; if (k == 16) die("Image must use the 16 console colors only\n" "Use ppmquant(1) -map clut_vga16.ppm to reduce the number " "of colors\n"); } /* write file header */ write_header(); /* write logo data */ for (i = 0; i < logo_height; i++) for (j = 0; j < logo_width; j++) { for (k = 0; k < 16; k++) if (is_equal(logo_data[i][j], clut_vga16[k])) break; val = k<<4; if (++j < logo_width) { for (k = 0; k < 16; k++) if (is_equal(logo_data[i][j], clut_vga16[k])) break; val |= k; } write_hex(val); } /* write logo structure and file footer */ write_footer(); } static void write_logo_clut224(void) { unsigned int i, j, k; /* validate image */ for (i = 0; i < logo_height; i++) for (j = 0; j < logo_width; j++) { for (k = 0; k < logo_clutsize; k++) if (is_equal(logo_data[i][j], logo_clut[k])) break; if (k == logo_clutsize) { if (logo_clutsize == MAX_LINUX_LOGO_COLORS) die("Image has more than %d colors\n" "Use ppmquant(1) to reduce the number of colors\n", MAX_LINUX_LOGO_COLORS); logo_clut[logo_clutsize++] = logo_data[i][j]; } } /* write file header */ write_header(); /* write logo data */ for (i = 0; i < logo_height; i++) for (j = 0; j < logo_width; j++) { for (k = 0; k < logo_clutsize; k++) if (is_equal(logo_data[i][j], logo_clut[k])) break; write_hex(k+32); } fputs("\n};\n\n", out); /* write logo clut */ fprintf(out, "static unsigned char %s_clut[] __initdata = {\n", logoname); write_hex_cnt = 0; for (i = 0; i < logo_clutsize; i++) { write_hex(logo_clut[i].red); write_hex(logo_clut[i].green); write_hex(logo_clut[i].blue); } /* write logo structure and file footer */ write_footer(); } static void write_logo_gray256(void) { unsigned int i, j; /* validate image */ for (i = 0; i < logo_height; i++) for (j = 0; j < logo_width; j++) if (!is_gray(logo_data[i][j])) die("Image must be grayscale\n"); /* write file header */ write_header(); /* write logo data */ for (i = 0; i < logo_height; i++) for (j = 0; j < logo_width; j++) write_hex(logo_data[i][j].red); /* write logo structure and file footer */ write_footer(); } static void die(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); exit(1); } static void usage(void) { die("\n" "Usage: %s [options] <filename>\n" "\n" "Valid options:\n" " -h : display this usage information\n" " -n <name> : specify logo name (default: linux_logo)\n" " -o <output> : output to file <output> instead of stdout\n" " -t <type> : specify logo type, one of\n" " mono : monochrome black/white\n" " vga16 : 16 colors VGA text palette\n" " clut224 : 224 colors (default)\n" " gray256 : 256 levels grayscale\n" "\n", programname); } int main(int argc, char *argv[]) { int opt; programname = argv[0]; opterr = 0; while (1) { opt = getopt(argc, argv, "hn:o:t:"); if (opt == -1) break; switch (opt) { case 'h': usage(); break; case 'n': logoname = optarg; break; case 'o': outputname = optarg; break; case 't': if (!strcmp(optarg, "mono")) logo_type = LINUX_LOGO_MONO; else if (!strcmp(optarg, "vga16")) logo_type = LINUX_LOGO_VGA16; else if (!strcmp(optarg, "clut224")) logo_type = LINUX_LOGO_CLUT224; else if (!strcmp(optarg, "gray256")) logo_type = LINUX_LOGO_GRAY256; else usage(); break; default: usage(); break; } } if (optind != argc-1) usage(); filename = argv[optind]; read_image(); switch (logo_type) { case LINUX_LOGO_MONO: write_logo_mono(); break; case LINUX_LOGO_VGA16: write_logo_vga16(); break; case LINUX_LOGO_CLUT224: write_logo_clut224(); break; case LINUX_LOGO_GRAY256: write_logo_gray256(); break; } exit(0); }
linux-master
drivers/video/logo/pnmtologo.c
// SPDX-License-Identifier: GPL-2.0-only /* * Linux logo to be displayed on boot * * Copyright (C) 1996 Larry Ewing ([email protected]) * Copyright (C) 1996,1998 Jakub Jelinek ([email protected]) * Copyright (C) 2001 Greg Banks <[email protected]> * Copyright (C) 2001 Jan-Benedict Glaw <[email protected]> * Copyright (C) 2003 Geert Uytterhoeven <[email protected]> */ #include <linux/linux_logo.h> #include <linux/stddef.h> #include <linux/module.h> #ifdef CONFIG_M68K #include <asm/setup.h> #endif static bool nologo; module_param(nologo, bool, 0); MODULE_PARM_DESC(nologo, "Disables startup logo"); /* * Logos are located in the initdata, and will be freed in kernel_init. * Use late_init to mark the logos as freed to prevent any further use. */ static bool logos_freed; static int __init fb_logo_late_init(void) { logos_freed = true; return 0; } late_initcall_sync(fb_logo_late_init); /* logo's are marked __initdata. Use __ref to tell * modpost that it is intended that this function uses data * marked __initdata. */ const struct linux_logo * __ref fb_find_logo(int depth) { const struct linux_logo *logo = NULL; if (nologo || logos_freed) return NULL; if (depth >= 1) { #ifdef CONFIG_LOGO_LINUX_MONO /* Generic Linux logo */ logo = &logo_linux_mono; #endif #ifdef CONFIG_LOGO_SUPERH_MONO /* SuperH Linux logo */ logo = &logo_superh_mono; #endif } if (depth >= 4) { #ifdef CONFIG_LOGO_LINUX_VGA16 /* Generic Linux logo */ logo = &logo_linux_vga16; #endif #ifdef CONFIG_LOGO_SUPERH_VGA16 /* SuperH Linux logo */ logo = &logo_superh_vga16; #endif } if (depth >= 8) { #ifdef CONFIG_LOGO_LINUX_CLUT224 /* Generic Linux logo */ logo = &logo_linux_clut224; #endif #ifdef CONFIG_LOGO_DEC_CLUT224 /* DEC Linux logo on MIPS/MIPS64 or ALPHA */ logo = &logo_dec_clut224; #endif #ifdef CONFIG_LOGO_MAC_CLUT224 /* Macintosh Linux logo on m68k */ if (MACH_IS_MAC) logo = &logo_mac_clut224; #endif #ifdef CONFIG_LOGO_PARISC_CLUT224 /* PA-RISC Linux logo */ logo = &logo_parisc_clut224; #endif #ifdef CONFIG_LOGO_SGI_CLUT224 /* SGI Linux logo on MIPS/MIPS64 */ logo = &logo_sgi_clut224; #endif #ifdef CONFIG_LOGO_SUN_CLUT224 /* Sun Linux logo */ logo = &logo_sun_clut224; #endif #ifdef CONFIG_LOGO_SUPERH_CLUT224 /* SuperH Linux logo */ logo = &logo_superh_clut224; #endif } return logo; } EXPORT_SYMBOL_GPL(fb_find_logo);
linux-master
drivers/video/logo/logo.c
// SPDX-License-Identifier: GPL-2.0-only /* drivers/video/backlight/ili9320.c * * ILI9320 LCD controller driver core. * * Copyright 2007 Simtec Electronics * http://armlinux.simtec.co.uk/ * Ben Dooks <[email protected]> */ #include <linux/delay.h> #include <linux/err.h> #include <linux/fb.h> #include <linux/init.h> #include <linux/lcd.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/spi/spi.h> #include <video/ili9320.h> #include "ili9320.h" static inline int ili9320_write_spi(struct ili9320 *ili, unsigned int reg, unsigned int value) { struct ili9320_spi *spi = &ili->access.spi; unsigned char *addr = spi->buffer_addr; unsigned char *data = spi->buffer_data; /* spi message consits of: * first byte: ID and operation */ addr[0] = spi->id | ILI9320_SPI_INDEX | ILI9320_SPI_WRITE; addr[1] = reg >> 8; addr[2] = reg; /* second message is the data to transfer */ data[0] = spi->id | ILI9320_SPI_DATA | ILI9320_SPI_WRITE; data[1] = value >> 8; data[2] = value; return spi_sync(spi->dev, &spi->message); } int ili9320_write(struct ili9320 *ili, unsigned int reg, unsigned int value) { dev_dbg(ili->dev, "write: reg=%02x, val=%04x\n", reg, value); return ili->write(ili, reg, value); } EXPORT_SYMBOL_GPL(ili9320_write); int ili9320_write_regs(struct ili9320 *ili, const struct ili9320_reg *values, int nr_values) { int index; int ret; for (index = 0; index < nr_values; index++, values++) { ret = ili9320_write(ili, values->address, values->value); if (ret != 0) return ret; } return 0; } EXPORT_SYMBOL_GPL(ili9320_write_regs); static void ili9320_reset(struct ili9320 *lcd) { struct ili9320_platdata *cfg = lcd->platdata; cfg->reset(1); mdelay(50); cfg->reset(0); mdelay(50); cfg->reset(1); mdelay(100); } static inline int ili9320_init_chip(struct ili9320 *lcd) { int ret; ili9320_reset(lcd); ret = lcd->client->init(lcd, lcd->platdata); if (ret != 0) { dev_err(lcd->dev, "failed to initialise display\n"); return ret; } lcd->initialised = 1; return 0; } static inline int ili9320_power_on(struct ili9320 *lcd) { if (!lcd->initialised) ili9320_init_chip(lcd); lcd->display1 |= (ILI9320_DISPLAY1_D(3) | ILI9320_DISPLAY1_BASEE); ili9320_write(lcd, ILI9320_DISPLAY1, lcd->display1); return 0; } static inline int ili9320_power_off(struct ili9320 *lcd) { lcd->display1 &= ~(ILI9320_DISPLAY1_D(3) | ILI9320_DISPLAY1_BASEE); ili9320_write(lcd, ILI9320_DISPLAY1, lcd->display1); return 0; } #define POWER_IS_ON(pwr) ((pwr) <= FB_BLANK_NORMAL) static int ili9320_power(struct ili9320 *lcd, int power) { int ret = 0; dev_dbg(lcd->dev, "power %d => %d\n", lcd->power, power); if (POWER_IS_ON(power) && !POWER_IS_ON(lcd->power)) ret = ili9320_power_on(lcd); else if (!POWER_IS_ON(power) && POWER_IS_ON(lcd->power)) ret = ili9320_power_off(lcd); if (ret == 0) lcd->power = power; else dev_warn(lcd->dev, "failed to set power mode %d\n", power); return ret; } static inline struct ili9320 *to_our_lcd(struct lcd_device *lcd) { return lcd_get_data(lcd); } static int ili9320_set_power(struct lcd_device *ld, int power) { struct ili9320 *lcd = to_our_lcd(ld); return ili9320_power(lcd, power); } static int ili9320_get_power(struct lcd_device *ld) { struct ili9320 *lcd = to_our_lcd(ld); return lcd->power; } static struct lcd_ops ili9320_ops = { .get_power = ili9320_get_power, .set_power = ili9320_set_power, }; static void ili9320_setup_spi(struct ili9320 *ili, struct spi_device *dev) { struct ili9320_spi *spi = &ili->access.spi; ili->write = ili9320_write_spi; spi->dev = dev; /* fill the two messages we are going to use to send the data * with, the first the address followed by the data. The datasheet * says they should be done as two distinct cycles of the SPI CS line. */ spi->xfer[0].tx_buf = spi->buffer_addr; spi->xfer[1].tx_buf = spi->buffer_data; spi->xfer[0].len = 3; spi->xfer[1].len = 3; spi->xfer[0].bits_per_word = 8; spi->xfer[1].bits_per_word = 8; spi->xfer[0].cs_change = 1; spi_message_init(&spi->message); spi_message_add_tail(&spi->xfer[0], &spi->message); spi_message_add_tail(&spi->xfer[1], &spi->message); } int ili9320_probe_spi(struct spi_device *spi, struct ili9320_client *client) { struct ili9320_platdata *cfg = dev_get_platdata(&spi->dev); struct device *dev = &spi->dev; struct ili9320 *ili; struct lcd_device *lcd; int ret = 0; /* verify we where given some information */ if (cfg == NULL) { dev_err(dev, "no platform data supplied\n"); return -EINVAL; } if (cfg->hsize <= 0 || cfg->vsize <= 0 || cfg->reset == NULL) { dev_err(dev, "invalid platform data supplied\n"); return -EINVAL; } /* allocate and initialse our state */ ili = devm_kzalloc(&spi->dev, sizeof(struct ili9320), GFP_KERNEL); if (ili == NULL) return -ENOMEM; ili->access.spi.id = ILI9320_SPI_IDCODE | ILI9320_SPI_ID(1); ili->dev = dev; ili->client = client; ili->power = FB_BLANK_POWERDOWN; ili->platdata = cfg; spi_set_drvdata(spi, ili); ili9320_setup_spi(ili, spi); lcd = devm_lcd_device_register(&spi->dev, "ili9320", dev, ili, &ili9320_ops); if (IS_ERR(lcd)) { dev_err(dev, "failed to register lcd device\n"); return PTR_ERR(lcd); } ili->lcd = lcd; dev_info(dev, "initialising %s\n", client->name); ret = ili9320_power(ili, FB_BLANK_UNBLANK); if (ret != 0) { dev_err(dev, "failed to set lcd power state\n"); return ret; } return 0; } EXPORT_SYMBOL_GPL(ili9320_probe_spi); void ili9320_remove(struct ili9320 *ili) { ili9320_power(ili, FB_BLANK_POWERDOWN); } EXPORT_SYMBOL_GPL(ili9320_remove); #ifdef CONFIG_PM_SLEEP int ili9320_suspend(struct ili9320 *lcd) { int ret; ret = ili9320_power(lcd, FB_BLANK_POWERDOWN); if (lcd->platdata->suspend == ILI9320_SUSPEND_DEEP) { ili9320_write(lcd, ILI9320_POWER1, lcd->power1 | ILI9320_POWER1_SLP | ILI9320_POWER1_DSTB); lcd->initialised = 0; } return ret; } EXPORT_SYMBOL_GPL(ili9320_suspend); int ili9320_resume(struct ili9320 *lcd) { dev_info(lcd->dev, "resuming from power state %d\n", lcd->power); if (lcd->platdata->suspend == ILI9320_SUSPEND_DEEP) ili9320_write(lcd, ILI9320_POWER1, 0x00); return ili9320_power(lcd, FB_BLANK_UNBLANK); } EXPORT_SYMBOL_GPL(ili9320_resume); #endif /* Power down all displays on reboot, poweroff or halt */ void ili9320_shutdown(struct ili9320 *lcd) { ili9320_power(lcd, FB_BLANK_POWERDOWN); } EXPORT_SYMBOL_GPL(ili9320_shutdown); MODULE_AUTHOR("Ben Dooks <[email protected]>"); MODULE_DESCRIPTION("ILI9320 LCD Driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/video/backlight/ili9320.c
// SPDX-License-Identifier: GPL-2.0-only /* * Power control for Samsung LTV350QV Quarter VGA LCD Panel * * Copyright (C) 2006, 2007 Atmel Corporation */ #include <linux/delay.h> #include <linux/err.h> #include <linux/fb.h> #include <linux/init.h> #include <linux/lcd.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/spi/spi.h> #include "ltv350qv.h" #define POWER_IS_ON(pwr) ((pwr) <= FB_BLANK_NORMAL) struct ltv350qv { struct spi_device *spi; u8 *buffer; int power; struct lcd_device *ld; }; /* * The power-on and power-off sequences are taken from the * LTV350QV-F04 data sheet from Samsung. The register definitions are * taken from the S6F2002 command list also from Samsung. * * There's still some voodoo going on here, but it's a lot better than * in the first incarnation of the driver where all we had was the raw * numbers from the initialization sequence. */ static int ltv350qv_write_reg(struct ltv350qv *lcd, u8 reg, u16 val) { struct spi_message msg; struct spi_transfer index_xfer = { .len = 3, .cs_change = 1, }; struct spi_transfer value_xfer = { .len = 3, }; spi_message_init(&msg); /* register index */ lcd->buffer[0] = LTV_OPC_INDEX; lcd->buffer[1] = 0x00; lcd->buffer[2] = reg & 0x7f; index_xfer.tx_buf = lcd->buffer; spi_message_add_tail(&index_xfer, &msg); /* register value */ lcd->buffer[4] = LTV_OPC_DATA; lcd->buffer[5] = val >> 8; lcd->buffer[6] = val; value_xfer.tx_buf = lcd->buffer + 4; spi_message_add_tail(&value_xfer, &msg); return spi_sync(lcd->spi, &msg); } /* The comments are taken straight from the data sheet */ static int ltv350qv_power_on(struct ltv350qv *lcd) { int ret; /* Power On Reset Display off State */ if (ltv350qv_write_reg(lcd, LTV_PWRCTL1, 0x0000)) goto err; usleep_range(15000, 16000); /* Power Setting Function 1 */ if (ltv350qv_write_reg(lcd, LTV_PWRCTL1, LTV_VCOM_DISABLE)) goto err; if (ltv350qv_write_reg(lcd, LTV_PWRCTL2, LTV_VCOML_ENABLE)) goto err_power1; /* Power Setting Function 2 */ if (ltv350qv_write_reg(lcd, LTV_PWRCTL1, LTV_VCOM_DISABLE | LTV_DRIVE_CURRENT(5) | LTV_SUPPLY_CURRENT(5))) goto err_power2; msleep(55); /* Instruction Setting */ ret = ltv350qv_write_reg(lcd, LTV_IFCTL, LTV_NMD | LTV_REV | LTV_NL(0x1d)); ret |= ltv350qv_write_reg(lcd, LTV_DATACTL, LTV_DS_SAME | LTV_CHS_480 | LTV_DF_RGB | LTV_RGB_BGR); ret |= ltv350qv_write_reg(lcd, LTV_ENTRY_MODE, LTV_VSPL_ACTIVE_LOW | LTV_HSPL_ACTIVE_LOW | LTV_DPL_SAMPLE_RISING | LTV_EPL_ACTIVE_LOW | LTV_SS_RIGHT_TO_LEFT); ret |= ltv350qv_write_reg(lcd, LTV_GATECTL1, LTV_CLW(3)); ret |= ltv350qv_write_reg(lcd, LTV_GATECTL2, LTV_NW_INV_1LINE | LTV_FWI(3)); ret |= ltv350qv_write_reg(lcd, LTV_VBP, 0x000a); ret |= ltv350qv_write_reg(lcd, LTV_HBP, 0x0021); ret |= ltv350qv_write_reg(lcd, LTV_SOTCTL, LTV_SDT(3) | LTV_EQ(0)); ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(0), 0x0103); ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(1), 0x0301); ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(2), 0x1f0f); ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(3), 0x1f0f); ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(4), 0x0707); ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(5), 0x0307); ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(6), 0x0707); ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(7), 0x0000); ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(8), 0x0004); ret |= ltv350qv_write_reg(lcd, LTV_GAMMA(9), 0x0000); if (ret) goto err_settings; /* Wait more than 2 frames */ msleep(20); /* Display On Sequence */ ret = ltv350qv_write_reg(lcd, LTV_PWRCTL1, LTV_VCOM_DISABLE | LTV_VCOMOUT_ENABLE | LTV_POWER_ON | LTV_DRIVE_CURRENT(5) | LTV_SUPPLY_CURRENT(5)); ret |= ltv350qv_write_reg(lcd, LTV_GATECTL2, LTV_NW_INV_1LINE | LTV_DSC | LTV_FWI(3)); if (ret) goto err_disp_on; /* Display should now be ON. Phew. */ return 0; err_disp_on: /* * Try to recover. Error handling probably isn't very useful * at this point, just make a best effort to switch the panel * off. */ ltv350qv_write_reg(lcd, LTV_PWRCTL1, LTV_VCOM_DISABLE | LTV_DRIVE_CURRENT(5) | LTV_SUPPLY_CURRENT(5)); ltv350qv_write_reg(lcd, LTV_GATECTL2, LTV_NW_INV_1LINE | LTV_FWI(3)); err_settings: err_power2: err_power1: ltv350qv_write_reg(lcd, LTV_PWRCTL2, 0x0000); usleep_range(1000, 1100); err: ltv350qv_write_reg(lcd, LTV_PWRCTL1, LTV_VCOM_DISABLE); return -EIO; } static int ltv350qv_power_off(struct ltv350qv *lcd) { int ret; /* Display Off Sequence */ ret = ltv350qv_write_reg(lcd, LTV_PWRCTL1, LTV_VCOM_DISABLE | LTV_DRIVE_CURRENT(5) | LTV_SUPPLY_CURRENT(5)); ret |= ltv350qv_write_reg(lcd, LTV_GATECTL2, LTV_NW_INV_1LINE | LTV_FWI(3)); /* Power down setting 1 */ ret |= ltv350qv_write_reg(lcd, LTV_PWRCTL2, 0x0000); /* Wait at least 1 ms */ usleep_range(1000, 1100); /* Power down setting 2 */ ret |= ltv350qv_write_reg(lcd, LTV_PWRCTL1, LTV_VCOM_DISABLE); /* * No point in trying to recover here. If we can't switch the * panel off, what are we supposed to do other than inform the * user about the failure? */ if (ret) return -EIO; /* Display power should now be OFF */ return 0; } static int ltv350qv_power(struct ltv350qv *lcd, int power) { int ret = 0; if (POWER_IS_ON(power) && !POWER_IS_ON(lcd->power)) ret = ltv350qv_power_on(lcd); else if (!POWER_IS_ON(power) && POWER_IS_ON(lcd->power)) ret = ltv350qv_power_off(lcd); if (!ret) lcd->power = power; return ret; } static int ltv350qv_set_power(struct lcd_device *ld, int power) { struct ltv350qv *lcd = lcd_get_data(ld); return ltv350qv_power(lcd, power); } static int ltv350qv_get_power(struct lcd_device *ld) { struct ltv350qv *lcd = lcd_get_data(ld); return lcd->power; } static struct lcd_ops ltv_ops = { .get_power = ltv350qv_get_power, .set_power = ltv350qv_set_power, }; static int ltv350qv_probe(struct spi_device *spi) { struct ltv350qv *lcd; struct lcd_device *ld; int ret; lcd = devm_kzalloc(&spi->dev, sizeof(struct ltv350qv), GFP_KERNEL); if (!lcd) return -ENOMEM; lcd->spi = spi; lcd->power = FB_BLANK_POWERDOWN; lcd->buffer = devm_kzalloc(&spi->dev, 8, GFP_KERNEL); if (!lcd->buffer) return -ENOMEM; ld = devm_lcd_device_register(&spi->dev, "ltv350qv", &spi->dev, lcd, &ltv_ops); if (IS_ERR(ld)) return PTR_ERR(ld); lcd->ld = ld; ret = ltv350qv_power(lcd, FB_BLANK_UNBLANK); if (ret) return ret; spi_set_drvdata(spi, lcd); return 0; } static void ltv350qv_remove(struct spi_device *spi) { struct ltv350qv *lcd = spi_get_drvdata(spi); ltv350qv_power(lcd, FB_BLANK_POWERDOWN); } #ifdef CONFIG_PM_SLEEP static int ltv350qv_suspend(struct device *dev) { struct ltv350qv *lcd = dev_get_drvdata(dev); return ltv350qv_power(lcd, FB_BLANK_POWERDOWN); } static int ltv350qv_resume(struct device *dev) { struct ltv350qv *lcd = dev_get_drvdata(dev); return ltv350qv_power(lcd, FB_BLANK_UNBLANK); } #endif static SIMPLE_DEV_PM_OPS(ltv350qv_pm_ops, ltv350qv_suspend, ltv350qv_resume); /* Power down all displays on reboot, poweroff or halt */ static void ltv350qv_shutdown(struct spi_device *spi) { struct ltv350qv *lcd = spi_get_drvdata(spi); ltv350qv_power(lcd, FB_BLANK_POWERDOWN); } static struct spi_driver ltv350qv_driver = { .driver = { .name = "ltv350qv", .pm = &ltv350qv_pm_ops, }, .probe = ltv350qv_probe, .remove = ltv350qv_remove, .shutdown = ltv350qv_shutdown, }; module_spi_driver(ltv350qv_driver); MODULE_AUTHOR("Haavard Skinnemoen (Atmel)"); MODULE_DESCRIPTION("Samsung LTV350QV LCD Driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("spi:ltv350qv");
linux-master
drivers/video/backlight/ltv350qv.c
// SPDX-License-Identifier: GPL-2.0-only /* * Backlight Lowlevel Control Abstraction * * Copyright (C) 2003,2004 Hewlett-Packard Company * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/init.h> #include <linux/device.h> #include <linux/backlight.h> #include <linux/notifier.h> #include <linux/ctype.h> #include <linux/err.h> #include <linux/fb.h> #include <linux/slab.h> #ifdef CONFIG_PMAC_BACKLIGHT #include <asm/backlight.h> #endif /** * DOC: overview * * The backlight core supports implementing backlight drivers. * * A backlight driver registers a driver using * devm_backlight_device_register(). The properties of the backlight * driver such as type and max_brightness must be specified. * When the core detect changes in for example brightness or power state * the update_status() operation is called. The backlight driver shall * implement this operation and use it to adjust backlight. * * Several sysfs attributes are provided by the backlight core:: * * - brightness R/W, set the requested brightness level * - actual_brightness RO, the brightness level used by the HW * - max_brightness RO, the maximum brightness level supported * * See Documentation/ABI/stable/sysfs-class-backlight for the full list. * * The backlight can be adjusted using the sysfs interface, and * the backlight driver may also support adjusting backlight using * a hot-key or some other platform or firmware specific way. * * The driver must implement the get_brightness() operation if * the HW do not support all the levels that can be specified in * brightness, thus providing user-space access to the actual level * via the actual_brightness attribute. * * When the backlight changes this is reported to user-space using * an uevent connected to the actual_brightness attribute. * When brightness is set by platform specific means, for example * a hot-key to adjust backlight, the driver must notify the backlight * core that brightness has changed using backlight_force_update(). * * The backlight driver core receives notifications from fbdev and * if the event is FB_EVENT_BLANK and if the value of blank, from the * FBIOBLANK ioctrl, results in a change in the backlight state the * update_status() operation is called. */ static struct list_head backlight_dev_list; static struct mutex backlight_dev_list_mutex; static struct blocking_notifier_head backlight_notifier; static const char *const backlight_types[] = { [BACKLIGHT_RAW] = "raw", [BACKLIGHT_PLATFORM] = "platform", [BACKLIGHT_FIRMWARE] = "firmware", }; static const char *const backlight_scale_types[] = { [BACKLIGHT_SCALE_UNKNOWN] = "unknown", [BACKLIGHT_SCALE_LINEAR] = "linear", [BACKLIGHT_SCALE_NON_LINEAR] = "non-linear", }; #if defined(CONFIG_FB_CORE) || (defined(CONFIG_FB_CORE_MODULE) && \ defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)) /* * fb_notifier_callback * * This callback gets called when something important happens inside a * framebuffer driver. The backlight core only cares about FB_BLANK_UNBLANK * which is reported to the driver using backlight_update_status() * as a state change. * * There may be several fbdev's connected to the backlight device, * in which case they are kept track of. A state change is only reported * if there is a change in backlight for the specified fbdev. */ static int fb_notifier_callback(struct notifier_block *self, unsigned long event, void *data) { struct backlight_device *bd; struct fb_event *evdata = data; int node = evdata->info->node; int fb_blank = 0; /* If we aren't interested in this event, skip it immediately ... */ if (event != FB_EVENT_BLANK) return 0; bd = container_of(self, struct backlight_device, fb_notif); mutex_lock(&bd->ops_lock); if (!bd->ops) goto out; if (bd->ops->check_fb && !bd->ops->check_fb(bd, evdata->info)) goto out; fb_blank = *(int *)evdata->data; if (fb_blank == FB_BLANK_UNBLANK && !bd->fb_bl_on[node]) { bd->fb_bl_on[node] = true; if (!bd->use_count++) { bd->props.state &= ~BL_CORE_FBBLANK; bd->props.fb_blank = FB_BLANK_UNBLANK; backlight_update_status(bd); } } else if (fb_blank != FB_BLANK_UNBLANK && bd->fb_bl_on[node]) { bd->fb_bl_on[node] = false; if (!(--bd->use_count)) { bd->props.state |= BL_CORE_FBBLANK; bd->props.fb_blank = fb_blank; backlight_update_status(bd); } } out: mutex_unlock(&bd->ops_lock); return 0; } static int backlight_register_fb(struct backlight_device *bd) { memset(&bd->fb_notif, 0, sizeof(bd->fb_notif)); bd->fb_notif.notifier_call = fb_notifier_callback; return fb_register_client(&bd->fb_notif); } static void backlight_unregister_fb(struct backlight_device *bd) { fb_unregister_client(&bd->fb_notif); } #else static inline int backlight_register_fb(struct backlight_device *bd) { return 0; } static inline void backlight_unregister_fb(struct backlight_device *bd) { } #endif /* CONFIG_FB_CORE */ static void backlight_generate_event(struct backlight_device *bd, enum backlight_update_reason reason) { char *envp[2]; switch (reason) { case BACKLIGHT_UPDATE_SYSFS: envp[0] = "SOURCE=sysfs"; break; case BACKLIGHT_UPDATE_HOTKEY: envp[0] = "SOURCE=hotkey"; break; default: envp[0] = "SOURCE=unknown"; break; } envp[1] = NULL; kobject_uevent_env(&bd->dev.kobj, KOBJ_CHANGE, envp); sysfs_notify(&bd->dev.kobj, NULL, "actual_brightness"); } static ssize_t bl_power_show(struct device *dev, struct device_attribute *attr, char *buf) { struct backlight_device *bd = to_backlight_device(dev); return sprintf(buf, "%d\n", bd->props.power); } static ssize_t bl_power_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int rc; struct backlight_device *bd = to_backlight_device(dev); unsigned long power, old_power; rc = kstrtoul(buf, 0, &power); if (rc) return rc; rc = -ENXIO; mutex_lock(&bd->ops_lock); if (bd->ops) { pr_debug("set power to %lu\n", power); if (bd->props.power != power) { old_power = bd->props.power; bd->props.power = power; rc = backlight_update_status(bd); if (rc) bd->props.power = old_power; else rc = count; } else { rc = count; } } mutex_unlock(&bd->ops_lock); return rc; } static DEVICE_ATTR_RW(bl_power); static ssize_t brightness_show(struct device *dev, struct device_attribute *attr, char *buf) { struct backlight_device *bd = to_backlight_device(dev); return sprintf(buf, "%d\n", bd->props.brightness); } int backlight_device_set_brightness(struct backlight_device *bd, unsigned long brightness) { int rc = -ENXIO; mutex_lock(&bd->ops_lock); if (bd->ops) { if (brightness > bd->props.max_brightness) rc = -EINVAL; else { pr_debug("set brightness to %lu\n", brightness); bd->props.brightness = brightness; rc = backlight_update_status(bd); } } mutex_unlock(&bd->ops_lock); backlight_generate_event(bd, BACKLIGHT_UPDATE_SYSFS); return rc; } EXPORT_SYMBOL(backlight_device_set_brightness); static ssize_t brightness_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int rc; struct backlight_device *bd = to_backlight_device(dev); unsigned long brightness; rc = kstrtoul(buf, 0, &brightness); if (rc) return rc; rc = backlight_device_set_brightness(bd, brightness); return rc ? rc : count; } static DEVICE_ATTR_RW(brightness); static ssize_t type_show(struct device *dev, struct device_attribute *attr, char *buf) { struct backlight_device *bd = to_backlight_device(dev); return sprintf(buf, "%s\n", backlight_types[bd->props.type]); } static DEVICE_ATTR_RO(type); static ssize_t max_brightness_show(struct device *dev, struct device_attribute *attr, char *buf) { struct backlight_device *bd = to_backlight_device(dev); return sprintf(buf, "%d\n", bd->props.max_brightness); } static DEVICE_ATTR_RO(max_brightness); static ssize_t actual_brightness_show(struct device *dev, struct device_attribute *attr, char *buf) { int rc = -ENXIO; struct backlight_device *bd = to_backlight_device(dev); mutex_lock(&bd->ops_lock); if (bd->ops && bd->ops->get_brightness) { rc = bd->ops->get_brightness(bd); if (rc >= 0) rc = sprintf(buf, "%d\n", rc); } else { rc = sprintf(buf, "%d\n", bd->props.brightness); } mutex_unlock(&bd->ops_lock); return rc; } static DEVICE_ATTR_RO(actual_brightness); static ssize_t scale_show(struct device *dev, struct device_attribute *attr, char *buf) { struct backlight_device *bd = to_backlight_device(dev); if (WARN_ON(bd->props.scale > BACKLIGHT_SCALE_NON_LINEAR)) return sprintf(buf, "unknown\n"); return sprintf(buf, "%s\n", backlight_scale_types[bd->props.scale]); } static DEVICE_ATTR_RO(scale); static struct class *backlight_class; #ifdef CONFIG_PM_SLEEP static int backlight_suspend(struct device *dev) { struct backlight_device *bd = to_backlight_device(dev); mutex_lock(&bd->ops_lock); if (bd->ops && bd->ops->options & BL_CORE_SUSPENDRESUME) { bd->props.state |= BL_CORE_SUSPENDED; backlight_update_status(bd); } mutex_unlock(&bd->ops_lock); return 0; } static int backlight_resume(struct device *dev) { struct backlight_device *bd = to_backlight_device(dev); mutex_lock(&bd->ops_lock); if (bd->ops && bd->ops->options & BL_CORE_SUSPENDRESUME) { bd->props.state &= ~BL_CORE_SUSPENDED; backlight_update_status(bd); } mutex_unlock(&bd->ops_lock); return 0; } #endif static SIMPLE_DEV_PM_OPS(backlight_class_dev_pm_ops, backlight_suspend, backlight_resume); static void bl_device_release(struct device *dev) { struct backlight_device *bd = to_backlight_device(dev); kfree(bd); } static struct attribute *bl_device_attrs[] = { &dev_attr_bl_power.attr, &dev_attr_brightness.attr, &dev_attr_actual_brightness.attr, &dev_attr_max_brightness.attr, &dev_attr_scale.attr, &dev_attr_type.attr, NULL, }; ATTRIBUTE_GROUPS(bl_device); /** * backlight_force_update - tell the backlight subsystem that hardware state * has changed * @bd: the backlight device to update * @reason: reason for update * * Updates the internal state of the backlight in response to a hardware event, * and generates an uevent to notify userspace. A backlight driver shall call * backlight_force_update() when the backlight is changed using, for example, * a hot-key. The updated brightness is read using get_brightness() and the * brightness value is reported using an uevent. */ void backlight_force_update(struct backlight_device *bd, enum backlight_update_reason reason) { int brightness; mutex_lock(&bd->ops_lock); if (bd->ops && bd->ops->get_brightness) { brightness = bd->ops->get_brightness(bd); if (brightness >= 0) bd->props.brightness = brightness; else dev_err(&bd->dev, "Could not update brightness from device: %pe\n", ERR_PTR(brightness)); } mutex_unlock(&bd->ops_lock); backlight_generate_event(bd, reason); } EXPORT_SYMBOL(backlight_force_update); /* deprecated - use devm_backlight_device_register() */ struct backlight_device *backlight_device_register(const char *name, struct device *parent, void *devdata, const struct backlight_ops *ops, const struct backlight_properties *props) { struct backlight_device *new_bd; int rc; pr_debug("backlight_device_register: name=%s\n", name); new_bd = kzalloc(sizeof(struct backlight_device), GFP_KERNEL); if (!new_bd) return ERR_PTR(-ENOMEM); mutex_init(&new_bd->update_lock); mutex_init(&new_bd->ops_lock); new_bd->dev.class = backlight_class; new_bd->dev.parent = parent; new_bd->dev.release = bl_device_release; dev_set_name(&new_bd->dev, "%s", name); dev_set_drvdata(&new_bd->dev, devdata); /* Set default properties */ if (props) { memcpy(&new_bd->props, props, sizeof(struct backlight_properties)); if (props->type <= 0 || props->type >= BACKLIGHT_TYPE_MAX) { WARN(1, "%s: invalid backlight type", name); new_bd->props.type = BACKLIGHT_RAW; } } else { new_bd->props.type = BACKLIGHT_RAW; } rc = device_register(&new_bd->dev); if (rc) { put_device(&new_bd->dev); return ERR_PTR(rc); } rc = backlight_register_fb(new_bd); if (rc) { device_unregister(&new_bd->dev); return ERR_PTR(rc); } new_bd->ops = ops; #ifdef CONFIG_PMAC_BACKLIGHT mutex_lock(&pmac_backlight_mutex); if (!pmac_backlight) pmac_backlight = new_bd; mutex_unlock(&pmac_backlight_mutex); #endif mutex_lock(&backlight_dev_list_mutex); list_add(&new_bd->entry, &backlight_dev_list); mutex_unlock(&backlight_dev_list_mutex); blocking_notifier_call_chain(&backlight_notifier, BACKLIGHT_REGISTERED, new_bd); return new_bd; } EXPORT_SYMBOL(backlight_device_register); /** backlight_device_get_by_type - find first backlight device of a type * @type: the type of backlight device * * Look up the first backlight device of the specified type * * RETURNS: * * Pointer to backlight device if any was found. Otherwise NULL. */ struct backlight_device *backlight_device_get_by_type(enum backlight_type type) { bool found = false; struct backlight_device *bd; mutex_lock(&backlight_dev_list_mutex); list_for_each_entry(bd, &backlight_dev_list, entry) { if (bd->props.type == type) { found = true; break; } } mutex_unlock(&backlight_dev_list_mutex); return found ? bd : NULL; } EXPORT_SYMBOL(backlight_device_get_by_type); /** * backlight_device_get_by_name - Get backlight device by name * @name: Device name * * This function looks up a backlight device by its name. It obtains a reference * on the backlight device and it is the caller's responsibility to drop the * reference by calling put_device(). * * Returns: * A pointer to the backlight device if found, otherwise NULL. */ struct backlight_device *backlight_device_get_by_name(const char *name) { struct device *dev; dev = class_find_device_by_name(backlight_class, name); return dev ? to_backlight_device(dev) : NULL; } EXPORT_SYMBOL(backlight_device_get_by_name); /* deprecated - use devm_backlight_device_unregister() */ void backlight_device_unregister(struct backlight_device *bd) { if (!bd) return; mutex_lock(&backlight_dev_list_mutex); list_del(&bd->entry); mutex_unlock(&backlight_dev_list_mutex); #ifdef CONFIG_PMAC_BACKLIGHT mutex_lock(&pmac_backlight_mutex); if (pmac_backlight == bd) pmac_backlight = NULL; mutex_unlock(&pmac_backlight_mutex); #endif blocking_notifier_call_chain(&backlight_notifier, BACKLIGHT_UNREGISTERED, bd); mutex_lock(&bd->ops_lock); bd->ops = NULL; mutex_unlock(&bd->ops_lock); backlight_unregister_fb(bd); device_unregister(&bd->dev); } EXPORT_SYMBOL(backlight_device_unregister); static void devm_backlight_device_release(struct device *dev, void *res) { struct backlight_device *backlight = *(struct backlight_device **)res; backlight_device_unregister(backlight); } static int devm_backlight_device_match(struct device *dev, void *res, void *data) { struct backlight_device **r = res; return *r == data; } /** * backlight_register_notifier - get notified of backlight (un)registration * @nb: notifier block with the notifier to call on backlight (un)registration * * Register a notifier to get notified when backlight devices get registered * or unregistered. * * RETURNS: * * 0 on success, otherwise a negative error code */ int backlight_register_notifier(struct notifier_block *nb) { return blocking_notifier_chain_register(&backlight_notifier, nb); } EXPORT_SYMBOL(backlight_register_notifier); /** * backlight_unregister_notifier - unregister a backlight notifier * @nb: notifier block to unregister * * Register a notifier to get notified when backlight devices get registered * or unregistered. * * RETURNS: * * 0 on success, otherwise a negative error code */ int backlight_unregister_notifier(struct notifier_block *nb) { return blocking_notifier_chain_unregister(&backlight_notifier, nb); } EXPORT_SYMBOL(backlight_unregister_notifier); /** * devm_backlight_device_register - register a new backlight device * @dev: the device to register * @name: the name of the device * @parent: a pointer to the parent device (often the same as @dev) * @devdata: an optional pointer to be stored for private driver use * @ops: the backlight operations structure * @props: the backlight properties * * Creates and registers new backlight device. When a backlight device * is registered the configuration must be specified in the @props * parameter. See description of &backlight_properties. * * RETURNS: * * struct backlight on success, or an ERR_PTR on error */ struct backlight_device *devm_backlight_device_register(struct device *dev, const char *name, struct device *parent, void *devdata, const struct backlight_ops *ops, const struct backlight_properties *props) { struct backlight_device **ptr, *backlight; ptr = devres_alloc(devm_backlight_device_release, sizeof(*ptr), GFP_KERNEL); if (!ptr) return ERR_PTR(-ENOMEM); backlight = backlight_device_register(name, parent, devdata, ops, props); if (!IS_ERR(backlight)) { *ptr = backlight; devres_add(dev, ptr); } else { devres_free(ptr); } return backlight; } EXPORT_SYMBOL(devm_backlight_device_register); /** * devm_backlight_device_unregister - unregister backlight device * @dev: the device to unregister * @bd: the backlight device to unregister * * Deallocates a backlight allocated with devm_backlight_device_register(). * Normally this function will not need to be called and the resource management * code will ensure that the resources are freed. */ void devm_backlight_device_unregister(struct device *dev, struct backlight_device *bd) { int rc; rc = devres_release(dev, devm_backlight_device_release, devm_backlight_device_match, bd); WARN_ON(rc); } EXPORT_SYMBOL(devm_backlight_device_unregister); #ifdef CONFIG_OF static int of_parent_match(struct device *dev, const void *data) { return dev->parent && dev->parent->of_node == data; } /** * of_find_backlight_by_node() - find backlight device by device-tree node * @node: device-tree node of the backlight device * * Returns a pointer to the backlight device corresponding to the given DT * node or NULL if no such backlight device exists or if the device hasn't * been probed yet. * * This function obtains a reference on the backlight device and it is the * caller's responsibility to drop the reference by calling put_device() on * the backlight device's .dev field. */ struct backlight_device *of_find_backlight_by_node(struct device_node *node) { struct device *dev; dev = class_find_device(backlight_class, NULL, node, of_parent_match); return dev ? to_backlight_device(dev) : NULL; } EXPORT_SYMBOL(of_find_backlight_by_node); #endif static struct backlight_device *of_find_backlight(struct device *dev) { struct backlight_device *bd = NULL; struct device_node *np; if (!dev) return NULL; if (IS_ENABLED(CONFIG_OF) && dev->of_node) { np = of_parse_phandle(dev->of_node, "backlight", 0); if (np) { bd = of_find_backlight_by_node(np); of_node_put(np); if (!bd) return ERR_PTR(-EPROBE_DEFER); } } return bd; } static void devm_backlight_release(void *data) { struct backlight_device *bd = data; put_device(&bd->dev); } /** * devm_of_find_backlight - find backlight for a device * @dev: the device * * This function looks for a property named 'backlight' on the DT node * connected to @dev and looks up the backlight device. The lookup is * device managed so the reference to the backlight device is automatically * dropped on driver detach. * * RETURNS: * * A pointer to the backlight device if found. * Error pointer -EPROBE_DEFER if the DT property is set, but no backlight * device is found. NULL if there's no backlight property. */ struct backlight_device *devm_of_find_backlight(struct device *dev) { struct backlight_device *bd; int ret; bd = of_find_backlight(dev); if (IS_ERR_OR_NULL(bd)) return bd; ret = devm_add_action_or_reset(dev, devm_backlight_release, bd); if (ret) return ERR_PTR(ret); return bd; } EXPORT_SYMBOL(devm_of_find_backlight); static void __exit backlight_class_exit(void) { class_destroy(backlight_class); } static int __init backlight_class_init(void) { backlight_class = class_create("backlight"); if (IS_ERR(backlight_class)) { pr_warn("Unable to create backlight class; errno = %ld\n", PTR_ERR(backlight_class)); return PTR_ERR(backlight_class); } backlight_class->dev_groups = bl_device_groups; backlight_class->pm = &backlight_class_dev_pm_ops; INIT_LIST_HEAD(&backlight_dev_list); mutex_init(&backlight_dev_list_mutex); BLOCKING_INIT_NOTIFIER_HEAD(&backlight_notifier); return 0; } /* * if this is compiled into the kernel, we need to ensure that the * class is registered before users of the class try to register lcd's */ postcore_initcall(backlight_class_init); module_exit(backlight_class_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Jamey Hicks <[email protected]>, Andrew Zabolotny <[email protected]>"); MODULE_DESCRIPTION("Backlight Lowlevel Control Abstraction");
linux-master
drivers/video/backlight/backlight.c
// SPDX-License-Identifier: GPL-2.0-only /* * tps65217_bl.c * * TPS65217 backlight driver * * Copyright (C) 2012 Matthias Kaehlcke * Author: Matthias Kaehlcke <[email protected]> */ #include <linux/kernel.h> #include <linux/backlight.h> #include <linux/err.h> #include <linux/fb.h> #include <linux/mfd/tps65217.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/slab.h> struct tps65217_bl { struct tps65217 *tps; struct device *dev; struct backlight_device *bl; bool is_enabled; }; static int tps65217_bl_enable(struct tps65217_bl *tps65217_bl) { int rc; rc = tps65217_set_bits(tps65217_bl->tps, TPS65217_REG_WLEDCTRL1, TPS65217_WLEDCTRL1_ISINK_ENABLE, TPS65217_WLEDCTRL1_ISINK_ENABLE, TPS65217_PROTECT_NONE); if (rc) { dev_err(tps65217_bl->dev, "failed to enable backlight: %d\n", rc); return rc; } tps65217_bl->is_enabled = true; dev_dbg(tps65217_bl->dev, "backlight enabled\n"); return 0; } static int tps65217_bl_disable(struct tps65217_bl *tps65217_bl) { int rc; rc = tps65217_clear_bits(tps65217_bl->tps, TPS65217_REG_WLEDCTRL1, TPS65217_WLEDCTRL1_ISINK_ENABLE, TPS65217_PROTECT_NONE); if (rc) { dev_err(tps65217_bl->dev, "failed to disable backlight: %d\n", rc); return rc; } tps65217_bl->is_enabled = false; dev_dbg(tps65217_bl->dev, "backlight disabled\n"); return 0; } static int tps65217_bl_update_status(struct backlight_device *bl) { struct tps65217_bl *tps65217_bl = bl_get_data(bl); int rc; int brightness = backlight_get_brightness(bl); if (brightness > 0) { rc = tps65217_reg_write(tps65217_bl->tps, TPS65217_REG_WLEDCTRL2, brightness - 1, TPS65217_PROTECT_NONE); if (rc) { dev_err(tps65217_bl->dev, "failed to set brightness level: %d\n", rc); return rc; } dev_dbg(tps65217_bl->dev, "brightness set to %d\n", brightness); if (!tps65217_bl->is_enabled) rc = tps65217_bl_enable(tps65217_bl); } else { rc = tps65217_bl_disable(tps65217_bl); } return rc; } static const struct backlight_ops tps65217_bl_ops = { .options = BL_CORE_SUSPENDRESUME, .update_status = tps65217_bl_update_status, }; static int tps65217_bl_hw_init(struct tps65217_bl *tps65217_bl, struct tps65217_bl_pdata *pdata) { int rc; rc = tps65217_bl_disable(tps65217_bl); if (rc) return rc; switch (pdata->isel) { case TPS65217_BL_ISET1: /* select ISET_1 current level */ rc = tps65217_clear_bits(tps65217_bl->tps, TPS65217_REG_WLEDCTRL1, TPS65217_WLEDCTRL1_ISEL, TPS65217_PROTECT_NONE); if (rc) { dev_err(tps65217_bl->dev, "failed to select ISET1 current level: %d)\n", rc); return rc; } dev_dbg(tps65217_bl->dev, "selected ISET1 current level\n"); break; case TPS65217_BL_ISET2: /* select ISET2 current level */ rc = tps65217_set_bits(tps65217_bl->tps, TPS65217_REG_WLEDCTRL1, TPS65217_WLEDCTRL1_ISEL, TPS65217_WLEDCTRL1_ISEL, TPS65217_PROTECT_NONE); if (rc) { dev_err(tps65217_bl->dev, "failed to select ISET2 current level: %d\n", rc); return rc; } dev_dbg(tps65217_bl->dev, "selected ISET2 current level\n"); break; default: dev_err(tps65217_bl->dev, "invalid value for current level: %d\n", pdata->isel); return -EINVAL; } /* set PWM frequency */ rc = tps65217_set_bits(tps65217_bl->tps, TPS65217_REG_WLEDCTRL1, TPS65217_WLEDCTRL1_FDIM_MASK, pdata->fdim, TPS65217_PROTECT_NONE); if (rc) { dev_err(tps65217_bl->dev, "failed to select PWM dimming frequency: %d\n", rc); return rc; } return 0; } #ifdef CONFIG_OF static struct tps65217_bl_pdata * tps65217_bl_parse_dt(struct platform_device *pdev) { struct tps65217 *tps = dev_get_drvdata(pdev->dev.parent); struct device_node *node; struct tps65217_bl_pdata *pdata, *err; u32 val; node = of_get_child_by_name(tps->dev->of_node, "backlight"); if (!node) return ERR_PTR(-ENODEV); pdata = devm_kzalloc(&pdev->dev, sizeof(*pdata), GFP_KERNEL); if (!pdata) { err = ERR_PTR(-ENOMEM); goto err; } pdata->isel = TPS65217_BL_ISET1; if (!of_property_read_u32(node, "isel", &val)) { if (val < TPS65217_BL_ISET1 || val > TPS65217_BL_ISET2) { dev_err(&pdev->dev, "invalid 'isel' value in the device tree\n"); err = ERR_PTR(-EINVAL); goto err; } pdata->isel = val; } pdata->fdim = TPS65217_BL_FDIM_200HZ; if (!of_property_read_u32(node, "fdim", &val)) { switch (val) { case 100: pdata->fdim = TPS65217_BL_FDIM_100HZ; break; case 200: pdata->fdim = TPS65217_BL_FDIM_200HZ; break; case 500: pdata->fdim = TPS65217_BL_FDIM_500HZ; break; case 1000: pdata->fdim = TPS65217_BL_FDIM_1000HZ; break; default: dev_err(&pdev->dev, "invalid 'fdim' value in the device tree\n"); err = ERR_PTR(-EINVAL); goto err; } } if (!of_property_read_u32(node, "default-brightness", &val)) { if (val > 100) { dev_err(&pdev->dev, "invalid 'default-brightness' value in the device tree\n"); err = ERR_PTR(-EINVAL); goto err; } pdata->dft_brightness = val; } of_node_put(node); return pdata; err: of_node_put(node); return err; } #else static struct tps65217_bl_pdata * tps65217_bl_parse_dt(struct platform_device *pdev) { return NULL; } #endif static int tps65217_bl_probe(struct platform_device *pdev) { int rc; struct tps65217 *tps = dev_get_drvdata(pdev->dev.parent); struct tps65217_bl *tps65217_bl; struct tps65217_bl_pdata *pdata; struct backlight_properties bl_props; pdata = tps65217_bl_parse_dt(pdev); if (IS_ERR(pdata)) return PTR_ERR(pdata); tps65217_bl = devm_kzalloc(&pdev->dev, sizeof(*tps65217_bl), GFP_KERNEL); if (tps65217_bl == NULL) return -ENOMEM; tps65217_bl->tps = tps; tps65217_bl->dev = &pdev->dev; tps65217_bl->is_enabled = false; rc = tps65217_bl_hw_init(tps65217_bl, pdata); if (rc) return rc; memset(&bl_props, 0, sizeof(struct backlight_properties)); bl_props.type = BACKLIGHT_RAW; bl_props.max_brightness = 100; tps65217_bl->bl = devm_backlight_device_register(&pdev->dev, pdev->name, tps65217_bl->dev, tps65217_bl, &tps65217_bl_ops, &bl_props); if (IS_ERR(tps65217_bl->bl)) { dev_err(tps65217_bl->dev, "registration of backlight device failed: %d\n", rc); return PTR_ERR(tps65217_bl->bl); } tps65217_bl->bl->props.brightness = pdata->dft_brightness; backlight_update_status(tps65217_bl->bl); platform_set_drvdata(pdev, tps65217_bl); return 0; } #ifdef CONFIG_OF static const struct of_device_id tps65217_bl_of_match[] = { { .compatible = "ti,tps65217-bl", }, { /* sentinel */ }, }; MODULE_DEVICE_TABLE(of, tps65217_bl_of_match); #endif static struct platform_driver tps65217_bl_driver = { .probe = tps65217_bl_probe, .driver = { .name = "tps65217-bl", .of_match_table = of_match_ptr(tps65217_bl_of_match), }, }; module_platform_driver(tps65217_bl_driver); MODULE_DESCRIPTION("TPS65217 Backlight driver"); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Matthias Kaehlcke <[email protected]>");
linux-master
drivers/video/backlight/tps65217_bl.c
// SPDX-License-Identifier: GPL-2.0+ /* * LCD Backlight driver for RAVE SP * * Copyright (C) 2018 Zodiac Inflight Innovations * */ #include <linux/backlight.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/mfd/rave-sp.h> #include <linux/platform_device.h> #define RAVE_SP_BACKLIGHT_LCD_EN BIT(7) static int rave_sp_backlight_update_status(struct backlight_device *bd) { const struct backlight_properties *p = &bd->props; const u8 intensity = (p->power == FB_BLANK_UNBLANK) ? p->brightness : 0; struct rave_sp *sp = dev_get_drvdata(&bd->dev); u8 cmd[] = { [0] = RAVE_SP_CMD_SET_BACKLIGHT, [1] = 0, [2] = intensity ? RAVE_SP_BACKLIGHT_LCD_EN | intensity : 0, [3] = 0, [4] = 0, }; return rave_sp_exec(sp, cmd, sizeof(cmd), NULL, 0); } static const struct backlight_ops rave_sp_backlight_ops = { .options = BL_CORE_SUSPENDRESUME, .update_status = rave_sp_backlight_update_status, }; static struct backlight_properties rave_sp_backlight_props = { .type = BACKLIGHT_PLATFORM, .max_brightness = 100, .brightness = 50, }; static int rave_sp_backlight_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct backlight_device *bd; bd = devm_backlight_device_register(dev, pdev->name, dev, dev_get_drvdata(dev->parent), &rave_sp_backlight_ops, &rave_sp_backlight_props); if (IS_ERR(bd)) return PTR_ERR(bd); /* * If there is a phandle pointing to the device node we can * assume that another device will manage the status changes. * If not we make sure the backlight is in a consistent state. */ if (!dev->of_node->phandle) backlight_update_status(bd); return 0; } static const struct of_device_id rave_sp_backlight_of_match[] = { { .compatible = "zii,rave-sp-backlight" }, {} }; static struct platform_driver rave_sp_backlight_driver = { .probe = rave_sp_backlight_probe, .driver = { .name = KBUILD_MODNAME, .of_match_table = rave_sp_backlight_of_match, }, }; module_platform_driver(rave_sp_backlight_driver); MODULE_DEVICE_TABLE(of, rave_sp_backlight_of_match); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Andrey Vostrikov <[email protected]>"); MODULE_AUTHOR("Nikita Yushchenko <[email protected]>"); MODULE_AUTHOR("Andrey Smirnov <[email protected]>"); MODULE_DESCRIPTION("RAVE SP Backlight driver");
linux-master
drivers/video/backlight/rave-sp-backlight.c
// SPDX-License-Identifier: GPL-2.0-only /* * Backlight driver for Wolfson Microelectronics WM831x PMICs * * Copyright 2009 Wolfson Microelectonics plc */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/module.h> #include <linux/fb.h> #include <linux/backlight.h> #include <linux/slab.h> #include <linux/mfd/wm831x/core.h> #include <linux/mfd/wm831x/pdata.h> #include <linux/mfd/wm831x/regulator.h> struct wm831x_backlight_data { struct wm831x *wm831x; int isink_reg; int current_brightness; }; static int wm831x_backlight_set(struct backlight_device *bl, int brightness) { struct wm831x_backlight_data *data = bl_get_data(bl); struct wm831x *wm831x = data->wm831x; int power_up = !data->current_brightness && brightness; int power_down = data->current_brightness && !brightness; int ret; if (power_up) { /* Enable the ISINK */ ret = wm831x_set_bits(wm831x, data->isink_reg, WM831X_CS1_ENA, WM831X_CS1_ENA); if (ret < 0) goto err; /* Enable the DC-DC */ ret = wm831x_set_bits(wm831x, WM831X_DCDC_ENABLE, WM831X_DC4_ENA, WM831X_DC4_ENA); if (ret < 0) goto err; } if (power_down) { /* DCDC first */ ret = wm831x_set_bits(wm831x, WM831X_DCDC_ENABLE, WM831X_DC4_ENA, 0); if (ret < 0) goto err; /* ISINK */ ret = wm831x_set_bits(wm831x, data->isink_reg, WM831X_CS1_DRIVE | WM831X_CS1_ENA, 0); if (ret < 0) goto err; } /* Set the new brightness */ ret = wm831x_set_bits(wm831x, data->isink_reg, WM831X_CS1_ISEL_MASK, brightness); if (ret < 0) goto err; if (power_up) { /* Drive current through the ISINK */ ret = wm831x_set_bits(wm831x, data->isink_reg, WM831X_CS1_DRIVE, WM831X_CS1_DRIVE); if (ret < 0) return ret; } data->current_brightness = brightness; return 0; err: /* If we were in the middle of a power transition always shut down * for safety. */ if (power_up || power_down) { wm831x_set_bits(wm831x, WM831X_DCDC_ENABLE, WM831X_DC4_ENA, 0); wm831x_set_bits(wm831x, data->isink_reg, WM831X_CS1_ENA, 0); } return ret; } static int wm831x_backlight_update_status(struct backlight_device *bl) { return wm831x_backlight_set(bl, backlight_get_brightness(bl)); } static int wm831x_backlight_get_brightness(struct backlight_device *bl) { struct wm831x_backlight_data *data = bl_get_data(bl); return data->current_brightness; } static const struct backlight_ops wm831x_backlight_ops = { .options = BL_CORE_SUSPENDRESUME, .update_status = wm831x_backlight_update_status, .get_brightness = wm831x_backlight_get_brightness, }; static int wm831x_backlight_probe(struct platform_device *pdev) { struct wm831x *wm831x = dev_get_drvdata(pdev->dev.parent); struct wm831x_pdata *wm831x_pdata = dev_get_platdata(pdev->dev.parent); struct wm831x_backlight_pdata *pdata; struct wm831x_backlight_data *data; struct backlight_device *bl; struct backlight_properties props; int ret, i, max_isel, isink_reg, dcdc_cfg; /* We need platform data */ if (wm831x_pdata) pdata = wm831x_pdata->backlight; else pdata = NULL; if (!pdata) { dev_err(&pdev->dev, "No platform data supplied\n"); return -EINVAL; } /* Figure out the maximum current we can use */ for (i = 0; i < WM831X_ISINK_MAX_ISEL; i++) { if (wm831x_isinkv_values[i] > pdata->max_uA) break; } if (i == 0) { dev_err(&pdev->dev, "Invalid max_uA: %duA\n", pdata->max_uA); return -EINVAL; } max_isel = i - 1; if (pdata->max_uA != wm831x_isinkv_values[max_isel]) dev_warn(&pdev->dev, "Maximum current is %duA not %duA as requested\n", wm831x_isinkv_values[max_isel], pdata->max_uA); switch (pdata->isink) { case 1: isink_reg = WM831X_CURRENT_SINK_1; dcdc_cfg = 0; break; case 2: isink_reg = WM831X_CURRENT_SINK_2; dcdc_cfg = WM831X_DC4_FBSRC; break; default: dev_err(&pdev->dev, "Invalid ISINK %d\n", pdata->isink); return -EINVAL; } /* Configure the ISINK to use for feedback */ ret = wm831x_reg_unlock(wm831x); if (ret < 0) return ret; ret = wm831x_set_bits(wm831x, WM831X_DC4_CONTROL, WM831X_DC4_FBSRC, dcdc_cfg); wm831x_reg_lock(wm831x); if (ret < 0) return ret; data = devm_kzalloc(&pdev->dev, sizeof(*data), GFP_KERNEL); if (data == NULL) return -ENOMEM; data->wm831x = wm831x; data->current_brightness = 0; data->isink_reg = isink_reg; memset(&props, 0, sizeof(props)); props.type = BACKLIGHT_RAW; props.max_brightness = max_isel; bl = devm_backlight_device_register(&pdev->dev, "wm831x", &pdev->dev, data, &wm831x_backlight_ops, &props); if (IS_ERR(bl)) { dev_err(&pdev->dev, "failed to register backlight\n"); return PTR_ERR(bl); } bl->props.brightness = max_isel; platform_set_drvdata(pdev, bl); /* Disable the DCDC if it was started so we can bootstrap */ wm831x_set_bits(wm831x, WM831X_DCDC_ENABLE, WM831X_DC4_ENA, 0); backlight_update_status(bl); return 0; } static struct platform_driver wm831x_backlight_driver = { .driver = { .name = "wm831x-backlight", }, .probe = wm831x_backlight_probe, }; module_platform_driver(wm831x_backlight_driver); MODULE_DESCRIPTION("Backlight Driver for WM831x PMICs"); MODULE_AUTHOR("Mark Brown <[email protected]"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:wm831x-backlight");
linux-master
drivers/video/backlight/wm831x_bl.c
/* * Backlight Driver for HP Jornada 680 * * Copyright (c) 2005 Andriy Skulysh * * Based on Sharp's Corgi Backlight Driver * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/spinlock.h> #include <linux/fb.h> #include <linux/backlight.h> #include <cpu/dac.h> #include <mach/hp6xx.h> #include <asm/hd64461.h> #define HP680_MAX_INTENSITY 255 #define HP680_DEFAULT_INTENSITY 10 static int hp680bl_suspended; static int current_intensity; static DEFINE_SPINLOCK(bl_lock); static void hp680bl_send_intensity(struct backlight_device *bd) { unsigned long flags; u16 v; int intensity = backlight_get_brightness(bd); if (hp680bl_suspended) intensity = 0; spin_lock_irqsave(&bl_lock, flags); if (intensity && current_intensity == 0) { sh_dac_enable(DAC_LCD_BRIGHTNESS); v = inw(HD64461_GPBDR); v &= ~HD64461_GPBDR_LCDOFF; outw(v, HD64461_GPBDR); sh_dac_output(255-(u8)intensity, DAC_LCD_BRIGHTNESS); } else if (intensity == 0 && current_intensity != 0) { sh_dac_output(255-(u8)intensity, DAC_LCD_BRIGHTNESS); sh_dac_disable(DAC_LCD_BRIGHTNESS); v = inw(HD64461_GPBDR); v |= HD64461_GPBDR_LCDOFF; outw(v, HD64461_GPBDR); } else if (intensity) { sh_dac_output(255-(u8)intensity, DAC_LCD_BRIGHTNESS); } spin_unlock_irqrestore(&bl_lock, flags); current_intensity = intensity; } #ifdef CONFIG_PM_SLEEP static int hp680bl_suspend(struct device *dev) { struct backlight_device *bd = dev_get_drvdata(dev); hp680bl_suspended = 1; hp680bl_send_intensity(bd); return 0; } static int hp680bl_resume(struct device *dev) { struct backlight_device *bd = dev_get_drvdata(dev); hp680bl_suspended = 0; hp680bl_send_intensity(bd); return 0; } #endif static SIMPLE_DEV_PM_OPS(hp680bl_pm_ops, hp680bl_suspend, hp680bl_resume); static int hp680bl_set_intensity(struct backlight_device *bd) { hp680bl_send_intensity(bd); return 0; } static int hp680bl_get_intensity(struct backlight_device *bd) { return current_intensity; } static const struct backlight_ops hp680bl_ops = { .get_brightness = hp680bl_get_intensity, .update_status = hp680bl_set_intensity, }; static int hp680bl_probe(struct platform_device *pdev) { struct backlight_properties props; struct backlight_device *bd; memset(&props, 0, sizeof(struct backlight_properties)); props.type = BACKLIGHT_RAW; props.max_brightness = HP680_MAX_INTENSITY; bd = devm_backlight_device_register(&pdev->dev, "hp680-bl", &pdev->dev, NULL, &hp680bl_ops, &props); if (IS_ERR(bd)) return PTR_ERR(bd); platform_set_drvdata(pdev, bd); bd->props.brightness = HP680_DEFAULT_INTENSITY; hp680bl_send_intensity(bd); return 0; } static void hp680bl_remove(struct platform_device *pdev) { struct backlight_device *bd = platform_get_drvdata(pdev); bd->props.brightness = 0; bd->props.power = 0; hp680bl_send_intensity(bd); } static struct platform_driver hp680bl_driver = { .probe = hp680bl_probe, .remove_new = hp680bl_remove, .driver = { .name = "hp680-bl", .pm = &hp680bl_pm_ops, }, }; static struct platform_device *hp680bl_device; static int __init hp680bl_init(void) { int ret; ret = platform_driver_register(&hp680bl_driver); if (ret) return ret; hp680bl_device = platform_device_register_simple("hp680-bl", -1, NULL, 0); if (IS_ERR(hp680bl_device)) { platform_driver_unregister(&hp680bl_driver); return PTR_ERR(hp680bl_device); } return 0; } static void __exit hp680bl_exit(void) { platform_device_unregister(hp680bl_device); platform_driver_unregister(&hp680bl_driver); } module_init(hp680bl_init); module_exit(hp680bl_exit); MODULE_AUTHOR("Andriy Skulysh <[email protected]>"); MODULE_DESCRIPTION("HP Jornada 680 Backlight Driver"); MODULE_LICENSE("GPL");
linux-master
drivers/video/backlight/hp680_bl.c
// SPDX-License-Identifier: GPL-2.0-only /* * linux/drivers/video/backlight/aat2870_bl.c * * Copyright (c) 2011, NVIDIA Corporation. * Author: Jin Park <[email protected]> */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/mutex.h> #include <linux/delay.h> #include <linux/fb.h> #include <linux/backlight.h> #include <linux/mfd/aat2870.h> struct aat2870_bl_driver_data { struct platform_device *pdev; struct backlight_device *bd; int channels; int max_current; int brightness; /* current brightness */ }; static inline int aat2870_brightness(struct aat2870_bl_driver_data *aat2870_bl, int brightness) { struct backlight_device *bd = aat2870_bl->bd; int val; val = brightness * (aat2870_bl->max_current - 1); val /= bd->props.max_brightness; return val; } static inline int aat2870_bl_enable(struct aat2870_bl_driver_data *aat2870_bl) { struct aat2870_data *aat2870 = dev_get_drvdata(aat2870_bl->pdev->dev.parent); return aat2870->write(aat2870, AAT2870_BL_CH_EN, (u8)aat2870_bl->channels); } static inline int aat2870_bl_disable(struct aat2870_bl_driver_data *aat2870_bl) { struct aat2870_data *aat2870 = dev_get_drvdata(aat2870_bl->pdev->dev.parent); return aat2870->write(aat2870, AAT2870_BL_CH_EN, 0x0); } static int aat2870_bl_update_status(struct backlight_device *bd) { struct aat2870_bl_driver_data *aat2870_bl = bl_get_data(bd); struct aat2870_data *aat2870 = dev_get_drvdata(aat2870_bl->pdev->dev.parent); int brightness = backlight_get_brightness(bd); int ret; if ((brightness < 0) || (bd->props.max_brightness < brightness)) { dev_err(&bd->dev, "invalid brightness, %d\n", brightness); return -EINVAL; } dev_dbg(&bd->dev, "brightness=%d, power=%d, state=%d\n", bd->props.brightness, bd->props.power, bd->props.state); ret = aat2870->write(aat2870, AAT2870_BLM, (u8)aat2870_brightness(aat2870_bl, brightness)); if (ret < 0) return ret; if (brightness == 0) { ret = aat2870_bl_disable(aat2870_bl); if (ret < 0) return ret; } else if (aat2870_bl->brightness == 0) { ret = aat2870_bl_enable(aat2870_bl); if (ret < 0) return ret; } aat2870_bl->brightness = brightness; return 0; } static int aat2870_bl_check_fb(struct backlight_device *bd, struct fb_info *fi) { return 1; } static const struct backlight_ops aat2870_bl_ops = { .options = BL_CORE_SUSPENDRESUME, .update_status = aat2870_bl_update_status, .check_fb = aat2870_bl_check_fb, }; static int aat2870_bl_probe(struct platform_device *pdev) { struct aat2870_bl_platform_data *pdata = dev_get_platdata(&pdev->dev); struct aat2870_bl_driver_data *aat2870_bl; struct backlight_device *bd; struct backlight_properties props; int ret = 0; if (!pdata) { dev_err(&pdev->dev, "No platform data\n"); ret = -ENXIO; goto out; } if (pdev->id != AAT2870_ID_BL) { dev_err(&pdev->dev, "Invalid device ID, %d\n", pdev->id); ret = -EINVAL; goto out; } aat2870_bl = devm_kzalloc(&pdev->dev, sizeof(struct aat2870_bl_driver_data), GFP_KERNEL); if (!aat2870_bl) { ret = -ENOMEM; goto out; } memset(&props, 0, sizeof(struct backlight_properties)); props.type = BACKLIGHT_RAW; bd = devm_backlight_device_register(&pdev->dev, "aat2870-backlight", &pdev->dev, aat2870_bl, &aat2870_bl_ops, &props); if (IS_ERR(bd)) { dev_err(&pdev->dev, "Failed allocate memory for backlight device\n"); ret = PTR_ERR(bd); goto out; } aat2870_bl->pdev = pdev; platform_set_drvdata(pdev, aat2870_bl); aat2870_bl->bd = bd; if (pdata->channels > 0) aat2870_bl->channels = pdata->channels; else aat2870_bl->channels = AAT2870_BL_CH_ALL; if (pdata->max_current > 0) aat2870_bl->max_current = pdata->max_current; else aat2870_bl->max_current = AAT2870_CURRENT_27_9; if (pdata->max_brightness > 0) bd->props.max_brightness = pdata->max_brightness; else bd->props.max_brightness = 255; aat2870_bl->brightness = 0; bd->props.power = FB_BLANK_UNBLANK; bd->props.brightness = bd->props.max_brightness; ret = aat2870_bl_update_status(bd); if (ret < 0) { dev_err(&pdev->dev, "Failed to initialize\n"); return ret; } return 0; out: return ret; } static void aat2870_bl_remove(struct platform_device *pdev) { struct aat2870_bl_driver_data *aat2870_bl = platform_get_drvdata(pdev); struct backlight_device *bd = aat2870_bl->bd; bd->props.power = FB_BLANK_POWERDOWN; bd->props.brightness = 0; backlight_update_status(bd); } static struct platform_driver aat2870_bl_driver = { .driver = { .name = "aat2870-backlight", }, .probe = aat2870_bl_probe, .remove_new = aat2870_bl_remove, }; static int __init aat2870_bl_init(void) { return platform_driver_register(&aat2870_bl_driver); } subsys_initcall(aat2870_bl_init); static void __exit aat2870_bl_exit(void) { platform_driver_unregister(&aat2870_bl_driver); } module_exit(aat2870_bl_exit); MODULE_DESCRIPTION("AnalogicTech AAT2870 Backlight"); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Jin Park <[email protected]>");
linux-master
drivers/video/backlight/aat2870_bl.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * (C) Copyright 2008 * Stefano Babic, DENX Software Engineering, [email protected]. * * This driver implements a lcd device for the ILITEK 922x display * controller. The interface to the display is SPI and the display's * memory is cyclically updated over the RGB interface. */ #include <linux/fb.h> #include <linux/delay.h> #include <linux/errno.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/lcd.h> #include <linux/module.h> #include <linux/of.h> #include <linux/slab.h> #include <linux/spi/spi.h> #include <linux/string.h> /* Register offset, see manual section 8.2 */ #define REG_START_OSCILLATION 0x00 #define REG_DRIVER_CODE_READ 0x00 #define REG_DRIVER_OUTPUT_CONTROL 0x01 #define REG_LCD_AC_DRIVEING_CONTROL 0x02 #define REG_ENTRY_MODE 0x03 #define REG_COMPARE_1 0x04 #define REG_COMPARE_2 0x05 #define REG_DISPLAY_CONTROL_1 0x07 #define REG_DISPLAY_CONTROL_2 0x08 #define REG_DISPLAY_CONTROL_3 0x09 #define REG_FRAME_CYCLE_CONTROL 0x0B #define REG_EXT_INTF_CONTROL 0x0C #define REG_POWER_CONTROL_1 0x10 #define REG_POWER_CONTROL_2 0x11 #define REG_POWER_CONTROL_3 0x12 #define REG_POWER_CONTROL_4 0x13 #define REG_RAM_ADDRESS_SET 0x21 #define REG_WRITE_DATA_TO_GRAM 0x22 #define REG_RAM_WRITE_MASK1 0x23 #define REG_RAM_WRITE_MASK2 0x24 #define REG_GAMMA_CONTROL_1 0x30 #define REG_GAMMA_CONTROL_2 0x31 #define REG_GAMMA_CONTROL_3 0x32 #define REG_GAMMA_CONTROL_4 0x33 #define REG_GAMMA_CONTROL_5 0x34 #define REG_GAMMA_CONTROL_6 0x35 #define REG_GAMMA_CONTROL_7 0x36 #define REG_GAMMA_CONTROL_8 0x37 #define REG_GAMMA_CONTROL_9 0x38 #define REG_GAMMA_CONTROL_10 0x39 #define REG_GATE_SCAN_CONTROL 0x40 #define REG_VERT_SCROLL_CONTROL 0x41 #define REG_FIRST_SCREEN_DRIVE_POS 0x42 #define REG_SECOND_SCREEN_DRIVE_POS 0x43 #define REG_RAM_ADDR_POS_H 0x44 #define REG_RAM_ADDR_POS_V 0x45 #define REG_OSCILLATOR_CONTROL 0x4F #define REG_GPIO 0x60 #define REG_OTP_VCM_PROGRAMMING 0x61 #define REG_OTP_VCM_STATUS_ENABLE 0x62 #define REG_OTP_PROGRAMMING_ID_KEY 0x65 /* * maximum frequency for register access * (not for the GRAM access) */ #define ILITEK_MAX_FREQ_REG 4000000 /* * Device ID as found in the datasheet (supports 9221 and 9222) */ #define ILITEK_DEVICE_ID 0x9220 #define ILITEK_DEVICE_ID_MASK 0xFFF0 /* Last two bits in the START BYTE */ #define START_RS_INDEX 0 #define START_RS_REG 1 #define START_RW_WRITE 0 #define START_RW_READ 1 /** * START_BYTE(id, rs, rw) * * Set the start byte according to the required operation. * The start byte is defined as: * ---------------------------------- * | 0 | 1 | 1 | 1 | 0 | ID | RS | RW | * ---------------------------------- * @id: display's id as set by the manufacturer * @rs: operation type bit, one of: * - START_RS_INDEX set the index register * - START_RS_REG write/read registers/GRAM * @rw: read/write operation * - START_RW_WRITE write * - START_RW_READ read */ #define START_BYTE(id, rs, rw) \ (0x70 | (((id) & 0x01) << 2) | (((rs) & 0x01) << 1) | ((rw) & 0x01)) /** * CHECK_FREQ_REG(spi_device s, spi_transfer x) - Check the frequency * for the SPI transfer. According to the datasheet, the controller * accept higher frequency for the GRAM transfer, but it requires * lower frequency when the registers are read/written. * The macro sets the frequency in the spi_transfer structure if * the frequency exceeds the maximum value. * @s: pointer to an SPI device * @x: pointer to the read/write buffer pair */ #define CHECK_FREQ_REG(s, x) \ do { \ if (s->max_speed_hz > ILITEK_MAX_FREQ_REG) \ ((struct spi_transfer *)x)->speed_hz = \ ILITEK_MAX_FREQ_REG; \ } while (0) #define CMD_BUFSIZE 16 #define POWER_IS_ON(pwr) ((pwr) <= FB_BLANK_NORMAL) #define set_tx_byte(b) (tx_invert ? ~(b) : b) /* * ili922x_id - id as set by manufacturer */ static int ili922x_id = 1; module_param(ili922x_id, int, 0); static int tx_invert; module_param(tx_invert, int, 0); /* * driver's private structure */ struct ili922x { struct spi_device *spi; struct lcd_device *ld; int power; }; /** * ili922x_read_status - read status register from display * @spi: spi device * @rs: output value */ static int ili922x_read_status(struct spi_device *spi, u16 *rs) { struct spi_message msg; struct spi_transfer xfer; unsigned char tbuf[CMD_BUFSIZE]; unsigned char rbuf[CMD_BUFSIZE]; int ret, i; memset(&xfer, 0, sizeof(struct spi_transfer)); spi_message_init(&msg); xfer.tx_buf = tbuf; xfer.rx_buf = rbuf; xfer.cs_change = 1; CHECK_FREQ_REG(spi, &xfer); tbuf[0] = set_tx_byte(START_BYTE(ili922x_id, START_RS_INDEX, START_RW_READ)); /* * we need 4-byte xfer here due to invalid dummy byte * received after start byte */ for (i = 1; i < 4; i++) tbuf[i] = set_tx_byte(0); /* dummy */ xfer.bits_per_word = 8; xfer.len = 4; spi_message_add_tail(&xfer, &msg); ret = spi_sync(spi, &msg); if (ret < 0) { dev_dbg(&spi->dev, "Error sending SPI message 0x%x", ret); return ret; } *rs = (rbuf[2] << 8) + rbuf[3]; return 0; } /** * ili922x_read - read register from display * @spi: spi device * @reg: offset of the register to be read * @rx: output value */ static int ili922x_read(struct spi_device *spi, u8 reg, u16 *rx) { struct spi_message msg; struct spi_transfer xfer_regindex, xfer_regvalue; unsigned char tbuf[CMD_BUFSIZE]; unsigned char rbuf[CMD_BUFSIZE]; int ret, len = 0, send_bytes; memset(&xfer_regindex, 0, sizeof(struct spi_transfer)); memset(&xfer_regvalue, 0, sizeof(struct spi_transfer)); spi_message_init(&msg); xfer_regindex.tx_buf = tbuf; xfer_regindex.rx_buf = rbuf; xfer_regindex.cs_change = 1; CHECK_FREQ_REG(spi, &xfer_regindex); tbuf[0] = set_tx_byte(START_BYTE(ili922x_id, START_RS_INDEX, START_RW_WRITE)); tbuf[1] = set_tx_byte(0); tbuf[2] = set_tx_byte(reg); xfer_regindex.bits_per_word = 8; len = xfer_regindex.len = 3; spi_message_add_tail(&xfer_regindex, &msg); send_bytes = len; tbuf[len++] = set_tx_byte(START_BYTE(ili922x_id, START_RS_REG, START_RW_READ)); tbuf[len++] = set_tx_byte(0); tbuf[len] = set_tx_byte(0); xfer_regvalue.cs_change = 1; xfer_regvalue.len = 3; xfer_regvalue.tx_buf = &tbuf[send_bytes]; xfer_regvalue.rx_buf = &rbuf[send_bytes]; CHECK_FREQ_REG(spi, &xfer_regvalue); spi_message_add_tail(&xfer_regvalue, &msg); ret = spi_sync(spi, &msg); if (ret < 0) { dev_dbg(&spi->dev, "Error sending SPI message 0x%x", ret); return ret; } *rx = (rbuf[1 + send_bytes] << 8) + rbuf[2 + send_bytes]; return 0; } /** * ili922x_write - write a controller register * @spi: struct spi_device * * @reg: offset of the register to be written * @value: value to be written */ static int ili922x_write(struct spi_device *spi, u8 reg, u16 value) { struct spi_message msg; struct spi_transfer xfer_regindex, xfer_regvalue; unsigned char tbuf[CMD_BUFSIZE]; unsigned char rbuf[CMD_BUFSIZE]; int ret; memset(&xfer_regindex, 0, sizeof(struct spi_transfer)); memset(&xfer_regvalue, 0, sizeof(struct spi_transfer)); spi_message_init(&msg); xfer_regindex.tx_buf = tbuf; xfer_regindex.rx_buf = rbuf; xfer_regindex.cs_change = 1; CHECK_FREQ_REG(spi, &xfer_regindex); tbuf[0] = set_tx_byte(START_BYTE(ili922x_id, START_RS_INDEX, START_RW_WRITE)); tbuf[1] = set_tx_byte(0); tbuf[2] = set_tx_byte(reg); xfer_regindex.bits_per_word = 8; xfer_regindex.len = 3; spi_message_add_tail(&xfer_regindex, &msg); ret = spi_sync(spi, &msg); spi_message_init(&msg); tbuf[0] = set_tx_byte(START_BYTE(ili922x_id, START_RS_REG, START_RW_WRITE)); tbuf[1] = set_tx_byte((value & 0xFF00) >> 8); tbuf[2] = set_tx_byte(value & 0x00FF); xfer_regvalue.cs_change = 1; xfer_regvalue.len = 3; xfer_regvalue.tx_buf = tbuf; xfer_regvalue.rx_buf = rbuf; CHECK_FREQ_REG(spi, &xfer_regvalue); spi_message_add_tail(&xfer_regvalue, &msg); ret = spi_sync(spi, &msg); if (ret < 0) { dev_err(&spi->dev, "Error sending SPI message 0x%x", ret); return ret; } return 0; } #ifdef DEBUG /** * ili922x_reg_dump - dump all registers * * @spi: pointer to an SPI device */ static void ili922x_reg_dump(struct spi_device *spi) { u8 reg; u16 rx; dev_dbg(&spi->dev, "ILI922x configuration registers:\n"); for (reg = REG_START_OSCILLATION; reg <= REG_OTP_PROGRAMMING_ID_KEY; reg++) { ili922x_read(spi, reg, &rx); dev_dbg(&spi->dev, "reg @ 0x%02X: 0x%04X\n", reg, rx); } } #else static inline void ili922x_reg_dump(struct spi_device *spi) {} #endif /** * set_write_to_gram_reg - initialize the display to write the GRAM * @spi: spi device */ static void set_write_to_gram_reg(struct spi_device *spi) { struct spi_message msg; struct spi_transfer xfer; unsigned char tbuf[CMD_BUFSIZE]; memset(&xfer, 0, sizeof(struct spi_transfer)); spi_message_init(&msg); xfer.tx_buf = tbuf; xfer.rx_buf = NULL; xfer.cs_change = 1; tbuf[0] = START_BYTE(ili922x_id, START_RS_INDEX, START_RW_WRITE); tbuf[1] = 0; tbuf[2] = REG_WRITE_DATA_TO_GRAM; xfer.bits_per_word = 8; xfer.len = 3; spi_message_add_tail(&xfer, &msg); spi_sync(spi, &msg); } /** * ili922x_poweron - turn the display on * @spi: spi device * * The sequence to turn on the display is taken from * the datasheet and/or the example code provided by the * manufacturer. */ static int ili922x_poweron(struct spi_device *spi) { int ret; /* Power on */ ret = ili922x_write(spi, REG_POWER_CONTROL_1, 0x0000); usleep_range(10000, 10500); ret += ili922x_write(spi, REG_POWER_CONTROL_2, 0x0000); ret += ili922x_write(spi, REG_POWER_CONTROL_3, 0x0000); msleep(40); ret += ili922x_write(spi, REG_POWER_CONTROL_4, 0x0000); msleep(40); /* register 0x56 is not documented in the datasheet */ ret += ili922x_write(spi, 0x56, 0x080F); ret += ili922x_write(spi, REG_POWER_CONTROL_1, 0x4240); usleep_range(10000, 10500); ret += ili922x_write(spi, REG_POWER_CONTROL_2, 0x0000); ret += ili922x_write(spi, REG_POWER_CONTROL_3, 0x0014); msleep(40); ret += ili922x_write(spi, REG_POWER_CONTROL_4, 0x1319); msleep(40); return ret; } /** * ili922x_poweroff - turn the display off * @spi: spi device */ static int ili922x_poweroff(struct spi_device *spi) { int ret; /* Power off */ ret = ili922x_write(spi, REG_POWER_CONTROL_1, 0x0000); usleep_range(10000, 10500); ret += ili922x_write(spi, REG_POWER_CONTROL_2, 0x0000); ret += ili922x_write(spi, REG_POWER_CONTROL_3, 0x0000); msleep(40); ret += ili922x_write(spi, REG_POWER_CONTROL_4, 0x0000); msleep(40); return ret; } /** * ili922x_display_init - initialize the display by setting * the configuration registers * @spi: spi device */ static void ili922x_display_init(struct spi_device *spi) { ili922x_write(spi, REG_START_OSCILLATION, 1); usleep_range(10000, 10500); ili922x_write(spi, REG_DRIVER_OUTPUT_CONTROL, 0x691B); ili922x_write(spi, REG_LCD_AC_DRIVEING_CONTROL, 0x0700); ili922x_write(spi, REG_ENTRY_MODE, 0x1030); ili922x_write(spi, REG_COMPARE_1, 0x0000); ili922x_write(spi, REG_COMPARE_2, 0x0000); ili922x_write(spi, REG_DISPLAY_CONTROL_1, 0x0037); ili922x_write(spi, REG_DISPLAY_CONTROL_2, 0x0202); ili922x_write(spi, REG_DISPLAY_CONTROL_3, 0x0000); ili922x_write(spi, REG_FRAME_CYCLE_CONTROL, 0x0000); /* Set RGB interface */ ili922x_write(spi, REG_EXT_INTF_CONTROL, 0x0110); ili922x_poweron(spi); ili922x_write(spi, REG_GAMMA_CONTROL_1, 0x0302); ili922x_write(spi, REG_GAMMA_CONTROL_2, 0x0407); ili922x_write(spi, REG_GAMMA_CONTROL_3, 0x0304); ili922x_write(spi, REG_GAMMA_CONTROL_4, 0x0203); ili922x_write(spi, REG_GAMMA_CONTROL_5, 0x0706); ili922x_write(spi, REG_GAMMA_CONTROL_6, 0x0407); ili922x_write(spi, REG_GAMMA_CONTROL_7, 0x0706); ili922x_write(spi, REG_GAMMA_CONTROL_8, 0x0000); ili922x_write(spi, REG_GAMMA_CONTROL_9, 0x0C06); ili922x_write(spi, REG_GAMMA_CONTROL_10, 0x0F00); ili922x_write(spi, REG_RAM_ADDRESS_SET, 0x0000); ili922x_write(spi, REG_GATE_SCAN_CONTROL, 0x0000); ili922x_write(spi, REG_VERT_SCROLL_CONTROL, 0x0000); ili922x_write(spi, REG_FIRST_SCREEN_DRIVE_POS, 0xDB00); ili922x_write(spi, REG_SECOND_SCREEN_DRIVE_POS, 0xDB00); ili922x_write(spi, REG_RAM_ADDR_POS_H, 0xAF00); ili922x_write(spi, REG_RAM_ADDR_POS_V, 0xDB00); ili922x_reg_dump(spi); set_write_to_gram_reg(spi); } static int ili922x_lcd_power(struct ili922x *lcd, int power) { int ret = 0; if (POWER_IS_ON(power) && !POWER_IS_ON(lcd->power)) ret = ili922x_poweron(lcd->spi); else if (!POWER_IS_ON(power) && POWER_IS_ON(lcd->power)) ret = ili922x_poweroff(lcd->spi); if (!ret) lcd->power = power; return ret; } static int ili922x_set_power(struct lcd_device *ld, int power) { struct ili922x *ili = lcd_get_data(ld); return ili922x_lcd_power(ili, power); } static int ili922x_get_power(struct lcd_device *ld) { struct ili922x *ili = lcd_get_data(ld); return ili->power; } static struct lcd_ops ili922x_ops = { .get_power = ili922x_get_power, .set_power = ili922x_set_power, }; static int ili922x_probe(struct spi_device *spi) { struct ili922x *ili; struct lcd_device *lcd; int ret; u16 reg = 0; ili = devm_kzalloc(&spi->dev, sizeof(*ili), GFP_KERNEL); if (!ili) return -ENOMEM; ili->spi = spi; spi_set_drvdata(spi, ili); /* check if the device is connected */ ret = ili922x_read(spi, REG_DRIVER_CODE_READ, &reg); if (ret || ((reg & ILITEK_DEVICE_ID_MASK) != ILITEK_DEVICE_ID)) { dev_err(&spi->dev, "no LCD found: Chip ID 0x%x, ret %d\n", reg, ret); return -ENODEV; } dev_info(&spi->dev, "ILI%x found, SPI freq %d, mode %d\n", reg, spi->max_speed_hz, spi->mode); ret = ili922x_read_status(spi, &reg); if (ret) { dev_err(&spi->dev, "reading RS failed...\n"); return ret; } dev_dbg(&spi->dev, "status: 0x%x\n", reg); ili922x_display_init(spi); ili->power = FB_BLANK_POWERDOWN; lcd = devm_lcd_device_register(&spi->dev, "ili922xlcd", &spi->dev, ili, &ili922x_ops); if (IS_ERR(lcd)) { dev_err(&spi->dev, "cannot register LCD\n"); return PTR_ERR(lcd); } ili->ld = lcd; spi_set_drvdata(spi, ili); ili922x_lcd_power(ili, FB_BLANK_UNBLANK); return 0; } static void ili922x_remove(struct spi_device *spi) { ili922x_poweroff(spi); } static struct spi_driver ili922x_driver = { .driver = { .name = "ili922x", }, .probe = ili922x_probe, .remove = ili922x_remove, }; module_spi_driver(ili922x_driver); MODULE_AUTHOR("Stefano Babic <[email protected]>"); MODULE_DESCRIPTION("ILI9221/9222 LCD driver"); MODULE_LICENSE("GPL"); MODULE_PARM_DESC(ili922x_id, "set controller identifier (default=1)"); MODULE_PARM_DESC(tx_invert, "invert bytes before sending");
linux-master
drivers/video/backlight/ili922x.c
// SPDX-License-Identifier: GPL-2.0-only /* * ROHM Semiconductor BD6107 LED Driver * * Copyright (C) 2013 Ideas on board SPRL * * Contact: Laurent Pinchart <[email protected]> */ #include <linux/backlight.h> #include <linux/delay.h> #include <linux/err.h> #include <linux/fb.h> #include <linux/gpio/consumer.h> #include <linux/i2c.h> #include <linux/module.h> #include <linux/platform_data/bd6107.h> #include <linux/slab.h> #define BD6107_PSCNT1 0x00 #define BD6107_PSCNT1_PSCNTREG2 (1 << 2) #define BD6107_PSCNT1_PSCNTREG1 (1 << 0) #define BD6107_REGVSET 0x02 #define BD6107_REGVSET_REG1VSET_2_85V (1 << 2) #define BD6107_REGVSET_REG1VSET_2_80V (0 << 2) #define BD6107_LEDCNT1 0x03 #define BD6107_LEDCNT1_LEDONOFF2 (1 << 1) #define BD6107_LEDCNT1_LEDONOFF1 (1 << 0) #define BD6107_PORTSEL 0x04 #define BD6107_PORTSEL_LEDM(n) (1 << (n)) #define BD6107_RGB1CNT1 0x05 #define BD6107_RGB1CNT2 0x06 #define BD6107_RGB1CNT3 0x07 #define BD6107_RGB1CNT4 0x08 #define BD6107_RGB1CNT5 0x09 #define BD6107_RGB1FLM 0x0a #define BD6107_RGB2CNT1 0x0b #define BD6107_RGB2CNT2 0x0c #define BD6107_RGB2CNT3 0x0d #define BD6107_RGB2CNT4 0x0e #define BD6107_RGB2CNT5 0x0f #define BD6107_RGB2FLM 0x10 #define BD6107_PSCONT3 0x11 #define BD6107_SMMONCNT 0x12 #define BD6107_DCDCCNT 0x13 #define BD6107_IOSEL 0x14 #define BD6107_OUT1 0x15 #define BD6107_OUT2 0x16 #define BD6107_MASK1 0x17 #define BD6107_MASK2 0x18 #define BD6107_FACTOR1 0x19 #define BD6107_FACTOR2 0x1a #define BD6107_CLRFACT1 0x1b #define BD6107_CLRFACT2 0x1c #define BD6107_STATE1 0x1d #define BD6107_LSIVER 0x1e #define BD6107_GRPSEL 0x1f #define BD6107_LEDCNT2 0x20 #define BD6107_LEDCNT3 0x21 #define BD6107_MCURRENT 0x22 #define BD6107_MAINCNT1 0x23 #define BD6107_MAINCNT2 0x24 #define BD6107_SLOPECNT 0x25 #define BD6107_MSLOPE 0x26 #define BD6107_RGBSLOPE 0x27 #define BD6107_TEST 0x29 #define BD6107_SFTRST 0x2a #define BD6107_SFTRSTGD 0x2b struct bd6107 { struct i2c_client *client; struct backlight_device *backlight; struct bd6107_platform_data *pdata; struct gpio_desc *reset; }; static int bd6107_write(struct bd6107 *bd, u8 reg, u8 data) { return i2c_smbus_write_byte_data(bd->client, reg, data); } static int bd6107_backlight_update_status(struct backlight_device *backlight) { struct bd6107 *bd = bl_get_data(backlight); int brightness = backlight_get_brightness(backlight); if (brightness) { bd6107_write(bd, BD6107_PORTSEL, BD6107_PORTSEL_LEDM(2) | BD6107_PORTSEL_LEDM(1) | BD6107_PORTSEL_LEDM(0)); bd6107_write(bd, BD6107_MAINCNT1, brightness); bd6107_write(bd, BD6107_LEDCNT1, BD6107_LEDCNT1_LEDONOFF1); } else { /* Assert the reset line (gpiolib will handle active low) */ gpiod_set_value(bd->reset, 1); msleep(24); gpiod_set_value(bd->reset, 0); } return 0; } static int bd6107_backlight_check_fb(struct backlight_device *backlight, struct fb_info *info) { struct bd6107 *bd = bl_get_data(backlight); return !bd->pdata->dev || bd->pdata->dev == info->device; } static const struct backlight_ops bd6107_backlight_ops = { .options = BL_CORE_SUSPENDRESUME, .update_status = bd6107_backlight_update_status, .check_fb = bd6107_backlight_check_fb, }; static int bd6107_probe(struct i2c_client *client) { struct bd6107_platform_data *pdata = dev_get_platdata(&client->dev); struct backlight_device *backlight; struct backlight_properties props; struct bd6107 *bd; int ret; if (pdata == NULL) { dev_err(&client->dev, "No platform data\n"); return -EINVAL; } if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA)) { dev_warn(&client->dev, "I2C adapter doesn't support I2C_FUNC_SMBUS_BYTE\n"); return -EIO; } bd = devm_kzalloc(&client->dev, sizeof(*bd), GFP_KERNEL); if (!bd) return -ENOMEM; bd->client = client; bd->pdata = pdata; /* * Request the reset GPIO line with GPIOD_OUT_HIGH meaning asserted, * so in the machine descriptor table (or other hardware description), * the line should be flagged as active low so this will assert * the reset. */ bd->reset = devm_gpiod_get(&client->dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(bd->reset)) { dev_err(&client->dev, "unable to request reset GPIO\n"); ret = PTR_ERR(bd->reset); return ret; } memset(&props, 0, sizeof(props)); props.type = BACKLIGHT_RAW; props.max_brightness = 128; props.brightness = clamp_t(unsigned int, pdata->def_value, 0, props.max_brightness); backlight = devm_backlight_device_register(&client->dev, dev_name(&client->dev), &bd->client->dev, bd, &bd6107_backlight_ops, &props); if (IS_ERR(backlight)) { dev_err(&client->dev, "failed to register backlight\n"); return PTR_ERR(backlight); } backlight_update_status(backlight); i2c_set_clientdata(client, backlight); return 0; } static void bd6107_remove(struct i2c_client *client) { struct backlight_device *backlight = i2c_get_clientdata(client); backlight->props.brightness = 0; backlight_update_status(backlight); } static const struct i2c_device_id bd6107_ids[] = { { "bd6107", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, bd6107_ids); static struct i2c_driver bd6107_driver = { .driver = { .name = "bd6107", }, .probe = bd6107_probe, .remove = bd6107_remove, .id_table = bd6107_ids, }; module_i2c_driver(bd6107_driver); MODULE_DESCRIPTION("Rohm BD6107 Backlight Driver"); MODULE_AUTHOR("Laurent Pinchart <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/video/backlight/bd6107.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (C) 2009-2010, Lars-Peter Clausen <[email protected]> * PCF50633 backlight device driver */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/platform_device.h> #include <linux/backlight.h> #include <linux/fb.h> #include <linux/mfd/pcf50633/core.h> #include <linux/mfd/pcf50633/backlight.h> struct pcf50633_bl { struct pcf50633 *pcf; struct backlight_device *bl; unsigned int brightness; unsigned int brightness_limit; }; /* * pcf50633_bl_set_brightness_limit * * Update the brightness limit for the pc50633 backlight. The actual brightness * will not go above the limit. This is useful to limit power drain for example * on low battery. * * @dev: Pointer to a pcf50633 device * @limit: The brightness limit. Valid values are 0-63 */ int pcf50633_bl_set_brightness_limit(struct pcf50633 *pcf, unsigned int limit) { struct pcf50633_bl *pcf_bl = platform_get_drvdata(pcf->bl_pdev); if (!pcf_bl) return -ENODEV; pcf_bl->brightness_limit = limit & 0x3f; backlight_update_status(pcf_bl->bl); return 0; } static int pcf50633_bl_update_status(struct backlight_device *bl) { struct pcf50633_bl *pcf_bl = bl_get_data(bl); unsigned int new_brightness; if (bl->props.state & (BL_CORE_SUSPENDED | BL_CORE_FBBLANK) || bl->props.power != FB_BLANK_UNBLANK) new_brightness = 0; else if (bl->props.brightness < pcf_bl->brightness_limit) new_brightness = bl->props.brightness; else new_brightness = pcf_bl->brightness_limit; if (pcf_bl->brightness == new_brightness) return 0; if (new_brightness) { pcf50633_reg_write(pcf_bl->pcf, PCF50633_REG_LEDOUT, new_brightness); if (!pcf_bl->brightness) pcf50633_reg_write(pcf_bl->pcf, PCF50633_REG_LEDENA, 1); } else { pcf50633_reg_write(pcf_bl->pcf, PCF50633_REG_LEDENA, 0); } pcf_bl->brightness = new_brightness; return 0; } static int pcf50633_bl_get_brightness(struct backlight_device *bl) { struct pcf50633_bl *pcf_bl = bl_get_data(bl); return pcf_bl->brightness; } static const struct backlight_ops pcf50633_bl_ops = { .get_brightness = pcf50633_bl_get_brightness, .update_status = pcf50633_bl_update_status, .options = BL_CORE_SUSPENDRESUME, }; static int pcf50633_bl_probe(struct platform_device *pdev) { struct pcf50633_bl *pcf_bl; struct device *parent = pdev->dev.parent; struct pcf50633_platform_data *pcf50633_data = dev_get_platdata(parent); struct pcf50633_bl_platform_data *pdata = pcf50633_data->backlight_data; struct backlight_properties bl_props; pcf_bl = devm_kzalloc(&pdev->dev, sizeof(*pcf_bl), GFP_KERNEL); if (!pcf_bl) return -ENOMEM; memset(&bl_props, 0, sizeof(bl_props)); bl_props.type = BACKLIGHT_RAW; bl_props.max_brightness = 0x3f; bl_props.power = FB_BLANK_UNBLANK; if (pdata) { bl_props.brightness = pdata->default_brightness; pcf_bl->brightness_limit = pdata->default_brightness_limit; } else { bl_props.brightness = 0x3f; pcf_bl->brightness_limit = 0x3f; } pcf_bl->pcf = dev_to_pcf50633(pdev->dev.parent); pcf_bl->bl = devm_backlight_device_register(&pdev->dev, pdev->name, &pdev->dev, pcf_bl, &pcf50633_bl_ops, &bl_props); if (IS_ERR(pcf_bl->bl)) return PTR_ERR(pcf_bl->bl); platform_set_drvdata(pdev, pcf_bl); pcf50633_reg_write(pcf_bl->pcf, PCF50633_REG_LEDDIM, pdata->ramp_time); /* * Should be different from bl_props.brightness, so we do not exit * update_status early the first time it's called */ pcf_bl->brightness = pcf_bl->bl->props.brightness + 1; backlight_update_status(pcf_bl->bl); return 0; } static struct platform_driver pcf50633_bl_driver = { .probe = pcf50633_bl_probe, .driver = { .name = "pcf50633-backlight", }, }; module_platform_driver(pcf50633_bl_driver); MODULE_AUTHOR("Lars-Peter Clausen <[email protected]>"); MODULE_DESCRIPTION("PCF50633 backlight driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:pcf50633-backlight");
linux-master
drivers/video/backlight/pcf50633-backlight.c
// SPDX-License-Identifier: GPL-2.0-only /* * Simple driver for Texas Instruments LM3630A Backlight driver chip * Copyright (C) 2012 Texas Instruments */ #include <linux/module.h> #include <linux/slab.h> #include <linux/i2c.h> #include <linux/backlight.h> #include <linux/err.h> #include <linux/delay.h> #include <linux/uaccess.h> #include <linux/interrupt.h> #include <linux/regmap.h> #include <linux/gpio/consumer.h> #include <linux/pwm.h> #include <linux/platform_data/lm3630a_bl.h> #define REG_CTRL 0x00 #define REG_BOOST 0x02 #define REG_CONFIG 0x01 #define REG_BRT_A 0x03 #define REG_BRT_B 0x04 #define REG_I_A 0x05 #define REG_I_B 0x06 #define REG_INT_STATUS 0x09 #define REG_INT_EN 0x0A #define REG_FAULT 0x0B #define REG_PWM_OUTLOW 0x12 #define REG_PWM_OUTHIGH 0x13 #define REG_FILTER_STRENGTH 0x50 #define REG_MAX 0x50 #define INT_DEBOUNCE_MSEC 10 #define LM3630A_BANK_0 0 #define LM3630A_BANK_1 1 #define LM3630A_NUM_SINKS 2 #define LM3630A_SINK_0 0 #define LM3630A_SINK_1 1 struct lm3630a_chip { struct device *dev; struct delayed_work work; int irq; struct workqueue_struct *irqthread; struct lm3630a_platform_data *pdata; struct backlight_device *bleda; struct backlight_device *bledb; struct gpio_desc *enable_gpio; struct regmap *regmap; struct pwm_device *pwmd; struct pwm_state pwmd_state; }; /* i2c access */ static int lm3630a_read(struct lm3630a_chip *pchip, unsigned int reg) { int rval; unsigned int reg_val; rval = regmap_read(pchip->regmap, reg, &reg_val); if (rval < 0) return rval; return reg_val & 0xFF; } static int lm3630a_write(struct lm3630a_chip *pchip, unsigned int reg, unsigned int data) { return regmap_write(pchip->regmap, reg, data); } static int lm3630a_update(struct lm3630a_chip *pchip, unsigned int reg, unsigned int mask, unsigned int data) { return regmap_update_bits(pchip->regmap, reg, mask, data); } /* initialize chip */ static int lm3630a_chip_init(struct lm3630a_chip *pchip) { int rval; struct lm3630a_platform_data *pdata = pchip->pdata; usleep_range(1000, 2000); /* set Filter Strength Register */ rval = lm3630a_write(pchip, REG_FILTER_STRENGTH, 0x03); /* set Cofig. register */ rval |= lm3630a_update(pchip, REG_CONFIG, 0x07, pdata->pwm_ctrl); /* set boost control */ rval |= lm3630a_write(pchip, REG_BOOST, 0x38); /* set current A */ rval |= lm3630a_update(pchip, REG_I_A, 0x1F, 0x1F); /* set current B */ rval |= lm3630a_write(pchip, REG_I_B, 0x1F); /* set control */ rval |= lm3630a_update(pchip, REG_CTRL, 0x14, pdata->leda_ctrl); rval |= lm3630a_update(pchip, REG_CTRL, 0x0B, pdata->ledb_ctrl); usleep_range(1000, 2000); /* set brightness A and B */ rval |= lm3630a_write(pchip, REG_BRT_A, pdata->leda_init_brt); rval |= lm3630a_write(pchip, REG_BRT_B, pdata->ledb_init_brt); if (rval < 0) dev_err(pchip->dev, "i2c failed to access register\n"); return rval; } /* interrupt handling */ static void lm3630a_delayed_func(struct work_struct *work) { int rval; struct lm3630a_chip *pchip; pchip = container_of(work, struct lm3630a_chip, work.work); rval = lm3630a_read(pchip, REG_INT_STATUS); if (rval < 0) { dev_err(pchip->dev, "i2c failed to access REG_INT_STATUS Register\n"); return; } dev_info(pchip->dev, "REG_INT_STATUS Register is 0x%x\n", rval); } static irqreturn_t lm3630a_isr_func(int irq, void *chip) { int rval; struct lm3630a_chip *pchip = chip; unsigned long delay = msecs_to_jiffies(INT_DEBOUNCE_MSEC); queue_delayed_work(pchip->irqthread, &pchip->work, delay); rval = lm3630a_update(pchip, REG_CTRL, 0x80, 0x00); if (rval < 0) { dev_err(pchip->dev, "i2c failed to access register\n"); return IRQ_NONE; } return IRQ_HANDLED; } static int lm3630a_intr_config(struct lm3630a_chip *pchip) { int rval; rval = lm3630a_write(pchip, REG_INT_EN, 0x87); if (rval < 0) return rval; INIT_DELAYED_WORK(&pchip->work, lm3630a_delayed_func); pchip->irqthread = create_singlethread_workqueue("lm3630a-irqthd"); if (!pchip->irqthread) { dev_err(pchip->dev, "create irq thread fail\n"); return -ENOMEM; } if (request_threaded_irq (pchip->irq, NULL, lm3630a_isr_func, IRQF_TRIGGER_FALLING | IRQF_ONESHOT, "lm3630a_irq", pchip)) { dev_err(pchip->dev, "request threaded irq fail\n"); destroy_workqueue(pchip->irqthread); return -ENOMEM; } return rval; } static int lm3630a_pwm_ctrl(struct lm3630a_chip *pchip, int br, int br_max) { int err; pchip->pwmd_state.period = pchip->pdata->pwm_period; err = pwm_set_relative_duty_cycle(&pchip->pwmd_state, br, br_max); if (err) return err; pchip->pwmd_state.enabled = pchip->pwmd_state.duty_cycle ? true : false; return pwm_apply_state(pchip->pwmd, &pchip->pwmd_state); } /* update and get brightness */ static int lm3630a_bank_a_update_status(struct backlight_device *bl) { int ret; struct lm3630a_chip *pchip = bl_get_data(bl); enum lm3630a_pwm_ctrl pwm_ctrl = pchip->pdata->pwm_ctrl; /* pwm control */ if ((pwm_ctrl & LM3630A_PWM_BANK_A) != 0) return lm3630a_pwm_ctrl(pchip, bl->props.brightness, bl->props.max_brightness); /* disable sleep */ ret = lm3630a_update(pchip, REG_CTRL, 0x80, 0x00); if (ret < 0) goto out_i2c_err; usleep_range(1000, 2000); /* minimum brightness is 0x04 */ ret = lm3630a_write(pchip, REG_BRT_A, bl->props.brightness); if (backlight_is_blank(bl) || (backlight_get_brightness(bl) < 0x4)) /* turn the string off */ ret |= lm3630a_update(pchip, REG_CTRL, LM3630A_LEDA_ENABLE, 0); else ret |= lm3630a_update(pchip, REG_CTRL, LM3630A_LEDA_ENABLE, LM3630A_LEDA_ENABLE); if (ret < 0) goto out_i2c_err; return 0; out_i2c_err: dev_err(pchip->dev, "i2c failed to access (%pe)\n", ERR_PTR(ret)); return ret; } static int lm3630a_bank_a_get_brightness(struct backlight_device *bl) { int brightness, rval; struct lm3630a_chip *pchip = bl_get_data(bl); enum lm3630a_pwm_ctrl pwm_ctrl = pchip->pdata->pwm_ctrl; if ((pwm_ctrl & LM3630A_PWM_BANK_A) != 0) { rval = lm3630a_read(pchip, REG_PWM_OUTHIGH); if (rval < 0) goto out_i2c_err; brightness = (rval & 0x01) << 8; rval = lm3630a_read(pchip, REG_PWM_OUTLOW); if (rval < 0) goto out_i2c_err; brightness |= rval; goto out; } /* disable sleep */ rval = lm3630a_update(pchip, REG_CTRL, 0x80, 0x00); if (rval < 0) goto out_i2c_err; usleep_range(1000, 2000); rval = lm3630a_read(pchip, REG_BRT_A); if (rval < 0) goto out_i2c_err; brightness = rval; out: bl->props.brightness = brightness; return bl->props.brightness; out_i2c_err: dev_err(pchip->dev, "i2c failed to access register\n"); return 0; } static const struct backlight_ops lm3630a_bank_a_ops = { .options = BL_CORE_SUSPENDRESUME, .update_status = lm3630a_bank_a_update_status, .get_brightness = lm3630a_bank_a_get_brightness, }; /* update and get brightness */ static int lm3630a_bank_b_update_status(struct backlight_device *bl) { int ret; struct lm3630a_chip *pchip = bl_get_data(bl); enum lm3630a_pwm_ctrl pwm_ctrl = pchip->pdata->pwm_ctrl; /* pwm control */ if ((pwm_ctrl & LM3630A_PWM_BANK_B) != 0) return lm3630a_pwm_ctrl(pchip, bl->props.brightness, bl->props.max_brightness); /* disable sleep */ ret = lm3630a_update(pchip, REG_CTRL, 0x80, 0x00); if (ret < 0) goto out_i2c_err; usleep_range(1000, 2000); /* minimum brightness is 0x04 */ ret = lm3630a_write(pchip, REG_BRT_B, bl->props.brightness); if (backlight_is_blank(bl) || (backlight_get_brightness(bl) < 0x4)) /* turn the string off */ ret |= lm3630a_update(pchip, REG_CTRL, LM3630A_LEDB_ENABLE, 0); else ret |= lm3630a_update(pchip, REG_CTRL, LM3630A_LEDB_ENABLE, LM3630A_LEDB_ENABLE); if (ret < 0) goto out_i2c_err; return 0; out_i2c_err: dev_err(pchip->dev, "i2c failed to access (%pe)\n", ERR_PTR(ret)); return ret; } static int lm3630a_bank_b_get_brightness(struct backlight_device *bl) { int brightness, rval; struct lm3630a_chip *pchip = bl_get_data(bl); enum lm3630a_pwm_ctrl pwm_ctrl = pchip->pdata->pwm_ctrl; if ((pwm_ctrl & LM3630A_PWM_BANK_B) != 0) { rval = lm3630a_read(pchip, REG_PWM_OUTHIGH); if (rval < 0) goto out_i2c_err; brightness = (rval & 0x01) << 8; rval = lm3630a_read(pchip, REG_PWM_OUTLOW); if (rval < 0) goto out_i2c_err; brightness |= rval; goto out; } /* disable sleep */ rval = lm3630a_update(pchip, REG_CTRL, 0x80, 0x00); if (rval < 0) goto out_i2c_err; usleep_range(1000, 2000); rval = lm3630a_read(pchip, REG_BRT_B); if (rval < 0) goto out_i2c_err; brightness = rval; out: bl->props.brightness = brightness; return bl->props.brightness; out_i2c_err: dev_err(pchip->dev, "i2c failed to access register\n"); return 0; } static const struct backlight_ops lm3630a_bank_b_ops = { .options = BL_CORE_SUSPENDRESUME, .update_status = lm3630a_bank_b_update_status, .get_brightness = lm3630a_bank_b_get_brightness, }; static int lm3630a_backlight_register(struct lm3630a_chip *pchip) { struct lm3630a_platform_data *pdata = pchip->pdata; struct backlight_properties props; const char *label; props.type = BACKLIGHT_RAW; if (pdata->leda_ctrl != LM3630A_LEDA_DISABLE) { props.brightness = pdata->leda_init_brt; props.max_brightness = pdata->leda_max_brt; label = pdata->leda_label ? pdata->leda_label : "lm3630a_leda"; pchip->bleda = devm_backlight_device_register(pchip->dev, label, pchip->dev, pchip, &lm3630a_bank_a_ops, &props); if (IS_ERR(pchip->bleda)) return PTR_ERR(pchip->bleda); } if ((pdata->ledb_ctrl != LM3630A_LEDB_DISABLE) && (pdata->ledb_ctrl != LM3630A_LEDB_ON_A)) { props.brightness = pdata->ledb_init_brt; props.max_brightness = pdata->ledb_max_brt; label = pdata->ledb_label ? pdata->ledb_label : "lm3630a_ledb"; pchip->bledb = devm_backlight_device_register(pchip->dev, label, pchip->dev, pchip, &lm3630a_bank_b_ops, &props); if (IS_ERR(pchip->bledb)) return PTR_ERR(pchip->bledb); } return 0; } static const struct regmap_config lm3630a_regmap = { .reg_bits = 8, .val_bits = 8, .max_register = REG_MAX, }; static int lm3630a_parse_led_sources(struct fwnode_handle *node, int default_led_sources) { u32 sources[LM3630A_NUM_SINKS]; int ret, num_sources, i; num_sources = fwnode_property_count_u32(node, "led-sources"); if (num_sources < 0) return default_led_sources; else if (num_sources > ARRAY_SIZE(sources)) return -EINVAL; ret = fwnode_property_read_u32_array(node, "led-sources", sources, num_sources); if (ret) return ret; for (i = 0; i < num_sources; i++) { if (sources[i] != LM3630A_SINK_0 && sources[i] != LM3630A_SINK_1) return -EINVAL; ret |= BIT(sources[i]); } return ret; } static int lm3630a_parse_bank(struct lm3630a_platform_data *pdata, struct fwnode_handle *node, int *seen_led_sources) { int led_sources, ret; const char *label; u32 bank, val; bool linear; ret = fwnode_property_read_u32(node, "reg", &bank); if (ret) return ret; if (bank != LM3630A_BANK_0 && bank != LM3630A_BANK_1) return -EINVAL; led_sources = lm3630a_parse_led_sources(node, BIT(bank)); if (led_sources < 0) return led_sources; if (*seen_led_sources & led_sources) return -EINVAL; *seen_led_sources |= led_sources; linear = fwnode_property_read_bool(node, "ti,linear-mapping-mode"); if (bank) { if (led_sources & BIT(LM3630A_SINK_0) || !(led_sources & BIT(LM3630A_SINK_1))) return -EINVAL; pdata->ledb_ctrl = linear ? LM3630A_LEDB_ENABLE_LINEAR : LM3630A_LEDB_ENABLE; } else { if (!(led_sources & BIT(LM3630A_SINK_0))) return -EINVAL; pdata->leda_ctrl = linear ? LM3630A_LEDA_ENABLE_LINEAR : LM3630A_LEDA_ENABLE; if (led_sources & BIT(LM3630A_SINK_1)) pdata->ledb_ctrl = LM3630A_LEDB_ON_A; } ret = fwnode_property_read_string(node, "label", &label); if (!ret) { if (bank) pdata->ledb_label = label; else pdata->leda_label = label; } ret = fwnode_property_read_u32(node, "default-brightness", &val); if (!ret) { if (bank) pdata->ledb_init_brt = val; else pdata->leda_init_brt = val; } ret = fwnode_property_read_u32(node, "max-brightness", &val); if (!ret) { if (bank) pdata->ledb_max_brt = val; else pdata->leda_max_brt = val; } return 0; } static int lm3630a_parse_node(struct lm3630a_chip *pchip, struct lm3630a_platform_data *pdata) { int ret = -ENODEV, seen_led_sources = 0; struct fwnode_handle *node; device_for_each_child_node(pchip->dev, node) { ret = lm3630a_parse_bank(pdata, node, &seen_led_sources); if (ret) { fwnode_handle_put(node); return ret; } } return ret; } static int lm3630a_probe(struct i2c_client *client) { struct lm3630a_platform_data *pdata = dev_get_platdata(&client->dev); struct lm3630a_chip *pchip; int rval; if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_err(&client->dev, "fail : i2c functionality check\n"); return -EOPNOTSUPP; } pchip = devm_kzalloc(&client->dev, sizeof(struct lm3630a_chip), GFP_KERNEL); if (!pchip) return -ENOMEM; pchip->dev = &client->dev; pchip->regmap = devm_regmap_init_i2c(client, &lm3630a_regmap); if (IS_ERR(pchip->regmap)) { rval = PTR_ERR(pchip->regmap); dev_err(&client->dev, "fail : allocate reg. map: %d\n", rval); return rval; } i2c_set_clientdata(client, pchip); if (pdata == NULL) { pdata = devm_kzalloc(pchip->dev, sizeof(struct lm3630a_platform_data), GFP_KERNEL); if (pdata == NULL) return -ENOMEM; /* default values */ pdata->leda_max_brt = LM3630A_MAX_BRIGHTNESS; pdata->ledb_max_brt = LM3630A_MAX_BRIGHTNESS; pdata->leda_init_brt = LM3630A_MAX_BRIGHTNESS; pdata->ledb_init_brt = LM3630A_MAX_BRIGHTNESS; rval = lm3630a_parse_node(pchip, pdata); if (rval) { dev_err(&client->dev, "fail : parse node\n"); return rval; } } pchip->pdata = pdata; pchip->enable_gpio = devm_gpiod_get_optional(&client->dev, "enable", GPIOD_OUT_HIGH); if (IS_ERR(pchip->enable_gpio)) { rval = PTR_ERR(pchip->enable_gpio); return rval; } /* chip initialize */ rval = lm3630a_chip_init(pchip); if (rval < 0) { dev_err(&client->dev, "fail : init chip\n"); return rval; } /* backlight register */ rval = lm3630a_backlight_register(pchip); if (rval < 0) { dev_err(&client->dev, "fail : backlight register.\n"); return rval; } /* pwm */ if (pdata->pwm_ctrl != LM3630A_PWM_DISABLE) { pchip->pwmd = devm_pwm_get(pchip->dev, "lm3630a-pwm"); if (IS_ERR(pchip->pwmd)) { dev_err(&client->dev, "fail : get pwm device\n"); return PTR_ERR(pchip->pwmd); } pwm_init_state(pchip->pwmd, &pchip->pwmd_state); } /* interrupt enable : irq 0 is not allowed */ pchip->irq = client->irq; if (pchip->irq) { rval = lm3630a_intr_config(pchip); if (rval < 0) return rval; } dev_info(&client->dev, "LM3630A backlight register OK.\n"); return 0; } static void lm3630a_remove(struct i2c_client *client) { int rval; struct lm3630a_chip *pchip = i2c_get_clientdata(client); rval = lm3630a_write(pchip, REG_BRT_A, 0); if (rval < 0) dev_err(pchip->dev, "i2c failed to access register\n"); rval = lm3630a_write(pchip, REG_BRT_B, 0); if (rval < 0) dev_err(pchip->dev, "i2c failed to access register\n"); if (pchip->irq) { free_irq(pchip->irq, pchip); destroy_workqueue(pchip->irqthread); } } static const struct i2c_device_id lm3630a_id[] = { {LM3630A_NAME, 0}, {} }; MODULE_DEVICE_TABLE(i2c, lm3630a_id); static const struct of_device_id lm3630a_match_table[] = { { .compatible = "ti,lm3630a", }, { }, }; MODULE_DEVICE_TABLE(of, lm3630a_match_table); static struct i2c_driver lm3630a_i2c_driver = { .driver = { .name = LM3630A_NAME, .of_match_table = lm3630a_match_table, }, .probe = lm3630a_probe, .remove = lm3630a_remove, .id_table = lm3630a_id, }; module_i2c_driver(lm3630a_i2c_driver); MODULE_DESCRIPTION("Texas Instruments Backlight driver for LM3630A"); MODULE_AUTHOR("Daniel Jeong <[email protected]>"); MODULE_AUTHOR("LDD MLP <[email protected]>"); MODULE_LICENSE("GPL v2");
linux-master
drivers/video/backlight/lm3630a_bl.c
// SPDX-License-Identifier: GPL-2.0-only /* * TI LP855x Backlight Driver * * Copyright (C) 2011 Texas Instruments */ #include <linux/acpi.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/i2c.h> #include <linux/backlight.h> #include <linux/delay.h> #include <linux/err.h> #include <linux/of.h> #include <linux/platform_data/lp855x.h> #include <linux/pwm.h> #include <linux/regulator/consumer.h> /* LP8550/1/2/3/6 Registers */ #define LP855X_BRIGHTNESS_CTRL 0x00 #define LP855X_DEVICE_CTRL 0x01 #define LP855X_EEPROM_START 0xA0 #define LP855X_EEPROM_END 0xA7 #define LP8556_EPROM_START 0xA0 #define LP8556_EPROM_END 0xAF /* LP8555/7 Registers */ #define LP8557_BL_CMD 0x00 #define LP8557_BL_MASK 0x01 #define LP8557_BL_ON 0x01 #define LP8557_BL_OFF 0x00 #define LP8557_BRIGHTNESS_CTRL 0x04 #define LP8557_CONFIG 0x10 #define LP8555_EPROM_START 0x10 #define LP8555_EPROM_END 0x7A #define LP8557_EPROM_START 0x10 #define LP8557_EPROM_END 0x1E #define DEFAULT_BL_NAME "lcd-backlight" #define MAX_BRIGHTNESS 255 enum lp855x_brightness_ctrl_mode { PWM_BASED = 1, REGISTER_BASED, }; struct lp855x; /* * struct lp855x_device_config * @pre_init_device: init device function call before updating the brightness * @reg_brightness: register address for brigthenss control * @reg_devicectrl: register address for device control * @post_init_device: late init device function call */ struct lp855x_device_config { int (*pre_init_device)(struct lp855x *); u8 reg_brightness; u8 reg_devicectrl; int (*post_init_device)(struct lp855x *); }; struct lp855x { const char *chipname; enum lp855x_chip_id chip_id; enum lp855x_brightness_ctrl_mode mode; struct lp855x_device_config *cfg; struct i2c_client *client; struct backlight_device *bl; struct device *dev; struct lp855x_platform_data *pdata; struct pwm_device *pwm; bool needs_pwm_init; struct regulator *supply; /* regulator for VDD input */ struct regulator *enable; /* regulator for EN/VDDIO input */ }; static int lp855x_write_byte(struct lp855x *lp, u8 reg, u8 data) { return i2c_smbus_write_byte_data(lp->client, reg, data); } static int lp855x_update_bit(struct lp855x *lp, u8 reg, u8 mask, u8 data) { int ret; u8 tmp; ret = i2c_smbus_read_byte_data(lp->client, reg); if (ret < 0) { dev_err(lp->dev, "failed to read 0x%.2x\n", reg); return ret; } tmp = (u8)ret; tmp &= ~mask; tmp |= data & mask; return lp855x_write_byte(lp, reg, tmp); } static bool lp855x_is_valid_rom_area(struct lp855x *lp, u8 addr) { u8 start, end; switch (lp->chip_id) { case LP8550: case LP8551: case LP8552: case LP8553: start = LP855X_EEPROM_START; end = LP855X_EEPROM_END; break; case LP8556: start = LP8556_EPROM_START; end = LP8556_EPROM_END; break; case LP8555: start = LP8555_EPROM_START; end = LP8555_EPROM_END; break; case LP8557: start = LP8557_EPROM_START; end = LP8557_EPROM_END; break; default: return false; } return addr >= start && addr <= end; } static int lp8557_bl_off(struct lp855x *lp) { /* BL_ON = 0 before updating EPROM settings */ return lp855x_update_bit(lp, LP8557_BL_CMD, LP8557_BL_MASK, LP8557_BL_OFF); } static int lp8557_bl_on(struct lp855x *lp) { /* BL_ON = 1 after updating EPROM settings */ return lp855x_update_bit(lp, LP8557_BL_CMD, LP8557_BL_MASK, LP8557_BL_ON); } static struct lp855x_device_config lp855x_dev_cfg = { .reg_brightness = LP855X_BRIGHTNESS_CTRL, .reg_devicectrl = LP855X_DEVICE_CTRL, }; static struct lp855x_device_config lp8557_dev_cfg = { .reg_brightness = LP8557_BRIGHTNESS_CTRL, .reg_devicectrl = LP8557_CONFIG, .pre_init_device = lp8557_bl_off, .post_init_device = lp8557_bl_on, }; /* * Device specific configuration flow * * a) pre_init_device(optional) * b) update the brightness register * c) update device control register * d) update ROM area(optional) * e) post_init_device(optional) * */ static int lp855x_configure(struct lp855x *lp) { u8 val, addr; int i, ret; struct lp855x_platform_data *pd = lp->pdata; if (lp->cfg->pre_init_device) { ret = lp->cfg->pre_init_device(lp); if (ret) { dev_err(lp->dev, "pre init device err: %d\n", ret); goto err; } } val = pd->initial_brightness; ret = lp855x_write_byte(lp, lp->cfg->reg_brightness, val); if (ret) goto err; val = pd->device_control; ret = lp855x_write_byte(lp, lp->cfg->reg_devicectrl, val); if (ret) goto err; if (pd->size_program > 0) { for (i = 0; i < pd->size_program; i++) { addr = pd->rom_data[i].addr; val = pd->rom_data[i].val; if (!lp855x_is_valid_rom_area(lp, addr)) continue; ret = lp855x_write_byte(lp, addr, val); if (ret) goto err; } } if (lp->cfg->post_init_device) { ret = lp->cfg->post_init_device(lp); if (ret) { dev_err(lp->dev, "post init device err: %d\n", ret); goto err; } } return 0; err: return ret; } static int lp855x_pwm_ctrl(struct lp855x *lp, int br, int max_br) { struct pwm_state state; if (lp->needs_pwm_init) { pwm_init_state(lp->pwm, &state); /* Legacy platform data compatibility */ if (lp->pdata->period_ns > 0) state.period = lp->pdata->period_ns; lp->needs_pwm_init = false; } else { pwm_get_state(lp->pwm, &state); } state.duty_cycle = div_u64(br * state.period, max_br); state.enabled = state.duty_cycle; return pwm_apply_state(lp->pwm, &state); } static int lp855x_bl_update_status(struct backlight_device *bl) { struct lp855x *lp = bl_get_data(bl); int brightness = bl->props.brightness; if (bl->props.state & (BL_CORE_SUSPENDED | BL_CORE_FBBLANK)) brightness = 0; if (lp->mode == PWM_BASED) return lp855x_pwm_ctrl(lp, brightness, bl->props.max_brightness); else if (lp->mode == REGISTER_BASED) return lp855x_write_byte(lp, lp->cfg->reg_brightness, (u8)brightness); return -EINVAL; } static const struct backlight_ops lp855x_bl_ops = { .options = BL_CORE_SUSPENDRESUME, .update_status = lp855x_bl_update_status, }; static int lp855x_backlight_register(struct lp855x *lp) { struct backlight_device *bl; struct backlight_properties props; struct lp855x_platform_data *pdata = lp->pdata; const char *name = pdata->name ? : DEFAULT_BL_NAME; memset(&props, 0, sizeof(props)); props.type = BACKLIGHT_PLATFORM; props.max_brightness = MAX_BRIGHTNESS; if (pdata->initial_brightness > props.max_brightness) pdata->initial_brightness = props.max_brightness; props.brightness = pdata->initial_brightness; bl = devm_backlight_device_register(lp->dev, name, lp->dev, lp, &lp855x_bl_ops, &props); if (IS_ERR(bl)) return PTR_ERR(bl); lp->bl = bl; return 0; } static ssize_t lp855x_get_chip_id(struct device *dev, struct device_attribute *attr, char *buf) { struct lp855x *lp = dev_get_drvdata(dev); return scnprintf(buf, PAGE_SIZE, "%s\n", lp->chipname); } static ssize_t lp855x_get_bl_ctl_mode(struct device *dev, struct device_attribute *attr, char *buf) { struct lp855x *lp = dev_get_drvdata(dev); char *strmode = NULL; if (lp->mode == PWM_BASED) strmode = "pwm based"; else if (lp->mode == REGISTER_BASED) strmode = "register based"; return scnprintf(buf, PAGE_SIZE, "%s\n", strmode); } static DEVICE_ATTR(chip_id, S_IRUGO, lp855x_get_chip_id, NULL); static DEVICE_ATTR(bl_ctl_mode, S_IRUGO, lp855x_get_bl_ctl_mode, NULL); static struct attribute *lp855x_attributes[] = { &dev_attr_chip_id.attr, &dev_attr_bl_ctl_mode.attr, NULL, }; static const struct attribute_group lp855x_attr_group = { .attrs = lp855x_attributes, }; #ifdef CONFIG_OF static int lp855x_parse_dt(struct lp855x *lp) { struct device *dev = lp->dev; struct device_node *node = dev->of_node; struct lp855x_platform_data *pdata = lp->pdata; int rom_length; if (!node) { dev_err(dev, "no platform data\n"); return -EINVAL; } of_property_read_string(node, "bl-name", &pdata->name); of_property_read_u8(node, "dev-ctrl", &pdata->device_control); of_property_read_u8(node, "init-brt", &pdata->initial_brightness); /* Deprecated, specify period in pwms property instead */ of_property_read_u32(node, "pwm-period", &pdata->period_ns); /* Fill ROM platform data if defined */ rom_length = of_get_child_count(node); if (rom_length > 0) { struct lp855x_rom_data *rom; struct device_node *child; int i = 0; rom = devm_kcalloc(dev, rom_length, sizeof(*rom), GFP_KERNEL); if (!rom) return -ENOMEM; for_each_child_of_node(node, child) { of_property_read_u8(child, "rom-addr", &rom[i].addr); of_property_read_u8(child, "rom-val", &rom[i].val); i++; } pdata->size_program = rom_length; pdata->rom_data = &rom[0]; } return 0; } #else static int lp855x_parse_dt(struct lp855x *lp) { return -EINVAL; } #endif static int lp855x_parse_acpi(struct lp855x *lp) { int ret; /* * On ACPI the device has already been initialized by the firmware * and is in register mode, so we can read back the settings from * the registers. */ ret = i2c_smbus_read_byte_data(lp->client, lp->cfg->reg_brightness); if (ret < 0) return ret; lp->pdata->initial_brightness = ret; ret = i2c_smbus_read_byte_data(lp->client, lp->cfg->reg_devicectrl); if (ret < 0) return ret; lp->pdata->device_control = ret; return 0; } static int lp855x_probe(struct i2c_client *cl) { const struct i2c_device_id *id = i2c_client_get_device_id(cl); const struct acpi_device_id *acpi_id = NULL; struct device *dev = &cl->dev; struct lp855x *lp; int ret; if (!i2c_check_functionality(cl->adapter, I2C_FUNC_SMBUS_I2C_BLOCK)) return -EIO; lp = devm_kzalloc(dev, sizeof(struct lp855x), GFP_KERNEL); if (!lp) return -ENOMEM; lp->client = cl; lp->dev = dev; lp->pdata = dev_get_platdata(dev); if (id) { lp->chipname = id->name; lp->chip_id = id->driver_data; } else { acpi_id = acpi_match_device(dev->driver->acpi_match_table, dev); if (!acpi_id) return -ENODEV; lp->chipname = acpi_id->id; lp->chip_id = acpi_id->driver_data; } switch (lp->chip_id) { case LP8550: case LP8551: case LP8552: case LP8553: case LP8556: lp->cfg = &lp855x_dev_cfg; break; case LP8555: case LP8557: lp->cfg = &lp8557_dev_cfg; break; default: return -EINVAL; } if (!lp->pdata) { lp->pdata = devm_kzalloc(dev, sizeof(*lp->pdata), GFP_KERNEL); if (!lp->pdata) return -ENOMEM; if (id) { ret = lp855x_parse_dt(lp); if (ret < 0) return ret; } else { ret = lp855x_parse_acpi(lp); if (ret < 0) return ret; } } lp->supply = devm_regulator_get(dev, "power"); if (IS_ERR(lp->supply)) { if (PTR_ERR(lp->supply) == -EPROBE_DEFER) return -EPROBE_DEFER; lp->supply = NULL; } lp->enable = devm_regulator_get_optional(dev, "enable"); if (IS_ERR(lp->enable)) { ret = PTR_ERR(lp->enable); if (ret == -ENODEV) lp->enable = NULL; else return dev_err_probe(dev, ret, "getting enable regulator\n"); } lp->pwm = devm_pwm_get(lp->dev, lp->chipname); if (IS_ERR(lp->pwm)) { ret = PTR_ERR(lp->pwm); if (ret == -ENODEV || ret == -EINVAL) lp->pwm = NULL; else return dev_err_probe(dev, ret, "getting PWM\n"); lp->needs_pwm_init = false; lp->mode = REGISTER_BASED; dev_dbg(dev, "mode: register based\n"); } else { lp->needs_pwm_init = true; lp->mode = PWM_BASED; dev_dbg(dev, "mode: PWM based\n"); } if (lp->supply) { ret = regulator_enable(lp->supply); if (ret < 0) { dev_err(dev, "failed to enable supply: %d\n", ret); return ret; } } if (lp->enable) { ret = regulator_enable(lp->enable); if (ret < 0) { dev_err(dev, "failed to enable vddio: %d\n", ret); goto disable_supply; } /* * LP8555 datasheet says t_RESPONSE (time between VDDIO and * I2C) is 1ms. */ usleep_range(1000, 2000); } i2c_set_clientdata(cl, lp); ret = lp855x_configure(lp); if (ret) { dev_err(dev, "device config err: %d", ret); goto disable_vddio; } ret = lp855x_backlight_register(lp); if (ret) { dev_err(dev, "failed to register backlight. err: %d\n", ret); goto disable_vddio; } ret = sysfs_create_group(&dev->kobj, &lp855x_attr_group); if (ret) { dev_err(dev, "failed to register sysfs. err: %d\n", ret); goto disable_vddio; } backlight_update_status(lp->bl); return 0; disable_vddio: if (lp->enable) regulator_disable(lp->enable); disable_supply: if (lp->supply) regulator_disable(lp->supply); return ret; } static void lp855x_remove(struct i2c_client *cl) { struct lp855x *lp = i2c_get_clientdata(cl); lp->bl->props.brightness = 0; backlight_update_status(lp->bl); if (lp->enable) regulator_disable(lp->enable); if (lp->supply) regulator_disable(lp->supply); sysfs_remove_group(&lp->dev->kobj, &lp855x_attr_group); } static const struct of_device_id lp855x_dt_ids[] __maybe_unused = { { .compatible = "ti,lp8550", }, { .compatible = "ti,lp8551", }, { .compatible = "ti,lp8552", }, { .compatible = "ti,lp8553", }, { .compatible = "ti,lp8555", }, { .compatible = "ti,lp8556", }, { .compatible = "ti,lp8557", }, { } }; MODULE_DEVICE_TABLE(of, lp855x_dt_ids); static const struct i2c_device_id lp855x_ids[] = { {"lp8550", LP8550}, {"lp8551", LP8551}, {"lp8552", LP8552}, {"lp8553", LP8553}, {"lp8555", LP8555}, {"lp8556", LP8556}, {"lp8557", LP8557}, { } }; MODULE_DEVICE_TABLE(i2c, lp855x_ids); #ifdef CONFIG_ACPI static const struct acpi_device_id lp855x_acpi_match[] = { /* Xiaomi specific HID used for the LP8556 on the Mi Pad 2 */ { "XMCC0001", LP8556 }, { } }; MODULE_DEVICE_TABLE(acpi, lp855x_acpi_match); #endif static struct i2c_driver lp855x_driver = { .driver = { .name = "lp855x", .of_match_table = of_match_ptr(lp855x_dt_ids), .acpi_match_table = ACPI_PTR(lp855x_acpi_match), }, .probe = lp855x_probe, .remove = lp855x_remove, .id_table = lp855x_ids, }; module_i2c_driver(lp855x_driver); MODULE_DESCRIPTION("Texas Instruments LP855x Backlight driver"); MODULE_AUTHOR("Milo Kim <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/video/backlight/lp855x_bl.c
// SPDX-License-Identifier: GPL-2.0-only #include <dt-bindings/leds/rt4831-backlight.h> #include <linux/backlight.h> #include <linux/bitops.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/property.h> #include <linux/regmap.h> #define RT4831_REG_BLCFG 0x02 #define RT4831_REG_BLDIML 0x04 #define RT4831_REG_ENABLE 0x08 #define RT4831_REG_BLOPT2 0x11 #define RT4831_BLMAX_BRIGHTNESS 2048 #define RT4831_BLOVP_MASK GENMASK(7, 5) #define RT4831_BLOVP_SHIFT 5 #define RT4831_BLPWMEN_MASK BIT(0) #define RT4831_BLEN_MASK BIT(4) #define RT4831_BLCH_MASK GENMASK(3, 0) #define RT4831_BLDIML_MASK GENMASK(2, 0) #define RT4831_BLDIMH_MASK GENMASK(10, 3) #define RT4831_BLDIMH_SHIFT 3 #define RT4831_BLOCP_MASK GENMASK(1, 0) #define RT4831_BLOCP_MINUA 900000 #define RT4831_BLOCP_MAXUA 1800000 #define RT4831_BLOCP_STEPUA 300000 struct rt4831_priv { struct device *dev; struct regmap *regmap; struct backlight_device *bl; }; static int rt4831_bl_update_status(struct backlight_device *bl_dev) { struct rt4831_priv *priv = bl_get_data(bl_dev); int brightness = backlight_get_brightness(bl_dev); unsigned int enable = brightness ? RT4831_BLEN_MASK : 0; u8 v[2]; int ret; if (brightness) { v[0] = (brightness - 1) & RT4831_BLDIML_MASK; v[1] = ((brightness - 1) & RT4831_BLDIMH_MASK) >> RT4831_BLDIMH_SHIFT; ret = regmap_raw_write(priv->regmap, RT4831_REG_BLDIML, v, sizeof(v)); if (ret) return ret; } return regmap_update_bits(priv->regmap, RT4831_REG_ENABLE, RT4831_BLEN_MASK, enable); } static int rt4831_bl_get_brightness(struct backlight_device *bl_dev) { struct rt4831_priv *priv = bl_get_data(bl_dev); unsigned int val; u8 v[2]; int ret; ret = regmap_read(priv->regmap, RT4831_REG_ENABLE, &val); if (ret) return ret; if (!(val & RT4831_BLEN_MASK)) return 0; ret = regmap_raw_read(priv->regmap, RT4831_REG_BLDIML, v, sizeof(v)); if (ret) return ret; ret = (v[1] << RT4831_BLDIMH_SHIFT) + (v[0] & RT4831_BLDIML_MASK) + 1; return ret; } static const struct backlight_ops rt4831_bl_ops = { .options = BL_CORE_SUSPENDRESUME, .update_status = rt4831_bl_update_status, .get_brightness = rt4831_bl_get_brightness, }; static int rt4831_parse_backlight_properties(struct rt4831_priv *priv, struct backlight_properties *bl_props) { struct device *dev = priv->dev; u8 propval; u32 brightness, ocp_uA; unsigned int val = 0; int ret; /* common properties */ ret = device_property_read_u32(dev, "max-brightness", &brightness); if (ret) brightness = RT4831_BLMAX_BRIGHTNESS; bl_props->max_brightness = min_t(u32, brightness, RT4831_BLMAX_BRIGHTNESS); ret = device_property_read_u32(dev, "default-brightness", &brightness); if (ret) brightness = bl_props->max_brightness; bl_props->brightness = min_t(u32, brightness, bl_props->max_brightness); /* vendor properties */ if (device_property_read_bool(dev, "richtek,pwm-enable")) val = RT4831_BLPWMEN_MASK; ret = regmap_update_bits(priv->regmap, RT4831_REG_BLCFG, RT4831_BLPWMEN_MASK, val); if (ret) return ret; ret = device_property_read_u8(dev, "richtek,bled-ovp-sel", &propval); if (ret) propval = RT4831_BLOVPLVL_21V; propval = min_t(u8, propval, RT4831_BLOVPLVL_29V); ret = regmap_update_bits(priv->regmap, RT4831_REG_BLCFG, RT4831_BLOVP_MASK, propval << RT4831_BLOVP_SHIFT); if (ret) return ret; /* * This OCP level is used to protect and limit the inductor current. * If inductor peak current reach the level, low-side MOSFET will be * turned off. Meanwhile, the output channel current may be limited. * To match the configured channel current, the inductor chosen must * be higher than the OCP level. * * Not like the OVP level, the default 21V can be used in the most * application. But if the chosen OCP level is smaller than needed, * it will also affect the backlight channel output current to be * smaller than the register setting. */ ret = device_property_read_u32(dev, "richtek,bled-ocp-microamp", &ocp_uA); if (!ret) { ocp_uA = clamp_val(ocp_uA, RT4831_BLOCP_MINUA, RT4831_BLOCP_MAXUA); val = DIV_ROUND_UP(ocp_uA - RT4831_BLOCP_MINUA, RT4831_BLOCP_STEPUA); ret = regmap_update_bits(priv->regmap, RT4831_REG_BLOPT2, RT4831_BLOCP_MASK, val); if (ret) return ret; } ret = device_property_read_u8(dev, "richtek,channel-use", &propval); if (ret) { dev_err(dev, "richtek,channel-use DT property missing\n"); return ret; } if (!(propval & RT4831_BLCH_MASK)) { dev_err(dev, "No channel specified\n"); return -EINVAL; } return regmap_update_bits(priv->regmap, RT4831_REG_ENABLE, RT4831_BLCH_MASK, propval); } static int rt4831_bl_probe(struct platform_device *pdev) { struct rt4831_priv *priv; struct backlight_properties bl_props = { .type = BACKLIGHT_RAW, .scale = BACKLIGHT_SCALE_LINEAR }; int ret; priv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; priv->dev = &pdev->dev; priv->regmap = dev_get_regmap(pdev->dev.parent, NULL); if (!priv->regmap) { dev_err(&pdev->dev, "Failed to init regmap\n"); return -ENODEV; } ret = rt4831_parse_backlight_properties(priv, &bl_props); if (ret) { dev_err(&pdev->dev, "Failed to parse backlight properties\n"); return ret; } priv->bl = devm_backlight_device_register(&pdev->dev, pdev->name, &pdev->dev, priv, &rt4831_bl_ops, &bl_props); if (IS_ERR(priv->bl)) { dev_err(&pdev->dev, "Failed to register backlight\n"); return PTR_ERR(priv->bl); } backlight_update_status(priv->bl); platform_set_drvdata(pdev, priv); return 0; } static void rt4831_bl_remove(struct platform_device *pdev) { struct rt4831_priv *priv = platform_get_drvdata(pdev); struct backlight_device *bl_dev = priv->bl; bl_dev->props.brightness = 0; backlight_update_status(priv->bl); } static const struct of_device_id __maybe_unused rt4831_bl_of_match[] = { { .compatible = "richtek,rt4831-backlight", }, {} }; MODULE_DEVICE_TABLE(of, rt4831_bl_of_match); static struct platform_driver rt4831_bl_driver = { .driver = { .name = "rt4831-backlight", .of_match_table = rt4831_bl_of_match, }, .probe = rt4831_bl_probe, .remove_new = rt4831_bl_remove, }; module_platform_driver(rt4831_bl_driver); MODULE_AUTHOR("ChiYuan Huang <[email protected]>"); MODULE_LICENSE("GPL v2");
linux-master
drivers/video/backlight/rt4831-backlight.c
// SPDX-License-Identifier: GPL-2.0-only /* * LCD/Backlight Driver for Sharp Zaurus Handhelds (various models) * * Copyright (c) 2004-2006 Richard Purdie * * Based on Sharp's 2.4 Backlight Driver * * Copyright (c) 2008 Marvell International Ltd. * Converted to SPI device based LCD/Backlight device driver * by Eric Miao <[email protected]> */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/gpio/consumer.h> #include <linux/fb.h> #include <linux/lcd.h> #include <linux/spi/spi.h> #include <linux/spi/corgi_lcd.h> #include <linux/slab.h> #include <asm/mach/sharpsl_param.h> #define POWER_IS_ON(pwr) ((pwr) <= FB_BLANK_NORMAL) /* Register Addresses */ #define RESCTL_ADRS 0x00 #define PHACTRL_ADRS 0x01 #define DUTYCTRL_ADRS 0x02 #define POWERREG0_ADRS 0x03 #define POWERREG1_ADRS 0x04 #define GPOR3_ADRS 0x05 #define PICTRL_ADRS 0x06 #define POLCTRL_ADRS 0x07 /* Register Bit Definitions */ #define RESCTL_QVGA 0x01 #define RESCTL_VGA 0x00 #define POWER1_VW_ON 0x01 /* VW Supply FET ON */ #define POWER1_GVSS_ON 0x02 /* GVSS(-8V) Power Supply ON */ #define POWER1_VDD_ON 0x04 /* VDD(8V),SVSS(-4V) Power Supply ON */ #define POWER1_VW_OFF 0x00 /* VW Supply FET OFF */ #define POWER1_GVSS_OFF 0x00 /* GVSS(-8V) Power Supply OFF */ #define POWER1_VDD_OFF 0x00 /* VDD(8V),SVSS(-4V) Power Supply OFF */ #define POWER0_COM_DCLK 0x01 /* COM Voltage DC Bias DAC Serial Data Clock */ #define POWER0_COM_DOUT 0x02 /* COM Voltage DC Bias DAC Serial Data Out */ #define POWER0_DAC_ON 0x04 /* DAC Power Supply ON */ #define POWER0_COM_ON 0x08 /* COM Power Supply ON */ #define POWER0_VCC5_ON 0x10 /* VCC5 Power Supply ON */ #define POWER0_DAC_OFF 0x00 /* DAC Power Supply OFF */ #define POWER0_COM_OFF 0x00 /* COM Power Supply OFF */ #define POWER0_VCC5_OFF 0x00 /* VCC5 Power Supply OFF */ #define PICTRL_INIT_STATE 0x01 #define PICTRL_INIOFF 0x02 #define PICTRL_POWER_DOWN 0x04 #define PICTRL_COM_SIGNAL_OFF 0x08 #define PICTRL_DAC_SIGNAL_OFF 0x10 #define POLCTRL_SYNC_POL_FALL 0x01 #define POLCTRL_EN_POL_FALL 0x02 #define POLCTRL_DATA_POL_FALL 0x04 #define POLCTRL_SYNC_ACT_H 0x08 #define POLCTRL_EN_ACT_L 0x10 #define POLCTRL_SYNC_POL_RISE 0x00 #define POLCTRL_EN_POL_RISE 0x00 #define POLCTRL_DATA_POL_RISE 0x00 #define POLCTRL_SYNC_ACT_L 0x00 #define POLCTRL_EN_ACT_H 0x00 #define PHACTRL_PHASE_MANUAL 0x01 #define DEFAULT_PHAD_QVGA (9) #define DEFAULT_COMADJ (125) struct corgi_lcd { struct spi_device *spi_dev; struct lcd_device *lcd_dev; struct backlight_device *bl_dev; int limit_mask; int intensity; int power; int mode; char buf[2]; struct gpio_desc *backlight_on; struct gpio_desc *backlight_cont; void (*kick_battery)(void); }; static int corgi_ssp_lcdtg_send(struct corgi_lcd *lcd, int reg, uint8_t val); static struct corgi_lcd *the_corgi_lcd; static unsigned long corgibl_flags; #define CORGIBL_SUSPENDED 0x01 #define CORGIBL_BATTLOW 0x02 /* * This is only a pseudo I2C interface. We can't use the standard kernel * routines as the interface is write only. We just assume the data is acked... */ static void lcdtg_ssp_i2c_send(struct corgi_lcd *lcd, uint8_t data) { corgi_ssp_lcdtg_send(lcd, POWERREG0_ADRS, data); udelay(10); } static void lcdtg_i2c_send_bit(struct corgi_lcd *lcd, uint8_t data) { lcdtg_ssp_i2c_send(lcd, data); lcdtg_ssp_i2c_send(lcd, data | POWER0_COM_DCLK); lcdtg_ssp_i2c_send(lcd, data); } static void lcdtg_i2c_send_start(struct corgi_lcd *lcd, uint8_t base) { lcdtg_ssp_i2c_send(lcd, base | POWER0_COM_DCLK | POWER0_COM_DOUT); lcdtg_ssp_i2c_send(lcd, base | POWER0_COM_DCLK); lcdtg_ssp_i2c_send(lcd, base); } static void lcdtg_i2c_send_stop(struct corgi_lcd *lcd, uint8_t base) { lcdtg_ssp_i2c_send(lcd, base); lcdtg_ssp_i2c_send(lcd, base | POWER0_COM_DCLK); lcdtg_ssp_i2c_send(lcd, base | POWER0_COM_DCLK | POWER0_COM_DOUT); } static void lcdtg_i2c_send_byte(struct corgi_lcd *lcd, uint8_t base, uint8_t data) { int i; for (i = 0; i < 8; i++) { if (data & 0x80) lcdtg_i2c_send_bit(lcd, base | POWER0_COM_DOUT); else lcdtg_i2c_send_bit(lcd, base); data <<= 1; } } static void lcdtg_i2c_wait_ack(struct corgi_lcd *lcd, uint8_t base) { lcdtg_i2c_send_bit(lcd, base); } static void lcdtg_set_common_voltage(struct corgi_lcd *lcd, uint8_t base_data, uint8_t data) { /* Set Common Voltage to M62332FP via I2C */ lcdtg_i2c_send_start(lcd, base_data); lcdtg_i2c_send_byte(lcd, base_data, 0x9c); lcdtg_i2c_wait_ack(lcd, base_data); lcdtg_i2c_send_byte(lcd, base_data, 0x00); lcdtg_i2c_wait_ack(lcd, base_data); lcdtg_i2c_send_byte(lcd, base_data, data); lcdtg_i2c_wait_ack(lcd, base_data); lcdtg_i2c_send_stop(lcd, base_data); } static int corgi_ssp_lcdtg_send(struct corgi_lcd *lcd, int adrs, uint8_t data) { struct spi_message msg; struct spi_transfer xfer = { .len = 1, .cs_change = 0, .tx_buf = lcd->buf, }; lcd->buf[0] = ((adrs & 0x07) << 5) | (data & 0x1f); spi_message_init(&msg); spi_message_add_tail(&xfer, &msg); return spi_sync(lcd->spi_dev, &msg); } /* Set Phase Adjust */ static void lcdtg_set_phadadj(struct corgi_lcd *lcd, int mode) { int adj; switch (mode) { case CORGI_LCD_MODE_VGA: /* Setting for VGA */ adj = sharpsl_param.phadadj; adj = (adj < 0) ? PHACTRL_PHASE_MANUAL : PHACTRL_PHASE_MANUAL | ((adj & 0xf) << 1); break; case CORGI_LCD_MODE_QVGA: default: /* Setting for QVGA */ adj = (DEFAULT_PHAD_QVGA << 1) | PHACTRL_PHASE_MANUAL; break; } corgi_ssp_lcdtg_send(lcd, PHACTRL_ADRS, adj); } static void corgi_lcd_power_on(struct corgi_lcd *lcd) { int comadj; /* Initialize Internal Logic & Port */ corgi_ssp_lcdtg_send(lcd, PICTRL_ADRS, PICTRL_POWER_DOWN | PICTRL_INIOFF | PICTRL_INIT_STATE | PICTRL_COM_SIGNAL_OFF | PICTRL_DAC_SIGNAL_OFF); corgi_ssp_lcdtg_send(lcd, POWERREG0_ADRS, POWER0_COM_DCLK | POWER0_COM_DOUT | POWER0_DAC_OFF | POWER0_COM_OFF | POWER0_VCC5_OFF); corgi_ssp_lcdtg_send(lcd, POWERREG1_ADRS, POWER1_VW_OFF | POWER1_GVSS_OFF | POWER1_VDD_OFF); /* VDD(+8V), SVSS(-4V) ON */ corgi_ssp_lcdtg_send(lcd, POWERREG1_ADRS, POWER1_VW_OFF | POWER1_GVSS_OFF | POWER1_VDD_ON); mdelay(3); /* DAC ON */ corgi_ssp_lcdtg_send(lcd, POWERREG0_ADRS, POWER0_COM_DCLK | POWER0_COM_DOUT | POWER0_DAC_ON | POWER0_COM_OFF | POWER0_VCC5_OFF); /* INIB = H, INI = L */ /* PICTL[0] = H , PICTL[1] = PICTL[2] = PICTL[4] = L */ corgi_ssp_lcdtg_send(lcd, PICTRL_ADRS, PICTRL_INIT_STATE | PICTRL_COM_SIGNAL_OFF); /* Set Common Voltage */ comadj = sharpsl_param.comadj; if (comadj < 0) comadj = DEFAULT_COMADJ; lcdtg_set_common_voltage(lcd, POWER0_DAC_ON | POWER0_COM_OFF | POWER0_VCC5_OFF, comadj); /* VCC5 ON, DAC ON */ corgi_ssp_lcdtg_send(lcd, POWERREG0_ADRS, POWER0_COM_DCLK | POWER0_COM_DOUT | POWER0_DAC_ON | POWER0_COM_OFF | POWER0_VCC5_ON); /* GVSS(-8V) ON, VDD ON */ corgi_ssp_lcdtg_send(lcd, POWERREG1_ADRS, POWER1_VW_OFF | POWER1_GVSS_ON | POWER1_VDD_ON); mdelay(2); /* COM SIGNAL ON (PICTL[3] = L) */ corgi_ssp_lcdtg_send(lcd, PICTRL_ADRS, PICTRL_INIT_STATE); /* COM ON, DAC ON, VCC5_ON */ corgi_ssp_lcdtg_send(lcd, POWERREG0_ADRS, POWER0_COM_DCLK | POWER0_COM_DOUT | POWER0_DAC_ON | POWER0_COM_ON | POWER0_VCC5_ON); /* VW ON, GVSS ON, VDD ON */ corgi_ssp_lcdtg_send(lcd, POWERREG1_ADRS, POWER1_VW_ON | POWER1_GVSS_ON | POWER1_VDD_ON); /* Signals output enable */ corgi_ssp_lcdtg_send(lcd, PICTRL_ADRS, 0); /* Set Phase Adjust */ lcdtg_set_phadadj(lcd, lcd->mode); /* Initialize for Input Signals from ATI */ corgi_ssp_lcdtg_send(lcd, POLCTRL_ADRS, POLCTRL_SYNC_POL_RISE | POLCTRL_EN_POL_RISE | POLCTRL_DATA_POL_RISE | POLCTRL_SYNC_ACT_L | POLCTRL_EN_ACT_H); udelay(1000); switch (lcd->mode) { case CORGI_LCD_MODE_VGA: corgi_ssp_lcdtg_send(lcd, RESCTL_ADRS, RESCTL_VGA); break; case CORGI_LCD_MODE_QVGA: default: corgi_ssp_lcdtg_send(lcd, RESCTL_ADRS, RESCTL_QVGA); break; } } static void corgi_lcd_power_off(struct corgi_lcd *lcd) { /* 60Hz x 2 frame = 16.7msec x 2 = 33.4 msec */ msleep(34); /* (1)VW OFF */ corgi_ssp_lcdtg_send(lcd, POWERREG1_ADRS, POWER1_VW_OFF | POWER1_GVSS_ON | POWER1_VDD_ON); /* (2)COM OFF */ corgi_ssp_lcdtg_send(lcd, PICTRL_ADRS, PICTRL_COM_SIGNAL_OFF); corgi_ssp_lcdtg_send(lcd, POWERREG0_ADRS, POWER0_DAC_ON | POWER0_COM_OFF | POWER0_VCC5_ON); /* (3)Set Common Voltage Bias 0V */ lcdtg_set_common_voltage(lcd, POWER0_DAC_ON | POWER0_COM_OFF | POWER0_VCC5_ON, 0); /* (4)GVSS OFF */ corgi_ssp_lcdtg_send(lcd, POWERREG1_ADRS, POWER1_VW_OFF | POWER1_GVSS_OFF | POWER1_VDD_ON); /* (5)VCC5 OFF */ corgi_ssp_lcdtg_send(lcd, POWERREG0_ADRS, POWER0_DAC_ON | POWER0_COM_OFF | POWER0_VCC5_OFF); /* (6)Set PDWN, INIOFF, DACOFF */ corgi_ssp_lcdtg_send(lcd, PICTRL_ADRS, PICTRL_INIOFF | PICTRL_DAC_SIGNAL_OFF | PICTRL_POWER_DOWN | PICTRL_COM_SIGNAL_OFF); /* (7)DAC OFF */ corgi_ssp_lcdtg_send(lcd, POWERREG0_ADRS, POWER0_DAC_OFF | POWER0_COM_OFF | POWER0_VCC5_OFF); /* (8)VDD OFF */ corgi_ssp_lcdtg_send(lcd, POWERREG1_ADRS, POWER1_VW_OFF | POWER1_GVSS_OFF | POWER1_VDD_OFF); } static int corgi_lcd_set_mode(struct lcd_device *ld, struct fb_videomode *m) { struct corgi_lcd *lcd = lcd_get_data(ld); int mode = CORGI_LCD_MODE_QVGA; if (m->xres == 640 || m->xres == 480) mode = CORGI_LCD_MODE_VGA; if (lcd->mode == mode) return 0; lcdtg_set_phadadj(lcd, mode); switch (mode) { case CORGI_LCD_MODE_VGA: corgi_ssp_lcdtg_send(lcd, RESCTL_ADRS, RESCTL_VGA); break; case CORGI_LCD_MODE_QVGA: default: corgi_ssp_lcdtg_send(lcd, RESCTL_ADRS, RESCTL_QVGA); break; } lcd->mode = mode; return 0; } static int corgi_lcd_set_power(struct lcd_device *ld, int power) { struct corgi_lcd *lcd = lcd_get_data(ld); if (POWER_IS_ON(power) && !POWER_IS_ON(lcd->power)) corgi_lcd_power_on(lcd); if (!POWER_IS_ON(power) && POWER_IS_ON(lcd->power)) corgi_lcd_power_off(lcd); lcd->power = power; return 0; } static int corgi_lcd_get_power(struct lcd_device *ld) { struct corgi_lcd *lcd = lcd_get_data(ld); return lcd->power; } static struct lcd_ops corgi_lcd_ops = { .get_power = corgi_lcd_get_power, .set_power = corgi_lcd_set_power, .set_mode = corgi_lcd_set_mode, }; static int corgi_bl_get_intensity(struct backlight_device *bd) { struct corgi_lcd *lcd = bl_get_data(bd); return lcd->intensity; } static int corgi_bl_set_intensity(struct corgi_lcd *lcd, int intensity) { int cont; if (intensity > 0x10) intensity += 0x10; corgi_ssp_lcdtg_send(lcd, DUTYCTRL_ADRS, intensity); /* Bit 5 via GPIO_BACKLIGHT_CONT */ cont = !!(intensity & 0x20); if (lcd->backlight_cont) gpiod_set_value_cansleep(lcd->backlight_cont, cont); if (lcd->backlight_on) gpiod_set_value_cansleep(lcd->backlight_on, intensity); if (lcd->kick_battery) lcd->kick_battery(); lcd->intensity = intensity; return 0; } static int corgi_bl_update_status(struct backlight_device *bd) { struct corgi_lcd *lcd = bl_get_data(bd); int intensity = backlight_get_brightness(bd); if (corgibl_flags & CORGIBL_SUSPENDED) intensity = 0; if ((corgibl_flags & CORGIBL_BATTLOW) && intensity > lcd->limit_mask) intensity = lcd->limit_mask; return corgi_bl_set_intensity(lcd, intensity); } void corgi_lcd_limit_intensity(int limit) { if (limit) corgibl_flags |= CORGIBL_BATTLOW; else corgibl_flags &= ~CORGIBL_BATTLOW; backlight_update_status(the_corgi_lcd->bl_dev); } EXPORT_SYMBOL(corgi_lcd_limit_intensity); static const struct backlight_ops corgi_bl_ops = { .get_brightness = corgi_bl_get_intensity, .update_status = corgi_bl_update_status, }; #ifdef CONFIG_PM_SLEEP static int corgi_lcd_suspend(struct device *dev) { struct corgi_lcd *lcd = dev_get_drvdata(dev); corgibl_flags |= CORGIBL_SUSPENDED; corgi_bl_set_intensity(lcd, 0); corgi_lcd_set_power(lcd->lcd_dev, FB_BLANK_POWERDOWN); return 0; } static int corgi_lcd_resume(struct device *dev) { struct corgi_lcd *lcd = dev_get_drvdata(dev); corgibl_flags &= ~CORGIBL_SUSPENDED; corgi_lcd_set_power(lcd->lcd_dev, FB_BLANK_UNBLANK); backlight_update_status(lcd->bl_dev); return 0; } #endif static SIMPLE_DEV_PM_OPS(corgi_lcd_pm_ops, corgi_lcd_suspend, corgi_lcd_resume); static int setup_gpio_backlight(struct corgi_lcd *lcd, struct corgi_lcd_platform_data *pdata) { struct spi_device *spi = lcd->spi_dev; lcd->backlight_on = devm_gpiod_get_optional(&spi->dev, "BL_ON", GPIOD_OUT_LOW); if (IS_ERR(lcd->backlight_on)) return PTR_ERR(lcd->backlight_on); lcd->backlight_cont = devm_gpiod_get_optional(&spi->dev, "BL_CONT", GPIOD_OUT_LOW); if (IS_ERR(lcd->backlight_cont)) return PTR_ERR(lcd->backlight_cont); return 0; } static int corgi_lcd_probe(struct spi_device *spi) { struct backlight_properties props; struct corgi_lcd_platform_data *pdata = dev_get_platdata(&spi->dev); struct corgi_lcd *lcd; int ret = 0; if (pdata == NULL) { dev_err(&spi->dev, "platform data not available\n"); return -EINVAL; } lcd = devm_kzalloc(&spi->dev, sizeof(struct corgi_lcd), GFP_KERNEL); if (!lcd) return -ENOMEM; lcd->spi_dev = spi; lcd->lcd_dev = devm_lcd_device_register(&spi->dev, "corgi_lcd", &spi->dev, lcd, &corgi_lcd_ops); if (IS_ERR(lcd->lcd_dev)) return PTR_ERR(lcd->lcd_dev); lcd->power = FB_BLANK_POWERDOWN; lcd->mode = (pdata) ? pdata->init_mode : CORGI_LCD_MODE_VGA; memset(&props, 0, sizeof(struct backlight_properties)); props.type = BACKLIGHT_RAW; props.max_brightness = pdata->max_intensity; lcd->bl_dev = devm_backlight_device_register(&spi->dev, "corgi_bl", &spi->dev, lcd, &corgi_bl_ops, &props); if (IS_ERR(lcd->bl_dev)) return PTR_ERR(lcd->bl_dev); lcd->bl_dev->props.brightness = pdata->default_intensity; lcd->bl_dev->props.power = FB_BLANK_UNBLANK; ret = setup_gpio_backlight(lcd, pdata); if (ret) return ret; lcd->kick_battery = pdata->kick_battery; spi_set_drvdata(spi, lcd); corgi_lcd_set_power(lcd->lcd_dev, FB_BLANK_UNBLANK); backlight_update_status(lcd->bl_dev); lcd->limit_mask = pdata->limit_mask; the_corgi_lcd = lcd; return 0; } static void corgi_lcd_remove(struct spi_device *spi) { struct corgi_lcd *lcd = spi_get_drvdata(spi); lcd->bl_dev->props.power = FB_BLANK_UNBLANK; lcd->bl_dev->props.brightness = 0; backlight_update_status(lcd->bl_dev); corgi_lcd_set_power(lcd->lcd_dev, FB_BLANK_POWERDOWN); } static struct spi_driver corgi_lcd_driver = { .driver = { .name = "corgi-lcd", .pm = &corgi_lcd_pm_ops, }, .probe = corgi_lcd_probe, .remove = corgi_lcd_remove, }; module_spi_driver(corgi_lcd_driver); MODULE_DESCRIPTION("LCD and backlight driver for SHARP C7x0/Cxx00"); MODULE_AUTHOR("Eric Miao <[email protected]>"); MODULE_LICENSE("GPL"); MODULE_ALIAS("spi:corgi-lcd");
linux-master
drivers/video/backlight/corgi_lcd.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Backlight driver for Analog Devices ADP8860 Backlight Devices * * Copyright 2009-2010 Analog Devices Inc. */ #include <linux/module.h> #include <linux/init.h> #include <linux/errno.h> #include <linux/pm.h> #include <linux/platform_device.h> #include <linux/i2c.h> #include <linux/fb.h> #include <linux/backlight.h> #include <linux/leds.h> #include <linux/slab.h> #include <linux/workqueue.h> #include <linux/platform_data/adp8860.h> #define ADP8860_EXT_FEATURES #define ADP8860_USE_LEDS #define ADP8860_MFDVID 0x00 /* Manufacturer and device ID */ #define ADP8860_MDCR 0x01 /* Device mode and status */ #define ADP8860_MDCR2 0x02 /* Device mode and Status Register 2 */ #define ADP8860_INTR_EN 0x03 /* Interrupts enable */ #define ADP8860_CFGR 0x04 /* Configuration register */ #define ADP8860_BLSEN 0x05 /* Sink enable backlight or independent */ #define ADP8860_BLOFF 0x06 /* Backlight off timeout */ #define ADP8860_BLDIM 0x07 /* Backlight dim timeout */ #define ADP8860_BLFR 0x08 /* Backlight fade in and out rates */ #define ADP8860_BLMX1 0x09 /* Backlight (Brightness Level 1-daylight) maximum current */ #define ADP8860_BLDM1 0x0A /* Backlight (Brightness Level 1-daylight) dim current */ #define ADP8860_BLMX2 0x0B /* Backlight (Brightness Level 2-office) maximum current */ #define ADP8860_BLDM2 0x0C /* Backlight (Brightness Level 2-office) dim current */ #define ADP8860_BLMX3 0x0D /* Backlight (Brightness Level 3-dark) maximum current */ #define ADP8860_BLDM3 0x0E /* Backlight (Brightness Level 3-dark) dim current */ #define ADP8860_ISCFR 0x0F /* Independent sink current fade control register */ #define ADP8860_ISCC 0x10 /* Independent sink current control register */ #define ADP8860_ISCT1 0x11 /* Independent Sink Current Timer Register LED[7:5] */ #define ADP8860_ISCT2 0x12 /* Independent Sink Current Timer Register LED[4:1] */ #define ADP8860_ISCF 0x13 /* Independent sink current fade register */ #define ADP8860_ISC7 0x14 /* Independent Sink Current LED7 */ #define ADP8860_ISC6 0x15 /* Independent Sink Current LED6 */ #define ADP8860_ISC5 0x16 /* Independent Sink Current LED5 */ #define ADP8860_ISC4 0x17 /* Independent Sink Current LED4 */ #define ADP8860_ISC3 0x18 /* Independent Sink Current LED3 */ #define ADP8860_ISC2 0x19 /* Independent Sink Current LED2 */ #define ADP8860_ISC1 0x1A /* Independent Sink Current LED1 */ #define ADP8860_CCFG 0x1B /* Comparator configuration */ #define ADP8860_CCFG2 0x1C /* Second comparator configuration */ #define ADP8860_L2_TRP 0x1D /* L2 comparator reference */ #define ADP8860_L2_HYS 0x1E /* L2 hysteresis */ #define ADP8860_L3_TRP 0x1F /* L3 comparator reference */ #define ADP8860_L3_HYS 0x20 /* L3 hysteresis */ #define ADP8860_PH1LEVL 0x21 /* First phototransistor ambient light level-low byte register */ #define ADP8860_PH1LEVH 0x22 /* First phototransistor ambient light level-high byte register */ #define ADP8860_PH2LEVL 0x23 /* Second phototransistor ambient light level-low byte register */ #define ADP8860_PH2LEVH 0x24 /* Second phototransistor ambient light level-high byte register */ #define ADP8860_MANUFID 0x0 /* Analog Devices ADP8860 Manufacturer ID */ #define ADP8861_MANUFID 0x4 /* Analog Devices ADP8861 Manufacturer ID */ #define ADP8863_MANUFID 0x2 /* Analog Devices ADP8863 Manufacturer ID */ #define ADP8860_DEVID(x) ((x) & 0xF) #define ADP8860_MANID(x) ((x) >> 4) /* MDCR Device mode and status */ #define INT_CFG (1 << 6) #define NSTBY (1 << 5) #define DIM_EN (1 << 4) #define GDWN_DIS (1 << 3) #define SIS_EN (1 << 2) #define CMP_AUTOEN (1 << 1) #define BLEN (1 << 0) /* ADP8860_CCFG Main ALS comparator level enable */ #define L3_EN (1 << 1) #define L2_EN (1 << 0) #define CFGR_BLV_SHIFT 3 #define CFGR_BLV_MASK 0x3 #define ADP8860_FLAG_LED_MASK 0xFF #define FADE_VAL(in, out) ((0xF & (in)) | ((0xF & (out)) << 4)) #define BL_CFGR_VAL(law, blv) ((((blv) & CFGR_BLV_MASK) << CFGR_BLV_SHIFT) | ((0x3 & (law)) << 1)) #define ALS_CCFG_VAL(filt) ((0x7 & filt) << 5) enum { adp8860, adp8861, adp8863 }; struct adp8860_led { struct led_classdev cdev; struct work_struct work; struct i2c_client *client; enum led_brightness new_brightness; int id; int flags; }; struct adp8860_bl { struct i2c_client *client; struct backlight_device *bl; struct adp8860_led *led; struct adp8860_backlight_platform_data *pdata; struct mutex lock; unsigned long cached_daylight_max; int id; int revid; int current_brightness; unsigned en_ambl_sens:1; unsigned gdwn_dis:1; }; static int adp8860_read(struct i2c_client *client, int reg, uint8_t *val) { int ret; ret = i2c_smbus_read_byte_data(client, reg); if (ret < 0) { dev_err(&client->dev, "failed reading at 0x%02x\n", reg); return ret; } *val = (uint8_t)ret; return 0; } static int adp8860_write(struct i2c_client *client, u8 reg, u8 val) { return i2c_smbus_write_byte_data(client, reg, val); } static int adp8860_set_bits(struct i2c_client *client, int reg, uint8_t bit_mask) { struct adp8860_bl *data = i2c_get_clientdata(client); uint8_t reg_val; int ret; mutex_lock(&data->lock); ret = adp8860_read(client, reg, &reg_val); if (!ret && ((reg_val & bit_mask) != bit_mask)) { reg_val |= bit_mask; ret = adp8860_write(client, reg, reg_val); } mutex_unlock(&data->lock); return ret; } static int adp8860_clr_bits(struct i2c_client *client, int reg, uint8_t bit_mask) { struct adp8860_bl *data = i2c_get_clientdata(client); uint8_t reg_val; int ret; mutex_lock(&data->lock); ret = adp8860_read(client, reg, &reg_val); if (!ret && (reg_val & bit_mask)) { reg_val &= ~bit_mask; ret = adp8860_write(client, reg, reg_val); } mutex_unlock(&data->lock); return ret; } /* * Independent sink / LED */ #if defined(ADP8860_USE_LEDS) static void adp8860_led_work(struct work_struct *work) { struct adp8860_led *led = container_of(work, struct adp8860_led, work); adp8860_write(led->client, ADP8860_ISC1 - led->id + 1, led->new_brightness >> 1); } static void adp8860_led_set(struct led_classdev *led_cdev, enum led_brightness value) { struct adp8860_led *led; led = container_of(led_cdev, struct adp8860_led, cdev); led->new_brightness = value; schedule_work(&led->work); } static int adp8860_led_setup(struct adp8860_led *led) { struct i2c_client *client = led->client; int ret = 0; ret = adp8860_write(client, ADP8860_ISC1 - led->id + 1, 0); ret |= adp8860_set_bits(client, ADP8860_ISCC, 1 << (led->id - 1)); if (led->id > 4) ret |= adp8860_set_bits(client, ADP8860_ISCT1, (led->flags & 0x3) << ((led->id - 5) * 2)); else ret |= adp8860_set_bits(client, ADP8860_ISCT2, (led->flags & 0x3) << ((led->id - 1) * 2)); return ret; } static int adp8860_led_probe(struct i2c_client *client) { struct adp8860_backlight_platform_data *pdata = dev_get_platdata(&client->dev); struct adp8860_bl *data = i2c_get_clientdata(client); struct adp8860_led *led, *led_dat; struct led_info *cur_led; int ret, i; led = devm_kcalloc(&client->dev, pdata->num_leds, sizeof(*led), GFP_KERNEL); if (led == NULL) return -ENOMEM; ret = adp8860_write(client, ADP8860_ISCFR, pdata->led_fade_law); ret = adp8860_write(client, ADP8860_ISCT1, (pdata->led_on_time & 0x3) << 6); ret |= adp8860_write(client, ADP8860_ISCF, FADE_VAL(pdata->led_fade_in, pdata->led_fade_out)); if (ret) { dev_err(&client->dev, "failed to write\n"); return ret; } for (i = 0; i < pdata->num_leds; ++i) { cur_led = &pdata->leds[i]; led_dat = &led[i]; led_dat->id = cur_led->flags & ADP8860_FLAG_LED_MASK; if (led_dat->id > 7 || led_dat->id < 1) { dev_err(&client->dev, "Invalid LED ID %d\n", led_dat->id); ret = -EINVAL; goto err; } if (pdata->bl_led_assign & (1 << (led_dat->id - 1))) { dev_err(&client->dev, "LED %d used by Backlight\n", led_dat->id); ret = -EBUSY; goto err; } led_dat->cdev.name = cur_led->name; led_dat->cdev.default_trigger = cur_led->default_trigger; led_dat->cdev.brightness_set = adp8860_led_set; led_dat->cdev.brightness = LED_OFF; led_dat->flags = cur_led->flags >> FLAG_OFFT_SHIFT; led_dat->client = client; led_dat->new_brightness = LED_OFF; INIT_WORK(&led_dat->work, adp8860_led_work); ret = led_classdev_register(&client->dev, &led_dat->cdev); if (ret) { dev_err(&client->dev, "failed to register LED %d\n", led_dat->id); goto err; } ret = adp8860_led_setup(led_dat); if (ret) { dev_err(&client->dev, "failed to write\n"); i++; goto err; } } data->led = led; return 0; err: for (i = i - 1; i >= 0; --i) { led_classdev_unregister(&led[i].cdev); cancel_work_sync(&led[i].work); } return ret; } static int adp8860_led_remove(struct i2c_client *client) { struct adp8860_backlight_platform_data *pdata = dev_get_platdata(&client->dev); struct adp8860_bl *data = i2c_get_clientdata(client); int i; for (i = 0; i < pdata->num_leds; i++) { led_classdev_unregister(&data->led[i].cdev); cancel_work_sync(&data->led[i].work); } return 0; } #else static int adp8860_led_probe(struct i2c_client *client) { return 0; } static int adp8860_led_remove(struct i2c_client *client) { return 0; } #endif static int adp8860_bl_set(struct backlight_device *bl, int brightness) { struct adp8860_bl *data = bl_get_data(bl); struct i2c_client *client = data->client; int ret = 0; if (data->en_ambl_sens) { if ((brightness > 0) && (brightness < ADP8860_MAX_BRIGHTNESS)) { /* Disable Ambient Light auto adjust */ ret |= adp8860_clr_bits(client, ADP8860_MDCR, CMP_AUTOEN); ret |= adp8860_write(client, ADP8860_BLMX1, brightness); } else { /* * MAX_BRIGHTNESS -> Enable Ambient Light auto adjust * restore daylight l1 sysfs brightness */ ret |= adp8860_write(client, ADP8860_BLMX1, data->cached_daylight_max); ret |= adp8860_set_bits(client, ADP8860_MDCR, CMP_AUTOEN); } } else ret |= adp8860_write(client, ADP8860_BLMX1, brightness); if (data->current_brightness && brightness == 0) ret |= adp8860_set_bits(client, ADP8860_MDCR, DIM_EN); else if (data->current_brightness == 0 && brightness) ret |= adp8860_clr_bits(client, ADP8860_MDCR, DIM_EN); if (!ret) data->current_brightness = brightness; return ret; } static int adp8860_bl_update_status(struct backlight_device *bl) { return adp8860_bl_set(bl, backlight_get_brightness(bl)); } static int adp8860_bl_get_brightness(struct backlight_device *bl) { struct adp8860_bl *data = bl_get_data(bl); return data->current_brightness; } static const struct backlight_ops adp8860_bl_ops = { .update_status = adp8860_bl_update_status, .get_brightness = adp8860_bl_get_brightness, }; static int adp8860_bl_setup(struct backlight_device *bl) { struct adp8860_bl *data = bl_get_data(bl); struct i2c_client *client = data->client; struct adp8860_backlight_platform_data *pdata = data->pdata; int ret = 0; ret |= adp8860_write(client, ADP8860_BLSEN, ~pdata->bl_led_assign); ret |= adp8860_write(client, ADP8860_BLMX1, pdata->l1_daylight_max); ret |= adp8860_write(client, ADP8860_BLDM1, pdata->l1_daylight_dim); if (data->en_ambl_sens) { data->cached_daylight_max = pdata->l1_daylight_max; ret |= adp8860_write(client, ADP8860_BLMX2, pdata->l2_office_max); ret |= adp8860_write(client, ADP8860_BLDM2, pdata->l2_office_dim); ret |= adp8860_write(client, ADP8860_BLMX3, pdata->l3_dark_max); ret |= adp8860_write(client, ADP8860_BLDM3, pdata->l3_dark_dim); ret |= adp8860_write(client, ADP8860_L2_TRP, pdata->l2_trip); ret |= adp8860_write(client, ADP8860_L2_HYS, pdata->l2_hyst); ret |= adp8860_write(client, ADP8860_L3_TRP, pdata->l3_trip); ret |= adp8860_write(client, ADP8860_L3_HYS, pdata->l3_hyst); ret |= adp8860_write(client, ADP8860_CCFG, L2_EN | L3_EN | ALS_CCFG_VAL(pdata->abml_filt)); } ret |= adp8860_write(client, ADP8860_CFGR, BL_CFGR_VAL(pdata->bl_fade_law, 0)); ret |= adp8860_write(client, ADP8860_BLFR, FADE_VAL(pdata->bl_fade_in, pdata->bl_fade_out)); ret |= adp8860_set_bits(client, ADP8860_MDCR, BLEN | DIM_EN | NSTBY | (data->gdwn_dis ? GDWN_DIS : 0)); return ret; } static ssize_t adp8860_show(struct device *dev, char *buf, int reg) { struct adp8860_bl *data = dev_get_drvdata(dev); int error; uint8_t reg_val; mutex_lock(&data->lock); error = adp8860_read(data->client, reg, &reg_val); mutex_unlock(&data->lock); if (error < 0) return error; return sprintf(buf, "%u\n", reg_val); } static ssize_t adp8860_store(struct device *dev, const char *buf, size_t count, int reg) { struct adp8860_bl *data = dev_get_drvdata(dev); unsigned long val; int ret; ret = kstrtoul(buf, 10, &val); if (ret) return ret; mutex_lock(&data->lock); adp8860_write(data->client, reg, val); mutex_unlock(&data->lock); return count; } static ssize_t adp8860_bl_l3_dark_max_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp8860_show(dev, buf, ADP8860_BLMX3); } static ssize_t adp8860_bl_l3_dark_max_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return adp8860_store(dev, buf, count, ADP8860_BLMX3); } static DEVICE_ATTR(l3_dark_max, 0664, adp8860_bl_l3_dark_max_show, adp8860_bl_l3_dark_max_store); static ssize_t adp8860_bl_l2_office_max_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp8860_show(dev, buf, ADP8860_BLMX2); } static ssize_t adp8860_bl_l2_office_max_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return adp8860_store(dev, buf, count, ADP8860_BLMX2); } static DEVICE_ATTR(l2_office_max, 0664, adp8860_bl_l2_office_max_show, adp8860_bl_l2_office_max_store); static ssize_t adp8860_bl_l1_daylight_max_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp8860_show(dev, buf, ADP8860_BLMX1); } static ssize_t adp8860_bl_l1_daylight_max_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct adp8860_bl *data = dev_get_drvdata(dev); int ret = kstrtoul(buf, 10, &data->cached_daylight_max); if (ret) return ret; return adp8860_store(dev, buf, count, ADP8860_BLMX1); } static DEVICE_ATTR(l1_daylight_max, 0664, adp8860_bl_l1_daylight_max_show, adp8860_bl_l1_daylight_max_store); static ssize_t adp8860_bl_l3_dark_dim_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp8860_show(dev, buf, ADP8860_BLDM3); } static ssize_t adp8860_bl_l3_dark_dim_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return adp8860_store(dev, buf, count, ADP8860_BLDM3); } static DEVICE_ATTR(l3_dark_dim, 0664, adp8860_bl_l3_dark_dim_show, adp8860_bl_l3_dark_dim_store); static ssize_t adp8860_bl_l2_office_dim_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp8860_show(dev, buf, ADP8860_BLDM2); } static ssize_t adp8860_bl_l2_office_dim_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return adp8860_store(dev, buf, count, ADP8860_BLDM2); } static DEVICE_ATTR(l2_office_dim, 0664, adp8860_bl_l2_office_dim_show, adp8860_bl_l2_office_dim_store); static ssize_t adp8860_bl_l1_daylight_dim_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp8860_show(dev, buf, ADP8860_BLDM1); } static ssize_t adp8860_bl_l1_daylight_dim_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return adp8860_store(dev, buf, count, ADP8860_BLDM1); } static DEVICE_ATTR(l1_daylight_dim, 0664, adp8860_bl_l1_daylight_dim_show, adp8860_bl_l1_daylight_dim_store); #ifdef ADP8860_EXT_FEATURES static ssize_t adp8860_bl_ambient_light_level_show(struct device *dev, struct device_attribute *attr, char *buf) { struct adp8860_bl *data = dev_get_drvdata(dev); int error; uint8_t reg_val; uint16_t ret_val; mutex_lock(&data->lock); error = adp8860_read(data->client, ADP8860_PH1LEVL, &reg_val); if (!error) { ret_val = reg_val; error = adp8860_read(data->client, ADP8860_PH1LEVH, &reg_val); } mutex_unlock(&data->lock); if (error) return error; /* Return 13-bit conversion value for the first light sensor */ ret_val += (reg_val & 0x1F) << 8; return sprintf(buf, "%u\n", ret_val); } static DEVICE_ATTR(ambient_light_level, 0444, adp8860_bl_ambient_light_level_show, NULL); static ssize_t adp8860_bl_ambient_light_zone_show(struct device *dev, struct device_attribute *attr, char *buf) { struct adp8860_bl *data = dev_get_drvdata(dev); int error; uint8_t reg_val; mutex_lock(&data->lock); error = adp8860_read(data->client, ADP8860_CFGR, &reg_val); mutex_unlock(&data->lock); if (error < 0) return error; return sprintf(buf, "%u\n", ((reg_val >> CFGR_BLV_SHIFT) & CFGR_BLV_MASK) + 1); } static ssize_t adp8860_bl_ambient_light_zone_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct adp8860_bl *data = dev_get_drvdata(dev); unsigned long val; uint8_t reg_val; int ret; ret = kstrtoul(buf, 10, &val); if (ret) return ret; if (val == 0) { /* Enable automatic ambient light sensing */ adp8860_set_bits(data->client, ADP8860_MDCR, CMP_AUTOEN); } else if ((val > 0) && (val <= 3)) { /* Disable automatic ambient light sensing */ adp8860_clr_bits(data->client, ADP8860_MDCR, CMP_AUTOEN); /* Set user supplied ambient light zone */ mutex_lock(&data->lock); ret = adp8860_read(data->client, ADP8860_CFGR, &reg_val); if (!ret) { reg_val &= ~(CFGR_BLV_MASK << CFGR_BLV_SHIFT); reg_val |= (val - 1) << CFGR_BLV_SHIFT; adp8860_write(data->client, ADP8860_CFGR, reg_val); } mutex_unlock(&data->lock); } return count; } static DEVICE_ATTR(ambient_light_zone, 0664, adp8860_bl_ambient_light_zone_show, adp8860_bl_ambient_light_zone_store); #endif static struct attribute *adp8860_bl_attributes[] = { &dev_attr_l3_dark_max.attr, &dev_attr_l3_dark_dim.attr, &dev_attr_l2_office_max.attr, &dev_attr_l2_office_dim.attr, &dev_attr_l1_daylight_max.attr, &dev_attr_l1_daylight_dim.attr, #ifdef ADP8860_EXT_FEATURES &dev_attr_ambient_light_level.attr, &dev_attr_ambient_light_zone.attr, #endif NULL }; static const struct attribute_group adp8860_bl_attr_group = { .attrs = adp8860_bl_attributes, }; static int adp8860_probe(struct i2c_client *client) { const struct i2c_device_id *id = i2c_client_get_device_id(client); struct backlight_device *bl; struct adp8860_bl *data; struct adp8860_backlight_platform_data *pdata = dev_get_platdata(&client->dev); struct backlight_properties props; uint8_t reg_val; int ret; if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA)) { dev_err(&client->dev, "SMBUS Byte Data not Supported\n"); return -EIO; } if (!pdata) { dev_err(&client->dev, "no platform data?\n"); return -EINVAL; } data = devm_kzalloc(&client->dev, sizeof(*data), GFP_KERNEL); if (data == NULL) return -ENOMEM; ret = adp8860_read(client, ADP8860_MFDVID, &reg_val); if (ret < 0) return ret; switch (ADP8860_MANID(reg_val)) { case ADP8863_MANUFID: data->gdwn_dis = !!pdata->gdwn_dis; fallthrough; case ADP8860_MANUFID: data->en_ambl_sens = !!pdata->en_ambl_sens; break; case ADP8861_MANUFID: data->gdwn_dis = !!pdata->gdwn_dis; break; default: dev_err(&client->dev, "failed to probe\n"); return -ENODEV; } /* It's confirmed that the DEVID field is actually a REVID */ data->revid = ADP8860_DEVID(reg_val); data->client = client; data->pdata = pdata; data->id = id->driver_data; data->current_brightness = 0; i2c_set_clientdata(client, data); memset(&props, 0, sizeof(props)); props.type = BACKLIGHT_RAW; props.max_brightness = ADP8860_MAX_BRIGHTNESS; mutex_init(&data->lock); bl = devm_backlight_device_register(&client->dev, dev_driver_string(&client->dev), &client->dev, data, &adp8860_bl_ops, &props); if (IS_ERR(bl)) { dev_err(&client->dev, "failed to register backlight\n"); return PTR_ERR(bl); } bl->props.brightness = ADP8860_MAX_BRIGHTNESS; data->bl = bl; if (data->en_ambl_sens) ret = sysfs_create_group(&bl->dev.kobj, &adp8860_bl_attr_group); if (ret) { dev_err(&client->dev, "failed to register sysfs\n"); return ret; } ret = adp8860_bl_setup(bl); if (ret) { ret = -EIO; goto out; } backlight_update_status(bl); dev_info(&client->dev, "%s Rev.%d Backlight\n", client->name, data->revid); if (pdata->num_leds) adp8860_led_probe(client); return 0; out: if (data->en_ambl_sens) sysfs_remove_group(&data->bl->dev.kobj, &adp8860_bl_attr_group); return ret; } static void adp8860_remove(struct i2c_client *client) { struct adp8860_bl *data = i2c_get_clientdata(client); adp8860_clr_bits(client, ADP8860_MDCR, NSTBY); if (data->led) adp8860_led_remove(client); if (data->en_ambl_sens) sysfs_remove_group(&data->bl->dev.kobj, &adp8860_bl_attr_group); } #ifdef CONFIG_PM_SLEEP static int adp8860_i2c_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); adp8860_clr_bits(client, ADP8860_MDCR, NSTBY); return 0; } static int adp8860_i2c_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); adp8860_set_bits(client, ADP8860_MDCR, NSTBY | BLEN); return 0; } #endif static SIMPLE_DEV_PM_OPS(adp8860_i2c_pm_ops, adp8860_i2c_suspend, adp8860_i2c_resume); static const struct i2c_device_id adp8860_id[] = { { "adp8860", adp8860 }, { "adp8861", adp8861 }, { "adp8863", adp8863 }, { } }; MODULE_DEVICE_TABLE(i2c, adp8860_id); static struct i2c_driver adp8860_driver = { .driver = { .name = KBUILD_MODNAME, .pm = &adp8860_i2c_pm_ops, }, .probe = adp8860_probe, .remove = adp8860_remove, .id_table = adp8860_id, }; module_i2c_driver(adp8860_driver); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Michael Hennerich <[email protected]>"); MODULE_DESCRIPTION("ADP8860 Backlight driver");
linux-master
drivers/video/backlight/adp8860_bl.c
// SPDX-License-Identifier: GPL-2.0-only /* * Backlight driver for Marvell Semiconductor 88PM8606 * * Copyright (C) 2009 Marvell International Ltd. * Haojian Zhuang <[email protected]> */ #include <linux/init.h> #include <linux/kernel.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/fb.h> #include <linux/i2c.h> #include <linux/backlight.h> #include <linux/mfd/88pm860x.h> #include <linux/module.h> #define MAX_BRIGHTNESS (0xFF) #define MIN_BRIGHTNESS (0) #define CURRENT_BITMASK (0x1F << 1) struct pm860x_backlight_data { struct pm860x_chip *chip; struct i2c_client *i2c; int current_brightness; int port; int pwm; int iset; int reg_duty_cycle; int reg_always_on; int reg_current; }; static int backlight_power_set(struct pm860x_chip *chip, int port, int on) { int ret = -EINVAL; switch (port) { case 0: ret = on ? pm8606_osc_enable(chip, WLED1_DUTY) : pm8606_osc_disable(chip, WLED1_DUTY); break; case 1: ret = on ? pm8606_osc_enable(chip, WLED2_DUTY) : pm8606_osc_disable(chip, WLED2_DUTY); break; case 2: ret = on ? pm8606_osc_enable(chip, WLED3_DUTY) : pm8606_osc_disable(chip, WLED3_DUTY); break; } return ret; } static int pm860x_backlight_set(struct backlight_device *bl, int brightness) { struct pm860x_backlight_data *data = bl_get_data(bl); struct pm860x_chip *chip = data->chip; unsigned char value; int ret; if (brightness > MAX_BRIGHTNESS) value = MAX_BRIGHTNESS; else value = brightness; if (brightness) backlight_power_set(chip, data->port, 1); ret = pm860x_reg_write(data->i2c, data->reg_duty_cycle, value); if (ret < 0) goto out; if ((data->current_brightness == 0) && brightness) { if (data->iset) { ret = pm860x_set_bits(data->i2c, data->reg_current, CURRENT_BITMASK, data->iset); if (ret < 0) goto out; } if (data->pwm) { ret = pm860x_set_bits(data->i2c, PM8606_PWM, PM8606_PWM_FREQ_MASK, data->pwm); if (ret < 0) goto out; } if (brightness == MAX_BRIGHTNESS) { /* set WLED_ON bit as 100% */ ret = pm860x_set_bits(data->i2c, data->reg_always_on, PM8606_WLED_ON, PM8606_WLED_ON); } } else { if (brightness == MAX_BRIGHTNESS) { /* set WLED_ON bit as 100% */ ret = pm860x_set_bits(data->i2c, data->reg_always_on, PM8606_WLED_ON, PM8606_WLED_ON); } else { /* clear WLED_ON bit since it's not 100% */ ret = pm860x_set_bits(data->i2c, data->reg_always_on, PM8606_WLED_ON, 0); } } if (ret < 0) goto out; if (brightness == 0) backlight_power_set(chip, data->port, 0); dev_dbg(chip->dev, "set brightness %d\n", value); data->current_brightness = value; return 0; out: dev_dbg(chip->dev, "set brightness %d failure with return value: %d\n", value, ret); return ret; } static int pm860x_backlight_update_status(struct backlight_device *bl) { return pm860x_backlight_set(bl, backlight_get_brightness(bl)); } static int pm860x_backlight_get_brightness(struct backlight_device *bl) { struct pm860x_backlight_data *data = bl_get_data(bl); struct pm860x_chip *chip = data->chip; int ret; ret = pm860x_reg_read(data->i2c, data->reg_duty_cycle); if (ret < 0) goto out; data->current_brightness = ret; dev_dbg(chip->dev, "get brightness %d\n", data->current_brightness); return data->current_brightness; out: return -EINVAL; } static const struct backlight_ops pm860x_backlight_ops = { .options = BL_CORE_SUSPENDRESUME, .update_status = pm860x_backlight_update_status, .get_brightness = pm860x_backlight_get_brightness, }; #ifdef CONFIG_OF static int pm860x_backlight_dt_init(struct platform_device *pdev, struct pm860x_backlight_data *data, char *name) { struct device_node *nproot, *np; int iset = 0; nproot = of_get_child_by_name(pdev->dev.parent->of_node, "backlights"); if (!nproot) { dev_err(&pdev->dev, "failed to find backlights node\n"); return -ENODEV; } for_each_child_of_node(nproot, np) { if (of_node_name_eq(np, name)) { of_property_read_u32(np, "marvell,88pm860x-iset", &iset); data->iset = PM8606_WLED_CURRENT(iset); of_property_read_u32(np, "marvell,88pm860x-pwm", &data->pwm); of_node_put(np); break; } } of_node_put(nproot); return 0; } #else #define pm860x_backlight_dt_init(x, y, z) (-1) #endif static int pm860x_backlight_probe(struct platform_device *pdev) { struct pm860x_chip *chip = dev_get_drvdata(pdev->dev.parent); struct pm860x_backlight_pdata *pdata = dev_get_platdata(&pdev->dev); struct pm860x_backlight_data *data; struct backlight_device *bl; struct resource *res; struct backlight_properties props; char name[MFD_NAME_SIZE]; int ret = 0; data = devm_kzalloc(&pdev->dev, sizeof(struct pm860x_backlight_data), GFP_KERNEL); if (data == NULL) return -ENOMEM; res = platform_get_resource_byname(pdev, IORESOURCE_REG, "duty cycle"); if (!res) { dev_err(&pdev->dev, "No REG resource for duty cycle\n"); return -ENXIO; } data->reg_duty_cycle = res->start; res = platform_get_resource_byname(pdev, IORESOURCE_REG, "always on"); if (!res) { dev_err(&pdev->dev, "No REG resource for always on\n"); return -ENXIO; } data->reg_always_on = res->start; res = platform_get_resource_byname(pdev, IORESOURCE_REG, "current"); if (!res) { dev_err(&pdev->dev, "No REG resource for current\n"); return -ENXIO; } data->reg_current = res->start; memset(name, 0, MFD_NAME_SIZE); sprintf(name, "backlight-%d", pdev->id); data->port = pdev->id; data->chip = chip; data->i2c = (chip->id == CHIP_PM8606) ? chip->client : chip->companion; data->current_brightness = MAX_BRIGHTNESS; if (pm860x_backlight_dt_init(pdev, data, name)) { if (pdata) { data->pwm = pdata->pwm; data->iset = pdata->iset; } } memset(&props, 0, sizeof(struct backlight_properties)); props.type = BACKLIGHT_RAW; props.max_brightness = MAX_BRIGHTNESS; bl = devm_backlight_device_register(&pdev->dev, name, &pdev->dev, data, &pm860x_backlight_ops, &props); if (IS_ERR(bl)) { dev_err(&pdev->dev, "failed to register backlight\n"); return PTR_ERR(bl); } bl->props.brightness = MAX_BRIGHTNESS; platform_set_drvdata(pdev, bl); /* read current backlight */ ret = pm860x_backlight_get_brightness(bl); if (ret < 0) return ret; backlight_update_status(bl); return 0; } static struct platform_driver pm860x_backlight_driver = { .driver = { .name = "88pm860x-backlight", }, .probe = pm860x_backlight_probe, }; module_platform_driver(pm860x_backlight_driver); MODULE_DESCRIPTION("Backlight Driver for Marvell Semiconductor 88PM8606"); MODULE_AUTHOR("Haojian Zhuang <[email protected]>"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:88pm860x-backlight");
linux-master
drivers/video/backlight/88pm860x_bl.c
// SPDX-License-Identifier: GPL-2.0-only /* * Backlight Driver for the KB3886 Backlight * * Copyright (c) 2007-2008 Claudio Nieder * * Based on corgi_bl.c by Richard Purdie and kb3886 driver by Robert Woerle */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/mutex.h> #include <linux/fb.h> #include <linux/backlight.h> #include <linux/delay.h> #include <linux/dmi.h> #define KB3886_PARENT 0x64 #define KB3886_IO 0x60 #define KB3886_ADC_DAC_PWM 0xC4 #define KB3886_PWM0_WRITE 0x81 #define KB3886_PWM0_READ 0x41 static DEFINE_MUTEX(bl_mutex); static void kb3886_bl_set_intensity(int intensity) { mutex_lock(&bl_mutex); intensity = intensity&0xff; outb(KB3886_ADC_DAC_PWM, KB3886_PARENT); usleep_range(10000, 11000); outb(KB3886_PWM0_WRITE, KB3886_IO); usleep_range(10000, 11000); outb(intensity, KB3886_IO); mutex_unlock(&bl_mutex); } struct kb3886bl_machinfo { int max_intensity; int default_intensity; int limit_mask; void (*set_bl_intensity)(int intensity); }; static struct kb3886bl_machinfo kb3886_bl_machinfo = { .max_intensity = 0xff, .default_intensity = 0xa0, .limit_mask = 0x7f, .set_bl_intensity = kb3886_bl_set_intensity, }; static struct platform_device kb3886bl_device = { .name = "kb3886-bl", .dev = { .platform_data = &kb3886_bl_machinfo, }, .id = -1, }; static struct platform_device *devices[] __initdata = { &kb3886bl_device, }; /* * Back to driver */ static int kb3886bl_intensity; static struct backlight_device *kb3886_backlight_device; static struct kb3886bl_machinfo *bl_machinfo; static unsigned long kb3886bl_flags; #define KB3886BL_SUSPENDED 0x01 static const struct dmi_system_id kb3886bl_device_table[] __initconst = { { .ident = "Sahara Touch-iT", .matches = { DMI_MATCH(DMI_SYS_VENDOR, "SDV"), DMI_MATCH(DMI_PRODUCT_NAME, "iTouch T201"), }, }, { } }; static int kb3886bl_send_intensity(struct backlight_device *bd) { int intensity = backlight_get_brightness(bd); if (kb3886bl_flags & KB3886BL_SUSPENDED) intensity = 0; bl_machinfo->set_bl_intensity(intensity); kb3886bl_intensity = intensity; return 0; } #ifdef CONFIG_PM_SLEEP static int kb3886bl_suspend(struct device *dev) { struct backlight_device *bd = dev_get_drvdata(dev); kb3886bl_flags |= KB3886BL_SUSPENDED; backlight_update_status(bd); return 0; } static int kb3886bl_resume(struct device *dev) { struct backlight_device *bd = dev_get_drvdata(dev); kb3886bl_flags &= ~KB3886BL_SUSPENDED; backlight_update_status(bd); return 0; } #endif static SIMPLE_DEV_PM_OPS(kb3886bl_pm_ops, kb3886bl_suspend, kb3886bl_resume); static int kb3886bl_get_intensity(struct backlight_device *bd) { return kb3886bl_intensity; } static const struct backlight_ops kb3886bl_ops = { .get_brightness = kb3886bl_get_intensity, .update_status = kb3886bl_send_intensity, }; static int kb3886bl_probe(struct platform_device *pdev) { struct backlight_properties props; struct kb3886bl_machinfo *machinfo = dev_get_platdata(&pdev->dev); bl_machinfo = machinfo; if (!machinfo->limit_mask) machinfo->limit_mask = -1; memset(&props, 0, sizeof(struct backlight_properties)); props.type = BACKLIGHT_RAW; props.max_brightness = machinfo->max_intensity; kb3886_backlight_device = devm_backlight_device_register(&pdev->dev, "kb3886-bl", &pdev->dev, NULL, &kb3886bl_ops, &props); if (IS_ERR(kb3886_backlight_device)) return PTR_ERR(kb3886_backlight_device); platform_set_drvdata(pdev, kb3886_backlight_device); kb3886_backlight_device->props.power = FB_BLANK_UNBLANK; kb3886_backlight_device->props.brightness = machinfo->default_intensity; backlight_update_status(kb3886_backlight_device); return 0; } static struct platform_driver kb3886bl_driver = { .probe = kb3886bl_probe, .driver = { .name = "kb3886-bl", .pm = &kb3886bl_pm_ops, }, }; static int __init kb3886_init(void) { if (!dmi_check_system(kb3886bl_device_table)) return -ENODEV; platform_add_devices(devices, ARRAY_SIZE(devices)); return platform_driver_register(&kb3886bl_driver); } static void __exit kb3886_exit(void) { platform_driver_unregister(&kb3886bl_driver); } module_init(kb3886_init); module_exit(kb3886_exit); MODULE_AUTHOR("Claudio Nieder <[email protected]>"); MODULE_DESCRIPTION("Tabletkiosk Sahara Touch-iT Backlight Driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("dmi:*:svnSDV:pniTouchT201:*");
linux-master
drivers/video/backlight/kb3886_bl.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Backlight driver for Analog Devices ADP5520/ADP5501 MFD PMICs * * Copyright 2009 Analog Devices Inc. */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/fb.h> #include <linux/backlight.h> #include <linux/mfd/adp5520.h> #include <linux/slab.h> #include <linux/module.h> struct adp5520_bl { struct device *master; struct adp5520_backlight_platform_data *pdata; struct mutex lock; unsigned long cached_daylight_max; int id; int current_brightness; }; static int adp5520_bl_set(struct backlight_device *bl, int brightness) { struct adp5520_bl *data = bl_get_data(bl); struct device *master = data->master; int ret = 0; if (data->pdata->en_ambl_sens) { if ((brightness > 0) && (brightness < ADP5020_MAX_BRIGHTNESS)) { /* Disable Ambient Light auto adjust */ ret |= adp5520_clr_bits(master, ADP5520_BL_CONTROL, ADP5520_BL_AUTO_ADJ); ret |= adp5520_write(master, ADP5520_DAYLIGHT_MAX, brightness); } else { /* * MAX_BRIGHTNESS -> Enable Ambient Light auto adjust * restore daylight l3 sysfs brightness */ ret |= adp5520_write(master, ADP5520_DAYLIGHT_MAX, data->cached_daylight_max); ret |= adp5520_set_bits(master, ADP5520_BL_CONTROL, ADP5520_BL_AUTO_ADJ); } } else { ret |= adp5520_write(master, ADP5520_DAYLIGHT_MAX, brightness); } if (data->current_brightness && brightness == 0) ret |= adp5520_set_bits(master, ADP5520_MODE_STATUS, ADP5520_DIM_EN); else if (data->current_brightness == 0 && brightness) ret |= adp5520_clr_bits(master, ADP5520_MODE_STATUS, ADP5520_DIM_EN); if (!ret) data->current_brightness = brightness; return ret; } static int adp5520_bl_update_status(struct backlight_device *bl) { return adp5520_bl_set(bl, backlight_get_brightness(bl)); } static int adp5520_bl_get_brightness(struct backlight_device *bl) { struct adp5520_bl *data = bl_get_data(bl); int error; uint8_t reg_val; error = adp5520_read(data->master, ADP5520_BL_VALUE, &reg_val); return error ? data->current_brightness : reg_val; } static const struct backlight_ops adp5520_bl_ops = { .update_status = adp5520_bl_update_status, .get_brightness = adp5520_bl_get_brightness, }; static int adp5520_bl_setup(struct backlight_device *bl) { struct adp5520_bl *data = bl_get_data(bl); struct device *master = data->master; struct adp5520_backlight_platform_data *pdata = data->pdata; int ret = 0; ret |= adp5520_write(master, ADP5520_DAYLIGHT_MAX, pdata->l1_daylight_max); ret |= adp5520_write(master, ADP5520_DAYLIGHT_DIM, pdata->l1_daylight_dim); if (pdata->en_ambl_sens) { data->cached_daylight_max = pdata->l1_daylight_max; ret |= adp5520_write(master, ADP5520_OFFICE_MAX, pdata->l2_office_max); ret |= adp5520_write(master, ADP5520_OFFICE_DIM, pdata->l2_office_dim); ret |= adp5520_write(master, ADP5520_DARK_MAX, pdata->l3_dark_max); ret |= adp5520_write(master, ADP5520_DARK_DIM, pdata->l3_dark_dim); ret |= adp5520_write(master, ADP5520_L2_TRIP, pdata->l2_trip); ret |= adp5520_write(master, ADP5520_L2_HYS, pdata->l2_hyst); ret |= adp5520_write(master, ADP5520_L3_TRIP, pdata->l3_trip); ret |= adp5520_write(master, ADP5520_L3_HYS, pdata->l3_hyst); ret |= adp5520_write(master, ADP5520_ALS_CMPR_CFG, ALS_CMPR_CFG_VAL(pdata->abml_filt, ADP5520_L3_EN)); } ret |= adp5520_write(master, ADP5520_BL_CONTROL, BL_CTRL_VAL(pdata->fade_led_law, pdata->en_ambl_sens)); ret |= adp5520_write(master, ADP5520_BL_FADE, FADE_VAL(pdata->fade_in, pdata->fade_out)); ret |= adp5520_set_bits(master, ADP5520_MODE_STATUS, ADP5520_BL_EN | ADP5520_DIM_EN); return ret; } static ssize_t adp5520_show(struct device *dev, char *buf, int reg) { struct adp5520_bl *data = dev_get_drvdata(dev); int ret; uint8_t reg_val; mutex_lock(&data->lock); ret = adp5520_read(data->master, reg, &reg_val); mutex_unlock(&data->lock); if (ret < 0) return ret; return sprintf(buf, "%u\n", reg_val); } static ssize_t adp5520_store(struct device *dev, const char *buf, size_t count, int reg) { struct adp5520_bl *data = dev_get_drvdata(dev); unsigned long val; int ret; ret = kstrtoul(buf, 10, &val); if (ret) return ret; mutex_lock(&data->lock); adp5520_write(data->master, reg, val); mutex_unlock(&data->lock); return count; } static ssize_t adp5520_bl_dark_max_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp5520_show(dev, buf, ADP5520_DARK_MAX); } static ssize_t adp5520_bl_dark_max_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return adp5520_store(dev, buf, count, ADP5520_DARK_MAX); } static DEVICE_ATTR(dark_max, 0664, adp5520_bl_dark_max_show, adp5520_bl_dark_max_store); static ssize_t adp5520_bl_office_max_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp5520_show(dev, buf, ADP5520_OFFICE_MAX); } static ssize_t adp5520_bl_office_max_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return adp5520_store(dev, buf, count, ADP5520_OFFICE_MAX); } static DEVICE_ATTR(office_max, 0664, adp5520_bl_office_max_show, adp5520_bl_office_max_store); static ssize_t adp5520_bl_daylight_max_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp5520_show(dev, buf, ADP5520_DAYLIGHT_MAX); } static ssize_t adp5520_bl_daylight_max_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct adp5520_bl *data = dev_get_drvdata(dev); int ret; ret = kstrtoul(buf, 10, &data->cached_daylight_max); if (ret < 0) return ret; return adp5520_store(dev, buf, count, ADP5520_DAYLIGHT_MAX); } static DEVICE_ATTR(daylight_max, 0664, adp5520_bl_daylight_max_show, adp5520_bl_daylight_max_store); static ssize_t adp5520_bl_dark_dim_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp5520_show(dev, buf, ADP5520_DARK_DIM); } static ssize_t adp5520_bl_dark_dim_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return adp5520_store(dev, buf, count, ADP5520_DARK_DIM); } static DEVICE_ATTR(dark_dim, 0664, adp5520_bl_dark_dim_show, adp5520_bl_dark_dim_store); static ssize_t adp5520_bl_office_dim_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp5520_show(dev, buf, ADP5520_OFFICE_DIM); } static ssize_t adp5520_bl_office_dim_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return adp5520_store(dev, buf, count, ADP5520_OFFICE_DIM); } static DEVICE_ATTR(office_dim, 0664, adp5520_bl_office_dim_show, adp5520_bl_office_dim_store); static ssize_t adp5520_bl_daylight_dim_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp5520_show(dev, buf, ADP5520_DAYLIGHT_DIM); } static ssize_t adp5520_bl_daylight_dim_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return adp5520_store(dev, buf, count, ADP5520_DAYLIGHT_DIM); } static DEVICE_ATTR(daylight_dim, 0664, adp5520_bl_daylight_dim_show, adp5520_bl_daylight_dim_store); static struct attribute *adp5520_bl_attributes[] = { &dev_attr_dark_max.attr, &dev_attr_dark_dim.attr, &dev_attr_office_max.attr, &dev_attr_office_dim.attr, &dev_attr_daylight_max.attr, &dev_attr_daylight_dim.attr, NULL }; static const struct attribute_group adp5520_bl_attr_group = { .attrs = adp5520_bl_attributes, }; static int adp5520_bl_probe(struct platform_device *pdev) { struct backlight_properties props; struct backlight_device *bl; struct adp5520_bl *data; int ret = 0; data = devm_kzalloc(&pdev->dev, sizeof(*data), GFP_KERNEL); if (data == NULL) return -ENOMEM; data->master = pdev->dev.parent; data->pdata = dev_get_platdata(&pdev->dev); if (data->pdata == NULL) { dev_err(&pdev->dev, "missing platform data\n"); return -ENODEV; } data->id = pdev->id; data->current_brightness = 0; mutex_init(&data->lock); memset(&props, 0, sizeof(struct backlight_properties)); props.type = BACKLIGHT_RAW; props.max_brightness = ADP5020_MAX_BRIGHTNESS; bl = devm_backlight_device_register(&pdev->dev, pdev->name, data->master, data, &adp5520_bl_ops, &props); if (IS_ERR(bl)) { dev_err(&pdev->dev, "failed to register backlight\n"); return PTR_ERR(bl); } bl->props.brightness = ADP5020_MAX_BRIGHTNESS; if (data->pdata->en_ambl_sens) ret = sysfs_create_group(&bl->dev.kobj, &adp5520_bl_attr_group); if (ret) { dev_err(&pdev->dev, "failed to register sysfs\n"); return ret; } platform_set_drvdata(pdev, bl); ret = adp5520_bl_setup(bl); if (ret) { dev_err(&pdev->dev, "failed to setup\n"); if (data->pdata->en_ambl_sens) sysfs_remove_group(&bl->dev.kobj, &adp5520_bl_attr_group); return ret; } backlight_update_status(bl); return 0; } static void adp5520_bl_remove(struct platform_device *pdev) { struct backlight_device *bl = platform_get_drvdata(pdev); struct adp5520_bl *data = bl_get_data(bl); adp5520_clr_bits(data->master, ADP5520_MODE_STATUS, ADP5520_BL_EN); if (data->pdata->en_ambl_sens) sysfs_remove_group(&bl->dev.kobj, &adp5520_bl_attr_group); } #ifdef CONFIG_PM_SLEEP static int adp5520_bl_suspend(struct device *dev) { struct backlight_device *bl = dev_get_drvdata(dev); return adp5520_bl_set(bl, 0); } static int adp5520_bl_resume(struct device *dev) { struct backlight_device *bl = dev_get_drvdata(dev); backlight_update_status(bl); return 0; } #endif static SIMPLE_DEV_PM_OPS(adp5520_bl_pm_ops, adp5520_bl_suspend, adp5520_bl_resume); static struct platform_driver adp5520_bl_driver = { .driver = { .name = "adp5520-backlight", .pm = &adp5520_bl_pm_ops, }, .probe = adp5520_bl_probe, .remove_new = adp5520_bl_remove, }; module_platform_driver(adp5520_bl_driver); MODULE_AUTHOR("Michael Hennerich <[email protected]>"); MODULE_DESCRIPTION("ADP5520(01) Backlight Driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:adp5520-backlight");
linux-master
drivers/video/backlight/adp5520_bl.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * ams369fg06 AMOLED LCD panel driver. * * Copyright (c) 2011 Samsung Electronics Co., Ltd. * Author: Jingoo Han <[email protected]> * * Derived from drivers/video/s6e63m0.c */ #include <linux/backlight.h> #include <linux/delay.h> #include <linux/fb.h> #include <linux/lcd.h> #include <linux/module.h> #include <linux/spi/spi.h> #include <linux/wait.h> #define SLEEPMSEC 0x1000 #define ENDDEF 0x2000 #define DEFMASK 0xFF00 #define COMMAND_ONLY 0xFE #define DATA_ONLY 0xFF #define MAX_GAMMA_LEVEL 5 #define GAMMA_TABLE_COUNT 21 #define MIN_BRIGHTNESS 0 #define MAX_BRIGHTNESS 255 #define DEFAULT_BRIGHTNESS 150 struct ams369fg06 { struct device *dev; struct spi_device *spi; unsigned int power; struct lcd_device *ld; struct backlight_device *bd; struct lcd_platform_data *lcd_pd; }; static const unsigned short seq_display_on[] = { 0x14, 0x03, ENDDEF, 0x0000 }; static const unsigned short seq_display_off[] = { 0x14, 0x00, ENDDEF, 0x0000 }; static const unsigned short seq_stand_by_on[] = { 0x1D, 0xA1, SLEEPMSEC, 200, ENDDEF, 0x0000 }; static const unsigned short seq_stand_by_off[] = { 0x1D, 0xA0, SLEEPMSEC, 250, ENDDEF, 0x0000 }; static const unsigned short seq_setting[] = { 0x31, 0x08, 0x32, 0x14, 0x30, 0x02, 0x27, 0x01, 0x12, 0x08, 0x13, 0x08, 0x15, 0x00, 0x16, 0x00, 0xef, 0xd0, DATA_ONLY, 0xe8, 0x39, 0x44, 0x40, 0x00, 0x41, 0x3f, 0x42, 0x2a, 0x43, 0x27, 0x44, 0x27, 0x45, 0x1f, 0x46, 0x44, 0x50, 0x00, 0x51, 0x00, 0x52, 0x17, 0x53, 0x24, 0x54, 0x26, 0x55, 0x1f, 0x56, 0x43, 0x60, 0x00, 0x61, 0x3f, 0x62, 0x2a, 0x63, 0x25, 0x64, 0x24, 0x65, 0x1b, 0x66, 0x5c, 0x17, 0x22, 0x18, 0x33, 0x19, 0x03, 0x1a, 0x01, 0x22, 0xa4, 0x23, 0x00, 0x26, 0xa0, 0x1d, 0xa0, SLEEPMSEC, 300, 0x14, 0x03, ENDDEF, 0x0000 }; /* gamma value: 2.2 */ static const unsigned int ams369fg06_22_250[] = { 0x00, 0x3f, 0x2a, 0x27, 0x27, 0x1f, 0x44, 0x00, 0x00, 0x17, 0x24, 0x26, 0x1f, 0x43, 0x00, 0x3f, 0x2a, 0x25, 0x24, 0x1b, 0x5c, }; static const unsigned int ams369fg06_22_200[] = { 0x00, 0x3f, 0x28, 0x29, 0x27, 0x21, 0x3e, 0x00, 0x00, 0x10, 0x25, 0x27, 0x20, 0x3d, 0x00, 0x3f, 0x28, 0x27, 0x25, 0x1d, 0x53, }; static const unsigned int ams369fg06_22_150[] = { 0x00, 0x3f, 0x2d, 0x29, 0x28, 0x23, 0x37, 0x00, 0x00, 0x0b, 0x25, 0x28, 0x22, 0x36, 0x00, 0x3f, 0x2b, 0x28, 0x26, 0x1f, 0x4a, }; static const unsigned int ams369fg06_22_100[] = { 0x00, 0x3f, 0x30, 0x2a, 0x2b, 0x24, 0x2f, 0x00, 0x00, 0x00, 0x25, 0x29, 0x24, 0x2e, 0x00, 0x3f, 0x2f, 0x29, 0x29, 0x21, 0x3f, }; static const unsigned int ams369fg06_22_50[] = { 0x00, 0x3f, 0x3c, 0x2c, 0x2d, 0x27, 0x24, 0x00, 0x00, 0x00, 0x22, 0x2a, 0x27, 0x23, 0x00, 0x3f, 0x3b, 0x2c, 0x2b, 0x24, 0x31, }; struct ams369fg06_gamma { unsigned int *gamma_22_table[MAX_GAMMA_LEVEL]; }; static struct ams369fg06_gamma gamma_table = { .gamma_22_table[0] = (unsigned int *)&ams369fg06_22_50, .gamma_22_table[1] = (unsigned int *)&ams369fg06_22_100, .gamma_22_table[2] = (unsigned int *)&ams369fg06_22_150, .gamma_22_table[3] = (unsigned int *)&ams369fg06_22_200, .gamma_22_table[4] = (unsigned int *)&ams369fg06_22_250, }; static int ams369fg06_spi_write_byte(struct ams369fg06 *lcd, int addr, int data) { u16 buf[1]; struct spi_message msg; struct spi_transfer xfer = { .len = 2, .tx_buf = buf, }; buf[0] = (addr << 8) | data; spi_message_init(&msg); spi_message_add_tail(&xfer, &msg); return spi_sync(lcd->spi, &msg); } static int ams369fg06_spi_write(struct ams369fg06 *lcd, unsigned char address, unsigned char command) { int ret = 0; if (address != DATA_ONLY) ret = ams369fg06_spi_write_byte(lcd, 0x70, address); if (command != COMMAND_ONLY) ret = ams369fg06_spi_write_byte(lcd, 0x72, command); return ret; } static int ams369fg06_panel_send_sequence(struct ams369fg06 *lcd, const unsigned short *wbuf) { int ret = 0, i = 0; while ((wbuf[i] & DEFMASK) != ENDDEF) { if ((wbuf[i] & DEFMASK) != SLEEPMSEC) { ret = ams369fg06_spi_write(lcd, wbuf[i], wbuf[i+1]); if (ret) break; } else { msleep(wbuf[i+1]); } i += 2; } return ret; } static int _ams369fg06_gamma_ctl(struct ams369fg06 *lcd, const unsigned int *gamma) { unsigned int i = 0; int ret = 0; for (i = 0 ; i < GAMMA_TABLE_COUNT / 3; i++) { ret = ams369fg06_spi_write(lcd, 0x40 + i, gamma[i]); ret = ams369fg06_spi_write(lcd, 0x50 + i, gamma[i+7*1]); ret = ams369fg06_spi_write(lcd, 0x60 + i, gamma[i+7*2]); if (ret) { dev_err(lcd->dev, "failed to set gamma table.\n"); goto gamma_err; } } gamma_err: return ret; } static int ams369fg06_gamma_ctl(struct ams369fg06 *lcd, int brightness) { int ret = 0; int gamma = 0; if ((brightness >= 0) && (brightness <= 50)) gamma = 0; else if ((brightness > 50) && (brightness <= 100)) gamma = 1; else if ((brightness > 100) && (brightness <= 150)) gamma = 2; else if ((brightness > 150) && (brightness <= 200)) gamma = 3; else if ((brightness > 200) && (brightness <= 255)) gamma = 4; ret = _ams369fg06_gamma_ctl(lcd, gamma_table.gamma_22_table[gamma]); return ret; } static int ams369fg06_ldi_init(struct ams369fg06 *lcd) { int ret, i; static const unsigned short *init_seq[] = { seq_setting, seq_stand_by_off, }; for (i = 0; i < ARRAY_SIZE(init_seq); i++) { ret = ams369fg06_panel_send_sequence(lcd, init_seq[i]); if (ret) break; } return ret; } static int ams369fg06_ldi_enable(struct ams369fg06 *lcd) { int ret, i; static const unsigned short *init_seq[] = { seq_stand_by_off, seq_display_on, }; for (i = 0; i < ARRAY_SIZE(init_seq); i++) { ret = ams369fg06_panel_send_sequence(lcd, init_seq[i]); if (ret) break; } return ret; } static int ams369fg06_ldi_disable(struct ams369fg06 *lcd) { int ret, i; static const unsigned short *init_seq[] = { seq_display_off, seq_stand_by_on, }; for (i = 0; i < ARRAY_SIZE(init_seq); i++) { ret = ams369fg06_panel_send_sequence(lcd, init_seq[i]); if (ret) break; } return ret; } static int ams369fg06_power_is_on(int power) { return power <= FB_BLANK_NORMAL; } static int ams369fg06_power_on(struct ams369fg06 *lcd) { int ret = 0; struct lcd_platform_data *pd; struct backlight_device *bd; pd = lcd->lcd_pd; bd = lcd->bd; if (pd->power_on) { pd->power_on(lcd->ld, 1); msleep(pd->power_on_delay); } if (!pd->reset) { dev_err(lcd->dev, "reset is NULL.\n"); return -EINVAL; } pd->reset(lcd->ld); msleep(pd->reset_delay); ret = ams369fg06_ldi_init(lcd); if (ret) { dev_err(lcd->dev, "failed to initialize ldi.\n"); return ret; } ret = ams369fg06_ldi_enable(lcd); if (ret) { dev_err(lcd->dev, "failed to enable ldi.\n"); return ret; } /* set brightness to current value after power on or resume. */ ret = ams369fg06_gamma_ctl(lcd, bd->props.brightness); if (ret) { dev_err(lcd->dev, "lcd gamma setting failed.\n"); return ret; } return 0; } static int ams369fg06_power_off(struct ams369fg06 *lcd) { int ret; struct lcd_platform_data *pd; pd = lcd->lcd_pd; ret = ams369fg06_ldi_disable(lcd); if (ret) { dev_err(lcd->dev, "lcd setting failed.\n"); return -EIO; } msleep(pd->power_off_delay); if (pd->power_on) pd->power_on(lcd->ld, 0); return 0; } static int ams369fg06_power(struct ams369fg06 *lcd, int power) { int ret = 0; if (ams369fg06_power_is_on(power) && !ams369fg06_power_is_on(lcd->power)) ret = ams369fg06_power_on(lcd); else if (!ams369fg06_power_is_on(power) && ams369fg06_power_is_on(lcd->power)) ret = ams369fg06_power_off(lcd); if (!ret) lcd->power = power; return ret; } static int ams369fg06_get_power(struct lcd_device *ld) { struct ams369fg06 *lcd = lcd_get_data(ld); return lcd->power; } static int ams369fg06_set_power(struct lcd_device *ld, int power) { struct ams369fg06 *lcd = lcd_get_data(ld); if (power != FB_BLANK_UNBLANK && power != FB_BLANK_POWERDOWN && power != FB_BLANK_NORMAL) { dev_err(lcd->dev, "power value should be 0, 1 or 4.\n"); return -EINVAL; } return ams369fg06_power(lcd, power); } static int ams369fg06_set_brightness(struct backlight_device *bd) { int ret = 0; int brightness = bd->props.brightness; struct ams369fg06 *lcd = bl_get_data(bd); if (brightness < MIN_BRIGHTNESS || brightness > bd->props.max_brightness) { dev_err(&bd->dev, "lcd brightness should be %d to %d.\n", MIN_BRIGHTNESS, MAX_BRIGHTNESS); return -EINVAL; } ret = ams369fg06_gamma_ctl(lcd, bd->props.brightness); if (ret) { dev_err(&bd->dev, "lcd brightness setting failed.\n"); return -EIO; } return ret; } static struct lcd_ops ams369fg06_lcd_ops = { .get_power = ams369fg06_get_power, .set_power = ams369fg06_set_power, }; static const struct backlight_ops ams369fg06_backlight_ops = { .update_status = ams369fg06_set_brightness, }; static int ams369fg06_probe(struct spi_device *spi) { int ret = 0; struct ams369fg06 *lcd = NULL; struct lcd_device *ld = NULL; struct backlight_device *bd = NULL; struct backlight_properties props; lcd = devm_kzalloc(&spi->dev, sizeof(struct ams369fg06), GFP_KERNEL); if (!lcd) return -ENOMEM; /* ams369fg06 lcd panel uses 3-wire 16bits SPI Mode. */ spi->bits_per_word = 16; ret = spi_setup(spi); if (ret < 0) { dev_err(&spi->dev, "spi setup failed.\n"); return ret; } lcd->spi = spi; lcd->dev = &spi->dev; lcd->lcd_pd = dev_get_platdata(&spi->dev); if (!lcd->lcd_pd) { dev_err(&spi->dev, "platform data is NULL\n"); return -EINVAL; } ld = devm_lcd_device_register(&spi->dev, "ams369fg06", &spi->dev, lcd, &ams369fg06_lcd_ops); if (IS_ERR(ld)) return PTR_ERR(ld); lcd->ld = ld; memset(&props, 0, sizeof(struct backlight_properties)); props.type = BACKLIGHT_RAW; props.max_brightness = MAX_BRIGHTNESS; bd = devm_backlight_device_register(&spi->dev, "ams369fg06-bl", &spi->dev, lcd, &ams369fg06_backlight_ops, &props); if (IS_ERR(bd)) return PTR_ERR(bd); bd->props.brightness = DEFAULT_BRIGHTNESS; lcd->bd = bd; if (!lcd->lcd_pd->lcd_enabled) { /* * if lcd panel was off from bootloader then * current lcd status is powerdown and then * it enables lcd panel. */ lcd->power = FB_BLANK_POWERDOWN; ams369fg06_power(lcd, FB_BLANK_UNBLANK); } else { lcd->power = FB_BLANK_UNBLANK; } spi_set_drvdata(spi, lcd); dev_info(&spi->dev, "ams369fg06 panel driver has been probed.\n"); return 0; } static void ams369fg06_remove(struct spi_device *spi) { struct ams369fg06 *lcd = spi_get_drvdata(spi); ams369fg06_power(lcd, FB_BLANK_POWERDOWN); } #ifdef CONFIG_PM_SLEEP static int ams369fg06_suspend(struct device *dev) { struct ams369fg06 *lcd = dev_get_drvdata(dev); dev_dbg(dev, "lcd->power = %d\n", lcd->power); /* * when lcd panel is suspend, lcd panel becomes off * regardless of status. */ return ams369fg06_power(lcd, FB_BLANK_POWERDOWN); } static int ams369fg06_resume(struct device *dev) { struct ams369fg06 *lcd = dev_get_drvdata(dev); lcd->power = FB_BLANK_POWERDOWN; return ams369fg06_power(lcd, FB_BLANK_UNBLANK); } #endif static SIMPLE_DEV_PM_OPS(ams369fg06_pm_ops, ams369fg06_suspend, ams369fg06_resume); static void ams369fg06_shutdown(struct spi_device *spi) { struct ams369fg06 *lcd = spi_get_drvdata(spi); ams369fg06_power(lcd, FB_BLANK_POWERDOWN); } static struct spi_driver ams369fg06_driver = { .driver = { .name = "ams369fg06", .pm = &ams369fg06_pm_ops, }, .probe = ams369fg06_probe, .remove = ams369fg06_remove, .shutdown = ams369fg06_shutdown, }; module_spi_driver(ams369fg06_driver); MODULE_AUTHOR("Jingoo Han <[email protected]>"); MODULE_DESCRIPTION("ams369fg06 LCD Driver"); MODULE_LICENSE("GPL");
linux-master
drivers/video/backlight/ams369fg06.c
// SPDX-License-Identifier: GPL-2.0-only /* drivers/video/backlight/vgg2432a4.c * * VGG2432A4 (ILI9320) LCD controller driver. * * Copyright 2007 Simtec Electronics * http://armlinux.simtec.co.uk/ * Ben Dooks <[email protected]> */ #include <linux/delay.h> #include <linux/err.h> #include <linux/fb.h> #include <linux/init.h> #include <linux/lcd.h> #include <linux/module.h> #include <linux/spi/spi.h> #include <video/ili9320.h> #include "ili9320.h" /* Device initialisation sequences */ static const struct ili9320_reg vgg_init1[] = { { .address = ILI9320_POWER1, .value = ILI9320_POWER1_AP(0) | ILI9320_POWER1_BT(0), }, { .address = ILI9320_POWER2, .value = (ILI9320_POWER2_VC(7) | ILI9320_POWER2_DC0(0) | ILI9320_POWER2_DC1(0)), }, { .address = ILI9320_POWER3, .value = ILI9320_POWER3_VRH(0), }, { .address = ILI9320_POWER4, .value = ILI9320_POWER4_VREOUT(0), }, }; static const struct ili9320_reg vgg_init2[] = { { .address = ILI9320_POWER1, .value = (ILI9320_POWER1_AP(3) | ILI9320_POWER1_APE | ILI9320_POWER1_BT(7) | ILI9320_POWER1_SAP), }, { .address = ILI9320_POWER2, .value = ILI9320_POWER2_VC(7) | ILI9320_POWER2_DC0(3), } }; static const struct ili9320_reg vgg_gamma[] = { { .address = ILI9320_GAMMA1, .value = 0x0000, }, { .address = ILI9320_GAMMA2, .value = 0x0505, }, { .address = ILI9320_GAMMA3, .value = 0x0004, }, { .address = ILI9320_GAMMA4, .value = 0x0006, }, { .address = ILI9320_GAMMA5, .value = 0x0707, }, { .address = ILI9320_GAMMA6, .value = 0x0105, }, { .address = ILI9320_GAMMA7, .value = 0x0002, }, { .address = ILI9320_GAMMA8, .value = 0x0707, }, { .address = ILI9320_GAMMA9, .value = 0x0704, }, { .address = ILI9320_GAMMA10, .value = 0x807, } }; static const struct ili9320_reg vgg_init0[] = { [0] = { /* set direction and scan mode gate */ .address = ILI9320_DRIVER, .value = ILI9320_DRIVER_SS, }, { .address = ILI9320_DRIVEWAVE, .value = (ILI9320_DRIVEWAVE_MUSTSET | ILI9320_DRIVEWAVE_EOR | ILI9320_DRIVEWAVE_BC), }, { .address = ILI9320_ENTRYMODE, .value = ILI9320_ENTRYMODE_ID(3) | ILI9320_ENTRYMODE_BGR, }, { .address = ILI9320_RESIZING, .value = 0x0, }, }; static int vgg2432a4_lcd_init(struct ili9320 *lcd, struct ili9320_platdata *cfg) { unsigned int addr; int ret; /* Set VCore before anything else (VGG243237-6UFLWA) */ ret = ili9320_write(lcd, 0x00e5, 0x8000); if (ret) goto err_initial; /* Start the oscillator up before we can do anything else. */ ret = ili9320_write(lcd, ILI9320_OSCILATION, ILI9320_OSCILATION_OSC); if (ret) goto err_initial; /* must wait at-lesat 10ms after starting */ mdelay(15); ret = ili9320_write_regs(lcd, vgg_init0, ARRAY_SIZE(vgg_init0)); if (ret != 0) goto err_initial; ili9320_write(lcd, ILI9320_DISPLAY2, cfg->display2); ili9320_write(lcd, ILI9320_DISPLAY3, cfg->display3); ili9320_write(lcd, ILI9320_DISPLAY4, cfg->display4); ili9320_write(lcd, ILI9320_RGB_IF1, cfg->rgb_if1); ili9320_write(lcd, ILI9320_FRAMEMAKER, 0x0); ili9320_write(lcd, ILI9320_RGB_IF2, cfg->rgb_if2); ret = ili9320_write_regs(lcd, vgg_init1, ARRAY_SIZE(vgg_init1)); if (ret != 0) goto err_vgg; mdelay(300); ret = ili9320_write_regs(lcd, vgg_init2, ARRAY_SIZE(vgg_init2)); if (ret != 0) goto err_vgg2; mdelay(100); ili9320_write(lcd, ILI9320_POWER3, 0x13c); mdelay(100); ili9320_write(lcd, ILI9320_POWER4, 0x1c00); ili9320_write(lcd, ILI9320_POWER7, 0x000e); mdelay(100); ili9320_write(lcd, ILI9320_GRAM_HORIZ_ADDR, 0x00); ili9320_write(lcd, ILI9320_GRAM_VERT_ADD, 0x00); ret = ili9320_write_regs(lcd, vgg_gamma, ARRAY_SIZE(vgg_gamma)); if (ret != 0) goto err_vgg3; ili9320_write(lcd, ILI9320_HORIZ_START, 0x0); ili9320_write(lcd, ILI9320_HORIZ_END, cfg->hsize - 1); ili9320_write(lcd, ILI9320_VERT_START, 0x0); ili9320_write(lcd, ILI9320_VERT_END, cfg->vsize - 1); ili9320_write(lcd, ILI9320_DRIVER2, ILI9320_DRIVER2_NL(((cfg->vsize - 240) / 8) + 0x1D)); ili9320_write(lcd, ILI9320_BASE_IMAGE, 0x1); ili9320_write(lcd, ILI9320_VERT_SCROLL, 0x00); for (addr = ILI9320_PARTIAL1_POSITION; addr <= ILI9320_PARTIAL2_END; addr++) { ili9320_write(lcd, addr, 0x0); } ili9320_write(lcd, ILI9320_INTERFACE1, 0x10); ili9320_write(lcd, ILI9320_INTERFACE2, cfg->interface2); ili9320_write(lcd, ILI9320_INTERFACE3, cfg->interface3); ili9320_write(lcd, ILI9320_INTERFACE4, cfg->interface4); ili9320_write(lcd, ILI9320_INTERFACE5, cfg->interface5); ili9320_write(lcd, ILI9320_INTERFACE6, cfg->interface6); lcd->display1 = (ILI9320_DISPLAY1_D(3) | ILI9320_DISPLAY1_DTE | ILI9320_DISPLAY1_GON | ILI9320_DISPLAY1_BASEE | 0x40); ili9320_write(lcd, ILI9320_DISPLAY1, lcd->display1); return 0; err_vgg3: err_vgg2: err_vgg: err_initial: return ret; } #ifdef CONFIG_PM_SLEEP static int vgg2432a4_suspend(struct device *dev) { return ili9320_suspend(dev_get_drvdata(dev)); } static int vgg2432a4_resume(struct device *dev) { return ili9320_resume(dev_get_drvdata(dev)); } #endif static struct ili9320_client vgg2432a4_client = { .name = "VGG2432A4", .init = vgg2432a4_lcd_init, }; /* Device probe */ static int vgg2432a4_probe(struct spi_device *spi) { int ret; ret = ili9320_probe_spi(spi, &vgg2432a4_client); if (ret != 0) { dev_err(&spi->dev, "failed to initialise ili9320\n"); return ret; } return 0; } static void vgg2432a4_remove(struct spi_device *spi) { ili9320_remove(spi_get_drvdata(spi)); } static void vgg2432a4_shutdown(struct spi_device *spi) { ili9320_shutdown(spi_get_drvdata(spi)); } static SIMPLE_DEV_PM_OPS(vgg2432a4_pm_ops, vgg2432a4_suspend, vgg2432a4_resume); static struct spi_driver vgg2432a4_driver = { .driver = { .name = "VGG2432A4", .pm = &vgg2432a4_pm_ops, }, .probe = vgg2432a4_probe, .remove = vgg2432a4_remove, .shutdown = vgg2432a4_shutdown, }; module_spi_driver(vgg2432a4_driver); MODULE_AUTHOR("Ben Dooks <[email protected]>"); MODULE_DESCRIPTION("VGG2432A4 LCD Driver"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("spi:VGG2432A4");
linux-master
drivers/video/backlight/vgg2432a4.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * lm3533-bl.c -- LM3533 Backlight driver * * Copyright (C) 2011-2012 Texas Instruments * * Author: Johan Hovold <[email protected]> */ #include <linux/module.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/backlight.h> #include <linux/fb.h> #include <linux/slab.h> #include <linux/mfd/lm3533.h> #define LM3533_HVCTRLBANK_COUNT 2 #define LM3533_BL_MAX_BRIGHTNESS 255 #define LM3533_REG_CTRLBANK_AB_BCONF 0x1a struct lm3533_bl { struct lm3533 *lm3533; struct lm3533_ctrlbank cb; struct backlight_device *bd; int id; }; static inline int lm3533_bl_get_ctrlbank_id(struct lm3533_bl *bl) { return bl->id; } static int lm3533_bl_update_status(struct backlight_device *bd) { struct lm3533_bl *bl = bl_get_data(bd); return lm3533_ctrlbank_set_brightness(&bl->cb, backlight_get_brightness(bd)); } static int lm3533_bl_get_brightness(struct backlight_device *bd) { struct lm3533_bl *bl = bl_get_data(bd); u8 val; int ret; ret = lm3533_ctrlbank_get_brightness(&bl->cb, &val); if (ret) return ret; return val; } static const struct backlight_ops lm3533_bl_ops = { .get_brightness = lm3533_bl_get_brightness, .update_status = lm3533_bl_update_status, }; static ssize_t show_id(struct device *dev, struct device_attribute *attr, char *buf) { struct lm3533_bl *bl = dev_get_drvdata(dev); return scnprintf(buf, PAGE_SIZE, "%d\n", bl->id); } static ssize_t show_als_channel(struct device *dev, struct device_attribute *attr, char *buf) { struct lm3533_bl *bl = dev_get_drvdata(dev); unsigned channel = lm3533_bl_get_ctrlbank_id(bl); return scnprintf(buf, PAGE_SIZE, "%u\n", channel); } static ssize_t show_als_en(struct device *dev, struct device_attribute *attr, char *buf) { struct lm3533_bl *bl = dev_get_drvdata(dev); int ctrlbank = lm3533_bl_get_ctrlbank_id(bl); u8 val; u8 mask; bool enable; int ret; ret = lm3533_read(bl->lm3533, LM3533_REG_CTRLBANK_AB_BCONF, &val); if (ret) return ret; mask = 1 << (2 * ctrlbank); enable = val & mask; return scnprintf(buf, PAGE_SIZE, "%d\n", enable); } static ssize_t store_als_en(struct device *dev, struct device_attribute *attr, const char *buf, size_t len) { struct lm3533_bl *bl = dev_get_drvdata(dev); int ctrlbank = lm3533_bl_get_ctrlbank_id(bl); int enable; u8 val; u8 mask; int ret; if (kstrtoint(buf, 0, &enable)) return -EINVAL; mask = 1 << (2 * ctrlbank); if (enable) val = mask; else val = 0; ret = lm3533_update(bl->lm3533, LM3533_REG_CTRLBANK_AB_BCONF, val, mask); if (ret) return ret; return len; } static ssize_t show_linear(struct device *dev, struct device_attribute *attr, char *buf) { struct lm3533_bl *bl = dev_get_drvdata(dev); u8 val; u8 mask; int linear; int ret; ret = lm3533_read(bl->lm3533, LM3533_REG_CTRLBANK_AB_BCONF, &val); if (ret) return ret; mask = 1 << (2 * lm3533_bl_get_ctrlbank_id(bl) + 1); if (val & mask) linear = 1; else linear = 0; return scnprintf(buf, PAGE_SIZE, "%x\n", linear); } static ssize_t store_linear(struct device *dev, struct device_attribute *attr, const char *buf, size_t len) { struct lm3533_bl *bl = dev_get_drvdata(dev); unsigned long linear; u8 mask; u8 val; int ret; if (kstrtoul(buf, 0, &linear)) return -EINVAL; mask = 1 << (2 * lm3533_bl_get_ctrlbank_id(bl) + 1); if (linear) val = mask; else val = 0; ret = lm3533_update(bl->lm3533, LM3533_REG_CTRLBANK_AB_BCONF, val, mask); if (ret) return ret; return len; } static ssize_t show_pwm(struct device *dev, struct device_attribute *attr, char *buf) { struct lm3533_bl *bl = dev_get_drvdata(dev); u8 val; int ret; ret = lm3533_ctrlbank_get_pwm(&bl->cb, &val); if (ret) return ret; return scnprintf(buf, PAGE_SIZE, "%u\n", val); } static ssize_t store_pwm(struct device *dev, struct device_attribute *attr, const char *buf, size_t len) { struct lm3533_bl *bl = dev_get_drvdata(dev); u8 val; int ret; if (kstrtou8(buf, 0, &val)) return -EINVAL; ret = lm3533_ctrlbank_set_pwm(&bl->cb, val); if (ret) return ret; return len; } static LM3533_ATTR_RO(als_channel); static LM3533_ATTR_RW(als_en); static LM3533_ATTR_RO(id); static LM3533_ATTR_RW(linear); static LM3533_ATTR_RW(pwm); static struct attribute *lm3533_bl_attributes[] = { &dev_attr_als_channel.attr, &dev_attr_als_en.attr, &dev_attr_id.attr, &dev_attr_linear.attr, &dev_attr_pwm.attr, NULL, }; static umode_t lm3533_bl_attr_is_visible(struct kobject *kobj, struct attribute *attr, int n) { struct device *dev = kobj_to_dev(kobj); struct lm3533_bl *bl = dev_get_drvdata(dev); umode_t mode = attr->mode; if (attr == &dev_attr_als_channel.attr || attr == &dev_attr_als_en.attr) { if (!bl->lm3533->have_als) mode = 0; } return mode; }; static struct attribute_group lm3533_bl_attribute_group = { .is_visible = lm3533_bl_attr_is_visible, .attrs = lm3533_bl_attributes }; static int lm3533_bl_setup(struct lm3533_bl *bl, struct lm3533_bl_platform_data *pdata) { int ret; ret = lm3533_ctrlbank_set_max_current(&bl->cb, pdata->max_current); if (ret) return ret; return lm3533_ctrlbank_set_pwm(&bl->cb, pdata->pwm); } static int lm3533_bl_probe(struct platform_device *pdev) { struct lm3533 *lm3533; struct lm3533_bl_platform_data *pdata; struct lm3533_bl *bl; struct backlight_device *bd; struct backlight_properties props; int ret; dev_dbg(&pdev->dev, "%s\n", __func__); lm3533 = dev_get_drvdata(pdev->dev.parent); if (!lm3533) return -EINVAL; pdata = dev_get_platdata(&pdev->dev); if (!pdata) { dev_err(&pdev->dev, "no platform data\n"); return -EINVAL; } if (pdev->id < 0 || pdev->id >= LM3533_HVCTRLBANK_COUNT) { dev_err(&pdev->dev, "illegal backlight id %d\n", pdev->id); return -EINVAL; } bl = devm_kzalloc(&pdev->dev, sizeof(*bl), GFP_KERNEL); if (!bl) return -ENOMEM; bl->lm3533 = lm3533; bl->id = pdev->id; bl->cb.lm3533 = lm3533; bl->cb.id = lm3533_bl_get_ctrlbank_id(bl); bl->cb.dev = NULL; /* until registered */ memset(&props, 0, sizeof(props)); props.type = BACKLIGHT_RAW; props.max_brightness = LM3533_BL_MAX_BRIGHTNESS; props.brightness = pdata->default_brightness; bd = devm_backlight_device_register(&pdev->dev, pdata->name, pdev->dev.parent, bl, &lm3533_bl_ops, &props); if (IS_ERR(bd)) { dev_err(&pdev->dev, "failed to register backlight device\n"); return PTR_ERR(bd); } bl->bd = bd; bl->cb.dev = &bl->bd->dev; platform_set_drvdata(pdev, bl); ret = sysfs_create_group(&bd->dev.kobj, &lm3533_bl_attribute_group); if (ret < 0) { dev_err(&pdev->dev, "failed to create sysfs attributes\n"); return ret; } backlight_update_status(bd); ret = lm3533_bl_setup(bl, pdata); if (ret) goto err_sysfs_remove; ret = lm3533_ctrlbank_enable(&bl->cb); if (ret) goto err_sysfs_remove; return 0; err_sysfs_remove: sysfs_remove_group(&bd->dev.kobj, &lm3533_bl_attribute_group); return ret; } static void lm3533_bl_remove(struct platform_device *pdev) { struct lm3533_bl *bl = platform_get_drvdata(pdev); struct backlight_device *bd = bl->bd; dev_dbg(&bd->dev, "%s\n", __func__); bd->props.power = FB_BLANK_POWERDOWN; bd->props.brightness = 0; lm3533_ctrlbank_disable(&bl->cb); sysfs_remove_group(&bd->dev.kobj, &lm3533_bl_attribute_group); } #ifdef CONFIG_PM_SLEEP static int lm3533_bl_suspend(struct device *dev) { struct lm3533_bl *bl = dev_get_drvdata(dev); dev_dbg(dev, "%s\n", __func__); return lm3533_ctrlbank_disable(&bl->cb); } static int lm3533_bl_resume(struct device *dev) { struct lm3533_bl *bl = dev_get_drvdata(dev); dev_dbg(dev, "%s\n", __func__); return lm3533_ctrlbank_enable(&bl->cb); } #endif static SIMPLE_DEV_PM_OPS(lm3533_bl_pm_ops, lm3533_bl_suspend, lm3533_bl_resume); static void lm3533_bl_shutdown(struct platform_device *pdev) { struct lm3533_bl *bl = platform_get_drvdata(pdev); dev_dbg(&pdev->dev, "%s\n", __func__); lm3533_ctrlbank_disable(&bl->cb); } static struct platform_driver lm3533_bl_driver = { .driver = { .name = "lm3533-backlight", .pm = &lm3533_bl_pm_ops, }, .probe = lm3533_bl_probe, .remove_new = lm3533_bl_remove, .shutdown = lm3533_bl_shutdown, }; module_platform_driver(lm3533_bl_driver); MODULE_AUTHOR("Johan Hovold <[email protected]>"); MODULE_DESCRIPTION("LM3533 Backlight driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:lm3533-backlight");
linux-master
drivers/video/backlight/lm3533_bl.c
// SPDX-License-Identifier: GPL-2.0-only /* * l4f00242t03.c -- support for Epson L4F00242T03 LCD * * Copyright 2007-2009 Freescale Semiconductor, Inc. All Rights Reserved. * * Copyright (c) 2009 Alberto Panizzo <[email protected]> * Inspired by Marek Vasut work in l4f00242t03.c */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/device.h> #include <linux/kernel.h> #include <linux/delay.h> #include <linux/module.h> #include <linux/gpio/consumer.h> #include <linux/lcd.h> #include <linux/slab.h> #include <linux/regulator/consumer.h> #include <linux/spi/spi.h> struct l4f00242t03_priv { struct spi_device *spi; struct lcd_device *ld; int lcd_state; struct regulator *io_reg; struct regulator *core_reg; struct gpio_desc *reset; struct gpio_desc *enable; }; static void l4f00242t03_reset(struct gpio_desc *gpiod) { pr_debug("l4f00242t03_reset.\n"); gpiod_set_value(gpiod, 1); mdelay(100); gpiod_set_value(gpiod, 0); mdelay(10); /* tRES >= 100us */ gpiod_set_value(gpiod, 1); mdelay(20); } #define param(x) ((x) | 0x100) static void l4f00242t03_lcd_init(struct spi_device *spi) { struct l4f00242t03_priv *priv = spi_get_drvdata(spi); const u16 cmd[] = { 0x36, param(0), 0x3A, param(0x60) }; int ret; dev_dbg(&spi->dev, "initializing LCD\n"); ret = regulator_set_voltage(priv->io_reg, 1800000, 1800000); if (ret) { dev_err(&spi->dev, "failed to set the IO regulator voltage.\n"); return; } ret = regulator_enable(priv->io_reg); if (ret) { dev_err(&spi->dev, "failed to enable the IO regulator.\n"); return; } ret = regulator_set_voltage(priv->core_reg, 2800000, 2800000); if (ret) { dev_err(&spi->dev, "failed to set the core regulator voltage.\n"); regulator_disable(priv->io_reg); return; } ret = regulator_enable(priv->core_reg); if (ret) { dev_err(&spi->dev, "failed to enable the core regulator.\n"); regulator_disable(priv->io_reg); return; } l4f00242t03_reset(priv->reset); gpiod_set_value(priv->enable, 1); msleep(60); spi_write(spi, (const u8 *)cmd, ARRAY_SIZE(cmd) * sizeof(u16)); } static void l4f00242t03_lcd_powerdown(struct spi_device *spi) { struct l4f00242t03_priv *priv = spi_get_drvdata(spi); dev_dbg(&spi->dev, "Powering down LCD\n"); gpiod_set_value(priv->enable, 0); regulator_disable(priv->io_reg); regulator_disable(priv->core_reg); } static int l4f00242t03_lcd_power_get(struct lcd_device *ld) { struct l4f00242t03_priv *priv = lcd_get_data(ld); return priv->lcd_state; } static int l4f00242t03_lcd_power_set(struct lcd_device *ld, int power) { struct l4f00242t03_priv *priv = lcd_get_data(ld); struct spi_device *spi = priv->spi; const u16 slpout = 0x11; const u16 dison = 0x29; const u16 slpin = 0x10; const u16 disoff = 0x28; if (power <= FB_BLANK_NORMAL) { if (priv->lcd_state <= FB_BLANK_NORMAL) { /* Do nothing, the LCD is running */ } else if (priv->lcd_state < FB_BLANK_POWERDOWN) { dev_dbg(&spi->dev, "Resuming LCD\n"); spi_write(spi, (const u8 *)&slpout, sizeof(u16)); msleep(60); spi_write(spi, (const u8 *)&dison, sizeof(u16)); } else { /* priv->lcd_state == FB_BLANK_POWERDOWN */ l4f00242t03_lcd_init(spi); priv->lcd_state = FB_BLANK_VSYNC_SUSPEND; l4f00242t03_lcd_power_set(priv->ld, power); } } else if (power < FB_BLANK_POWERDOWN) { if (priv->lcd_state <= FB_BLANK_NORMAL) { /* Send the display in standby */ dev_dbg(&spi->dev, "Standby the LCD\n"); spi_write(spi, (const u8 *)&disoff, sizeof(u16)); msleep(60); spi_write(spi, (const u8 *)&slpin, sizeof(u16)); } else if (priv->lcd_state < FB_BLANK_POWERDOWN) { /* Do nothing, the LCD is already in standby */ } else { /* priv->lcd_state == FB_BLANK_POWERDOWN */ l4f00242t03_lcd_init(spi); priv->lcd_state = FB_BLANK_UNBLANK; l4f00242t03_lcd_power_set(ld, power); } } else { /* power == FB_BLANK_POWERDOWN */ if (priv->lcd_state != FB_BLANK_POWERDOWN) { /* Clear the screen before shutting down */ spi_write(spi, (const u8 *)&disoff, sizeof(u16)); msleep(60); l4f00242t03_lcd_powerdown(spi); } } priv->lcd_state = power; return 0; } static struct lcd_ops l4f_ops = { .set_power = l4f00242t03_lcd_power_set, .get_power = l4f00242t03_lcd_power_get, }; static int l4f00242t03_probe(struct spi_device *spi) { struct l4f00242t03_priv *priv; priv = devm_kzalloc(&spi->dev, sizeof(struct l4f00242t03_priv), GFP_KERNEL); if (priv == NULL) return -ENOMEM; spi_set_drvdata(spi, priv); spi->bits_per_word = 9; spi_setup(spi); priv->spi = spi; priv->reset = devm_gpiod_get(&spi->dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(priv->reset)) { dev_err(&spi->dev, "Unable to get the lcd l4f00242t03 reset gpio.\n"); return PTR_ERR(priv->reset); } gpiod_set_consumer_name(priv->reset, "lcd l4f00242t03 reset"); priv->enable = devm_gpiod_get(&spi->dev, "enable", GPIOD_OUT_LOW); if (IS_ERR(priv->enable)) { dev_err(&spi->dev, "Unable to get the lcd l4f00242t03 data en gpio.\n"); return PTR_ERR(priv->enable); } gpiod_set_consumer_name(priv->enable, "lcd l4f00242t03 data enable"); priv->io_reg = devm_regulator_get(&spi->dev, "vdd"); if (IS_ERR(priv->io_reg)) { dev_err(&spi->dev, "%s: Unable to get the IO regulator\n", __func__); return PTR_ERR(priv->io_reg); } priv->core_reg = devm_regulator_get(&spi->dev, "vcore"); if (IS_ERR(priv->core_reg)) { dev_err(&spi->dev, "%s: Unable to get the core regulator\n", __func__); return PTR_ERR(priv->core_reg); } priv->ld = devm_lcd_device_register(&spi->dev, "l4f00242t03", &spi->dev, priv, &l4f_ops); if (IS_ERR(priv->ld)) return PTR_ERR(priv->ld); /* Init the LCD */ l4f00242t03_lcd_init(spi); priv->lcd_state = FB_BLANK_VSYNC_SUSPEND; l4f00242t03_lcd_power_set(priv->ld, FB_BLANK_UNBLANK); dev_info(&spi->dev, "Epson l4f00242t03 lcd probed.\n"); return 0; } static void l4f00242t03_remove(struct spi_device *spi) { struct l4f00242t03_priv *priv = spi_get_drvdata(spi); l4f00242t03_lcd_power_set(priv->ld, FB_BLANK_POWERDOWN); } static void l4f00242t03_shutdown(struct spi_device *spi) { struct l4f00242t03_priv *priv = spi_get_drvdata(spi); if (priv) l4f00242t03_lcd_power_set(priv->ld, FB_BLANK_POWERDOWN); } static struct spi_driver l4f00242t03_driver = { .driver = { .name = "l4f00242t03", }, .probe = l4f00242t03_probe, .remove = l4f00242t03_remove, .shutdown = l4f00242t03_shutdown, }; module_spi_driver(l4f00242t03_driver); MODULE_AUTHOR("Alberto Panizzo <[email protected]>"); MODULE_DESCRIPTION("EPSON L4F00242T03 LCD"); MODULE_LICENSE("GPL v2");
linux-master
drivers/video/backlight/l4f00242t03.c
// SPDX-License-Identifier: GPL-2.0-only /* * TI LP8788 MFD - backlight driver * * Copyright 2012 Texas Instruments * * Author: Milo(Woogyom) Kim <[email protected]> */ #include <linux/backlight.h> #include <linux/err.h> #include <linux/mfd/lp8788.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/pwm.h> #include <linux/slab.h> /* Register address */ #define LP8788_BL_CONFIG 0x96 #define LP8788_BL_EN BIT(0) #define LP8788_BL_PWM_INPUT_EN BIT(5) #define LP8788_BL_FULLSCALE_SHIFT 2 #define LP8788_BL_DIM_MODE_SHIFT 1 #define LP8788_BL_PWM_POLARITY_SHIFT 6 #define LP8788_BL_BRIGHTNESS 0x97 #define LP8788_BL_RAMP 0x98 #define LP8788_BL_RAMP_RISE_SHIFT 4 #define MAX_BRIGHTNESS 127 #define DEFAULT_BL_NAME "lcd-backlight" struct lp8788_bl_config { enum lp8788_bl_ctrl_mode bl_mode; enum lp8788_bl_dim_mode dim_mode; enum lp8788_bl_full_scale_current full_scale; enum lp8788_bl_ramp_step rise_time; enum lp8788_bl_ramp_step fall_time; enum pwm_polarity pwm_pol; }; struct lp8788_bl { struct lp8788 *lp; struct backlight_device *bl_dev; struct lp8788_backlight_platform_data *pdata; enum lp8788_bl_ctrl_mode mode; struct pwm_device *pwm; }; static struct lp8788_bl_config default_bl_config = { .bl_mode = LP8788_BL_REGISTER_ONLY, .dim_mode = LP8788_DIM_EXPONENTIAL, .full_scale = LP8788_FULLSCALE_1900uA, .rise_time = LP8788_RAMP_8192us, .fall_time = LP8788_RAMP_8192us, .pwm_pol = PWM_POLARITY_NORMAL, }; static inline bool is_brightness_ctrl_by_pwm(enum lp8788_bl_ctrl_mode mode) { return mode == LP8788_BL_COMB_PWM_BASED; } static inline bool is_brightness_ctrl_by_register(enum lp8788_bl_ctrl_mode mode) { return mode == LP8788_BL_REGISTER_ONLY || mode == LP8788_BL_COMB_REGISTER_BASED; } static int lp8788_backlight_configure(struct lp8788_bl *bl) { struct lp8788_backlight_platform_data *pdata = bl->pdata; struct lp8788_bl_config *cfg = &default_bl_config; int ret; u8 val; /* * Update chip configuration if platform data exists, * otherwise use the default settings. */ if (pdata) { cfg->bl_mode = pdata->bl_mode; cfg->dim_mode = pdata->dim_mode; cfg->full_scale = pdata->full_scale; cfg->rise_time = pdata->rise_time; cfg->fall_time = pdata->fall_time; cfg->pwm_pol = pdata->pwm_pol; } /* Brightness ramp up/down */ val = (cfg->rise_time << LP8788_BL_RAMP_RISE_SHIFT) | cfg->fall_time; ret = lp8788_write_byte(bl->lp, LP8788_BL_RAMP, val); if (ret) return ret; /* Fullscale current setting */ val = (cfg->full_scale << LP8788_BL_FULLSCALE_SHIFT) | (cfg->dim_mode << LP8788_BL_DIM_MODE_SHIFT); /* Brightness control mode */ switch (cfg->bl_mode) { case LP8788_BL_REGISTER_ONLY: val |= LP8788_BL_EN; break; case LP8788_BL_COMB_PWM_BASED: case LP8788_BL_COMB_REGISTER_BASED: val |= LP8788_BL_EN | LP8788_BL_PWM_INPUT_EN | (cfg->pwm_pol << LP8788_BL_PWM_POLARITY_SHIFT); break; default: dev_err(bl->lp->dev, "invalid mode: %d\n", cfg->bl_mode); return -EINVAL; } bl->mode = cfg->bl_mode; return lp8788_write_byte(bl->lp, LP8788_BL_CONFIG, val); } static void lp8788_pwm_ctrl(struct lp8788_bl *bl, int br, int max_br) { unsigned int period; unsigned int duty; struct device *dev; struct pwm_device *pwm; if (!bl->pdata) return; period = bl->pdata->period_ns; duty = br * period / max_br; dev = bl->lp->dev; /* request PWM device with the consumer name */ if (!bl->pwm) { pwm = devm_pwm_get(dev, LP8788_DEV_BACKLIGHT); if (IS_ERR(pwm)) { dev_err(dev, "can not get PWM device\n"); return; } bl->pwm = pwm; /* * FIXME: pwm_apply_args() should be removed when switching to * the atomic PWM API. */ pwm_apply_args(pwm); } pwm_config(bl->pwm, duty, period); if (duty) pwm_enable(bl->pwm); else pwm_disable(bl->pwm); } static int lp8788_bl_update_status(struct backlight_device *bl_dev) { struct lp8788_bl *bl = bl_get_data(bl_dev); enum lp8788_bl_ctrl_mode mode = bl->mode; if (bl_dev->props.state & BL_CORE_SUSPENDED) bl_dev->props.brightness = 0; if (is_brightness_ctrl_by_pwm(mode)) { int brt = bl_dev->props.brightness; int max = bl_dev->props.max_brightness; lp8788_pwm_ctrl(bl, brt, max); } else if (is_brightness_ctrl_by_register(mode)) { u8 brt = bl_dev->props.brightness; lp8788_write_byte(bl->lp, LP8788_BL_BRIGHTNESS, brt); } return 0; } static const struct backlight_ops lp8788_bl_ops = { .options = BL_CORE_SUSPENDRESUME, .update_status = lp8788_bl_update_status, }; static int lp8788_backlight_register(struct lp8788_bl *bl) { struct backlight_device *bl_dev; struct backlight_properties props; struct lp8788_backlight_platform_data *pdata = bl->pdata; int init_brt; char *name; props.type = BACKLIGHT_PLATFORM; props.max_brightness = MAX_BRIGHTNESS; /* Initial brightness */ if (pdata) init_brt = min_t(int, pdata->initial_brightness, props.max_brightness); else init_brt = 0; props.brightness = init_brt; /* Backlight device name */ if (!pdata || !pdata->name) name = DEFAULT_BL_NAME; else name = pdata->name; bl_dev = backlight_device_register(name, bl->lp->dev, bl, &lp8788_bl_ops, &props); if (IS_ERR(bl_dev)) return PTR_ERR(bl_dev); bl->bl_dev = bl_dev; return 0; } static void lp8788_backlight_unregister(struct lp8788_bl *bl) { struct backlight_device *bl_dev = bl->bl_dev; backlight_device_unregister(bl_dev); } static ssize_t lp8788_get_bl_ctl_mode(struct device *dev, struct device_attribute *attr, char *buf) { struct lp8788_bl *bl = dev_get_drvdata(dev); enum lp8788_bl_ctrl_mode mode = bl->mode; char *strmode; if (is_brightness_ctrl_by_pwm(mode)) strmode = "PWM based"; else if (is_brightness_ctrl_by_register(mode)) strmode = "Register based"; else strmode = "Invalid mode"; return scnprintf(buf, PAGE_SIZE, "%s\n", strmode); } static DEVICE_ATTR(bl_ctl_mode, S_IRUGO, lp8788_get_bl_ctl_mode, NULL); static struct attribute *lp8788_attributes[] = { &dev_attr_bl_ctl_mode.attr, NULL, }; static const struct attribute_group lp8788_attr_group = { .attrs = lp8788_attributes, }; static int lp8788_backlight_probe(struct platform_device *pdev) { struct lp8788 *lp = dev_get_drvdata(pdev->dev.parent); struct lp8788_bl *bl; int ret; bl = devm_kzalloc(lp->dev, sizeof(struct lp8788_bl), GFP_KERNEL); if (!bl) return -ENOMEM; bl->lp = lp; if (lp->pdata) bl->pdata = lp->pdata->bl_pdata; platform_set_drvdata(pdev, bl); ret = lp8788_backlight_configure(bl); if (ret) { dev_err(lp->dev, "backlight config err: %d\n", ret); goto err_dev; } ret = lp8788_backlight_register(bl); if (ret) { dev_err(lp->dev, "register backlight err: %d\n", ret); goto err_dev; } ret = sysfs_create_group(&pdev->dev.kobj, &lp8788_attr_group); if (ret) { dev_err(lp->dev, "register sysfs err: %d\n", ret); goto err_sysfs; } backlight_update_status(bl->bl_dev); return 0; err_sysfs: lp8788_backlight_unregister(bl); err_dev: return ret; } static void lp8788_backlight_remove(struct platform_device *pdev) { struct lp8788_bl *bl = platform_get_drvdata(pdev); struct backlight_device *bl_dev = bl->bl_dev; bl_dev->props.brightness = 0; backlight_update_status(bl_dev); sysfs_remove_group(&pdev->dev.kobj, &lp8788_attr_group); lp8788_backlight_unregister(bl); } static struct platform_driver lp8788_bl_driver = { .probe = lp8788_backlight_probe, .remove_new = lp8788_backlight_remove, .driver = { .name = LP8788_DEV_BACKLIGHT, }, }; module_platform_driver(lp8788_bl_driver); MODULE_DESCRIPTION("Texas Instruments LP8788 Backlight Driver"); MODULE_AUTHOR("Milo Kim"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:lp8788-backlight");
linux-master
drivers/video/backlight/lp8788_bl.c
// SPDX-License-Identifier: GPL-2.0-only /* * Driver for the Cirrus EP93xx lcd backlight * * Copyright (c) 2010 H Hartley Sweeten <[email protected]> * * This driver controls the pulse width modulated brightness control output, * BRIGHT, on the Cirrus EP9307, EP9312, and EP9315 processors. */ #include <linux/module.h> #include <linux/platform_device.h> #include <linux/io.h> #include <linux/fb.h> #include <linux/backlight.h> #define EP93XX_MAX_COUNT 255 #define EP93XX_MAX_BRIGHT 255 #define EP93XX_DEF_BRIGHT 128 struct ep93xxbl { void __iomem *mmio; int brightness; }; static int ep93xxbl_set(struct backlight_device *bl, int brightness) { struct ep93xxbl *ep93xxbl = bl_get_data(bl); writel((brightness << 8) | EP93XX_MAX_COUNT, ep93xxbl->mmio); ep93xxbl->brightness = brightness; return 0; } static int ep93xxbl_update_status(struct backlight_device *bl) { return ep93xxbl_set(bl, backlight_get_brightness(bl)); } static int ep93xxbl_get_brightness(struct backlight_device *bl) { struct ep93xxbl *ep93xxbl = bl_get_data(bl); return ep93xxbl->brightness; } static const struct backlight_ops ep93xxbl_ops = { .update_status = ep93xxbl_update_status, .get_brightness = ep93xxbl_get_brightness, }; static int ep93xxbl_probe(struct platform_device *dev) { struct ep93xxbl *ep93xxbl; struct backlight_device *bl; struct backlight_properties props; struct resource *res; ep93xxbl = devm_kzalloc(&dev->dev, sizeof(*ep93xxbl), GFP_KERNEL); if (!ep93xxbl) return -ENOMEM; res = platform_get_resource(dev, IORESOURCE_MEM, 0); if (!res) return -ENXIO; /* * FIXME - We don't do a request_mem_region here because we are * sharing the register space with the framebuffer driver (see * drivers/video/ep93xx-fb.c) and doing so will cause the second * loaded driver to return -EBUSY. * * NOTE: No locking is required; the framebuffer does not touch * this register. */ ep93xxbl->mmio = devm_ioremap(&dev->dev, res->start, resource_size(res)); if (!ep93xxbl->mmio) return -ENXIO; memset(&props, 0, sizeof(struct backlight_properties)); props.type = BACKLIGHT_RAW; props.max_brightness = EP93XX_MAX_BRIGHT; bl = devm_backlight_device_register(&dev->dev, dev->name, &dev->dev, ep93xxbl, &ep93xxbl_ops, &props); if (IS_ERR(bl)) return PTR_ERR(bl); bl->props.brightness = EP93XX_DEF_BRIGHT; platform_set_drvdata(dev, bl); ep93xxbl_update_status(bl); return 0; } #ifdef CONFIG_PM_SLEEP static int ep93xxbl_suspend(struct device *dev) { struct backlight_device *bl = dev_get_drvdata(dev); return ep93xxbl_set(bl, 0); } static int ep93xxbl_resume(struct device *dev) { struct backlight_device *bl = dev_get_drvdata(dev); backlight_update_status(bl); return 0; } #endif static SIMPLE_DEV_PM_OPS(ep93xxbl_pm_ops, ep93xxbl_suspend, ep93xxbl_resume); static struct platform_driver ep93xxbl_driver = { .driver = { .name = "ep93xx-bl", .pm = &ep93xxbl_pm_ops, }, .probe = ep93xxbl_probe, }; module_platform_driver(ep93xxbl_driver); MODULE_DESCRIPTION("EP93xx Backlight Driver"); MODULE_AUTHOR("H Hartley Sweeten <[email protected]>"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:ep93xx-bl");
linux-master
drivers/video/backlight/ep93xx_bl.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Backlight driver for Analog Devices ADP8870 Backlight Devices * * Copyright 2009-2011 Analog Devices Inc. */ #include <linux/module.h> #include <linux/init.h> #include <linux/errno.h> #include <linux/pm.h> #include <linux/platform_device.h> #include <linux/i2c.h> #include <linux/fb.h> #include <linux/backlight.h> #include <linux/leds.h> #include <linux/workqueue.h> #include <linux/slab.h> #include <linux/platform_data/adp8870.h> #define ADP8870_EXT_FEATURES #define ADP8870_USE_LEDS #define ADP8870_MFDVID 0x00 /* Manufacturer and device ID */ #define ADP8870_MDCR 0x01 /* Device mode and status */ #define ADP8870_INT_STAT 0x02 /* Interrupts status */ #define ADP8870_INT_EN 0x03 /* Interrupts enable */ #define ADP8870_CFGR 0x04 /* Configuration register */ #define ADP8870_BLSEL 0x05 /* Sink enable backlight or independent */ #define ADP8870_PWMLED 0x06 /* PWM Enable Selection Register */ #define ADP8870_BLOFF 0x07 /* Backlight off timeout */ #define ADP8870_BLDIM 0x08 /* Backlight dim timeout */ #define ADP8870_BLFR 0x09 /* Backlight fade in and out rates */ #define ADP8870_BLMX1 0x0A /* Backlight (Brightness Level 1-daylight) maximum current */ #define ADP8870_BLDM1 0x0B /* Backlight (Brightness Level 1-daylight) dim current */ #define ADP8870_BLMX2 0x0C /* Backlight (Brightness Level 2-bright) maximum current */ #define ADP8870_BLDM2 0x0D /* Backlight (Brightness Level 2-bright) dim current */ #define ADP8870_BLMX3 0x0E /* Backlight (Brightness Level 3-office) maximum current */ #define ADP8870_BLDM3 0x0F /* Backlight (Brightness Level 3-office) dim current */ #define ADP8870_BLMX4 0x10 /* Backlight (Brightness Level 4-indoor) maximum current */ #define ADP8870_BLDM4 0x11 /* Backlight (Brightness Level 4-indoor) dim current */ #define ADP8870_BLMX5 0x12 /* Backlight (Brightness Level 5-dark) maximum current */ #define ADP8870_BLDM5 0x13 /* Backlight (Brightness Level 5-dark) dim current */ #define ADP8870_ISCLAW 0x1A /* Independent sink current fade law register */ #define ADP8870_ISCC 0x1B /* Independent sink current control register */ #define ADP8870_ISCT1 0x1C /* Independent Sink Current Timer Register LED[7:5] */ #define ADP8870_ISCT2 0x1D /* Independent Sink Current Timer Register LED[4:1] */ #define ADP8870_ISCF 0x1E /* Independent sink current fade register */ #define ADP8870_ISC1 0x1F /* Independent Sink Current LED1 */ #define ADP8870_ISC2 0x20 /* Independent Sink Current LED2 */ #define ADP8870_ISC3 0x21 /* Independent Sink Current LED3 */ #define ADP8870_ISC4 0x22 /* Independent Sink Current LED4 */ #define ADP8870_ISC5 0x23 /* Independent Sink Current LED5 */ #define ADP8870_ISC6 0x24 /* Independent Sink Current LED6 */ #define ADP8870_ISC7 0x25 /* Independent Sink Current LED7 (Brightness Level 1-daylight) */ #define ADP8870_ISC7_L2 0x26 /* Independent Sink Current LED7 (Brightness Level 2-bright) */ #define ADP8870_ISC7_L3 0x27 /* Independent Sink Current LED7 (Brightness Level 3-office) */ #define ADP8870_ISC7_L4 0x28 /* Independent Sink Current LED7 (Brightness Level 4-indoor) */ #define ADP8870_ISC7_L5 0x29 /* Independent Sink Current LED7 (Brightness Level 5-dark) */ #define ADP8870_CMP_CTL 0x2D /* ALS Comparator Control Register */ #define ADP8870_ALS1_EN 0x2E /* Main ALS comparator level enable */ #define ADP8870_ALS2_EN 0x2F /* Second ALS comparator level enable */ #define ADP8870_ALS1_STAT 0x30 /* Main ALS Comparator Status Register */ #define ADP8870_ALS2_STAT 0x31 /* Second ALS Comparator Status Register */ #define ADP8870_L2TRP 0x32 /* L2 comparator reference */ #define ADP8870_L2HYS 0x33 /* L2 hysteresis */ #define ADP8870_L3TRP 0x34 /* L3 comparator reference */ #define ADP8870_L3HYS 0x35 /* L3 hysteresis */ #define ADP8870_L4TRP 0x36 /* L4 comparator reference */ #define ADP8870_L4HYS 0x37 /* L4 hysteresis */ #define ADP8870_L5TRP 0x38 /* L5 comparator reference */ #define ADP8870_L5HYS 0x39 /* L5 hysteresis */ #define ADP8870_PH1LEVL 0x40 /* First phototransistor ambient light level-low byte register */ #define ADP8870_PH1LEVH 0x41 /* First phototransistor ambient light level-high byte register */ #define ADP8870_PH2LEVL 0x42 /* Second phototransistor ambient light level-low byte register */ #define ADP8870_PH2LEVH 0x43 /* Second phototransistor ambient light level-high byte register */ #define ADP8870_MANUFID 0x3 /* Analog Devices AD8870 Manufacturer and device ID */ #define ADP8870_DEVID(x) ((x) & 0xF) #define ADP8870_MANID(x) ((x) >> 4) /* MDCR Device mode and status */ #define D7ALSEN (1 << 7) #define INT_CFG (1 << 6) #define NSTBY (1 << 5) #define DIM_EN (1 << 4) #define GDWN_DIS (1 << 3) #define SIS_EN (1 << 2) #define CMP_AUTOEN (1 << 1) #define BLEN (1 << 0) /* ADP8870_ALS1_EN Main ALS comparator level enable */ #define L5_EN (1 << 3) #define L4_EN (1 << 2) #define L3_EN (1 << 1) #define L2_EN (1 << 0) #define CFGR_BLV_SHIFT 3 #define CFGR_BLV_MASK 0x7 #define ADP8870_FLAG_LED_MASK 0xFF #define FADE_VAL(in, out) ((0xF & (in)) | ((0xF & (out)) << 4)) #define BL_CFGR_VAL(law, blv) ((((blv) & CFGR_BLV_MASK) << CFGR_BLV_SHIFT) | ((0x3 & (law)) << 1)) #define ALS_CMPR_CFG_VAL(filt) ((0x7 & (filt)) << 1) struct adp8870_bl { struct i2c_client *client; struct backlight_device *bl; struct adp8870_led *led; struct adp8870_backlight_platform_data *pdata; struct mutex lock; unsigned long cached_daylight_max; int id; int revid; int current_brightness; }; struct adp8870_led { struct led_classdev cdev; struct work_struct work; struct i2c_client *client; enum led_brightness new_brightness; int id; int flags; }; static int adp8870_read(struct i2c_client *client, int reg, uint8_t *val) { int ret; ret = i2c_smbus_read_byte_data(client, reg); if (ret < 0) { dev_err(&client->dev, "failed reading at 0x%02x\n", reg); return ret; } *val = ret; return 0; } static int adp8870_write(struct i2c_client *client, u8 reg, u8 val) { int ret = i2c_smbus_write_byte_data(client, reg, val); if (ret) dev_err(&client->dev, "failed to write\n"); return ret; } static int adp8870_set_bits(struct i2c_client *client, int reg, uint8_t bit_mask) { struct adp8870_bl *data = i2c_get_clientdata(client); uint8_t reg_val; int ret; mutex_lock(&data->lock); ret = adp8870_read(client, reg, &reg_val); if (!ret && ((reg_val & bit_mask) != bit_mask)) { reg_val |= bit_mask; ret = adp8870_write(client, reg, reg_val); } mutex_unlock(&data->lock); return ret; } static int adp8870_clr_bits(struct i2c_client *client, int reg, uint8_t bit_mask) { struct adp8870_bl *data = i2c_get_clientdata(client); uint8_t reg_val; int ret; mutex_lock(&data->lock); ret = adp8870_read(client, reg, &reg_val); if (!ret && (reg_val & bit_mask)) { reg_val &= ~bit_mask; ret = adp8870_write(client, reg, reg_val); } mutex_unlock(&data->lock); return ret; } /* * Independent sink / LED */ #if defined(ADP8870_USE_LEDS) static void adp8870_led_work(struct work_struct *work) { struct adp8870_led *led = container_of(work, struct adp8870_led, work); adp8870_write(led->client, ADP8870_ISC1 + led->id - 1, led->new_brightness >> 1); } static void adp8870_led_set(struct led_classdev *led_cdev, enum led_brightness value) { struct adp8870_led *led; led = container_of(led_cdev, struct adp8870_led, cdev); led->new_brightness = value; /* * Use workqueue for IO since I2C operations can sleep. */ schedule_work(&led->work); } static int adp8870_led_setup(struct adp8870_led *led) { struct i2c_client *client = led->client; int ret = 0; ret = adp8870_write(client, ADP8870_ISC1 + led->id - 1, 0); if (ret) return ret; ret = adp8870_set_bits(client, ADP8870_ISCC, 1 << (led->id - 1)); if (ret) return ret; if (led->id > 4) ret = adp8870_set_bits(client, ADP8870_ISCT1, (led->flags & 0x3) << ((led->id - 5) * 2)); else ret = adp8870_set_bits(client, ADP8870_ISCT2, (led->flags & 0x3) << ((led->id - 1) * 2)); return ret; } static int adp8870_led_probe(struct i2c_client *client) { struct adp8870_backlight_platform_data *pdata = dev_get_platdata(&client->dev); struct adp8870_bl *data = i2c_get_clientdata(client); struct adp8870_led *led, *led_dat; struct led_info *cur_led; int ret, i; led = devm_kcalloc(&client->dev, pdata->num_leds, sizeof(*led), GFP_KERNEL); if (led == NULL) return -ENOMEM; ret = adp8870_write(client, ADP8870_ISCLAW, pdata->led_fade_law); if (ret) return ret; ret = adp8870_write(client, ADP8870_ISCT1, (pdata->led_on_time & 0x3) << 6); if (ret) return ret; ret = adp8870_write(client, ADP8870_ISCF, FADE_VAL(pdata->led_fade_in, pdata->led_fade_out)); if (ret) return ret; for (i = 0; i < pdata->num_leds; ++i) { cur_led = &pdata->leds[i]; led_dat = &led[i]; led_dat->id = cur_led->flags & ADP8870_FLAG_LED_MASK; if (led_dat->id > 7 || led_dat->id < 1) { dev_err(&client->dev, "Invalid LED ID %d\n", led_dat->id); ret = -EINVAL; goto err; } if (pdata->bl_led_assign & (1 << (led_dat->id - 1))) { dev_err(&client->dev, "LED %d used by Backlight\n", led_dat->id); ret = -EBUSY; goto err; } led_dat->cdev.name = cur_led->name; led_dat->cdev.default_trigger = cur_led->default_trigger; led_dat->cdev.brightness_set = adp8870_led_set; led_dat->cdev.brightness = LED_OFF; led_dat->flags = cur_led->flags >> FLAG_OFFT_SHIFT; led_dat->client = client; led_dat->new_brightness = LED_OFF; INIT_WORK(&led_dat->work, adp8870_led_work); ret = led_classdev_register(&client->dev, &led_dat->cdev); if (ret) { dev_err(&client->dev, "failed to register LED %d\n", led_dat->id); goto err; } ret = adp8870_led_setup(led_dat); if (ret) { dev_err(&client->dev, "failed to write\n"); i++; goto err; } } data->led = led; return 0; err: for (i = i - 1; i >= 0; --i) { led_classdev_unregister(&led[i].cdev); cancel_work_sync(&led[i].work); } return ret; } static int adp8870_led_remove(struct i2c_client *client) { struct adp8870_backlight_platform_data *pdata = dev_get_platdata(&client->dev); struct adp8870_bl *data = i2c_get_clientdata(client); int i; for (i = 0; i < pdata->num_leds; i++) { led_classdev_unregister(&data->led[i].cdev); cancel_work_sync(&data->led[i].work); } return 0; } #else static int adp8870_led_probe(struct i2c_client *client) { return 0; } static int adp8870_led_remove(struct i2c_client *client) { return 0; } #endif static int adp8870_bl_set(struct backlight_device *bl, int brightness) { struct adp8870_bl *data = bl_get_data(bl); struct i2c_client *client = data->client; int ret = 0; if (data->pdata->en_ambl_sens) { if ((brightness > 0) && (brightness < ADP8870_MAX_BRIGHTNESS)) { /* Disable Ambient Light auto adjust */ ret = adp8870_clr_bits(client, ADP8870_MDCR, CMP_AUTOEN); if (ret) return ret; ret = adp8870_write(client, ADP8870_BLMX1, brightness); if (ret) return ret; } else { /* * MAX_BRIGHTNESS -> Enable Ambient Light auto adjust * restore daylight l1 sysfs brightness */ ret = adp8870_write(client, ADP8870_BLMX1, data->cached_daylight_max); if (ret) return ret; ret = adp8870_set_bits(client, ADP8870_MDCR, CMP_AUTOEN); if (ret) return ret; } } else { ret = adp8870_write(client, ADP8870_BLMX1, brightness); if (ret) return ret; } if (data->current_brightness && brightness == 0) ret = adp8870_set_bits(client, ADP8870_MDCR, DIM_EN); else if (data->current_brightness == 0 && brightness) ret = adp8870_clr_bits(client, ADP8870_MDCR, DIM_EN); if (!ret) data->current_brightness = brightness; return ret; } static int adp8870_bl_update_status(struct backlight_device *bl) { return adp8870_bl_set(bl, backlight_get_brightness(bl)); } static int adp8870_bl_get_brightness(struct backlight_device *bl) { struct adp8870_bl *data = bl_get_data(bl); return data->current_brightness; } static const struct backlight_ops adp8870_bl_ops = { .update_status = adp8870_bl_update_status, .get_brightness = adp8870_bl_get_brightness, }; static int adp8870_bl_setup(struct backlight_device *bl) { struct adp8870_bl *data = bl_get_data(bl); struct i2c_client *client = data->client; struct adp8870_backlight_platform_data *pdata = data->pdata; int ret = 0; ret = adp8870_write(client, ADP8870_BLSEL, ~pdata->bl_led_assign); if (ret) return ret; ret = adp8870_write(client, ADP8870_PWMLED, pdata->pwm_assign); if (ret) return ret; ret = adp8870_write(client, ADP8870_BLMX1, pdata->l1_daylight_max); if (ret) return ret; ret = adp8870_write(client, ADP8870_BLDM1, pdata->l1_daylight_dim); if (ret) return ret; if (pdata->en_ambl_sens) { data->cached_daylight_max = pdata->l1_daylight_max; ret = adp8870_write(client, ADP8870_BLMX2, pdata->l2_bright_max); if (ret) return ret; ret = adp8870_write(client, ADP8870_BLDM2, pdata->l2_bright_dim); if (ret) return ret; ret = adp8870_write(client, ADP8870_BLMX3, pdata->l3_office_max); if (ret) return ret; ret = adp8870_write(client, ADP8870_BLDM3, pdata->l3_office_dim); if (ret) return ret; ret = adp8870_write(client, ADP8870_BLMX4, pdata->l4_indoor_max); if (ret) return ret; ret = adp8870_write(client, ADP8870_BLDM4, pdata->l4_indor_dim); if (ret) return ret; ret = adp8870_write(client, ADP8870_BLMX5, pdata->l5_dark_max); if (ret) return ret; ret = adp8870_write(client, ADP8870_BLDM5, pdata->l5_dark_dim); if (ret) return ret; ret = adp8870_write(client, ADP8870_L2TRP, pdata->l2_trip); if (ret) return ret; ret = adp8870_write(client, ADP8870_L2HYS, pdata->l2_hyst); if (ret) return ret; ret = adp8870_write(client, ADP8870_L3TRP, pdata->l3_trip); if (ret) return ret; ret = adp8870_write(client, ADP8870_L3HYS, pdata->l3_hyst); if (ret) return ret; ret = adp8870_write(client, ADP8870_L4TRP, pdata->l4_trip); if (ret) return ret; ret = adp8870_write(client, ADP8870_L4HYS, pdata->l4_hyst); if (ret) return ret; ret = adp8870_write(client, ADP8870_L5TRP, pdata->l5_trip); if (ret) return ret; ret = adp8870_write(client, ADP8870_L5HYS, pdata->l5_hyst); if (ret) return ret; ret = adp8870_write(client, ADP8870_ALS1_EN, L5_EN | L4_EN | L3_EN | L2_EN); if (ret) return ret; ret = adp8870_write(client, ADP8870_CMP_CTL, ALS_CMPR_CFG_VAL(pdata->abml_filt)); if (ret) return ret; } ret = adp8870_write(client, ADP8870_CFGR, BL_CFGR_VAL(pdata->bl_fade_law, 0)); if (ret) return ret; ret = adp8870_write(client, ADP8870_BLFR, FADE_VAL(pdata->bl_fade_in, pdata->bl_fade_out)); if (ret) return ret; /* * ADP8870 Rev0 requires GDWN_DIS bit set */ ret = adp8870_set_bits(client, ADP8870_MDCR, BLEN | DIM_EN | NSTBY | (data->revid == 0 ? GDWN_DIS : 0)); return ret; } static ssize_t adp8870_show(struct device *dev, char *buf, int reg) { struct adp8870_bl *data = dev_get_drvdata(dev); int error; uint8_t reg_val; mutex_lock(&data->lock); error = adp8870_read(data->client, reg, &reg_val); mutex_unlock(&data->lock); if (error < 0) return error; return sprintf(buf, "%u\n", reg_val); } static ssize_t adp8870_store(struct device *dev, const char *buf, size_t count, int reg) { struct adp8870_bl *data = dev_get_drvdata(dev); unsigned long val; int ret; ret = kstrtoul(buf, 10, &val); if (ret) return ret; mutex_lock(&data->lock); adp8870_write(data->client, reg, val); mutex_unlock(&data->lock); return count; } static ssize_t adp8870_bl_l5_dark_max_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp8870_show(dev, buf, ADP8870_BLMX5); } static ssize_t adp8870_bl_l5_dark_max_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return adp8870_store(dev, buf, count, ADP8870_BLMX5); } static DEVICE_ATTR(l5_dark_max, 0664, adp8870_bl_l5_dark_max_show, adp8870_bl_l5_dark_max_store); static ssize_t adp8870_bl_l4_indoor_max_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp8870_show(dev, buf, ADP8870_BLMX4); } static ssize_t adp8870_bl_l4_indoor_max_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return adp8870_store(dev, buf, count, ADP8870_BLMX4); } static DEVICE_ATTR(l4_indoor_max, 0664, adp8870_bl_l4_indoor_max_show, adp8870_bl_l4_indoor_max_store); static ssize_t adp8870_bl_l3_office_max_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp8870_show(dev, buf, ADP8870_BLMX3); } static ssize_t adp8870_bl_l3_office_max_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return adp8870_store(dev, buf, count, ADP8870_BLMX3); } static DEVICE_ATTR(l3_office_max, 0664, adp8870_bl_l3_office_max_show, adp8870_bl_l3_office_max_store); static ssize_t adp8870_bl_l2_bright_max_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp8870_show(dev, buf, ADP8870_BLMX2); } static ssize_t adp8870_bl_l2_bright_max_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return adp8870_store(dev, buf, count, ADP8870_BLMX2); } static DEVICE_ATTR(l2_bright_max, 0664, adp8870_bl_l2_bright_max_show, adp8870_bl_l2_bright_max_store); static ssize_t adp8870_bl_l1_daylight_max_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp8870_show(dev, buf, ADP8870_BLMX1); } static ssize_t adp8870_bl_l1_daylight_max_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct adp8870_bl *data = dev_get_drvdata(dev); int ret = kstrtoul(buf, 10, &data->cached_daylight_max); if (ret) return ret; return adp8870_store(dev, buf, count, ADP8870_BLMX1); } static DEVICE_ATTR(l1_daylight_max, 0664, adp8870_bl_l1_daylight_max_show, adp8870_bl_l1_daylight_max_store); static ssize_t adp8870_bl_l5_dark_dim_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp8870_show(dev, buf, ADP8870_BLDM5); } static ssize_t adp8870_bl_l5_dark_dim_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return adp8870_store(dev, buf, count, ADP8870_BLDM5); } static DEVICE_ATTR(l5_dark_dim, 0664, adp8870_bl_l5_dark_dim_show, adp8870_bl_l5_dark_dim_store); static ssize_t adp8870_bl_l4_indoor_dim_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp8870_show(dev, buf, ADP8870_BLDM4); } static ssize_t adp8870_bl_l4_indoor_dim_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return adp8870_store(dev, buf, count, ADP8870_BLDM4); } static DEVICE_ATTR(l4_indoor_dim, 0664, adp8870_bl_l4_indoor_dim_show, adp8870_bl_l4_indoor_dim_store); static ssize_t adp8870_bl_l3_office_dim_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp8870_show(dev, buf, ADP8870_BLDM3); } static ssize_t adp8870_bl_l3_office_dim_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return adp8870_store(dev, buf, count, ADP8870_BLDM3); } static DEVICE_ATTR(l3_office_dim, 0664, adp8870_bl_l3_office_dim_show, adp8870_bl_l3_office_dim_store); static ssize_t adp8870_bl_l2_bright_dim_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp8870_show(dev, buf, ADP8870_BLDM2); } static ssize_t adp8870_bl_l2_bright_dim_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return adp8870_store(dev, buf, count, ADP8870_BLDM2); } static DEVICE_ATTR(l2_bright_dim, 0664, adp8870_bl_l2_bright_dim_show, adp8870_bl_l2_bright_dim_store); static ssize_t adp8870_bl_l1_daylight_dim_show(struct device *dev, struct device_attribute *attr, char *buf) { return adp8870_show(dev, buf, ADP8870_BLDM1); } static ssize_t adp8870_bl_l1_daylight_dim_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return adp8870_store(dev, buf, count, ADP8870_BLDM1); } static DEVICE_ATTR(l1_daylight_dim, 0664, adp8870_bl_l1_daylight_dim_show, adp8870_bl_l1_daylight_dim_store); #ifdef ADP8870_EXT_FEATURES static ssize_t adp8870_bl_ambient_light_level_show(struct device *dev, struct device_attribute *attr, char *buf) { struct adp8870_bl *data = dev_get_drvdata(dev); int error; uint8_t reg_val; uint16_t ret_val; mutex_lock(&data->lock); error = adp8870_read(data->client, ADP8870_PH1LEVL, &reg_val); if (error < 0) { mutex_unlock(&data->lock); return error; } ret_val = reg_val; error = adp8870_read(data->client, ADP8870_PH1LEVH, &reg_val); mutex_unlock(&data->lock); if (error < 0) return error; /* Return 13-bit conversion value for the first light sensor */ ret_val += (reg_val & 0x1F) << 8; return sprintf(buf, "%u\n", ret_val); } static DEVICE_ATTR(ambient_light_level, 0444, adp8870_bl_ambient_light_level_show, NULL); static ssize_t adp8870_bl_ambient_light_zone_show(struct device *dev, struct device_attribute *attr, char *buf) { struct adp8870_bl *data = dev_get_drvdata(dev); int error; uint8_t reg_val; mutex_lock(&data->lock); error = adp8870_read(data->client, ADP8870_CFGR, &reg_val); mutex_unlock(&data->lock); if (error < 0) return error; return sprintf(buf, "%u\n", ((reg_val >> CFGR_BLV_SHIFT) & CFGR_BLV_MASK) + 1); } static ssize_t adp8870_bl_ambient_light_zone_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct adp8870_bl *data = dev_get_drvdata(dev); unsigned long val; uint8_t reg_val; int ret; ret = kstrtoul(buf, 10, &val); if (ret) return ret; if (val == 0) { /* Enable automatic ambient light sensing */ adp8870_set_bits(data->client, ADP8870_MDCR, CMP_AUTOEN); } else if ((val > 0) && (val < 6)) { /* Disable automatic ambient light sensing */ adp8870_clr_bits(data->client, ADP8870_MDCR, CMP_AUTOEN); /* Set user supplied ambient light zone */ mutex_lock(&data->lock); ret = adp8870_read(data->client, ADP8870_CFGR, &reg_val); if (!ret) { reg_val &= ~(CFGR_BLV_MASK << CFGR_BLV_SHIFT); reg_val |= (val - 1) << CFGR_BLV_SHIFT; adp8870_write(data->client, ADP8870_CFGR, reg_val); } mutex_unlock(&data->lock); } return count; } static DEVICE_ATTR(ambient_light_zone, 0664, adp8870_bl_ambient_light_zone_show, adp8870_bl_ambient_light_zone_store); #endif static struct attribute *adp8870_bl_attributes[] = { &dev_attr_l5_dark_max.attr, &dev_attr_l5_dark_dim.attr, &dev_attr_l4_indoor_max.attr, &dev_attr_l4_indoor_dim.attr, &dev_attr_l3_office_max.attr, &dev_attr_l3_office_dim.attr, &dev_attr_l2_bright_max.attr, &dev_attr_l2_bright_dim.attr, &dev_attr_l1_daylight_max.attr, &dev_attr_l1_daylight_dim.attr, #ifdef ADP8870_EXT_FEATURES &dev_attr_ambient_light_level.attr, &dev_attr_ambient_light_zone.attr, #endif NULL }; static const struct attribute_group adp8870_bl_attr_group = { .attrs = adp8870_bl_attributes, }; static int adp8870_probe(struct i2c_client *client) { const struct i2c_device_id *id = i2c_client_get_device_id(client); struct backlight_properties props; struct backlight_device *bl; struct adp8870_bl *data; struct adp8870_backlight_platform_data *pdata = dev_get_platdata(&client->dev); uint8_t reg_val; int ret; if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA)) { dev_err(&client->dev, "SMBUS Byte Data not Supported\n"); return -EIO; } if (!pdata) { dev_err(&client->dev, "no platform data?\n"); return -EINVAL; } ret = adp8870_read(client, ADP8870_MFDVID, &reg_val); if (ret < 0) return -EIO; if (ADP8870_MANID(reg_val) != ADP8870_MANUFID) { dev_err(&client->dev, "failed to probe\n"); return -ENODEV; } data = devm_kzalloc(&client->dev, sizeof(*data), GFP_KERNEL); if (data == NULL) return -ENOMEM; data->revid = ADP8870_DEVID(reg_val); data->client = client; data->pdata = pdata; data->id = id->driver_data; data->current_brightness = 0; i2c_set_clientdata(client, data); mutex_init(&data->lock); memset(&props, 0, sizeof(props)); props.type = BACKLIGHT_RAW; props.max_brightness = props.brightness = ADP8870_MAX_BRIGHTNESS; bl = devm_backlight_device_register(&client->dev, dev_driver_string(&client->dev), &client->dev, data, &adp8870_bl_ops, &props); if (IS_ERR(bl)) { dev_err(&client->dev, "failed to register backlight\n"); return PTR_ERR(bl); } data->bl = bl; if (pdata->en_ambl_sens) { ret = sysfs_create_group(&bl->dev.kobj, &adp8870_bl_attr_group); if (ret) { dev_err(&client->dev, "failed to register sysfs\n"); return ret; } } ret = adp8870_bl_setup(bl); if (ret) { ret = -EIO; goto out; } backlight_update_status(bl); dev_info(&client->dev, "Rev.%d Backlight\n", data->revid); if (pdata->num_leds) adp8870_led_probe(client); return 0; out: if (data->pdata->en_ambl_sens) sysfs_remove_group(&data->bl->dev.kobj, &adp8870_bl_attr_group); return ret; } static void adp8870_remove(struct i2c_client *client) { struct adp8870_bl *data = i2c_get_clientdata(client); adp8870_clr_bits(client, ADP8870_MDCR, NSTBY); if (data->led) adp8870_led_remove(client); if (data->pdata->en_ambl_sens) sysfs_remove_group(&data->bl->dev.kobj, &adp8870_bl_attr_group); } #ifdef CONFIG_PM_SLEEP static int adp8870_i2c_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); adp8870_clr_bits(client, ADP8870_MDCR, NSTBY); return 0; } static int adp8870_i2c_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); adp8870_set_bits(client, ADP8870_MDCR, NSTBY | BLEN); return 0; } #endif static SIMPLE_DEV_PM_OPS(adp8870_i2c_pm_ops, adp8870_i2c_suspend, adp8870_i2c_resume); static const struct i2c_device_id adp8870_id[] = { { "adp8870", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, adp8870_id); static struct i2c_driver adp8870_driver = { .driver = { .name = KBUILD_MODNAME, .pm = &adp8870_i2c_pm_ops, }, .probe = adp8870_probe, .remove = adp8870_remove, .id_table = adp8870_id, }; module_i2c_driver(adp8870_driver); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Michael Hennerich <[email protected]>"); MODULE_DESCRIPTION("ADP8870 Backlight driver");
linux-master
drivers/video/backlight/adp8870_bl.c
// SPDX-License-Identifier: GPL-2.0-only /* * Backlight control code for Sharp Zaurus SL-5500 * * Copyright 2005 John Lenz <[email protected]> * Maintainer: Pavel Machek <[email protected]> (unless John wants to :-) * * This driver assumes single CPU. That's okay, because collie is * slightly old hardware, and no one is going to retrofit second CPU to * old PDA. */ /* LCD power functions */ #include <linux/module.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/interrupt.h> #include <linux/fb.h> #include <linux/backlight.h> #include <asm/hardware/locomo.h> #include <asm/irq.h> #include <asm/mach/sharpsl_param.h> #include <asm/mach-types.h> #include "../../../arch/arm/mach-sa1100/generic.h" static struct backlight_device *locomolcd_bl_device; static struct locomo_dev *locomolcd_dev; static unsigned long locomolcd_flags; #define LOCOMOLCD_SUSPENDED 0x01 static void locomolcd_on(int comadj) { locomo_gpio_set_dir(locomolcd_dev->dev.parent, LOCOMO_GPIO_LCD_VSHA_ON, 0); locomo_gpio_write(locomolcd_dev->dev.parent, LOCOMO_GPIO_LCD_VSHA_ON, 1); mdelay(2); locomo_gpio_set_dir(locomolcd_dev->dev.parent, LOCOMO_GPIO_LCD_VSHD_ON, 0); locomo_gpio_write(locomolcd_dev->dev.parent, LOCOMO_GPIO_LCD_VSHD_ON, 1); mdelay(2); locomo_m62332_senddata(locomolcd_dev, comadj, 0); mdelay(5); locomo_gpio_set_dir(locomolcd_dev->dev.parent, LOCOMO_GPIO_LCD_VEE_ON, 0); locomo_gpio_write(locomolcd_dev->dev.parent, LOCOMO_GPIO_LCD_VEE_ON, 1); mdelay(10); /* TFTCRST | CPSOUT=0 | CPSEN */ locomo_writel(0x01, locomolcd_dev->mapbase + LOCOMO_TC); /* Set CPSD */ locomo_writel(6, locomolcd_dev->mapbase + LOCOMO_CPSD); /* TFTCRST | CPSOUT=0 | CPSEN */ locomo_writel((0x04 | 0x01), locomolcd_dev->mapbase + LOCOMO_TC); mdelay(10); locomo_gpio_set_dir(locomolcd_dev->dev.parent, LOCOMO_GPIO_LCD_MOD, 0); locomo_gpio_write(locomolcd_dev->dev.parent, LOCOMO_GPIO_LCD_MOD, 1); } static void locomolcd_off(int comadj) { /* TFTCRST=1 | CPSOUT=1 | CPSEN = 0 */ locomo_writel(0x06, locomolcd_dev->mapbase + LOCOMO_TC); mdelay(1); locomo_gpio_write(locomolcd_dev->dev.parent, LOCOMO_GPIO_LCD_VSHA_ON, 0); mdelay(110); locomo_gpio_write(locomolcd_dev->dev.parent, LOCOMO_GPIO_LCD_VEE_ON, 0); mdelay(700); /* TFTCRST=0 | CPSOUT=0 | CPSEN = 0 */ locomo_writel(0, locomolcd_dev->mapbase + LOCOMO_TC); locomo_gpio_write(locomolcd_dev->dev.parent, LOCOMO_GPIO_LCD_MOD, 0); locomo_gpio_write(locomolcd_dev->dev.parent, LOCOMO_GPIO_LCD_VSHD_ON, 0); } void locomolcd_power(int on) { int comadj = sharpsl_param.comadj; unsigned long flags; local_irq_save(flags); if (!locomolcd_dev) { local_irq_restore(flags); return; } /* read comadj */ if (comadj == -1 && machine_is_collie()) comadj = 128; if (on) locomolcd_on(comadj); else locomolcd_off(comadj); local_irq_restore(flags); } EXPORT_SYMBOL(locomolcd_power); static int current_intensity; static int locomolcd_set_intensity(struct backlight_device *bd) { int intensity = backlight_get_brightness(bd); if (locomolcd_flags & LOCOMOLCD_SUSPENDED) intensity = 0; switch (intensity) { /* * AC and non-AC are handled differently, * but produce same results in sharp code? */ case 0: locomo_frontlight_set(locomolcd_dev, 0, 0, 161); break; case 1: locomo_frontlight_set(locomolcd_dev, 117, 0, 161); break; case 2: locomo_frontlight_set(locomolcd_dev, 163, 0, 148); break; case 3: locomo_frontlight_set(locomolcd_dev, 194, 0, 161); break; case 4: locomo_frontlight_set(locomolcd_dev, 194, 1, 161); break; default: return -ENODEV; } current_intensity = intensity; return 0; } static int locomolcd_get_intensity(struct backlight_device *bd) { return current_intensity; } static const struct backlight_ops locomobl_data = { .get_brightness = locomolcd_get_intensity, .update_status = locomolcd_set_intensity, }; #ifdef CONFIG_PM_SLEEP static int locomolcd_suspend(struct device *dev) { locomolcd_flags |= LOCOMOLCD_SUSPENDED; locomolcd_set_intensity(locomolcd_bl_device); return 0; } static int locomolcd_resume(struct device *dev) { locomolcd_flags &= ~LOCOMOLCD_SUSPENDED; locomolcd_set_intensity(locomolcd_bl_device); return 0; } #endif static SIMPLE_DEV_PM_OPS(locomolcd_pm_ops, locomolcd_suspend, locomolcd_resume); static int locomolcd_probe(struct locomo_dev *ldev) { struct backlight_properties props; unsigned long flags; local_irq_save(flags); locomolcd_dev = ldev; locomo_gpio_set_dir(ldev->dev.parent, LOCOMO_GPIO_FL_VR, 0); local_irq_restore(flags); memset(&props, 0, sizeof(struct backlight_properties)); props.type = BACKLIGHT_RAW; props.max_brightness = 4; locomolcd_bl_device = backlight_device_register("locomo-bl", &ldev->dev, NULL, &locomobl_data, &props); if (IS_ERR(locomolcd_bl_device)) return PTR_ERR(locomolcd_bl_device); /* Set up frontlight so that screen is readable */ locomolcd_bl_device->props.brightness = 2; locomolcd_set_intensity(locomolcd_bl_device); return 0; } static void locomolcd_remove(struct locomo_dev *dev) { unsigned long flags; locomolcd_bl_device->props.brightness = 0; locomolcd_bl_device->props.power = 0; locomolcd_set_intensity(locomolcd_bl_device); backlight_device_unregister(locomolcd_bl_device); local_irq_save(flags); locomolcd_dev = NULL; local_irq_restore(flags); } static struct locomo_driver poodle_lcd_driver = { .drv = { .name = "locomo-backlight", .pm = &locomolcd_pm_ops, }, .devid = LOCOMO_DEVID_BACKLIGHT, .probe = locomolcd_probe, .remove = locomolcd_remove, }; static int __init locomolcd_init(void) { return locomo_driver_register(&poodle_lcd_driver); } static void __exit locomolcd_exit(void) { locomo_driver_unregister(&poodle_lcd_driver); } module_init(locomolcd_init); module_exit(locomolcd_exit); MODULE_AUTHOR("John Lenz <[email protected]>, Pavel Machek <[email protected]>"); MODULE_DESCRIPTION("Collie LCD driver"); MODULE_LICENSE("GPL");
linux-master
drivers/video/backlight/locomolcd.c
// SPDX-License-Identifier: GPL-2.0-only /* drivers/video/backlight/platform_lcd.c * * Copyright 2008 Simtec Electronics * Ben Dooks <[email protected]> * * Generic platform-device LCD power control interface. */ #include <linux/module.h> #include <linux/platform_device.h> #include <linux/fb.h> #include <linux/backlight.h> #include <linux/lcd.h> #include <linux/slab.h> #include <video/platform_lcd.h> struct platform_lcd { struct device *us; struct lcd_device *lcd; struct plat_lcd_data *pdata; unsigned int power; unsigned int suspended:1; }; static inline struct platform_lcd *to_our_lcd(struct lcd_device *lcd) { return lcd_get_data(lcd); } static int platform_lcd_get_power(struct lcd_device *lcd) { struct platform_lcd *plcd = to_our_lcd(lcd); return plcd->power; } static int platform_lcd_set_power(struct lcd_device *lcd, int power) { struct platform_lcd *plcd = to_our_lcd(lcd); int lcd_power = 1; if (power == FB_BLANK_POWERDOWN || plcd->suspended) lcd_power = 0; plcd->pdata->set_power(plcd->pdata, lcd_power); plcd->power = power; return 0; } static int platform_lcd_match(struct lcd_device *lcd, struct fb_info *info) { struct platform_lcd *plcd = to_our_lcd(lcd); struct plat_lcd_data *pdata = plcd->pdata; if (pdata->match_fb) return pdata->match_fb(pdata, info); return plcd->us->parent == info->device; } static struct lcd_ops platform_lcd_ops = { .get_power = platform_lcd_get_power, .set_power = platform_lcd_set_power, .check_fb = platform_lcd_match, }; static int platform_lcd_probe(struct platform_device *pdev) { struct plat_lcd_data *pdata; struct platform_lcd *plcd; struct device *dev = &pdev->dev; int err; pdata = dev_get_platdata(&pdev->dev); if (!pdata) { dev_err(dev, "no platform data supplied\n"); return -EINVAL; } if (pdata->probe) { err = pdata->probe(pdata); if (err) return err; } plcd = devm_kzalloc(&pdev->dev, sizeof(struct platform_lcd), GFP_KERNEL); if (!plcd) return -ENOMEM; plcd->us = dev; plcd->pdata = pdata; plcd->lcd = devm_lcd_device_register(&pdev->dev, dev_name(dev), dev, plcd, &platform_lcd_ops); if (IS_ERR(plcd->lcd)) { dev_err(dev, "cannot register lcd device\n"); return PTR_ERR(plcd->lcd); } platform_set_drvdata(pdev, plcd); platform_lcd_set_power(plcd->lcd, FB_BLANK_NORMAL); return 0; } #ifdef CONFIG_PM_SLEEP static int platform_lcd_suspend(struct device *dev) { struct platform_lcd *plcd = dev_get_drvdata(dev); plcd->suspended = 1; platform_lcd_set_power(plcd->lcd, plcd->power); return 0; } static int platform_lcd_resume(struct device *dev) { struct platform_lcd *plcd = dev_get_drvdata(dev); plcd->suspended = 0; platform_lcd_set_power(plcd->lcd, plcd->power); return 0; } #endif static SIMPLE_DEV_PM_OPS(platform_lcd_pm_ops, platform_lcd_suspend, platform_lcd_resume); static struct platform_driver platform_lcd_driver = { .driver = { .name = "platform-lcd", .pm = &platform_lcd_pm_ops, }, .probe = platform_lcd_probe, }; module_platform_driver(platform_lcd_driver); MODULE_AUTHOR("Ben Dooks <[email protected]>"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("platform:platform-lcd");
linux-master
drivers/video/backlight/platform_lcd.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Backlight Driver for Dialog DA9052 PMICs * * Copyright(c) 2012 Dialog Semiconductor Ltd. * * Author: David Dajun Chen <[email protected]> */ #include <linux/backlight.h> #include <linux/delay.h> #include <linux/fb.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/mfd/da9052/da9052.h> #include <linux/mfd/da9052/reg.h> #define DA9052_MAX_BRIGHTNESS 0xFF enum { DA9052_WLEDS_OFF, DA9052_WLEDS_ON, }; enum { DA9052_TYPE_WLED1, DA9052_TYPE_WLED2, DA9052_TYPE_WLED3, }; static const unsigned char wled_bank[] = { DA9052_LED1_CONF_REG, DA9052_LED2_CONF_REG, DA9052_LED3_CONF_REG, }; struct da9052_bl { struct da9052 *da9052; uint brightness; uint state; uint led_reg; }; static int da9052_adjust_wled_brightness(struct da9052_bl *wleds) { unsigned char boost_en; unsigned char i_sink; int ret; boost_en = 0x3F; i_sink = 0xFF; if (wleds->state == DA9052_WLEDS_OFF) { boost_en = 0x00; i_sink = 0x00; } ret = da9052_reg_write(wleds->da9052, DA9052_BOOST_REG, boost_en); if (ret < 0) return ret; ret = da9052_reg_write(wleds->da9052, DA9052_LED_CONT_REG, i_sink); if (ret < 0) return ret; ret = da9052_reg_write(wleds->da9052, wled_bank[wleds->led_reg], 0x0); if (ret < 0) return ret; usleep_range(10000, 11000); if (wleds->brightness) { ret = da9052_reg_write(wleds->da9052, wled_bank[wleds->led_reg], wleds->brightness); if (ret < 0) return ret; } return 0; } static int da9052_backlight_update_status(struct backlight_device *bl) { int brightness = bl->props.brightness; struct da9052_bl *wleds = bl_get_data(bl); wleds->brightness = brightness; wleds->state = DA9052_WLEDS_ON; return da9052_adjust_wled_brightness(wleds); } static int da9052_backlight_get_brightness(struct backlight_device *bl) { struct da9052_bl *wleds = bl_get_data(bl); return wleds->brightness; } static const struct backlight_ops da9052_backlight_ops = { .update_status = da9052_backlight_update_status, .get_brightness = da9052_backlight_get_brightness, }; static int da9052_backlight_probe(struct platform_device *pdev) { struct backlight_device *bl; struct backlight_properties props; struct da9052_bl *wleds; wleds = devm_kzalloc(&pdev->dev, sizeof(struct da9052_bl), GFP_KERNEL); if (!wleds) return -ENOMEM; wleds->da9052 = dev_get_drvdata(pdev->dev.parent); wleds->brightness = 0; wleds->led_reg = platform_get_device_id(pdev)->driver_data; wleds->state = DA9052_WLEDS_OFF; props.type = BACKLIGHT_RAW; props.max_brightness = DA9052_MAX_BRIGHTNESS; bl = devm_backlight_device_register(&pdev->dev, pdev->name, wleds->da9052->dev, wleds, &da9052_backlight_ops, &props); if (IS_ERR(bl)) { dev_err(&pdev->dev, "Failed to register backlight\n"); return PTR_ERR(bl); } bl->props.max_brightness = DA9052_MAX_BRIGHTNESS; bl->props.brightness = 0; platform_set_drvdata(pdev, bl); return da9052_adjust_wled_brightness(wleds); } static void da9052_backlight_remove(struct platform_device *pdev) { struct backlight_device *bl = platform_get_drvdata(pdev); struct da9052_bl *wleds = bl_get_data(bl); wleds->brightness = 0; wleds->state = DA9052_WLEDS_OFF; da9052_adjust_wled_brightness(wleds); } static const struct platform_device_id da9052_wled_ids[] = { { .name = "da9052-wled1", .driver_data = DA9052_TYPE_WLED1, }, { .name = "da9052-wled2", .driver_data = DA9052_TYPE_WLED2, }, { .name = "da9052-wled3", .driver_data = DA9052_TYPE_WLED3, }, { }, }; MODULE_DEVICE_TABLE(platform, da9052_wled_ids); static struct platform_driver da9052_wled_driver = { .probe = da9052_backlight_probe, .remove_new = da9052_backlight_remove, .id_table = da9052_wled_ids, .driver = { .name = "da9052-wled", }, }; module_platform_driver(da9052_wled_driver); MODULE_AUTHOR("David Dajun Chen <[email protected]>"); MODULE_DESCRIPTION("Backlight driver for DA9052 PMIC"); MODULE_LICENSE("GPL");
linux-master
drivers/video/backlight/da9052_bl.c
// SPDX-License-Identifier: GPL-2.0-only /* * sky81452-backlight.c SKY81452 backlight driver * * Copyright 2014 Skyworks Solutions Inc. * Author : Gyungoh Yoo <[email protected]> */ #include <linux/backlight.h> #include <linux/err.h> #include <linux/gpio/consumer.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/regmap.h> #include <linux/slab.h> /* registers */ #define SKY81452_REG0 0x00 #define SKY81452_REG1 0x01 #define SKY81452_REG2 0x02 #define SKY81452_REG4 0x04 #define SKY81452_REG5 0x05 /* bit mask */ #define SKY81452_CS 0xFF #define SKY81452_EN 0x3F #define SKY81452_IGPW 0x20 #define SKY81452_PWMMD 0x10 #define SKY81452_PHASE 0x08 #define SKY81452_ILIM 0x04 #define SKY81452_VSHRT 0x03 #define SKY81452_OCP 0x80 #define SKY81452_OTMP 0x40 #define SKY81452_SHRT 0x3F #define SKY81452_OPN 0x3F #define SKY81452_DEFAULT_NAME "lcd-backlight" #define SKY81452_MAX_BRIGHTNESS (SKY81452_CS + 1) /** * struct sky81452_bl_platform_data - backlight platform data * @name: backlight driver name. * If it is not defined, default name is lcd-backlight. * @gpiod_enable:GPIO descriptor which control EN pin * @enable: Enable mask for current sink channel 1, 2, 3, 4, 5 and 6. * @ignore_pwm: true if DPWMI should be ignored. * @dpwm_mode: true is DPWM dimming mode, otherwise Analog dimming mode. * @phase_shift:true is phase shift mode. * @short_detection_threshold: It should be one of 4, 5, 6 and 7V. * @boost_current_limit: It should be one of 2300, 2750mA. */ struct sky81452_bl_platform_data { const char *name; struct gpio_desc *gpiod_enable; unsigned int enable; bool ignore_pwm; bool dpwm_mode; bool phase_shift; unsigned int short_detection_threshold; unsigned int boost_current_limit; }; #define CTZ(b) __builtin_ctz(b) static int sky81452_bl_update_status(struct backlight_device *bd) { const struct sky81452_bl_platform_data *pdata = dev_get_platdata(bd->dev.parent); const unsigned int brightness = (unsigned int)bd->props.brightness; struct regmap *regmap = bl_get_data(bd); int ret; if (brightness > 0) { ret = regmap_write(regmap, SKY81452_REG0, brightness - 1); if (ret < 0) return ret; return regmap_update_bits(regmap, SKY81452_REG1, SKY81452_EN, pdata->enable << CTZ(SKY81452_EN)); } return regmap_update_bits(regmap, SKY81452_REG1, SKY81452_EN, 0); } static const struct backlight_ops sky81452_bl_ops = { .update_status = sky81452_bl_update_status, }; static ssize_t sky81452_bl_store_enable(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct regmap *regmap = bl_get_data(to_backlight_device(dev)); unsigned long value; int ret; ret = kstrtoul(buf, 16, &value); if (ret < 0) return ret; ret = regmap_update_bits(regmap, SKY81452_REG1, SKY81452_EN, value << CTZ(SKY81452_EN)); if (ret < 0) return ret; return count; } static ssize_t sky81452_bl_show_open_short(struct device *dev, struct device_attribute *attr, char *buf) { struct regmap *regmap = bl_get_data(to_backlight_device(dev)); unsigned int reg, value = 0; char tmp[3]; int i, ret; reg = !strcmp(attr->attr.name, "open") ? SKY81452_REG5 : SKY81452_REG4; ret = regmap_read(regmap, reg, &value); if (ret < 0) return ret; if (value & SKY81452_SHRT) { *buf = 0; for (i = 0; i < 6; i++) { if (value & 0x01) { sprintf(tmp, "%d ", i + 1); strcat(buf, tmp); } value >>= 1; } strcat(buf, "\n"); } else { strcpy(buf, "none\n"); } return strlen(buf); } static ssize_t sky81452_bl_show_fault(struct device *dev, struct device_attribute *attr, char *buf) { struct regmap *regmap = bl_get_data(to_backlight_device(dev)); unsigned int value = 0; int ret; ret = regmap_read(regmap, SKY81452_REG4, &value); if (ret < 0) return ret; *buf = 0; if (value & SKY81452_OCP) strcat(buf, "over-current "); if (value & SKY81452_OTMP) strcat(buf, "over-temperature"); strcat(buf, "\n"); return strlen(buf); } static DEVICE_ATTR(enable, S_IWGRP | S_IWUSR, NULL, sky81452_bl_store_enable); static DEVICE_ATTR(open, S_IRUGO, sky81452_bl_show_open_short, NULL); static DEVICE_ATTR(short, S_IRUGO, sky81452_bl_show_open_short, NULL); static DEVICE_ATTR(fault, S_IRUGO, sky81452_bl_show_fault, NULL); static struct attribute *sky81452_bl_attribute[] = { &dev_attr_enable.attr, &dev_attr_open.attr, &dev_attr_short.attr, &dev_attr_fault.attr, NULL }; static const struct attribute_group sky81452_bl_attr_group = { .attrs = sky81452_bl_attribute, }; #ifdef CONFIG_OF static struct sky81452_bl_platform_data *sky81452_bl_parse_dt( struct device *dev) { struct device_node *np = of_node_get(dev->of_node); struct sky81452_bl_platform_data *pdata; int num_entry; unsigned int sources[6]; int ret; if (!np) { dev_err(dev, "backlight node not found.\n"); return ERR_PTR(-ENODATA); } pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL); if (!pdata) { of_node_put(np); return ERR_PTR(-ENOMEM); } of_property_read_string(np, "name", &pdata->name); pdata->ignore_pwm = of_property_read_bool(np, "skyworks,ignore-pwm"); pdata->dpwm_mode = of_property_read_bool(np, "skyworks,dpwm-mode"); pdata->phase_shift = of_property_read_bool(np, "skyworks,phase-shift"); pdata->gpiod_enable = devm_gpiod_get_optional(dev, NULL, GPIOD_OUT_HIGH); ret = of_property_count_u32_elems(np, "led-sources"); if (ret < 0) { pdata->enable = SKY81452_EN >> CTZ(SKY81452_EN); } else { num_entry = ret; if (num_entry > 6) num_entry = 6; ret = of_property_read_u32_array(np, "led-sources", sources, num_entry); if (ret < 0) { dev_err(dev, "led-sources node is invalid.\n"); of_node_put(np); return ERR_PTR(-EINVAL); } pdata->enable = 0; while (--num_entry) pdata->enable |= (1 << sources[num_entry]); } ret = of_property_read_u32(np, "skyworks,short-detection-threshold-volt", &pdata->short_detection_threshold); if (ret < 0) pdata->short_detection_threshold = 7; ret = of_property_read_u32(np, "skyworks,current-limit-mA", &pdata->boost_current_limit); if (ret < 0) pdata->boost_current_limit = 2750; of_node_put(np); return pdata; } #else static struct sky81452_bl_platform_data *sky81452_bl_parse_dt( struct device *dev) { return ERR_PTR(-EINVAL); } #endif static int sky81452_bl_init_device(struct regmap *regmap, struct sky81452_bl_platform_data *pdata) { unsigned int value; value = pdata->ignore_pwm ? SKY81452_IGPW : 0; value |= pdata->dpwm_mode ? SKY81452_PWMMD : 0; value |= pdata->phase_shift ? 0 : SKY81452_PHASE; if (pdata->boost_current_limit == 2300) value |= SKY81452_ILIM; else if (pdata->boost_current_limit != 2750) return -EINVAL; if (pdata->short_detection_threshold < 4 || pdata->short_detection_threshold > 7) return -EINVAL; value |= (7 - pdata->short_detection_threshold) << CTZ(SKY81452_VSHRT); return regmap_write(regmap, SKY81452_REG2, value); } static int sky81452_bl_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct regmap *regmap = dev_get_drvdata(dev->parent); struct sky81452_bl_platform_data *pdata; struct backlight_device *bd; struct backlight_properties props; const char *name; int ret; pdata = sky81452_bl_parse_dt(dev); if (IS_ERR(pdata)) return PTR_ERR(pdata); ret = sky81452_bl_init_device(regmap, pdata); if (ret < 0) { dev_err(dev, "failed to initialize. err=%d\n", ret); return ret; } memset(&props, 0, sizeof(props)); props.max_brightness = SKY81452_MAX_BRIGHTNESS; name = pdata->name ? pdata->name : SKY81452_DEFAULT_NAME; bd = devm_backlight_device_register(dev, name, dev, regmap, &sky81452_bl_ops, &props); if (IS_ERR(bd)) { dev_err(dev, "failed to register. err=%ld\n", PTR_ERR(bd)); return PTR_ERR(bd); } platform_set_drvdata(pdev, bd); ret = sysfs_create_group(&bd->dev.kobj, &sky81452_bl_attr_group); if (ret < 0) { dev_err(dev, "failed to create attribute. err=%d\n", ret); return ret; } return ret; } static void sky81452_bl_remove(struct platform_device *pdev) { const struct sky81452_bl_platform_data *pdata = dev_get_platdata(&pdev->dev); struct backlight_device *bd = platform_get_drvdata(pdev); sysfs_remove_group(&bd->dev.kobj, &sky81452_bl_attr_group); bd->props.power = FB_BLANK_UNBLANK; bd->props.brightness = 0; backlight_update_status(bd); if (pdata->gpiod_enable) gpiod_set_value_cansleep(pdata->gpiod_enable, 0); } #ifdef CONFIG_OF static const struct of_device_id sky81452_bl_of_match[] = { { .compatible = "skyworks,sky81452-backlight", }, { } }; MODULE_DEVICE_TABLE(of, sky81452_bl_of_match); #endif static struct platform_driver sky81452_bl_driver = { .driver = { .name = "sky81452-backlight", .of_match_table = of_match_ptr(sky81452_bl_of_match), }, .probe = sky81452_bl_probe, .remove_new = sky81452_bl_remove, }; module_platform_driver(sky81452_bl_driver); MODULE_DESCRIPTION("Skyworks SKY81452 backlight driver"); MODULE_AUTHOR("Gyungoh Yoo <[email protected]>"); MODULE_LICENSE("GPL v2");
linux-master
drivers/video/backlight/sky81452-backlight.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Backlight driver for OMAP based boards. * * Copyright (c) 2006 Andrzej Zaborowski <[email protected]> */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/fb.h> #include <linux/backlight.h> #include <linux/slab.h> #include <linux/platform_data/omap1_bl.h> #include <linux/soc/ti/omap1-io.h> #include <linux/soc/ti/omap1-mux.h> #define OMAPBL_MAX_INTENSITY 0xff struct omap_backlight { int powermode; int current_intensity; struct device *dev; struct omap_backlight_config *pdata; }; static inline void omapbl_send_intensity(int intensity) { omap_writeb(intensity, OMAP_PWL_ENABLE); } static inline void omapbl_send_enable(int enable) { omap_writeb(enable, OMAP_PWL_CLK_ENABLE); } static void omapbl_blank(struct omap_backlight *bl, int mode) { if (bl->pdata->set_power) bl->pdata->set_power(bl->dev, mode); switch (mode) { case FB_BLANK_NORMAL: case FB_BLANK_VSYNC_SUSPEND: case FB_BLANK_HSYNC_SUSPEND: case FB_BLANK_POWERDOWN: omapbl_send_intensity(0); omapbl_send_enable(0); break; case FB_BLANK_UNBLANK: omapbl_send_intensity(bl->current_intensity); omapbl_send_enable(1); break; } } #ifdef CONFIG_PM_SLEEP static int omapbl_suspend(struct device *dev) { struct backlight_device *bl_dev = dev_get_drvdata(dev); struct omap_backlight *bl = bl_get_data(bl_dev); omapbl_blank(bl, FB_BLANK_POWERDOWN); return 0; } static int omapbl_resume(struct device *dev) { struct backlight_device *bl_dev = dev_get_drvdata(dev); struct omap_backlight *bl = bl_get_data(bl_dev); omapbl_blank(bl, bl->powermode); return 0; } #endif static int omapbl_set_power(struct backlight_device *dev, int state) { struct omap_backlight *bl = bl_get_data(dev); omapbl_blank(bl, state); bl->powermode = state; return 0; } static int omapbl_update_status(struct backlight_device *dev) { struct omap_backlight *bl = bl_get_data(dev); if (bl->current_intensity != dev->props.brightness) { if (bl->powermode == FB_BLANK_UNBLANK) omapbl_send_intensity(dev->props.brightness); bl->current_intensity = dev->props.brightness; } if (dev->props.fb_blank != bl->powermode) omapbl_set_power(dev, dev->props.fb_blank); return 0; } static int omapbl_get_intensity(struct backlight_device *dev) { struct omap_backlight *bl = bl_get_data(dev); return bl->current_intensity; } static const struct backlight_ops omapbl_ops = { .get_brightness = omapbl_get_intensity, .update_status = omapbl_update_status, }; static int omapbl_probe(struct platform_device *pdev) { struct backlight_properties props; struct backlight_device *dev; struct omap_backlight *bl; struct omap_backlight_config *pdata = dev_get_platdata(&pdev->dev); if (!pdata) return -ENXIO; bl = devm_kzalloc(&pdev->dev, sizeof(struct omap_backlight), GFP_KERNEL); if (unlikely(!bl)) return -ENOMEM; memset(&props, 0, sizeof(struct backlight_properties)); props.type = BACKLIGHT_RAW; props.max_brightness = OMAPBL_MAX_INTENSITY; dev = devm_backlight_device_register(&pdev->dev, "omap-bl", &pdev->dev, bl, &omapbl_ops, &props); if (IS_ERR(dev)) return PTR_ERR(dev); bl->powermode = FB_BLANK_POWERDOWN; bl->current_intensity = 0; bl->pdata = pdata; bl->dev = &pdev->dev; platform_set_drvdata(pdev, dev); omap_cfg_reg(PWL); /* Conflicts with UART3 */ dev->props.fb_blank = FB_BLANK_UNBLANK; dev->props.brightness = pdata->default_intensity; omapbl_update_status(dev); dev_info(&pdev->dev, "OMAP LCD backlight initialised\n"); return 0; } static SIMPLE_DEV_PM_OPS(omapbl_pm_ops, omapbl_suspend, omapbl_resume); static struct platform_driver omapbl_driver = { .probe = omapbl_probe, .driver = { .name = "omap-bl", .pm = &omapbl_pm_ops, }, }; module_platform_driver(omapbl_driver); MODULE_AUTHOR("Andrzej Zaborowski <[email protected]>"); MODULE_DESCRIPTION("OMAP LCD Backlight driver"); MODULE_LICENSE("GPL");
linux-master
drivers/video/backlight/omap1_bl.c
// SPDX-License-Identifier: GPL-2.0-only /* * Backlight driver for ArcticSand ARC_X_C_0N_0N Devices * * Copyright 2016 ArcticSand, Inc. * Author : Brian Dodge <[email protected]> */ #include <linux/backlight.h> #include <linux/err.h> #include <linux/i2c.h> #include <linux/module.h> #include <linux/of.h> #include <linux/slab.h> enum arcxcnn_chip_id { ARC2C0608 }; /** * struct arcxcnn_platform_data * @name : Backlight driver name (NULL will use default) * @initial_brightness : initial value of backlight brightness * @leden : initial LED string enables, upper bit is global on/off * @led_config_0 : fading speed (period between intensity steps) * @led_config_1 : misc settings, see datasheet * @dim_freq : pwm dimming frequency if in pwm mode * @comp_config : misc config, see datasheet * @filter_config : RC/PWM filter config, see datasheet * @trim_config : full scale current trim, see datasheet */ struct arcxcnn_platform_data { const char *name; u16 initial_brightness; u8 leden; u8 led_config_0; u8 led_config_1; u8 dim_freq; u8 comp_config; u8 filter_config; u8 trim_config; }; #define ARCXCNN_CMD 0x00 /* Command Register */ #define ARCXCNN_CMD_STDBY 0x80 /* I2C Standby */ #define ARCXCNN_CMD_RESET 0x40 /* Reset */ #define ARCXCNN_CMD_BOOST 0x10 /* Boost */ #define ARCXCNN_CMD_OVP_MASK 0x0C /* --- Over Voltage Threshold */ #define ARCXCNN_CMD_OVP_XXV 0x0C /* <rsvrd> Over Voltage Threshold */ #define ARCXCNN_CMD_OVP_20V 0x08 /* 20v Over Voltage Threshold */ #define ARCXCNN_CMD_OVP_24V 0x04 /* 24v Over Voltage Threshold */ #define ARCXCNN_CMD_OVP_31V 0x00 /* 31.4v Over Voltage Threshold */ #define ARCXCNN_CMD_EXT_COMP 0x01 /* part (0) or full (1) ext. comp */ #define ARCXCNN_CONFIG 0x01 /* Configuration */ #define ARCXCNN_STATUS1 0x02 /* Status 1 */ #define ARCXCNN_STATUS2 0x03 /* Status 2 */ #define ARCXCNN_FADECTRL 0x04 /* Fading Control */ #define ARCXCNN_ILED_CONFIG 0x05 /* ILED Configuration */ #define ARCXCNN_ILED_DIM_PWM 0x00 /* config dim mode pwm */ #define ARCXCNN_ILED_DIM_INT 0x04 /* config dim mode internal */ #define ARCXCNN_LEDEN 0x06 /* LED Enable Register */ #define ARCXCNN_LEDEN_ISETEXT 0x80 /* Full-scale current set extern */ #define ARCXCNN_LEDEN_MASK 0x3F /* LED string enables mask */ #define ARCXCNN_LEDEN_BITS 0x06 /* Bits of LED string enables */ #define ARCXCNN_LEDEN_LED1 0x01 #define ARCXCNN_LEDEN_LED2 0x02 #define ARCXCNN_LEDEN_LED3 0x04 #define ARCXCNN_LEDEN_LED4 0x08 #define ARCXCNN_LEDEN_LED5 0x10 #define ARCXCNN_LEDEN_LED6 0x20 #define ARCXCNN_WLED_ISET_LSB 0x07 /* LED ISET LSB (in upper nibble) */ #define ARCXCNN_WLED_ISET_LSB_SHIFT 0x04 /* ISET LSB Left Shift */ #define ARCXCNN_WLED_ISET_MSB 0x08 /* LED ISET MSB (8 bits) */ #define ARCXCNN_DIMFREQ 0x09 #define ARCXCNN_COMP_CONFIG 0x0A #define ARCXCNN_FILT_CONFIG 0x0B #define ARCXCNN_IMAXTUNE 0x0C #define ARCXCNN_ID_MSB 0x1E #define ARCXCNN_ID_LSB 0x1F #define MAX_BRIGHTNESS 4095 #define INIT_BRIGHT 60 struct arcxcnn { struct i2c_client *client; struct backlight_device *bl; struct device *dev; struct arcxcnn_platform_data *pdata; }; static int arcxcnn_update_field(struct arcxcnn *lp, u8 reg, u8 mask, u8 data) { int ret; u8 tmp; ret = i2c_smbus_read_byte_data(lp->client, reg); if (ret < 0) { dev_err(lp->dev, "failed to read 0x%.2x\n", reg); return ret; } tmp = (u8)ret; tmp &= ~mask; tmp |= data & mask; return i2c_smbus_write_byte_data(lp->client, reg, tmp); } static int arcxcnn_set_brightness(struct arcxcnn *lp, u32 brightness) { int ret; u8 val; /* lower nibble of brightness goes in upper nibble of LSB register */ val = (brightness & 0xF) << ARCXCNN_WLED_ISET_LSB_SHIFT; ret = i2c_smbus_write_byte_data(lp->client, ARCXCNN_WLED_ISET_LSB, val); if (ret < 0) return ret; /* remaining 8 bits of brightness go in MSB register */ val = (brightness >> 4); return i2c_smbus_write_byte_data(lp->client, ARCXCNN_WLED_ISET_MSB, val); } static int arcxcnn_bl_update_status(struct backlight_device *bl) { struct arcxcnn *lp = bl_get_data(bl); u32 brightness = backlight_get_brightness(bl); int ret; ret = arcxcnn_set_brightness(lp, brightness); if (ret) return ret; /* set power-on/off/save modes */ return arcxcnn_update_field(lp, ARCXCNN_CMD, ARCXCNN_CMD_STDBY, (bl->props.power == 0) ? 0 : ARCXCNN_CMD_STDBY); } static const struct backlight_ops arcxcnn_bl_ops = { .options = BL_CORE_SUSPENDRESUME, .update_status = arcxcnn_bl_update_status, }; static int arcxcnn_backlight_register(struct arcxcnn *lp) { struct backlight_properties *props; const char *name = lp->pdata->name ? : "arctic_bl"; props = devm_kzalloc(lp->dev, sizeof(*props), GFP_KERNEL); if (!props) return -ENOMEM; props->type = BACKLIGHT_PLATFORM; props->max_brightness = MAX_BRIGHTNESS; if (lp->pdata->initial_brightness > props->max_brightness) lp->pdata->initial_brightness = props->max_brightness; props->brightness = lp->pdata->initial_brightness; lp->bl = devm_backlight_device_register(lp->dev, name, lp->dev, lp, &arcxcnn_bl_ops, props); return PTR_ERR_OR_ZERO(lp->bl); } static void arcxcnn_parse_dt(struct arcxcnn *lp) { struct device *dev = lp->dev; struct device_node *node = dev->of_node; u32 prog_val, num_entry, entry, sources[ARCXCNN_LEDEN_BITS]; int ret; /* device tree entry isn't required, defaults are OK */ if (!node) return; ret = of_property_read_string(node, "label", &lp->pdata->name); if (ret < 0) lp->pdata->name = NULL; ret = of_property_read_u32(node, "default-brightness", &prog_val); if (ret == 0) lp->pdata->initial_brightness = prog_val; ret = of_property_read_u32(node, "arc,led-config-0", &prog_val); if (ret == 0) lp->pdata->led_config_0 = (u8)prog_val; ret = of_property_read_u32(node, "arc,led-config-1", &prog_val); if (ret == 0) lp->pdata->led_config_1 = (u8)prog_val; ret = of_property_read_u32(node, "arc,dim-freq", &prog_val); if (ret == 0) lp->pdata->dim_freq = (u8)prog_val; ret = of_property_read_u32(node, "arc,comp-config", &prog_val); if (ret == 0) lp->pdata->comp_config = (u8)prog_val; ret = of_property_read_u32(node, "arc,filter-config", &prog_val); if (ret == 0) lp->pdata->filter_config = (u8)prog_val; ret = of_property_read_u32(node, "arc,trim-config", &prog_val); if (ret == 0) lp->pdata->trim_config = (u8)prog_val; ret = of_property_count_u32_elems(node, "led-sources"); if (ret < 0) { lp->pdata->leden = ARCXCNN_LEDEN_MASK; /* all on is default */ } else { num_entry = ret; if (num_entry > ARCXCNN_LEDEN_BITS) num_entry = ARCXCNN_LEDEN_BITS; ret = of_property_read_u32_array(node, "led-sources", sources, num_entry); if (ret < 0) { dev_err(dev, "led-sources node is invalid.\n"); return; } lp->pdata->leden = 0; /* for each enable in source, set bit in led enable */ for (entry = 0; entry < num_entry; entry++) { u8 onbit = 1 << sources[entry]; lp->pdata->leden |= onbit; } } } static int arcxcnn_probe(struct i2c_client *cl) { struct arcxcnn *lp; int ret; if (!i2c_check_functionality(cl->adapter, I2C_FUNC_SMBUS_BYTE_DATA)) return -EIO; lp = devm_kzalloc(&cl->dev, sizeof(*lp), GFP_KERNEL); if (!lp) return -ENOMEM; lp->client = cl; lp->dev = &cl->dev; lp->pdata = dev_get_platdata(&cl->dev); /* reset the device */ ret = i2c_smbus_write_byte_data(lp->client, ARCXCNN_CMD, ARCXCNN_CMD_RESET); if (ret) goto probe_err; if (!lp->pdata) { lp->pdata = devm_kzalloc(lp->dev, sizeof(*lp->pdata), GFP_KERNEL); if (!lp->pdata) return -ENOMEM; /* Setup defaults based on power-on defaults */ lp->pdata->name = NULL; lp->pdata->initial_brightness = INIT_BRIGHT; lp->pdata->leden = ARCXCNN_LEDEN_MASK; lp->pdata->led_config_0 = i2c_smbus_read_byte_data( lp->client, ARCXCNN_FADECTRL); lp->pdata->led_config_1 = i2c_smbus_read_byte_data( lp->client, ARCXCNN_ILED_CONFIG); /* insure dim mode is not default pwm */ lp->pdata->led_config_1 |= ARCXCNN_ILED_DIM_INT; lp->pdata->dim_freq = i2c_smbus_read_byte_data( lp->client, ARCXCNN_DIMFREQ); lp->pdata->comp_config = i2c_smbus_read_byte_data( lp->client, ARCXCNN_COMP_CONFIG); lp->pdata->filter_config = i2c_smbus_read_byte_data( lp->client, ARCXCNN_FILT_CONFIG); lp->pdata->trim_config = i2c_smbus_read_byte_data( lp->client, ARCXCNN_IMAXTUNE); if (IS_ENABLED(CONFIG_OF)) arcxcnn_parse_dt(lp); } i2c_set_clientdata(cl, lp); /* constrain settings to what is possible */ if (lp->pdata->initial_brightness > MAX_BRIGHTNESS) lp->pdata->initial_brightness = MAX_BRIGHTNESS; /* set initial brightness */ ret = arcxcnn_set_brightness(lp, lp->pdata->initial_brightness); if (ret) goto probe_err; /* set other register values directly */ ret = i2c_smbus_write_byte_data(lp->client, ARCXCNN_FADECTRL, lp->pdata->led_config_0); if (ret) goto probe_err; ret = i2c_smbus_write_byte_data(lp->client, ARCXCNN_ILED_CONFIG, lp->pdata->led_config_1); if (ret) goto probe_err; ret = i2c_smbus_write_byte_data(lp->client, ARCXCNN_DIMFREQ, lp->pdata->dim_freq); if (ret) goto probe_err; ret = i2c_smbus_write_byte_data(lp->client, ARCXCNN_COMP_CONFIG, lp->pdata->comp_config); if (ret) goto probe_err; ret = i2c_smbus_write_byte_data(lp->client, ARCXCNN_FILT_CONFIG, lp->pdata->filter_config); if (ret) goto probe_err; ret = i2c_smbus_write_byte_data(lp->client, ARCXCNN_IMAXTUNE, lp->pdata->trim_config); if (ret) goto probe_err; /* set initial LED Enables */ arcxcnn_update_field(lp, ARCXCNN_LEDEN, ARCXCNN_LEDEN_MASK, lp->pdata->leden); ret = arcxcnn_backlight_register(lp); if (ret) goto probe_register_err; backlight_update_status(lp->bl); return 0; probe_register_err: dev_err(lp->dev, "failed to register backlight.\n"); probe_err: dev_err(lp->dev, "failure ret: %d\n", ret); return ret; } static void arcxcnn_remove(struct i2c_client *cl) { struct arcxcnn *lp = i2c_get_clientdata(cl); /* disable all strings (ignore errors) */ i2c_smbus_write_byte_data(lp->client, ARCXCNN_LEDEN, 0x00); /* reset the device (ignore errors) */ i2c_smbus_write_byte_data(lp->client, ARCXCNN_CMD, ARCXCNN_CMD_RESET); lp->bl->props.brightness = 0; backlight_update_status(lp->bl); } static const struct of_device_id arcxcnn_dt_ids[] = { { .compatible = "arc,arc2c0608" }, { } }; MODULE_DEVICE_TABLE(of, arcxcnn_dt_ids); static const struct i2c_device_id arcxcnn_ids[] = { {"arc2c0608", ARC2C0608}, { } }; MODULE_DEVICE_TABLE(i2c, arcxcnn_ids); static struct i2c_driver arcxcnn_driver = { .driver = { .name = "arcxcnn_bl", .of_match_table = arcxcnn_dt_ids, }, .probe = arcxcnn_probe, .remove = arcxcnn_remove, .id_table = arcxcnn_ids, }; module_i2c_driver(arcxcnn_driver); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Brian Dodge <[email protected]>"); MODULE_DESCRIPTION("ARCXCNN Backlight driver");
linux-master
drivers/video/backlight/arcxcnn_bl.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (c) Intel Corp. 2007. * All Rights Reserved. * * Intel funded Tungsten Graphics (http://www.tungstengraphics.com) to * develop this driver. * * This file is part of the Carillo Ranch video subsystem driver. * * Authors: * Thomas Hellstrom <thomas-at-tungstengraphics-dot-com> * Alan Hourihane <alanh-at-tungstengraphics-dot-com> */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/mutex.h> #include <linux/fb.h> #include <linux/backlight.h> #include <linux/lcd.h> #include <linux/pci.h> #include <linux/slab.h> /* The LVDS- and panel power controls sits on the * GPIO port of the ISA bridge. */ #define CRVML_DEVICE_LPC 0x27B8 #define CRVML_REG_GPIOBAR 0x48 #define CRVML_REG_GPIOEN 0x4C #define CRVML_GPIOEN_BIT (1 << 4) #define CRVML_PANEL_PORT 0x38 #define CRVML_LVDS_ON 0x00000001 #define CRVML_PANEL_ON 0x00000002 #define CRVML_BACKLIGHT_OFF 0x00000004 /* The PLL Clock register sits on Host bridge */ #define CRVML_DEVICE_MCH 0x5001 #define CRVML_REG_MCHBAR 0x44 #define CRVML_REG_MCHEN 0x54 #define CRVML_MCHEN_BIT (1 << 28) #define CRVML_MCHMAP_SIZE 4096 #define CRVML_REG_CLOCK 0xc3c #define CRVML_CLOCK_SHIFT 8 #define CRVML_CLOCK_MASK 0x00000f00 static struct pci_dev *lpc_dev; static u32 gpio_bar; struct cr_panel { struct backlight_device *cr_backlight_device; struct lcd_device *cr_lcd_device; }; static int cr_backlight_set_intensity(struct backlight_device *bd) { u32 addr = gpio_bar + CRVML_PANEL_PORT; u32 cur = inl(addr); if (backlight_get_brightness(bd) == 0) { /* OFF */ cur |= CRVML_BACKLIGHT_OFF; outl(cur, addr); } else { /* FULL ON */ cur &= ~CRVML_BACKLIGHT_OFF; outl(cur, addr); } return 0; } static int cr_backlight_get_intensity(struct backlight_device *bd) { u32 addr = gpio_bar + CRVML_PANEL_PORT; u32 cur = inl(addr); u8 intensity; if (cur & CRVML_BACKLIGHT_OFF) intensity = 0; else intensity = 1; return intensity; } static const struct backlight_ops cr_backlight_ops = { .get_brightness = cr_backlight_get_intensity, .update_status = cr_backlight_set_intensity, }; static void cr_panel_on(void) { u32 addr = gpio_bar + CRVML_PANEL_PORT; u32 cur = inl(addr); if (!(cur & CRVML_PANEL_ON)) { /* Make sure LVDS controller is down. */ if (cur & 0x00000001) { cur &= ~CRVML_LVDS_ON; outl(cur, addr); } /* Power up Panel */ schedule_timeout(HZ / 10); cur |= CRVML_PANEL_ON; outl(cur, addr); } /* Power up LVDS controller */ if (!(cur & CRVML_LVDS_ON)) { schedule_timeout(HZ / 10); outl(cur | CRVML_LVDS_ON, addr); } } static void cr_panel_off(void) { u32 addr = gpio_bar + CRVML_PANEL_PORT; u32 cur = inl(addr); /* Power down LVDS controller first to avoid high currents */ if (cur & CRVML_LVDS_ON) { cur &= ~CRVML_LVDS_ON; outl(cur, addr); } if (cur & CRVML_PANEL_ON) { schedule_timeout(HZ / 10); outl(cur & ~CRVML_PANEL_ON, addr); } } static int cr_lcd_set_power(struct lcd_device *ld, int power) { if (power == FB_BLANK_UNBLANK) cr_panel_on(); if (power == FB_BLANK_POWERDOWN) cr_panel_off(); return 0; } static struct lcd_ops cr_lcd_ops = { .set_power = cr_lcd_set_power, }; static int cr_backlight_probe(struct platform_device *pdev) { struct backlight_properties props; struct backlight_device *bdp; struct lcd_device *ldp; struct cr_panel *crp; u8 dev_en; lpc_dev = pci_get_device(PCI_VENDOR_ID_INTEL, CRVML_DEVICE_LPC, NULL); if (!lpc_dev) { pr_err("INTEL CARILLO RANCH LPC not found.\n"); return -ENODEV; } pci_read_config_byte(lpc_dev, CRVML_REG_GPIOEN, &dev_en); if (!(dev_en & CRVML_GPIOEN_BIT)) { pr_err("Carillo Ranch GPIO device was not enabled.\n"); pci_dev_put(lpc_dev); return -ENODEV; } memset(&props, 0, sizeof(struct backlight_properties)); props.type = BACKLIGHT_RAW; bdp = devm_backlight_device_register(&pdev->dev, "cr-backlight", &pdev->dev, NULL, &cr_backlight_ops, &props); if (IS_ERR(bdp)) { pci_dev_put(lpc_dev); return PTR_ERR(bdp); } ldp = devm_lcd_device_register(&pdev->dev, "cr-lcd", &pdev->dev, NULL, &cr_lcd_ops); if (IS_ERR(ldp)) { pci_dev_put(lpc_dev); return PTR_ERR(ldp); } pci_read_config_dword(lpc_dev, CRVML_REG_GPIOBAR, &gpio_bar); gpio_bar &= ~0x3F; crp = devm_kzalloc(&pdev->dev, sizeof(*crp), GFP_KERNEL); if (!crp) { pci_dev_put(lpc_dev); return -ENOMEM; } crp->cr_backlight_device = bdp; crp->cr_lcd_device = ldp; crp->cr_backlight_device->props.power = FB_BLANK_UNBLANK; crp->cr_backlight_device->props.brightness = 0; cr_backlight_set_intensity(crp->cr_backlight_device); cr_lcd_set_power(crp->cr_lcd_device, FB_BLANK_UNBLANK); platform_set_drvdata(pdev, crp); return 0; } static void cr_backlight_remove(struct platform_device *pdev) { struct cr_panel *crp = platform_get_drvdata(pdev); crp->cr_backlight_device->props.power = FB_BLANK_POWERDOWN; crp->cr_backlight_device->props.brightness = 0; crp->cr_backlight_device->props.max_brightness = 0; cr_backlight_set_intensity(crp->cr_backlight_device); cr_lcd_set_power(crp->cr_lcd_device, FB_BLANK_POWERDOWN); pci_dev_put(lpc_dev); } static struct platform_driver cr_backlight_driver = { .probe = cr_backlight_probe, .remove_new = cr_backlight_remove, .driver = { .name = "cr_backlight", }, }; static struct platform_device *crp; static int __init cr_backlight_init(void) { int ret = platform_driver_register(&cr_backlight_driver); if (ret) return ret; crp = platform_device_register_simple("cr_backlight", -1, NULL, 0); if (IS_ERR(crp)) { platform_driver_unregister(&cr_backlight_driver); return PTR_ERR(crp); } pr_info("Carillo Ranch Backlight Driver Initialized.\n"); return 0; } static void __exit cr_backlight_exit(void) { platform_device_unregister(crp); platform_driver_unregister(&cr_backlight_driver); } module_init(cr_backlight_init); module_exit(cr_backlight_exit); MODULE_AUTHOR("Tungsten Graphics Inc."); MODULE_DESCRIPTION("Carillo Ranch Backlight Driver"); MODULE_LICENSE("GPL");
linux-master
drivers/video/backlight/cr_bllcd.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * * LCD driver for HP Jornada 700 series (710/720/728) * Copyright (C) 2006-2009 Kristoffer Ericson <[email protected]> */ #include <linux/device.h> #include <linux/fb.h> #include <linux/kernel.h> #include <linux/lcd.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/delay.h> #include <mach/jornada720.h> #include <mach/hardware.h> #include <video/s1d13xxxfb.h> #define LCD_MAX_CONTRAST 0xff #define LCD_DEF_CONTRAST 0x80 static int jornada_lcd_get_power(struct lcd_device *ld) { return PPSR & PPC_LDD2 ? FB_BLANK_UNBLANK : FB_BLANK_POWERDOWN; } static int jornada_lcd_get_contrast(struct lcd_device *ld) { int ret; if (jornada_lcd_get_power(ld) != FB_BLANK_UNBLANK) return 0; jornada_ssp_start(); if (jornada_ssp_byte(GETCONTRAST) == TXDUMMY) { ret = jornada_ssp_byte(TXDUMMY); goto success; } dev_err(&ld->dev, "failed to set contrast\n"); ret = -ETIMEDOUT; success: jornada_ssp_end(); return ret; } static int jornada_lcd_set_contrast(struct lcd_device *ld, int value) { int ret = 0; jornada_ssp_start(); /* start by sending our set contrast cmd to mcu */ if (jornada_ssp_byte(SETCONTRAST) == TXDUMMY) { /* if successful push the new value */ if (jornada_ssp_byte(value) == TXDUMMY) goto success; } dev_err(&ld->dev, "failed to set contrast\n"); ret = -ETIMEDOUT; success: jornada_ssp_end(); return ret; } static int jornada_lcd_set_power(struct lcd_device *ld, int power) { if (power != FB_BLANK_UNBLANK) { PPSR &= ~PPC_LDD2; PPDR |= PPC_LDD2; } else { PPSR |= PPC_LDD2; } return 0; } static struct lcd_ops jornada_lcd_props = { .get_contrast = jornada_lcd_get_contrast, .set_contrast = jornada_lcd_set_contrast, .get_power = jornada_lcd_get_power, .set_power = jornada_lcd_set_power, }; static int jornada_lcd_probe(struct platform_device *pdev) { struct lcd_device *lcd_device; int ret; lcd_device = devm_lcd_device_register(&pdev->dev, S1D_DEVICENAME, &pdev->dev, NULL, &jornada_lcd_props); if (IS_ERR(lcd_device)) { ret = PTR_ERR(lcd_device); dev_err(&pdev->dev, "failed to register device\n"); return ret; } platform_set_drvdata(pdev, lcd_device); /* lets set our default values */ jornada_lcd_set_contrast(lcd_device, LCD_DEF_CONTRAST); jornada_lcd_set_power(lcd_device, FB_BLANK_UNBLANK); /* give it some time to startup */ msleep(100); return 0; } static struct platform_driver jornada_lcd_driver = { .probe = jornada_lcd_probe, .driver = { .name = "jornada_lcd", }, }; module_platform_driver(jornada_lcd_driver); MODULE_AUTHOR("Kristoffer Ericson <[email protected]>"); MODULE_DESCRIPTION("HP Jornada 710/720/728 LCD driver"); MODULE_LICENSE("GPL");
linux-master
drivers/video/backlight/jornada720_lcd.c