python_code
stringlengths
0
1.8M
repo_name
stringclasses
7 values
file_path
stringlengths
5
99
// SPDX-License-Identifier: GPL-2.0-only /* * Minimalist driver for a generic PCI-to-EISA bridge. * * (C) 2003 Marc Zyngier <[email protected]> * * Ivan Kokshaysky <[email protected]> : * Generalisation from i82375 to PCI_CLASS_BRIDGE_EISA. */ #include <linux/kernel.h> #include <linux/device.h> #include <linux/eisa.h> #include <linux/pci.h> #include <linux/module.h> #include <linux/init.h> /* There is only *one* pci_eisa device per machine, right ? */ static struct eisa_root_device pci_eisa_root; static int __init pci_eisa_init(struct pci_dev *pdev) { struct resource *res, *bus_res = NULL; int rc; if ((rc = pci_enable_device (pdev))) { dev_err(&pdev->dev, "Could not enable device\n"); return rc; } /* * The Intel 82375 PCI-EISA bridge is a subtractive-decode PCI * device, so the resources available on EISA are the same as those * available on the 82375 bus. This works the same as a PCI-PCI * bridge in subtractive-decode mode (see pci_read_bridge_bases()). * We assume other PCI-EISA bridges are similar. * * eisa_root_register() can only deal with a single io port resource, * so we use the first valid io port resource. */ pci_bus_for_each_resource(pdev->bus, res) if (res && (res->flags & IORESOURCE_IO)) { bus_res = res; break; } if (!bus_res) { dev_err(&pdev->dev, "No resources available\n"); return -1; } pci_eisa_root.dev = &pdev->dev; pci_eisa_root.res = bus_res; pci_eisa_root.bus_base_addr = bus_res->start; pci_eisa_root.slots = EISA_MAX_SLOTS; pci_eisa_root.dma_mask = pdev->dma_mask; dev_set_drvdata(pci_eisa_root.dev, &pci_eisa_root); if (eisa_root_register (&pci_eisa_root)) { dev_err(&pdev->dev, "Could not register EISA root\n"); return -1; } return 0; } /* * We have to call pci_eisa_init_early() before pnpacpi_init()/isapnp_init(). * Otherwise pnp resource will get enabled early and could prevent eisa * to be initialized. * Also need to make sure pci_eisa_init_early() is called after * x86/pci_subsys_init(). * So need to use subsys_initcall_sync with it. */ static int __init pci_eisa_init_early(void) { struct pci_dev *dev = NULL; int ret; for_each_pci_dev(dev) if ((dev->class >> 8) == PCI_CLASS_BRIDGE_EISA) { ret = pci_eisa_init(dev); if (ret) return ret; } return 0; } subsys_initcall_sync(pci_eisa_init_early);
linux-master
drivers/eisa/pci_eisa.c
// SPDX-License-Identifier: GPL-2.0-only /* * Virtual EISA root driver. * Acts as a placeholder if we don't have a proper EISA bridge. * * (C) 2003 Marc Zyngier <[email protected]> */ #include <linux/kernel.h> #include <linux/platform_device.h> #include <linux/eisa.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/init.h> #if defined(CONFIG_ALPHA_JENSEN) || defined(CONFIG_EISA_VLB_PRIMING) #define EISA_FORCE_PROBE_DEFAULT 1 #else #define EISA_FORCE_PROBE_DEFAULT 0 #endif static int force_probe = EISA_FORCE_PROBE_DEFAULT; static void virtual_eisa_release (struct device *); /* The default EISA device parent (virtual root device). * Now use a platform device, since that's the obvious choice. */ static struct platform_device eisa_root_dev = { .name = "eisa", .id = 0, .dev = { .release = virtual_eisa_release, }, }; static struct eisa_root_device eisa_bus_root = { .dev = &eisa_root_dev.dev, .bus_base_addr = 0, .res = &ioport_resource, .slots = EISA_MAX_SLOTS, .dma_mask = 0xffffffff, }; static void virtual_eisa_release (struct device *dev) { /* nothing really to do here */ } static int __init virtual_eisa_root_init (void) { int r; if ((r = platform_device_register (&eisa_root_dev))) return r; eisa_bus_root.force_probe = force_probe; dev_set_drvdata(&eisa_root_dev.dev, &eisa_bus_root); if (eisa_root_register (&eisa_bus_root)) { /* A real bridge may have been registered before * us. So quietly unregister. */ platform_device_unregister (&eisa_root_dev); return -1; } return 0; } module_param (force_probe, int, 0444); device_initcall (virtual_eisa_root_init);
linux-master
drivers/eisa/virtual_root.c
// SPDX-License-Identifier: GPL-2.0 /* bbc_envctrl.c: UltraSPARC-III environment control driver. * * Copyright (C) 2001, 2008 David S. Miller ([email protected]) */ #include <linux/kthread.h> #include <linux/delay.h> #include <linux/kmod.h> #include <linux/reboot.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <asm/oplib.h> #include "bbc_i2c.h" #include "max1617.h" #undef ENVCTRL_TRACE /* WARNING: Making changes to this driver is very dangerous. * If you misprogram the sensor chips they can * cut the power on you instantly. */ /* Two temperature sensors exist in the SunBLADE-1000 enclosure. * Both are implemented using max1617 i2c devices. Each max1617 * monitors 2 temperatures, one for one of the cpu dies and the other * for the ambient temperature. * * The max1617 is capable of being programmed with power-off * temperature values, one low limit and one high limit. These * can be controlled independently for the cpu or ambient temperature. * If a limit is violated, the power is simply shut off. The frequency * with which the max1617 does temperature sampling can be controlled * as well. * * Three fans exist inside the machine, all three are controlled with * an i2c digital to analog converter. There is a fan directed at the * two processor slots, another for the rest of the enclosure, and the * third is for the power supply. The first two fans may be speed * controlled by changing the voltage fed to them. The third fan may * only be completely off or on. The third fan is meant to only be * disabled/enabled when entering/exiting the lowest power-saving * mode of the machine. * * An environmental control kernel thread periodically monitors all * temperature sensors. Based upon the samples it will adjust the * fan speeds to try and keep the system within a certain temperature * range (the goal being to make the fans as quiet as possible without * allowing the system to get too hot). * * If the temperature begins to rise/fall outside of the acceptable * operating range, a periodic warning will be sent to the kernel log. * The fans will be put on full blast to attempt to deal with this * situation. After exceeding the acceptable operating range by a * certain threshold, the kernel thread will shut down the system. * Here, the thread is attempting to shut the machine down cleanly * before the hardware based power-off event is triggered. */ /* These settings are in Celsius. We use these defaults only * if we cannot interrogate the cpu-fru SEEPROM. */ struct temp_limits { s8 high_pwroff, high_shutdown, high_warn; s8 low_warn, low_shutdown, low_pwroff; }; static struct temp_limits cpu_temp_limits[2] = { { 100, 85, 80, 5, -5, -10 }, { 100, 85, 80, 5, -5, -10 }, }; static struct temp_limits amb_temp_limits[2] = { { 65, 55, 40, 5, -5, -10 }, { 65, 55, 40, 5, -5, -10 }, }; static LIST_HEAD(all_temps); static LIST_HEAD(all_fans); #define CPU_FAN_REG 0xf0 #define SYS_FAN_REG 0xf2 #define PSUPPLY_FAN_REG 0xf4 #define FAN_SPEED_MIN 0x0c #define FAN_SPEED_MAX 0x3f #define PSUPPLY_FAN_ON 0x1f #define PSUPPLY_FAN_OFF 0x00 static void set_fan_speeds(struct bbc_fan_control *fp) { /* Put temperatures into range so we don't mis-program * the hardware. */ if (fp->cpu_fan_speed < FAN_SPEED_MIN) fp->cpu_fan_speed = FAN_SPEED_MIN; if (fp->cpu_fan_speed > FAN_SPEED_MAX) fp->cpu_fan_speed = FAN_SPEED_MAX; if (fp->system_fan_speed < FAN_SPEED_MIN) fp->system_fan_speed = FAN_SPEED_MIN; if (fp->system_fan_speed > FAN_SPEED_MAX) fp->system_fan_speed = FAN_SPEED_MAX; #ifdef ENVCTRL_TRACE printk("fan%d: Changed fan speed to cpu(%02x) sys(%02x)\n", fp->index, fp->cpu_fan_speed, fp->system_fan_speed); #endif bbc_i2c_writeb(fp->client, fp->cpu_fan_speed, CPU_FAN_REG); bbc_i2c_writeb(fp->client, fp->system_fan_speed, SYS_FAN_REG); bbc_i2c_writeb(fp->client, (fp->psupply_fan_on ? PSUPPLY_FAN_ON : PSUPPLY_FAN_OFF), PSUPPLY_FAN_REG); } static void get_current_temps(struct bbc_cpu_temperature *tp) { tp->prev_amb_temp = tp->curr_amb_temp; bbc_i2c_readb(tp->client, (unsigned char *) &tp->curr_amb_temp, MAX1617_AMB_TEMP); tp->prev_cpu_temp = tp->curr_cpu_temp; bbc_i2c_readb(tp->client, (unsigned char *) &tp->curr_cpu_temp, MAX1617_CPU_TEMP); #ifdef ENVCTRL_TRACE printk("temp%d: cpu(%d C) amb(%d C)\n", tp->index, (int) tp->curr_cpu_temp, (int) tp->curr_amb_temp); #endif } static void do_envctrl_shutdown(struct bbc_cpu_temperature *tp) { static int shutting_down = 0; char *type = "???"; s8 val = -1; if (shutting_down != 0) return; if (tp->curr_amb_temp >= amb_temp_limits[tp->index].high_shutdown || tp->curr_amb_temp < amb_temp_limits[tp->index].low_shutdown) { type = "ambient"; val = tp->curr_amb_temp; } else if (tp->curr_cpu_temp >= cpu_temp_limits[tp->index].high_shutdown || tp->curr_cpu_temp < cpu_temp_limits[tp->index].low_shutdown) { type = "CPU"; val = tp->curr_cpu_temp; } printk(KERN_CRIT "temp%d: Outside of safe %s " "operating temperature, %d C.\n", tp->index, type, val); printk(KERN_CRIT "kenvctrld: Shutting down the system now.\n"); shutting_down = 1; orderly_poweroff(true); } #define WARN_INTERVAL (30 * HZ) static void analyze_ambient_temp(struct bbc_cpu_temperature *tp, unsigned long *last_warn, int tick) { int ret = 0; if (time_after(jiffies, (*last_warn + WARN_INTERVAL))) { if (tp->curr_amb_temp >= amb_temp_limits[tp->index].high_warn) { printk(KERN_WARNING "temp%d: " "Above safe ambient operating temperature, %d C.\n", tp->index, (int) tp->curr_amb_temp); ret = 1; } else if (tp->curr_amb_temp < amb_temp_limits[tp->index].low_warn) { printk(KERN_WARNING "temp%d: " "Below safe ambient operating temperature, %d C.\n", tp->index, (int) tp->curr_amb_temp); ret = 1; } if (ret) *last_warn = jiffies; } else if (tp->curr_amb_temp >= amb_temp_limits[tp->index].high_warn || tp->curr_amb_temp < amb_temp_limits[tp->index].low_warn) ret = 1; /* Now check the shutdown limits. */ if (tp->curr_amb_temp >= amb_temp_limits[tp->index].high_shutdown || tp->curr_amb_temp < amb_temp_limits[tp->index].low_shutdown) { do_envctrl_shutdown(tp); ret = 1; } if (ret) { tp->fan_todo[FAN_AMBIENT] = FAN_FULLBLAST; } else if ((tick & (8 - 1)) == 0) { s8 amb_goal_hi = amb_temp_limits[tp->index].high_warn - 10; s8 amb_goal_lo; amb_goal_lo = amb_goal_hi - 3; /* We do not try to avoid 'too cold' events. Basically we * only try to deal with over-heating and fan noise reduction. */ if (tp->avg_amb_temp < amb_goal_hi) { if (tp->avg_amb_temp >= amb_goal_lo) tp->fan_todo[FAN_AMBIENT] = FAN_SAME; else tp->fan_todo[FAN_AMBIENT] = FAN_SLOWER; } else { tp->fan_todo[FAN_AMBIENT] = FAN_FASTER; } } else { tp->fan_todo[FAN_AMBIENT] = FAN_SAME; } } static void analyze_cpu_temp(struct bbc_cpu_temperature *tp, unsigned long *last_warn, int tick) { int ret = 0; if (time_after(jiffies, (*last_warn + WARN_INTERVAL))) { if (tp->curr_cpu_temp >= cpu_temp_limits[tp->index].high_warn) { printk(KERN_WARNING "temp%d: " "Above safe CPU operating temperature, %d C.\n", tp->index, (int) tp->curr_cpu_temp); ret = 1; } else if (tp->curr_cpu_temp < cpu_temp_limits[tp->index].low_warn) { printk(KERN_WARNING "temp%d: " "Below safe CPU operating temperature, %d C.\n", tp->index, (int) tp->curr_cpu_temp); ret = 1; } if (ret) *last_warn = jiffies; } else if (tp->curr_cpu_temp >= cpu_temp_limits[tp->index].high_warn || tp->curr_cpu_temp < cpu_temp_limits[tp->index].low_warn) ret = 1; /* Now check the shutdown limits. */ if (tp->curr_cpu_temp >= cpu_temp_limits[tp->index].high_shutdown || tp->curr_cpu_temp < cpu_temp_limits[tp->index].low_shutdown) { do_envctrl_shutdown(tp); ret = 1; } if (ret) { tp->fan_todo[FAN_CPU] = FAN_FULLBLAST; } else if ((tick & (8 - 1)) == 0) { s8 cpu_goal_hi = cpu_temp_limits[tp->index].high_warn - 10; s8 cpu_goal_lo; cpu_goal_lo = cpu_goal_hi - 3; /* We do not try to avoid 'too cold' events. Basically we * only try to deal with over-heating and fan noise reduction. */ if (tp->avg_cpu_temp < cpu_goal_hi) { if (tp->avg_cpu_temp >= cpu_goal_lo) tp->fan_todo[FAN_CPU] = FAN_SAME; else tp->fan_todo[FAN_CPU] = FAN_SLOWER; } else { tp->fan_todo[FAN_CPU] = FAN_FASTER; } } else { tp->fan_todo[FAN_CPU] = FAN_SAME; } } static void analyze_temps(struct bbc_cpu_temperature *tp, unsigned long *last_warn) { tp->avg_amb_temp = (s8)((int)((int)tp->avg_amb_temp + (int)tp->curr_amb_temp) / 2); tp->avg_cpu_temp = (s8)((int)((int)tp->avg_cpu_temp + (int)tp->curr_cpu_temp) / 2); analyze_ambient_temp(tp, last_warn, tp->sample_tick); analyze_cpu_temp(tp, last_warn, tp->sample_tick); tp->sample_tick++; } static enum fan_action prioritize_fan_action(int which_fan) { struct bbc_cpu_temperature *tp; enum fan_action decision = FAN_STATE_MAX; /* Basically, prioritize what the temperature sensors * recommend we do, and perform that action on all the * fans. */ list_for_each_entry(tp, &all_temps, glob_list) { if (tp->fan_todo[which_fan] == FAN_FULLBLAST) { decision = FAN_FULLBLAST; break; } if (tp->fan_todo[which_fan] == FAN_SAME && decision != FAN_FASTER) decision = FAN_SAME; else if (tp->fan_todo[which_fan] == FAN_FASTER) decision = FAN_FASTER; else if (decision != FAN_FASTER && decision != FAN_SAME && tp->fan_todo[which_fan] == FAN_SLOWER) decision = FAN_SLOWER; } if (decision == FAN_STATE_MAX) decision = FAN_SAME; return decision; } static int maybe_new_ambient_fan_speed(struct bbc_fan_control *fp) { enum fan_action decision = prioritize_fan_action(FAN_AMBIENT); int ret; if (decision == FAN_SAME) return 0; ret = 1; if (decision == FAN_FULLBLAST) { if (fp->system_fan_speed >= FAN_SPEED_MAX) ret = 0; else fp->system_fan_speed = FAN_SPEED_MAX; } else { if (decision == FAN_FASTER) { if (fp->system_fan_speed >= FAN_SPEED_MAX) ret = 0; else fp->system_fan_speed += 2; } else { int orig_speed = fp->system_fan_speed; if (orig_speed <= FAN_SPEED_MIN || orig_speed <= (fp->cpu_fan_speed - 3)) ret = 0; else fp->system_fan_speed -= 1; } } return ret; } static int maybe_new_cpu_fan_speed(struct bbc_fan_control *fp) { enum fan_action decision = prioritize_fan_action(FAN_CPU); int ret; if (decision == FAN_SAME) return 0; ret = 1; if (decision == FAN_FULLBLAST) { if (fp->cpu_fan_speed >= FAN_SPEED_MAX) ret = 0; else fp->cpu_fan_speed = FAN_SPEED_MAX; } else { if (decision == FAN_FASTER) { if (fp->cpu_fan_speed >= FAN_SPEED_MAX) ret = 0; else { fp->cpu_fan_speed += 2; if (fp->system_fan_speed < (fp->cpu_fan_speed - 3)) fp->system_fan_speed = fp->cpu_fan_speed - 3; } } else { if (fp->cpu_fan_speed <= FAN_SPEED_MIN) ret = 0; else fp->cpu_fan_speed -= 1; } } return ret; } static void maybe_new_fan_speeds(struct bbc_fan_control *fp) { int new; new = maybe_new_ambient_fan_speed(fp); new |= maybe_new_cpu_fan_speed(fp); if (new) set_fan_speeds(fp); } static void fans_full_blast(void) { struct bbc_fan_control *fp; /* Since we will not be monitoring things anymore, put * the fans on full blast. */ list_for_each_entry(fp, &all_fans, glob_list) { fp->cpu_fan_speed = FAN_SPEED_MAX; fp->system_fan_speed = FAN_SPEED_MAX; fp->psupply_fan_on = 1; set_fan_speeds(fp); } } #define POLL_INTERVAL (5 * 1000) static unsigned long last_warning_jiffies; static struct task_struct *kenvctrld_task; static int kenvctrld(void *__unused) { printk(KERN_INFO "bbc_envctrl: kenvctrld starting...\n"); last_warning_jiffies = jiffies - WARN_INTERVAL; for (;;) { struct bbc_cpu_temperature *tp; struct bbc_fan_control *fp; msleep_interruptible(POLL_INTERVAL); if (kthread_should_stop()) break; list_for_each_entry(tp, &all_temps, glob_list) { get_current_temps(tp); analyze_temps(tp, &last_warning_jiffies); } list_for_each_entry(fp, &all_fans, glob_list) maybe_new_fan_speeds(fp); } printk(KERN_INFO "bbc_envctrl: kenvctrld exiting...\n"); fans_full_blast(); return 0; } static void attach_one_temp(struct bbc_i2c_bus *bp, struct platform_device *op, int temp_idx) { struct bbc_cpu_temperature *tp; tp = kzalloc(sizeof(*tp), GFP_KERNEL); if (!tp) return; INIT_LIST_HEAD(&tp->bp_list); INIT_LIST_HEAD(&tp->glob_list); tp->client = bbc_i2c_attach(bp, op); if (!tp->client) { kfree(tp); return; } tp->index = temp_idx; list_add(&tp->glob_list, &all_temps); list_add(&tp->bp_list, &bp->temps); /* Tell it to convert once every 5 seconds, clear all cfg * bits. */ bbc_i2c_writeb(tp->client, 0x00, MAX1617_WR_CFG_BYTE); bbc_i2c_writeb(tp->client, 0x02, MAX1617_WR_CVRATE_BYTE); /* Program the hard temperature limits into the chip. */ bbc_i2c_writeb(tp->client, amb_temp_limits[tp->index].high_pwroff, MAX1617_WR_AMB_HIGHLIM); bbc_i2c_writeb(tp->client, amb_temp_limits[tp->index].low_pwroff, MAX1617_WR_AMB_LOWLIM); bbc_i2c_writeb(tp->client, cpu_temp_limits[tp->index].high_pwroff, MAX1617_WR_CPU_HIGHLIM); bbc_i2c_writeb(tp->client, cpu_temp_limits[tp->index].low_pwroff, MAX1617_WR_CPU_LOWLIM); get_current_temps(tp); tp->prev_cpu_temp = tp->avg_cpu_temp = tp->curr_cpu_temp; tp->prev_amb_temp = tp->avg_amb_temp = tp->curr_amb_temp; tp->fan_todo[FAN_AMBIENT] = FAN_SAME; tp->fan_todo[FAN_CPU] = FAN_SAME; } static void attach_one_fan(struct bbc_i2c_bus *bp, struct platform_device *op, int fan_idx) { struct bbc_fan_control *fp; fp = kzalloc(sizeof(*fp), GFP_KERNEL); if (!fp) return; INIT_LIST_HEAD(&fp->bp_list); INIT_LIST_HEAD(&fp->glob_list); fp->client = bbc_i2c_attach(bp, op); if (!fp->client) { kfree(fp); return; } fp->index = fan_idx; list_add(&fp->glob_list, &all_fans); list_add(&fp->bp_list, &bp->fans); /* The i2c device controlling the fans is write-only. * So the only way to keep track of the current power * level fed to the fans is via software. Choose half * power for cpu/system and 'on' fo the powersupply fan * and set it now. */ fp->psupply_fan_on = 1; fp->cpu_fan_speed = (FAN_SPEED_MAX - FAN_SPEED_MIN) / 2; fp->cpu_fan_speed += FAN_SPEED_MIN; fp->system_fan_speed = (FAN_SPEED_MAX - FAN_SPEED_MIN) / 2; fp->system_fan_speed += FAN_SPEED_MIN; set_fan_speeds(fp); } static void destroy_one_temp(struct bbc_cpu_temperature *tp) { bbc_i2c_detach(tp->client); kfree(tp); } static void destroy_all_temps(struct bbc_i2c_bus *bp) { struct bbc_cpu_temperature *tp, *tpos; list_for_each_entry_safe(tp, tpos, &bp->temps, bp_list) { list_del(&tp->bp_list); list_del(&tp->glob_list); destroy_one_temp(tp); } } static void destroy_one_fan(struct bbc_fan_control *fp) { bbc_i2c_detach(fp->client); kfree(fp); } static void destroy_all_fans(struct bbc_i2c_bus *bp) { struct bbc_fan_control *fp, *fpos; list_for_each_entry_safe(fp, fpos, &bp->fans, bp_list) { list_del(&fp->bp_list); list_del(&fp->glob_list); destroy_one_fan(fp); } } int bbc_envctrl_init(struct bbc_i2c_bus *bp) { struct platform_device *op; int temp_index = 0; int fan_index = 0; int devidx = 0; while ((op = bbc_i2c_getdev(bp, devidx++)) != NULL) { if (of_node_name_eq(op->dev.of_node, "temperature")) attach_one_temp(bp, op, temp_index++); if (of_node_name_eq(op->dev.of_node, "fan-control")) attach_one_fan(bp, op, fan_index++); } if (temp_index != 0 && fan_index != 0) { kenvctrld_task = kthread_run(kenvctrld, NULL, "kenvctrld"); if (IS_ERR(kenvctrld_task)) { int err = PTR_ERR(kenvctrld_task); kenvctrld_task = NULL; destroy_all_temps(bp); destroy_all_fans(bp); return err; } } return 0; } void bbc_envctrl_cleanup(struct bbc_i2c_bus *bp) { if (kenvctrld_task) kthread_stop(kenvctrld_task); destroy_all_temps(bp); destroy_all_fans(bp); }
linux-master
drivers/sbus/char/bbc_envctrl.c
// SPDX-License-Identifier: GPL-2.0-only /* flash.c: Allow mmap access to the OBP Flash, for OBP updates. * * Copyright (C) 1997 Eddie C. Dost ([email protected]) */ #include <linux/module.h> #include <linux/types.h> #include <linux/errno.h> #include <linux/miscdevice.h> #include <linux/fcntl.h> #include <linux/poll.h> #include <linux/mutex.h> #include <linux/spinlock.h> #include <linux/mm.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/uaccess.h> #include <asm/io.h> #include <asm/upa.h> static DEFINE_MUTEX(flash_mutex); static DEFINE_SPINLOCK(flash_lock); static struct { unsigned long read_base; /* Physical read address */ unsigned long write_base; /* Physical write address */ unsigned long read_size; /* Size of read area */ unsigned long write_size; /* Size of write area */ unsigned long busy; /* In use? */ } flash; static int flash_mmap(struct file *file, struct vm_area_struct *vma) { unsigned long addr; unsigned long size; spin_lock(&flash_lock); if (flash.read_base == flash.write_base) { addr = flash.read_base; size = flash.read_size; } else { if ((vma->vm_flags & VM_READ) && (vma->vm_flags & VM_WRITE)) { spin_unlock(&flash_lock); return -EINVAL; } if (vma->vm_flags & VM_READ) { addr = flash.read_base; size = flash.read_size; } else if (vma->vm_flags & VM_WRITE) { addr = flash.write_base; size = flash.write_size; } else { spin_unlock(&flash_lock); return -ENXIO; } } spin_unlock(&flash_lock); if ((vma->vm_pgoff << PAGE_SHIFT) > size) return -ENXIO; addr = vma->vm_pgoff + (addr >> PAGE_SHIFT); if (vma->vm_end - (vma->vm_start + (vma->vm_pgoff << PAGE_SHIFT)) > size) size = vma->vm_end - (vma->vm_start + (vma->vm_pgoff << PAGE_SHIFT)); vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); if (io_remap_pfn_range(vma, vma->vm_start, addr, size, vma->vm_page_prot)) return -EAGAIN; return 0; } static long long flash_llseek(struct file *file, long long offset, int origin) { mutex_lock(&flash_mutex); switch (origin) { case 0: file->f_pos = offset; break; case 1: file->f_pos += offset; if (file->f_pos > flash.read_size) file->f_pos = flash.read_size; break; case 2: file->f_pos = flash.read_size; break; default: mutex_unlock(&flash_mutex); return -EINVAL; } mutex_unlock(&flash_mutex); return file->f_pos; } static ssize_t flash_read(struct file * file, char __user * buf, size_t count, loff_t *ppos) { loff_t p = *ppos; int i; if (count > flash.read_size - p) count = flash.read_size - p; for (i = 0; i < count; i++) { u8 data = upa_readb(flash.read_base + p + i); if (put_user(data, buf)) return -EFAULT; buf++; } *ppos += count; return count; } static int flash_open(struct inode *inode, struct file *file) { mutex_lock(&flash_mutex); if (test_and_set_bit(0, (void *)&flash.busy) != 0) { mutex_unlock(&flash_mutex); return -EBUSY; } mutex_unlock(&flash_mutex); return 0; } static int flash_release(struct inode *inode, struct file *file) { spin_lock(&flash_lock); flash.busy = 0; spin_unlock(&flash_lock); return 0; } static const struct file_operations flash_fops = { /* no write to the Flash, use mmap * and play flash dependent tricks. */ .owner = THIS_MODULE, .llseek = flash_llseek, .read = flash_read, .mmap = flash_mmap, .open = flash_open, .release = flash_release, }; static struct miscdevice flash_dev = { SBUS_FLASH_MINOR, "flash", &flash_fops }; static int flash_probe(struct platform_device *op) { struct device_node *dp = op->dev.of_node; struct device_node *parent; parent = dp->parent; if (!of_node_name_eq(parent, "sbus") && !of_node_name_eq(parent, "sbi") && !of_node_name_eq(parent, "ebus")) return -ENODEV; flash.read_base = op->resource[0].start; flash.read_size = resource_size(&op->resource[0]); if (op->resource[1].flags) { flash.write_base = op->resource[1].start; flash.write_size = resource_size(&op->resource[1]); } else { flash.write_base = op->resource[0].start; flash.write_size = resource_size(&op->resource[0]); } flash.busy = 0; printk(KERN_INFO "%pOF: OBP Flash, RD %lx[%lx] WR %lx[%lx]\n", op->dev.of_node, flash.read_base, flash.read_size, flash.write_base, flash.write_size); return misc_register(&flash_dev); } static int flash_remove(struct platform_device *op) { misc_deregister(&flash_dev); return 0; } static const struct of_device_id flash_match[] = { { .name = "flashprom", }, {}, }; MODULE_DEVICE_TABLE(of, flash_match); static struct platform_driver flash_driver = { .driver = { .name = "flash", .of_match_table = flash_match, }, .probe = flash_probe, .remove = flash_remove, }; module_platform_driver(flash_driver); MODULE_LICENSE("GPL");
linux-master
drivers/sbus/char/flash.c
// SPDX-License-Identifier: GPL-2.0-only /* uctrl.c: TS102 Microcontroller interface on Tadpole Sparcbook 3 * * Copyright 1999 Derrick J Brashear ([email protected]) * Copyright 2008 David S. Miller ([email protected]) */ #include <linux/module.h> #include <linux/errno.h> #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/slab.h> #include <linux/mutex.h> #include <linux/ioport.h> #include <linux/miscdevice.h> #include <linux/mm.h> #include <linux/of.h> #include <linux/platform_device.h> #include <asm/openprom.h> #include <asm/oplib.h> #include <asm/irq.h> #include <asm/io.h> #define DEBUG 1 #ifdef DEBUG #define dprintk(x) printk x #else #define dprintk(x) #endif struct uctrl_regs { u32 uctrl_intr; u32 uctrl_data; u32 uctrl_stat; u32 uctrl_xxx[5]; }; struct ts102_regs { u32 card_a_intr; u32 card_a_stat; u32 card_a_ctrl; u32 card_a_xxx; u32 card_b_intr; u32 card_b_stat; u32 card_b_ctrl; u32 card_b_xxx; u32 uctrl_intr; u32 uctrl_data; u32 uctrl_stat; u32 uctrl_xxx; u32 ts102_xxx[4]; }; /* Bits for uctrl_intr register */ #define UCTRL_INTR_TXE_REQ 0x01 /* transmit FIFO empty int req */ #define UCTRL_INTR_TXNF_REQ 0x02 /* transmit FIFO not full int req */ #define UCTRL_INTR_RXNE_REQ 0x04 /* receive FIFO not empty int req */ #define UCTRL_INTR_RXO_REQ 0x08 /* receive FIFO overflow int req */ #define UCTRL_INTR_TXE_MSK 0x10 /* transmit FIFO empty mask */ #define UCTRL_INTR_TXNF_MSK 0x20 /* transmit FIFO not full mask */ #define UCTRL_INTR_RXNE_MSK 0x40 /* receive FIFO not empty mask */ #define UCTRL_INTR_RXO_MSK 0x80 /* receive FIFO overflow mask */ /* Bits for uctrl_stat register */ #define UCTRL_STAT_TXE_STA 0x01 /* transmit FIFO empty status */ #define UCTRL_STAT_TXNF_STA 0x02 /* transmit FIFO not full status */ #define UCTRL_STAT_RXNE_STA 0x04 /* receive FIFO not empty status */ #define UCTRL_STAT_RXO_STA 0x08 /* receive FIFO overflow status */ static DEFINE_MUTEX(uctrl_mutex); static const char *uctrl_extstatus[16] = { "main power available", "internal battery attached", "external battery attached", "external VGA attached", "external keyboard attached", "external mouse attached", "lid down", "internal battery currently charging", "external battery currently charging", "internal battery currently discharging", "external battery currently discharging", }; /* Everything required for one transaction with the uctrl */ struct uctrl_txn { u8 opcode; u8 inbits; u8 outbits; u8 *inbuf; u8 *outbuf; }; struct uctrl_status { u8 current_temp; /* 0x07 */ u8 reset_status; /* 0x0b */ u16 event_status; /* 0x0c */ u16 error_status; /* 0x10 */ u16 external_status; /* 0x11, 0x1b */ u8 internal_charge; /* 0x18 */ u8 external_charge; /* 0x19 */ u16 control_lcd; /* 0x20 */ u8 control_bitport; /* 0x21 */ u8 speaker_volume; /* 0x23 */ u8 control_tft_brightness; /* 0x24 */ u8 control_kbd_repeat_delay; /* 0x28 */ u8 control_kbd_repeat_period; /* 0x29 */ u8 control_screen_contrast; /* 0x2F */ }; enum uctrl_opcode { READ_SERIAL_NUMBER=0x1, READ_ETHERNET_ADDRESS=0x2, READ_HARDWARE_VERSION=0x3, READ_MICROCONTROLLER_VERSION=0x4, READ_MAX_TEMPERATURE=0x5, READ_MIN_TEMPERATURE=0x6, READ_CURRENT_TEMPERATURE=0x7, READ_SYSTEM_VARIANT=0x8, READ_POWERON_CYCLES=0x9, READ_POWERON_SECONDS=0xA, READ_RESET_STATUS=0xB, READ_EVENT_STATUS=0xC, READ_REAL_TIME_CLOCK=0xD, READ_EXTERNAL_VGA_PORT=0xE, READ_MICROCONTROLLER_ROM_CHECKSUM=0xF, READ_ERROR_STATUS=0x10, READ_EXTERNAL_STATUS=0x11, READ_USER_CONFIGURATION_AREA=0x12, READ_MICROCONTROLLER_VOLTAGE=0x13, READ_INTERNAL_BATTERY_VOLTAGE=0x14, READ_DCIN_VOLTAGE=0x15, READ_HORIZONTAL_POINTER_VOLTAGE=0x16, READ_VERTICAL_POINTER_VOLTAGE=0x17, READ_INTERNAL_BATTERY_CHARGE_LEVEL=0x18, READ_EXTERNAL_BATTERY_CHARGE_LEVEL=0x19, READ_REAL_TIME_CLOCK_ALARM=0x1A, READ_EVENT_STATUS_NO_RESET=0x1B, READ_INTERNAL_KEYBOARD_LAYOUT=0x1C, READ_EXTERNAL_KEYBOARD_LAYOUT=0x1D, READ_EEPROM_STATUS=0x1E, CONTROL_LCD=0x20, CONTROL_BITPORT=0x21, SPEAKER_VOLUME=0x23, CONTROL_TFT_BRIGHTNESS=0x24, CONTROL_WATCHDOG=0x25, CONTROL_FACTORY_EEPROM_AREA=0x26, CONTROL_KBD_TIME_UNTIL_REPEAT=0x28, CONTROL_KBD_TIME_BETWEEN_REPEATS=0x29, CONTROL_TIMEZONE=0x2A, CONTROL_MARK_SPACE_RATIO=0x2B, CONTROL_DIAGNOSTIC_MODE=0x2E, CONTROL_SCREEN_CONTRAST=0x2F, RING_BELL=0x30, SET_DIAGNOSTIC_STATUS=0x32, CLEAR_KEY_COMBINATION_TABLE=0x33, PERFORM_SOFTWARE_RESET=0x34, SET_REAL_TIME_CLOCK=0x35, RECALIBRATE_POINTING_STICK=0x36, SET_BELL_FREQUENCY=0x37, SET_INTERNAL_BATTERY_CHARGE_RATE=0x39, SET_EXTERNAL_BATTERY_CHARGE_RATE=0x3A, SET_REAL_TIME_CLOCK_ALARM=0x3B, READ_EEPROM=0x40, WRITE_EEPROM=0x41, WRITE_TO_STATUS_DISPLAY=0x42, DEFINE_SPECIAL_CHARACTER=0x43, DEFINE_KEY_COMBINATION_ENTRY=0x50, DEFINE_STRING_TABLE_ENTRY=0x51, DEFINE_STATUS_SCREEN_DISPLAY=0x52, PERFORM_EMU_COMMANDS=0x64, READ_EMU_REGISTER=0x65, WRITE_EMU_REGISTER=0x66, READ_EMU_RAM=0x67, WRITE_EMU_RAM=0x68, READ_BQ_REGISTER=0x69, WRITE_BQ_REGISTER=0x6A, SET_USER_PASSWORD=0x70, VERIFY_USER_PASSWORD=0x71, GET_SYSTEM_PASSWORD_KEY=0x72, VERIFY_SYSTEM_PASSWORD=0x73, POWER_OFF=0x82, POWER_RESTART=0x83, }; static struct uctrl_driver { struct uctrl_regs __iomem *regs; int irq; int pending; struct uctrl_status status; } *global_driver; static void uctrl_get_event_status(struct uctrl_driver *); static void uctrl_get_external_status(struct uctrl_driver *); static long uctrl_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { switch (cmd) { default: return -EINVAL; } return 0; } static int uctrl_open(struct inode *inode, struct file *file) { mutex_lock(&uctrl_mutex); uctrl_get_event_status(global_driver); uctrl_get_external_status(global_driver); mutex_unlock(&uctrl_mutex); return 0; } static irqreturn_t uctrl_interrupt(int irq, void *dev_id) { return IRQ_HANDLED; } static const struct file_operations uctrl_fops = { .owner = THIS_MODULE, .llseek = no_llseek, .unlocked_ioctl = uctrl_ioctl, .open = uctrl_open, }; static struct miscdevice uctrl_dev = { UCTRL_MINOR, "uctrl", &uctrl_fops }; /* Wait for space to write, then write to it */ #define WRITEUCTLDATA(value) \ { \ unsigned int i; \ for (i = 0; i < 10000; i++) { \ if (UCTRL_STAT_TXNF_STA & sbus_readl(&driver->regs->uctrl_stat)) \ break; \ } \ dprintk(("write data 0x%02x\n", value)); \ sbus_writel(value, &driver->regs->uctrl_data); \ } /* Wait for something to read, read it, then clear the bit */ #define READUCTLDATA(value) \ { \ unsigned int i; \ value = 0; \ for (i = 0; i < 10000; i++) { \ if ((UCTRL_STAT_RXNE_STA & sbus_readl(&driver->regs->uctrl_stat)) == 0) \ break; \ udelay(1); \ } \ value = sbus_readl(&driver->regs->uctrl_data); \ dprintk(("read data 0x%02x\n", value)); \ sbus_writel(UCTRL_STAT_RXNE_STA, &driver->regs->uctrl_stat); \ } static void uctrl_do_txn(struct uctrl_driver *driver, struct uctrl_txn *txn) { int stat, incnt, outcnt, bytecnt, intr; u32 byte; stat = sbus_readl(&driver->regs->uctrl_stat); intr = sbus_readl(&driver->regs->uctrl_intr); sbus_writel(stat, &driver->regs->uctrl_stat); dprintk(("interrupt stat 0x%x int 0x%x\n", stat, intr)); incnt = txn->inbits; outcnt = txn->outbits; byte = (txn->opcode << 8); WRITEUCTLDATA(byte); bytecnt = 0; while (incnt > 0) { byte = (txn->inbuf[bytecnt] << 8); WRITEUCTLDATA(byte); incnt--; bytecnt++; } /* Get the ack */ READUCTLDATA(byte); dprintk(("ack was %x\n", (byte >> 8))); bytecnt = 0; while (outcnt > 0) { READUCTLDATA(byte); txn->outbuf[bytecnt] = (byte >> 8); dprintk(("set byte to %02x\n", byte)); outcnt--; bytecnt++; } } static void uctrl_get_event_status(struct uctrl_driver *driver) { struct uctrl_txn txn; u8 outbits[2]; txn.opcode = READ_EVENT_STATUS; txn.inbits = 0; txn.outbits = 2; txn.inbuf = NULL; txn.outbuf = outbits; uctrl_do_txn(driver, &txn); dprintk(("bytes %x %x\n", (outbits[0] & 0xff), (outbits[1] & 0xff))); driver->status.event_status = ((outbits[0] & 0xff) << 8) | (outbits[1] & 0xff); dprintk(("ev is %x\n", driver->status.event_status)); } static void uctrl_get_external_status(struct uctrl_driver *driver) { struct uctrl_txn txn; u8 outbits[2]; int i, v; txn.opcode = READ_EXTERNAL_STATUS; txn.inbits = 0; txn.outbits = 2; txn.inbuf = NULL; txn.outbuf = outbits; uctrl_do_txn(driver, &txn); dprintk(("bytes %x %x\n", (outbits[0] & 0xff), (outbits[1] & 0xff))); driver->status.external_status = ((outbits[0] * 256) + (outbits[1])); dprintk(("ex is %x\n", driver->status.external_status)); v = driver->status.external_status; for (i = 0; v != 0; i++, v >>= 1) { if (v & 1) { dprintk(("%s%s", " ", uctrl_extstatus[i])); } } dprintk(("\n")); } static int uctrl_probe(struct platform_device *op) { struct uctrl_driver *p; int err = -ENOMEM; p = kzalloc(sizeof(*p), GFP_KERNEL); if (!p) { printk(KERN_ERR "uctrl: Unable to allocate device struct.\n"); goto out; } p->regs = of_ioremap(&op->resource[0], 0, resource_size(&op->resource[0]), "uctrl"); if (!p->regs) { printk(KERN_ERR "uctrl: Unable to map registers.\n"); goto out_free; } p->irq = op->archdata.irqs[0]; err = request_irq(p->irq, uctrl_interrupt, 0, "uctrl", p); if (err) { printk(KERN_ERR "uctrl: Unable to register irq.\n"); goto out_iounmap; } err = misc_register(&uctrl_dev); if (err) { printk(KERN_ERR "uctrl: Unable to register misc device.\n"); goto out_free_irq; } sbus_writel(UCTRL_INTR_RXNE_REQ|UCTRL_INTR_RXNE_MSK, &p->regs->uctrl_intr); printk(KERN_INFO "%pOF: uctrl regs[0x%p] (irq %d)\n", op->dev.of_node, p->regs, p->irq); uctrl_get_event_status(p); uctrl_get_external_status(p); dev_set_drvdata(&op->dev, p); global_driver = p; out: return err; out_free_irq: free_irq(p->irq, p); out_iounmap: of_iounmap(&op->resource[0], p->regs, resource_size(&op->resource[0])); out_free: kfree(p); goto out; } static int uctrl_remove(struct platform_device *op) { struct uctrl_driver *p = dev_get_drvdata(&op->dev); if (p) { misc_deregister(&uctrl_dev); free_irq(p->irq, p); of_iounmap(&op->resource[0], p->regs, resource_size(&op->resource[0])); kfree(p); } return 0; } static const struct of_device_id uctrl_match[] = { { .name = "uctrl", }, {}, }; MODULE_DEVICE_TABLE(of, uctrl_match); static struct platform_driver uctrl_driver = { .driver = { .name = "uctrl", .of_match_table = uctrl_match, }, .probe = uctrl_probe, .remove = uctrl_remove, }; module_platform_driver(uctrl_driver); MODULE_LICENSE("GPL");
linux-master
drivers/sbus/char/uctrl.c
// SPDX-License-Identifier: GPL-2.0-only /* envctrl.c: Temperature and Fan monitoring on Machines providing it. * * Copyright (C) 1998 Eddie C. Dost ([email protected]) * Copyright (C) 2000 Vinh Truong ([email protected]) * VT - The implementation is to support Sun Microelectronics (SME) platform * environment monitoring. SME platforms use pcf8584 as the i2c bus * controller to access pcf8591 (8-bit A/D and D/A converter) and * pcf8571 (256 x 8-bit static low-voltage RAM with I2C-bus interface). * At board level, it follows SME Firmware I2C Specification. Reference: * http://www-eu2.semiconductors.com/pip/PCF8584P * http://www-eu2.semiconductors.com/pip/PCF8574AP * http://www-eu2.semiconductors.com/pip/PCF8591P * * EB - Added support for CP1500 Global Address and PS/Voltage monitoring. * Eric Brower <[email protected]> * * DB - Audit every copy_to_user in envctrl_read. * Daniele Bellucci <[email protected]> */ #include <linux/module.h> #include <linux/kthread.h> #include <linux/delay.h> #include <linux/ioport.h> #include <linux/miscdevice.h> #include <linux/kmod.h> #include <linux/reboot.h> #include <linux/slab.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/uaccess.h> #include <asm/envctrl.h> #include <asm/io.h> #define DRIVER_NAME "envctrl" #define PFX DRIVER_NAME ": " #define PCF8584_ADDRESS 0x55 #define CONTROL_PIN 0x80 #define CONTROL_ES0 0x40 #define CONTROL_ES1 0x20 #define CONTROL_ES2 0x10 #define CONTROL_ENI 0x08 #define CONTROL_STA 0x04 #define CONTROL_STO 0x02 #define CONTROL_ACK 0x01 #define STATUS_PIN 0x80 #define STATUS_STS 0x20 #define STATUS_BER 0x10 #define STATUS_LRB 0x08 #define STATUS_AD0 0x08 #define STATUS_AAB 0x04 #define STATUS_LAB 0x02 #define STATUS_BB 0x01 /* * CLK Mode Register. */ #define BUS_CLK_90 0x00 #define BUS_CLK_45 0x01 #define BUS_CLK_11 0x02 #define BUS_CLK_1_5 0x03 #define CLK_3 0x00 #define CLK_4_43 0x10 #define CLK_6 0x14 #define CLK_8 0x18 #define CLK_12 0x1c #define OBD_SEND_START 0xc5 /* value to generate I2c_bus START condition */ #define OBD_SEND_STOP 0xc3 /* value to generate I2c_bus STOP condition */ /* Monitor type of i2c child device. * Firmware definitions. */ #define PCF8584_MAX_CHANNELS 8 #define PCF8584_GLOBALADDR_TYPE 6 /* global address monitor */ #define PCF8584_FANSTAT_TYPE 3 /* fan status monitor */ #define PCF8584_VOLTAGE_TYPE 2 /* voltage monitor */ #define PCF8584_TEMP_TYPE 1 /* temperature monitor*/ /* Monitor type of i2c child device. * Driver definitions. */ #define ENVCTRL_NOMON 0 #define ENVCTRL_CPUTEMP_MON 1 /* cpu temperature monitor */ #define ENVCTRL_CPUVOLTAGE_MON 2 /* voltage monitor */ #define ENVCTRL_FANSTAT_MON 3 /* fan status monitor */ #define ENVCTRL_ETHERTEMP_MON 4 /* ethernet temperature */ /* monitor */ #define ENVCTRL_VOLTAGESTAT_MON 5 /* voltage status monitor */ #define ENVCTRL_MTHRBDTEMP_MON 6 /* motherboard temperature */ #define ENVCTRL_SCSITEMP_MON 7 /* scsi temperature */ #define ENVCTRL_GLOBALADDR_MON 8 /* global address */ /* Child device type. * Driver definitions. */ #define I2C_ADC 0 /* pcf8591 */ #define I2C_GPIO 1 /* pcf8571 */ /* Data read from child device may need to decode * through a data table and a scale. * Translation type as defined by firmware. */ #define ENVCTRL_TRANSLATE_NO 0 #define ENVCTRL_TRANSLATE_PARTIAL 1 #define ENVCTRL_TRANSLATE_COMBINED 2 #define ENVCTRL_TRANSLATE_FULL 3 /* table[data] */ #define ENVCTRL_TRANSLATE_SCALE 4 /* table[data]/scale */ /* Driver miscellaneous definitions. */ #define ENVCTRL_MAX_CPU 4 #define CHANNEL_DESC_SZ 256 /* Mask values for combined GlobalAddress/PowerStatus node */ #define ENVCTRL_GLOBALADDR_ADDR_MASK 0x1F #define ENVCTRL_GLOBALADDR_PSTAT_MASK 0x60 /* Node 0x70 ignored on CompactPCI CP1400/1500 platforms * (see envctrl_init_i2c_child) */ #define ENVCTRL_CPCI_IGNORED_NODE 0x70 #define PCF8584_DATA 0x00 #define PCF8584_CSR 0x01 /* Each child device can be monitored by up to PCF8584_MAX_CHANNELS. * Property of a port or channel as defined by the firmware. */ struct pcf8584_channel { unsigned char chnl_no; unsigned char io_direction; unsigned char type; unsigned char last; }; /* Each child device may have one or more tables of bytes to help decode * data. Table property as defined by the firmware. */ struct pcf8584_tblprop { unsigned int type; unsigned int scale; unsigned int offset; /* offset from the beginning of the table */ unsigned int size; }; /* i2c child */ struct i2c_child_t { /* Either ADC or GPIO. */ unsigned char i2ctype; unsigned long addr; struct pcf8584_channel chnl_array[PCF8584_MAX_CHANNELS]; /* Channel info. */ unsigned int total_chnls; /* Number of monitor channels. */ unsigned char fan_mask; /* Byte mask for fan status channels. */ unsigned char voltage_mask; /* Byte mask for voltage status channels. */ struct pcf8584_tblprop tblprop_array[PCF8584_MAX_CHANNELS]; /* Properties of all monitor channels. */ unsigned int total_tbls; /* Number of monitor tables. */ char *tables; /* Pointer to table(s). */ char chnls_desc[CHANNEL_DESC_SZ]; /* Channel description. */ char mon_type[PCF8584_MAX_CHANNELS]; }; static void __iomem *i2c; static struct i2c_child_t i2c_childlist[ENVCTRL_MAX_CPU*2]; static unsigned char chnls_mask[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 }; static unsigned int warning_temperature = 0; static unsigned int shutdown_temperature = 0; static char read_cpu; /* Forward declarations. */ static struct i2c_child_t *envctrl_get_i2c_child(unsigned char); /* Function Description: Test the PIN bit (Pending Interrupt Not) * to test when serial transmission is completed . * Return : None. */ static void envtrl_i2c_test_pin(void) { int limit = 1000000; while (--limit > 0) { if (!(readb(i2c + PCF8584_CSR) & STATUS_PIN)) break; udelay(1); } if (limit <= 0) printk(KERN_INFO PFX "Pin status will not clear.\n"); } /* Function Description: Test busy bit. * Return : None. */ static void envctrl_i2c_test_bb(void) { int limit = 1000000; while (--limit > 0) { /* Busy bit 0 means busy. */ if (readb(i2c + PCF8584_CSR) & STATUS_BB) break; udelay(1); } if (limit <= 0) printk(KERN_INFO PFX "Busy bit will not clear.\n"); } /* Function Description: Send the address for a read access. * Return : 0 if not acknowledged, otherwise acknowledged. */ static int envctrl_i2c_read_addr(unsigned char addr) { envctrl_i2c_test_bb(); /* Load address. */ writeb(addr + 1, i2c + PCF8584_DATA); envctrl_i2c_test_bb(); writeb(OBD_SEND_START, i2c + PCF8584_CSR); /* Wait for PIN. */ envtrl_i2c_test_pin(); /* CSR 0 means acknowledged. */ if (!(readb(i2c + PCF8584_CSR) & STATUS_LRB)) { return readb(i2c + PCF8584_DATA); } else { writeb(OBD_SEND_STOP, i2c + PCF8584_CSR); return 0; } } /* Function Description: Send the address for write mode. * Return : None. */ static void envctrl_i2c_write_addr(unsigned char addr) { envctrl_i2c_test_bb(); writeb(addr, i2c + PCF8584_DATA); /* Generate Start condition. */ writeb(OBD_SEND_START, i2c + PCF8584_CSR); } /* Function Description: Read 1 byte of data from addr * set by envctrl_i2c_read_addr() * Return : Data from address set by envctrl_i2c_read_addr(). */ static unsigned char envctrl_i2c_read_data(void) { envtrl_i2c_test_pin(); writeb(CONTROL_ES0, i2c + PCF8584_CSR); /* Send neg ack. */ return readb(i2c + PCF8584_DATA); } /* Function Description: Instruct the device which port to read data from. * Return : None. */ static void envctrl_i2c_write_data(unsigned char port) { envtrl_i2c_test_pin(); writeb(port, i2c + PCF8584_DATA); } /* Function Description: Generate Stop condition after last byte is sent. * Return : None. */ static void envctrl_i2c_stop(void) { envtrl_i2c_test_pin(); writeb(OBD_SEND_STOP, i2c + PCF8584_CSR); } /* Function Description: Read adc device. * Return : Data at address and port. */ static unsigned char envctrl_i2c_read_8591(unsigned char addr, unsigned char port) { /* Send address. */ envctrl_i2c_write_addr(addr); /* Setup port to read. */ envctrl_i2c_write_data(port); envctrl_i2c_stop(); /* Read port. */ envctrl_i2c_read_addr(addr); /* Do a single byte read and send stop. */ envctrl_i2c_read_data(); envctrl_i2c_stop(); return readb(i2c + PCF8584_DATA); } /* Function Description: Read gpio device. * Return : Data at address. */ static unsigned char envctrl_i2c_read_8574(unsigned char addr) { unsigned char rd; envctrl_i2c_read_addr(addr); /* Do a single byte read and send stop. */ rd = envctrl_i2c_read_data(); envctrl_i2c_stop(); return rd; } /* Function Description: Decode data read from an adc device using firmware * table. * Return: Number of read bytes. Data is stored in bufdata in ascii format. */ static int envctrl_i2c_data_translate(unsigned char data, int translate_type, int scale, char *tbl, char *bufdata) { int len = 0; switch (translate_type) { case ENVCTRL_TRANSLATE_NO: /* No decode necessary. */ len = 1; bufdata[0] = data; break; case ENVCTRL_TRANSLATE_FULL: /* Decode this way: data = table[data]. */ len = 1; bufdata[0] = tbl[data]; break; case ENVCTRL_TRANSLATE_SCALE: /* Decode this way: data = table[data]/scale */ sprintf(bufdata,"%d ", (tbl[data] * 10) / (scale)); len = strlen(bufdata); bufdata[len - 1] = bufdata[len - 2]; bufdata[len - 2] = '.'; break; default: break; } return len; } /* Function Description: Read cpu-related data such as cpu temperature, voltage. * Return: Number of read bytes. Data is stored in bufdata in ascii format. */ static int envctrl_read_cpu_info(int cpu, struct i2c_child_t *pchild, char mon_type, unsigned char *bufdata) { unsigned char data; int i, j = -1; char *tbl; /* Find the right monitor type and channel. */ for (i = 0; i < PCF8584_MAX_CHANNELS; i++) { if (pchild->mon_type[i] == mon_type) { if (++j == cpu) { break; } } } if (j != cpu) return 0; /* Read data from address and port. */ data = envctrl_i2c_read_8591((unsigned char)pchild->addr, (unsigned char)pchild->chnl_array[i].chnl_no); /* Find decoding table. */ tbl = pchild->tables + pchild->tblprop_array[i].offset; return envctrl_i2c_data_translate(data, pchild->tblprop_array[i].type, pchild->tblprop_array[i].scale, tbl, bufdata); } /* Function Description: Read noncpu-related data such as motherboard * temperature. * Return: Number of read bytes. Data is stored in bufdata in ascii format. */ static int envctrl_read_noncpu_info(struct i2c_child_t *pchild, char mon_type, unsigned char *bufdata) { unsigned char data; int i; char *tbl = NULL; for (i = 0; i < PCF8584_MAX_CHANNELS; i++) { if (pchild->mon_type[i] == mon_type) break; } if (i >= PCF8584_MAX_CHANNELS) return 0; /* Read data from address and port. */ data = envctrl_i2c_read_8591((unsigned char)pchild->addr, (unsigned char)pchild->chnl_array[i].chnl_no); /* Find decoding table. */ tbl = pchild->tables + pchild->tblprop_array[i].offset; return envctrl_i2c_data_translate(data, pchild->tblprop_array[i].type, pchild->tblprop_array[i].scale, tbl, bufdata); } /* Function Description: Read fan status. * Return : Always 1 byte. Status stored in bufdata. */ static int envctrl_i2c_fan_status(struct i2c_child_t *pchild, unsigned char data, char *bufdata) { unsigned char tmp, ret = 0; int i, j = 0; tmp = data & pchild->fan_mask; if (tmp == pchild->fan_mask) { /* All bits are on. All fans are functioning. */ ret = ENVCTRL_ALL_FANS_GOOD; } else if (tmp == 0) { /* No bits are on. No fans are functioning. */ ret = ENVCTRL_ALL_FANS_BAD; } else { /* Go through all channels, mark 'on' the matched bits. * Notice that fan_mask may have discontiguous bits but * return mask are always contiguous. For example if we * monitor 4 fans at channels 0,1,2,4, the return mask * should be 00010000 if only fan at channel 4 is working. */ for (i = 0; i < PCF8584_MAX_CHANNELS;i++) { if (pchild->fan_mask & chnls_mask[i]) { if (!(chnls_mask[i] & tmp)) ret |= chnls_mask[j]; j++; } } } bufdata[0] = ret; return 1; } /* Function Description: Read global addressing line. * Return : Always 1 byte. Status stored in bufdata. */ static int envctrl_i2c_globaladdr(struct i2c_child_t *pchild, unsigned char data, char *bufdata) { /* Translatation table is not necessary, as global * addr is the integer value of the GA# bits. * * NOTE: MSB is documented as zero, but I see it as '1' always.... * * ----------------------------------------------- * | 0 | FAL | DEG | GA4 | GA3 | GA2 | GA1 | GA0 | * ----------------------------------------------- * GA0 - GA4 integer value of Global Address (backplane slot#) * DEG 0 = cPCI Power supply output is starting to degrade * 1 = cPCI Power supply output is OK * FAL 0 = cPCI Power supply has failed * 1 = cPCI Power supply output is OK */ bufdata[0] = (data & ENVCTRL_GLOBALADDR_ADDR_MASK); return 1; } /* Function Description: Read standard voltage and power supply status. * Return : Always 1 byte. Status stored in bufdata. */ static unsigned char envctrl_i2c_voltage_status(struct i2c_child_t *pchild, unsigned char data, char *bufdata) { unsigned char tmp, ret = 0; int i, j = 0; tmp = data & pchild->voltage_mask; /* Two channels are used to monitor voltage and power supply. */ if (tmp == pchild->voltage_mask) { /* All bits are on. Voltage and power supply are okay. */ ret = ENVCTRL_VOLTAGE_POWERSUPPLY_GOOD; } else if (tmp == 0) { /* All bits are off. Voltage and power supply are bad */ ret = ENVCTRL_VOLTAGE_POWERSUPPLY_BAD; } else { /* Either voltage or power supply has problem. */ for (i = 0; i < PCF8584_MAX_CHANNELS; i++) { if (pchild->voltage_mask & chnls_mask[i]) { j++; /* Break out when there is a mismatch. */ if (!(chnls_mask[i] & tmp)) break; } } /* Make a wish that hardware will always use the * first channel for voltage and the second for * power supply. */ if (j == 1) ret = ENVCTRL_VOLTAGE_BAD; else ret = ENVCTRL_POWERSUPPLY_BAD; } bufdata[0] = ret; return 1; } /* Function Description: Read a byte from /dev/envctrl. Mapped to user read(). * Return: Number of read bytes. 0 for error. */ static ssize_t envctrl_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { struct i2c_child_t *pchild; unsigned char data[10]; int ret = 0; /* Get the type of read as decided in ioctl() call. * Find the appropriate i2c child. * Get the data and put back to the user buffer. */ switch ((int)(long)file->private_data) { case ENVCTRL_RD_WARNING_TEMPERATURE: if (warning_temperature == 0) return 0; data[0] = (unsigned char)(warning_temperature); ret = 1; if (copy_to_user(buf, data, ret)) ret = -EFAULT; break; case ENVCTRL_RD_SHUTDOWN_TEMPERATURE: if (shutdown_temperature == 0) return 0; data[0] = (unsigned char)(shutdown_temperature); ret = 1; if (copy_to_user(buf, data, ret)) ret = -EFAULT; break; case ENVCTRL_RD_MTHRBD_TEMPERATURE: if (!(pchild = envctrl_get_i2c_child(ENVCTRL_MTHRBDTEMP_MON))) return 0; ret = envctrl_read_noncpu_info(pchild, ENVCTRL_MTHRBDTEMP_MON, data); if (copy_to_user(buf, data, ret)) ret = -EFAULT; break; case ENVCTRL_RD_CPU_TEMPERATURE: if (!(pchild = envctrl_get_i2c_child(ENVCTRL_CPUTEMP_MON))) return 0; ret = envctrl_read_cpu_info(read_cpu, pchild, ENVCTRL_CPUTEMP_MON, data); /* Reset cpu to the default cpu0. */ if (copy_to_user(buf, data, ret)) ret = -EFAULT; break; case ENVCTRL_RD_CPU_VOLTAGE: if (!(pchild = envctrl_get_i2c_child(ENVCTRL_CPUVOLTAGE_MON))) return 0; ret = envctrl_read_cpu_info(read_cpu, pchild, ENVCTRL_CPUVOLTAGE_MON, data); /* Reset cpu to the default cpu0. */ if (copy_to_user(buf, data, ret)) ret = -EFAULT; break; case ENVCTRL_RD_SCSI_TEMPERATURE: if (!(pchild = envctrl_get_i2c_child(ENVCTRL_SCSITEMP_MON))) return 0; ret = envctrl_read_noncpu_info(pchild, ENVCTRL_SCSITEMP_MON, data); if (copy_to_user(buf, data, ret)) ret = -EFAULT; break; case ENVCTRL_RD_ETHERNET_TEMPERATURE: if (!(pchild = envctrl_get_i2c_child(ENVCTRL_ETHERTEMP_MON))) return 0; ret = envctrl_read_noncpu_info(pchild, ENVCTRL_ETHERTEMP_MON, data); if (copy_to_user(buf, data, ret)) ret = -EFAULT; break; case ENVCTRL_RD_FAN_STATUS: if (!(pchild = envctrl_get_i2c_child(ENVCTRL_FANSTAT_MON))) return 0; data[0] = envctrl_i2c_read_8574(pchild->addr); ret = envctrl_i2c_fan_status(pchild,data[0], data); if (copy_to_user(buf, data, ret)) ret = -EFAULT; break; case ENVCTRL_RD_GLOBALADDRESS: if (!(pchild = envctrl_get_i2c_child(ENVCTRL_GLOBALADDR_MON))) return 0; data[0] = envctrl_i2c_read_8574(pchild->addr); ret = envctrl_i2c_globaladdr(pchild, data[0], data); if (copy_to_user(buf, data, ret)) ret = -EFAULT; break; case ENVCTRL_RD_VOLTAGE_STATUS: if (!(pchild = envctrl_get_i2c_child(ENVCTRL_VOLTAGESTAT_MON))) /* If voltage monitor not present, check for CPCI equivalent */ if (!(pchild = envctrl_get_i2c_child(ENVCTRL_GLOBALADDR_MON))) return 0; data[0] = envctrl_i2c_read_8574(pchild->addr); ret = envctrl_i2c_voltage_status(pchild, data[0], data); if (copy_to_user(buf, data, ret)) ret = -EFAULT; break; default: break; } return ret; } /* Function Description: Command what to read. Mapped to user ioctl(). * Return: Gives 0 for implemented commands, -EINVAL otherwise. */ static long envctrl_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { char __user *infobuf; switch (cmd) { case ENVCTRL_RD_WARNING_TEMPERATURE: case ENVCTRL_RD_SHUTDOWN_TEMPERATURE: case ENVCTRL_RD_MTHRBD_TEMPERATURE: case ENVCTRL_RD_FAN_STATUS: case ENVCTRL_RD_VOLTAGE_STATUS: case ENVCTRL_RD_ETHERNET_TEMPERATURE: case ENVCTRL_RD_SCSI_TEMPERATURE: case ENVCTRL_RD_GLOBALADDRESS: file->private_data = (void *)(long)cmd; break; case ENVCTRL_RD_CPU_TEMPERATURE: case ENVCTRL_RD_CPU_VOLTAGE: /* Check to see if application passes in any cpu number, * the default is cpu0. */ infobuf = (char __user *) arg; if (infobuf == NULL) { read_cpu = 0; }else { get_user(read_cpu, infobuf); } /* Save the command for use when reading. */ file->private_data = (void *)(long)cmd; break; default: return -EINVAL; } return 0; } /* Function Description: open device. Mapped to user open(). * Return: Always 0. */ static int envctrl_open(struct inode *inode, struct file *file) { file->private_data = NULL; return 0; } /* Function Description: Open device. Mapped to user close(). * Return: Always 0. */ static int envctrl_release(struct inode *inode, struct file *file) { return 0; } static const struct file_operations envctrl_fops = { .owner = THIS_MODULE, .read = envctrl_read, .unlocked_ioctl = envctrl_ioctl, .compat_ioctl = compat_ptr_ioctl, .open = envctrl_open, .release = envctrl_release, .llseek = noop_llseek, }; static struct miscdevice envctrl_dev = { ENVCTRL_MINOR, "envctrl", &envctrl_fops }; /* Function Description: Set monitor type based on firmware description. * Return: None. */ static void envctrl_set_mon(struct i2c_child_t *pchild, const char *chnl_desc, int chnl_no) { /* Firmware only has temperature type. It does not distinguish * different kinds of temperatures. We use channel description * to disinguish them. */ if (!(strcmp(chnl_desc,"temp,cpu")) || !(strcmp(chnl_desc,"temp,cpu0")) || !(strcmp(chnl_desc,"temp,cpu1")) || !(strcmp(chnl_desc,"temp,cpu2")) || !(strcmp(chnl_desc,"temp,cpu3"))) pchild->mon_type[chnl_no] = ENVCTRL_CPUTEMP_MON; if (!(strcmp(chnl_desc,"vddcore,cpu0")) || !(strcmp(chnl_desc,"vddcore,cpu1")) || !(strcmp(chnl_desc,"vddcore,cpu2")) || !(strcmp(chnl_desc,"vddcore,cpu3"))) pchild->mon_type[chnl_no] = ENVCTRL_CPUVOLTAGE_MON; if (!(strcmp(chnl_desc,"temp,motherboard"))) pchild->mon_type[chnl_no] = ENVCTRL_MTHRBDTEMP_MON; if (!(strcmp(chnl_desc,"temp,scsi"))) pchild->mon_type[chnl_no] = ENVCTRL_SCSITEMP_MON; if (!(strcmp(chnl_desc,"temp,ethernet"))) pchild->mon_type[chnl_no] = ENVCTRL_ETHERTEMP_MON; } /* Function Description: Initialize monitor channel with channel desc, * decoding tables, monitor type, optional properties. * Return: None. */ static void envctrl_init_adc(struct i2c_child_t *pchild, struct device_node *dp) { int i = 0, len; const char *pos; const unsigned int *pval; /* Firmware describe channels into a stream separated by a '\0'. */ pos = of_get_property(dp, "channels-description", &len); while (len > 0) { int l = strlen(pos) + 1; envctrl_set_mon(pchild, pos, i++); len -= l; pos += l; } /* Get optional properties. */ pval = of_get_property(dp, "warning-temp", NULL); if (pval) warning_temperature = *pval; pval = of_get_property(dp, "shutdown-temp", NULL); if (pval) shutdown_temperature = *pval; } /* Function Description: Initialize child device monitoring fan status. * Return: None. */ static void envctrl_init_fanstat(struct i2c_child_t *pchild) { int i; /* Go through all channels and set up the mask. */ for (i = 0; i < pchild->total_chnls; i++) pchild->fan_mask |= chnls_mask[(pchild->chnl_array[i]).chnl_no]; /* We only need to know if this child has fan status monitored. * We don't care which channels since we have the mask already. */ pchild->mon_type[0] = ENVCTRL_FANSTAT_MON; } /* Function Description: Initialize child device for global addressing line. * Return: None. */ static void envctrl_init_globaladdr(struct i2c_child_t *pchild) { int i; /* Voltage/PowerSupply monitoring is piggybacked * with Global Address on CompactPCI. See comments * within envctrl_i2c_globaladdr for bit assignments. * * The mask is created here by assigning mask bits to each * bit position that represents PCF8584_VOLTAGE_TYPE data. * Channel numbers are not consecutive within the globaladdr * node (why?), so we use the actual counter value as chnls_mask * index instead of the chnl_array[x].chnl_no value. * * NOTE: This loop could be replaced with a constant representing * a mask of bits 5&6 (ENVCTRL_GLOBALADDR_PSTAT_MASK). */ for (i = 0; i < pchild->total_chnls; i++) { if (PCF8584_VOLTAGE_TYPE == pchild->chnl_array[i].type) { pchild->voltage_mask |= chnls_mask[i]; } } /* We only need to know if this child has global addressing * line monitored. We don't care which channels since we know * the mask already (ENVCTRL_GLOBALADDR_ADDR_MASK). */ pchild->mon_type[0] = ENVCTRL_GLOBALADDR_MON; } /* Initialize child device monitoring voltage status. */ static void envctrl_init_voltage_status(struct i2c_child_t *pchild) { int i; /* Go through all channels and set up the mask. */ for (i = 0; i < pchild->total_chnls; i++) pchild->voltage_mask |= chnls_mask[(pchild->chnl_array[i]).chnl_no]; /* We only need to know if this child has voltage status monitored. * We don't care which channels since we have the mask already. */ pchild->mon_type[0] = ENVCTRL_VOLTAGESTAT_MON; } /* Function Description: Initialize i2c child device. * Return: None. */ static void envctrl_init_i2c_child(struct device_node *dp, struct i2c_child_t *pchild) { int len, i, tbls_size = 0; const void *pval; /* Get device address. */ pval = of_get_property(dp, "reg", &len); memcpy(&pchild->addr, pval, len); /* Get tables property. Read firmware temperature tables. */ pval = of_get_property(dp, "translation", &len); if (pval && len > 0) { memcpy(pchild->tblprop_array, pval, len); pchild->total_tbls = len / sizeof(struct pcf8584_tblprop); for (i = 0; i < pchild->total_tbls; i++) { if ((pchild->tblprop_array[i].size + pchild->tblprop_array[i].offset) > tbls_size) { tbls_size = pchild->tblprop_array[i].size + pchild->tblprop_array[i].offset; } } pchild->tables = kmalloc(tbls_size, GFP_KERNEL); if (pchild->tables == NULL){ printk(KERN_ERR PFX "Failed to allocate table.\n"); return; } pval = of_get_property(dp, "tables", &len); if (!pval || len <= 0) { printk(KERN_ERR PFX "Failed to get table.\n"); return; } memcpy(pchild->tables, pval, len); } /* SPARCengine ASM Reference Manual (ref. SMI doc 805-7581-04) * sections 2.5, 3.5, 4.5 state node 0x70 for CP1400/1500 is * "For Factory Use Only." * * We ignore the node on these platforms by assigning the * 'NULL' monitor type. */ if (ENVCTRL_CPCI_IGNORED_NODE == pchild->addr) { struct device_node *root_node; int len; root_node = of_find_node_by_path("/"); if (of_node_name_eq(root_node, "SUNW,UltraSPARC-IIi-cEngine")) { for (len = 0; len < PCF8584_MAX_CHANNELS; ++len) { pchild->mon_type[len] = ENVCTRL_NOMON; } of_node_put(root_node); return; } of_node_put(root_node); } /* Get the monitor channels. */ pval = of_get_property(dp, "channels-in-use", &len); memcpy(pchild->chnl_array, pval, len); pchild->total_chnls = len / sizeof(struct pcf8584_channel); for (i = 0; i < pchild->total_chnls; i++) { switch (pchild->chnl_array[i].type) { case PCF8584_TEMP_TYPE: envctrl_init_adc(pchild, dp); break; case PCF8584_GLOBALADDR_TYPE: envctrl_init_globaladdr(pchild); i = pchild->total_chnls; break; case PCF8584_FANSTAT_TYPE: envctrl_init_fanstat(pchild); i = pchild->total_chnls; break; case PCF8584_VOLTAGE_TYPE: if (pchild->i2ctype == I2C_ADC) { envctrl_init_adc(pchild,dp); } else { envctrl_init_voltage_status(pchild); } i = pchild->total_chnls; break; default: break; } } } /* Function Description: Search the child device list for a device. * Return : The i2c child if found. NULL otherwise. */ static struct i2c_child_t *envctrl_get_i2c_child(unsigned char mon_type) { int i, j; for (i = 0; i < ENVCTRL_MAX_CPU*2; i++) { for (j = 0; j < PCF8584_MAX_CHANNELS; j++) { if (i2c_childlist[i].mon_type[j] == mon_type) { return (struct i2c_child_t *)(&(i2c_childlist[i])); } } } return NULL; } static void envctrl_do_shutdown(void) { static int inprog = 0; if (inprog != 0) return; inprog = 1; printk(KERN_CRIT "kenvctrld: WARNING: Shutting down the system now.\n"); orderly_poweroff(true); } static struct task_struct *kenvctrld_task; static int kenvctrld(void *__unused) { int poll_interval; int whichcpu; char tempbuf[10]; struct i2c_child_t *cputemp; if (NULL == (cputemp = envctrl_get_i2c_child(ENVCTRL_CPUTEMP_MON))) { printk(KERN_ERR PFX "kenvctrld unable to monitor CPU temp-- exiting\n"); return -ENODEV; } poll_interval = 5000; /* TODO env_mon_interval */ printk(KERN_INFO PFX "%s starting...\n", current->comm); for (;;) { msleep_interruptible(poll_interval); if (kthread_should_stop()) break; for (whichcpu = 0; whichcpu < ENVCTRL_MAX_CPU; ++whichcpu) { if (0 < envctrl_read_cpu_info(whichcpu, cputemp, ENVCTRL_CPUTEMP_MON, tempbuf)) { if (tempbuf[0] >= shutdown_temperature) { printk(KERN_CRIT "%s: WARNING: CPU%i temperature %i C meets or exceeds "\ "shutdown threshold %i C\n", current->comm, whichcpu, tempbuf[0], shutdown_temperature); envctrl_do_shutdown(); } } } } printk(KERN_INFO PFX "%s exiting...\n", current->comm); return 0; } static int envctrl_probe(struct platform_device *op) { struct device_node *dp; int index, err; if (i2c) return -EINVAL; i2c = of_ioremap(&op->resource[0], 0, 0x2, DRIVER_NAME); if (!i2c) return -ENOMEM; index = 0; dp = op->dev.of_node->child; while (dp) { if (of_node_name_eq(dp, "gpio")) { i2c_childlist[index].i2ctype = I2C_GPIO; envctrl_init_i2c_child(dp, &(i2c_childlist[index++])); } else if (of_node_name_eq(dp, "adc")) { i2c_childlist[index].i2ctype = I2C_ADC; envctrl_init_i2c_child(dp, &(i2c_childlist[index++])); } dp = dp->sibling; } /* Set device address. */ writeb(CONTROL_PIN, i2c + PCF8584_CSR); writeb(PCF8584_ADDRESS, i2c + PCF8584_DATA); /* Set system clock and SCL frequencies. */ writeb(CONTROL_PIN | CONTROL_ES1, i2c + PCF8584_CSR); writeb(CLK_4_43 | BUS_CLK_90, i2c + PCF8584_DATA); /* Enable serial interface. */ writeb(CONTROL_PIN | CONTROL_ES0 | CONTROL_ACK, i2c + PCF8584_CSR); udelay(200); /* Register the device as a minor miscellaneous device. */ err = misc_register(&envctrl_dev); if (err) { printk(KERN_ERR PFX "Unable to get misc minor %d\n", envctrl_dev.minor); goto out_iounmap; } /* Note above traversal routine post-incremented 'i' to accommodate * a next child device, so we decrement before reverse-traversal of * child devices. */ printk(KERN_INFO PFX "Initialized "); for (--index; index >= 0; --index) { printk("[%s 0x%lx]%s", (I2C_ADC == i2c_childlist[index].i2ctype) ? "adc" : ((I2C_GPIO == i2c_childlist[index].i2ctype) ? "gpio" : "unknown"), i2c_childlist[index].addr, (0 == index) ? "\n" : " "); } kenvctrld_task = kthread_run(kenvctrld, NULL, "kenvctrld"); if (IS_ERR(kenvctrld_task)) { err = PTR_ERR(kenvctrld_task); goto out_deregister; } return 0; out_deregister: misc_deregister(&envctrl_dev); out_iounmap: of_iounmap(&op->resource[0], i2c, 0x2); for (index = 0; index < ENVCTRL_MAX_CPU * 2; index++) kfree(i2c_childlist[index].tables); return err; } static int envctrl_remove(struct platform_device *op) { int index; kthread_stop(kenvctrld_task); of_iounmap(&op->resource[0], i2c, 0x2); misc_deregister(&envctrl_dev); for (index = 0; index < ENVCTRL_MAX_CPU * 2; index++) kfree(i2c_childlist[index].tables); return 0; } static const struct of_device_id envctrl_match[] = { { .name = "i2c", .compatible = "i2cpcf,8584", }, {}, }; MODULE_DEVICE_TABLE(of, envctrl_match); static struct platform_driver envctrl_driver = { .driver = { .name = DRIVER_NAME, .of_match_table = envctrl_match, }, .probe = envctrl_probe, .remove = envctrl_remove, }; module_platform_driver(envctrl_driver); MODULE_LICENSE("GPL");
linux-master
drivers/sbus/char/envctrl.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Linux/SPARC PROM Configuration Driver * Copyright (C) 1996 Thomas K. Dyas ([email protected]) * Copyright (C) 1996 Eddie C. Dost ([email protected]) * * This character device driver allows user programs to access the * PROM device tree. It is compatible with the SunOS /dev/openprom * driver and the NetBSD /dev/openprom driver. The SunOS eeprom * utility works without any modifications. * * The driver uses a minor number under the misc device major. The * file read/write mode determines the type of access to the PROM. * Interrupts are disabled whenever the driver calls into the PROM for * sanity's sake. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/mutex.h> #include <linux/string.h> #include <linux/miscdevice.h> #include <linux/init.h> #include <linux/fs.h> #include <asm/oplib.h> #include <asm/prom.h> #include <linux/uaccess.h> #include <asm/openpromio.h> #ifdef CONFIG_PCI #include <linux/pci.h> #endif MODULE_AUTHOR("Thomas K. Dyas ([email protected]) and Eddie C. Dost ([email protected])"); MODULE_DESCRIPTION("OPENPROM Configuration Driver"); MODULE_LICENSE("GPL"); MODULE_VERSION("1.0"); MODULE_ALIAS_MISCDEV(SUN_OPENPROM_MINOR); /* Private data kept by the driver for each descriptor. */ typedef struct openprom_private_data { struct device_node *current_node; /* Current node for SunOS ioctls. */ struct device_node *lastnode; /* Last valid node used by BSD ioctls. */ } DATA; /* ID of the PROM node containing all of the EEPROM options. */ static DEFINE_MUTEX(openprom_mutex); static struct device_node *options_node; /* * Copy an openpromio structure into kernel space from user space. * This routine does error checking to make sure that all memory * accesses are within bounds. A pointer to the allocated openpromio * structure will be placed in "*opp_p". Return value is the length * of the user supplied buffer. */ static int copyin(struct openpromio __user *info, struct openpromio **opp_p) { unsigned int bufsize; if (!info || !opp_p) return -EFAULT; if (get_user(bufsize, &info->oprom_size)) return -EFAULT; if (bufsize == 0) return -EINVAL; /* If the bufsize is too large, just limit it. * Fix from Jason Rappleye. */ if (bufsize > OPROMMAXPARAM) bufsize = OPROMMAXPARAM; if (!(*opp_p = kzalloc(sizeof(int) + bufsize + 1, GFP_KERNEL))) return -ENOMEM; if (copy_from_user(&(*opp_p)->oprom_array, &info->oprom_array, bufsize)) { kfree(*opp_p); return -EFAULT; } return bufsize; } static int getstrings(struct openpromio __user *info, struct openpromio **opp_p) { int n, bufsize; char c; if (!info || !opp_p) return -EFAULT; if (!(*opp_p = kzalloc(sizeof(int) + OPROMMAXPARAM + 1, GFP_KERNEL))) return -ENOMEM; (*opp_p)->oprom_size = 0; n = bufsize = 0; while ((n < 2) && (bufsize < OPROMMAXPARAM)) { if (get_user(c, &info->oprom_array[bufsize])) { kfree(*opp_p); return -EFAULT; } if (c == '\0') n++; (*opp_p)->oprom_array[bufsize++] = c; } if (!n) { kfree(*opp_p); return -EINVAL; } return bufsize; } /* * Copy an openpromio structure in kernel space back to user space. */ static int copyout(void __user *info, struct openpromio *opp, int len) { if (copy_to_user(info, opp, len)) return -EFAULT; return 0; } static int opromgetprop(void __user *argp, struct device_node *dp, struct openpromio *op, int bufsize) { const void *pval; int len; if (!dp || !(pval = of_get_property(dp, op->oprom_array, &len)) || len <= 0 || len > bufsize) return copyout(argp, op, sizeof(int)); memcpy(op->oprom_array, pval, len); op->oprom_array[len] = '\0'; op->oprom_size = len; return copyout(argp, op, sizeof(int) + bufsize); } static int opromnxtprop(void __user *argp, struct device_node *dp, struct openpromio *op, int bufsize) { struct property *prop; int len; if (!dp) return copyout(argp, op, sizeof(int)); if (op->oprom_array[0] == '\0') { prop = dp->properties; if (!prop) return copyout(argp, op, sizeof(int)); len = strlen(prop->name); } else { prop = of_find_property(dp, op->oprom_array, NULL); if (!prop || !prop->next || (len = strlen(prop->next->name)) + 1 > bufsize) return copyout(argp, op, sizeof(int)); prop = prop->next; } memcpy(op->oprom_array, prop->name, len); op->oprom_array[len] = '\0'; op->oprom_size = ++len; return copyout(argp, op, sizeof(int) + bufsize); } static int opromsetopt(struct device_node *dp, struct openpromio *op, int bufsize) { char *buf = op->oprom_array + strlen(op->oprom_array) + 1; int len = op->oprom_array + bufsize - buf; return of_set_property(options_node, op->oprom_array, buf, len); } static int opromnext(void __user *argp, unsigned int cmd, struct device_node *dp, struct openpromio *op, int bufsize, DATA *data) { phandle ph; BUILD_BUG_ON(sizeof(phandle) != sizeof(int)); if (bufsize < sizeof(phandle)) return -EINVAL; ph = *((int *) op->oprom_array); if (ph) { dp = of_find_node_by_phandle(ph); if (!dp) return -EINVAL; switch (cmd) { case OPROMNEXT: dp = dp->sibling; break; case OPROMCHILD: dp = dp->child; break; case OPROMSETCUR: default: break; } } else { /* Sibling of node zero is the root node. */ if (cmd != OPROMNEXT) return -EINVAL; dp = of_find_node_by_path("/"); } ph = 0; if (dp) ph = dp->phandle; data->current_node = dp; *((int *) op->oprom_array) = ph; op->oprom_size = sizeof(phandle); return copyout(argp, op, bufsize + sizeof(int)); } static int oprompci2node(void __user *argp, struct device_node *dp, struct openpromio *op, int bufsize, DATA *data) { int err = -EINVAL; if (bufsize >= 2*sizeof(int)) { #ifdef CONFIG_PCI struct pci_dev *pdev; struct device_node *dp; pdev = pci_get_domain_bus_and_slot(0, ((int *) op->oprom_array)[0], ((int *) op->oprom_array)[1]); dp = pci_device_to_OF_node(pdev); data->current_node = dp; *((int *)op->oprom_array) = dp->phandle; op->oprom_size = sizeof(int); err = copyout(argp, op, bufsize + sizeof(int)); pci_dev_put(pdev); #endif } return err; } static int oprompath2node(void __user *argp, struct device_node *dp, struct openpromio *op, int bufsize, DATA *data) { phandle ph = 0; dp = of_find_node_by_path(op->oprom_array); if (dp) ph = dp->phandle; data->current_node = dp; *((int *)op->oprom_array) = ph; op->oprom_size = sizeof(int); return copyout(argp, op, bufsize + sizeof(int)); } static int opromgetbootargs(void __user *argp, struct openpromio *op, int bufsize) { char *buf = saved_command_line; int len = strlen(buf); if (len > bufsize) return -EINVAL; strcpy(op->oprom_array, buf); op->oprom_size = len; return copyout(argp, op, bufsize + sizeof(int)); } /* * SunOS and Solaris /dev/openprom ioctl calls. */ static long openprom_sunos_ioctl(struct file * file, unsigned int cmd, unsigned long arg, struct device_node *dp) { DATA *data = file->private_data; struct openpromio *opp = NULL; int bufsize, error = 0; static int cnt; void __user *argp = (void __user *)arg; if (cmd == OPROMSETOPT) bufsize = getstrings(argp, &opp); else bufsize = copyin(argp, &opp); if (bufsize < 0) return bufsize; mutex_lock(&openprom_mutex); switch (cmd) { case OPROMGETOPT: case OPROMGETPROP: error = opromgetprop(argp, dp, opp, bufsize); break; case OPROMNXTOPT: case OPROMNXTPROP: error = opromnxtprop(argp, dp, opp, bufsize); break; case OPROMSETOPT: case OPROMSETOPT2: error = opromsetopt(dp, opp, bufsize); break; case OPROMNEXT: case OPROMCHILD: case OPROMSETCUR: error = opromnext(argp, cmd, dp, opp, bufsize, data); break; case OPROMPCI2NODE: error = oprompci2node(argp, dp, opp, bufsize, data); break; case OPROMPATH2NODE: error = oprompath2node(argp, dp, opp, bufsize, data); break; case OPROMGETBOOTARGS: error = opromgetbootargs(argp, opp, bufsize); break; case OPROMU2P: case OPROMGETCONS: case OPROMGETFBNAME: if (cnt++ < 10) printk(KERN_INFO "openprom_sunos_ioctl: unimplemented ioctl\n"); error = -EINVAL; break; default: if (cnt++ < 10) printk(KERN_INFO "openprom_sunos_ioctl: cmd 0x%X, arg 0x%lX\n", cmd, arg); error = -EINVAL; break; } kfree(opp); mutex_unlock(&openprom_mutex); return error; } static struct device_node *get_node(phandle n, DATA *data) { struct device_node *dp = of_find_node_by_phandle(n); if (dp) data->lastnode = dp; return dp; } /* Copy in a whole string from userspace into kernelspace. */ static char * copyin_string(char __user *user, size_t len) { if ((ssize_t)len < 0 || (ssize_t)(len + 1) < 0) return ERR_PTR(-EINVAL); return memdup_user_nul(user, len); } /* * NetBSD /dev/openprom ioctl calls. */ static int opiocget(void __user *argp, DATA *data) { struct opiocdesc op; struct device_node *dp; char *str; const void *pval; int err, len; if (copy_from_user(&op, argp, sizeof(op))) return -EFAULT; dp = get_node(op.op_nodeid, data); str = copyin_string(op.op_name, op.op_namelen); if (IS_ERR(str)) return PTR_ERR(str); pval = of_get_property(dp, str, &len); err = 0; if (!pval || len > op.op_buflen) { err = -EINVAL; } else { op.op_buflen = len; if (copy_to_user(argp, &op, sizeof(op)) || copy_to_user(op.op_buf, pval, len)) err = -EFAULT; } kfree(str); return err; } static int opiocnextprop(void __user *argp, DATA *data) { struct opiocdesc op; struct device_node *dp; struct property *prop; char *str; int len; if (copy_from_user(&op, argp, sizeof(op))) return -EFAULT; dp = get_node(op.op_nodeid, data); if (!dp) return -EINVAL; str = copyin_string(op.op_name, op.op_namelen); if (IS_ERR(str)) return PTR_ERR(str); if (str[0] == '\0') { prop = dp->properties; } else { prop = of_find_property(dp, str, NULL); if (prop) prop = prop->next; } kfree(str); if (!prop) len = 0; else len = prop->length; if (len > op.op_buflen) len = op.op_buflen; if (copy_to_user(argp, &op, sizeof(op))) return -EFAULT; if (len && copy_to_user(op.op_buf, prop->value, len)) return -EFAULT; return 0; } static int opiocset(void __user *argp, DATA *data) { struct opiocdesc op; struct device_node *dp; char *str, *tmp; int err; if (copy_from_user(&op, argp, sizeof(op))) return -EFAULT; dp = get_node(op.op_nodeid, data); if (!dp) return -EINVAL; str = copyin_string(op.op_name, op.op_namelen); if (IS_ERR(str)) return PTR_ERR(str); tmp = copyin_string(op.op_buf, op.op_buflen); if (IS_ERR(tmp)) { kfree(str); return PTR_ERR(tmp); } err = of_set_property(dp, str, tmp, op.op_buflen); kfree(str); kfree(tmp); return err; } static int opiocgetnext(unsigned int cmd, void __user *argp) { struct device_node *dp; phandle nd; BUILD_BUG_ON(sizeof(phandle) != sizeof(int)); if (copy_from_user(&nd, argp, sizeof(phandle))) return -EFAULT; if (nd == 0) { if (cmd != OPIOCGETNEXT) return -EINVAL; dp = of_find_node_by_path("/"); } else { dp = of_find_node_by_phandle(nd); nd = 0; if (dp) { if (cmd == OPIOCGETNEXT) dp = dp->sibling; else dp = dp->child; } } if (dp) nd = dp->phandle; if (copy_to_user(argp, &nd, sizeof(phandle))) return -EFAULT; return 0; } static int openprom_bsd_ioctl(struct file * file, unsigned int cmd, unsigned long arg) { DATA *data = file->private_data; void __user *argp = (void __user *)arg; int err; mutex_lock(&openprom_mutex); switch (cmd) { case OPIOCGET: err = opiocget(argp, data); break; case OPIOCNEXTPROP: err = opiocnextprop(argp, data); break; case OPIOCSET: err = opiocset(argp, data); break; case OPIOCGETOPTNODE: BUILD_BUG_ON(sizeof(phandle) != sizeof(int)); err = 0; if (copy_to_user(argp, &options_node->phandle, sizeof(phandle))) err = -EFAULT; break; case OPIOCGETNEXT: case OPIOCGETCHILD: err = opiocgetnext(cmd, argp); break; default: err = -EINVAL; break; } mutex_unlock(&openprom_mutex); return err; } /* * Handoff control to the correct ioctl handler. */ static long openprom_ioctl(struct file * file, unsigned int cmd, unsigned long arg) { DATA *data = file->private_data; switch (cmd) { case OPROMGETOPT: case OPROMNXTOPT: if ((file->f_mode & FMODE_READ) == 0) return -EPERM; return openprom_sunos_ioctl(file, cmd, arg, options_node); case OPROMSETOPT: case OPROMSETOPT2: if ((file->f_mode & FMODE_WRITE) == 0) return -EPERM; return openprom_sunos_ioctl(file, cmd, arg, options_node); case OPROMNEXT: case OPROMCHILD: case OPROMGETPROP: case OPROMNXTPROP: if ((file->f_mode & FMODE_READ) == 0) return -EPERM; return openprom_sunos_ioctl(file, cmd, arg, data->current_node); case OPROMU2P: case OPROMGETCONS: case OPROMGETFBNAME: case OPROMGETBOOTARGS: case OPROMSETCUR: case OPROMPCI2NODE: case OPROMPATH2NODE: if ((file->f_mode & FMODE_READ) == 0) return -EPERM; return openprom_sunos_ioctl(file, cmd, arg, NULL); case OPIOCGET: case OPIOCNEXTPROP: case OPIOCGETOPTNODE: case OPIOCGETNEXT: case OPIOCGETCHILD: if ((file->f_mode & FMODE_READ) == 0) return -EBADF; return openprom_bsd_ioctl(file,cmd,arg); case OPIOCSET: if ((file->f_mode & FMODE_WRITE) == 0) return -EBADF; return openprom_bsd_ioctl(file,cmd,arg); default: return -EINVAL; }; } static long openprom_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { long rval = -ENOTTY; /* * SunOS/Solaris only, the NetBSD one's have embedded pointers in * the arg which we'd need to clean up... */ switch (cmd) { case OPROMGETOPT: case OPROMSETOPT: case OPROMNXTOPT: case OPROMSETOPT2: case OPROMNEXT: case OPROMCHILD: case OPROMGETPROP: case OPROMNXTPROP: case OPROMU2P: case OPROMGETCONS: case OPROMGETFBNAME: case OPROMGETBOOTARGS: case OPROMSETCUR: case OPROMPCI2NODE: case OPROMPATH2NODE: rval = openprom_ioctl(file, cmd, arg); break; } return rval; } static int openprom_open(struct inode * inode, struct file * file) { DATA *data; data = kmalloc(sizeof(DATA), GFP_KERNEL); if (!data) return -ENOMEM; mutex_lock(&openprom_mutex); data->current_node = of_find_node_by_path("/"); data->lastnode = data->current_node; file->private_data = (void *) data; mutex_unlock(&openprom_mutex); return 0; } static int openprom_release(struct inode * inode, struct file * file) { kfree(file->private_data); return 0; } static const struct file_operations openprom_fops = { .owner = THIS_MODULE, .llseek = no_llseek, .unlocked_ioctl = openprom_ioctl, .compat_ioctl = openprom_compat_ioctl, .open = openprom_open, .release = openprom_release, }; static struct miscdevice openprom_dev = { .minor = SUN_OPENPROM_MINOR, .name = "openprom", .fops = &openprom_fops, }; static int __init openprom_init(void) { int err; err = misc_register(&openprom_dev); if (err) return err; options_node = of_get_child_by_name(of_find_node_by_path("/"), "options"); if (!options_node) { misc_deregister(&openprom_dev); return -EIO; } return 0; } static void __exit openprom_cleanup(void) { misc_deregister(&openprom_dev); } module_init(openprom_init); module_exit(openprom_cleanup);
linux-master
drivers/sbus/char/openprom.c
// SPDX-License-Identifier: GPL-2.0-only /* bbc_i2c.c: I2C low-level driver for BBC device on UltraSPARC-III * platforms. * * Copyright (C) 2001, 2008 David S. Miller ([email protected]) */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/sched.h> #include <linux/wait.h> #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/of.h> #include <linux/of_platform.h> #include <linux/platform_device.h> #include <asm/bbc.h> #include <asm/io.h> #include "bbc_i2c.h" /* Convert this driver to use i2c bus layer someday... */ #define I2C_PCF_PIN 0x80 #define I2C_PCF_ESO 0x40 #define I2C_PCF_ES1 0x20 #define I2C_PCF_ES2 0x10 #define I2C_PCF_ENI 0x08 #define I2C_PCF_STA 0x04 #define I2C_PCF_STO 0x02 #define I2C_PCF_ACK 0x01 #define I2C_PCF_START (I2C_PCF_PIN | I2C_PCF_ESO | I2C_PCF_ENI | I2C_PCF_STA | I2C_PCF_ACK) #define I2C_PCF_STOP (I2C_PCF_PIN | I2C_PCF_ESO | I2C_PCF_STO | I2C_PCF_ACK) #define I2C_PCF_REPSTART ( I2C_PCF_ESO | I2C_PCF_STA | I2C_PCF_ACK) #define I2C_PCF_IDLE (I2C_PCF_PIN | I2C_PCF_ESO | I2C_PCF_ACK) #define I2C_PCF_INI 0x40 /* 1 if not initialized */ #define I2C_PCF_STS 0x20 #define I2C_PCF_BER 0x10 #define I2C_PCF_AD0 0x08 #define I2C_PCF_LRB 0x08 #define I2C_PCF_AAS 0x04 #define I2C_PCF_LAB 0x02 #define I2C_PCF_BB 0x01 /* The BBC devices have two I2C controllers. The first I2C controller * connects mainly to configuration proms (NVRAM, cpu configuration, * dimm types, etc.). Whereas the second I2C controller connects to * environmental control devices such as fans and temperature sensors. * The second controller also connects to the smartcard reader, if present. */ static void set_device_claimage(struct bbc_i2c_bus *bp, struct platform_device *op, int val) { int i; for (i = 0; i < NUM_CHILDREN; i++) { if (bp->devs[i].device == op) { bp->devs[i].client_claimed = val; return; } } } #define claim_device(BP,ECHILD) set_device_claimage(BP,ECHILD,1) #define release_device(BP,ECHILD) set_device_claimage(BP,ECHILD,0) struct platform_device *bbc_i2c_getdev(struct bbc_i2c_bus *bp, int index) { struct platform_device *op = NULL; int curidx = 0, i; for (i = 0; i < NUM_CHILDREN; i++) { if (!(op = bp->devs[i].device)) break; if (curidx == index) goto out; op = NULL; curidx++; } out: if (curidx == index) return op; return NULL; } struct bbc_i2c_client *bbc_i2c_attach(struct bbc_i2c_bus *bp, struct platform_device *op) { struct bbc_i2c_client *client; const u32 *reg; client = kzalloc(sizeof(*client), GFP_KERNEL); if (!client) return NULL; client->bp = bp; client->op = op; reg = of_get_property(op->dev.of_node, "reg", NULL); if (!reg) { kfree(client); return NULL; } client->bus = reg[0]; client->address = reg[1]; claim_device(bp, op); return client; } void bbc_i2c_detach(struct bbc_i2c_client *client) { struct bbc_i2c_bus *bp = client->bp; struct platform_device *op = client->op; release_device(bp, op); kfree(client); } static int wait_for_pin(struct bbc_i2c_bus *bp, u8 *status) { DECLARE_WAITQUEUE(wait, current); int limit = 32; int ret = 1; bp->waiting = 1; add_wait_queue(&bp->wq, &wait); while (limit-- > 0) { long val; val = wait_event_interruptible_timeout( bp->wq, (((*status = readb(bp->i2c_control_regs + 0)) & I2C_PCF_PIN) == 0), msecs_to_jiffies(250)); if (val > 0) { ret = 0; break; } } remove_wait_queue(&bp->wq, &wait); bp->waiting = 0; return ret; } int bbc_i2c_writeb(struct bbc_i2c_client *client, unsigned char val, int off) { struct bbc_i2c_bus *bp = client->bp; int address = client->address; u8 status; int ret = -1; if (bp->i2c_bussel_reg != NULL) writeb(client->bus, bp->i2c_bussel_reg); writeb(address, bp->i2c_control_regs + 0x1); writeb(I2C_PCF_START, bp->i2c_control_regs + 0x0); if (wait_for_pin(bp, &status)) goto out; writeb(off, bp->i2c_control_regs + 0x1); if (wait_for_pin(bp, &status) || (status & I2C_PCF_LRB) != 0) goto out; writeb(val, bp->i2c_control_regs + 0x1); if (wait_for_pin(bp, &status)) goto out; ret = 0; out: writeb(I2C_PCF_STOP, bp->i2c_control_regs + 0x0); return ret; } int bbc_i2c_readb(struct bbc_i2c_client *client, unsigned char *byte, int off) { struct bbc_i2c_bus *bp = client->bp; unsigned char address = client->address, status; int ret = -1; if (bp->i2c_bussel_reg != NULL) writeb(client->bus, bp->i2c_bussel_reg); writeb(address, bp->i2c_control_regs + 0x1); writeb(I2C_PCF_START, bp->i2c_control_regs + 0x0); if (wait_for_pin(bp, &status)) goto out; writeb(off, bp->i2c_control_regs + 0x1); if (wait_for_pin(bp, &status) || (status & I2C_PCF_LRB) != 0) goto out; writeb(I2C_PCF_STOP, bp->i2c_control_regs + 0x0); address |= 0x1; /* READ */ writeb(address, bp->i2c_control_regs + 0x1); writeb(I2C_PCF_START, bp->i2c_control_regs + 0x0); if (wait_for_pin(bp, &status)) goto out; /* Set PIN back to one so the device sends the first * byte. */ (void) readb(bp->i2c_control_regs + 0x1); if (wait_for_pin(bp, &status)) goto out; writeb(I2C_PCF_ESO | I2C_PCF_ENI, bp->i2c_control_regs + 0x0); *byte = readb(bp->i2c_control_regs + 0x1); if (wait_for_pin(bp, &status)) goto out; ret = 0; out: writeb(I2C_PCF_STOP, bp->i2c_control_regs + 0x0); (void) readb(bp->i2c_control_regs + 0x1); return ret; } int bbc_i2c_write_buf(struct bbc_i2c_client *client, char *buf, int len, int off) { int ret = 0; while (len > 0) { ret = bbc_i2c_writeb(client, *buf, off); if (ret < 0) break; len--; buf++; off++; } return ret; } int bbc_i2c_read_buf(struct bbc_i2c_client *client, char *buf, int len, int off) { int ret = 0; while (len > 0) { ret = bbc_i2c_readb(client, buf, off); if (ret < 0) break; len--; buf++; off++; } return ret; } EXPORT_SYMBOL(bbc_i2c_getdev); EXPORT_SYMBOL(bbc_i2c_attach); EXPORT_SYMBOL(bbc_i2c_detach); EXPORT_SYMBOL(bbc_i2c_writeb); EXPORT_SYMBOL(bbc_i2c_readb); EXPORT_SYMBOL(bbc_i2c_write_buf); EXPORT_SYMBOL(bbc_i2c_read_buf); static irqreturn_t bbc_i2c_interrupt(int irq, void *dev_id) { struct bbc_i2c_bus *bp = dev_id; /* PIN going from set to clear is the only event which * makes the i2c assert an interrupt. */ if (bp->waiting && !(readb(bp->i2c_control_regs + 0x0) & I2C_PCF_PIN)) wake_up_interruptible(&bp->wq); return IRQ_HANDLED; } static void reset_one_i2c(struct bbc_i2c_bus *bp) { writeb(I2C_PCF_PIN, bp->i2c_control_regs + 0x0); writeb(bp->own, bp->i2c_control_regs + 0x1); writeb(I2C_PCF_PIN | I2C_PCF_ES1, bp->i2c_control_regs + 0x0); writeb(bp->clock, bp->i2c_control_regs + 0x1); writeb(I2C_PCF_IDLE, bp->i2c_control_regs + 0x0); } static struct bbc_i2c_bus * attach_one_i2c(struct platform_device *op, int index) { struct bbc_i2c_bus *bp; struct device_node *dp; int entry; bp = kzalloc(sizeof(*bp), GFP_KERNEL); if (!bp) return NULL; INIT_LIST_HEAD(&bp->temps); INIT_LIST_HEAD(&bp->fans); bp->i2c_control_regs = of_ioremap(&op->resource[0], 0, 0x2, "bbc_i2c_regs"); if (!bp->i2c_control_regs) goto fail; if (op->num_resources == 2) { bp->i2c_bussel_reg = of_ioremap(&op->resource[1], 0, 0x1, "bbc_i2c_bussel"); if (!bp->i2c_bussel_reg) goto fail; } bp->waiting = 0; init_waitqueue_head(&bp->wq); if (request_irq(op->archdata.irqs[0], bbc_i2c_interrupt, IRQF_SHARED, "bbc_i2c", bp)) goto fail; bp->index = index; bp->op = op; spin_lock_init(&bp->lock); entry = 0; for (dp = op->dev.of_node->child; dp && entry < 8; dp = dp->sibling, entry++) { struct platform_device *child_op; child_op = of_find_device_by_node(dp); bp->devs[entry].device = child_op; bp->devs[entry].client_claimed = 0; } writeb(I2C_PCF_PIN, bp->i2c_control_regs + 0x0); bp->own = readb(bp->i2c_control_regs + 0x01); writeb(I2C_PCF_PIN | I2C_PCF_ES1, bp->i2c_control_regs + 0x0); bp->clock = readb(bp->i2c_control_regs + 0x01); printk(KERN_INFO "i2c-%d: Regs at %p, %d devices, own %02x, clock %02x.\n", bp->index, bp->i2c_control_regs, entry, bp->own, bp->clock); reset_one_i2c(bp); return bp; fail: if (bp->i2c_bussel_reg) of_iounmap(&op->resource[1], bp->i2c_bussel_reg, 1); if (bp->i2c_control_regs) of_iounmap(&op->resource[0], bp->i2c_control_regs, 2); kfree(bp); return NULL; } extern int bbc_envctrl_init(struct bbc_i2c_bus *bp); extern void bbc_envctrl_cleanup(struct bbc_i2c_bus *bp); static int bbc_i2c_probe(struct platform_device *op) { struct bbc_i2c_bus *bp; int err, index = 0; bp = attach_one_i2c(op, index); if (!bp) return -EINVAL; err = bbc_envctrl_init(bp); if (err) { free_irq(op->archdata.irqs[0], bp); if (bp->i2c_bussel_reg) of_iounmap(&op->resource[0], bp->i2c_bussel_reg, 1); if (bp->i2c_control_regs) of_iounmap(&op->resource[1], bp->i2c_control_regs, 2); kfree(bp); } else { dev_set_drvdata(&op->dev, bp); } return err; } static int bbc_i2c_remove(struct platform_device *op) { struct bbc_i2c_bus *bp = dev_get_drvdata(&op->dev); bbc_envctrl_cleanup(bp); free_irq(op->archdata.irqs[0], bp); if (bp->i2c_bussel_reg) of_iounmap(&op->resource[0], bp->i2c_bussel_reg, 1); if (bp->i2c_control_regs) of_iounmap(&op->resource[1], bp->i2c_control_regs, 2); kfree(bp); return 0; } static const struct of_device_id bbc_i2c_match[] = { { .name = "i2c", .compatible = "SUNW,bbc-i2c", }, {}, }; MODULE_DEVICE_TABLE(of, bbc_i2c_match); static struct platform_driver bbc_i2c_driver = { .driver = { .name = "bbc_i2c", .of_match_table = bbc_i2c_match, }, .probe = bbc_i2c_probe, .remove = bbc_i2c_remove, }; module_platform_driver(bbc_i2c_driver); MODULE_LICENSE("GPL");
linux-master
drivers/sbus/char/bbc_i2c.c
// SPDX-License-Identifier: GPL-2.0-only /* display7seg.c - Driver implementation for the 7-segment display * present on Sun Microsystems CP1400 and CP1500 * * Copyright (c) 2000 Eric Brower ([email protected]) */ #include <linux/device.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/fs.h> #include <linux/errno.h> #include <linux/major.h> #include <linux/miscdevice.h> #include <linux/ioport.h> /* request_region */ #include <linux/slab.h> #include <linux/mutex.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/atomic.h> #include <linux/uaccess.h> /* put_/get_user */ #include <asm/io.h> #include <asm/display7seg.h> #define DRIVER_NAME "d7s" #define PFX DRIVER_NAME ": " static DEFINE_MUTEX(d7s_mutex); static int sol_compat = 0; /* Solaris compatibility mode */ /* Solaris compatibility flag - * The Solaris implementation omits support for several * documented driver features (ref Sun doc 806-0180-03). * By default, this module supports the documented driver * abilities, rather than the Solaris implementation: * * 1) Device ALWAYS reverts to OBP-specified FLIPPED mode * upon closure of device or module unload. * 2) Device ioctls D7SIOCRD/D7SIOCWR honor toggling of * FLIP bit * * If you wish the device to operate as under Solaris, * omitting above features, set this parameter to non-zero. */ module_param(sol_compat, int, 0); MODULE_PARM_DESC(sol_compat, "Disables documented functionality omitted from Solaris driver"); MODULE_AUTHOR("Eric Brower <[email protected]>"); MODULE_DESCRIPTION("7-Segment Display driver for Sun Microsystems CP1400/1500"); MODULE_LICENSE("GPL"); struct d7s { void __iomem *regs; bool flipped; }; struct d7s *d7s_device; /* * Register block address- see header for details * ----------------------------------------- * | DP | ALARM | FLIP | 4 | 3 | 2 | 1 | 0 | * ----------------------------------------- * * DP - Toggles decimal point on/off * ALARM - Toggles "Alarm" LED green/red * FLIP - Inverts display for upside-down mounted board * bits 0-4 - 7-segment display contents */ static atomic_t d7s_users = ATOMIC_INIT(0); static int d7s_open(struct inode *inode, struct file *f) { if (D7S_MINOR != iminor(inode)) return -ENODEV; atomic_inc(&d7s_users); return 0; } static int d7s_release(struct inode *inode, struct file *f) { /* Reset flipped state to OBP default only if * no other users have the device open and we * are not operating in solaris-compat mode */ if (atomic_dec_and_test(&d7s_users) && !sol_compat) { struct d7s *p = d7s_device; u8 regval = 0; regval = readb(p->regs); if (p->flipped) regval |= D7S_FLIP; else regval &= ~D7S_FLIP; writeb(regval, p->regs); } return 0; } static long d7s_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct d7s *p = d7s_device; u8 regs = readb(p->regs); int error = 0; u8 ireg = 0; if (D7S_MINOR != iminor(file_inode(file))) return -ENODEV; mutex_lock(&d7s_mutex); switch (cmd) { case D7SIOCWR: /* assign device register values we mask-out D7S_FLIP * if in sol_compat mode */ if (get_user(ireg, (int __user *) arg)) { error = -EFAULT; break; } if (sol_compat) { if (regs & D7S_FLIP) ireg |= D7S_FLIP; else ireg &= ~D7S_FLIP; } writeb(ireg, p->regs); break; case D7SIOCRD: /* retrieve device register values * NOTE: Solaris implementation returns D7S_FLIP bit * as toggled by user, even though it does not honor it. * This driver will not misinform you about the state * of your hardware while in sol_compat mode */ if (put_user(regs, (int __user *) arg)) { error = -EFAULT; break; } break; case D7SIOCTM: /* toggle device mode-- flip display orientation */ regs ^= D7S_FLIP; writeb(regs, p->regs); break; } mutex_unlock(&d7s_mutex); return error; } static const struct file_operations d7s_fops = { .owner = THIS_MODULE, .unlocked_ioctl = d7s_ioctl, .compat_ioctl = compat_ptr_ioctl, .open = d7s_open, .release = d7s_release, .llseek = noop_llseek, }; static struct miscdevice d7s_miscdev = { .minor = D7S_MINOR, .name = DRIVER_NAME, .fops = &d7s_fops }; static int d7s_probe(struct platform_device *op) { struct device_node *opts; int err = -EINVAL; struct d7s *p; u8 regs; if (d7s_device) goto out; p = devm_kzalloc(&op->dev, sizeof(*p), GFP_KERNEL); err = -ENOMEM; if (!p) goto out; p->regs = of_ioremap(&op->resource[0], 0, sizeof(u8), "d7s"); if (!p->regs) { printk(KERN_ERR PFX "Cannot map chip registers\n"); goto out; } err = misc_register(&d7s_miscdev); if (err) { printk(KERN_ERR PFX "Unable to acquire miscdevice minor %i\n", D7S_MINOR); goto out_iounmap; } /* OBP option "d7s-flipped?" is honored as default for the * device, and reset default when detached */ regs = readb(p->regs); opts = of_find_node_by_path("/options"); if (opts) p->flipped = of_property_read_bool(opts, "d7s-flipped?"); if (p->flipped) regs |= D7S_FLIP; else regs &= ~D7S_FLIP; writeb(regs, p->regs); printk(KERN_INFO PFX "7-Segment Display%pOF at [%s:0x%llx] %s\n", op->dev.of_node, (regs & D7S_FLIP) ? " (FLIPPED)" : "", op->resource[0].start, sol_compat ? "in sol_compat mode" : ""); dev_set_drvdata(&op->dev, p); d7s_device = p; err = 0; of_node_put(opts); out: return err; out_iounmap: of_iounmap(&op->resource[0], p->regs, sizeof(u8)); goto out; } static int d7s_remove(struct platform_device *op) { struct d7s *p = dev_get_drvdata(&op->dev); u8 regs = readb(p->regs); /* Honor OBP d7s-flipped? unless operating in solaris-compat mode */ if (sol_compat) { if (p->flipped) regs |= D7S_FLIP; else regs &= ~D7S_FLIP; writeb(regs, p->regs); } misc_deregister(&d7s_miscdev); of_iounmap(&op->resource[0], p->regs, sizeof(u8)); return 0; } static const struct of_device_id d7s_match[] = { { .name = "display7seg", }, {}, }; MODULE_DEVICE_TABLE(of, d7s_match); static struct platform_driver d7s_driver = { .driver = { .name = DRIVER_NAME, .of_match_table = d7s_match, }, .probe = d7s_probe, .remove = d7s_remove, }; module_platform_driver(d7s_driver);
linux-master
drivers/sbus/char/display7seg.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. */ /* * Oracle Data Analytics Accelerator (DAX) * * DAX is a coprocessor which resides on the SPARC M7 (DAX1) and M8 * (DAX2) processor chips, and has direct access to the CPU's L3 * caches as well as physical memory. It can perform several * operations on data streams with various input and output formats. * The driver provides a transport mechanism only and has limited * knowledge of the various opcodes and data formats. A user space * library provides high level services and translates these into low * level commands which are then passed into the driver and * subsequently the hypervisor and the coprocessor. The library is * the recommended way for applications to use the coprocessor, and * the driver interface is not intended for general use. * * See Documentation/arch/sparc/oradax/oracle-dax.rst for more details. */ #include <linux/uaccess.h> #include <linux/module.h> #include <linux/delay.h> #include <linux/cdev.h> #include <linux/slab.h> #include <linux/mm.h> #include <asm/hypervisor.h> #include <asm/mdesc.h> #include <asm/oradax.h> MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Driver for Oracle Data Analytics Accelerator"); #define DAX_DBG_FLG_BASIC 0x01 #define DAX_DBG_FLG_STAT 0x02 #define DAX_DBG_FLG_INFO 0x04 #define DAX_DBG_FLG_ALL 0xff #define dax_err(fmt, ...) pr_err("%s: " fmt "\n", __func__, ##__VA_ARGS__) #define dax_info(fmt, ...) pr_info("%s: " fmt "\n", __func__, ##__VA_ARGS__) #define dax_dbg(fmt, ...) do { \ if (dax_debug & DAX_DBG_FLG_BASIC)\ dax_info(fmt, ##__VA_ARGS__); \ } while (0) #define dax_stat_dbg(fmt, ...) do { \ if (dax_debug & DAX_DBG_FLG_STAT) \ dax_info(fmt, ##__VA_ARGS__); \ } while (0) #define dax_info_dbg(fmt, ...) do { \ if (dax_debug & DAX_DBG_FLG_INFO) \ dax_info(fmt, ##__VA_ARGS__); \ } while (0) #define DAX1_MINOR 1 #define DAX1_MAJOR 1 #define DAX2_MINOR 0 #define DAX2_MAJOR 2 #define DAX1_STR "ORCL,sun4v-dax" #define DAX2_STR "ORCL,sun4v-dax2" #define DAX_CA_ELEMS (DAX_MMAP_LEN / sizeof(struct dax_cca)) #define DAX_CCB_USEC 100 #define DAX_CCB_RETRIES 10000 /* stream types */ enum { OUT, PRI, SEC, TBL, NUM_STREAM_TYPES }; /* completion status */ #define CCA_STAT_NOT_COMPLETED 0 #define CCA_STAT_COMPLETED 1 #define CCA_STAT_FAILED 2 #define CCA_STAT_KILLED 3 #define CCA_STAT_NOT_RUN 4 #define CCA_STAT_PIPE_OUT 5 #define CCA_STAT_PIPE_SRC 6 #define CCA_STAT_PIPE_DST 7 /* completion err */ #define CCA_ERR_SUCCESS 0x0 /* no error */ #define CCA_ERR_OVERFLOW 0x1 /* buffer overflow */ #define CCA_ERR_DECODE 0x2 /* CCB decode error */ #define CCA_ERR_PAGE_OVERFLOW 0x3 /* page overflow */ #define CCA_ERR_KILLED 0x7 /* command was killed */ #define CCA_ERR_TIMEOUT 0x8 /* Timeout */ #define CCA_ERR_ADI 0x9 /* ADI error */ #define CCA_ERR_DATA_FMT 0xA /* data format error */ #define CCA_ERR_OTHER_NO_RETRY 0xE /* Other error, do not retry */ #define CCA_ERR_OTHER_RETRY 0xF /* Other error, retry */ #define CCA_ERR_PARTIAL_SYMBOL 0x80 /* QP partial symbol warning */ /* CCB address types */ #define DAX_ADDR_TYPE_NONE 0 #define DAX_ADDR_TYPE_VA_ALT 1 /* secondary context */ #define DAX_ADDR_TYPE_RA 2 /* real address */ #define DAX_ADDR_TYPE_VA 3 /* virtual address */ /* dax_header_t opcode */ #define DAX_OP_SYNC_NOP 0x0 #define DAX_OP_EXTRACT 0x1 #define DAX_OP_SCAN_VALUE 0x2 #define DAX_OP_SCAN_RANGE 0x3 #define DAX_OP_TRANSLATE 0x4 #define DAX_OP_SELECT 0x5 #define DAX_OP_INVERT 0x10 /* OR with translate, scan opcodes */ struct dax_header { u32 ccb_version:4; /* 31:28 CCB Version */ /* 27:24 Sync Flags */ u32 pipe:1; /* Pipeline */ u32 longccb:1; /* Longccb. Set for scan with lu2, lu3, lu4. */ u32 cond:1; /* Conditional */ u32 serial:1; /* Serial */ u32 opcode:8; /* 23:16 Opcode */ /* 15:0 Address Type. */ u32 reserved:3; /* 15:13 reserved */ u32 table_addr_type:2; /* 12:11 Huffman Table Address Type */ u32 out_addr_type:3; /* 10:8 Destination Address Type */ u32 sec_addr_type:3; /* 7:5 Secondary Source Address Type */ u32 pri_addr_type:3; /* 4:2 Primary Source Address Type */ u32 cca_addr_type:2; /* 1:0 Completion Address Type */ }; struct dax_control { u32 pri_fmt:4; /* 31:28 Primary Input Format */ u32 pri_elem_size:5; /* 27:23 Primary Input Element Size(less1) */ u32 pri_offset:3; /* 22:20 Primary Input Starting Offset */ u32 sec_encoding:1; /* 19 Secondary Input Encoding */ /* (must be 0 for Select) */ u32 sec_offset:3; /* 18:16 Secondary Input Starting Offset */ u32 sec_elem_size:2; /* 15:14 Secondary Input Element Size */ /* (must be 0 for Select) */ u32 out_fmt:2; /* 13:12 Output Format */ u32 out_elem_size:2; /* 11:10 Output Element Size */ u32 misc:10; /* 9:0 Opcode specific info */ }; struct dax_data_access { u64 flow_ctrl:2; /* 63:62 Flow Control Type */ u64 pipe_target:2; /* 61:60 Pipeline Target */ u64 out_buf_size:20; /* 59:40 Output Buffer Size */ /* (cachelines less 1) */ u64 unused1:8; /* 39:32 Reserved, Set to 0 */ u64 out_alloc:5; /* 31:27 Output Allocation */ u64 unused2:1; /* 26 Reserved */ u64 pri_len_fmt:2; /* 25:24 Input Length Format */ u64 pri_len:24; /* 23:0 Input Element/Byte/Bit Count */ /* (less 1) */ }; struct dax_ccb { struct dax_header hdr; /* CCB Header */ struct dax_control ctrl;/* Control Word */ void *ca; /* Completion Address */ void *pri; /* Primary Input Address */ struct dax_data_access dac; /* Data Access Control */ void *sec; /* Secondary Input Address */ u64 dword5; /* depends on opcode */ void *out; /* Output Address */ void *tbl; /* Table Address or bitmap */ }; struct dax_cca { u8 status; /* user may mwait on this address */ u8 err; /* user visible error notification */ u8 rsvd[2]; /* reserved */ u32 n_remaining; /* for QP partial symbol warning */ u32 output_sz; /* output in bytes */ u32 rsvd2; /* reserved */ u64 run_cycles; /* run time in OCND2 cycles */ u64 run_stats; /* nothing reported in version 1.0 */ u32 n_processed; /* number input elements */ u32 rsvd3[5]; /* reserved */ u64 retval; /* command return value */ u64 rsvd4[8]; /* reserved */ }; /* per thread CCB context */ struct dax_ctx { struct dax_ccb *ccb_buf; u64 ccb_buf_ra; /* cached RA of ccb_buf */ struct dax_cca *ca_buf; u64 ca_buf_ra; /* cached RA of ca_buf */ struct page *pages[DAX_CA_ELEMS][NUM_STREAM_TYPES]; /* array of locked pages */ struct task_struct *owner; /* thread that owns ctx */ struct task_struct *client; /* requesting thread */ union ccb_result result; u32 ccb_count; u32 fail_count; }; /* driver public entry points */ static int dax_open(struct inode *inode, struct file *file); static ssize_t dax_read(struct file *filp, char __user *buf, size_t count, loff_t *ppos); static ssize_t dax_write(struct file *filp, const char __user *buf, size_t count, loff_t *ppos); static int dax_devmap(struct file *f, struct vm_area_struct *vma); static int dax_close(struct inode *i, struct file *f); static const struct file_operations dax_fops = { .owner = THIS_MODULE, .open = dax_open, .read = dax_read, .write = dax_write, .mmap = dax_devmap, .release = dax_close, }; static int dax_ccb_exec(struct dax_ctx *ctx, const char __user *buf, size_t count, loff_t *ppos); static int dax_ccb_info(u64 ca, struct ccb_info_result *info); static int dax_ccb_kill(u64 ca, u16 *kill_res); static struct cdev c_dev; static dev_t first; static const struct class cl = { .name = DAX_NAME, }; static int max_ccb_version; static int dax_debug; module_param(dax_debug, int, 0644); MODULE_PARM_DESC(dax_debug, "Debug flags"); static int __init dax_attach(void) { unsigned long dummy, hv_rv, major, minor, minor_requested, max_ccbs; struct mdesc_handle *hp = mdesc_grab(); char *prop, *dax_name; bool found = false; int len, ret = 0; u64 pn; if (hp == NULL) { dax_err("Unable to grab mdesc"); return -ENODEV; } mdesc_for_each_node_by_name(hp, pn, "virtual-device") { prop = (char *)mdesc_get_property(hp, pn, "name", &len); if (prop == NULL) continue; if (strncmp(prop, "dax", strlen("dax"))) continue; dax_dbg("Found node 0x%llx = %s", pn, prop); prop = (char *)mdesc_get_property(hp, pn, "compatible", &len); if (prop == NULL) continue; dax_dbg("Found node 0x%llx = %s", pn, prop); found = true; break; } if (!found) { dax_err("No DAX device found"); ret = -ENODEV; goto done; } if (strncmp(prop, DAX2_STR, strlen(DAX2_STR)) == 0) { dax_name = DAX_NAME "2"; major = DAX2_MAJOR; minor_requested = DAX2_MINOR; max_ccb_version = 1; dax_dbg("MD indicates DAX2 coprocessor"); } else if (strncmp(prop, DAX1_STR, strlen(DAX1_STR)) == 0) { dax_name = DAX_NAME "1"; major = DAX1_MAJOR; minor_requested = DAX1_MINOR; max_ccb_version = 0; dax_dbg("MD indicates DAX1 coprocessor"); } else { dax_err("Unknown dax type: %s", prop); ret = -ENODEV; goto done; } minor = minor_requested; dax_dbg("Registering DAX HV api with major %ld minor %ld", major, minor); if (sun4v_hvapi_register(HV_GRP_DAX, major, &minor)) { dax_err("hvapi_register failed"); ret = -ENODEV; goto done; } else { dax_dbg("Max minor supported by HV = %ld (major %ld)", minor, major); minor = min(minor, minor_requested); dax_dbg("registered DAX major %ld minor %ld", major, minor); } /* submit a zero length ccb array to query coprocessor queue size */ hv_rv = sun4v_ccb_submit(0, 0, HV_CCB_QUERY_CMD, 0, &max_ccbs, &dummy); if (hv_rv != 0) { dax_err("get_hwqueue_size failed with status=%ld and max_ccbs=%ld", hv_rv, max_ccbs); ret = -ENODEV; goto done; } if (max_ccbs != DAX_MAX_CCBS) { dax_err("HV reports unsupported max_ccbs=%ld", max_ccbs); ret = -ENODEV; goto done; } if (alloc_chrdev_region(&first, 0, 1, DAX_NAME) < 0) { dax_err("alloc_chrdev_region failed"); ret = -ENXIO; goto done; } ret = class_register(&cl); if (ret) goto class_error; if (device_create(&cl, NULL, first, NULL, dax_name) == NULL) { dax_err("device_create failed"); ret = -ENXIO; goto device_error; } cdev_init(&c_dev, &dax_fops); if (cdev_add(&c_dev, first, 1) == -1) { dax_err("cdev_add failed"); ret = -ENXIO; goto cdev_error; } pr_info("Attached DAX module\n"); goto done; cdev_error: device_destroy(&cl, first); device_error: class_unregister(&cl); class_error: unregister_chrdev_region(first, 1); done: mdesc_release(hp); return ret; } module_init(dax_attach); static void __exit dax_detach(void) { pr_info("Cleaning up DAX module\n"); cdev_del(&c_dev); device_destroy(&cl, first); class_unregister(&cl); unregister_chrdev_region(first, 1); } module_exit(dax_detach); /* map completion area */ static int dax_devmap(struct file *f, struct vm_area_struct *vma) { struct dax_ctx *ctx = (struct dax_ctx *)f->private_data; size_t len = vma->vm_end - vma->vm_start; dax_dbg("len=0x%lx, flags=0x%lx", len, vma->vm_flags); if (ctx->owner != current) { dax_dbg("devmap called from wrong thread"); return -EINVAL; } if (len != DAX_MMAP_LEN) { dax_dbg("len(%lu) != DAX_MMAP_LEN(%d)", len, DAX_MMAP_LEN); return -EINVAL; } /* completion area is mapped read-only for user */ if (vma->vm_flags & VM_WRITE) return -EPERM; vm_flags_clear(vma, VM_MAYWRITE); if (remap_pfn_range(vma, vma->vm_start, ctx->ca_buf_ra >> PAGE_SHIFT, len, vma->vm_page_prot)) return -EAGAIN; dax_dbg("mmapped completion area at uva 0x%lx", vma->vm_start); return 0; } /* Unlock user pages. Called during dequeue or device close */ static void dax_unlock_pages(struct dax_ctx *ctx, int ccb_index, int nelem) { int i, j; for (i = ccb_index; i < ccb_index + nelem; i++) { for (j = 0; j < NUM_STREAM_TYPES; j++) { struct page *p = ctx->pages[i][j]; if (p) { dax_dbg("freeing page %p", p); unpin_user_pages_dirty_lock(&p, 1, j == OUT); ctx->pages[i][j] = NULL; } } } } static int dax_lock_page(void *va, struct page **p) { int ret; dax_dbg("uva %p", va); ret = pin_user_pages_fast((unsigned long)va, 1, FOLL_WRITE, p); if (ret == 1) { dax_dbg("locked page %p, for VA %p", *p, va); return 0; } dax_dbg("pin_user_pages failed, va=%p, ret=%d", va, ret); return -1; } static int dax_lock_pages(struct dax_ctx *ctx, int idx, int nelem, u64 *err_va) { int i; for (i = 0; i < nelem; i++) { struct dax_ccb *ccbp = &ctx->ccb_buf[i]; /* * For each address in the CCB whose type is virtual, * lock the page and change the type to virtual alternate * context. On error, return the offending address in * err_va. */ if (ccbp->hdr.out_addr_type == DAX_ADDR_TYPE_VA) { dax_dbg("output"); if (dax_lock_page(ccbp->out, &ctx->pages[i + idx][OUT]) != 0) { *err_va = (u64)ccbp->out; goto error; } ccbp->hdr.out_addr_type = DAX_ADDR_TYPE_VA_ALT; } if (ccbp->hdr.pri_addr_type == DAX_ADDR_TYPE_VA) { dax_dbg("input"); if (dax_lock_page(ccbp->pri, &ctx->pages[i + idx][PRI]) != 0) { *err_va = (u64)ccbp->pri; goto error; } ccbp->hdr.pri_addr_type = DAX_ADDR_TYPE_VA_ALT; } if (ccbp->hdr.sec_addr_type == DAX_ADDR_TYPE_VA) { dax_dbg("sec input"); if (dax_lock_page(ccbp->sec, &ctx->pages[i + idx][SEC]) != 0) { *err_va = (u64)ccbp->sec; goto error; } ccbp->hdr.sec_addr_type = DAX_ADDR_TYPE_VA_ALT; } if (ccbp->hdr.table_addr_type == DAX_ADDR_TYPE_VA) { dax_dbg("tbl"); if (dax_lock_page(ccbp->tbl, &ctx->pages[i + idx][TBL]) != 0) { *err_va = (u64)ccbp->tbl; goto error; } ccbp->hdr.table_addr_type = DAX_ADDR_TYPE_VA_ALT; } /* skip over 2nd 64 bytes of long CCB */ if (ccbp->hdr.longccb) i++; } return DAX_SUBMIT_OK; error: dax_unlock_pages(ctx, idx, nelem); return DAX_SUBMIT_ERR_NOACCESS; } static void dax_ccb_wait(struct dax_ctx *ctx, int idx) { int ret, nretries; u16 kill_res; dax_dbg("idx=%d", idx); for (nretries = 0; nretries < DAX_CCB_RETRIES; nretries++) { if (ctx->ca_buf[idx].status == CCA_STAT_NOT_COMPLETED) udelay(DAX_CCB_USEC); else return; } dax_dbg("ctx (%p): CCB[%d] timed out, wait usec=%d, retries=%d. Killing ccb", (void *)ctx, idx, DAX_CCB_USEC, DAX_CCB_RETRIES); ret = dax_ccb_kill(ctx->ca_buf_ra + idx * sizeof(struct dax_cca), &kill_res); dax_dbg("Kill CCB[%d] %s", idx, ret ? "failed" : "succeeded"); } static int dax_close(struct inode *ino, struct file *f) { struct dax_ctx *ctx = (struct dax_ctx *)f->private_data; int i; f->private_data = NULL; for (i = 0; i < DAX_CA_ELEMS; i++) { if (ctx->ca_buf[i].status == CCA_STAT_NOT_COMPLETED) { dax_dbg("CCB[%d] not completed", i); dax_ccb_wait(ctx, i); } dax_unlock_pages(ctx, i, 1); } kfree(ctx->ccb_buf); kfree(ctx->ca_buf); dax_stat_dbg("CCBs: %d good, %d bad", ctx->ccb_count, ctx->fail_count); kfree(ctx); return 0; } static ssize_t dax_read(struct file *f, char __user *buf, size_t count, loff_t *ppos) { struct dax_ctx *ctx = f->private_data; if (ctx->client != current) return -EUSERS; ctx->client = NULL; if (count != sizeof(union ccb_result)) return -EINVAL; if (copy_to_user(buf, &ctx->result, sizeof(union ccb_result))) return -EFAULT; return count; } static ssize_t dax_write(struct file *f, const char __user *buf, size_t count, loff_t *ppos) { struct dax_ctx *ctx = f->private_data; struct dax_command hdr; unsigned long ca; int i, idx, ret; if (ctx->client != NULL) return -EINVAL; if (count == 0 || count > DAX_MAX_CCBS * sizeof(struct dax_ccb)) return -EINVAL; if (count % sizeof(struct dax_ccb) == 0) return dax_ccb_exec(ctx, buf, count, ppos); /* CCB EXEC */ if (count != sizeof(struct dax_command)) return -EINVAL; /* immediate command */ if (ctx->owner != current) return -EUSERS; if (copy_from_user(&hdr, buf, sizeof(hdr))) return -EFAULT; ca = ctx->ca_buf_ra + hdr.ca_offset; switch (hdr.command) { case CCB_KILL: if (hdr.ca_offset >= DAX_MMAP_LEN) { dax_dbg("invalid ca_offset (%d) >= ca_buflen (%d)", hdr.ca_offset, DAX_MMAP_LEN); return -EINVAL; } ret = dax_ccb_kill(ca, &ctx->result.kill.action); if (ret != 0) { dax_dbg("dax_ccb_kill failed (ret=%d)", ret); return ret; } dax_info_dbg("killed (ca_offset %d)", hdr.ca_offset); idx = hdr.ca_offset / sizeof(struct dax_cca); ctx->ca_buf[idx].status = CCA_STAT_KILLED; ctx->ca_buf[idx].err = CCA_ERR_KILLED; ctx->client = current; return count; case CCB_INFO: if (hdr.ca_offset >= DAX_MMAP_LEN) { dax_dbg("invalid ca_offset (%d) >= ca_buflen (%d)", hdr.ca_offset, DAX_MMAP_LEN); return -EINVAL; } ret = dax_ccb_info(ca, &ctx->result.info); if (ret != 0) { dax_dbg("dax_ccb_info failed (ret=%d)", ret); return ret; } dax_info_dbg("info succeeded on ca_offset %d", hdr.ca_offset); ctx->client = current; return count; case CCB_DEQUEUE: for (i = 0; i < DAX_CA_ELEMS; i++) { if (ctx->ca_buf[i].status != CCA_STAT_NOT_COMPLETED) dax_unlock_pages(ctx, i, 1); } return count; default: return -EINVAL; } } static int dax_open(struct inode *inode, struct file *f) { struct dax_ctx *ctx = NULL; int i; ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); if (ctx == NULL) goto done; ctx->ccb_buf = kcalloc(DAX_MAX_CCBS, sizeof(struct dax_ccb), GFP_KERNEL); if (ctx->ccb_buf == NULL) goto done; ctx->ccb_buf_ra = virt_to_phys(ctx->ccb_buf); dax_dbg("ctx->ccb_buf=0x%p, ccb_buf_ra=0x%llx", (void *)ctx->ccb_buf, ctx->ccb_buf_ra); /* allocate CCB completion area buffer */ ctx->ca_buf = kzalloc(DAX_MMAP_LEN, GFP_KERNEL); if (ctx->ca_buf == NULL) goto alloc_error; for (i = 0; i < DAX_CA_ELEMS; i++) ctx->ca_buf[i].status = CCA_STAT_COMPLETED; ctx->ca_buf_ra = virt_to_phys(ctx->ca_buf); dax_dbg("ctx=0x%p, ctx->ca_buf=0x%p, ca_buf_ra=0x%llx", (void *)ctx, (void *)ctx->ca_buf, ctx->ca_buf_ra); ctx->owner = current; f->private_data = ctx; return 0; alloc_error: kfree(ctx->ccb_buf); done: kfree(ctx); return -ENOMEM; } static char *dax_hv_errno(unsigned long hv_ret, int *ret) { switch (hv_ret) { case HV_EBADALIGN: *ret = -EFAULT; return "HV_EBADALIGN"; case HV_ENORADDR: *ret = -EFAULT; return "HV_ENORADDR"; case HV_EINVAL: *ret = -EINVAL; return "HV_EINVAL"; case HV_EWOULDBLOCK: *ret = -EAGAIN; return "HV_EWOULDBLOCK"; case HV_ENOACCESS: *ret = -EPERM; return "HV_ENOACCESS"; default: break; } *ret = -EIO; return "UNKNOWN"; } static int dax_ccb_kill(u64 ca, u16 *kill_res) { unsigned long hv_ret; int count, ret = 0; char *err_str; for (count = 0; count < DAX_CCB_RETRIES; count++) { dax_dbg("attempting kill on ca_ra 0x%llx", ca); hv_ret = sun4v_ccb_kill(ca, kill_res); if (hv_ret == HV_EOK) { dax_info_dbg("HV_EOK (ca_ra 0x%llx): %d", ca, *kill_res); } else { err_str = dax_hv_errno(hv_ret, &ret); dax_dbg("%s (ca_ra 0x%llx)", err_str, ca); } if (ret != -EAGAIN) return ret; dax_info_dbg("ccb_kill count = %d", count); udelay(DAX_CCB_USEC); } return -EAGAIN; } static int dax_ccb_info(u64 ca, struct ccb_info_result *info) { unsigned long hv_ret; char *err_str; int ret = 0; dax_dbg("attempting info on ca_ra 0x%llx", ca); hv_ret = sun4v_ccb_info(ca, info); if (hv_ret == HV_EOK) { dax_info_dbg("HV_EOK (ca_ra 0x%llx): %d", ca, info->state); if (info->state == DAX_CCB_ENQUEUED) { dax_info_dbg("dax_unit %d, queue_num %d, queue_pos %d", info->inst_num, info->q_num, info->q_pos); } } else { err_str = dax_hv_errno(hv_ret, &ret); dax_dbg("%s (ca_ra 0x%llx)", err_str, ca); } return ret; } static void dax_prt_ccbs(struct dax_ccb *ccb, int nelem) { int i, j; u64 *ccbp; dax_dbg("ccb buffer:"); for (i = 0; i < nelem; i++) { ccbp = (u64 *)&ccb[i]; dax_dbg(" %sccb[%d]", ccb[i].hdr.longccb ? "long " : "", i); for (j = 0; j < 8; j++) dax_dbg("\tccb[%d].dwords[%d]=0x%llx", i, j, *(ccbp + j)); } } /* * Validates user CCB content. Also sets completion address and address types * for all addresses contained in CCB. */ static int dax_preprocess_usr_ccbs(struct dax_ctx *ctx, int idx, int nelem) { int i; /* * The user is not allowed to specify real address types in * the CCB header. This must be enforced by the kernel before * submitting the CCBs to HV. The only allowed values for all * address fields are VA or IMM */ for (i = 0; i < nelem; i++) { struct dax_ccb *ccbp = &ctx->ccb_buf[i]; unsigned long ca_offset; if (ccbp->hdr.ccb_version > max_ccb_version) return DAX_SUBMIT_ERR_CCB_INVAL; switch (ccbp->hdr.opcode) { case DAX_OP_SYNC_NOP: case DAX_OP_EXTRACT: case DAX_OP_SCAN_VALUE: case DAX_OP_SCAN_RANGE: case DAX_OP_TRANSLATE: case DAX_OP_SCAN_VALUE | DAX_OP_INVERT: case DAX_OP_SCAN_RANGE | DAX_OP_INVERT: case DAX_OP_TRANSLATE | DAX_OP_INVERT: case DAX_OP_SELECT: break; default: return DAX_SUBMIT_ERR_CCB_INVAL; } if (ccbp->hdr.out_addr_type != DAX_ADDR_TYPE_VA && ccbp->hdr.out_addr_type != DAX_ADDR_TYPE_NONE) { dax_dbg("invalid out_addr_type in user CCB[%d]", i); return DAX_SUBMIT_ERR_CCB_INVAL; } if (ccbp->hdr.pri_addr_type != DAX_ADDR_TYPE_VA && ccbp->hdr.pri_addr_type != DAX_ADDR_TYPE_NONE) { dax_dbg("invalid pri_addr_type in user CCB[%d]", i); return DAX_SUBMIT_ERR_CCB_INVAL; } if (ccbp->hdr.sec_addr_type != DAX_ADDR_TYPE_VA && ccbp->hdr.sec_addr_type != DAX_ADDR_TYPE_NONE) { dax_dbg("invalid sec_addr_type in user CCB[%d]", i); return DAX_SUBMIT_ERR_CCB_INVAL; } if (ccbp->hdr.table_addr_type != DAX_ADDR_TYPE_VA && ccbp->hdr.table_addr_type != DAX_ADDR_TYPE_NONE) { dax_dbg("invalid table_addr_type in user CCB[%d]", i); return DAX_SUBMIT_ERR_CCB_INVAL; } /* set completion (real) address and address type */ ccbp->hdr.cca_addr_type = DAX_ADDR_TYPE_RA; ca_offset = (idx + i) * sizeof(struct dax_cca); ccbp->ca = (void *)ctx->ca_buf_ra + ca_offset; memset(&ctx->ca_buf[idx + i], 0, sizeof(struct dax_cca)); dax_dbg("ccb[%d]=%p, ca_offset=0x%lx, compl RA=0x%llx", i, ccbp, ca_offset, ctx->ca_buf_ra + ca_offset); /* skip over 2nd 64 bytes of long CCB */ if (ccbp->hdr.longccb) i++; } return DAX_SUBMIT_OK; } static int dax_ccb_exec(struct dax_ctx *ctx, const char __user *buf, size_t count, loff_t *ppos) { unsigned long accepted_len, hv_rv; int i, idx, nccbs, naccepted; ctx->client = current; idx = *ppos; nccbs = count / sizeof(struct dax_ccb); if (ctx->owner != current) { dax_dbg("wrong thread"); ctx->result.exec.status = DAX_SUBMIT_ERR_THR_INIT; return 0; } dax_dbg("args: ccb_buf_len=%ld, idx=%d", count, idx); /* for given index and length, verify ca_buf range exists */ if (idx < 0 || idx > (DAX_CA_ELEMS - nccbs)) { ctx->result.exec.status = DAX_SUBMIT_ERR_NO_CA_AVAIL; return 0; } /* * Copy CCBs into kernel buffer to prevent modification by the * user in between validation and submission. */ if (copy_from_user(ctx->ccb_buf, buf, count)) { dax_dbg("copyin of user CCB buffer failed"); ctx->result.exec.status = DAX_SUBMIT_ERR_CCB_ARR_MMU_MISS; return 0; } /* check to see if ca_buf[idx] .. ca_buf[idx + nccbs] are available */ for (i = idx; i < idx + nccbs; i++) { if (ctx->ca_buf[i].status == CCA_STAT_NOT_COMPLETED) { dax_dbg("CA range not available, dequeue needed"); ctx->result.exec.status = DAX_SUBMIT_ERR_NO_CA_AVAIL; return 0; } } dax_unlock_pages(ctx, idx, nccbs); ctx->result.exec.status = dax_preprocess_usr_ccbs(ctx, idx, nccbs); if (ctx->result.exec.status != DAX_SUBMIT_OK) return 0; ctx->result.exec.status = dax_lock_pages(ctx, idx, nccbs, &ctx->result.exec.status_data); if (ctx->result.exec.status != DAX_SUBMIT_OK) return 0; if (dax_debug & DAX_DBG_FLG_BASIC) dax_prt_ccbs(ctx->ccb_buf, nccbs); hv_rv = sun4v_ccb_submit(ctx->ccb_buf_ra, count, HV_CCB_QUERY_CMD | HV_CCB_VA_SECONDARY, 0, &accepted_len, &ctx->result.exec.status_data); switch (hv_rv) { case HV_EOK: /* * Hcall succeeded with no errors but the accepted * length may be less than the requested length. The * only way the driver can resubmit the remainder is * to wait for completion of the submitted CCBs since * there is no way to guarantee the ordering semantics * required by the client applications. Therefore we * let the user library deal with resubmissions. */ ctx->result.exec.status = DAX_SUBMIT_OK; break; case HV_EWOULDBLOCK: /* * This is a transient HV API error. The user library * can retry. */ dax_dbg("hcall returned HV_EWOULDBLOCK"); ctx->result.exec.status = DAX_SUBMIT_ERR_WOULDBLOCK; break; case HV_ENOMAP: /* * HV was unable to translate a VA. The VA it could * not translate is returned in the status_data param. */ dax_dbg("hcall returned HV_ENOMAP"); ctx->result.exec.status = DAX_SUBMIT_ERR_NOMAP; break; case HV_EINVAL: /* * This is the result of an invalid user CCB as HV is * validating some of the user CCB fields. Pass this * error back to the user. There is no supporting info * to isolate the invalid field. */ dax_dbg("hcall returned HV_EINVAL"); ctx->result.exec.status = DAX_SUBMIT_ERR_CCB_INVAL; break; case HV_ENOACCESS: /* * HV found a VA that did not have the appropriate * permissions (such as the w bit). The VA in question * is returned in status_data param. */ dax_dbg("hcall returned HV_ENOACCESS"); ctx->result.exec.status = DAX_SUBMIT_ERR_NOACCESS; break; case HV_EUNAVAILABLE: /* * The requested CCB operation could not be performed * at this time. Return the specific unavailable code * in the status_data field. */ dax_dbg("hcall returned HV_EUNAVAILABLE"); ctx->result.exec.status = DAX_SUBMIT_ERR_UNAVAIL; break; default: ctx->result.exec.status = DAX_SUBMIT_ERR_INTERNAL; dax_dbg("unknown hcall return value (%ld)", hv_rv); break; } /* unlock pages associated with the unaccepted CCBs */ naccepted = accepted_len / sizeof(struct dax_ccb); dax_unlock_pages(ctx, idx + naccepted, nccbs - naccepted); /* mark unaccepted CCBs as not completed */ for (i = idx + naccepted; i < idx + nccbs; i++) ctx->ca_buf[i].status = CCA_STAT_COMPLETED; ctx->ccb_count += naccepted; ctx->fail_count += nccbs - naccepted; dax_dbg("hcall rv=%ld, accepted_len=%ld, status_data=0x%llx, ret status=%d", hv_rv, accepted_len, ctx->result.exec.status_data, ctx->result.exec.status); if (count == accepted_len) ctx->client = NULL; /* no read needed to complete protocol */ return accepted_len; }
linux-master
drivers/sbus/char/oradax.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2015, 2017, 2022 Linaro Limited */ #include <linux/device.h> #include <linux/dma-buf.h> #include <linux/genalloc.h> #include <linux/slab.h> #include <linux/tee_drv.h> #include "tee_private.h" static int pool_op_gen_alloc(struct tee_shm_pool *pool, struct tee_shm *shm, size_t size, size_t align) { unsigned long va; struct gen_pool *genpool = pool->private_data; size_t a = max_t(size_t, align, BIT(genpool->min_alloc_order)); struct genpool_data_align data = { .align = a }; size_t s = roundup(size, a); va = gen_pool_alloc_algo(genpool, s, gen_pool_first_fit_align, &data); if (!va) return -ENOMEM; memset((void *)va, 0, s); shm->kaddr = (void *)va; shm->paddr = gen_pool_virt_to_phys(genpool, va); shm->size = s; /* * This is from a static shared memory pool so no need to register * each chunk, and no need to unregister later either. */ shm->flags &= ~TEE_SHM_DYNAMIC; return 0; } static void pool_op_gen_free(struct tee_shm_pool *pool, struct tee_shm *shm) { gen_pool_free(pool->private_data, (unsigned long)shm->kaddr, shm->size); shm->kaddr = NULL; } static void pool_op_gen_destroy_pool(struct tee_shm_pool *pool) { gen_pool_destroy(pool->private_data); kfree(pool); } static const struct tee_shm_pool_ops pool_ops_generic = { .alloc = pool_op_gen_alloc, .free = pool_op_gen_free, .destroy_pool = pool_op_gen_destroy_pool, }; struct tee_shm_pool *tee_shm_pool_alloc_res_mem(unsigned long vaddr, phys_addr_t paddr, size_t size, int min_alloc_order) { const size_t page_mask = PAGE_SIZE - 1; struct tee_shm_pool *pool; int rc; /* Start and end must be page aligned */ if (vaddr & page_mask || paddr & page_mask || size & page_mask) return ERR_PTR(-EINVAL); pool = kzalloc(sizeof(*pool), GFP_KERNEL); if (!pool) return ERR_PTR(-ENOMEM); pool->private_data = gen_pool_create(min_alloc_order, -1); if (!pool->private_data) { rc = -ENOMEM; goto err; } rc = gen_pool_add_virt(pool->private_data, vaddr, paddr, size, -1); if (rc) { gen_pool_destroy(pool->private_data); goto err; } pool->ops = &pool_ops_generic; return pool; err: kfree(pool); return ERR_PTR(rc); } EXPORT_SYMBOL_GPL(tee_shm_pool_alloc_res_mem);
linux-master
drivers/tee/tee_shm_pool.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2015-2016, Linaro Limited */ #define pr_fmt(fmt) "%s: " fmt, __func__ #include <linux/cdev.h> #include <linux/cred.h> #include <linux/fs.h> #include <linux/idr.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/tee_drv.h> #include <linux/uaccess.h> #include <crypto/hash.h> #include <crypto/sha1.h> #include "tee_private.h" #define TEE_NUM_DEVICES 32 #define TEE_IOCTL_PARAM_SIZE(x) (sizeof(struct tee_param) * (x)) #define TEE_UUID_NS_NAME_SIZE 128 /* * TEE Client UUID name space identifier (UUIDv4) * * Value here is random UUID that is allocated as name space identifier for * forming Client UUID's for TEE environment using UUIDv5 scheme. */ static const uuid_t tee_client_uuid_ns = UUID_INIT(0x58ac9ca0, 0x2086, 0x4683, 0xa1, 0xb8, 0xec, 0x4b, 0xc0, 0x8e, 0x01, 0xb6); /* * Unprivileged devices in the lower half range and privileged devices in * the upper half range. */ static DECLARE_BITMAP(dev_mask, TEE_NUM_DEVICES); static DEFINE_SPINLOCK(driver_lock); static struct class *tee_class; static dev_t tee_devt; struct tee_context *teedev_open(struct tee_device *teedev) { int rc; struct tee_context *ctx; if (!tee_device_get(teedev)) return ERR_PTR(-EINVAL); ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); if (!ctx) { rc = -ENOMEM; goto err; } kref_init(&ctx->refcount); ctx->teedev = teedev; rc = teedev->desc->ops->open(ctx); if (rc) goto err; return ctx; err: kfree(ctx); tee_device_put(teedev); return ERR_PTR(rc); } EXPORT_SYMBOL_GPL(teedev_open); void teedev_ctx_get(struct tee_context *ctx) { if (ctx->releasing) return; kref_get(&ctx->refcount); } static void teedev_ctx_release(struct kref *ref) { struct tee_context *ctx = container_of(ref, struct tee_context, refcount); ctx->releasing = true; ctx->teedev->desc->ops->release(ctx); kfree(ctx); } void teedev_ctx_put(struct tee_context *ctx) { if (ctx->releasing) return; kref_put(&ctx->refcount, teedev_ctx_release); } void teedev_close_context(struct tee_context *ctx) { struct tee_device *teedev = ctx->teedev; teedev_ctx_put(ctx); tee_device_put(teedev); } EXPORT_SYMBOL_GPL(teedev_close_context); static int tee_open(struct inode *inode, struct file *filp) { struct tee_context *ctx; ctx = teedev_open(container_of(inode->i_cdev, struct tee_device, cdev)); if (IS_ERR(ctx)) return PTR_ERR(ctx); /* * Default user-space behaviour is to wait for tee-supplicant * if not present for any requests in this context. */ ctx->supp_nowait = false; filp->private_data = ctx; return 0; } static int tee_release(struct inode *inode, struct file *filp) { teedev_close_context(filp->private_data); return 0; } /** * uuid_v5() - Calculate UUIDv5 * @uuid: Resulting UUID * @ns: Name space ID for UUIDv5 function * @name: Name for UUIDv5 function * @size: Size of name * * UUIDv5 is specific in RFC 4122. * * This implements section (for SHA-1): * 4.3. Algorithm for Creating a Name-Based UUID */ static int uuid_v5(uuid_t *uuid, const uuid_t *ns, const void *name, size_t size) { unsigned char hash[SHA1_DIGEST_SIZE]; struct crypto_shash *shash = NULL; struct shash_desc *desc = NULL; int rc; shash = crypto_alloc_shash("sha1", 0, 0); if (IS_ERR(shash)) { rc = PTR_ERR(shash); pr_err("shash(sha1) allocation failed\n"); return rc; } desc = kzalloc(sizeof(*desc) + crypto_shash_descsize(shash), GFP_KERNEL); if (!desc) { rc = -ENOMEM; goto out_free_shash; } desc->tfm = shash; rc = crypto_shash_init(desc); if (rc < 0) goto out_free_desc; rc = crypto_shash_update(desc, (const u8 *)ns, sizeof(*ns)); if (rc < 0) goto out_free_desc; rc = crypto_shash_update(desc, (const u8 *)name, size); if (rc < 0) goto out_free_desc; rc = crypto_shash_final(desc, hash); if (rc < 0) goto out_free_desc; memcpy(uuid->b, hash, UUID_SIZE); /* Tag for version 5 */ uuid->b[6] = (hash[6] & 0x0F) | 0x50; uuid->b[8] = (hash[8] & 0x3F) | 0x80; out_free_desc: kfree(desc); out_free_shash: crypto_free_shash(shash); return rc; } int tee_session_calc_client_uuid(uuid_t *uuid, u32 connection_method, const u8 connection_data[TEE_IOCTL_UUID_LEN]) { gid_t ns_grp = (gid_t)-1; kgid_t grp = INVALID_GID; char *name = NULL; int name_len; int rc; if (connection_method == TEE_IOCTL_LOGIN_PUBLIC || connection_method == TEE_IOCTL_LOGIN_REE_KERNEL) { /* Nil UUID to be passed to TEE environment */ uuid_copy(uuid, &uuid_null); return 0; } /* * In Linux environment client UUID is based on UUIDv5. * * Determine client UUID with following semantics for 'name': * * For TEEC_LOGIN_USER: * uid=<uid> * * For TEEC_LOGIN_GROUP: * gid=<gid> * */ name = kzalloc(TEE_UUID_NS_NAME_SIZE, GFP_KERNEL); if (!name) return -ENOMEM; switch (connection_method) { case TEE_IOCTL_LOGIN_USER: name_len = snprintf(name, TEE_UUID_NS_NAME_SIZE, "uid=%x", current_euid().val); if (name_len >= TEE_UUID_NS_NAME_SIZE) { rc = -E2BIG; goto out_free_name; } break; case TEE_IOCTL_LOGIN_GROUP: memcpy(&ns_grp, connection_data, sizeof(gid_t)); grp = make_kgid(current_user_ns(), ns_grp); if (!gid_valid(grp) || !in_egroup_p(grp)) { rc = -EPERM; goto out_free_name; } name_len = snprintf(name, TEE_UUID_NS_NAME_SIZE, "gid=%x", grp.val); if (name_len >= TEE_UUID_NS_NAME_SIZE) { rc = -E2BIG; goto out_free_name; } break; default: rc = -EINVAL; goto out_free_name; } rc = uuid_v5(uuid, &tee_client_uuid_ns, name, name_len); out_free_name: kfree(name); return rc; } EXPORT_SYMBOL_GPL(tee_session_calc_client_uuid); static int tee_ioctl_version(struct tee_context *ctx, struct tee_ioctl_version_data __user *uvers) { struct tee_ioctl_version_data vers; ctx->teedev->desc->ops->get_version(ctx->teedev, &vers); if (ctx->teedev->desc->flags & TEE_DESC_PRIVILEGED) vers.gen_caps |= TEE_GEN_CAP_PRIVILEGED; if (copy_to_user(uvers, &vers, sizeof(vers))) return -EFAULT; return 0; } static int tee_ioctl_shm_alloc(struct tee_context *ctx, struct tee_ioctl_shm_alloc_data __user *udata) { long ret; struct tee_ioctl_shm_alloc_data data; struct tee_shm *shm; if (copy_from_user(&data, udata, sizeof(data))) return -EFAULT; /* Currently no input flags are supported */ if (data.flags) return -EINVAL; shm = tee_shm_alloc_user_buf(ctx, data.size); if (IS_ERR(shm)) return PTR_ERR(shm); data.id = shm->id; data.size = shm->size; if (copy_to_user(udata, &data, sizeof(data))) ret = -EFAULT; else ret = tee_shm_get_fd(shm); /* * When user space closes the file descriptor the shared memory * should be freed or if tee_shm_get_fd() failed then it will * be freed immediately. */ tee_shm_put(shm); return ret; } static int tee_ioctl_shm_register(struct tee_context *ctx, struct tee_ioctl_shm_register_data __user *udata) { long ret; struct tee_ioctl_shm_register_data data; struct tee_shm *shm; if (copy_from_user(&data, udata, sizeof(data))) return -EFAULT; /* Currently no input flags are supported */ if (data.flags) return -EINVAL; shm = tee_shm_register_user_buf(ctx, data.addr, data.length); if (IS_ERR(shm)) return PTR_ERR(shm); data.id = shm->id; data.length = shm->size; if (copy_to_user(udata, &data, sizeof(data))) ret = -EFAULT; else ret = tee_shm_get_fd(shm); /* * When user space closes the file descriptor the shared memory * should be freed or if tee_shm_get_fd() failed then it will * be freed immediately. */ tee_shm_put(shm); return ret; } static int params_from_user(struct tee_context *ctx, struct tee_param *params, size_t num_params, struct tee_ioctl_param __user *uparams) { size_t n; for (n = 0; n < num_params; n++) { struct tee_shm *shm; struct tee_ioctl_param ip; if (copy_from_user(&ip, uparams + n, sizeof(ip))) return -EFAULT; /* All unused attribute bits has to be zero */ if (ip.attr & ~TEE_IOCTL_PARAM_ATTR_MASK) return -EINVAL; params[n].attr = ip.attr; switch (ip.attr & TEE_IOCTL_PARAM_ATTR_TYPE_MASK) { case TEE_IOCTL_PARAM_ATTR_TYPE_NONE: case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_OUTPUT: break; case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INOUT: params[n].u.value.a = ip.a; params[n].u.value.b = ip.b; params[n].u.value.c = ip.c; break; case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_OUTPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INOUT: /* * If a NULL pointer is passed to a TA in the TEE, * the ip.c IOCTL parameters is set to TEE_MEMREF_NULL * indicating a NULL memory reference. */ if (ip.c != TEE_MEMREF_NULL) { /* * If we fail to get a pointer to a shared * memory object (and increase the ref count) * from an identifier we return an error. All * pointers that has been added in params have * an increased ref count. It's the callers * responibility to do tee_shm_put() on all * resolved pointers. */ shm = tee_shm_get_from_id(ctx, ip.c); if (IS_ERR(shm)) return PTR_ERR(shm); /* * Ensure offset + size does not overflow * offset and does not overflow the size of * the referred shared memory object. */ if ((ip.a + ip.b) < ip.a || (ip.a + ip.b) > shm->size) { tee_shm_put(shm); return -EINVAL; } } else if (ctx->cap_memref_null) { /* Pass NULL pointer to OP-TEE */ shm = NULL; } else { return -EINVAL; } params[n].u.memref.shm_offs = ip.a; params[n].u.memref.size = ip.b; params[n].u.memref.shm = shm; break; default: /* Unknown attribute */ return -EINVAL; } } return 0; } static int params_to_user(struct tee_ioctl_param __user *uparams, size_t num_params, struct tee_param *params) { size_t n; for (n = 0; n < num_params; n++) { struct tee_ioctl_param __user *up = uparams + n; struct tee_param *p = params + n; switch (p->attr) { case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_OUTPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INOUT: if (put_user(p->u.value.a, &up->a) || put_user(p->u.value.b, &up->b) || put_user(p->u.value.c, &up->c)) return -EFAULT; break; case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_OUTPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INOUT: if (put_user((u64)p->u.memref.size, &up->b)) return -EFAULT; break; default: break; } } return 0; } static int tee_ioctl_open_session(struct tee_context *ctx, struct tee_ioctl_buf_data __user *ubuf) { int rc; size_t n; struct tee_ioctl_buf_data buf; struct tee_ioctl_open_session_arg __user *uarg; struct tee_ioctl_open_session_arg arg; struct tee_ioctl_param __user *uparams = NULL; struct tee_param *params = NULL; bool have_session = false; if (!ctx->teedev->desc->ops->open_session) return -EINVAL; if (copy_from_user(&buf, ubuf, sizeof(buf))) return -EFAULT; if (buf.buf_len > TEE_MAX_ARG_SIZE || buf.buf_len < sizeof(struct tee_ioctl_open_session_arg)) return -EINVAL; uarg = u64_to_user_ptr(buf.buf_ptr); if (copy_from_user(&arg, uarg, sizeof(arg))) return -EFAULT; if (sizeof(arg) + TEE_IOCTL_PARAM_SIZE(arg.num_params) != buf.buf_len) return -EINVAL; if (arg.num_params) { params = kcalloc(arg.num_params, sizeof(struct tee_param), GFP_KERNEL); if (!params) return -ENOMEM; uparams = uarg->params; rc = params_from_user(ctx, params, arg.num_params, uparams); if (rc) goto out; } if (arg.clnt_login >= TEE_IOCTL_LOGIN_REE_KERNEL_MIN && arg.clnt_login <= TEE_IOCTL_LOGIN_REE_KERNEL_MAX) { pr_debug("login method not allowed for user-space client\n"); rc = -EPERM; goto out; } rc = ctx->teedev->desc->ops->open_session(ctx, &arg, params); if (rc) goto out; have_session = true; if (put_user(arg.session, &uarg->session) || put_user(arg.ret, &uarg->ret) || put_user(arg.ret_origin, &uarg->ret_origin)) { rc = -EFAULT; goto out; } rc = params_to_user(uparams, arg.num_params, params); out: /* * If we've succeeded to open the session but failed to communicate * it back to user space, close the session again to avoid leakage. */ if (rc && have_session && ctx->teedev->desc->ops->close_session) ctx->teedev->desc->ops->close_session(ctx, arg.session); if (params) { /* Decrease ref count for all valid shared memory pointers */ for (n = 0; n < arg.num_params; n++) if (tee_param_is_memref(params + n) && params[n].u.memref.shm) tee_shm_put(params[n].u.memref.shm); kfree(params); } return rc; } static int tee_ioctl_invoke(struct tee_context *ctx, struct tee_ioctl_buf_data __user *ubuf) { int rc; size_t n; struct tee_ioctl_buf_data buf; struct tee_ioctl_invoke_arg __user *uarg; struct tee_ioctl_invoke_arg arg; struct tee_ioctl_param __user *uparams = NULL; struct tee_param *params = NULL; if (!ctx->teedev->desc->ops->invoke_func) return -EINVAL; if (copy_from_user(&buf, ubuf, sizeof(buf))) return -EFAULT; if (buf.buf_len > TEE_MAX_ARG_SIZE || buf.buf_len < sizeof(struct tee_ioctl_invoke_arg)) return -EINVAL; uarg = u64_to_user_ptr(buf.buf_ptr); if (copy_from_user(&arg, uarg, sizeof(arg))) return -EFAULT; if (sizeof(arg) + TEE_IOCTL_PARAM_SIZE(arg.num_params) != buf.buf_len) return -EINVAL; if (arg.num_params) { params = kcalloc(arg.num_params, sizeof(struct tee_param), GFP_KERNEL); if (!params) return -ENOMEM; uparams = uarg->params; rc = params_from_user(ctx, params, arg.num_params, uparams); if (rc) goto out; } rc = ctx->teedev->desc->ops->invoke_func(ctx, &arg, params); if (rc) goto out; if (put_user(arg.ret, &uarg->ret) || put_user(arg.ret_origin, &uarg->ret_origin)) { rc = -EFAULT; goto out; } rc = params_to_user(uparams, arg.num_params, params); out: if (params) { /* Decrease ref count for all valid shared memory pointers */ for (n = 0; n < arg.num_params; n++) if (tee_param_is_memref(params + n) && params[n].u.memref.shm) tee_shm_put(params[n].u.memref.shm); kfree(params); } return rc; } static int tee_ioctl_cancel(struct tee_context *ctx, struct tee_ioctl_cancel_arg __user *uarg) { struct tee_ioctl_cancel_arg arg; if (!ctx->teedev->desc->ops->cancel_req) return -EINVAL; if (copy_from_user(&arg, uarg, sizeof(arg))) return -EFAULT; return ctx->teedev->desc->ops->cancel_req(ctx, arg.cancel_id, arg.session); } static int tee_ioctl_close_session(struct tee_context *ctx, struct tee_ioctl_close_session_arg __user *uarg) { struct tee_ioctl_close_session_arg arg; if (!ctx->teedev->desc->ops->close_session) return -EINVAL; if (copy_from_user(&arg, uarg, sizeof(arg))) return -EFAULT; return ctx->teedev->desc->ops->close_session(ctx, arg.session); } static int params_to_supp(struct tee_context *ctx, struct tee_ioctl_param __user *uparams, size_t num_params, struct tee_param *params) { size_t n; for (n = 0; n < num_params; n++) { struct tee_ioctl_param ip; struct tee_param *p = params + n; ip.attr = p->attr; switch (p->attr & TEE_IOCTL_PARAM_ATTR_TYPE_MASK) { case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INOUT: ip.a = p->u.value.a; ip.b = p->u.value.b; ip.c = p->u.value.c; break; case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_OUTPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INOUT: ip.b = p->u.memref.size; if (!p->u.memref.shm) { ip.a = 0; ip.c = (u64)-1; /* invalid shm id */ break; } ip.a = p->u.memref.shm_offs; ip.c = p->u.memref.shm->id; break; default: ip.a = 0; ip.b = 0; ip.c = 0; break; } if (copy_to_user(uparams + n, &ip, sizeof(ip))) return -EFAULT; } return 0; } static int tee_ioctl_supp_recv(struct tee_context *ctx, struct tee_ioctl_buf_data __user *ubuf) { int rc; struct tee_ioctl_buf_data buf; struct tee_iocl_supp_recv_arg __user *uarg; struct tee_param *params; u32 num_params; u32 func; if (!ctx->teedev->desc->ops->supp_recv) return -EINVAL; if (copy_from_user(&buf, ubuf, sizeof(buf))) return -EFAULT; if (buf.buf_len > TEE_MAX_ARG_SIZE || buf.buf_len < sizeof(struct tee_iocl_supp_recv_arg)) return -EINVAL; uarg = u64_to_user_ptr(buf.buf_ptr); if (get_user(num_params, &uarg->num_params)) return -EFAULT; if (sizeof(*uarg) + TEE_IOCTL_PARAM_SIZE(num_params) != buf.buf_len) return -EINVAL; params = kcalloc(num_params, sizeof(struct tee_param), GFP_KERNEL); if (!params) return -ENOMEM; rc = params_from_user(ctx, params, num_params, uarg->params); if (rc) goto out; rc = ctx->teedev->desc->ops->supp_recv(ctx, &func, &num_params, params); if (rc) goto out; if (put_user(func, &uarg->func) || put_user(num_params, &uarg->num_params)) { rc = -EFAULT; goto out; } rc = params_to_supp(ctx, uarg->params, num_params, params); out: kfree(params); return rc; } static int params_from_supp(struct tee_param *params, size_t num_params, struct tee_ioctl_param __user *uparams) { size_t n; for (n = 0; n < num_params; n++) { struct tee_param *p = params + n; struct tee_ioctl_param ip; if (copy_from_user(&ip, uparams + n, sizeof(ip))) return -EFAULT; /* All unused attribute bits has to be zero */ if (ip.attr & ~TEE_IOCTL_PARAM_ATTR_MASK) return -EINVAL; p->attr = ip.attr; switch (ip.attr & TEE_IOCTL_PARAM_ATTR_TYPE_MASK) { case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_OUTPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INOUT: /* Only out and in/out values can be updated */ p->u.value.a = ip.a; p->u.value.b = ip.b; p->u.value.c = ip.c; break; case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_OUTPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INOUT: /* * Only the size of the memref can be updated. * Since we don't have access to the original * parameters here, only store the supplied size. * The driver will copy the updated size into the * original parameters. */ p->u.memref.shm = NULL; p->u.memref.shm_offs = 0; p->u.memref.size = ip.b; break; default: memset(&p->u, 0, sizeof(p->u)); break; } } return 0; } static int tee_ioctl_supp_send(struct tee_context *ctx, struct tee_ioctl_buf_data __user *ubuf) { long rc; struct tee_ioctl_buf_data buf; struct tee_iocl_supp_send_arg __user *uarg; struct tee_param *params; u32 num_params; u32 ret; /* Not valid for this driver */ if (!ctx->teedev->desc->ops->supp_send) return -EINVAL; if (copy_from_user(&buf, ubuf, sizeof(buf))) return -EFAULT; if (buf.buf_len > TEE_MAX_ARG_SIZE || buf.buf_len < sizeof(struct tee_iocl_supp_send_arg)) return -EINVAL; uarg = u64_to_user_ptr(buf.buf_ptr); if (get_user(ret, &uarg->ret) || get_user(num_params, &uarg->num_params)) return -EFAULT; if (sizeof(*uarg) + TEE_IOCTL_PARAM_SIZE(num_params) > buf.buf_len) return -EINVAL; params = kcalloc(num_params, sizeof(struct tee_param), GFP_KERNEL); if (!params) return -ENOMEM; rc = params_from_supp(params, num_params, uarg->params); if (rc) goto out; rc = ctx->teedev->desc->ops->supp_send(ctx, ret, num_params, params); out: kfree(params); return rc; } static long tee_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct tee_context *ctx = filp->private_data; void __user *uarg = (void __user *)arg; switch (cmd) { case TEE_IOC_VERSION: return tee_ioctl_version(ctx, uarg); case TEE_IOC_SHM_ALLOC: return tee_ioctl_shm_alloc(ctx, uarg); case TEE_IOC_SHM_REGISTER: return tee_ioctl_shm_register(ctx, uarg); case TEE_IOC_OPEN_SESSION: return tee_ioctl_open_session(ctx, uarg); case TEE_IOC_INVOKE: return tee_ioctl_invoke(ctx, uarg); case TEE_IOC_CANCEL: return tee_ioctl_cancel(ctx, uarg); case TEE_IOC_CLOSE_SESSION: return tee_ioctl_close_session(ctx, uarg); case TEE_IOC_SUPPL_RECV: return tee_ioctl_supp_recv(ctx, uarg); case TEE_IOC_SUPPL_SEND: return tee_ioctl_supp_send(ctx, uarg); default: return -EINVAL; } } static const struct file_operations tee_fops = { .owner = THIS_MODULE, .open = tee_open, .release = tee_release, .unlocked_ioctl = tee_ioctl, .compat_ioctl = compat_ptr_ioctl, }; static void tee_release_device(struct device *dev) { struct tee_device *teedev = container_of(dev, struct tee_device, dev); spin_lock(&driver_lock); clear_bit(teedev->id, dev_mask); spin_unlock(&driver_lock); mutex_destroy(&teedev->mutex); idr_destroy(&teedev->idr); kfree(teedev); } /** * tee_device_alloc() - Allocate a new struct tee_device instance * @teedesc: Descriptor for this driver * @dev: Parent device for this device * @pool: Shared memory pool, NULL if not used * @driver_data: Private driver data for this device * * Allocates a new struct tee_device instance. The device is * removed by tee_device_unregister(). * * @returns a pointer to a 'struct tee_device' or an ERR_PTR on failure */ struct tee_device *tee_device_alloc(const struct tee_desc *teedesc, struct device *dev, struct tee_shm_pool *pool, void *driver_data) { struct tee_device *teedev; void *ret; int rc, max_id; int offs = 0; if (!teedesc || !teedesc->name || !teedesc->ops || !teedesc->ops->get_version || !teedesc->ops->open || !teedesc->ops->release || !pool) return ERR_PTR(-EINVAL); teedev = kzalloc(sizeof(*teedev), GFP_KERNEL); if (!teedev) { ret = ERR_PTR(-ENOMEM); goto err; } max_id = TEE_NUM_DEVICES / 2; if (teedesc->flags & TEE_DESC_PRIVILEGED) { offs = TEE_NUM_DEVICES / 2; max_id = TEE_NUM_DEVICES; } spin_lock(&driver_lock); teedev->id = find_next_zero_bit(dev_mask, max_id, offs); if (teedev->id < max_id) set_bit(teedev->id, dev_mask); spin_unlock(&driver_lock); if (teedev->id >= max_id) { ret = ERR_PTR(-ENOMEM); goto err; } snprintf(teedev->name, sizeof(teedev->name), "tee%s%d", teedesc->flags & TEE_DESC_PRIVILEGED ? "priv" : "", teedev->id - offs); teedev->dev.class = tee_class; teedev->dev.release = tee_release_device; teedev->dev.parent = dev; teedev->dev.devt = MKDEV(MAJOR(tee_devt), teedev->id); rc = dev_set_name(&teedev->dev, "%s", teedev->name); if (rc) { ret = ERR_PTR(rc); goto err_devt; } cdev_init(&teedev->cdev, &tee_fops); teedev->cdev.owner = teedesc->owner; dev_set_drvdata(&teedev->dev, driver_data); device_initialize(&teedev->dev); /* 1 as tee_device_unregister() does one final tee_device_put() */ teedev->num_users = 1; init_completion(&teedev->c_no_users); mutex_init(&teedev->mutex); idr_init(&teedev->idr); teedev->desc = teedesc; teedev->pool = pool; return teedev; err_devt: unregister_chrdev_region(teedev->dev.devt, 1); err: pr_err("could not register %s driver\n", teedesc->flags & TEE_DESC_PRIVILEGED ? "privileged" : "client"); if (teedev && teedev->id < TEE_NUM_DEVICES) { spin_lock(&driver_lock); clear_bit(teedev->id, dev_mask); spin_unlock(&driver_lock); } kfree(teedev); return ret; } EXPORT_SYMBOL_GPL(tee_device_alloc); static ssize_t implementation_id_show(struct device *dev, struct device_attribute *attr, char *buf) { struct tee_device *teedev = container_of(dev, struct tee_device, dev); struct tee_ioctl_version_data vers; teedev->desc->ops->get_version(teedev, &vers); return scnprintf(buf, PAGE_SIZE, "%d\n", vers.impl_id); } static DEVICE_ATTR_RO(implementation_id); static struct attribute *tee_dev_attrs[] = { &dev_attr_implementation_id.attr, NULL }; ATTRIBUTE_GROUPS(tee_dev); /** * tee_device_register() - Registers a TEE device * @teedev: Device to register * * tee_device_unregister() need to be called to remove the @teedev if * this function fails. * * @returns < 0 on failure */ int tee_device_register(struct tee_device *teedev) { int rc; if (teedev->flags & TEE_DEVICE_FLAG_REGISTERED) { dev_err(&teedev->dev, "attempt to register twice\n"); return -EINVAL; } teedev->dev.groups = tee_dev_groups; rc = cdev_device_add(&teedev->cdev, &teedev->dev); if (rc) { dev_err(&teedev->dev, "unable to cdev_device_add() %s, major %d, minor %d, err=%d\n", teedev->name, MAJOR(teedev->dev.devt), MINOR(teedev->dev.devt), rc); return rc; } teedev->flags |= TEE_DEVICE_FLAG_REGISTERED; return 0; } EXPORT_SYMBOL_GPL(tee_device_register); void tee_device_put(struct tee_device *teedev) { mutex_lock(&teedev->mutex); /* Shouldn't put in this state */ if (!WARN_ON(!teedev->desc)) { teedev->num_users--; if (!teedev->num_users) { teedev->desc = NULL; complete(&teedev->c_no_users); } } mutex_unlock(&teedev->mutex); } bool tee_device_get(struct tee_device *teedev) { mutex_lock(&teedev->mutex); if (!teedev->desc) { mutex_unlock(&teedev->mutex); return false; } teedev->num_users++; mutex_unlock(&teedev->mutex); return true; } /** * tee_device_unregister() - Removes a TEE device * @teedev: Device to unregister * * This function should be called to remove the @teedev even if * tee_device_register() hasn't been called yet. Does nothing if * @teedev is NULL. */ void tee_device_unregister(struct tee_device *teedev) { if (!teedev) return; if (teedev->flags & TEE_DEVICE_FLAG_REGISTERED) cdev_device_del(&teedev->cdev, &teedev->dev); tee_device_put(teedev); wait_for_completion(&teedev->c_no_users); /* * No need to take a mutex any longer now since teedev->desc was * set to NULL before teedev->c_no_users was completed. */ teedev->pool = NULL; put_device(&teedev->dev); } EXPORT_SYMBOL_GPL(tee_device_unregister); /** * tee_get_drvdata() - Return driver_data pointer * @teedev: Device containing the driver_data pointer * @returns the driver_data pointer supplied to tee_device_alloc(). */ void *tee_get_drvdata(struct tee_device *teedev) { return dev_get_drvdata(&teedev->dev); } EXPORT_SYMBOL_GPL(tee_get_drvdata); struct match_dev_data { struct tee_ioctl_version_data *vers; const void *data; int (*match)(struct tee_ioctl_version_data *, const void *); }; static int match_dev(struct device *dev, const void *data) { const struct match_dev_data *match_data = data; struct tee_device *teedev = container_of(dev, struct tee_device, dev); teedev->desc->ops->get_version(teedev, match_data->vers); return match_data->match(match_data->vers, match_data->data); } struct tee_context * tee_client_open_context(struct tee_context *start, int (*match)(struct tee_ioctl_version_data *, const void *), const void *data, struct tee_ioctl_version_data *vers) { struct device *dev = NULL; struct device *put_dev = NULL; struct tee_context *ctx = NULL; struct tee_ioctl_version_data v; struct match_dev_data match_data = { vers ? vers : &v, data, match }; if (start) dev = &start->teedev->dev; do { dev = class_find_device(tee_class, dev, &match_data, match_dev); if (!dev) { ctx = ERR_PTR(-ENOENT); break; } put_device(put_dev); put_dev = dev; ctx = teedev_open(container_of(dev, struct tee_device, dev)); } while (IS_ERR(ctx) && PTR_ERR(ctx) != -ENOMEM); put_device(put_dev); /* * Default behaviour for in kernel client is to not wait for * tee-supplicant if not present for any requests in this context. * Also this flag could be configured again before call to * tee_client_open_session() if any in kernel client requires * different behaviour. */ if (!IS_ERR(ctx)) ctx->supp_nowait = true; return ctx; } EXPORT_SYMBOL_GPL(tee_client_open_context); void tee_client_close_context(struct tee_context *ctx) { teedev_close_context(ctx); } EXPORT_SYMBOL_GPL(tee_client_close_context); void tee_client_get_version(struct tee_context *ctx, struct tee_ioctl_version_data *vers) { ctx->teedev->desc->ops->get_version(ctx->teedev, vers); } EXPORT_SYMBOL_GPL(tee_client_get_version); int tee_client_open_session(struct tee_context *ctx, struct tee_ioctl_open_session_arg *arg, struct tee_param *param) { if (!ctx->teedev->desc->ops->open_session) return -EINVAL; return ctx->teedev->desc->ops->open_session(ctx, arg, param); } EXPORT_SYMBOL_GPL(tee_client_open_session); int tee_client_close_session(struct tee_context *ctx, u32 session) { if (!ctx->teedev->desc->ops->close_session) return -EINVAL; return ctx->teedev->desc->ops->close_session(ctx, session); } EXPORT_SYMBOL_GPL(tee_client_close_session); int tee_client_invoke_func(struct tee_context *ctx, struct tee_ioctl_invoke_arg *arg, struct tee_param *param) { if (!ctx->teedev->desc->ops->invoke_func) return -EINVAL; return ctx->teedev->desc->ops->invoke_func(ctx, arg, param); } EXPORT_SYMBOL_GPL(tee_client_invoke_func); int tee_client_cancel_req(struct tee_context *ctx, struct tee_ioctl_cancel_arg *arg) { if (!ctx->teedev->desc->ops->cancel_req) return -EINVAL; return ctx->teedev->desc->ops->cancel_req(ctx, arg->cancel_id, arg->session); } static int tee_client_device_match(struct device *dev, struct device_driver *drv) { const struct tee_client_device_id *id_table; struct tee_client_device *tee_device; id_table = to_tee_client_driver(drv)->id_table; tee_device = to_tee_client_device(dev); while (!uuid_is_null(&id_table->uuid)) { if (uuid_equal(&tee_device->id.uuid, &id_table->uuid)) return 1; id_table++; } return 0; } static int tee_client_device_uevent(const struct device *dev, struct kobj_uevent_env *env) { uuid_t *dev_id = &to_tee_client_device(dev)->id.uuid; return add_uevent_var(env, "MODALIAS=tee:%pUb", dev_id); } struct bus_type tee_bus_type = { .name = "tee", .match = tee_client_device_match, .uevent = tee_client_device_uevent, }; EXPORT_SYMBOL_GPL(tee_bus_type); static int __init tee_init(void) { int rc; tee_class = class_create("tee"); if (IS_ERR(tee_class)) { pr_err("couldn't create class\n"); return PTR_ERR(tee_class); } rc = alloc_chrdev_region(&tee_devt, 0, TEE_NUM_DEVICES, "tee"); if (rc) { pr_err("failed to allocate char dev region\n"); goto out_unreg_class; } rc = bus_register(&tee_bus_type); if (rc) { pr_err("failed to register tee bus\n"); goto out_unreg_chrdev; } return 0; out_unreg_chrdev: unregister_chrdev_region(tee_devt, TEE_NUM_DEVICES); out_unreg_class: class_destroy(tee_class); tee_class = NULL; return rc; } static void __exit tee_exit(void) { bus_unregister(&tee_bus_type); unregister_chrdev_region(tee_devt, TEE_NUM_DEVICES); class_destroy(tee_class); tee_class = NULL; } subsys_initcall(tee_init); module_exit(tee_exit); MODULE_AUTHOR("Linaro"); MODULE_DESCRIPTION("TEE Driver"); MODULE_VERSION("1.0"); MODULE_LICENSE("GPL v2");
linux-master
drivers/tee/tee_core.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2015-2017, 2019-2021 Linaro Limited */ #include <linux/anon_inodes.h> #include <linux/device.h> #include <linux/idr.h> #include <linux/mm.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/tee_drv.h> #include <linux/uaccess.h> #include <linux/uio.h> #include <linux/highmem.h> #include "tee_private.h" static void shm_put_kernel_pages(struct page **pages, size_t page_count) { size_t n; for (n = 0; n < page_count; n++) put_page(pages[n]); } static int shm_get_kernel_pages(unsigned long start, size_t page_count, struct page **pages) { struct page *page; size_t n; if (WARN_ON_ONCE(is_vmalloc_addr((void *)start) || is_kmap_addr((void *)start))) return -EINVAL; page = virt_to_page((void *)start); for (n = 0; n < page_count; n++) { pages[n] = page + n; get_page(pages[n]); } return page_count; } static void release_registered_pages(struct tee_shm *shm) { if (shm->pages) { if (shm->flags & TEE_SHM_USER_MAPPED) unpin_user_pages(shm->pages, shm->num_pages); else shm_put_kernel_pages(shm->pages, shm->num_pages); kfree(shm->pages); } } static void tee_shm_release(struct tee_device *teedev, struct tee_shm *shm) { if (shm->flags & TEE_SHM_POOL) { teedev->pool->ops->free(teedev->pool, shm); } else if (shm->flags & TEE_SHM_DYNAMIC) { int rc = teedev->desc->ops->shm_unregister(shm->ctx, shm); if (rc) dev_err(teedev->dev.parent, "unregister shm %p failed: %d", shm, rc); release_registered_pages(shm); } teedev_ctx_put(shm->ctx); kfree(shm); tee_device_put(teedev); } static struct tee_shm *shm_alloc_helper(struct tee_context *ctx, size_t size, size_t align, u32 flags, int id) { struct tee_device *teedev = ctx->teedev; struct tee_shm *shm; void *ret; int rc; if (!tee_device_get(teedev)) return ERR_PTR(-EINVAL); if (!teedev->pool) { /* teedev has been detached from driver */ ret = ERR_PTR(-EINVAL); goto err_dev_put; } shm = kzalloc(sizeof(*shm), GFP_KERNEL); if (!shm) { ret = ERR_PTR(-ENOMEM); goto err_dev_put; } refcount_set(&shm->refcount, 1); shm->flags = flags; shm->id = id; /* * We're assigning this as it is needed if the shm is to be * registered. If this function returns OK then the caller expected * to call teedev_ctx_get() or clear shm->ctx in case it's not * needed any longer. */ shm->ctx = ctx; rc = teedev->pool->ops->alloc(teedev->pool, shm, size, align); if (rc) { ret = ERR_PTR(rc); goto err_kfree; } teedev_ctx_get(ctx); return shm; err_kfree: kfree(shm); err_dev_put: tee_device_put(teedev); return ret; } /** * tee_shm_alloc_user_buf() - Allocate shared memory for user space * @ctx: Context that allocates the shared memory * @size: Requested size of shared memory * * Memory allocated as user space shared memory is automatically freed when * the TEE file pointer is closed. The primary usage of this function is * when the TEE driver doesn't support registering ordinary user space * memory. * * @returns a pointer to 'struct tee_shm' */ struct tee_shm *tee_shm_alloc_user_buf(struct tee_context *ctx, size_t size) { u32 flags = TEE_SHM_DYNAMIC | TEE_SHM_POOL; struct tee_device *teedev = ctx->teedev; struct tee_shm *shm; void *ret; int id; mutex_lock(&teedev->mutex); id = idr_alloc(&teedev->idr, NULL, 1, 0, GFP_KERNEL); mutex_unlock(&teedev->mutex); if (id < 0) return ERR_PTR(id); shm = shm_alloc_helper(ctx, size, PAGE_SIZE, flags, id); if (IS_ERR(shm)) { mutex_lock(&teedev->mutex); idr_remove(&teedev->idr, id); mutex_unlock(&teedev->mutex); return shm; } mutex_lock(&teedev->mutex); ret = idr_replace(&teedev->idr, shm, id); mutex_unlock(&teedev->mutex); if (IS_ERR(ret)) { tee_shm_free(shm); return ret; } return shm; } /** * tee_shm_alloc_kernel_buf() - Allocate shared memory for kernel buffer * @ctx: Context that allocates the shared memory * @size: Requested size of shared memory * * The returned memory registered in secure world and is suitable to be * passed as a memory buffer in parameter argument to * tee_client_invoke_func(). The memory allocated is later freed with a * call to tee_shm_free(). * * @returns a pointer to 'struct tee_shm' */ struct tee_shm *tee_shm_alloc_kernel_buf(struct tee_context *ctx, size_t size) { u32 flags = TEE_SHM_DYNAMIC | TEE_SHM_POOL; return shm_alloc_helper(ctx, size, PAGE_SIZE, flags, -1); } EXPORT_SYMBOL_GPL(tee_shm_alloc_kernel_buf); /** * tee_shm_alloc_priv_buf() - Allocate shared memory for a privately shared * kernel buffer * @ctx: Context that allocates the shared memory * @size: Requested size of shared memory * * This function returns similar shared memory as * tee_shm_alloc_kernel_buf(), but with the difference that the memory * might not be registered in secure world in case the driver supports * passing memory not registered in advance. * * This function should normally only be used internally in the TEE * drivers. * * @returns a pointer to 'struct tee_shm' */ struct tee_shm *tee_shm_alloc_priv_buf(struct tee_context *ctx, size_t size) { u32 flags = TEE_SHM_PRIV | TEE_SHM_POOL; return shm_alloc_helper(ctx, size, sizeof(long) * 2, flags, -1); } EXPORT_SYMBOL_GPL(tee_shm_alloc_priv_buf); static struct tee_shm * register_shm_helper(struct tee_context *ctx, unsigned long addr, size_t length, u32 flags, int id) { struct tee_device *teedev = ctx->teedev; struct tee_shm *shm; unsigned long start; size_t num_pages; void *ret; int rc; if (!tee_device_get(teedev)) return ERR_PTR(-EINVAL); if (!teedev->desc->ops->shm_register || !teedev->desc->ops->shm_unregister) { ret = ERR_PTR(-ENOTSUPP); goto err_dev_put; } teedev_ctx_get(ctx); shm = kzalloc(sizeof(*shm), GFP_KERNEL); if (!shm) { ret = ERR_PTR(-ENOMEM); goto err_ctx_put; } refcount_set(&shm->refcount, 1); shm->flags = flags; shm->ctx = ctx; shm->id = id; addr = untagged_addr(addr); start = rounddown(addr, PAGE_SIZE); shm->offset = addr - start; shm->size = length; num_pages = (roundup(addr + length, PAGE_SIZE) - start) / PAGE_SIZE; shm->pages = kcalloc(num_pages, sizeof(*shm->pages), GFP_KERNEL); if (!shm->pages) { ret = ERR_PTR(-ENOMEM); goto err_free_shm; } if (flags & TEE_SHM_USER_MAPPED) rc = pin_user_pages_fast(start, num_pages, FOLL_WRITE, shm->pages); else rc = shm_get_kernel_pages(start, num_pages, shm->pages); if (rc > 0) shm->num_pages = rc; if (rc != num_pages) { if (rc >= 0) rc = -ENOMEM; ret = ERR_PTR(rc); goto err_put_shm_pages; } rc = teedev->desc->ops->shm_register(ctx, shm, shm->pages, shm->num_pages, start); if (rc) { ret = ERR_PTR(rc); goto err_put_shm_pages; } return shm; err_put_shm_pages: if (flags & TEE_SHM_USER_MAPPED) unpin_user_pages(shm->pages, shm->num_pages); else shm_put_kernel_pages(shm->pages, shm->num_pages); kfree(shm->pages); err_free_shm: kfree(shm); err_ctx_put: teedev_ctx_put(ctx); err_dev_put: tee_device_put(teedev); return ret; } /** * tee_shm_register_user_buf() - Register a userspace shared memory buffer * @ctx: Context that registers the shared memory * @addr: The userspace address of the shared buffer * @length: Length of the shared buffer * * @returns a pointer to 'struct tee_shm' */ struct tee_shm *tee_shm_register_user_buf(struct tee_context *ctx, unsigned long addr, size_t length) { u32 flags = TEE_SHM_USER_MAPPED | TEE_SHM_DYNAMIC; struct tee_device *teedev = ctx->teedev; struct tee_shm *shm; void *ret; int id; if (!access_ok((void __user *)addr, length)) return ERR_PTR(-EFAULT); mutex_lock(&teedev->mutex); id = idr_alloc(&teedev->idr, NULL, 1, 0, GFP_KERNEL); mutex_unlock(&teedev->mutex); if (id < 0) return ERR_PTR(id); shm = register_shm_helper(ctx, addr, length, flags, id); if (IS_ERR(shm)) { mutex_lock(&teedev->mutex); idr_remove(&teedev->idr, id); mutex_unlock(&teedev->mutex); return shm; } mutex_lock(&teedev->mutex); ret = idr_replace(&teedev->idr, shm, id); mutex_unlock(&teedev->mutex); if (IS_ERR(ret)) { tee_shm_free(shm); return ret; } return shm; } /** * tee_shm_register_kernel_buf() - Register kernel memory to be shared with * secure world * @ctx: Context that registers the shared memory * @addr: The buffer * @length: Length of the buffer * * @returns a pointer to 'struct tee_shm' */ struct tee_shm *tee_shm_register_kernel_buf(struct tee_context *ctx, void *addr, size_t length) { u32 flags = TEE_SHM_DYNAMIC; return register_shm_helper(ctx, (unsigned long)addr, length, flags, -1); } EXPORT_SYMBOL_GPL(tee_shm_register_kernel_buf); static int tee_shm_fop_release(struct inode *inode, struct file *filp) { tee_shm_put(filp->private_data); return 0; } static int tee_shm_fop_mmap(struct file *filp, struct vm_area_struct *vma) { struct tee_shm *shm = filp->private_data; size_t size = vma->vm_end - vma->vm_start; /* Refuse sharing shared memory provided by application */ if (shm->flags & TEE_SHM_USER_MAPPED) return -EINVAL; /* check for overflowing the buffer's size */ if (vma->vm_pgoff + vma_pages(vma) > shm->size >> PAGE_SHIFT) return -EINVAL; return remap_pfn_range(vma, vma->vm_start, shm->paddr >> PAGE_SHIFT, size, vma->vm_page_prot); } static const struct file_operations tee_shm_fops = { .owner = THIS_MODULE, .release = tee_shm_fop_release, .mmap = tee_shm_fop_mmap, }; /** * tee_shm_get_fd() - Increase reference count and return file descriptor * @shm: Shared memory handle * @returns user space file descriptor to shared memory */ int tee_shm_get_fd(struct tee_shm *shm) { int fd; if (shm->id < 0) return -EINVAL; /* matched by tee_shm_put() in tee_shm_op_release() */ refcount_inc(&shm->refcount); fd = anon_inode_getfd("tee_shm", &tee_shm_fops, shm, O_RDWR); if (fd < 0) tee_shm_put(shm); return fd; } /** * tee_shm_free() - Free shared memory * @shm: Handle to shared memory to free */ void tee_shm_free(struct tee_shm *shm) { tee_shm_put(shm); } EXPORT_SYMBOL_GPL(tee_shm_free); /** * tee_shm_get_va() - Get virtual address of a shared memory plus an offset * @shm: Shared memory handle * @offs: Offset from start of this shared memory * @returns virtual address of the shared memory + offs if offs is within * the bounds of this shared memory, else an ERR_PTR */ void *tee_shm_get_va(struct tee_shm *shm, size_t offs) { if (!shm->kaddr) return ERR_PTR(-EINVAL); if (offs >= shm->size) return ERR_PTR(-EINVAL); return (char *)shm->kaddr + offs; } EXPORT_SYMBOL_GPL(tee_shm_get_va); /** * tee_shm_get_pa() - Get physical address of a shared memory plus an offset * @shm: Shared memory handle * @offs: Offset from start of this shared memory * @pa: Physical address to return * @returns 0 if offs is within the bounds of this shared memory, else an * error code. */ int tee_shm_get_pa(struct tee_shm *shm, size_t offs, phys_addr_t *pa) { if (offs >= shm->size) return -EINVAL; if (pa) *pa = shm->paddr + offs; return 0; } EXPORT_SYMBOL_GPL(tee_shm_get_pa); /** * tee_shm_get_from_id() - Find shared memory object and increase reference * count * @ctx: Context owning the shared memory * @id: Id of shared memory object * @returns a pointer to 'struct tee_shm' on success or an ERR_PTR on failure */ struct tee_shm *tee_shm_get_from_id(struct tee_context *ctx, int id) { struct tee_device *teedev; struct tee_shm *shm; if (!ctx) return ERR_PTR(-EINVAL); teedev = ctx->teedev; mutex_lock(&teedev->mutex); shm = idr_find(&teedev->idr, id); /* * If the tee_shm was found in the IDR it must have a refcount * larger than 0 due to the guarantee in tee_shm_put() below. So * it's safe to use refcount_inc(). */ if (!shm || shm->ctx != ctx) shm = ERR_PTR(-EINVAL); else refcount_inc(&shm->refcount); mutex_unlock(&teedev->mutex); return shm; } EXPORT_SYMBOL_GPL(tee_shm_get_from_id); /** * tee_shm_put() - Decrease reference count on a shared memory handle * @shm: Shared memory handle */ void tee_shm_put(struct tee_shm *shm) { struct tee_device *teedev = shm->ctx->teedev; bool do_release = false; mutex_lock(&teedev->mutex); if (refcount_dec_and_test(&shm->refcount)) { /* * refcount has reached 0, we must now remove it from the * IDR before releasing the mutex. This will guarantee that * the refcount_inc() in tee_shm_get_from_id() never starts * from 0. */ if (shm->id >= 0) idr_remove(&teedev->idr, shm->id); do_release = true; } mutex_unlock(&teedev->mutex); if (do_release) tee_shm_release(teedev, shm); } EXPORT_SYMBOL_GPL(tee_shm_put);
linux-master
drivers/tee/tee_shm.c
// SPDX-License-Identifier: MIT /* * Copyright 2019 Advanced Micro Devices, Inc. */ #include <linux/errno.h> #include <linux/io.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/device.h> #include <linux/tee_drv.h> #include <linux/types.h> #include <linux/mm.h> #include <linux/uaccess.h> #include <linux/firmware.h> #include "amdtee_private.h" #include "../tee_private.h" #include <linux/psp-tee.h> static struct amdtee_driver_data *drv_data; static DEFINE_MUTEX(session_list_mutex); static void amdtee_get_version(struct tee_device *teedev, struct tee_ioctl_version_data *vers) { struct tee_ioctl_version_data v = { .impl_id = TEE_IMPL_ID_AMDTEE, .impl_caps = 0, .gen_caps = TEE_GEN_CAP_GP, }; *vers = v; } static int amdtee_open(struct tee_context *ctx) { struct amdtee_context_data *ctxdata; ctxdata = kzalloc(sizeof(*ctxdata), GFP_KERNEL); if (!ctxdata) return -ENOMEM; INIT_LIST_HEAD(&ctxdata->sess_list); INIT_LIST_HEAD(&ctxdata->shm_list); mutex_init(&ctxdata->shm_mutex); ctx->data = ctxdata; return 0; } static void release_session(struct amdtee_session *sess) { int i; /* Close any open session */ for (i = 0; i < TEE_NUM_SESSIONS; ++i) { /* Check if session entry 'i' is valid */ if (!test_bit(i, sess->sess_mask)) continue; handle_close_session(sess->ta_handle, sess->session_info[i]); handle_unload_ta(sess->ta_handle); } kfree(sess); } static void amdtee_release(struct tee_context *ctx) { struct amdtee_context_data *ctxdata = ctx->data; if (!ctxdata) return; while (true) { struct amdtee_session *sess; sess = list_first_entry_or_null(&ctxdata->sess_list, struct amdtee_session, list_node); if (!sess) break; list_del(&sess->list_node); release_session(sess); } mutex_destroy(&ctxdata->shm_mutex); kfree(ctxdata); ctx->data = NULL; } /** * alloc_session() - Allocate a session structure * @ctxdata: TEE Context data structure * @session: Session ID for which 'struct amdtee_session' structure is to be * allocated. * * Scans the TEE context's session list to check if TA is already loaded in to * TEE. If yes, returns the 'session' structure for that TA. Else allocates, * initializes a new 'session' structure and adds it to context's session list. * * The caller must hold a mutex. * * Returns: * 'struct amdtee_session *' on success and NULL on failure. */ static struct amdtee_session *alloc_session(struct amdtee_context_data *ctxdata, u32 session) { struct amdtee_session *sess; u32 ta_handle = get_ta_handle(session); /* Scan session list to check if TA is already loaded in to TEE */ list_for_each_entry(sess, &ctxdata->sess_list, list_node) if (sess->ta_handle == ta_handle) { kref_get(&sess->refcount); return sess; } /* Allocate a new session and add to list */ sess = kzalloc(sizeof(*sess), GFP_KERNEL); if (sess) { sess->ta_handle = ta_handle; kref_init(&sess->refcount); spin_lock_init(&sess->lock); list_add(&sess->list_node, &ctxdata->sess_list); } return sess; } /* Requires mutex to be held */ static struct amdtee_session *find_session(struct amdtee_context_data *ctxdata, u32 session) { u32 ta_handle = get_ta_handle(session); u32 index = get_session_index(session); struct amdtee_session *sess; if (index >= TEE_NUM_SESSIONS) return NULL; list_for_each_entry(sess, &ctxdata->sess_list, list_node) if (ta_handle == sess->ta_handle && test_bit(index, sess->sess_mask)) return sess; return NULL; } u32 get_buffer_id(struct tee_shm *shm) { struct amdtee_context_data *ctxdata = shm->ctx->data; struct amdtee_shm_data *shmdata; u32 buf_id = 0; mutex_lock(&ctxdata->shm_mutex); list_for_each_entry(shmdata, &ctxdata->shm_list, shm_node) if (shmdata->kaddr == shm->kaddr) { buf_id = shmdata->buf_id; break; } mutex_unlock(&ctxdata->shm_mutex); return buf_id; } static DEFINE_MUTEX(drv_mutex); static int copy_ta_binary(struct tee_context *ctx, void *ptr, void **ta, size_t *ta_size) { const struct firmware *fw; char fw_name[TA_PATH_MAX]; struct { u32 lo; u16 mid; u16 hi_ver; u8 seq_n[8]; } *uuid = ptr; int n, rc = 0; n = snprintf(fw_name, TA_PATH_MAX, "%s/%08x-%04x-%04x-%02x%02x%02x%02x%02x%02x%02x%02x.bin", TA_LOAD_PATH, uuid->lo, uuid->mid, uuid->hi_ver, uuid->seq_n[0], uuid->seq_n[1], uuid->seq_n[2], uuid->seq_n[3], uuid->seq_n[4], uuid->seq_n[5], uuid->seq_n[6], uuid->seq_n[7]); if (n < 0 || n >= TA_PATH_MAX) { pr_err("failed to get firmware name\n"); return -EINVAL; } mutex_lock(&drv_mutex); n = request_firmware(&fw, fw_name, &ctx->teedev->dev); if (n) { pr_err("failed to load firmware %s\n", fw_name); rc = -ENOMEM; goto unlock; } *ta_size = roundup(fw->size, PAGE_SIZE); *ta = (void *)__get_free_pages(GFP_KERNEL, get_order(*ta_size)); if (!*ta) { pr_err("%s: get_free_pages failed\n", __func__); rc = -ENOMEM; goto rel_fw; } memcpy(*ta, fw->data, fw->size); rel_fw: release_firmware(fw); unlock: mutex_unlock(&drv_mutex); return rc; } static void destroy_session(struct kref *ref) { struct amdtee_session *sess = container_of(ref, struct amdtee_session, refcount); mutex_lock(&session_list_mutex); list_del(&sess->list_node); mutex_unlock(&session_list_mutex); kfree(sess); } int amdtee_open_session(struct tee_context *ctx, struct tee_ioctl_open_session_arg *arg, struct tee_param *param) { struct amdtee_context_data *ctxdata = ctx->data; struct amdtee_session *sess = NULL; u32 session_info, ta_handle; size_t ta_size; int rc, i; void *ta; if (arg->clnt_login != TEE_IOCTL_LOGIN_PUBLIC) { pr_err("unsupported client login method\n"); return -EINVAL; } rc = copy_ta_binary(ctx, &arg->uuid[0], &ta, &ta_size); if (rc) { pr_err("failed to copy TA binary\n"); return rc; } /* Load the TA binary into TEE environment */ handle_load_ta(ta, ta_size, arg); if (arg->ret != TEEC_SUCCESS) goto out; ta_handle = get_ta_handle(arg->session); mutex_lock(&session_list_mutex); sess = alloc_session(ctxdata, arg->session); mutex_unlock(&session_list_mutex); if (!sess) { handle_unload_ta(ta_handle); rc = -ENOMEM; goto out; } /* Open session with loaded TA */ handle_open_session(arg, &session_info, param); if (arg->ret != TEEC_SUCCESS) { pr_err("open_session failed %d\n", arg->ret); handle_unload_ta(ta_handle); kref_put(&sess->refcount, destroy_session); goto out; } /* Find an empty session index for the given TA */ spin_lock(&sess->lock); i = find_first_zero_bit(sess->sess_mask, TEE_NUM_SESSIONS); if (i < TEE_NUM_SESSIONS) { sess->session_info[i] = session_info; set_session_id(ta_handle, i, &arg->session); set_bit(i, sess->sess_mask); } spin_unlock(&sess->lock); if (i >= TEE_NUM_SESSIONS) { pr_err("reached maximum session count %d\n", TEE_NUM_SESSIONS); handle_close_session(ta_handle, session_info); handle_unload_ta(ta_handle); kref_put(&sess->refcount, destroy_session); rc = -ENOMEM; goto out; } out: free_pages((u64)ta, get_order(ta_size)); return rc; } int amdtee_close_session(struct tee_context *ctx, u32 session) { struct amdtee_context_data *ctxdata = ctx->data; u32 i, ta_handle, session_info; struct amdtee_session *sess; pr_debug("%s: sid = 0x%x\n", __func__, session); /* * Check that the session is valid and clear the session * usage bit */ mutex_lock(&session_list_mutex); sess = find_session(ctxdata, session); if (sess) { ta_handle = get_ta_handle(session); i = get_session_index(session); session_info = sess->session_info[i]; spin_lock(&sess->lock); clear_bit(i, sess->sess_mask); spin_unlock(&sess->lock); } mutex_unlock(&session_list_mutex); if (!sess) return -EINVAL; /* Close the session */ handle_close_session(ta_handle, session_info); handle_unload_ta(ta_handle); kref_put(&sess->refcount, destroy_session); return 0; } int amdtee_map_shmem(struct tee_shm *shm) { struct amdtee_context_data *ctxdata; struct amdtee_shm_data *shmnode; struct shmem_desc shmem; int rc, count; u32 buf_id; if (!shm) return -EINVAL; shmnode = kmalloc(sizeof(*shmnode), GFP_KERNEL); if (!shmnode) return -ENOMEM; count = 1; shmem.kaddr = shm->kaddr; shmem.size = shm->size; /* * Send a MAP command to TEE and get the corresponding * buffer Id */ rc = handle_map_shmem(count, &shmem, &buf_id); if (rc) { pr_err("map_shmem failed: ret = %d\n", rc); kfree(shmnode); return rc; } shmnode->kaddr = shm->kaddr; shmnode->buf_id = buf_id; ctxdata = shm->ctx->data; mutex_lock(&ctxdata->shm_mutex); list_add(&shmnode->shm_node, &ctxdata->shm_list); mutex_unlock(&ctxdata->shm_mutex); pr_debug("buf_id :[%x] kaddr[%p]\n", shmnode->buf_id, shmnode->kaddr); return 0; } void amdtee_unmap_shmem(struct tee_shm *shm) { struct amdtee_context_data *ctxdata; struct amdtee_shm_data *shmnode; u32 buf_id; if (!shm) return; buf_id = get_buffer_id(shm); /* Unmap the shared memory from TEE */ handle_unmap_shmem(buf_id); ctxdata = shm->ctx->data; mutex_lock(&ctxdata->shm_mutex); list_for_each_entry(shmnode, &ctxdata->shm_list, shm_node) if (buf_id == shmnode->buf_id) { list_del(&shmnode->shm_node); kfree(shmnode); break; } mutex_unlock(&ctxdata->shm_mutex); } int amdtee_invoke_func(struct tee_context *ctx, struct tee_ioctl_invoke_arg *arg, struct tee_param *param) { struct amdtee_context_data *ctxdata = ctx->data; struct amdtee_session *sess; u32 i, session_info; /* Check that the session is valid */ mutex_lock(&session_list_mutex); sess = find_session(ctxdata, arg->session); if (sess) { i = get_session_index(arg->session); session_info = sess->session_info[i]; } mutex_unlock(&session_list_mutex); if (!sess) return -EINVAL; handle_invoke_cmd(arg, session_info, param); return 0; } int amdtee_cancel_req(struct tee_context *ctx, u32 cancel_id, u32 session) { return -EINVAL; } static const struct tee_driver_ops amdtee_ops = { .get_version = amdtee_get_version, .open = amdtee_open, .release = amdtee_release, .open_session = amdtee_open_session, .close_session = amdtee_close_session, .invoke_func = amdtee_invoke_func, .cancel_req = amdtee_cancel_req, }; static const struct tee_desc amdtee_desc = { .name = DRIVER_NAME "-clnt", .ops = &amdtee_ops, .owner = THIS_MODULE, }; static int __init amdtee_driver_init(void) { struct tee_device *teedev; struct tee_shm_pool *pool; struct amdtee *amdtee; int rc; rc = psp_check_tee_status(); if (rc) { pr_err("amd-tee driver: tee not present\n"); return rc; } drv_data = kzalloc(sizeof(*drv_data), GFP_KERNEL); if (!drv_data) return -ENOMEM; amdtee = kzalloc(sizeof(*amdtee), GFP_KERNEL); if (!amdtee) { rc = -ENOMEM; goto err_kfree_drv_data; } pool = amdtee_config_shm(); if (IS_ERR(pool)) { pr_err("shared pool configuration error\n"); rc = PTR_ERR(pool); goto err_kfree_amdtee; } teedev = tee_device_alloc(&amdtee_desc, NULL, pool, amdtee); if (IS_ERR(teedev)) { rc = PTR_ERR(teedev); goto err_free_pool; } amdtee->teedev = teedev; rc = tee_device_register(amdtee->teedev); if (rc) goto err_device_unregister; amdtee->pool = pool; drv_data->amdtee = amdtee; pr_info("amd-tee driver initialization successful\n"); return 0; err_device_unregister: tee_device_unregister(amdtee->teedev); err_free_pool: tee_shm_pool_free(pool); err_kfree_amdtee: kfree(amdtee); err_kfree_drv_data: kfree(drv_data); drv_data = NULL; pr_err("amd-tee driver initialization failed\n"); return rc; } module_init(amdtee_driver_init); static void __exit amdtee_driver_exit(void) { struct amdtee *amdtee; if (!drv_data || !drv_data->amdtee) return; amdtee = drv_data->amdtee; tee_device_unregister(amdtee->teedev); tee_shm_pool_free(amdtee->pool); } module_exit(amdtee_driver_exit); MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION("AMD-TEE driver"); MODULE_VERSION("1.0"); MODULE_LICENSE("Dual MIT/GPL");
linux-master
drivers/tee/amdtee/core.c
// SPDX-License-Identifier: MIT /* * Copyright 2019 Advanced Micro Devices, Inc. */ #include <linux/slab.h> #include <linux/tee_drv.h> #include <linux/psp.h> #include "amdtee_private.h" static int pool_op_alloc(struct tee_shm_pool *pool, struct tee_shm *shm, size_t size, size_t align) { unsigned int order = get_order(size); unsigned long va; int rc; /* * Ignore alignment since this is already going to be page aligned * and there's no need for any larger alignment. */ va = __get_free_pages(GFP_KERNEL | __GFP_ZERO, order); if (!va) return -ENOMEM; shm->kaddr = (void *)va; shm->paddr = __psp_pa((void *)va); shm->size = PAGE_SIZE << order; /* Map the allocated memory in to TEE */ rc = amdtee_map_shmem(shm); if (rc) { free_pages(va, order); shm->kaddr = NULL; return rc; } return 0; } static void pool_op_free(struct tee_shm_pool *pool, struct tee_shm *shm) { /* Unmap the shared memory from TEE */ amdtee_unmap_shmem(shm); free_pages((unsigned long)shm->kaddr, get_order(shm->size)); shm->kaddr = NULL; } static void pool_op_destroy_pool(struct tee_shm_pool *pool) { kfree(pool); } static const struct tee_shm_pool_ops pool_ops = { .alloc = pool_op_alloc, .free = pool_op_free, .destroy_pool = pool_op_destroy_pool, }; struct tee_shm_pool *amdtee_config_shm(void) { struct tee_shm_pool *pool = kzalloc(sizeof(*pool), GFP_KERNEL); if (!pool) return ERR_PTR(-ENOMEM); pool->ops = &pool_ops; return pool; }
linux-master
drivers/tee/amdtee/shm_pool.c
// SPDX-License-Identifier: MIT /* * Copyright 2019 Advanced Micro Devices, Inc. */ #include <linux/device.h> #include <linux/tee.h> #include <linux/tee_drv.h> #include <linux/psp-tee.h> #include <linux/slab.h> #include <linux/psp.h> #include "amdtee_if.h" #include "amdtee_private.h" static int tee_params_to_amd_params(struct tee_param *tee, u32 count, struct tee_operation *amd) { int i, ret = 0; u32 type; if (!count) return 0; if (!tee || !amd || count > TEE_MAX_PARAMS) return -EINVAL; amd->param_types = 0; for (i = 0; i < count; i++) { /* AMD TEE does not support meta parameter */ if (tee[i].attr > TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INOUT) return -EINVAL; amd->param_types |= ((tee[i].attr & 0xF) << i * 4); } for (i = 0; i < count; i++) { type = TEE_PARAM_TYPE_GET(amd->param_types, i); pr_debug("%s: type[%d] = 0x%x\n", __func__, i, type); if (type == TEE_OP_PARAM_TYPE_INVALID) return -EINVAL; if (type == TEE_OP_PARAM_TYPE_NONE) continue; /* It is assumed that all values are within 2^32-1 */ if (type > TEE_OP_PARAM_TYPE_VALUE_INOUT) { u32 buf_id = get_buffer_id(tee[i].u.memref.shm); amd->params[i].mref.buf_id = buf_id; amd->params[i].mref.offset = tee[i].u.memref.shm_offs; amd->params[i].mref.size = tee[i].u.memref.size; pr_debug("%s: bufid[%d] = 0x%x, offset[%d] = 0x%x, size[%d] = 0x%x\n", __func__, i, amd->params[i].mref.buf_id, i, amd->params[i].mref.offset, i, amd->params[i].mref.size); } else { if (tee[i].u.value.c) pr_warn("%s: Discarding value c", __func__); amd->params[i].val.a = tee[i].u.value.a; amd->params[i].val.b = tee[i].u.value.b; pr_debug("%s: a[%d] = 0x%x, b[%d] = 0x%x\n", __func__, i, amd->params[i].val.a, i, amd->params[i].val.b); } } return ret; } static int amd_params_to_tee_params(struct tee_param *tee, u32 count, struct tee_operation *amd) { int i, ret = 0; u32 type; if (!count) return 0; if (!tee || !amd || count > TEE_MAX_PARAMS) return -EINVAL; /* Assumes amd->param_types is valid */ for (i = 0; i < count; i++) { type = TEE_PARAM_TYPE_GET(amd->param_types, i); pr_debug("%s: type[%d] = 0x%x\n", __func__, i, type); if (type == TEE_OP_PARAM_TYPE_INVALID || type > TEE_OP_PARAM_TYPE_MEMREF_INOUT) return -EINVAL; if (type == TEE_OP_PARAM_TYPE_NONE || type == TEE_OP_PARAM_TYPE_VALUE_INPUT || type == TEE_OP_PARAM_TYPE_MEMREF_INPUT) continue; /* * It is assumed that buf_id remains unchanged for * both open_session and invoke_cmd call */ if (type > TEE_OP_PARAM_TYPE_MEMREF_INPUT) { tee[i].u.memref.shm_offs = amd->params[i].mref.offset; tee[i].u.memref.size = amd->params[i].mref.size; pr_debug("%s: bufid[%d] = 0x%x, offset[%d] = 0x%x, size[%d] = 0x%x\n", __func__, i, amd->params[i].mref.buf_id, i, amd->params[i].mref.offset, i, amd->params[i].mref.size); } else { /* field 'c' not supported by AMD TEE */ tee[i].u.value.a = amd->params[i].val.a; tee[i].u.value.b = amd->params[i].val.b; tee[i].u.value.c = 0; pr_debug("%s: a[%d] = 0x%x, b[%d] = 0x%x\n", __func__, i, amd->params[i].val.a, i, amd->params[i].val.b); } } return ret; } static DEFINE_MUTEX(ta_refcount_mutex); static LIST_HEAD(ta_list); static u32 get_ta_refcount(u32 ta_handle) { struct amdtee_ta_data *ta_data; u32 count = 0; /* Caller must hold a mutex */ list_for_each_entry(ta_data, &ta_list, list_node) if (ta_data->ta_handle == ta_handle) return ++ta_data->refcount; ta_data = kzalloc(sizeof(*ta_data), GFP_KERNEL); if (ta_data) { ta_data->ta_handle = ta_handle; ta_data->refcount = 1; count = ta_data->refcount; list_add(&ta_data->list_node, &ta_list); } return count; } static u32 put_ta_refcount(u32 ta_handle) { struct amdtee_ta_data *ta_data; u32 count = 0; /* Caller must hold a mutex */ list_for_each_entry(ta_data, &ta_list, list_node) if (ta_data->ta_handle == ta_handle) { count = --ta_data->refcount; if (count == 0) { list_del(&ta_data->list_node); kfree(ta_data); break; } } return count; } int handle_unload_ta(u32 ta_handle) { struct tee_cmd_unload_ta cmd = {0}; u32 status, count; int ret; if (!ta_handle) return -EINVAL; mutex_lock(&ta_refcount_mutex); count = put_ta_refcount(ta_handle); if (count) { pr_debug("unload ta: not unloading %u count %u\n", ta_handle, count); ret = -EBUSY; goto unlock; } cmd.ta_handle = ta_handle; ret = psp_tee_process_cmd(TEE_CMD_ID_UNLOAD_TA, (void *)&cmd, sizeof(cmd), &status); if (!ret && status != 0) { pr_err("unload ta: status = 0x%x\n", status); ret = -EBUSY; } else { pr_debug("unloaded ta handle %u\n", ta_handle); } unlock: mutex_unlock(&ta_refcount_mutex); return ret; } int handle_close_session(u32 ta_handle, u32 info) { struct tee_cmd_close_session cmd = {0}; u32 status; int ret; if (ta_handle == 0) return -EINVAL; cmd.ta_handle = ta_handle; cmd.session_info = info; ret = psp_tee_process_cmd(TEE_CMD_ID_CLOSE_SESSION, (void *)&cmd, sizeof(cmd), &status); if (!ret && status != 0) { pr_err("close session: status = 0x%x\n", status); ret = -EBUSY; } return ret; } void handle_unmap_shmem(u32 buf_id) { struct tee_cmd_unmap_shared_mem cmd = {0}; u32 status; int ret; cmd.buf_id = buf_id; ret = psp_tee_process_cmd(TEE_CMD_ID_UNMAP_SHARED_MEM, (void *)&cmd, sizeof(cmd), &status); if (!ret) pr_debug("unmap shared memory: buf_id %u status = 0x%x\n", buf_id, status); } int handle_invoke_cmd(struct tee_ioctl_invoke_arg *arg, u32 sinfo, struct tee_param *p) { struct tee_cmd_invoke_cmd cmd = {0}; int ret; if (!arg || (!p && arg->num_params)) return -EINVAL; arg->ret_origin = TEEC_ORIGIN_COMMS; if (arg->session == 0) { arg->ret = TEEC_ERROR_BAD_PARAMETERS; return -EINVAL; } ret = tee_params_to_amd_params(p, arg->num_params, &cmd.op); if (ret) { pr_err("invalid Params. Abort invoke command\n"); arg->ret = TEEC_ERROR_BAD_PARAMETERS; return ret; } cmd.ta_handle = get_ta_handle(arg->session); cmd.cmd_id = arg->func; cmd.session_info = sinfo; ret = psp_tee_process_cmd(TEE_CMD_ID_INVOKE_CMD, (void *)&cmd, sizeof(cmd), &arg->ret); if (ret) { arg->ret = TEEC_ERROR_COMMUNICATION; } else { ret = amd_params_to_tee_params(p, arg->num_params, &cmd.op); if (unlikely(ret)) { pr_err("invoke command: failed to copy output\n"); arg->ret = TEEC_ERROR_GENERIC; return ret; } arg->ret_origin = cmd.return_origin; pr_debug("invoke command: RO = 0x%x ret = 0x%x\n", arg->ret_origin, arg->ret); } return ret; } int handle_map_shmem(u32 count, struct shmem_desc *start, u32 *buf_id) { struct tee_cmd_map_shared_mem *cmd; phys_addr_t paddr; int ret, i; u32 status; if (!count || !start || !buf_id) return -EINVAL; cmd = kzalloc(sizeof(*cmd), GFP_KERNEL); if (!cmd) return -ENOMEM; /* Size must be page aligned */ for (i = 0; i < count ; i++) { if (!start[i].kaddr || (start[i].size & (PAGE_SIZE - 1))) { ret = -EINVAL; goto free_cmd; } if ((u64)start[i].kaddr & (PAGE_SIZE - 1)) { pr_err("map shared memory: page unaligned. addr 0x%llx", (u64)start[i].kaddr); ret = -EINVAL; goto free_cmd; } } cmd->sg_list.count = count; /* Create buffer list */ for (i = 0; i < count ; i++) { paddr = __psp_pa(start[i].kaddr); cmd->sg_list.buf[i].hi_addr = upper_32_bits(paddr); cmd->sg_list.buf[i].low_addr = lower_32_bits(paddr); cmd->sg_list.buf[i].size = start[i].size; cmd->sg_list.size += cmd->sg_list.buf[i].size; pr_debug("buf[%d]:hi addr = 0x%x\n", i, cmd->sg_list.buf[i].hi_addr); pr_debug("buf[%d]:low addr = 0x%x\n", i, cmd->sg_list.buf[i].low_addr); pr_debug("buf[%d]:size = 0x%x\n", i, cmd->sg_list.buf[i].size); pr_debug("list size = 0x%x\n", cmd->sg_list.size); } *buf_id = 0; ret = psp_tee_process_cmd(TEE_CMD_ID_MAP_SHARED_MEM, (void *)cmd, sizeof(*cmd), &status); if (!ret && !status) { *buf_id = cmd->buf_id; pr_debug("mapped buffer ID = 0x%x\n", *buf_id); } else { pr_err("map shared memory: status = 0x%x\n", status); ret = -ENOMEM; } free_cmd: kfree(cmd); return ret; } int handle_open_session(struct tee_ioctl_open_session_arg *arg, u32 *info, struct tee_param *p) { struct tee_cmd_open_session cmd = {0}; int ret; if (!arg || !info || (!p && arg->num_params)) return -EINVAL; arg->ret_origin = TEEC_ORIGIN_COMMS; if (arg->session == 0) { arg->ret = TEEC_ERROR_GENERIC; return -EINVAL; } ret = tee_params_to_amd_params(p, arg->num_params, &cmd.op); if (ret) { pr_err("invalid Params. Abort open session\n"); arg->ret = TEEC_ERROR_BAD_PARAMETERS; return ret; } cmd.ta_handle = get_ta_handle(arg->session); *info = 0; ret = psp_tee_process_cmd(TEE_CMD_ID_OPEN_SESSION, (void *)&cmd, sizeof(cmd), &arg->ret); if (ret) { arg->ret = TEEC_ERROR_COMMUNICATION; } else { ret = amd_params_to_tee_params(p, arg->num_params, &cmd.op); if (unlikely(ret)) { pr_err("open session: failed to copy output\n"); arg->ret = TEEC_ERROR_GENERIC; return ret; } arg->ret_origin = cmd.return_origin; *info = cmd.session_info; pr_debug("open session: session info = 0x%x\n", *info); } pr_debug("open session: ret = 0x%x RO = 0x%x\n", arg->ret, arg->ret_origin); return ret; } int handle_load_ta(void *data, u32 size, struct tee_ioctl_open_session_arg *arg) { struct tee_cmd_unload_ta unload_cmd = {}; struct tee_cmd_load_ta load_cmd = {}; phys_addr_t blob; int ret; if (size == 0 || !data || !arg) return -EINVAL; blob = __psp_pa(data); if (blob & (PAGE_SIZE - 1)) { pr_err("load TA: page unaligned. blob 0x%llx", blob); return -EINVAL; } load_cmd.hi_addr = upper_32_bits(blob); load_cmd.low_addr = lower_32_bits(blob); load_cmd.size = size; mutex_lock(&ta_refcount_mutex); ret = psp_tee_process_cmd(TEE_CMD_ID_LOAD_TA, (void *)&load_cmd, sizeof(load_cmd), &arg->ret); if (ret) { arg->ret_origin = TEEC_ORIGIN_COMMS; arg->ret = TEEC_ERROR_COMMUNICATION; } else { arg->ret_origin = load_cmd.return_origin; if (arg->ret == TEEC_SUCCESS) { ret = get_ta_refcount(load_cmd.ta_handle); if (!ret) { arg->ret_origin = TEEC_ORIGIN_COMMS; arg->ret = TEEC_ERROR_OUT_OF_MEMORY; /* Unload the TA on error */ unload_cmd.ta_handle = load_cmd.ta_handle; psp_tee_process_cmd(TEE_CMD_ID_UNLOAD_TA, (void *)&unload_cmd, sizeof(unload_cmd), &ret); } else { set_session_id(load_cmd.ta_handle, 0, &arg->session); } } } mutex_unlock(&ta_refcount_mutex); pr_debug("load TA: TA handle = 0x%x, RO = 0x%x, ret = 0x%x\n", load_cmd.ta_handle, arg->ret_origin, arg->ret); return 0; }
linux-master
drivers/tee/amdtee/call.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2015-2021, Linaro Limited */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/delay.h> #include <linux/i2c.h> #include <linux/slab.h> #include <linux/tee_drv.h> #include "optee_private.h" #include "optee_rpc_cmd.h" static void handle_rpc_func_cmd_get_time(struct optee_msg_arg *arg) { struct timespec64 ts; if (arg->num_params != 1) goto bad; if ((arg->params[0].attr & OPTEE_MSG_ATTR_TYPE_MASK) != OPTEE_MSG_ATTR_TYPE_VALUE_OUTPUT) goto bad; ktime_get_real_ts64(&ts); arg->params[0].u.value.a = ts.tv_sec; arg->params[0].u.value.b = ts.tv_nsec; arg->ret = TEEC_SUCCESS; return; bad: arg->ret = TEEC_ERROR_BAD_PARAMETERS; } #if IS_REACHABLE(CONFIG_I2C) static void handle_rpc_func_cmd_i2c_transfer(struct tee_context *ctx, struct optee_msg_arg *arg) { struct optee *optee = tee_get_drvdata(ctx->teedev); struct tee_param *params; struct i2c_adapter *adapter; struct i2c_msg msg = { }; size_t i; int ret = -EOPNOTSUPP; u8 attr[] = { TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INPUT, TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INPUT, TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INOUT, TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_OUTPUT, }; if (arg->num_params != ARRAY_SIZE(attr)) { arg->ret = TEEC_ERROR_BAD_PARAMETERS; return; } params = kmalloc_array(arg->num_params, sizeof(struct tee_param), GFP_KERNEL); if (!params) { arg->ret = TEEC_ERROR_OUT_OF_MEMORY; return; } if (optee->ops->from_msg_param(optee, params, arg->num_params, arg->params)) goto bad; for (i = 0; i < arg->num_params; i++) { if (params[i].attr != attr[i]) goto bad; } adapter = i2c_get_adapter(params[0].u.value.b); if (!adapter) goto bad; if (params[1].u.value.a & OPTEE_RPC_I2C_FLAGS_TEN_BIT) { if (!i2c_check_functionality(adapter, I2C_FUNC_10BIT_ADDR)) { i2c_put_adapter(adapter); goto bad; } msg.flags = I2C_M_TEN; } msg.addr = params[0].u.value.c; msg.buf = params[2].u.memref.shm->kaddr; msg.len = params[2].u.memref.size; switch (params[0].u.value.a) { case OPTEE_RPC_I2C_TRANSFER_RD: msg.flags |= I2C_M_RD; break; case OPTEE_RPC_I2C_TRANSFER_WR: break; default: i2c_put_adapter(adapter); goto bad; } ret = i2c_transfer(adapter, &msg, 1); if (ret < 0) { arg->ret = TEEC_ERROR_COMMUNICATION; } else { params[3].u.value.a = msg.len; if (optee->ops->to_msg_param(optee, arg->params, arg->num_params, params)) arg->ret = TEEC_ERROR_BAD_PARAMETERS; else arg->ret = TEEC_SUCCESS; } i2c_put_adapter(adapter); kfree(params); return; bad: kfree(params); arg->ret = TEEC_ERROR_BAD_PARAMETERS; } #else static void handle_rpc_func_cmd_i2c_transfer(struct tee_context *ctx, struct optee_msg_arg *arg) { arg->ret = TEEC_ERROR_NOT_SUPPORTED; } #endif static void handle_rpc_func_cmd_wq(struct optee *optee, struct optee_msg_arg *arg) { if (arg->num_params != 1) goto bad; if ((arg->params[0].attr & OPTEE_MSG_ATTR_TYPE_MASK) != OPTEE_MSG_ATTR_TYPE_VALUE_INPUT) goto bad; switch (arg->params[0].u.value.a) { case OPTEE_RPC_NOTIFICATION_WAIT: if (optee_notif_wait(optee, arg->params[0].u.value.b)) goto bad; break; case OPTEE_RPC_NOTIFICATION_SEND: if (optee_notif_send(optee, arg->params[0].u.value.b)) goto bad; break; default: goto bad; } arg->ret = TEEC_SUCCESS; return; bad: arg->ret = TEEC_ERROR_BAD_PARAMETERS; } static void handle_rpc_func_cmd_wait(struct optee_msg_arg *arg) { u32 msec_to_wait; if (arg->num_params != 1) goto bad; if ((arg->params[0].attr & OPTEE_MSG_ATTR_TYPE_MASK) != OPTEE_MSG_ATTR_TYPE_VALUE_INPUT) goto bad; msec_to_wait = arg->params[0].u.value.a; /* Go to interruptible sleep */ msleep_interruptible(msec_to_wait); arg->ret = TEEC_SUCCESS; return; bad: arg->ret = TEEC_ERROR_BAD_PARAMETERS; } static void handle_rpc_supp_cmd(struct tee_context *ctx, struct optee *optee, struct optee_msg_arg *arg) { struct tee_param *params; arg->ret_origin = TEEC_ORIGIN_COMMS; params = kmalloc_array(arg->num_params, sizeof(struct tee_param), GFP_KERNEL); if (!params) { arg->ret = TEEC_ERROR_OUT_OF_MEMORY; return; } if (optee->ops->from_msg_param(optee, params, arg->num_params, arg->params)) { arg->ret = TEEC_ERROR_BAD_PARAMETERS; goto out; } arg->ret = optee_supp_thrd_req(ctx, arg->cmd, arg->num_params, params); if (optee->ops->to_msg_param(optee, arg->params, arg->num_params, params)) arg->ret = TEEC_ERROR_BAD_PARAMETERS; out: kfree(params); } struct tee_shm *optee_rpc_cmd_alloc_suppl(struct tee_context *ctx, size_t sz) { u32 ret; struct tee_param param; struct optee *optee = tee_get_drvdata(ctx->teedev); struct tee_shm *shm; param.attr = TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INOUT; param.u.value.a = OPTEE_RPC_SHM_TYPE_APPL; param.u.value.b = sz; param.u.value.c = 0; ret = optee_supp_thrd_req(ctx, OPTEE_RPC_CMD_SHM_ALLOC, 1, &param); if (ret) return ERR_PTR(-ENOMEM); mutex_lock(&optee->supp.mutex); /* Increases count as secure world doesn't have a reference */ shm = tee_shm_get_from_id(optee->supp.ctx, param.u.value.c); mutex_unlock(&optee->supp.mutex); return shm; } void optee_rpc_cmd_free_suppl(struct tee_context *ctx, struct tee_shm *shm) { struct tee_param param; param.attr = TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INOUT; param.u.value.a = OPTEE_RPC_SHM_TYPE_APPL; param.u.value.b = tee_shm_get_id(shm); param.u.value.c = 0; /* * Match the tee_shm_get_from_id() in cmd_alloc_suppl() as secure * world has released its reference. * * It's better to do this before sending the request to supplicant * as we'd like to let the process doing the initial allocation to * do release the last reference too in order to avoid stacking * many pending fput() on the client process. This could otherwise * happen if secure world does many allocate and free in a single * invoke. */ tee_shm_put(shm); optee_supp_thrd_req(ctx, OPTEE_RPC_CMD_SHM_FREE, 1, &param); } void optee_rpc_cmd(struct tee_context *ctx, struct optee *optee, struct optee_msg_arg *arg) { switch (arg->cmd) { case OPTEE_RPC_CMD_GET_TIME: handle_rpc_func_cmd_get_time(arg); break; case OPTEE_RPC_CMD_NOTIFICATION: handle_rpc_func_cmd_wq(optee, arg); break; case OPTEE_RPC_CMD_SUSPEND: handle_rpc_func_cmd_wait(arg); break; case OPTEE_RPC_CMD_I2C_TRANSFER: handle_rpc_func_cmd_i2c_transfer(ctx, arg); break; default: handle_rpc_supp_cmd(ctx, optee, arg); } }
linux-master
drivers/tee/optee/rpc.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2015-2021, Linaro Limited * Copyright (c) 2016, EPAM Systems */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/arm-smccc.h> #include <linux/cpuhotplug.h> #include <linux/errno.h> #include <linux/firmware.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/irqdomain.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/of.h> #include <linux/of_irq.h> #include <linux/of_platform.h> #include <linux/platform_device.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/tee_drv.h> #include <linux/types.h> #include <linux/workqueue.h> #include "optee_private.h" #include "optee_smc.h" #include "optee_rpc_cmd.h" #include <linux/kmemleak.h> #define CREATE_TRACE_POINTS #include "optee_trace.h" /* * This file implement the SMC ABI used when communicating with secure world * OP-TEE OS via raw SMCs. * This file is divided into the following sections: * 1. Convert between struct tee_param and struct optee_msg_param * 2. Low level support functions to register shared memory in secure world * 3. Dynamic shared memory pool based on alloc_pages() * 4. Do a normal scheduled call into secure world * 5. Asynchronous notification * 6. Driver initialization. */ /* * A typical OP-TEE private shm allocation is 224 bytes (argument struct * with 6 parameters, needed for open session). So with an alignment of 512 * we'll waste a bit more than 50%. However, it's only expected that we'll * have a handful of these structs allocated at a time. Most memory will * be allocated aligned to the page size, So all in all this should scale * up and down quite well. */ #define OPTEE_MIN_STATIC_POOL_ALIGN 9 /* 512 bytes aligned */ /* SMC ABI considers at most a single TEE firmware */ static unsigned int pcpu_irq_num; static int optee_cpuhp_enable_pcpu_irq(unsigned int cpu) { enable_percpu_irq(pcpu_irq_num, IRQ_TYPE_NONE); return 0; } static int optee_cpuhp_disable_pcpu_irq(unsigned int cpu) { disable_percpu_irq(pcpu_irq_num); return 0; } /* * 1. Convert between struct tee_param and struct optee_msg_param * * optee_from_msg_param() and optee_to_msg_param() are the main * functions. */ static int from_msg_param_tmp_mem(struct tee_param *p, u32 attr, const struct optee_msg_param *mp) { struct tee_shm *shm; phys_addr_t pa; int rc; p->attr = TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT + attr - OPTEE_MSG_ATTR_TYPE_TMEM_INPUT; p->u.memref.size = mp->u.tmem.size; shm = (struct tee_shm *)(unsigned long)mp->u.tmem.shm_ref; if (!shm) { p->u.memref.shm_offs = 0; p->u.memref.shm = NULL; return 0; } rc = tee_shm_get_pa(shm, 0, &pa); if (rc) return rc; p->u.memref.shm_offs = mp->u.tmem.buf_ptr - pa; p->u.memref.shm = shm; return 0; } static void from_msg_param_reg_mem(struct tee_param *p, u32 attr, const struct optee_msg_param *mp) { struct tee_shm *shm; p->attr = TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT + attr - OPTEE_MSG_ATTR_TYPE_RMEM_INPUT; p->u.memref.size = mp->u.rmem.size; shm = (struct tee_shm *)(unsigned long)mp->u.rmem.shm_ref; if (shm) { p->u.memref.shm_offs = mp->u.rmem.offs; p->u.memref.shm = shm; } else { p->u.memref.shm_offs = 0; p->u.memref.shm = NULL; } } /** * optee_from_msg_param() - convert from OPTEE_MSG parameters to * struct tee_param * @optee: main service struct * @params: subsystem internal parameter representation * @num_params: number of elements in the parameter arrays * @msg_params: OPTEE_MSG parameters * Returns 0 on success or <0 on failure */ static int optee_from_msg_param(struct optee *optee, struct tee_param *params, size_t num_params, const struct optee_msg_param *msg_params) { int rc; size_t n; for (n = 0; n < num_params; n++) { struct tee_param *p = params + n; const struct optee_msg_param *mp = msg_params + n; u32 attr = mp->attr & OPTEE_MSG_ATTR_TYPE_MASK; switch (attr) { case OPTEE_MSG_ATTR_TYPE_NONE: p->attr = TEE_IOCTL_PARAM_ATTR_TYPE_NONE; memset(&p->u, 0, sizeof(p->u)); break; case OPTEE_MSG_ATTR_TYPE_VALUE_INPUT: case OPTEE_MSG_ATTR_TYPE_VALUE_OUTPUT: case OPTEE_MSG_ATTR_TYPE_VALUE_INOUT: optee_from_msg_param_value(p, attr, mp); break; case OPTEE_MSG_ATTR_TYPE_TMEM_INPUT: case OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT: case OPTEE_MSG_ATTR_TYPE_TMEM_INOUT: rc = from_msg_param_tmp_mem(p, attr, mp); if (rc) return rc; break; case OPTEE_MSG_ATTR_TYPE_RMEM_INPUT: case OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT: case OPTEE_MSG_ATTR_TYPE_RMEM_INOUT: from_msg_param_reg_mem(p, attr, mp); break; default: return -EINVAL; } } return 0; } static int to_msg_param_tmp_mem(struct optee_msg_param *mp, const struct tee_param *p) { int rc; phys_addr_t pa; mp->attr = OPTEE_MSG_ATTR_TYPE_TMEM_INPUT + p->attr - TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT; mp->u.tmem.shm_ref = (unsigned long)p->u.memref.shm; mp->u.tmem.size = p->u.memref.size; if (!p->u.memref.shm) { mp->u.tmem.buf_ptr = 0; return 0; } rc = tee_shm_get_pa(p->u.memref.shm, p->u.memref.shm_offs, &pa); if (rc) return rc; mp->u.tmem.buf_ptr = pa; mp->attr |= OPTEE_MSG_ATTR_CACHE_PREDEFINED << OPTEE_MSG_ATTR_CACHE_SHIFT; return 0; } static int to_msg_param_reg_mem(struct optee_msg_param *mp, const struct tee_param *p) { mp->attr = OPTEE_MSG_ATTR_TYPE_RMEM_INPUT + p->attr - TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT; mp->u.rmem.shm_ref = (unsigned long)p->u.memref.shm; mp->u.rmem.size = p->u.memref.size; mp->u.rmem.offs = p->u.memref.shm_offs; return 0; } /** * optee_to_msg_param() - convert from struct tee_params to OPTEE_MSG parameters * @optee: main service struct * @msg_params: OPTEE_MSG parameters * @num_params: number of elements in the parameter arrays * @params: subsystem itnernal parameter representation * Returns 0 on success or <0 on failure */ static int optee_to_msg_param(struct optee *optee, struct optee_msg_param *msg_params, size_t num_params, const struct tee_param *params) { int rc; size_t n; for (n = 0; n < num_params; n++) { const struct tee_param *p = params + n; struct optee_msg_param *mp = msg_params + n; switch (p->attr) { case TEE_IOCTL_PARAM_ATTR_TYPE_NONE: mp->attr = TEE_IOCTL_PARAM_ATTR_TYPE_NONE; memset(&mp->u, 0, sizeof(mp->u)); break; case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_OUTPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INOUT: optee_to_msg_param_value(mp, p); break; case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_OUTPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INOUT: if (tee_shm_is_dynamic(p->u.memref.shm)) rc = to_msg_param_reg_mem(mp, p); else rc = to_msg_param_tmp_mem(mp, p); if (rc) return rc; break; default: return -EINVAL; } } return 0; } /* * 2. Low level support functions to register shared memory in secure world * * Functions to enable/disable shared memory caching in secure world, that * is, lazy freeing of previously allocated shared memory. Freeing is * performed when a request has been compled. * * Functions to register and unregister shared memory both for normal * clients and for tee-supplicant. */ /** * optee_enable_shm_cache() - Enables caching of some shared memory allocation * in OP-TEE * @optee: main service struct */ static void optee_enable_shm_cache(struct optee *optee) { struct optee_call_waiter w; /* We need to retry until secure world isn't busy. */ optee_cq_wait_init(&optee->call_queue, &w); while (true) { struct arm_smccc_res res; optee->smc.invoke_fn(OPTEE_SMC_ENABLE_SHM_CACHE, 0, 0, 0, 0, 0, 0, 0, &res); if (res.a0 == OPTEE_SMC_RETURN_OK) break; optee_cq_wait_for_completion(&optee->call_queue, &w); } optee_cq_wait_final(&optee->call_queue, &w); } /** * __optee_disable_shm_cache() - Disables caching of some shared memory * allocation in OP-TEE * @optee: main service struct * @is_mapped: true if the cached shared memory addresses were mapped by this * kernel, are safe to dereference, and should be freed */ static void __optee_disable_shm_cache(struct optee *optee, bool is_mapped) { struct optee_call_waiter w; /* We need to retry until secure world isn't busy. */ optee_cq_wait_init(&optee->call_queue, &w); while (true) { union { struct arm_smccc_res smccc; struct optee_smc_disable_shm_cache_result result; } res; optee->smc.invoke_fn(OPTEE_SMC_DISABLE_SHM_CACHE, 0, 0, 0, 0, 0, 0, 0, &res.smccc); if (res.result.status == OPTEE_SMC_RETURN_ENOTAVAIL) break; /* All shm's freed */ if (res.result.status == OPTEE_SMC_RETURN_OK) { struct tee_shm *shm; /* * Shared memory references that were not mapped by * this kernel must be ignored to prevent a crash. */ if (!is_mapped) continue; shm = reg_pair_to_ptr(res.result.shm_upper32, res.result.shm_lower32); tee_shm_free(shm); } else { optee_cq_wait_for_completion(&optee->call_queue, &w); } } optee_cq_wait_final(&optee->call_queue, &w); } /** * optee_disable_shm_cache() - Disables caching of mapped shared memory * allocations in OP-TEE * @optee: main service struct */ static void optee_disable_shm_cache(struct optee *optee) { return __optee_disable_shm_cache(optee, true); } /** * optee_disable_unmapped_shm_cache() - Disables caching of shared memory * allocations in OP-TEE which are not * currently mapped * @optee: main service struct */ static void optee_disable_unmapped_shm_cache(struct optee *optee) { return __optee_disable_shm_cache(optee, false); } #define PAGELIST_ENTRIES_PER_PAGE \ ((OPTEE_MSG_NONCONTIG_PAGE_SIZE / sizeof(u64)) - 1) /* * The final entry in each pagelist page is a pointer to the next * pagelist page. */ static size_t get_pages_list_size(size_t num_entries) { int pages = DIV_ROUND_UP(num_entries, PAGELIST_ENTRIES_PER_PAGE); return pages * OPTEE_MSG_NONCONTIG_PAGE_SIZE; } static u64 *optee_allocate_pages_list(size_t num_entries) { return alloc_pages_exact(get_pages_list_size(num_entries), GFP_KERNEL); } static void optee_free_pages_list(void *list, size_t num_entries) { free_pages_exact(list, get_pages_list_size(num_entries)); } /** * optee_fill_pages_list() - write list of user pages to given shared * buffer. * * @dst: page-aligned buffer where list of pages will be stored * @pages: array of pages that represents shared buffer * @num_pages: number of entries in @pages * @page_offset: offset of user buffer from page start * * @dst should be big enough to hold list of user page addresses and * links to the next pages of buffer */ static void optee_fill_pages_list(u64 *dst, struct page **pages, int num_pages, size_t page_offset) { int n = 0; phys_addr_t optee_page; /* * Refer to OPTEE_MSG_ATTR_NONCONTIG description in optee_msg.h * for details. */ struct { u64 pages_list[PAGELIST_ENTRIES_PER_PAGE]; u64 next_page_data; } *pages_data; /* * Currently OP-TEE uses 4k page size and it does not looks * like this will change in the future. On other hand, there are * no know ARM architectures with page size < 4k. * Thus the next built assert looks redundant. But the following * code heavily relies on this assumption, so it is better be * safe than sorry. */ BUILD_BUG_ON(PAGE_SIZE < OPTEE_MSG_NONCONTIG_PAGE_SIZE); pages_data = (void *)dst; /* * If linux page is bigger than 4k, and user buffer offset is * larger than 4k/8k/12k/etc this will skip first 4k pages, * because they bear no value data for OP-TEE. */ optee_page = page_to_phys(*pages) + round_down(page_offset, OPTEE_MSG_NONCONTIG_PAGE_SIZE); while (true) { pages_data->pages_list[n++] = optee_page; if (n == PAGELIST_ENTRIES_PER_PAGE) { pages_data->next_page_data = virt_to_phys(pages_data + 1); pages_data++; n = 0; } optee_page += OPTEE_MSG_NONCONTIG_PAGE_SIZE; if (!(optee_page & ~PAGE_MASK)) { if (!--num_pages) break; pages++; optee_page = page_to_phys(*pages); } } } static int optee_shm_register(struct tee_context *ctx, struct tee_shm *shm, struct page **pages, size_t num_pages, unsigned long start) { struct optee *optee = tee_get_drvdata(ctx->teedev); struct optee_msg_arg *msg_arg; struct tee_shm *shm_arg; u64 *pages_list; size_t sz; int rc; if (!num_pages) return -EINVAL; rc = optee_check_mem_type(start, num_pages); if (rc) return rc; pages_list = optee_allocate_pages_list(num_pages); if (!pages_list) return -ENOMEM; /* * We're about to register shared memory we can't register shared * memory for this request or there's a catch-22. * * So in this we'll have to do the good old temporary private * allocation instead of using optee_get_msg_arg(). */ sz = optee_msg_arg_size(optee->rpc_param_count); shm_arg = tee_shm_alloc_priv_buf(ctx, sz); if (IS_ERR(shm_arg)) { rc = PTR_ERR(shm_arg); goto out; } msg_arg = tee_shm_get_va(shm_arg, 0); if (IS_ERR(msg_arg)) { rc = PTR_ERR(msg_arg); goto out; } optee_fill_pages_list(pages_list, pages, num_pages, tee_shm_get_page_offset(shm)); memset(msg_arg, 0, OPTEE_MSG_GET_ARG_SIZE(1)); msg_arg->num_params = 1; msg_arg->cmd = OPTEE_MSG_CMD_REGISTER_SHM; msg_arg->params->attr = OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT | OPTEE_MSG_ATTR_NONCONTIG; msg_arg->params->u.tmem.shm_ref = (unsigned long)shm; msg_arg->params->u.tmem.size = tee_shm_get_size(shm); /* * In the least bits of msg_arg->params->u.tmem.buf_ptr we * store buffer offset from 4k page, as described in OP-TEE ABI. */ msg_arg->params->u.tmem.buf_ptr = virt_to_phys(pages_list) | (tee_shm_get_page_offset(shm) & (OPTEE_MSG_NONCONTIG_PAGE_SIZE - 1)); if (optee->ops->do_call_with_arg(ctx, shm_arg, 0) || msg_arg->ret != TEEC_SUCCESS) rc = -EINVAL; tee_shm_free(shm_arg); out: optee_free_pages_list(pages_list, num_pages); return rc; } static int optee_shm_unregister(struct tee_context *ctx, struct tee_shm *shm) { struct optee *optee = tee_get_drvdata(ctx->teedev); struct optee_msg_arg *msg_arg; struct tee_shm *shm_arg; int rc = 0; size_t sz; /* * We're about to unregister shared memory and we may not be able * register shared memory for this request in case we're called * from optee_shm_arg_cache_uninit(). * * So in order to keep things simple in this function just as in * optee_shm_register() we'll use temporary private allocation * instead of using optee_get_msg_arg(). */ sz = optee_msg_arg_size(optee->rpc_param_count); shm_arg = tee_shm_alloc_priv_buf(ctx, sz); if (IS_ERR(shm_arg)) return PTR_ERR(shm_arg); msg_arg = tee_shm_get_va(shm_arg, 0); if (IS_ERR(msg_arg)) { rc = PTR_ERR(msg_arg); goto out; } memset(msg_arg, 0, sz); msg_arg->num_params = 1; msg_arg->cmd = OPTEE_MSG_CMD_UNREGISTER_SHM; msg_arg->params[0].attr = OPTEE_MSG_ATTR_TYPE_RMEM_INPUT; msg_arg->params[0].u.rmem.shm_ref = (unsigned long)shm; if (optee->ops->do_call_with_arg(ctx, shm_arg, 0) || msg_arg->ret != TEEC_SUCCESS) rc = -EINVAL; out: tee_shm_free(shm_arg); return rc; } static int optee_shm_register_supp(struct tee_context *ctx, struct tee_shm *shm, struct page **pages, size_t num_pages, unsigned long start) { /* * We don't want to register supplicant memory in OP-TEE. * Instead information about it will be passed in RPC code. */ return optee_check_mem_type(start, num_pages); } static int optee_shm_unregister_supp(struct tee_context *ctx, struct tee_shm *shm) { return 0; } /* * 3. Dynamic shared memory pool based on alloc_pages() * * Implements an OP-TEE specific shared memory pool which is used * when dynamic shared memory is supported by secure world. * * The main function is optee_shm_pool_alloc_pages(). */ static int pool_op_alloc(struct tee_shm_pool *pool, struct tee_shm *shm, size_t size, size_t align) { /* * Shared memory private to the OP-TEE driver doesn't need * to be registered with OP-TEE. */ if (shm->flags & TEE_SHM_PRIV) return optee_pool_op_alloc_helper(pool, shm, size, align, NULL); return optee_pool_op_alloc_helper(pool, shm, size, align, optee_shm_register); } static void pool_op_free(struct tee_shm_pool *pool, struct tee_shm *shm) { if (!(shm->flags & TEE_SHM_PRIV)) optee_pool_op_free_helper(pool, shm, optee_shm_unregister); else optee_pool_op_free_helper(pool, shm, NULL); } static void pool_op_destroy_pool(struct tee_shm_pool *pool) { kfree(pool); } static const struct tee_shm_pool_ops pool_ops = { .alloc = pool_op_alloc, .free = pool_op_free, .destroy_pool = pool_op_destroy_pool, }; /** * optee_shm_pool_alloc_pages() - create page-based allocator pool * * This pool is used when OP-TEE supports dymanic SHM. In this case * command buffers and such are allocated from kernel's own memory. */ static struct tee_shm_pool *optee_shm_pool_alloc_pages(void) { struct tee_shm_pool *pool = kzalloc(sizeof(*pool), GFP_KERNEL); if (!pool) return ERR_PTR(-ENOMEM); pool->ops = &pool_ops; return pool; } /* * 4. Do a normal scheduled call into secure world * * The function optee_smc_do_call_with_arg() performs a normal scheduled * call into secure world. During this call may normal world request help * from normal world using RPCs, Remote Procedure Calls. This includes * delivery of non-secure interrupts to for instance allow rescheduling of * the current task. */ static void handle_rpc_func_cmd_shm_free(struct tee_context *ctx, struct optee_msg_arg *arg) { struct tee_shm *shm; arg->ret_origin = TEEC_ORIGIN_COMMS; if (arg->num_params != 1 || arg->params[0].attr != OPTEE_MSG_ATTR_TYPE_VALUE_INPUT) { arg->ret = TEEC_ERROR_BAD_PARAMETERS; return; } shm = (struct tee_shm *)(unsigned long)arg->params[0].u.value.b; switch (arg->params[0].u.value.a) { case OPTEE_RPC_SHM_TYPE_APPL: optee_rpc_cmd_free_suppl(ctx, shm); break; case OPTEE_RPC_SHM_TYPE_KERNEL: tee_shm_free(shm); break; default: arg->ret = TEEC_ERROR_BAD_PARAMETERS; } arg->ret = TEEC_SUCCESS; } static void handle_rpc_func_cmd_shm_alloc(struct tee_context *ctx, struct optee *optee, struct optee_msg_arg *arg, struct optee_call_ctx *call_ctx) { phys_addr_t pa; struct tee_shm *shm; size_t sz; size_t n; arg->ret_origin = TEEC_ORIGIN_COMMS; if (!arg->num_params || arg->params[0].attr != OPTEE_MSG_ATTR_TYPE_VALUE_INPUT) { arg->ret = TEEC_ERROR_BAD_PARAMETERS; return; } for (n = 1; n < arg->num_params; n++) { if (arg->params[n].attr != OPTEE_MSG_ATTR_TYPE_NONE) { arg->ret = TEEC_ERROR_BAD_PARAMETERS; return; } } sz = arg->params[0].u.value.b; switch (arg->params[0].u.value.a) { case OPTEE_RPC_SHM_TYPE_APPL: shm = optee_rpc_cmd_alloc_suppl(ctx, sz); break; case OPTEE_RPC_SHM_TYPE_KERNEL: shm = tee_shm_alloc_priv_buf(optee->ctx, sz); break; default: arg->ret = TEEC_ERROR_BAD_PARAMETERS; return; } if (IS_ERR(shm)) { arg->ret = TEEC_ERROR_OUT_OF_MEMORY; return; } if (tee_shm_get_pa(shm, 0, &pa)) { arg->ret = TEEC_ERROR_BAD_PARAMETERS; goto bad; } sz = tee_shm_get_size(shm); if (tee_shm_is_dynamic(shm)) { struct page **pages; u64 *pages_list; size_t page_num; pages = tee_shm_get_pages(shm, &page_num); if (!pages || !page_num) { arg->ret = TEEC_ERROR_OUT_OF_MEMORY; goto bad; } pages_list = optee_allocate_pages_list(page_num); if (!pages_list) { arg->ret = TEEC_ERROR_OUT_OF_MEMORY; goto bad; } call_ctx->pages_list = pages_list; call_ctx->num_entries = page_num; arg->params[0].attr = OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT | OPTEE_MSG_ATTR_NONCONTIG; /* * In the least bits of u.tmem.buf_ptr we store buffer offset * from 4k page, as described in OP-TEE ABI. */ arg->params[0].u.tmem.buf_ptr = virt_to_phys(pages_list) | (tee_shm_get_page_offset(shm) & (OPTEE_MSG_NONCONTIG_PAGE_SIZE - 1)); arg->params[0].u.tmem.size = tee_shm_get_size(shm); arg->params[0].u.tmem.shm_ref = (unsigned long)shm; optee_fill_pages_list(pages_list, pages, page_num, tee_shm_get_page_offset(shm)); } else { arg->params[0].attr = OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT; arg->params[0].u.tmem.buf_ptr = pa; arg->params[0].u.tmem.size = sz; arg->params[0].u.tmem.shm_ref = (unsigned long)shm; } arg->ret = TEEC_SUCCESS; return; bad: tee_shm_free(shm); } static void free_pages_list(struct optee_call_ctx *call_ctx) { if (call_ctx->pages_list) { optee_free_pages_list(call_ctx->pages_list, call_ctx->num_entries); call_ctx->pages_list = NULL; call_ctx->num_entries = 0; } } static void optee_rpc_finalize_call(struct optee_call_ctx *call_ctx) { free_pages_list(call_ctx); } static void handle_rpc_func_cmd(struct tee_context *ctx, struct optee *optee, struct optee_msg_arg *arg, struct optee_call_ctx *call_ctx) { switch (arg->cmd) { case OPTEE_RPC_CMD_SHM_ALLOC: free_pages_list(call_ctx); handle_rpc_func_cmd_shm_alloc(ctx, optee, arg, call_ctx); break; case OPTEE_RPC_CMD_SHM_FREE: handle_rpc_func_cmd_shm_free(ctx, arg); break; default: optee_rpc_cmd(ctx, optee, arg); } } /** * optee_handle_rpc() - handle RPC from secure world * @ctx: context doing the RPC * @param: value of registers for the RPC * @call_ctx: call context. Preserved during one OP-TEE invocation * * Result of RPC is written back into @param. */ static void optee_handle_rpc(struct tee_context *ctx, struct optee_msg_arg *rpc_arg, struct optee_rpc_param *param, struct optee_call_ctx *call_ctx) { struct tee_device *teedev = ctx->teedev; struct optee *optee = tee_get_drvdata(teedev); struct optee_msg_arg *arg; struct tee_shm *shm; phys_addr_t pa; switch (OPTEE_SMC_RETURN_GET_RPC_FUNC(param->a0)) { case OPTEE_SMC_RPC_FUNC_ALLOC: shm = tee_shm_alloc_priv_buf(optee->ctx, param->a1); if (!IS_ERR(shm) && !tee_shm_get_pa(shm, 0, &pa)) { reg_pair_from_64(&param->a1, &param->a2, pa); reg_pair_from_64(&param->a4, &param->a5, (unsigned long)shm); } else { param->a1 = 0; param->a2 = 0; param->a4 = 0; param->a5 = 0; } kmemleak_not_leak(shm); break; case OPTEE_SMC_RPC_FUNC_FREE: shm = reg_pair_to_ptr(param->a1, param->a2); tee_shm_free(shm); break; case OPTEE_SMC_RPC_FUNC_FOREIGN_INTR: /* * A foreign interrupt was raised while secure world was * executing, since they are handled in Linux a dummy RPC is * performed to let Linux take the interrupt through the normal * vector. */ break; case OPTEE_SMC_RPC_FUNC_CMD: if (rpc_arg) { arg = rpc_arg; } else { shm = reg_pair_to_ptr(param->a1, param->a2); arg = tee_shm_get_va(shm, 0); if (IS_ERR(arg)) { pr_err("%s: tee_shm_get_va %p failed\n", __func__, shm); break; } } handle_rpc_func_cmd(ctx, optee, arg, call_ctx); break; default: pr_warn("Unknown RPC func 0x%x\n", (u32)OPTEE_SMC_RETURN_GET_RPC_FUNC(param->a0)); break; } param->a0 = OPTEE_SMC_CALL_RETURN_FROM_RPC; } /** * optee_smc_do_call_with_arg() - Do an SMC to OP-TEE in secure world * @ctx: calling context * @shm: shared memory holding the message to pass to secure world * @offs: offset of the message in @shm * * Does and SMC to OP-TEE in secure world and handles eventual resulting * Remote Procedure Calls (RPC) from OP-TEE. * * Returns return code from secure world, 0 is OK */ static int optee_smc_do_call_with_arg(struct tee_context *ctx, struct tee_shm *shm, u_int offs) { struct optee *optee = tee_get_drvdata(ctx->teedev); struct optee_call_waiter w; struct optee_rpc_param param = { }; struct optee_call_ctx call_ctx = { }; struct optee_msg_arg *rpc_arg = NULL; int rc; if (optee->rpc_param_count) { struct optee_msg_arg *arg; unsigned int rpc_arg_offs; arg = tee_shm_get_va(shm, offs); if (IS_ERR(arg)) return PTR_ERR(arg); rpc_arg_offs = OPTEE_MSG_GET_ARG_SIZE(arg->num_params); rpc_arg = tee_shm_get_va(shm, offs + rpc_arg_offs); if (IS_ERR(rpc_arg)) return PTR_ERR(rpc_arg); } if (rpc_arg && tee_shm_is_dynamic(shm)) { param.a0 = OPTEE_SMC_CALL_WITH_REGD_ARG; reg_pair_from_64(&param.a1, &param.a2, (u_long)shm); param.a3 = offs; } else { phys_addr_t parg; rc = tee_shm_get_pa(shm, offs, &parg); if (rc) return rc; if (rpc_arg) param.a0 = OPTEE_SMC_CALL_WITH_RPC_ARG; else param.a0 = OPTEE_SMC_CALL_WITH_ARG; reg_pair_from_64(&param.a1, &param.a2, parg); } /* Initialize waiter */ optee_cq_wait_init(&optee->call_queue, &w); while (true) { struct arm_smccc_res res; trace_optee_invoke_fn_begin(&param); optee->smc.invoke_fn(param.a0, param.a1, param.a2, param.a3, param.a4, param.a5, param.a6, param.a7, &res); trace_optee_invoke_fn_end(&param, &res); if (res.a0 == OPTEE_SMC_RETURN_ETHREAD_LIMIT) { /* * Out of threads in secure world, wait for a thread * become available. */ optee_cq_wait_for_completion(&optee->call_queue, &w); } else if (OPTEE_SMC_RETURN_IS_RPC(res.a0)) { cond_resched(); param.a0 = res.a0; param.a1 = res.a1; param.a2 = res.a2; param.a3 = res.a3; optee_handle_rpc(ctx, rpc_arg, &param, &call_ctx); } else { rc = res.a0; break; } } optee_rpc_finalize_call(&call_ctx); /* * We're done with our thread in secure world, if there's any * thread waiters wake up one. */ optee_cq_wait_final(&optee->call_queue, &w); return rc; } static int simple_call_with_arg(struct tee_context *ctx, u32 cmd) { struct optee_shm_arg_entry *entry; struct optee_msg_arg *msg_arg; struct tee_shm *shm; u_int offs; msg_arg = optee_get_msg_arg(ctx, 0, &entry, &shm, &offs); if (IS_ERR(msg_arg)) return PTR_ERR(msg_arg); msg_arg->cmd = cmd; optee_smc_do_call_with_arg(ctx, shm, offs); optee_free_msg_arg(ctx, entry, offs); return 0; } static int optee_smc_do_bottom_half(struct tee_context *ctx) { return simple_call_with_arg(ctx, OPTEE_MSG_CMD_DO_BOTTOM_HALF); } static int optee_smc_stop_async_notif(struct tee_context *ctx) { return simple_call_with_arg(ctx, OPTEE_MSG_CMD_STOP_ASYNC_NOTIF); } /* * 5. Asynchronous notification */ static u32 get_async_notif_value(optee_invoke_fn *invoke_fn, bool *value_valid, bool *value_pending) { struct arm_smccc_res res; invoke_fn(OPTEE_SMC_GET_ASYNC_NOTIF_VALUE, 0, 0, 0, 0, 0, 0, 0, &res); if (res.a0) { *value_valid = false; return 0; } *value_valid = (res.a2 & OPTEE_SMC_ASYNC_NOTIF_VALUE_VALID); *value_pending = (res.a2 & OPTEE_SMC_ASYNC_NOTIF_VALUE_PENDING); return res.a1; } static irqreturn_t irq_handler(struct optee *optee) { bool do_bottom_half = false; bool value_valid; bool value_pending; u32 value; do { value = get_async_notif_value(optee->smc.invoke_fn, &value_valid, &value_pending); if (!value_valid) break; if (value == OPTEE_SMC_ASYNC_NOTIF_VALUE_DO_BOTTOM_HALF) do_bottom_half = true; else optee_notif_send(optee, value); } while (value_pending); if (do_bottom_half) return IRQ_WAKE_THREAD; return IRQ_HANDLED; } static irqreturn_t notif_irq_handler(int irq, void *dev_id) { struct optee *optee = dev_id; return irq_handler(optee); } static irqreturn_t notif_irq_thread_fn(int irq, void *dev_id) { struct optee *optee = dev_id; optee_smc_do_bottom_half(optee->ctx); return IRQ_HANDLED; } static int init_irq(struct optee *optee, u_int irq) { int rc; rc = request_threaded_irq(irq, notif_irq_handler, notif_irq_thread_fn, 0, "optee_notification", optee); if (rc) return rc; optee->smc.notif_irq = irq; return 0; } static irqreturn_t notif_pcpu_irq_handler(int irq, void *dev_id) { struct optee_pcpu *pcpu = dev_id; struct optee *optee = pcpu->optee; if (irq_handler(optee) == IRQ_WAKE_THREAD) queue_work(optee->smc.notif_pcpu_wq, &optee->smc.notif_pcpu_work); return IRQ_HANDLED; } static void notif_pcpu_irq_work_fn(struct work_struct *work) { struct optee_smc *optee_smc = container_of(work, struct optee_smc, notif_pcpu_work); struct optee *optee = container_of(optee_smc, struct optee, smc); optee_smc_do_bottom_half(optee->ctx); } static int init_pcpu_irq(struct optee *optee, u_int irq) { struct optee_pcpu __percpu *optee_pcpu; int cpu, rc; optee_pcpu = alloc_percpu(struct optee_pcpu); if (!optee_pcpu) return -ENOMEM; for_each_present_cpu(cpu) per_cpu_ptr(optee_pcpu, cpu)->optee = optee; rc = request_percpu_irq(irq, notif_pcpu_irq_handler, "optee_pcpu_notification", optee_pcpu); if (rc) goto err_free_pcpu; INIT_WORK(&optee->smc.notif_pcpu_work, notif_pcpu_irq_work_fn); optee->smc.notif_pcpu_wq = create_workqueue("optee_pcpu_notification"); if (!optee->smc.notif_pcpu_wq) { rc = -EINVAL; goto err_free_pcpu_irq; } optee->smc.optee_pcpu = optee_pcpu; optee->smc.notif_irq = irq; pcpu_irq_num = irq; rc = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "optee/pcpu-notif:starting", optee_cpuhp_enable_pcpu_irq, optee_cpuhp_disable_pcpu_irq); if (!rc) rc = -EINVAL; if (rc < 0) goto err_free_pcpu_irq; optee->smc.notif_cpuhp_state = rc; return 0; err_free_pcpu_irq: free_percpu_irq(irq, optee_pcpu); err_free_pcpu: free_percpu(optee_pcpu); return rc; } static int optee_smc_notif_init_irq(struct optee *optee, u_int irq) { if (irq_is_percpu_devid(irq)) return init_pcpu_irq(optee, irq); else return init_irq(optee, irq); } static void uninit_pcpu_irq(struct optee *optee) { cpuhp_remove_state(optee->smc.notif_cpuhp_state); destroy_workqueue(optee->smc.notif_pcpu_wq); free_percpu_irq(optee->smc.notif_irq, optee->smc.optee_pcpu); free_percpu(optee->smc.optee_pcpu); } static void optee_smc_notif_uninit_irq(struct optee *optee) { if (optee->smc.sec_caps & OPTEE_SMC_SEC_CAP_ASYNC_NOTIF) { optee_smc_stop_async_notif(optee->ctx); if (optee->smc.notif_irq) { if (irq_is_percpu_devid(optee->smc.notif_irq)) uninit_pcpu_irq(optee); else free_irq(optee->smc.notif_irq, optee); irq_dispose_mapping(optee->smc.notif_irq); } } } /* * 6. Driver initialization * * During driver initialization is secure world probed to find out which * features it supports so the driver can be initialized with a matching * configuration. This involves for instance support for dynamic shared * memory instead of a static memory carvout. */ static void optee_get_version(struct tee_device *teedev, struct tee_ioctl_version_data *vers) { struct tee_ioctl_version_data v = { .impl_id = TEE_IMPL_ID_OPTEE, .impl_caps = TEE_OPTEE_CAP_TZ, .gen_caps = TEE_GEN_CAP_GP, }; struct optee *optee = tee_get_drvdata(teedev); if (optee->smc.sec_caps & OPTEE_SMC_SEC_CAP_DYNAMIC_SHM) v.gen_caps |= TEE_GEN_CAP_REG_MEM; if (optee->smc.sec_caps & OPTEE_SMC_SEC_CAP_MEMREF_NULL) v.gen_caps |= TEE_GEN_CAP_MEMREF_NULL; *vers = v; } static int optee_smc_open(struct tee_context *ctx) { struct optee *optee = tee_get_drvdata(ctx->teedev); u32 sec_caps = optee->smc.sec_caps; return optee_open(ctx, sec_caps & OPTEE_SMC_SEC_CAP_MEMREF_NULL); } static const struct tee_driver_ops optee_clnt_ops = { .get_version = optee_get_version, .open = optee_smc_open, .release = optee_release, .open_session = optee_open_session, .close_session = optee_close_session, .invoke_func = optee_invoke_func, .cancel_req = optee_cancel_req, .shm_register = optee_shm_register, .shm_unregister = optee_shm_unregister, }; static const struct tee_desc optee_clnt_desc = { .name = DRIVER_NAME "-clnt", .ops = &optee_clnt_ops, .owner = THIS_MODULE, }; static const struct tee_driver_ops optee_supp_ops = { .get_version = optee_get_version, .open = optee_smc_open, .release = optee_release_supp, .supp_recv = optee_supp_recv, .supp_send = optee_supp_send, .shm_register = optee_shm_register_supp, .shm_unregister = optee_shm_unregister_supp, }; static const struct tee_desc optee_supp_desc = { .name = DRIVER_NAME "-supp", .ops = &optee_supp_ops, .owner = THIS_MODULE, .flags = TEE_DESC_PRIVILEGED, }; static const struct optee_ops optee_ops = { .do_call_with_arg = optee_smc_do_call_with_arg, .to_msg_param = optee_to_msg_param, .from_msg_param = optee_from_msg_param, }; static int enable_async_notif(optee_invoke_fn *invoke_fn) { struct arm_smccc_res res; invoke_fn(OPTEE_SMC_ENABLE_ASYNC_NOTIF, 0, 0, 0, 0, 0, 0, 0, &res); if (res.a0) return -EINVAL; return 0; } static bool optee_msg_api_uid_is_optee_api(optee_invoke_fn *invoke_fn) { struct arm_smccc_res res; invoke_fn(OPTEE_SMC_CALLS_UID, 0, 0, 0, 0, 0, 0, 0, &res); if (res.a0 == OPTEE_MSG_UID_0 && res.a1 == OPTEE_MSG_UID_1 && res.a2 == OPTEE_MSG_UID_2 && res.a3 == OPTEE_MSG_UID_3) return true; return false; } #ifdef CONFIG_OPTEE_INSECURE_LOAD_IMAGE static bool optee_msg_api_uid_is_optee_image_load(optee_invoke_fn *invoke_fn) { struct arm_smccc_res res; invoke_fn(OPTEE_SMC_CALLS_UID, 0, 0, 0, 0, 0, 0, 0, &res); if (res.a0 == OPTEE_MSG_IMAGE_LOAD_UID_0 && res.a1 == OPTEE_MSG_IMAGE_LOAD_UID_1 && res.a2 == OPTEE_MSG_IMAGE_LOAD_UID_2 && res.a3 == OPTEE_MSG_IMAGE_LOAD_UID_3) return true; return false; } #endif static void optee_msg_get_os_revision(optee_invoke_fn *invoke_fn) { union { struct arm_smccc_res smccc; struct optee_smc_call_get_os_revision_result result; } res = { .result = { .build_id = 0 } }; invoke_fn(OPTEE_SMC_CALL_GET_OS_REVISION, 0, 0, 0, 0, 0, 0, 0, &res.smccc); if (res.result.build_id) pr_info("revision %lu.%lu (%08lx)", res.result.major, res.result.minor, res.result.build_id); else pr_info("revision %lu.%lu", res.result.major, res.result.minor); } static bool optee_msg_api_revision_is_compatible(optee_invoke_fn *invoke_fn) { union { struct arm_smccc_res smccc; struct optee_smc_calls_revision_result result; } res; invoke_fn(OPTEE_SMC_CALLS_REVISION, 0, 0, 0, 0, 0, 0, 0, &res.smccc); if (res.result.major == OPTEE_MSG_REVISION_MAJOR && (int)res.result.minor >= OPTEE_MSG_REVISION_MINOR) return true; return false; } static bool optee_msg_exchange_capabilities(optee_invoke_fn *invoke_fn, u32 *sec_caps, u32 *max_notif_value, unsigned int *rpc_param_count) { union { struct arm_smccc_res smccc; struct optee_smc_exchange_capabilities_result result; } res; u32 a1 = 0; /* * TODO This isn't enough to tell if it's UP system (from kernel * point of view) or not, is_smp() returns the information * needed, but can't be called directly from here. */ if (!IS_ENABLED(CONFIG_SMP) || nr_cpu_ids == 1) a1 |= OPTEE_SMC_NSEC_CAP_UNIPROCESSOR; invoke_fn(OPTEE_SMC_EXCHANGE_CAPABILITIES, a1, 0, 0, 0, 0, 0, 0, &res.smccc); if (res.result.status != OPTEE_SMC_RETURN_OK) return false; *sec_caps = res.result.capabilities; if (*sec_caps & OPTEE_SMC_SEC_CAP_ASYNC_NOTIF) *max_notif_value = res.result.max_notif_value; else *max_notif_value = OPTEE_DEFAULT_MAX_NOTIF_VALUE; if (*sec_caps & OPTEE_SMC_SEC_CAP_RPC_ARG) *rpc_param_count = (u8)res.result.data; else *rpc_param_count = 0; return true; } static struct tee_shm_pool * optee_config_shm_memremap(optee_invoke_fn *invoke_fn, void **memremaped_shm) { union { struct arm_smccc_res smccc; struct optee_smc_get_shm_config_result result; } res; unsigned long vaddr; phys_addr_t paddr; size_t size; phys_addr_t begin; phys_addr_t end; void *va; void *rc; invoke_fn(OPTEE_SMC_GET_SHM_CONFIG, 0, 0, 0, 0, 0, 0, 0, &res.smccc); if (res.result.status != OPTEE_SMC_RETURN_OK) { pr_err("static shm service not available\n"); return ERR_PTR(-ENOENT); } if (res.result.settings != OPTEE_SMC_SHM_CACHED) { pr_err("only normal cached shared memory supported\n"); return ERR_PTR(-EINVAL); } begin = roundup(res.result.start, PAGE_SIZE); end = rounddown(res.result.start + res.result.size, PAGE_SIZE); paddr = begin; size = end - begin; va = memremap(paddr, size, MEMREMAP_WB); if (!va) { pr_err("shared memory ioremap failed\n"); return ERR_PTR(-EINVAL); } vaddr = (unsigned long)va; rc = tee_shm_pool_alloc_res_mem(vaddr, paddr, size, OPTEE_MIN_STATIC_POOL_ALIGN); if (IS_ERR(rc)) memunmap(va); else *memremaped_shm = va; return rc; } /* Simple wrapper functions to be able to use a function pointer */ static void optee_smccc_smc(unsigned long a0, unsigned long a1, unsigned long a2, unsigned long a3, unsigned long a4, unsigned long a5, unsigned long a6, unsigned long a7, struct arm_smccc_res *res) { arm_smccc_smc(a0, a1, a2, a3, a4, a5, a6, a7, res); } static void optee_smccc_hvc(unsigned long a0, unsigned long a1, unsigned long a2, unsigned long a3, unsigned long a4, unsigned long a5, unsigned long a6, unsigned long a7, struct arm_smccc_res *res) { arm_smccc_hvc(a0, a1, a2, a3, a4, a5, a6, a7, res); } static optee_invoke_fn *get_invoke_func(struct device *dev) { const char *method; pr_info("probing for conduit method.\n"); if (device_property_read_string(dev, "method", &method)) { pr_warn("missing \"method\" property\n"); return ERR_PTR(-ENXIO); } if (!strcmp("hvc", method)) return optee_smccc_hvc; else if (!strcmp("smc", method)) return optee_smccc_smc; pr_warn("invalid \"method\" property: %s\n", method); return ERR_PTR(-EINVAL); } /* optee_remove - Device Removal Routine * @pdev: platform device information struct * * optee_remove is called by platform subsystem to alert the driver * that it should release the device */ static int optee_smc_remove(struct platform_device *pdev) { struct optee *optee = platform_get_drvdata(pdev); /* * Ask OP-TEE to free all cached shared memory objects to decrease * reference counters and also avoid wild pointers in secure world * into the old shared memory range. */ if (!optee->rpc_param_count) optee_disable_shm_cache(optee); optee_smc_notif_uninit_irq(optee); optee_remove_common(optee); if (optee->smc.memremaped_shm) memunmap(optee->smc.memremaped_shm); kfree(optee); return 0; } /* optee_shutdown - Device Removal Routine * @pdev: platform device information struct * * platform_shutdown is called by the platform subsystem to alert * the driver that a shutdown, reboot, or kexec is happening and * device must be disabled. */ static void optee_shutdown(struct platform_device *pdev) { struct optee *optee = platform_get_drvdata(pdev); if (!optee->rpc_param_count) optee_disable_shm_cache(optee); } #ifdef CONFIG_OPTEE_INSECURE_LOAD_IMAGE #define OPTEE_FW_IMAGE "optee/tee.bin" static optee_invoke_fn *cpuhp_invoke_fn; static int optee_cpuhp_probe(unsigned int cpu) { /* * Invoking a call on a CPU will cause OP-TEE to perform the required * setup for that CPU. Just invoke the call to get the UID since that * has no side effects. */ if (optee_msg_api_uid_is_optee_api(cpuhp_invoke_fn)) return 0; else return -EINVAL; } static int optee_load_fw(struct platform_device *pdev, optee_invoke_fn *invoke_fn) { const struct firmware *fw = NULL; struct arm_smccc_res res; phys_addr_t data_pa; u8 *data_buf = NULL; u64 data_size; u32 data_pa_high, data_pa_low; u32 data_size_high, data_size_low; int rc; int hp_state; if (!optee_msg_api_uid_is_optee_image_load(invoke_fn)) return 0; rc = request_firmware(&fw, OPTEE_FW_IMAGE, &pdev->dev); if (rc) { /* * The firmware in the rootfs will not be accessible until we * are in the SYSTEM_RUNNING state, so return EPROBE_DEFER until * that point. */ if (system_state < SYSTEM_RUNNING) return -EPROBE_DEFER; goto fw_err; } data_size = fw->size; /* * This uses the GFP_DMA flag to ensure we are allocated memory in the * 32-bit space since TF-A cannot map memory beyond the 32-bit boundary. */ data_buf = kmemdup(fw->data, fw->size, GFP_KERNEL | GFP_DMA); if (!data_buf) { rc = -ENOMEM; goto fw_err; } data_pa = virt_to_phys(data_buf); reg_pair_from_64(&data_pa_high, &data_pa_low, data_pa); reg_pair_from_64(&data_size_high, &data_size_low, data_size); goto fw_load; fw_err: pr_warn("image loading failed\n"); data_pa_high = 0; data_pa_low = 0; data_size_high = 0; data_size_low = 0; fw_load: /* * Always invoke the SMC, even if loading the image fails, to indicate * to EL3 that we have passed the point where it should allow invoking * this SMC. */ pr_warn("OP-TEE image loaded from kernel, this can be insecure"); invoke_fn(OPTEE_SMC_CALL_LOAD_IMAGE, data_size_high, data_size_low, data_pa_high, data_pa_low, 0, 0, 0, &res); if (!rc) rc = res.a0; if (fw) release_firmware(fw); kfree(data_buf); if (!rc) { /* * We need to initialize OP-TEE on all other running cores as * well. Any cores that aren't running yet will get initialized * when they are brought up by the power management functions in * TF-A which are registered by the OP-TEE SPD. Due to that we * can un-register the callback right after registering it. */ cpuhp_invoke_fn = invoke_fn; hp_state = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "optee:probe", optee_cpuhp_probe, NULL); if (hp_state < 0) { pr_warn("Failed with CPU hotplug setup for OP-TEE"); return -EINVAL; } cpuhp_remove_state(hp_state); cpuhp_invoke_fn = NULL; } return rc; } #else static inline int optee_load_fw(struct platform_device *pdev, optee_invoke_fn *invoke_fn) { return 0; } #endif static int optee_probe(struct platform_device *pdev) { optee_invoke_fn *invoke_fn; struct tee_shm_pool *pool = ERR_PTR(-EINVAL); struct optee *optee = NULL; void *memremaped_shm = NULL; unsigned int rpc_param_count; struct tee_device *teedev; struct tee_context *ctx; u32 max_notif_value; u32 arg_cache_flags; u32 sec_caps; int rc; invoke_fn = get_invoke_func(&pdev->dev); if (IS_ERR(invoke_fn)) return PTR_ERR(invoke_fn); rc = optee_load_fw(pdev, invoke_fn); if (rc) return rc; if (!optee_msg_api_uid_is_optee_api(invoke_fn)) { pr_warn("api uid mismatch\n"); return -EINVAL; } optee_msg_get_os_revision(invoke_fn); if (!optee_msg_api_revision_is_compatible(invoke_fn)) { pr_warn("api revision mismatch\n"); return -EINVAL; } if (!optee_msg_exchange_capabilities(invoke_fn, &sec_caps, &max_notif_value, &rpc_param_count)) { pr_warn("capabilities mismatch\n"); return -EINVAL; } /* * Try to use dynamic shared memory if possible */ if (sec_caps & OPTEE_SMC_SEC_CAP_DYNAMIC_SHM) { /* * If we have OPTEE_SMC_SEC_CAP_RPC_ARG we can ask * optee_get_msg_arg() to pre-register (by having * OPTEE_SHM_ARG_ALLOC_PRIV cleared) the page used to pass * an argument struct. * * With the page is pre-registered we can use a non-zero * offset for argument struct, this is indicated with * OPTEE_SHM_ARG_SHARED. * * This means that optee_smc_do_call_with_arg() will use * OPTEE_SMC_CALL_WITH_REGD_ARG for pre-registered pages. */ if (sec_caps & OPTEE_SMC_SEC_CAP_RPC_ARG) arg_cache_flags = OPTEE_SHM_ARG_SHARED; else arg_cache_flags = OPTEE_SHM_ARG_ALLOC_PRIV; pool = optee_shm_pool_alloc_pages(); } /* * If dynamic shared memory is not available or failed - try static one */ if (IS_ERR(pool) && (sec_caps & OPTEE_SMC_SEC_CAP_HAVE_RESERVED_SHM)) { /* * The static memory pool can use non-zero page offsets so * let optee_get_msg_arg() know that with OPTEE_SHM_ARG_SHARED. * * optee_get_msg_arg() should not pre-register the * allocated page used to pass an argument struct, this is * indicated with OPTEE_SHM_ARG_ALLOC_PRIV. * * This means that optee_smc_do_call_with_arg() will use * OPTEE_SMC_CALL_WITH_ARG if rpc_param_count is 0, else * OPTEE_SMC_CALL_WITH_RPC_ARG. */ arg_cache_flags = OPTEE_SHM_ARG_SHARED | OPTEE_SHM_ARG_ALLOC_PRIV; pool = optee_config_shm_memremap(invoke_fn, &memremaped_shm); } if (IS_ERR(pool)) return PTR_ERR(pool); optee = kzalloc(sizeof(*optee), GFP_KERNEL); if (!optee) { rc = -ENOMEM; goto err_free_pool; } optee->ops = &optee_ops; optee->smc.invoke_fn = invoke_fn; optee->smc.sec_caps = sec_caps; optee->rpc_param_count = rpc_param_count; teedev = tee_device_alloc(&optee_clnt_desc, NULL, pool, optee); if (IS_ERR(teedev)) { rc = PTR_ERR(teedev); goto err_free_optee; } optee->teedev = teedev; teedev = tee_device_alloc(&optee_supp_desc, NULL, pool, optee); if (IS_ERR(teedev)) { rc = PTR_ERR(teedev); goto err_unreg_teedev; } optee->supp_teedev = teedev; rc = tee_device_register(optee->teedev); if (rc) goto err_unreg_supp_teedev; rc = tee_device_register(optee->supp_teedev); if (rc) goto err_unreg_supp_teedev; mutex_init(&optee->call_queue.mutex); INIT_LIST_HEAD(&optee->call_queue.waiters); optee_supp_init(&optee->supp); optee->smc.memremaped_shm = memremaped_shm; optee->pool = pool; optee_shm_arg_cache_init(optee, arg_cache_flags); platform_set_drvdata(pdev, optee); ctx = teedev_open(optee->teedev); if (IS_ERR(ctx)) { rc = PTR_ERR(ctx); goto err_supp_uninit; } optee->ctx = ctx; rc = optee_notif_init(optee, max_notif_value); if (rc) goto err_close_ctx; if (sec_caps & OPTEE_SMC_SEC_CAP_ASYNC_NOTIF) { unsigned int irq; rc = platform_get_irq(pdev, 0); if (rc < 0) { pr_err("platform_get_irq: ret %d\n", rc); goto err_notif_uninit; } irq = rc; rc = optee_smc_notif_init_irq(optee, irq); if (rc) { irq_dispose_mapping(irq); goto err_notif_uninit; } enable_async_notif(optee->smc.invoke_fn); pr_info("Asynchronous notifications enabled\n"); } /* * Ensure that there are no pre-existing shm objects before enabling * the shm cache so that there's no chance of receiving an invalid * address during shutdown. This could occur, for example, if we're * kexec booting from an older kernel that did not properly cleanup the * shm cache. */ optee_disable_unmapped_shm_cache(optee); /* * Only enable the shm cache in case we're not able to pass the RPC * arg struct right after the normal arg struct. */ if (!optee->rpc_param_count) optee_enable_shm_cache(optee); if (optee->smc.sec_caps & OPTEE_SMC_SEC_CAP_DYNAMIC_SHM) pr_info("dynamic shared memory is enabled\n"); rc = optee_enumerate_devices(PTA_CMD_GET_DEVICES); if (rc) goto err_disable_shm_cache; pr_info("initialized driver\n"); return 0; err_disable_shm_cache: if (!optee->rpc_param_count) optee_disable_shm_cache(optee); optee_smc_notif_uninit_irq(optee); optee_unregister_devices(); err_notif_uninit: optee_notif_uninit(optee); err_close_ctx: teedev_close_context(ctx); err_supp_uninit: optee_shm_arg_cache_uninit(optee); optee_supp_uninit(&optee->supp); mutex_destroy(&optee->call_queue.mutex); err_unreg_supp_teedev: tee_device_unregister(optee->supp_teedev); err_unreg_teedev: tee_device_unregister(optee->teedev); err_free_optee: kfree(optee); err_free_pool: tee_shm_pool_free(pool); if (memremaped_shm) memunmap(memremaped_shm); return rc; } static const struct of_device_id optee_dt_match[] = { { .compatible = "linaro,optee-tz" }, {}, }; MODULE_DEVICE_TABLE(of, optee_dt_match); static struct platform_driver optee_driver = { .probe = optee_probe, .remove = optee_smc_remove, .shutdown = optee_shutdown, .driver = { .name = "optee", .of_match_table = optee_dt_match, }, }; int optee_smc_abi_register(void) { return platform_driver_register(&optee_driver); } void optee_smc_abi_unregister(void) { platform_driver_unregister(&optee_driver); }
linux-master
drivers/tee/optee/smc_abi.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2015, Linaro Limited */ #include <linux/device.h> #include <linux/slab.h> #include <linux/uaccess.h> #include "optee_private.h" struct optee_supp_req { struct list_head link; bool in_queue; u32 func; u32 ret; size_t num_params; struct tee_param *param; struct completion c; }; void optee_supp_init(struct optee_supp *supp) { memset(supp, 0, sizeof(*supp)); mutex_init(&supp->mutex); init_completion(&supp->reqs_c); idr_init(&supp->idr); INIT_LIST_HEAD(&supp->reqs); supp->req_id = -1; } void optee_supp_uninit(struct optee_supp *supp) { mutex_destroy(&supp->mutex); idr_destroy(&supp->idr); } void optee_supp_release(struct optee_supp *supp) { int id; struct optee_supp_req *req; struct optee_supp_req *req_tmp; mutex_lock(&supp->mutex); /* Abort all request retrieved by supplicant */ idr_for_each_entry(&supp->idr, req, id) { idr_remove(&supp->idr, id); req->ret = TEEC_ERROR_COMMUNICATION; complete(&req->c); } /* Abort all queued requests */ list_for_each_entry_safe(req, req_tmp, &supp->reqs, link) { list_del(&req->link); req->in_queue = false; req->ret = TEEC_ERROR_COMMUNICATION; complete(&req->c); } supp->ctx = NULL; supp->req_id = -1; mutex_unlock(&supp->mutex); } /** * optee_supp_thrd_req() - request service from supplicant * @ctx: context doing the request * @func: function requested * @num_params: number of elements in @param array * @param: parameters for function * * Returns result of operation to be passed to secure world */ u32 optee_supp_thrd_req(struct tee_context *ctx, u32 func, size_t num_params, struct tee_param *param) { struct optee *optee = tee_get_drvdata(ctx->teedev); struct optee_supp *supp = &optee->supp; struct optee_supp_req *req; bool interruptable; u32 ret; /* * Return in case there is no supplicant available and * non-blocking request. */ if (!supp->ctx && ctx->supp_nowait) return TEEC_ERROR_COMMUNICATION; req = kzalloc(sizeof(*req), GFP_KERNEL); if (!req) return TEEC_ERROR_OUT_OF_MEMORY; init_completion(&req->c); req->func = func; req->num_params = num_params; req->param = param; /* Insert the request in the request list */ mutex_lock(&supp->mutex); list_add_tail(&req->link, &supp->reqs); req->in_queue = true; mutex_unlock(&supp->mutex); /* Tell an eventual waiter there's a new request */ complete(&supp->reqs_c); /* * Wait for supplicant to process and return result, once we've * returned from wait_for_completion(&req->c) successfully we have * exclusive access again. */ while (wait_for_completion_interruptible(&req->c)) { mutex_lock(&supp->mutex); interruptable = !supp->ctx; if (interruptable) { /* * There's no supplicant available and since the * supp->mutex currently is held none can * become available until the mutex released * again. * * Interrupting an RPC to supplicant is only * allowed as a way of slightly improving the user * experience in case the supplicant hasn't been * started yet. During normal operation the supplicant * will serve all requests in a timely manner and * interrupting then wouldn't make sense. */ if (req->in_queue) { list_del(&req->link); req->in_queue = false; } } mutex_unlock(&supp->mutex); if (interruptable) { req->ret = TEEC_ERROR_COMMUNICATION; break; } } ret = req->ret; kfree(req); return ret; } static struct optee_supp_req *supp_pop_entry(struct optee_supp *supp, int num_params, int *id) { struct optee_supp_req *req; if (supp->req_id != -1) { /* * Supplicant should not mix synchronous and asnynchronous * requests. */ return ERR_PTR(-EINVAL); } if (list_empty(&supp->reqs)) return NULL; req = list_first_entry(&supp->reqs, struct optee_supp_req, link); if (num_params < req->num_params) { /* Not enough room for parameters */ return ERR_PTR(-EINVAL); } *id = idr_alloc(&supp->idr, req, 1, 0, GFP_KERNEL); if (*id < 0) return ERR_PTR(-ENOMEM); list_del(&req->link); req->in_queue = false; return req; } static int supp_check_recv_params(size_t num_params, struct tee_param *params, size_t *num_meta) { size_t n; if (!num_params) return -EINVAL; /* * If there's memrefs we need to decrease those as they where * increased earlier and we'll even refuse to accept any below. */ for (n = 0; n < num_params; n++) if (tee_param_is_memref(params + n) && params[n].u.memref.shm) tee_shm_put(params[n].u.memref.shm); /* * We only expect parameters as TEE_IOCTL_PARAM_ATTR_TYPE_NONE with * or without the TEE_IOCTL_PARAM_ATTR_META bit set. */ for (n = 0; n < num_params; n++) if (params[n].attr && params[n].attr != TEE_IOCTL_PARAM_ATTR_META) return -EINVAL; /* At most we'll need one meta parameter so no need to check for more */ if (params->attr == TEE_IOCTL_PARAM_ATTR_META) *num_meta = 1; else *num_meta = 0; return 0; } /** * optee_supp_recv() - receive request for supplicant * @ctx: context receiving the request * @func: requested function in supplicant * @num_params: number of elements allocated in @param, updated with number * used elements * @param: space for parameters for @func * * Returns 0 on success or <0 on failure */ int optee_supp_recv(struct tee_context *ctx, u32 *func, u32 *num_params, struct tee_param *param) { struct tee_device *teedev = ctx->teedev; struct optee *optee = tee_get_drvdata(teedev); struct optee_supp *supp = &optee->supp; struct optee_supp_req *req = NULL; int id; size_t num_meta; int rc; rc = supp_check_recv_params(*num_params, param, &num_meta); if (rc) return rc; while (true) { mutex_lock(&supp->mutex); req = supp_pop_entry(supp, *num_params - num_meta, &id); mutex_unlock(&supp->mutex); if (req) { if (IS_ERR(req)) return PTR_ERR(req); break; } /* * If we didn't get a request we'll block in * wait_for_completion() to avoid needless spinning. * * This is where supplicant will be hanging most of * the time, let's make this interruptable so we * can easily restart supplicant if needed. */ if (wait_for_completion_interruptible(&supp->reqs_c)) return -ERESTARTSYS; } if (num_meta) { /* * tee-supplicant support meta parameters -> requsts can be * processed asynchronously. */ param->attr = TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INOUT | TEE_IOCTL_PARAM_ATTR_META; param->u.value.a = id; param->u.value.b = 0; param->u.value.c = 0; } else { mutex_lock(&supp->mutex); supp->req_id = id; mutex_unlock(&supp->mutex); } *func = req->func; *num_params = req->num_params + num_meta; memcpy(param + num_meta, req->param, sizeof(struct tee_param) * req->num_params); return 0; } static struct optee_supp_req *supp_pop_req(struct optee_supp *supp, size_t num_params, struct tee_param *param, size_t *num_meta) { struct optee_supp_req *req; int id; size_t nm; const u32 attr = TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INOUT | TEE_IOCTL_PARAM_ATTR_META; if (!num_params) return ERR_PTR(-EINVAL); if (supp->req_id == -1) { if (param->attr != attr) return ERR_PTR(-EINVAL); id = param->u.value.a; nm = 1; } else { id = supp->req_id; nm = 0; } req = idr_find(&supp->idr, id); if (!req) return ERR_PTR(-ENOENT); if ((num_params - nm) != req->num_params) return ERR_PTR(-EINVAL); idr_remove(&supp->idr, id); supp->req_id = -1; *num_meta = nm; return req; } /** * optee_supp_send() - send result of request from supplicant * @ctx: context sending result * @ret: return value of request * @num_params: number of parameters returned * @param: returned parameters * * Returns 0 on success or <0 on failure. */ int optee_supp_send(struct tee_context *ctx, u32 ret, u32 num_params, struct tee_param *param) { struct tee_device *teedev = ctx->teedev; struct optee *optee = tee_get_drvdata(teedev); struct optee_supp *supp = &optee->supp; struct optee_supp_req *req; size_t n; size_t num_meta; mutex_lock(&supp->mutex); req = supp_pop_req(supp, num_params, param, &num_meta); mutex_unlock(&supp->mutex); if (IS_ERR(req)) { /* Something is wrong, let supplicant restart. */ return PTR_ERR(req); } /* Update out and in/out parameters */ for (n = 0; n < req->num_params; n++) { struct tee_param *p = req->param + n; switch (p->attr & TEE_IOCTL_PARAM_ATTR_TYPE_MASK) { case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_OUTPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INOUT: p->u.value.a = param[n + num_meta].u.value.a; p->u.value.b = param[n + num_meta].u.value.b; p->u.value.c = param[n + num_meta].u.value.c; break; case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_OUTPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INOUT: p->u.memref.size = param[n + num_meta].u.memref.size; break; default: break; } } req->ret = ret; /* Let the requesting thread continue */ complete(&req->c); return 0; }
linux-master
drivers/tee/optee/supp.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2015-2021, Linaro Limited * Copyright (c) 2016, EPAM Systems */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/crash_dump.h> #include <linux/errno.h> #include <linux/io.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/tee_drv.h> #include <linux/types.h> #include <linux/workqueue.h> #include "optee_private.h" int optee_pool_op_alloc_helper(struct tee_shm_pool *pool, struct tee_shm *shm, size_t size, size_t align, int (*shm_register)(struct tee_context *ctx, struct tee_shm *shm, struct page **pages, size_t num_pages, unsigned long start)) { unsigned int order = get_order(size); struct page *page; int rc = 0; /* * Ignore alignment since this is already going to be page aligned * and there's no need for any larger alignment. */ page = alloc_pages(GFP_KERNEL | __GFP_ZERO, order); if (!page) return -ENOMEM; shm->kaddr = page_address(page); shm->paddr = page_to_phys(page); shm->size = PAGE_SIZE << order; if (shm_register) { unsigned int nr_pages = 1 << order, i; struct page **pages; pages = kcalloc(nr_pages, sizeof(*pages), GFP_KERNEL); if (!pages) { rc = -ENOMEM; goto err; } for (i = 0; i < nr_pages; i++) pages[i] = page + i; rc = shm_register(shm->ctx, shm, pages, nr_pages, (unsigned long)shm->kaddr); kfree(pages); if (rc) goto err; } return 0; err: free_pages((unsigned long)shm->kaddr, order); return rc; } void optee_pool_op_free_helper(struct tee_shm_pool *pool, struct tee_shm *shm, int (*shm_unregister)(struct tee_context *ctx, struct tee_shm *shm)) { if (shm_unregister) shm_unregister(shm->ctx, shm); free_pages((unsigned long)shm->kaddr, get_order(shm->size)); shm->kaddr = NULL; } static void optee_bus_scan(struct work_struct *work) { WARN_ON(optee_enumerate_devices(PTA_CMD_GET_DEVICES_SUPP)); } int optee_open(struct tee_context *ctx, bool cap_memref_null) { struct optee_context_data *ctxdata; struct tee_device *teedev = ctx->teedev; struct optee *optee = tee_get_drvdata(teedev); ctxdata = kzalloc(sizeof(*ctxdata), GFP_KERNEL); if (!ctxdata) return -ENOMEM; if (teedev == optee->supp_teedev) { bool busy = true; mutex_lock(&optee->supp.mutex); if (!optee->supp.ctx) { busy = false; optee->supp.ctx = ctx; } mutex_unlock(&optee->supp.mutex); if (busy) { kfree(ctxdata); return -EBUSY; } if (!optee->scan_bus_done) { INIT_WORK(&optee->scan_bus_work, optee_bus_scan); optee->scan_bus_wq = create_workqueue("optee_bus_scan"); if (!optee->scan_bus_wq) { kfree(ctxdata); return -ECHILD; } queue_work(optee->scan_bus_wq, &optee->scan_bus_work); optee->scan_bus_done = true; } } mutex_init(&ctxdata->mutex); INIT_LIST_HEAD(&ctxdata->sess_list); ctx->cap_memref_null = cap_memref_null; ctx->data = ctxdata; return 0; } static void optee_release_helper(struct tee_context *ctx, int (*close_session)(struct tee_context *ctx, u32 session)) { struct optee_context_data *ctxdata = ctx->data; struct optee_session *sess; struct optee_session *sess_tmp; if (!ctxdata) return; list_for_each_entry_safe(sess, sess_tmp, &ctxdata->sess_list, list_node) { list_del(&sess->list_node); close_session(ctx, sess->session_id); kfree(sess); } kfree(ctxdata); ctx->data = NULL; } void optee_release(struct tee_context *ctx) { optee_release_helper(ctx, optee_close_session_helper); } void optee_release_supp(struct tee_context *ctx) { struct optee *optee = tee_get_drvdata(ctx->teedev); optee_release_helper(ctx, optee_close_session_helper); if (optee->scan_bus_wq) { destroy_workqueue(optee->scan_bus_wq); optee->scan_bus_wq = NULL; } optee_supp_release(&optee->supp); } void optee_remove_common(struct optee *optee) { /* Unregister OP-TEE specific client devices on TEE bus */ optee_unregister_devices(); optee_notif_uninit(optee); optee_shm_arg_cache_uninit(optee); teedev_close_context(optee->ctx); /* * The two devices have to be unregistered before we can free the * other resources. */ tee_device_unregister(optee->supp_teedev); tee_device_unregister(optee->teedev); tee_shm_pool_free(optee->pool); optee_supp_uninit(&optee->supp); mutex_destroy(&optee->call_queue.mutex); } static int smc_abi_rc; static int ffa_abi_rc; static int __init optee_core_init(void) { /* * The kernel may have crashed at the same time that all available * secure world threads were suspended and we cannot reschedule the * suspended threads without access to the crashed kernel's wait_queue. * Therefore, we cannot reliably initialize the OP-TEE driver in the * kdump kernel. */ if (is_kdump_kernel()) return -ENODEV; smc_abi_rc = optee_smc_abi_register(); ffa_abi_rc = optee_ffa_abi_register(); /* If both failed there's no point with this module */ if (smc_abi_rc && ffa_abi_rc) return smc_abi_rc; return 0; } module_init(optee_core_init); static void __exit optee_core_exit(void) { if (!smc_abi_rc) optee_smc_abi_unregister(); if (!ffa_abi_rc) optee_ffa_abi_unregister(); } module_exit(optee_core_exit); MODULE_AUTHOR("Linaro"); MODULE_DESCRIPTION("OP-TEE driver"); MODULE_VERSION("1.0"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("platform:optee");
linux-master
drivers/tee/optee/core.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2019 Linaro Ltd. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/slab.h> #include <linux/tee_drv.h> #include <linux/uuid.h> #include "optee_private.h" static int optee_ctx_match(struct tee_ioctl_version_data *ver, const void *data) { if (ver->impl_id == TEE_IMPL_ID_OPTEE) return 1; else return 0; } static int get_devices(struct tee_context *ctx, u32 session, struct tee_shm *device_shm, u32 *shm_size, u32 func) { int ret = 0; struct tee_ioctl_invoke_arg inv_arg; struct tee_param param[4]; memset(&inv_arg, 0, sizeof(inv_arg)); memset(&param, 0, sizeof(param)); inv_arg.func = func; inv_arg.session = session; inv_arg.num_params = 4; /* Fill invoke cmd params */ param[0].attr = TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_OUTPUT; param[0].u.memref.shm = device_shm; param[0].u.memref.size = *shm_size; param[0].u.memref.shm_offs = 0; ret = tee_client_invoke_func(ctx, &inv_arg, param); if ((ret < 0) || ((inv_arg.ret != TEEC_SUCCESS) && (inv_arg.ret != TEEC_ERROR_SHORT_BUFFER))) { pr_err("PTA_CMD_GET_DEVICES invoke function err: %x\n", inv_arg.ret); return -EINVAL; } *shm_size = param[0].u.memref.size; return 0; } static void optee_release_device(struct device *dev) { struct tee_client_device *optee_device = to_tee_client_device(dev); kfree(optee_device); } static int optee_register_device(const uuid_t *device_uuid) { struct tee_client_device *optee_device = NULL; int rc; optee_device = kzalloc(sizeof(*optee_device), GFP_KERNEL); if (!optee_device) return -ENOMEM; optee_device->dev.bus = &tee_bus_type; optee_device->dev.release = optee_release_device; if (dev_set_name(&optee_device->dev, "optee-ta-%pUb", device_uuid)) { kfree(optee_device); return -ENOMEM; } uuid_copy(&optee_device->id.uuid, device_uuid); rc = device_register(&optee_device->dev); if (rc) { pr_err("device registration failed, err: %d\n", rc); put_device(&optee_device->dev); } return rc; } static int __optee_enumerate_devices(u32 func) { const uuid_t pta_uuid = UUID_INIT(0x7011a688, 0xddde, 0x4053, 0xa5, 0xa9, 0x7b, 0x3c, 0x4d, 0xdf, 0x13, 0xb8); struct tee_ioctl_open_session_arg sess_arg; struct tee_shm *device_shm = NULL; const uuid_t *device_uuid = NULL; struct tee_context *ctx = NULL; u32 shm_size = 0, idx, num_devices = 0; int rc; memset(&sess_arg, 0, sizeof(sess_arg)); /* Open context with OP-TEE driver */ ctx = tee_client_open_context(NULL, optee_ctx_match, NULL, NULL); if (IS_ERR(ctx)) return -ENODEV; /* Open session with device enumeration pseudo TA */ export_uuid(sess_arg.uuid, &pta_uuid); sess_arg.clnt_login = TEE_IOCTL_LOGIN_PUBLIC; sess_arg.num_params = 0; rc = tee_client_open_session(ctx, &sess_arg, NULL); if ((rc < 0) || (sess_arg.ret != TEEC_SUCCESS)) { /* Device enumeration pseudo TA not found */ rc = 0; goto out_ctx; } rc = get_devices(ctx, sess_arg.session, NULL, &shm_size, func); if (rc < 0 || !shm_size) goto out_sess; device_shm = tee_shm_alloc_kernel_buf(ctx, shm_size); if (IS_ERR(device_shm)) { pr_err("tee_shm_alloc_kernel_buf failed\n"); rc = PTR_ERR(device_shm); goto out_sess; } rc = get_devices(ctx, sess_arg.session, device_shm, &shm_size, func); if (rc < 0) goto out_shm; device_uuid = tee_shm_get_va(device_shm, 0); if (IS_ERR(device_uuid)) { pr_err("tee_shm_get_va failed\n"); rc = PTR_ERR(device_uuid); goto out_shm; } num_devices = shm_size / sizeof(uuid_t); for (idx = 0; idx < num_devices; idx++) { rc = optee_register_device(&device_uuid[idx]); if (rc) goto out_shm; } out_shm: tee_shm_free(device_shm); out_sess: tee_client_close_session(ctx, sess_arg.session); out_ctx: tee_client_close_context(ctx); return rc; } int optee_enumerate_devices(u32 func) { return __optee_enumerate_devices(func); } static int __optee_unregister_device(struct device *dev, void *data) { if (!strncmp(dev_name(dev), "optee-ta", strlen("optee-ta"))) device_unregister(dev); return 0; } void optee_unregister_devices(void) { bus_for_each_dev(&tee_bus_type, NULL, NULL, __optee_unregister_device); }
linux-master
drivers/tee/optee/device.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2015-2021, Linaro Limited */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/arm-smccc.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/tee_drv.h> #include "optee_private.h" struct notif_entry { struct list_head link; struct completion c; u_int key; }; static bool have_key(struct optee *optee, u_int key) { struct notif_entry *entry; list_for_each_entry(entry, &optee->notif.db, link) if (entry->key == key) return true; return false; } int optee_notif_wait(struct optee *optee, u_int key) { unsigned long flags; struct notif_entry *entry; int rc = 0; if (key > optee->notif.max_key) return -EINVAL; entry = kmalloc(sizeof(*entry), GFP_KERNEL); if (!entry) return -ENOMEM; init_completion(&entry->c); entry->key = key; spin_lock_irqsave(&optee->notif.lock, flags); /* * If the bit is already set it means that the key has already * been posted and we must not wait. */ if (test_bit(key, optee->notif.bitmap)) { clear_bit(key, optee->notif.bitmap); goto out; } /* * Check if someone is already waiting for this key. If there is * it's a programming error. */ if (have_key(optee, key)) { rc = -EBUSY; goto out; } list_add_tail(&entry->link, &optee->notif.db); /* * Unlock temporarily and wait for completion. */ spin_unlock_irqrestore(&optee->notif.lock, flags); wait_for_completion(&entry->c); spin_lock_irqsave(&optee->notif.lock, flags); list_del(&entry->link); out: spin_unlock_irqrestore(&optee->notif.lock, flags); kfree(entry); return rc; } int optee_notif_send(struct optee *optee, u_int key) { unsigned long flags; struct notif_entry *entry; if (key > optee->notif.max_key) return -EINVAL; spin_lock_irqsave(&optee->notif.lock, flags); list_for_each_entry(entry, &optee->notif.db, link) if (entry->key == key) { complete(&entry->c); goto out; } /* Only set the bit in case there where nobody waiting */ set_bit(key, optee->notif.bitmap); out: spin_unlock_irqrestore(&optee->notif.lock, flags); return 0; } int optee_notif_init(struct optee *optee, u_int max_key) { spin_lock_init(&optee->notif.lock); INIT_LIST_HEAD(&optee->notif.db); optee->notif.bitmap = bitmap_zalloc(max_key, GFP_KERNEL); if (!optee->notif.bitmap) return -ENOMEM; optee->notif.max_key = max_key; return 0; } void optee_notif_uninit(struct optee *optee) { bitmap_free(optee->notif.bitmap); }
linux-master
drivers/tee/optee/notif.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2015-2021, Linaro Limited */ #include <linux/device.h> #include <linux/err.h> #include <linux/errno.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/tee_drv.h> #include <linux/types.h> #include "optee_private.h" #define MAX_ARG_PARAM_COUNT 6 /* * How much memory we allocate for each entry. This doesn't have to be a * single page, but it makes sense to keep at least keep it as multiples of * the page size. */ #define SHM_ENTRY_SIZE PAGE_SIZE /* * We need to have a compile time constant to be able to determine the * maximum needed size of the bit field. */ #define MIN_ARG_SIZE OPTEE_MSG_GET_ARG_SIZE(MAX_ARG_PARAM_COUNT) #define MAX_ARG_COUNT_PER_ENTRY (SHM_ENTRY_SIZE / MIN_ARG_SIZE) /* * Shared memory for argument structs are cached here. The number of * arguments structs that can fit is determined at runtime depending on the * needed RPC parameter count reported by secure world * (optee->rpc_param_count). */ struct optee_shm_arg_entry { struct list_head list_node; struct tee_shm *shm; DECLARE_BITMAP(map, MAX_ARG_COUNT_PER_ENTRY); }; void optee_cq_wait_init(struct optee_call_queue *cq, struct optee_call_waiter *w) { /* * We're preparing to make a call to secure world. In case we can't * allocate a thread in secure world we'll end up waiting in * optee_cq_wait_for_completion(). * * Normally if there's no contention in secure world the call will * complete and we can cleanup directly with optee_cq_wait_final(). */ mutex_lock(&cq->mutex); /* * We add ourselves to the queue, but we don't wait. This * guarantees that we don't lose a completion if secure world * returns busy and another thread just exited and try to complete * someone. */ init_completion(&w->c); list_add_tail(&w->list_node, &cq->waiters); mutex_unlock(&cq->mutex); } void optee_cq_wait_for_completion(struct optee_call_queue *cq, struct optee_call_waiter *w) { wait_for_completion(&w->c); mutex_lock(&cq->mutex); /* Move to end of list to get out of the way for other waiters */ list_del(&w->list_node); reinit_completion(&w->c); list_add_tail(&w->list_node, &cq->waiters); mutex_unlock(&cq->mutex); } static void optee_cq_complete_one(struct optee_call_queue *cq) { struct optee_call_waiter *w; list_for_each_entry(w, &cq->waiters, list_node) { if (!completion_done(&w->c)) { complete(&w->c); break; } } } void optee_cq_wait_final(struct optee_call_queue *cq, struct optee_call_waiter *w) { /* * We're done with the call to secure world. The thread in secure * world that was used for this call is now available for some * other task to use. */ mutex_lock(&cq->mutex); /* Get out of the list */ list_del(&w->list_node); /* Wake up one eventual waiting task */ optee_cq_complete_one(cq); /* * If we're completed we've got a completion from another task that * was just done with its call to secure world. Since yet another * thread now is available in secure world wake up another eventual * waiting task. */ if (completion_done(&w->c)) optee_cq_complete_one(cq); mutex_unlock(&cq->mutex); } /* Requires the filpstate mutex to be held */ static struct optee_session *find_session(struct optee_context_data *ctxdata, u32 session_id) { struct optee_session *sess; list_for_each_entry(sess, &ctxdata->sess_list, list_node) if (sess->session_id == session_id) return sess; return NULL; } void optee_shm_arg_cache_init(struct optee *optee, u32 flags) { INIT_LIST_HEAD(&optee->shm_arg_cache.shm_args); mutex_init(&optee->shm_arg_cache.mutex); optee->shm_arg_cache.flags = flags; } void optee_shm_arg_cache_uninit(struct optee *optee) { struct list_head *head = &optee->shm_arg_cache.shm_args; struct optee_shm_arg_entry *entry; mutex_destroy(&optee->shm_arg_cache.mutex); while (!list_empty(head)) { entry = list_first_entry(head, struct optee_shm_arg_entry, list_node); list_del(&entry->list_node); if (find_first_bit(entry->map, MAX_ARG_COUNT_PER_ENTRY) != MAX_ARG_COUNT_PER_ENTRY) { pr_err("Freeing non-free entry\n"); } tee_shm_free(entry->shm); kfree(entry); } } size_t optee_msg_arg_size(size_t rpc_param_count) { size_t sz = OPTEE_MSG_GET_ARG_SIZE(MAX_ARG_PARAM_COUNT); if (rpc_param_count) sz += OPTEE_MSG_GET_ARG_SIZE(rpc_param_count); return sz; } /** * optee_get_msg_arg() - Provide shared memory for argument struct * @ctx: Caller TEE context * @num_params: Number of parameter to store * @entry_ret: Entry pointer, needed when freeing the buffer * @shm_ret: Shared memory buffer * @offs_ret: Offset of argument strut in shared memory buffer * * @returns a pointer to the argument struct in memory, else an ERR_PTR */ struct optee_msg_arg *optee_get_msg_arg(struct tee_context *ctx, size_t num_params, struct optee_shm_arg_entry **entry_ret, struct tee_shm **shm_ret, u_int *offs_ret) { struct optee *optee = tee_get_drvdata(ctx->teedev); size_t sz = optee_msg_arg_size(optee->rpc_param_count); struct optee_shm_arg_entry *entry; struct optee_msg_arg *ma; size_t args_per_entry; u_long bit; u_int offs; void *res; if (num_params > MAX_ARG_PARAM_COUNT) return ERR_PTR(-EINVAL); if (optee->shm_arg_cache.flags & OPTEE_SHM_ARG_SHARED) args_per_entry = SHM_ENTRY_SIZE / sz; else args_per_entry = 1; mutex_lock(&optee->shm_arg_cache.mutex); list_for_each_entry(entry, &optee->shm_arg_cache.shm_args, list_node) { bit = find_first_zero_bit(entry->map, MAX_ARG_COUNT_PER_ENTRY); if (bit < args_per_entry) goto have_entry; } /* * No entry was found, let's allocate a new. */ entry = kzalloc(sizeof(*entry), GFP_KERNEL); if (!entry) { res = ERR_PTR(-ENOMEM); goto out; } if (optee->shm_arg_cache.flags & OPTEE_SHM_ARG_ALLOC_PRIV) res = tee_shm_alloc_priv_buf(ctx, SHM_ENTRY_SIZE); else res = tee_shm_alloc_kernel_buf(ctx, SHM_ENTRY_SIZE); if (IS_ERR(res)) { kfree(entry); goto out; } entry->shm = res; list_add(&entry->list_node, &optee->shm_arg_cache.shm_args); bit = 0; have_entry: offs = bit * sz; res = tee_shm_get_va(entry->shm, offs); if (IS_ERR(res)) goto out; ma = res; set_bit(bit, entry->map); memset(ma, 0, sz); ma->num_params = num_params; *entry_ret = entry; *shm_ret = entry->shm; *offs_ret = offs; out: mutex_unlock(&optee->shm_arg_cache.mutex); return res; } /** * optee_free_msg_arg() - Free previsouly obtained shared memory * @ctx: Caller TEE context * @entry: Pointer returned when the shared memory was obtained * @offs: Offset of shared memory buffer to free * * This function frees the shared memory obtained with optee_get_msg_arg(). */ void optee_free_msg_arg(struct tee_context *ctx, struct optee_shm_arg_entry *entry, u_int offs) { struct optee *optee = tee_get_drvdata(ctx->teedev); size_t sz = optee_msg_arg_size(optee->rpc_param_count); u_long bit; if (offs > SHM_ENTRY_SIZE || offs % sz) { pr_err("Invalid offs %u\n", offs); return; } bit = offs / sz; mutex_lock(&optee->shm_arg_cache.mutex); if (!test_bit(bit, entry->map)) pr_err("Bit pos %lu is already free\n", bit); clear_bit(bit, entry->map); mutex_unlock(&optee->shm_arg_cache.mutex); } int optee_open_session(struct tee_context *ctx, struct tee_ioctl_open_session_arg *arg, struct tee_param *param) { struct optee *optee = tee_get_drvdata(ctx->teedev); struct optee_context_data *ctxdata = ctx->data; struct optee_shm_arg_entry *entry; struct tee_shm *shm; struct optee_msg_arg *msg_arg; struct optee_session *sess = NULL; uuid_t client_uuid; u_int offs; int rc; /* +2 for the meta parameters added below */ msg_arg = optee_get_msg_arg(ctx, arg->num_params + 2, &entry, &shm, &offs); if (IS_ERR(msg_arg)) return PTR_ERR(msg_arg); msg_arg->cmd = OPTEE_MSG_CMD_OPEN_SESSION; msg_arg->cancel_id = arg->cancel_id; /* * Initialize and add the meta parameters needed when opening a * session. */ msg_arg->params[0].attr = OPTEE_MSG_ATTR_TYPE_VALUE_INPUT | OPTEE_MSG_ATTR_META; msg_arg->params[1].attr = OPTEE_MSG_ATTR_TYPE_VALUE_INPUT | OPTEE_MSG_ATTR_META; memcpy(&msg_arg->params[0].u.value, arg->uuid, sizeof(arg->uuid)); msg_arg->params[1].u.value.c = arg->clnt_login; rc = tee_session_calc_client_uuid(&client_uuid, arg->clnt_login, arg->clnt_uuid); if (rc) goto out; export_uuid(msg_arg->params[1].u.octets, &client_uuid); rc = optee->ops->to_msg_param(optee, msg_arg->params + 2, arg->num_params, param); if (rc) goto out; sess = kzalloc(sizeof(*sess), GFP_KERNEL); if (!sess) { rc = -ENOMEM; goto out; } if (optee->ops->do_call_with_arg(ctx, shm, offs)) { msg_arg->ret = TEEC_ERROR_COMMUNICATION; msg_arg->ret_origin = TEEC_ORIGIN_COMMS; } if (msg_arg->ret == TEEC_SUCCESS) { /* A new session has been created, add it to the list. */ sess->session_id = msg_arg->session; mutex_lock(&ctxdata->mutex); list_add(&sess->list_node, &ctxdata->sess_list); mutex_unlock(&ctxdata->mutex); } else { kfree(sess); } if (optee->ops->from_msg_param(optee, param, arg->num_params, msg_arg->params + 2)) { arg->ret = TEEC_ERROR_COMMUNICATION; arg->ret_origin = TEEC_ORIGIN_COMMS; /* Close session again to avoid leakage */ optee_close_session(ctx, msg_arg->session); } else { arg->session = msg_arg->session; arg->ret = msg_arg->ret; arg->ret_origin = msg_arg->ret_origin; } out: optee_free_msg_arg(ctx, entry, offs); return rc; } int optee_close_session_helper(struct tee_context *ctx, u32 session) { struct optee *optee = tee_get_drvdata(ctx->teedev); struct optee_shm_arg_entry *entry; struct optee_msg_arg *msg_arg; struct tee_shm *shm; u_int offs; msg_arg = optee_get_msg_arg(ctx, 0, &entry, &shm, &offs); if (IS_ERR(msg_arg)) return PTR_ERR(msg_arg); msg_arg->cmd = OPTEE_MSG_CMD_CLOSE_SESSION; msg_arg->session = session; optee->ops->do_call_with_arg(ctx, shm, offs); optee_free_msg_arg(ctx, entry, offs); return 0; } int optee_close_session(struct tee_context *ctx, u32 session) { struct optee_context_data *ctxdata = ctx->data; struct optee_session *sess; /* Check that the session is valid and remove it from the list */ mutex_lock(&ctxdata->mutex); sess = find_session(ctxdata, session); if (sess) list_del(&sess->list_node); mutex_unlock(&ctxdata->mutex); if (!sess) return -EINVAL; kfree(sess); return optee_close_session_helper(ctx, session); } int optee_invoke_func(struct tee_context *ctx, struct tee_ioctl_invoke_arg *arg, struct tee_param *param) { struct optee *optee = tee_get_drvdata(ctx->teedev); struct optee_context_data *ctxdata = ctx->data; struct optee_shm_arg_entry *entry; struct optee_msg_arg *msg_arg; struct optee_session *sess; struct tee_shm *shm; u_int offs; int rc; /* Check that the session is valid */ mutex_lock(&ctxdata->mutex); sess = find_session(ctxdata, arg->session); mutex_unlock(&ctxdata->mutex); if (!sess) return -EINVAL; msg_arg = optee_get_msg_arg(ctx, arg->num_params, &entry, &shm, &offs); if (IS_ERR(msg_arg)) return PTR_ERR(msg_arg); msg_arg->cmd = OPTEE_MSG_CMD_INVOKE_COMMAND; msg_arg->func = arg->func; msg_arg->session = arg->session; msg_arg->cancel_id = arg->cancel_id; rc = optee->ops->to_msg_param(optee, msg_arg->params, arg->num_params, param); if (rc) goto out; if (optee->ops->do_call_with_arg(ctx, shm, offs)) { msg_arg->ret = TEEC_ERROR_COMMUNICATION; msg_arg->ret_origin = TEEC_ORIGIN_COMMS; } if (optee->ops->from_msg_param(optee, param, arg->num_params, msg_arg->params)) { msg_arg->ret = TEEC_ERROR_COMMUNICATION; msg_arg->ret_origin = TEEC_ORIGIN_COMMS; } arg->ret = msg_arg->ret; arg->ret_origin = msg_arg->ret_origin; out: optee_free_msg_arg(ctx, entry, offs); return rc; } int optee_cancel_req(struct tee_context *ctx, u32 cancel_id, u32 session) { struct optee *optee = tee_get_drvdata(ctx->teedev); struct optee_context_data *ctxdata = ctx->data; struct optee_shm_arg_entry *entry; struct optee_msg_arg *msg_arg; struct optee_session *sess; struct tee_shm *shm; u_int offs; /* Check that the session is valid */ mutex_lock(&ctxdata->mutex); sess = find_session(ctxdata, session); mutex_unlock(&ctxdata->mutex); if (!sess) return -EINVAL; msg_arg = optee_get_msg_arg(ctx, 0, &entry, &shm, &offs); if (IS_ERR(msg_arg)) return PTR_ERR(msg_arg); msg_arg->cmd = OPTEE_MSG_CMD_CANCEL; msg_arg->session = session; msg_arg->cancel_id = cancel_id; optee->ops->do_call_with_arg(ctx, shm, offs); optee_free_msg_arg(ctx, entry, offs); return 0; } static bool is_normal_memory(pgprot_t p) { #if defined(CONFIG_ARM) return (((pgprot_val(p) & L_PTE_MT_MASK) == L_PTE_MT_WRITEALLOC) || ((pgprot_val(p) & L_PTE_MT_MASK) == L_PTE_MT_WRITEBACK)); #elif defined(CONFIG_ARM64) return (pgprot_val(p) & PTE_ATTRINDX_MASK) == PTE_ATTRINDX(MT_NORMAL); #else #error "Unsupported architecture" #endif } static int __check_mem_type(struct mm_struct *mm, unsigned long start, unsigned long end) { struct vm_area_struct *vma; VMA_ITERATOR(vmi, mm, start); for_each_vma_range(vmi, vma, end) { if (!is_normal_memory(vma->vm_page_prot)) return -EINVAL; } return 0; } int optee_check_mem_type(unsigned long start, size_t num_pages) { struct mm_struct *mm = current->mm; int rc; /* * Allow kernel address to register with OP-TEE as kernel * pages are configured as normal memory only. */ if (virt_addr_valid((void *)start) || is_vmalloc_addr((void *)start)) return 0; mmap_read_lock(mm); rc = __check_mem_type(mm, start, start + num_pages * PAGE_SIZE); mmap_read_unlock(mm); return rc; }
linux-master
drivers/tee/optee/call.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2021, Linaro Limited */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/arm_ffa.h> #include <linux/errno.h> #include <linux/scatterlist.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/tee_drv.h> #include <linux/types.h> #include "optee_private.h" #include "optee_ffa.h" #include "optee_rpc_cmd.h" /* * This file implement the FF-A ABI used when communicating with secure world * OP-TEE OS via FF-A. * This file is divided into the following sections: * 1. Maintain a hash table for lookup of a global FF-A memory handle * 2. Convert between struct tee_param and struct optee_msg_param * 3. Low level support functions to register shared memory in secure world * 4. Dynamic shared memory pool based on alloc_pages() * 5. Do a normal scheduled call into secure world * 6. Driver initialization. */ /* * 1. Maintain a hash table for lookup of a global FF-A memory handle * * FF-A assigns a global memory handle for each piece shared memory. * This handle is then used when communicating with secure world. * * Main functions are optee_shm_add_ffa_handle() and optee_shm_rem_ffa_handle() */ struct shm_rhash { struct tee_shm *shm; u64 global_id; struct rhash_head linkage; }; static void rh_free_fn(void *ptr, void *arg) { kfree(ptr); } static const struct rhashtable_params shm_rhash_params = { .head_offset = offsetof(struct shm_rhash, linkage), .key_len = sizeof(u64), .key_offset = offsetof(struct shm_rhash, global_id), .automatic_shrinking = true, }; static struct tee_shm *optee_shm_from_ffa_handle(struct optee *optee, u64 global_id) { struct tee_shm *shm = NULL; struct shm_rhash *r; mutex_lock(&optee->ffa.mutex); r = rhashtable_lookup_fast(&optee->ffa.global_ids, &global_id, shm_rhash_params); if (r) shm = r->shm; mutex_unlock(&optee->ffa.mutex); return shm; } static int optee_shm_add_ffa_handle(struct optee *optee, struct tee_shm *shm, u64 global_id) { struct shm_rhash *r; int rc; r = kmalloc(sizeof(*r), GFP_KERNEL); if (!r) return -ENOMEM; r->shm = shm; r->global_id = global_id; mutex_lock(&optee->ffa.mutex); rc = rhashtable_lookup_insert_fast(&optee->ffa.global_ids, &r->linkage, shm_rhash_params); mutex_unlock(&optee->ffa.mutex); if (rc) kfree(r); return rc; } static int optee_shm_rem_ffa_handle(struct optee *optee, u64 global_id) { struct shm_rhash *r; int rc = -ENOENT; mutex_lock(&optee->ffa.mutex); r = rhashtable_lookup_fast(&optee->ffa.global_ids, &global_id, shm_rhash_params); if (r) rc = rhashtable_remove_fast(&optee->ffa.global_ids, &r->linkage, shm_rhash_params); mutex_unlock(&optee->ffa.mutex); if (!rc) kfree(r); return rc; } /* * 2. Convert between struct tee_param and struct optee_msg_param * * optee_ffa_from_msg_param() and optee_ffa_to_msg_param() are the main * functions. */ static void from_msg_param_ffa_mem(struct optee *optee, struct tee_param *p, u32 attr, const struct optee_msg_param *mp) { struct tee_shm *shm = NULL; u64 offs_high = 0; u64 offs_low = 0; p->attr = TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT + attr - OPTEE_MSG_ATTR_TYPE_FMEM_INPUT; p->u.memref.size = mp->u.fmem.size; if (mp->u.fmem.global_id != OPTEE_MSG_FMEM_INVALID_GLOBAL_ID) shm = optee_shm_from_ffa_handle(optee, mp->u.fmem.global_id); p->u.memref.shm = shm; if (shm) { offs_low = mp->u.fmem.offs_low; offs_high = mp->u.fmem.offs_high; } p->u.memref.shm_offs = offs_low | offs_high << 32; } /** * optee_ffa_from_msg_param() - convert from OPTEE_MSG parameters to * struct tee_param * @optee: main service struct * @params: subsystem internal parameter representation * @num_params: number of elements in the parameter arrays * @msg_params: OPTEE_MSG parameters * * Returns 0 on success or <0 on failure */ static int optee_ffa_from_msg_param(struct optee *optee, struct tee_param *params, size_t num_params, const struct optee_msg_param *msg_params) { size_t n; for (n = 0; n < num_params; n++) { struct tee_param *p = params + n; const struct optee_msg_param *mp = msg_params + n; u32 attr = mp->attr & OPTEE_MSG_ATTR_TYPE_MASK; switch (attr) { case OPTEE_MSG_ATTR_TYPE_NONE: p->attr = TEE_IOCTL_PARAM_ATTR_TYPE_NONE; memset(&p->u, 0, sizeof(p->u)); break; case OPTEE_MSG_ATTR_TYPE_VALUE_INPUT: case OPTEE_MSG_ATTR_TYPE_VALUE_OUTPUT: case OPTEE_MSG_ATTR_TYPE_VALUE_INOUT: optee_from_msg_param_value(p, attr, mp); break; case OPTEE_MSG_ATTR_TYPE_FMEM_INPUT: case OPTEE_MSG_ATTR_TYPE_FMEM_OUTPUT: case OPTEE_MSG_ATTR_TYPE_FMEM_INOUT: from_msg_param_ffa_mem(optee, p, attr, mp); break; default: return -EINVAL; } } return 0; } static int to_msg_param_ffa_mem(struct optee_msg_param *mp, const struct tee_param *p) { struct tee_shm *shm = p->u.memref.shm; mp->attr = OPTEE_MSG_ATTR_TYPE_FMEM_INPUT + p->attr - TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT; if (shm) { u64 shm_offs = p->u.memref.shm_offs; mp->u.fmem.internal_offs = shm->offset; mp->u.fmem.offs_low = shm_offs; mp->u.fmem.offs_high = shm_offs >> 32; /* Check that the entire offset could be stored. */ if (mp->u.fmem.offs_high != shm_offs >> 32) return -EINVAL; mp->u.fmem.global_id = shm->sec_world_id; } else { memset(&mp->u, 0, sizeof(mp->u)); mp->u.fmem.global_id = OPTEE_MSG_FMEM_INVALID_GLOBAL_ID; } mp->u.fmem.size = p->u.memref.size; return 0; } /** * optee_ffa_to_msg_param() - convert from struct tee_params to OPTEE_MSG * parameters * @optee: main service struct * @msg_params: OPTEE_MSG parameters * @num_params: number of elements in the parameter arrays * @params: subsystem itnernal parameter representation * Returns 0 on success or <0 on failure */ static int optee_ffa_to_msg_param(struct optee *optee, struct optee_msg_param *msg_params, size_t num_params, const struct tee_param *params) { size_t n; for (n = 0; n < num_params; n++) { const struct tee_param *p = params + n; struct optee_msg_param *mp = msg_params + n; switch (p->attr) { case TEE_IOCTL_PARAM_ATTR_TYPE_NONE: mp->attr = TEE_IOCTL_PARAM_ATTR_TYPE_NONE; memset(&mp->u, 0, sizeof(mp->u)); break; case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_OUTPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INOUT: optee_to_msg_param_value(mp, p); break; case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_OUTPUT: case TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INOUT: if (to_msg_param_ffa_mem(mp, p)) return -EINVAL; break; default: return -EINVAL; } } return 0; } /* * 3. Low level support functions to register shared memory in secure world * * Functions to register and unregister shared memory both for normal * clients and for tee-supplicant. */ static int optee_ffa_shm_register(struct tee_context *ctx, struct tee_shm *shm, struct page **pages, size_t num_pages, unsigned long start) { struct optee *optee = tee_get_drvdata(ctx->teedev); struct ffa_device *ffa_dev = optee->ffa.ffa_dev; const struct ffa_mem_ops *mem_ops = ffa_dev->ops->mem_ops; struct ffa_mem_region_attributes mem_attr = { .receiver = ffa_dev->vm_id, .attrs = FFA_MEM_RW, }; struct ffa_mem_ops_args args = { .use_txbuf = true, .attrs = &mem_attr, .nattrs = 1, }; struct sg_table sgt; int rc; rc = optee_check_mem_type(start, num_pages); if (rc) return rc; rc = sg_alloc_table_from_pages(&sgt, pages, num_pages, 0, num_pages * PAGE_SIZE, GFP_KERNEL); if (rc) return rc; args.sg = sgt.sgl; rc = mem_ops->memory_share(&args); sg_free_table(&sgt); if (rc) return rc; rc = optee_shm_add_ffa_handle(optee, shm, args.g_handle); if (rc) { mem_ops->memory_reclaim(args.g_handle, 0); return rc; } shm->sec_world_id = args.g_handle; return 0; } static int optee_ffa_shm_unregister(struct tee_context *ctx, struct tee_shm *shm) { struct optee *optee = tee_get_drvdata(ctx->teedev); struct ffa_device *ffa_dev = optee->ffa.ffa_dev; const struct ffa_msg_ops *msg_ops = ffa_dev->ops->msg_ops; const struct ffa_mem_ops *mem_ops = ffa_dev->ops->mem_ops; u64 global_handle = shm->sec_world_id; struct ffa_send_direct_data data = { .data0 = OPTEE_FFA_UNREGISTER_SHM, .data1 = (u32)global_handle, .data2 = (u32)(global_handle >> 32) }; int rc; optee_shm_rem_ffa_handle(optee, global_handle); shm->sec_world_id = 0; rc = msg_ops->sync_send_receive(ffa_dev, &data); if (rc) pr_err("Unregister SHM id 0x%llx rc %d\n", global_handle, rc); rc = mem_ops->memory_reclaim(global_handle, 0); if (rc) pr_err("mem_reclaim: 0x%llx %d", global_handle, rc); return rc; } static int optee_ffa_shm_unregister_supp(struct tee_context *ctx, struct tee_shm *shm) { struct optee *optee = tee_get_drvdata(ctx->teedev); const struct ffa_mem_ops *mem_ops; u64 global_handle = shm->sec_world_id; int rc; /* * We're skipping the OPTEE_FFA_YIELDING_CALL_UNREGISTER_SHM call * since this is OP-TEE freeing via RPC so it has already retired * this ID. */ optee_shm_rem_ffa_handle(optee, global_handle); mem_ops = optee->ffa.ffa_dev->ops->mem_ops; rc = mem_ops->memory_reclaim(global_handle, 0); if (rc) pr_err("mem_reclaim: 0x%llx %d", global_handle, rc); shm->sec_world_id = 0; return rc; } /* * 4. Dynamic shared memory pool based on alloc_pages() * * Implements an OP-TEE specific shared memory pool. * The main function is optee_ffa_shm_pool_alloc_pages(). */ static int pool_ffa_op_alloc(struct tee_shm_pool *pool, struct tee_shm *shm, size_t size, size_t align) { return optee_pool_op_alloc_helper(pool, shm, size, align, optee_ffa_shm_register); } static void pool_ffa_op_free(struct tee_shm_pool *pool, struct tee_shm *shm) { optee_pool_op_free_helper(pool, shm, optee_ffa_shm_unregister); } static void pool_ffa_op_destroy_pool(struct tee_shm_pool *pool) { kfree(pool); } static const struct tee_shm_pool_ops pool_ffa_ops = { .alloc = pool_ffa_op_alloc, .free = pool_ffa_op_free, .destroy_pool = pool_ffa_op_destroy_pool, }; /** * optee_ffa_shm_pool_alloc_pages() - create page-based allocator pool * * This pool is used with OP-TEE over FF-A. In this case command buffers * and such are allocated from kernel's own memory. */ static struct tee_shm_pool *optee_ffa_shm_pool_alloc_pages(void) { struct tee_shm_pool *pool = kzalloc(sizeof(*pool), GFP_KERNEL); if (!pool) return ERR_PTR(-ENOMEM); pool->ops = &pool_ffa_ops; return pool; } /* * 5. Do a normal scheduled call into secure world * * The function optee_ffa_do_call_with_arg() performs a normal scheduled * call into secure world. During this call may normal world request help * from normal world using RPCs, Remote Procedure Calls. This includes * delivery of non-secure interrupts to for instance allow rescheduling of * the current task. */ static void handle_ffa_rpc_func_cmd_shm_alloc(struct tee_context *ctx, struct optee *optee, struct optee_msg_arg *arg) { struct tee_shm *shm; if (arg->num_params != 1 || arg->params[0].attr != OPTEE_MSG_ATTR_TYPE_VALUE_INPUT) { arg->ret = TEEC_ERROR_BAD_PARAMETERS; return; } switch (arg->params[0].u.value.a) { case OPTEE_RPC_SHM_TYPE_APPL: shm = optee_rpc_cmd_alloc_suppl(ctx, arg->params[0].u.value.b); break; case OPTEE_RPC_SHM_TYPE_KERNEL: shm = tee_shm_alloc_priv_buf(optee->ctx, arg->params[0].u.value.b); break; default: arg->ret = TEEC_ERROR_BAD_PARAMETERS; return; } if (IS_ERR(shm)) { arg->ret = TEEC_ERROR_OUT_OF_MEMORY; return; } arg->params[0] = (struct optee_msg_param){ .attr = OPTEE_MSG_ATTR_TYPE_FMEM_OUTPUT, .u.fmem.size = tee_shm_get_size(shm), .u.fmem.global_id = shm->sec_world_id, .u.fmem.internal_offs = shm->offset, }; arg->ret = TEEC_SUCCESS; } static void handle_ffa_rpc_func_cmd_shm_free(struct tee_context *ctx, struct optee *optee, struct optee_msg_arg *arg) { struct tee_shm *shm; if (arg->num_params != 1 || arg->params[0].attr != OPTEE_MSG_ATTR_TYPE_VALUE_INPUT) goto err_bad_param; shm = optee_shm_from_ffa_handle(optee, arg->params[0].u.value.b); if (!shm) goto err_bad_param; switch (arg->params[0].u.value.a) { case OPTEE_RPC_SHM_TYPE_APPL: optee_rpc_cmd_free_suppl(ctx, shm); break; case OPTEE_RPC_SHM_TYPE_KERNEL: tee_shm_free(shm); break; default: goto err_bad_param; } arg->ret = TEEC_SUCCESS; return; err_bad_param: arg->ret = TEEC_ERROR_BAD_PARAMETERS; } static void handle_ffa_rpc_func_cmd(struct tee_context *ctx, struct optee *optee, struct optee_msg_arg *arg) { arg->ret_origin = TEEC_ORIGIN_COMMS; switch (arg->cmd) { case OPTEE_RPC_CMD_SHM_ALLOC: handle_ffa_rpc_func_cmd_shm_alloc(ctx, optee, arg); break; case OPTEE_RPC_CMD_SHM_FREE: handle_ffa_rpc_func_cmd_shm_free(ctx, optee, arg); break; default: optee_rpc_cmd(ctx, optee, arg); } } static void optee_handle_ffa_rpc(struct tee_context *ctx, struct optee *optee, u32 cmd, struct optee_msg_arg *arg) { switch (cmd) { case OPTEE_FFA_YIELDING_CALL_RETURN_RPC_CMD: handle_ffa_rpc_func_cmd(ctx, optee, arg); break; case OPTEE_FFA_YIELDING_CALL_RETURN_INTERRUPT: /* Interrupt delivered by now */ break; default: pr_warn("Unknown RPC func 0x%x\n", cmd); break; } } static int optee_ffa_yielding_call(struct tee_context *ctx, struct ffa_send_direct_data *data, struct optee_msg_arg *rpc_arg) { struct optee *optee = tee_get_drvdata(ctx->teedev); struct ffa_device *ffa_dev = optee->ffa.ffa_dev; const struct ffa_msg_ops *msg_ops = ffa_dev->ops->msg_ops; struct optee_call_waiter w; u32 cmd = data->data0; u32 w4 = data->data1; u32 w5 = data->data2; u32 w6 = data->data3; int rc; /* Initialize waiter */ optee_cq_wait_init(&optee->call_queue, &w); while (true) { rc = msg_ops->sync_send_receive(ffa_dev, data); if (rc) goto done; switch ((int)data->data0) { case TEEC_SUCCESS: break; case TEEC_ERROR_BUSY: if (cmd == OPTEE_FFA_YIELDING_CALL_RESUME) { rc = -EIO; goto done; } /* * Out of threads in secure world, wait for a thread * become available. */ optee_cq_wait_for_completion(&optee->call_queue, &w); data->data0 = cmd; data->data1 = w4; data->data2 = w5; data->data3 = w6; continue; default: rc = -EIO; goto done; } if (data->data1 == OPTEE_FFA_YIELDING_CALL_RETURN_DONE) goto done; /* * OP-TEE has returned with a RPC request. * * Note that data->data4 (passed in register w7) is already * filled in by ffa_mem_ops->sync_send_receive() returning * above. */ cond_resched(); optee_handle_ffa_rpc(ctx, optee, data->data1, rpc_arg); cmd = OPTEE_FFA_YIELDING_CALL_RESUME; data->data0 = cmd; data->data1 = 0; data->data2 = 0; data->data3 = 0; } done: /* * We're done with our thread in secure world, if there's any * thread waiters wake up one. */ optee_cq_wait_final(&optee->call_queue, &w); return rc; } /** * optee_ffa_do_call_with_arg() - Do a FF-A call to enter OP-TEE in secure world * @ctx: calling context * @shm: shared memory holding the message to pass to secure world * @offs: offset of the message in @shm * * Does a FF-A call to OP-TEE in secure world and handles eventual resulting * Remote Procedure Calls (RPC) from OP-TEE. * * Returns return code from FF-A, 0 is OK */ static int optee_ffa_do_call_with_arg(struct tee_context *ctx, struct tee_shm *shm, u_int offs) { struct ffa_send_direct_data data = { .data0 = OPTEE_FFA_YIELDING_CALL_WITH_ARG, .data1 = (u32)shm->sec_world_id, .data2 = (u32)(shm->sec_world_id >> 32), .data3 = offs, }; struct optee_msg_arg *arg; unsigned int rpc_arg_offs; struct optee_msg_arg *rpc_arg; /* * The shared memory object has to start on a page when passed as * an argument struct. This is also what the shm pool allocator * returns, but check this before calling secure world to catch * eventual errors early in case something changes. */ if (shm->offset) return -EINVAL; arg = tee_shm_get_va(shm, offs); if (IS_ERR(arg)) return PTR_ERR(arg); rpc_arg_offs = OPTEE_MSG_GET_ARG_SIZE(arg->num_params); rpc_arg = tee_shm_get_va(shm, offs + rpc_arg_offs); if (IS_ERR(rpc_arg)) return PTR_ERR(rpc_arg); return optee_ffa_yielding_call(ctx, &data, rpc_arg); } /* * 6. Driver initialization * * During driver inititialization is the OP-TEE Secure Partition is probed * to find out which features it supports so the driver can be initialized * with a matching configuration. */ static bool optee_ffa_api_is_compatbile(struct ffa_device *ffa_dev, const struct ffa_ops *ops) { const struct ffa_msg_ops *msg_ops = ops->msg_ops; struct ffa_send_direct_data data = { OPTEE_FFA_GET_API_VERSION }; int rc; msg_ops->mode_32bit_set(ffa_dev); rc = msg_ops->sync_send_receive(ffa_dev, &data); if (rc) { pr_err("Unexpected error %d\n", rc); return false; } if (data.data0 != OPTEE_FFA_VERSION_MAJOR || data.data1 < OPTEE_FFA_VERSION_MINOR) { pr_err("Incompatible OP-TEE API version %lu.%lu", data.data0, data.data1); return false; } data = (struct ffa_send_direct_data){ OPTEE_FFA_GET_OS_VERSION }; rc = msg_ops->sync_send_receive(ffa_dev, &data); if (rc) { pr_err("Unexpected error %d\n", rc); return false; } if (data.data2) pr_info("revision %lu.%lu (%08lx)", data.data0, data.data1, data.data2); else pr_info("revision %lu.%lu", data.data0, data.data1); return true; } static bool optee_ffa_exchange_caps(struct ffa_device *ffa_dev, const struct ffa_ops *ops, u32 *sec_caps, unsigned int *rpc_param_count) { struct ffa_send_direct_data data = { OPTEE_FFA_EXCHANGE_CAPABILITIES }; int rc; rc = ops->msg_ops->sync_send_receive(ffa_dev, &data); if (rc) { pr_err("Unexpected error %d", rc); return false; } if (data.data0) { pr_err("Unexpected exchange error %lu", data.data0); return false; } *rpc_param_count = (u8)data.data1; *sec_caps = data.data2; return true; } static void optee_ffa_get_version(struct tee_device *teedev, struct tee_ioctl_version_data *vers) { struct tee_ioctl_version_data v = { .impl_id = TEE_IMPL_ID_OPTEE, .impl_caps = TEE_OPTEE_CAP_TZ, .gen_caps = TEE_GEN_CAP_GP | TEE_GEN_CAP_REG_MEM | TEE_GEN_CAP_MEMREF_NULL, }; *vers = v; } static int optee_ffa_open(struct tee_context *ctx) { return optee_open(ctx, true); } static const struct tee_driver_ops optee_ffa_clnt_ops = { .get_version = optee_ffa_get_version, .open = optee_ffa_open, .release = optee_release, .open_session = optee_open_session, .close_session = optee_close_session, .invoke_func = optee_invoke_func, .cancel_req = optee_cancel_req, .shm_register = optee_ffa_shm_register, .shm_unregister = optee_ffa_shm_unregister, }; static const struct tee_desc optee_ffa_clnt_desc = { .name = DRIVER_NAME "-ffa-clnt", .ops = &optee_ffa_clnt_ops, .owner = THIS_MODULE, }; static const struct tee_driver_ops optee_ffa_supp_ops = { .get_version = optee_ffa_get_version, .open = optee_ffa_open, .release = optee_release_supp, .supp_recv = optee_supp_recv, .supp_send = optee_supp_send, .shm_register = optee_ffa_shm_register, /* same as for clnt ops */ .shm_unregister = optee_ffa_shm_unregister_supp, }; static const struct tee_desc optee_ffa_supp_desc = { .name = DRIVER_NAME "-ffa-supp", .ops = &optee_ffa_supp_ops, .owner = THIS_MODULE, .flags = TEE_DESC_PRIVILEGED, }; static const struct optee_ops optee_ffa_ops = { .do_call_with_arg = optee_ffa_do_call_with_arg, .to_msg_param = optee_ffa_to_msg_param, .from_msg_param = optee_ffa_from_msg_param, }; static void optee_ffa_remove(struct ffa_device *ffa_dev) { struct optee *optee = ffa_dev_get_drvdata(ffa_dev); optee_remove_common(optee); mutex_destroy(&optee->ffa.mutex); rhashtable_free_and_destroy(&optee->ffa.global_ids, rh_free_fn, NULL); kfree(optee); } static int optee_ffa_probe(struct ffa_device *ffa_dev) { const struct ffa_ops *ffa_ops; unsigned int rpc_param_count; struct tee_shm_pool *pool; struct tee_device *teedev; struct tee_context *ctx; u32 arg_cache_flags = 0; struct optee *optee; u32 sec_caps; int rc; ffa_ops = ffa_dev->ops; if (!optee_ffa_api_is_compatbile(ffa_dev, ffa_ops)) return -EINVAL; if (!optee_ffa_exchange_caps(ffa_dev, ffa_ops, &sec_caps, &rpc_param_count)) return -EINVAL; if (sec_caps & OPTEE_FFA_SEC_CAP_ARG_OFFSET) arg_cache_flags |= OPTEE_SHM_ARG_SHARED; optee = kzalloc(sizeof(*optee), GFP_KERNEL); if (!optee) return -ENOMEM; pool = optee_ffa_shm_pool_alloc_pages(); if (IS_ERR(pool)) { rc = PTR_ERR(pool); goto err_free_optee; } optee->pool = pool; optee->ops = &optee_ffa_ops; optee->ffa.ffa_dev = ffa_dev; optee->rpc_param_count = rpc_param_count; teedev = tee_device_alloc(&optee_ffa_clnt_desc, NULL, optee->pool, optee); if (IS_ERR(teedev)) { rc = PTR_ERR(teedev); goto err_free_pool; } optee->teedev = teedev; teedev = tee_device_alloc(&optee_ffa_supp_desc, NULL, optee->pool, optee); if (IS_ERR(teedev)) { rc = PTR_ERR(teedev); goto err_unreg_teedev; } optee->supp_teedev = teedev; rc = tee_device_register(optee->teedev); if (rc) goto err_unreg_supp_teedev; rc = tee_device_register(optee->supp_teedev); if (rc) goto err_unreg_supp_teedev; rc = rhashtable_init(&optee->ffa.global_ids, &shm_rhash_params); if (rc) goto err_unreg_supp_teedev; mutex_init(&optee->ffa.mutex); mutex_init(&optee->call_queue.mutex); INIT_LIST_HEAD(&optee->call_queue.waiters); optee_supp_init(&optee->supp); optee_shm_arg_cache_init(optee, arg_cache_flags); ffa_dev_set_drvdata(ffa_dev, optee); ctx = teedev_open(optee->teedev); if (IS_ERR(ctx)) { rc = PTR_ERR(ctx); goto err_rhashtable_free; } optee->ctx = ctx; rc = optee_notif_init(optee, OPTEE_DEFAULT_MAX_NOTIF_VALUE); if (rc) goto err_close_ctx; rc = optee_enumerate_devices(PTA_CMD_GET_DEVICES); if (rc) goto err_unregister_devices; pr_info("initialized driver\n"); return 0; err_unregister_devices: optee_unregister_devices(); optee_notif_uninit(optee); err_close_ctx: teedev_close_context(ctx); err_rhashtable_free: rhashtable_free_and_destroy(&optee->ffa.global_ids, rh_free_fn, NULL); optee_supp_uninit(&optee->supp); mutex_destroy(&optee->call_queue.mutex); mutex_destroy(&optee->ffa.mutex); err_unreg_supp_teedev: tee_device_unregister(optee->supp_teedev); err_unreg_teedev: tee_device_unregister(optee->teedev); err_free_pool: tee_shm_pool_free(pool); err_free_optee: kfree(optee); return rc; } static const struct ffa_device_id optee_ffa_device_id[] = { /* 486178e0-e7f8-11e3-bc5e0002a5d5c51b */ { UUID_INIT(0x486178e0, 0xe7f8, 0x11e3, 0xbc, 0x5e, 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b) }, {} }; static struct ffa_driver optee_ffa_driver = { .name = "optee", .probe = optee_ffa_probe, .remove = optee_ffa_remove, .id_table = optee_ffa_device_id, }; int optee_ffa_abi_register(void) { if (IS_REACHABLE(CONFIG_ARM_FFA_TRANSPORT)) return ffa_register(&optee_ffa_driver); else return -EOPNOTSUPP; } void optee_ffa_abi_unregister(void) { if (IS_REACHABLE(CONFIG_ARM_FFA_TRANSPORT)) ffa_unregister(&optee_ffa_driver); }
linux-master
drivers/tee/optee/ffa_abi.c
// SPDX-License-Identifier: GPL-2.0 /* * Virtio-based remote processor messaging bus * * Copyright (C) 2011 Texas Instruments, Inc. * Copyright (C) 2011 Google, Inc. * * Ohad Ben-Cohen <[email protected]> * Brian Swetland <[email protected]> */ #define pr_fmt(fmt) "%s: " fmt, __func__ #include <linux/dma-mapping.h> #include <linux/idr.h> #include <linux/jiffies.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/mutex.h> #include <linux/rpmsg.h> #include <linux/rpmsg/byteorder.h> #include <linux/rpmsg/ns.h> #include <linux/scatterlist.h> #include <linux/slab.h> #include <linux/sched.h> #include <linux/virtio.h> #include <linux/virtio_ids.h> #include <linux/virtio_config.h> #include <linux/wait.h> #include "rpmsg_internal.h" /** * struct virtproc_info - virtual remote processor state * @vdev: the virtio device * @rvq: rx virtqueue * @svq: tx virtqueue * @rbufs: kernel address of rx buffers * @sbufs: kernel address of tx buffers * @num_bufs: total number of buffers for rx and tx * @buf_size: size of one rx or tx buffer * @last_sbuf: index of last tx buffer used * @bufs_dma: dma base addr of the buffers * @tx_lock: protects svq, sbufs and sleepers, to allow concurrent senders. * sending a message might require waking up a dozing remote * processor, which involves sleeping, hence the mutex. * @endpoints: idr of local endpoints, allows fast retrieval * @endpoints_lock: lock of the endpoints set * @sendq: wait queue of sending contexts waiting for a tx buffers * @sleepers: number of senders that are waiting for a tx buffer * * This structure stores the rpmsg state of a given virtio remote processor * device (there might be several virtio proc devices for each physical * remote processor). */ struct virtproc_info { struct virtio_device *vdev; struct virtqueue *rvq, *svq; void *rbufs, *sbufs; unsigned int num_bufs; unsigned int buf_size; int last_sbuf; dma_addr_t bufs_dma; struct mutex tx_lock; struct idr endpoints; struct mutex endpoints_lock; wait_queue_head_t sendq; atomic_t sleepers; }; /* The feature bitmap for virtio rpmsg */ #define VIRTIO_RPMSG_F_NS 0 /* RP supports name service notifications */ /** * struct rpmsg_hdr - common header for all rpmsg messages * @src: source address * @dst: destination address * @reserved: reserved for future use * @len: length of payload (in bytes) * @flags: message flags * @data: @len bytes of message payload data * * Every message sent(/received) on the rpmsg bus begins with this header. */ struct rpmsg_hdr { __rpmsg32 src; __rpmsg32 dst; __rpmsg32 reserved; __rpmsg16 len; __rpmsg16 flags; u8 data[]; } __packed; /** * struct virtio_rpmsg_channel - rpmsg channel descriptor * @rpdev: the rpmsg channel device * @vrp: the virtio remote processor device this channel belongs to * * This structure stores the channel that links the rpmsg device to the virtio * remote processor device. */ struct virtio_rpmsg_channel { struct rpmsg_device rpdev; struct virtproc_info *vrp; }; #define to_virtio_rpmsg_channel(_rpdev) \ container_of(_rpdev, struct virtio_rpmsg_channel, rpdev) /* * We're allocating buffers of 512 bytes each for communications. The * number of buffers will be computed from the number of buffers supported * by the vring, upto a maximum of 512 buffers (256 in each direction). * * Each buffer will have 16 bytes for the msg header and 496 bytes for * the payload. * * This will utilize a maximum total space of 256KB for the buffers. * * We might also want to add support for user-provided buffers in time. * This will allow bigger buffer size flexibility, and can also be used * to achieve zero-copy messaging. * * Note that these numbers are purely a decision of this driver - we * can change this without changing anything in the firmware of the remote * processor. */ #define MAX_RPMSG_NUM_BUFS (512) #define MAX_RPMSG_BUF_SIZE (512) /* * Local addresses are dynamically allocated on-demand. * We do not dynamically assign addresses from the low 1024 range, * in order to reserve that address range for predefined services. */ #define RPMSG_RESERVED_ADDRESSES (1024) static void virtio_rpmsg_destroy_ept(struct rpmsg_endpoint *ept); static int virtio_rpmsg_send(struct rpmsg_endpoint *ept, void *data, int len); static int virtio_rpmsg_sendto(struct rpmsg_endpoint *ept, void *data, int len, u32 dst); static int virtio_rpmsg_send_offchannel(struct rpmsg_endpoint *ept, u32 src, u32 dst, void *data, int len); static int virtio_rpmsg_trysend(struct rpmsg_endpoint *ept, void *data, int len); static int virtio_rpmsg_trysendto(struct rpmsg_endpoint *ept, void *data, int len, u32 dst); static int virtio_rpmsg_trysend_offchannel(struct rpmsg_endpoint *ept, u32 src, u32 dst, void *data, int len); static ssize_t virtio_rpmsg_get_mtu(struct rpmsg_endpoint *ept); static struct rpmsg_device *__rpmsg_create_channel(struct virtproc_info *vrp, struct rpmsg_channel_info *chinfo); static const struct rpmsg_endpoint_ops virtio_endpoint_ops = { .destroy_ept = virtio_rpmsg_destroy_ept, .send = virtio_rpmsg_send, .sendto = virtio_rpmsg_sendto, .send_offchannel = virtio_rpmsg_send_offchannel, .trysend = virtio_rpmsg_trysend, .trysendto = virtio_rpmsg_trysendto, .trysend_offchannel = virtio_rpmsg_trysend_offchannel, .get_mtu = virtio_rpmsg_get_mtu, }; /** * rpmsg_sg_init - initialize scatterlist according to cpu address location * @sg: scatterlist to fill * @cpu_addr: virtual address of the buffer * @len: buffer length * * An internal function filling scatterlist according to virtual address * location (in vmalloc or in kernel). */ static void rpmsg_sg_init(struct scatterlist *sg, void *cpu_addr, unsigned int len) { if (is_vmalloc_addr(cpu_addr)) { sg_init_table(sg, 1); sg_set_page(sg, vmalloc_to_page(cpu_addr), len, offset_in_page(cpu_addr)); } else { WARN_ON(!virt_addr_valid(cpu_addr)); sg_init_one(sg, cpu_addr, len); } } /** * __ept_release() - deallocate an rpmsg endpoint * @kref: the ept's reference count * * This function deallocates an ept, and is invoked when its @kref refcount * drops to zero. * * Never invoke this function directly! */ static void __ept_release(struct kref *kref) { struct rpmsg_endpoint *ept = container_of(kref, struct rpmsg_endpoint, refcount); /* * At this point no one holds a reference to ept anymore, * so we can directly free it */ kfree(ept); } /* for more info, see below documentation of rpmsg_create_ept() */ static struct rpmsg_endpoint *__rpmsg_create_ept(struct virtproc_info *vrp, struct rpmsg_device *rpdev, rpmsg_rx_cb_t cb, void *priv, u32 addr) { int id_min, id_max, id; struct rpmsg_endpoint *ept; struct device *dev = rpdev ? &rpdev->dev : &vrp->vdev->dev; ept = kzalloc(sizeof(*ept), GFP_KERNEL); if (!ept) return NULL; kref_init(&ept->refcount); mutex_init(&ept->cb_lock); ept->rpdev = rpdev; ept->cb = cb; ept->priv = priv; ept->ops = &virtio_endpoint_ops; /* do we need to allocate a local address ? */ if (addr == RPMSG_ADDR_ANY) { id_min = RPMSG_RESERVED_ADDRESSES; id_max = 0; } else { id_min = addr; id_max = addr + 1; } mutex_lock(&vrp->endpoints_lock); /* bind the endpoint to an rpmsg address (and allocate one if needed) */ id = idr_alloc(&vrp->endpoints, ept, id_min, id_max, GFP_KERNEL); if (id < 0) { dev_err(dev, "idr_alloc failed: %d\n", id); goto free_ept; } ept->addr = id; mutex_unlock(&vrp->endpoints_lock); return ept; free_ept: mutex_unlock(&vrp->endpoints_lock); kref_put(&ept->refcount, __ept_release); return NULL; } static struct rpmsg_device *virtio_rpmsg_create_channel(struct rpmsg_device *rpdev, struct rpmsg_channel_info *chinfo) { struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(rpdev); struct virtproc_info *vrp = vch->vrp; return __rpmsg_create_channel(vrp, chinfo); } static int virtio_rpmsg_release_channel(struct rpmsg_device *rpdev, struct rpmsg_channel_info *chinfo) { struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(rpdev); struct virtproc_info *vrp = vch->vrp; return rpmsg_unregister_device(&vrp->vdev->dev, chinfo); } static struct rpmsg_endpoint *virtio_rpmsg_create_ept(struct rpmsg_device *rpdev, rpmsg_rx_cb_t cb, void *priv, struct rpmsg_channel_info chinfo) { struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(rpdev); return __rpmsg_create_ept(vch->vrp, rpdev, cb, priv, chinfo.src); } /** * __rpmsg_destroy_ept() - destroy an existing rpmsg endpoint * @vrp: virtproc which owns this ept * @ept: endpoing to destroy * * An internal function which destroy an ept without assuming it is * bound to an rpmsg channel. This is needed for handling the internal * name service endpoint, which isn't bound to an rpmsg channel. * See also __rpmsg_create_ept(). */ static void __rpmsg_destroy_ept(struct virtproc_info *vrp, struct rpmsg_endpoint *ept) { /* make sure new inbound messages can't find this ept anymore */ mutex_lock(&vrp->endpoints_lock); idr_remove(&vrp->endpoints, ept->addr); mutex_unlock(&vrp->endpoints_lock); /* make sure in-flight inbound messages won't invoke cb anymore */ mutex_lock(&ept->cb_lock); ept->cb = NULL; mutex_unlock(&ept->cb_lock); kref_put(&ept->refcount, __ept_release); } static void virtio_rpmsg_destroy_ept(struct rpmsg_endpoint *ept) { struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(ept->rpdev); __rpmsg_destroy_ept(vch->vrp, ept); } static int virtio_rpmsg_announce_create(struct rpmsg_device *rpdev) { struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(rpdev); struct virtproc_info *vrp = vch->vrp; struct device *dev = &rpdev->dev; int err = 0; /* need to tell remote processor's name service about this channel ? */ if (rpdev->announce && rpdev->ept && virtio_has_feature(vrp->vdev, VIRTIO_RPMSG_F_NS)) { struct rpmsg_ns_msg nsm; strncpy(nsm.name, rpdev->id.name, RPMSG_NAME_SIZE); nsm.addr = cpu_to_rpmsg32(rpdev, rpdev->ept->addr); nsm.flags = cpu_to_rpmsg32(rpdev, RPMSG_NS_CREATE); err = rpmsg_sendto(rpdev->ept, &nsm, sizeof(nsm), RPMSG_NS_ADDR); if (err) dev_err(dev, "failed to announce service %d\n", err); } return err; } static int virtio_rpmsg_announce_destroy(struct rpmsg_device *rpdev) { struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(rpdev); struct virtproc_info *vrp = vch->vrp; struct device *dev = &rpdev->dev; int err = 0; /* tell remote processor's name service we're removing this channel */ if (rpdev->announce && rpdev->ept && virtio_has_feature(vrp->vdev, VIRTIO_RPMSG_F_NS)) { struct rpmsg_ns_msg nsm; strncpy(nsm.name, rpdev->id.name, RPMSG_NAME_SIZE); nsm.addr = cpu_to_rpmsg32(rpdev, rpdev->ept->addr); nsm.flags = cpu_to_rpmsg32(rpdev, RPMSG_NS_DESTROY); err = rpmsg_sendto(rpdev->ept, &nsm, sizeof(nsm), RPMSG_NS_ADDR); if (err) dev_err(dev, "failed to announce service %d\n", err); } return err; } static const struct rpmsg_device_ops virtio_rpmsg_ops = { .create_channel = virtio_rpmsg_create_channel, .release_channel = virtio_rpmsg_release_channel, .create_ept = virtio_rpmsg_create_ept, .announce_create = virtio_rpmsg_announce_create, .announce_destroy = virtio_rpmsg_announce_destroy, }; static void virtio_rpmsg_release_device(struct device *dev) { struct rpmsg_device *rpdev = to_rpmsg_device(dev); struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(rpdev); kfree(vch); } /* * create an rpmsg channel using its name and address info. * this function will be used to create both static and dynamic * channels. */ static struct rpmsg_device *__rpmsg_create_channel(struct virtproc_info *vrp, struct rpmsg_channel_info *chinfo) { struct virtio_rpmsg_channel *vch; struct rpmsg_device *rpdev; struct device *tmp, *dev = &vrp->vdev->dev; int ret; /* make sure a similar channel doesn't already exist */ tmp = rpmsg_find_device(dev, chinfo); if (tmp) { /* decrement the matched device's refcount back */ put_device(tmp); dev_err(dev, "channel %s:%x:%x already exist\n", chinfo->name, chinfo->src, chinfo->dst); return NULL; } vch = kzalloc(sizeof(*vch), GFP_KERNEL); if (!vch) return NULL; /* Link the channel to our vrp */ vch->vrp = vrp; /* Assign public information to the rpmsg_device */ rpdev = &vch->rpdev; rpdev->src = chinfo->src; rpdev->dst = chinfo->dst; rpdev->ops = &virtio_rpmsg_ops; rpdev->little_endian = virtio_is_little_endian(vrp->vdev); /* * rpmsg server channels has predefined local address (for now), * and their existence needs to be announced remotely */ rpdev->announce = rpdev->src != RPMSG_ADDR_ANY; strncpy(rpdev->id.name, chinfo->name, RPMSG_NAME_SIZE); rpdev->dev.parent = &vrp->vdev->dev; rpdev->dev.release = virtio_rpmsg_release_device; ret = rpmsg_register_device(rpdev); if (ret) return NULL; return rpdev; } /* super simple buffer "allocator" that is just enough for now */ static void *get_a_tx_buf(struct virtproc_info *vrp) { unsigned int len; void *ret; /* support multiple concurrent senders */ mutex_lock(&vrp->tx_lock); /* * either pick the next unused tx buffer * (half of our buffers are used for sending messages) */ if (vrp->last_sbuf < vrp->num_bufs / 2) ret = vrp->sbufs + vrp->buf_size * vrp->last_sbuf++; /* or recycle a used one */ else ret = virtqueue_get_buf(vrp->svq, &len); mutex_unlock(&vrp->tx_lock); return ret; } /** * rpmsg_upref_sleepers() - enable "tx-complete" interrupts, if needed * @vrp: virtual remote processor state * * This function is called before a sender is blocked, waiting for * a tx buffer to become available. * * If we already have blocking senders, this function merely increases * the "sleepers" reference count, and exits. * * Otherwise, if this is the first sender to block, we also enable * virtio's tx callbacks, so we'd be immediately notified when a tx * buffer is consumed (we rely on virtio's tx callback in order * to wake up sleeping senders as soon as a tx buffer is used by the * remote processor). */ static void rpmsg_upref_sleepers(struct virtproc_info *vrp) { /* support multiple concurrent senders */ mutex_lock(&vrp->tx_lock); /* are we the first sleeping context waiting for tx buffers ? */ if (atomic_inc_return(&vrp->sleepers) == 1) /* enable "tx-complete" interrupts before dozing off */ virtqueue_enable_cb(vrp->svq); mutex_unlock(&vrp->tx_lock); } /** * rpmsg_downref_sleepers() - disable "tx-complete" interrupts, if needed * @vrp: virtual remote processor state * * This function is called after a sender, that waited for a tx buffer * to become available, is unblocked. * * If we still have blocking senders, this function merely decreases * the "sleepers" reference count, and exits. * * Otherwise, if there are no more blocking senders, we also disable * virtio's tx callbacks, to avoid the overhead incurred with handling * those (now redundant) interrupts. */ static void rpmsg_downref_sleepers(struct virtproc_info *vrp) { /* support multiple concurrent senders */ mutex_lock(&vrp->tx_lock); /* are we the last sleeping context waiting for tx buffers ? */ if (atomic_dec_and_test(&vrp->sleepers)) /* disable "tx-complete" interrupts */ virtqueue_disable_cb(vrp->svq); mutex_unlock(&vrp->tx_lock); } /** * rpmsg_send_offchannel_raw() - send a message across to the remote processor * @rpdev: the rpmsg channel * @src: source address * @dst: destination address * @data: payload of message * @len: length of payload * @wait: indicates whether caller should block in case no TX buffers available * * This function is the base implementation for all of the rpmsg sending API. * * It will send @data of length @len to @dst, and say it's from @src. The * message will be sent to the remote processor which the @rpdev channel * belongs to. * * The message is sent using one of the TX buffers that are available for * communication with this remote processor. * * If @wait is true, the caller will be blocked until either a TX buffer is * available, or 15 seconds elapses (we don't want callers to * sleep indefinitely due to misbehaving remote processors), and in that * case -ERESTARTSYS is returned. The number '15' itself was picked * arbitrarily; there's little point in asking drivers to provide a timeout * value themselves. * * Otherwise, if @wait is false, and there are no TX buffers available, * the function will immediately fail, and -ENOMEM will be returned. * * Normally drivers shouldn't use this function directly; instead, drivers * should use the appropriate rpmsg_{try}send{to, _offchannel} API * (see include/linux/rpmsg.h). * * Return: 0 on success and an appropriate error value on failure. */ static int rpmsg_send_offchannel_raw(struct rpmsg_device *rpdev, u32 src, u32 dst, void *data, int len, bool wait) { struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(rpdev); struct virtproc_info *vrp = vch->vrp; struct device *dev = &rpdev->dev; struct scatterlist sg; struct rpmsg_hdr *msg; int err; /* bcasting isn't allowed */ if (src == RPMSG_ADDR_ANY || dst == RPMSG_ADDR_ANY) { dev_err(dev, "invalid addr (src 0x%x, dst 0x%x)\n", src, dst); return -EINVAL; } /* * We currently use fixed-sized buffers, and therefore the payload * length is limited. * * One of the possible improvements here is either to support * user-provided buffers (and then we can also support zero-copy * messaging), or to improve the buffer allocator, to support * variable-length buffer sizes. */ if (len > vrp->buf_size - sizeof(struct rpmsg_hdr)) { dev_err(dev, "message is too big (%d)\n", len); return -EMSGSIZE; } /* grab a buffer */ msg = get_a_tx_buf(vrp); if (!msg && !wait) return -ENOMEM; /* no free buffer ? wait for one (but bail after 15 seconds) */ while (!msg) { /* enable "tx-complete" interrupts, if not already enabled */ rpmsg_upref_sleepers(vrp); /* * sleep until a free buffer is available or 15 secs elapse. * the timeout period is not configurable because there's * little point in asking drivers to specify that. * if later this happens to be required, it'd be easy to add. */ err = wait_event_interruptible_timeout(vrp->sendq, (msg = get_a_tx_buf(vrp)), msecs_to_jiffies(15000)); /* disable "tx-complete" interrupts if we're the last sleeper */ rpmsg_downref_sleepers(vrp); /* timeout ? */ if (!err) { dev_err(dev, "timeout waiting for a tx buffer\n"); return -ERESTARTSYS; } } msg->len = cpu_to_rpmsg16(rpdev, len); msg->flags = 0; msg->src = cpu_to_rpmsg32(rpdev, src); msg->dst = cpu_to_rpmsg32(rpdev, dst); msg->reserved = 0; memcpy(msg->data, data, len); dev_dbg(dev, "TX From 0x%x, To 0x%x, Len %d, Flags %d, Reserved %d\n", src, dst, len, msg->flags, msg->reserved); #if defined(CONFIG_DYNAMIC_DEBUG) dynamic_hex_dump("rpmsg_virtio TX: ", DUMP_PREFIX_NONE, 16, 1, msg, sizeof(*msg) + len, true); #endif rpmsg_sg_init(&sg, msg, sizeof(*msg) + len); mutex_lock(&vrp->tx_lock); /* add message to the remote processor's virtqueue */ err = virtqueue_add_outbuf(vrp->svq, &sg, 1, msg, GFP_KERNEL); if (err) { /* * need to reclaim the buffer here, otherwise it's lost * (memory won't leak, but rpmsg won't use it again for TX). * this will wait for a buffer management overhaul. */ dev_err(dev, "virtqueue_add_outbuf failed: %d\n", err); goto out; } /* tell the remote processor it has a pending message to read */ virtqueue_kick(vrp->svq); out: mutex_unlock(&vrp->tx_lock); return err; } static int virtio_rpmsg_send(struct rpmsg_endpoint *ept, void *data, int len) { struct rpmsg_device *rpdev = ept->rpdev; u32 src = ept->addr, dst = rpdev->dst; return rpmsg_send_offchannel_raw(rpdev, src, dst, data, len, true); } static int virtio_rpmsg_sendto(struct rpmsg_endpoint *ept, void *data, int len, u32 dst) { struct rpmsg_device *rpdev = ept->rpdev; u32 src = ept->addr; return rpmsg_send_offchannel_raw(rpdev, src, dst, data, len, true); } static int virtio_rpmsg_send_offchannel(struct rpmsg_endpoint *ept, u32 src, u32 dst, void *data, int len) { struct rpmsg_device *rpdev = ept->rpdev; return rpmsg_send_offchannel_raw(rpdev, src, dst, data, len, true); } static int virtio_rpmsg_trysend(struct rpmsg_endpoint *ept, void *data, int len) { struct rpmsg_device *rpdev = ept->rpdev; u32 src = ept->addr, dst = rpdev->dst; return rpmsg_send_offchannel_raw(rpdev, src, dst, data, len, false); } static int virtio_rpmsg_trysendto(struct rpmsg_endpoint *ept, void *data, int len, u32 dst) { struct rpmsg_device *rpdev = ept->rpdev; u32 src = ept->addr; return rpmsg_send_offchannel_raw(rpdev, src, dst, data, len, false); } static int virtio_rpmsg_trysend_offchannel(struct rpmsg_endpoint *ept, u32 src, u32 dst, void *data, int len) { struct rpmsg_device *rpdev = ept->rpdev; return rpmsg_send_offchannel_raw(rpdev, src, dst, data, len, false); } static ssize_t virtio_rpmsg_get_mtu(struct rpmsg_endpoint *ept) { struct rpmsg_device *rpdev = ept->rpdev; struct virtio_rpmsg_channel *vch = to_virtio_rpmsg_channel(rpdev); return vch->vrp->buf_size - sizeof(struct rpmsg_hdr); } static int rpmsg_recv_single(struct virtproc_info *vrp, struct device *dev, struct rpmsg_hdr *msg, unsigned int len) { struct rpmsg_endpoint *ept; struct scatterlist sg; bool little_endian = virtio_is_little_endian(vrp->vdev); unsigned int msg_len = __rpmsg16_to_cpu(little_endian, msg->len); int err; dev_dbg(dev, "From: 0x%x, To: 0x%x, Len: %d, Flags: %d, Reserved: %d\n", __rpmsg32_to_cpu(little_endian, msg->src), __rpmsg32_to_cpu(little_endian, msg->dst), msg_len, __rpmsg16_to_cpu(little_endian, msg->flags), __rpmsg32_to_cpu(little_endian, msg->reserved)); #if defined(CONFIG_DYNAMIC_DEBUG) dynamic_hex_dump("rpmsg_virtio RX: ", DUMP_PREFIX_NONE, 16, 1, msg, sizeof(*msg) + msg_len, true); #endif /* * We currently use fixed-sized buffers, so trivially sanitize * the reported payload length. */ if (len > vrp->buf_size || msg_len > (len - sizeof(struct rpmsg_hdr))) { dev_warn(dev, "inbound msg too big: (%d, %d)\n", len, msg_len); return -EINVAL; } /* use the dst addr to fetch the callback of the appropriate user */ mutex_lock(&vrp->endpoints_lock); ept = idr_find(&vrp->endpoints, __rpmsg32_to_cpu(little_endian, msg->dst)); /* let's make sure no one deallocates ept while we use it */ if (ept) kref_get(&ept->refcount); mutex_unlock(&vrp->endpoints_lock); if (ept) { /* make sure ept->cb doesn't go away while we use it */ mutex_lock(&ept->cb_lock); if (ept->cb) ept->cb(ept->rpdev, msg->data, msg_len, ept->priv, __rpmsg32_to_cpu(little_endian, msg->src)); mutex_unlock(&ept->cb_lock); /* farewell, ept, we don't need you anymore */ kref_put(&ept->refcount, __ept_release); } else dev_warn_ratelimited(dev, "msg received with no recipient\n"); /* publish the real size of the buffer */ rpmsg_sg_init(&sg, msg, vrp->buf_size); /* add the buffer back to the remote processor's virtqueue */ err = virtqueue_add_inbuf(vrp->rvq, &sg, 1, msg, GFP_KERNEL); if (err < 0) { dev_err(dev, "failed to add a virtqueue buffer: %d\n", err); return err; } return 0; } /* called when an rx buffer is used, and it's time to digest a message */ static void rpmsg_recv_done(struct virtqueue *rvq) { struct virtproc_info *vrp = rvq->vdev->priv; struct device *dev = &rvq->vdev->dev; struct rpmsg_hdr *msg; unsigned int len, msgs_received = 0; int err; msg = virtqueue_get_buf(rvq, &len); if (!msg) { dev_err(dev, "uhm, incoming signal, but no used buffer ?\n"); return; } while (msg) { err = rpmsg_recv_single(vrp, dev, msg, len); if (err) break; msgs_received++; msg = virtqueue_get_buf(rvq, &len); } dev_dbg(dev, "Received %u messages\n", msgs_received); /* tell the remote processor we added another available rx buffer */ if (msgs_received) virtqueue_kick(vrp->rvq); } /* * This is invoked whenever the remote processor completed processing * a TX msg we just sent it, and the buffer is put back to the used ring. * * Normally, though, we suppress this "tx complete" interrupt in order to * avoid the incurred overhead. */ static void rpmsg_xmit_done(struct virtqueue *svq) { struct virtproc_info *vrp = svq->vdev->priv; dev_dbg(&svq->vdev->dev, "%s\n", __func__); /* wake up potential senders that are waiting for a tx buffer */ wake_up_interruptible(&vrp->sendq); } /* * Called to expose to user a /dev/rpmsg_ctrlX interface allowing to * create endpoint-to-endpoint communication without associated RPMsg channel. * The endpoints are rattached to the ctrldev RPMsg device. */ static struct rpmsg_device *rpmsg_virtio_add_ctrl_dev(struct virtio_device *vdev) { struct virtproc_info *vrp = vdev->priv; struct virtio_rpmsg_channel *vch; struct rpmsg_device *rpdev_ctrl; int err = 0; vch = kzalloc(sizeof(*vch), GFP_KERNEL); if (!vch) return ERR_PTR(-ENOMEM); /* Link the channel to the vrp */ vch->vrp = vrp; /* Assign public information to the rpmsg_device */ rpdev_ctrl = &vch->rpdev; rpdev_ctrl->ops = &virtio_rpmsg_ops; rpdev_ctrl->dev.parent = &vrp->vdev->dev; rpdev_ctrl->dev.release = virtio_rpmsg_release_device; rpdev_ctrl->little_endian = virtio_is_little_endian(vrp->vdev); err = rpmsg_ctrldev_register_device(rpdev_ctrl); if (err) { /* vch will be free in virtio_rpmsg_release_device() */ return ERR_PTR(err); } return rpdev_ctrl; } static void rpmsg_virtio_del_ctrl_dev(struct rpmsg_device *rpdev_ctrl) { if (!rpdev_ctrl) return; device_unregister(&rpdev_ctrl->dev); } static int rpmsg_probe(struct virtio_device *vdev) { vq_callback_t *vq_cbs[] = { rpmsg_recv_done, rpmsg_xmit_done }; static const char * const names[] = { "input", "output" }; struct virtqueue *vqs[2]; struct virtproc_info *vrp; struct virtio_rpmsg_channel *vch = NULL; struct rpmsg_device *rpdev_ns, *rpdev_ctrl; void *bufs_va; int err = 0, i; size_t total_buf_space; bool notify; vrp = kzalloc(sizeof(*vrp), GFP_KERNEL); if (!vrp) return -ENOMEM; vrp->vdev = vdev; idr_init(&vrp->endpoints); mutex_init(&vrp->endpoints_lock); mutex_init(&vrp->tx_lock); init_waitqueue_head(&vrp->sendq); /* We expect two virtqueues, rx and tx (and in this order) */ err = virtio_find_vqs(vdev, 2, vqs, vq_cbs, names, NULL); if (err) goto free_vrp; vrp->rvq = vqs[0]; vrp->svq = vqs[1]; /* we expect symmetric tx/rx vrings */ WARN_ON(virtqueue_get_vring_size(vrp->rvq) != virtqueue_get_vring_size(vrp->svq)); /* we need less buffers if vrings are small */ if (virtqueue_get_vring_size(vrp->rvq) < MAX_RPMSG_NUM_BUFS / 2) vrp->num_bufs = virtqueue_get_vring_size(vrp->rvq) * 2; else vrp->num_bufs = MAX_RPMSG_NUM_BUFS; vrp->buf_size = MAX_RPMSG_BUF_SIZE; total_buf_space = vrp->num_bufs * vrp->buf_size; /* allocate coherent memory for the buffers */ bufs_va = dma_alloc_coherent(vdev->dev.parent, total_buf_space, &vrp->bufs_dma, GFP_KERNEL); if (!bufs_va) { err = -ENOMEM; goto vqs_del; } dev_dbg(&vdev->dev, "buffers: va %pK, dma %pad\n", bufs_va, &vrp->bufs_dma); /* half of the buffers is dedicated for RX */ vrp->rbufs = bufs_va; /* and half is dedicated for TX */ vrp->sbufs = bufs_va + total_buf_space / 2; /* set up the receive buffers */ for (i = 0; i < vrp->num_bufs / 2; i++) { struct scatterlist sg; void *cpu_addr = vrp->rbufs + i * vrp->buf_size; rpmsg_sg_init(&sg, cpu_addr, vrp->buf_size); err = virtqueue_add_inbuf(vrp->rvq, &sg, 1, cpu_addr, GFP_KERNEL); WARN_ON(err); /* sanity check; this can't really happen */ } /* suppress "tx-complete" interrupts */ virtqueue_disable_cb(vrp->svq); vdev->priv = vrp; rpdev_ctrl = rpmsg_virtio_add_ctrl_dev(vdev); if (IS_ERR(rpdev_ctrl)) { err = PTR_ERR(rpdev_ctrl); goto free_coherent; } /* if supported by the remote processor, enable the name service */ if (virtio_has_feature(vdev, VIRTIO_RPMSG_F_NS)) { vch = kzalloc(sizeof(*vch), GFP_KERNEL); if (!vch) { err = -ENOMEM; goto free_ctrldev; } /* Link the channel to our vrp */ vch->vrp = vrp; /* Assign public information to the rpmsg_device */ rpdev_ns = &vch->rpdev; rpdev_ns->ops = &virtio_rpmsg_ops; rpdev_ns->little_endian = virtio_is_little_endian(vrp->vdev); rpdev_ns->dev.parent = &vrp->vdev->dev; rpdev_ns->dev.release = virtio_rpmsg_release_device; err = rpmsg_ns_register_device(rpdev_ns); if (err) /* vch will be free in virtio_rpmsg_release_device() */ goto free_ctrldev; } /* * Prepare to kick but don't notify yet - we can't do this before * device is ready. */ notify = virtqueue_kick_prepare(vrp->rvq); /* From this point on, we can notify and get callbacks. */ virtio_device_ready(vdev); /* tell the remote processor it can start sending messages */ /* * this might be concurrent with callbacks, but we are only * doing notify, not a full kick here, so that's ok. */ if (notify) virtqueue_notify(vrp->rvq); dev_info(&vdev->dev, "rpmsg host is online\n"); return 0; free_ctrldev: rpmsg_virtio_del_ctrl_dev(rpdev_ctrl); free_coherent: dma_free_coherent(vdev->dev.parent, total_buf_space, bufs_va, vrp->bufs_dma); vqs_del: vdev->config->del_vqs(vrp->vdev); free_vrp: kfree(vrp); return err; } static int rpmsg_remove_device(struct device *dev, void *data) { device_unregister(dev); return 0; } static void rpmsg_remove(struct virtio_device *vdev) { struct virtproc_info *vrp = vdev->priv; size_t total_buf_space = vrp->num_bufs * vrp->buf_size; int ret; virtio_reset_device(vdev); ret = device_for_each_child(&vdev->dev, NULL, rpmsg_remove_device); if (ret) dev_warn(&vdev->dev, "can't remove rpmsg device: %d\n", ret); idr_destroy(&vrp->endpoints); vdev->config->del_vqs(vrp->vdev); dma_free_coherent(vdev->dev.parent, total_buf_space, vrp->rbufs, vrp->bufs_dma); kfree(vrp); } static struct virtio_device_id id_table[] = { { VIRTIO_ID_RPMSG, VIRTIO_DEV_ANY_ID }, { 0 }, }; static unsigned int features[] = { VIRTIO_RPMSG_F_NS, }; static struct virtio_driver virtio_ipc_driver = { .feature_table = features, .feature_table_size = ARRAY_SIZE(features), .driver.name = KBUILD_MODNAME, .driver.owner = THIS_MODULE, .id_table = id_table, .probe = rpmsg_probe, .remove = rpmsg_remove, }; static int __init rpmsg_init(void) { int ret; ret = register_virtio_driver(&virtio_ipc_driver); if (ret) pr_err("failed to register virtio driver: %d\n", ret); return ret; } subsys_initcall(rpmsg_init); static void __exit rpmsg_fini(void) { unregister_virtio_driver(&virtio_ipc_driver); } module_exit(rpmsg_fini); MODULE_DEVICE_TABLE(virtio, id_table); MODULE_DESCRIPTION("Virtio-based remote processor messaging bus"); MODULE_LICENSE("GPL v2");
linux-master
drivers/rpmsg/virtio_rpmsg_bus.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2014-2017, The Linux Foundation. All rights reserved. * Copyright (c) 2017, Linaro Ltd. */ #include <linux/completion.h> #include <linux/module.h> #include <linux/notifier.h> #include <linux/rpmsg.h> #include <linux/rpmsg/qcom_glink.h> #include <linux/remoteproc/qcom_rproc.h> /** * struct do_cleanup_msg - The data structure for an SSR do_cleanup message * @version: The G-Link SSR protocol version * @command: The G-Link SSR command - do_cleanup * @seq_num: Sequence number * @name_len: Length of the name of the subsystem being restarted * @name: G-Link edge name of the subsystem being restarted */ struct do_cleanup_msg { __le32 version; __le32 command; __le32 seq_num; __le32 name_len; char name[32]; }; /** * struct cleanup_done_msg - The data structure for an SSR cleanup_done message * @version: The G-Link SSR protocol version * @response: The G-Link SSR response to a do_cleanup command, cleanup_done * @seq_num: Sequence number */ struct cleanup_done_msg { __le32 version; __le32 response; __le32 seq_num; }; /* * G-Link SSR protocol commands */ #define GLINK_SSR_DO_CLEANUP 0 #define GLINK_SSR_CLEANUP_DONE 1 struct glink_ssr { struct device *dev; struct rpmsg_endpoint *ept; struct notifier_block nb; u32 seq_num; struct completion completion; }; /* Notifier list for all registered glink_ssr instances */ static BLOCKING_NOTIFIER_HEAD(ssr_notifiers); /** * qcom_glink_ssr_notify() - notify GLINK SSR about stopped remoteproc * @ssr_name: name of the remoteproc that has been stopped */ void qcom_glink_ssr_notify(const char *ssr_name) { blocking_notifier_call_chain(&ssr_notifiers, 0, (void *)ssr_name); } EXPORT_SYMBOL_GPL(qcom_glink_ssr_notify); static int qcom_glink_ssr_callback(struct rpmsg_device *rpdev, void *data, int len, void *priv, u32 addr) { struct cleanup_done_msg *msg = data; struct glink_ssr *ssr = dev_get_drvdata(&rpdev->dev); if (len < sizeof(*msg)) { dev_err(ssr->dev, "message too short\n"); return -EINVAL; } if (le32_to_cpu(msg->version) != 0) return -EINVAL; if (le32_to_cpu(msg->response) != GLINK_SSR_CLEANUP_DONE) return 0; if (le32_to_cpu(msg->seq_num) != ssr->seq_num) { dev_err(ssr->dev, "invalid sequence number of response\n"); return -EINVAL; } complete(&ssr->completion); return 0; } static int qcom_glink_ssr_notifier_call(struct notifier_block *nb, unsigned long event, void *data) { struct glink_ssr *ssr = container_of(nb, struct glink_ssr, nb); struct do_cleanup_msg msg; char *ssr_name = data; int ret; ssr->seq_num++; reinit_completion(&ssr->completion); memset(&msg, 0, sizeof(msg)); msg.command = cpu_to_le32(GLINK_SSR_DO_CLEANUP); msg.seq_num = cpu_to_le32(ssr->seq_num); msg.name_len = cpu_to_le32(strlen(ssr_name)); strscpy(msg.name, ssr_name, sizeof(msg.name)); ret = rpmsg_send(ssr->ept, &msg, sizeof(msg)); if (ret < 0) dev_err(ssr->dev, "failed to send cleanup message\n"); ret = wait_for_completion_timeout(&ssr->completion, HZ); if (!ret) dev_err(ssr->dev, "timeout waiting for cleanup done message\n"); return NOTIFY_DONE; } static int qcom_glink_ssr_probe(struct rpmsg_device *rpdev) { struct glink_ssr *ssr; ssr = devm_kzalloc(&rpdev->dev, sizeof(*ssr), GFP_KERNEL); if (!ssr) return -ENOMEM; init_completion(&ssr->completion); ssr->dev = &rpdev->dev; ssr->ept = rpdev->ept; ssr->nb.notifier_call = qcom_glink_ssr_notifier_call; dev_set_drvdata(&rpdev->dev, ssr); return blocking_notifier_chain_register(&ssr_notifiers, &ssr->nb); } static void qcom_glink_ssr_remove(struct rpmsg_device *rpdev) { struct glink_ssr *ssr = dev_get_drvdata(&rpdev->dev); blocking_notifier_chain_unregister(&ssr_notifiers, &ssr->nb); } static const struct rpmsg_device_id qcom_glink_ssr_match[] = { { "glink_ssr" }, {} }; static struct rpmsg_driver qcom_glink_ssr_driver = { .probe = qcom_glink_ssr_probe, .remove = qcom_glink_ssr_remove, .callback = qcom_glink_ssr_callback, .id_table = qcom_glink_ssr_match, .drv = { .name = "qcom_glink_ssr", }, }; module_rpmsg_driver(qcom_glink_ssr_driver);
linux-master
drivers/rpmsg/qcom_glink_ssr.c
// SPDX-License-Identifier: GPL-2.0 // // Copyright 2019 Google LLC. #include <linux/kernel.h> #include <linux/module.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/remoteproc.h> #include <linux/rpmsg/mtk_rpmsg.h> #include <linux/slab.h> #include <linux/workqueue.h> #include "rpmsg_internal.h" struct mtk_rpmsg_rproc_subdev { struct platform_device *pdev; struct mtk_rpmsg_info *info; struct rpmsg_endpoint *ns_ept; struct rproc_subdev subdev; struct work_struct register_work; struct list_head channels; struct mutex channels_lock; }; #define to_mtk_subdev(d) container_of(d, struct mtk_rpmsg_rproc_subdev, subdev) struct mtk_rpmsg_channel_info { struct rpmsg_channel_info info; bool registered; struct list_head list; }; /** * struct rpmsg_ns_msg - dynamic name service announcement message * @name: name of remote service that is published * @addr: address of remote service that is published * * This message is sent across to publish a new service. When we receive these * messages, an appropriate rpmsg channel (i.e device) is created. In turn, the * ->probe() handler of the appropriate rpmsg driver will be invoked * (if/as-soon-as one is registered). */ struct rpmsg_ns_msg { char name[RPMSG_NAME_SIZE]; u32 addr; } __packed; struct mtk_rpmsg_device { struct rpmsg_device rpdev; struct mtk_rpmsg_rproc_subdev *mtk_subdev; }; struct mtk_rpmsg_endpoint { struct rpmsg_endpoint ept; struct mtk_rpmsg_rproc_subdev *mtk_subdev; }; #define to_mtk_rpmsg_device(r) container_of(r, struct mtk_rpmsg_device, rpdev) #define to_mtk_rpmsg_endpoint(r) container_of(r, struct mtk_rpmsg_endpoint, ept) static const struct rpmsg_endpoint_ops mtk_rpmsg_endpoint_ops; static void __mtk_ept_release(struct kref *kref) { struct rpmsg_endpoint *ept = container_of(kref, struct rpmsg_endpoint, refcount); kfree(to_mtk_rpmsg_endpoint(ept)); } static void mtk_rpmsg_ipi_handler(void *data, unsigned int len, void *priv) { struct mtk_rpmsg_endpoint *mept = priv; struct rpmsg_endpoint *ept = &mept->ept; int ret; ret = (*ept->cb)(ept->rpdev, data, len, ept->priv, ept->addr); if (ret) dev_warn(&ept->rpdev->dev, "rpmsg handler return error = %d", ret); } static struct rpmsg_endpoint * __mtk_create_ept(struct mtk_rpmsg_rproc_subdev *mtk_subdev, struct rpmsg_device *rpdev, rpmsg_rx_cb_t cb, void *priv, u32 id) { struct mtk_rpmsg_endpoint *mept; struct rpmsg_endpoint *ept; struct platform_device *pdev = mtk_subdev->pdev; int ret; mept = kzalloc(sizeof(*mept), GFP_KERNEL); if (!mept) return NULL; mept->mtk_subdev = mtk_subdev; ept = &mept->ept; kref_init(&ept->refcount); ept->rpdev = rpdev; ept->cb = cb; ept->priv = priv; ept->ops = &mtk_rpmsg_endpoint_ops; ept->addr = id; ret = mtk_subdev->info->register_ipi(pdev, id, mtk_rpmsg_ipi_handler, mept); if (ret) { dev_err(&pdev->dev, "IPI register failed, id = %d", id); kref_put(&ept->refcount, __mtk_ept_release); return NULL; } return ept; } static struct rpmsg_endpoint * mtk_rpmsg_create_ept(struct rpmsg_device *rpdev, rpmsg_rx_cb_t cb, void *priv, struct rpmsg_channel_info chinfo) { struct mtk_rpmsg_rproc_subdev *mtk_subdev = to_mtk_rpmsg_device(rpdev)->mtk_subdev; return __mtk_create_ept(mtk_subdev, rpdev, cb, priv, chinfo.src); } static void mtk_rpmsg_destroy_ept(struct rpmsg_endpoint *ept) { struct mtk_rpmsg_rproc_subdev *mtk_subdev = to_mtk_rpmsg_endpoint(ept)->mtk_subdev; mtk_subdev->info->unregister_ipi(mtk_subdev->pdev, ept->addr); kref_put(&ept->refcount, __mtk_ept_release); } static int mtk_rpmsg_send(struct rpmsg_endpoint *ept, void *data, int len) { struct mtk_rpmsg_rproc_subdev *mtk_subdev = to_mtk_rpmsg_endpoint(ept)->mtk_subdev; return mtk_subdev->info->send_ipi(mtk_subdev->pdev, ept->addr, data, len, 0); } static int mtk_rpmsg_trysend(struct rpmsg_endpoint *ept, void *data, int len) { struct mtk_rpmsg_rproc_subdev *mtk_subdev = to_mtk_rpmsg_endpoint(ept)->mtk_subdev; /* * TODO: This currently is same as mtk_rpmsg_send, and wait until SCP * received the last command. */ return mtk_subdev->info->send_ipi(mtk_subdev->pdev, ept->addr, data, len, 0); } static const struct rpmsg_endpoint_ops mtk_rpmsg_endpoint_ops = { .destroy_ept = mtk_rpmsg_destroy_ept, .send = mtk_rpmsg_send, .trysend = mtk_rpmsg_trysend, }; static void mtk_rpmsg_release_device(struct device *dev) { struct rpmsg_device *rpdev = to_rpmsg_device(dev); struct mtk_rpmsg_device *mdev = to_mtk_rpmsg_device(rpdev); kfree(mdev); } static const struct rpmsg_device_ops mtk_rpmsg_device_ops = { .create_ept = mtk_rpmsg_create_ept, }; static struct device_node * mtk_rpmsg_match_device_subnode(struct device_node *node, const char *channel) { struct device_node *child; const char *name; int ret; for_each_available_child_of_node(node, child) { ret = of_property_read_string(child, "mediatek,rpmsg-name", &name); if (ret) continue; if (strcmp(name, channel) == 0) return child; } return NULL; } static int mtk_rpmsg_register_device(struct mtk_rpmsg_rproc_subdev *mtk_subdev, struct rpmsg_channel_info *info) { struct rpmsg_device *rpdev; struct mtk_rpmsg_device *mdev; struct platform_device *pdev = mtk_subdev->pdev; mdev = kzalloc(sizeof(*mdev), GFP_KERNEL); if (!mdev) return -ENOMEM; mdev->mtk_subdev = mtk_subdev; rpdev = &mdev->rpdev; rpdev->ops = &mtk_rpmsg_device_ops; rpdev->src = info->src; rpdev->dst = info->dst; strscpy(rpdev->id.name, info->name, RPMSG_NAME_SIZE); rpdev->dev.of_node = mtk_rpmsg_match_device_subnode(pdev->dev.of_node, info->name); rpdev->dev.parent = &pdev->dev; rpdev->dev.release = mtk_rpmsg_release_device; return rpmsg_register_device(rpdev); } static void mtk_register_device_work_function(struct work_struct *register_work) { struct mtk_rpmsg_rproc_subdev *subdev = container_of( register_work, struct mtk_rpmsg_rproc_subdev, register_work); struct platform_device *pdev = subdev->pdev; struct mtk_rpmsg_channel_info *info; int ret; mutex_lock(&subdev->channels_lock); list_for_each_entry(info, &subdev->channels, list) { if (info->registered) continue; mutex_unlock(&subdev->channels_lock); ret = mtk_rpmsg_register_device(subdev, &info->info); mutex_lock(&subdev->channels_lock); if (ret) { dev_err(&pdev->dev, "Can't create rpmsg_device\n"); continue; } info->registered = true; } mutex_unlock(&subdev->channels_lock); } static int mtk_rpmsg_create_device(struct mtk_rpmsg_rproc_subdev *mtk_subdev, char *name, u32 addr) { struct mtk_rpmsg_channel_info *info; info = kzalloc(sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; strscpy(info->info.name, name, RPMSG_NAME_SIZE); info->info.src = addr; info->info.dst = RPMSG_ADDR_ANY; mutex_lock(&mtk_subdev->channels_lock); list_add(&info->list, &mtk_subdev->channels); mutex_unlock(&mtk_subdev->channels_lock); schedule_work(&mtk_subdev->register_work); return 0; } static int mtk_rpmsg_ns_cb(struct rpmsg_device *rpdev, void *data, int len, void *priv, u32 src) { struct rpmsg_ns_msg *msg = data; struct mtk_rpmsg_rproc_subdev *mtk_subdev = priv; struct device *dev = &mtk_subdev->pdev->dev; int ret; if (len != sizeof(*msg)) { dev_err(dev, "malformed ns msg (%d)\n", len); return -EINVAL; } /* * the name service ept does _not_ belong to a real rpmsg channel, * and is handled by the rpmsg bus itself. * for sanity reasons, make sure a valid rpdev has _not_ sneaked * in somehow. */ if (rpdev) { dev_err(dev, "anomaly: ns ept has an rpdev handle\n"); return -EINVAL; } /* don't trust the remote processor for null terminating the name */ msg->name[RPMSG_NAME_SIZE - 1] = '\0'; dev_info(dev, "creating channel %s addr 0x%x\n", msg->name, msg->addr); ret = mtk_rpmsg_create_device(mtk_subdev, msg->name, msg->addr); if (ret) { dev_err(dev, "create rpmsg device failed\n"); return ret; } return 0; } static int mtk_rpmsg_prepare(struct rproc_subdev *subdev) { struct mtk_rpmsg_rproc_subdev *mtk_subdev = to_mtk_subdev(subdev); /* a dedicated endpoint handles the name service msgs */ if (mtk_subdev->info->ns_ipi_id >= 0) { mtk_subdev->ns_ept = __mtk_create_ept(mtk_subdev, NULL, mtk_rpmsg_ns_cb, mtk_subdev, mtk_subdev->info->ns_ipi_id); if (!mtk_subdev->ns_ept) { dev_err(&mtk_subdev->pdev->dev, "failed to create name service endpoint\n"); return -ENOMEM; } } return 0; } static void mtk_rpmsg_unprepare(struct rproc_subdev *subdev) { struct mtk_rpmsg_rproc_subdev *mtk_subdev = to_mtk_subdev(subdev); if (mtk_subdev->ns_ept) { mtk_rpmsg_destroy_ept(mtk_subdev->ns_ept); mtk_subdev->ns_ept = NULL; } } static void mtk_rpmsg_stop(struct rproc_subdev *subdev, bool crashed) { struct mtk_rpmsg_channel_info *info, *next; struct mtk_rpmsg_rproc_subdev *mtk_subdev = to_mtk_subdev(subdev); struct device *dev = &mtk_subdev->pdev->dev; /* * Destroy the name service endpoint here, to avoid new channel being * created after the rpmsg_unregister_device loop below. */ if (mtk_subdev->ns_ept) { mtk_rpmsg_destroy_ept(mtk_subdev->ns_ept); mtk_subdev->ns_ept = NULL; } cancel_work_sync(&mtk_subdev->register_work); mutex_lock(&mtk_subdev->channels_lock); list_for_each_entry(info, &mtk_subdev->channels, list) { if (!info->registered) continue; if (rpmsg_unregister_device(dev, &info->info)) { dev_warn( dev, "rpmsg_unregister_device failed for %s.%d.%d\n", info->info.name, info->info.src, info->info.dst); } } list_for_each_entry_safe(info, next, &mtk_subdev->channels, list) { list_del(&info->list); kfree(info); } mutex_unlock(&mtk_subdev->channels_lock); } struct rproc_subdev * mtk_rpmsg_create_rproc_subdev(struct platform_device *pdev, struct mtk_rpmsg_info *info) { struct mtk_rpmsg_rproc_subdev *mtk_subdev; mtk_subdev = kzalloc(sizeof(*mtk_subdev), GFP_KERNEL); if (!mtk_subdev) return NULL; mtk_subdev->pdev = pdev; mtk_subdev->subdev.prepare = mtk_rpmsg_prepare; mtk_subdev->subdev.stop = mtk_rpmsg_stop; mtk_subdev->subdev.unprepare = mtk_rpmsg_unprepare; mtk_subdev->info = info; INIT_LIST_HEAD(&mtk_subdev->channels); INIT_WORK(&mtk_subdev->register_work, mtk_register_device_work_function); mutex_init(&mtk_subdev->channels_lock); return &mtk_subdev->subdev; } EXPORT_SYMBOL_GPL(mtk_rpmsg_create_rproc_subdev); void mtk_rpmsg_destroy_rproc_subdev(struct rproc_subdev *subdev) { struct mtk_rpmsg_rproc_subdev *mtk_subdev = to_mtk_subdev(subdev); kfree(mtk_subdev); } EXPORT_SYMBOL_GPL(mtk_rpmsg_destroy_rproc_subdev); MODULE_LICENSE("GPL v2"); MODULE_DESCRIPTION("MediaTek scp rpmsg driver");
linux-master
drivers/rpmsg/mtk_rpmsg.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) STMicroelectronics 2020 - All Rights Reserved */ #include <linux/device.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/rpmsg.h> #include <linux/rpmsg/ns.h> #include <linux/slab.h> #include "rpmsg_internal.h" /** * rpmsg_ns_register_device() - register name service device based on rpdev * @rpdev: prepared rpdev to be used for creating endpoints * * This function wraps rpmsg_register_device() preparing the rpdev for use as * basis for the rpmsg name service device. */ int rpmsg_ns_register_device(struct rpmsg_device *rpdev) { rpdev->src = RPMSG_NS_ADDR; rpdev->dst = RPMSG_NS_ADDR; return rpmsg_register_device_override(rpdev, "rpmsg_ns"); } EXPORT_SYMBOL(rpmsg_ns_register_device); /* invoked when a name service announcement arrives */ static int rpmsg_ns_cb(struct rpmsg_device *rpdev, void *data, int len, void *priv, u32 src) { struct rpmsg_ns_msg *msg = data; struct rpmsg_device *newch; struct rpmsg_channel_info chinfo; struct device *dev = rpdev->dev.parent; int ret; #if defined(CONFIG_DYNAMIC_DEBUG) dynamic_hex_dump("NS announcement: ", DUMP_PREFIX_NONE, 16, 1, data, len, true); #endif if (len != sizeof(*msg)) { dev_err(dev, "malformed ns msg (%d)\n", len); return -EINVAL; } /* don't trust the remote processor for null terminating the name */ msg->name[RPMSG_NAME_SIZE - 1] = '\0'; strncpy(chinfo.name, msg->name, sizeof(chinfo.name)); chinfo.src = RPMSG_ADDR_ANY; chinfo.dst = rpmsg32_to_cpu(rpdev, msg->addr); dev_info(dev, "%sing channel %s addr 0x%x\n", rpmsg32_to_cpu(rpdev, msg->flags) & RPMSG_NS_DESTROY ? "destroy" : "creat", msg->name, chinfo.dst); if (rpmsg32_to_cpu(rpdev, msg->flags) & RPMSG_NS_DESTROY) { ret = rpmsg_release_channel(rpdev, &chinfo); if (ret) dev_err(dev, "rpmsg_destroy_channel failed: %d\n", ret); } else { newch = rpmsg_create_channel(rpdev, &chinfo); if (!newch) dev_err(dev, "rpmsg_create_channel failed\n"); } return 0; } static int rpmsg_ns_probe(struct rpmsg_device *rpdev) { struct rpmsg_endpoint *ns_ept; struct rpmsg_channel_info ns_chinfo = { .src = RPMSG_NS_ADDR, .dst = RPMSG_NS_ADDR, .name = "name_service", }; /* * Create the NS announcement service endpoint associated to the RPMsg * device. The endpoint will be automatically destroyed when the RPMsg * device will be deleted. */ ns_ept = rpmsg_create_ept(rpdev, rpmsg_ns_cb, NULL, ns_chinfo); if (!ns_ept) { dev_err(&rpdev->dev, "failed to create the ns ept\n"); return -ENOMEM; } rpdev->ept = ns_ept; return 0; } static struct rpmsg_driver rpmsg_ns_driver = { .drv.name = KBUILD_MODNAME, .probe = rpmsg_ns_probe, }; static int rpmsg_ns_init(void) { int ret; ret = register_rpmsg_driver(&rpmsg_ns_driver); if (ret < 0) pr_err("%s: Failed to register rpmsg driver\n", __func__); return ret; } postcore_initcall(rpmsg_ns_init); static void rpmsg_ns_exit(void) { unregister_rpmsg_driver(&rpmsg_ns_driver); } module_exit(rpmsg_ns_exit); MODULE_DESCRIPTION("Name service announcement rpmsg driver"); MODULE_AUTHOR("Arnaud Pouliquen <[email protected]>"); MODULE_ALIAS("rpmsg:" KBUILD_MODNAME); MODULE_LICENSE("GPL v2");
linux-master
drivers/rpmsg/rpmsg_ns.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (c) 2016-2017, Linaro Ltd */ #include <linux/idr.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/list.h> #include <linux/mfd/syscon.h> #include <linux/module.h> #include <linux/of.h> #include <linux/of_address.h> #include <linux/platform_device.h> #include <linux/regmap.h> #include <linux/rpmsg.h> #include <linux/sizes.h> #include <linux/slab.h> #include <linux/wait.h> #include <linux/workqueue.h> #include <linux/mailbox_client.h> #include "rpmsg_internal.h" #include "qcom_glink_native.h" #define GLINK_NAME_SIZE 32 #define GLINK_VERSION_1 1 #define RPM_GLINK_CID_MIN 1 #define RPM_GLINK_CID_MAX 65536 struct glink_msg { __le16 cmd; __le16 param1; __le32 param2; u8 data[]; } __packed; /** * struct glink_defer_cmd - deferred incoming control message * @node: list node * @msg: message header * @data: payload of the message * * Copy of a received control message, to be added to @rx_queue and processed * by @rx_work of @qcom_glink. */ struct glink_defer_cmd { struct list_head node; struct glink_msg msg; u8 data[]; }; /** * struct glink_core_rx_intent - RX intent * RX intent * * @data: pointer to the data (may be NULL for zero-copy) * @id: remote or local intent ID * @size: size of the original intent (do not modify) * @reuse: To mark if the intent can be reused after first use * @in_use: To mark if intent is already in use for the channel * @offset: next write offset (initially 0) * @node: list node */ struct glink_core_rx_intent { void *data; u32 id; size_t size; bool reuse; bool in_use; u32 offset; struct list_head node; }; /** * struct qcom_glink - driver context, relates to one remote subsystem * @dev: reference to the associated struct device * @rx_pipe: pipe object for receive FIFO * @tx_pipe: pipe object for transmit FIFO * @rx_work: worker for handling received control messages * @rx_lock: protects the @rx_queue * @rx_queue: queue of received control messages to be processed in @rx_work * @tx_lock: synchronizes operations on the tx fifo * @idr_lock: synchronizes @lcids and @rcids modifications * @lcids: idr of all channels with a known local channel id * @rcids: idr of all channels with a known remote channel id * @features: remote features * @intentless: flag to indicate that there is no intent * @tx_avail_notify: Waitqueue for pending tx tasks * @sent_read_notify: flag to check cmd sent or not * @abort_tx: flag indicating that all tx attempts should fail */ struct qcom_glink { struct device *dev; struct qcom_glink_pipe *rx_pipe; struct qcom_glink_pipe *tx_pipe; struct work_struct rx_work; spinlock_t rx_lock; struct list_head rx_queue; spinlock_t tx_lock; spinlock_t idr_lock; struct idr lcids; struct idr rcids; unsigned long features; bool intentless; wait_queue_head_t tx_avail_notify; bool sent_read_notify; bool abort_tx; }; enum { GLINK_STATE_CLOSED, GLINK_STATE_OPENING, GLINK_STATE_OPEN, GLINK_STATE_CLOSING, }; /** * struct glink_channel - internal representation of a channel * @rpdev: rpdev reference, only used for primary endpoints * @ept: rpmsg endpoint this channel is associated with * @glink: qcom_glink context handle * @refcount: refcount for the channel object * @recv_lock: guard for @ept.cb * @name: unique channel name/identifier * @lcid: channel id, in local space * @rcid: channel id, in remote space * @intent_lock: lock for protection of @liids, @riids * @liids: idr of all local intents * @riids: idr of all remote intents * @intent_work: worker responsible for transmitting rx_done packets * @done_intents: list of intents that needs to be announced rx_done * @buf: receive buffer, for gathering fragments * @buf_offset: write offset in @buf * @buf_size: size of current @buf * @open_ack: completed once remote has acked the open-request * @open_req: completed once open-request has been received * @intent_req_lock: Synchronises multiple intent requests * @intent_req_result: Result of intent request * @intent_received: flag indicating that an intent has been received * @intent_req_wq: wait queue for intent_req signalling */ struct glink_channel { struct rpmsg_endpoint ept; struct rpmsg_device *rpdev; struct qcom_glink *glink; struct kref refcount; spinlock_t recv_lock; char *name; unsigned int lcid; unsigned int rcid; spinlock_t intent_lock; struct idr liids; struct idr riids; struct work_struct intent_work; struct list_head done_intents; struct glink_core_rx_intent *buf; int buf_offset; int buf_size; struct completion open_ack; struct completion open_req; struct mutex intent_req_lock; int intent_req_result; bool intent_received; wait_queue_head_t intent_req_wq; }; #define to_glink_channel(_ept) container_of(_ept, struct glink_channel, ept) static const struct rpmsg_endpoint_ops glink_endpoint_ops; #define GLINK_CMD_VERSION 0 #define GLINK_CMD_VERSION_ACK 1 #define GLINK_CMD_OPEN 2 #define GLINK_CMD_CLOSE 3 #define GLINK_CMD_OPEN_ACK 4 #define GLINK_CMD_INTENT 5 #define GLINK_CMD_RX_DONE 6 #define GLINK_CMD_RX_INTENT_REQ 7 #define GLINK_CMD_RX_INTENT_REQ_ACK 8 #define GLINK_CMD_TX_DATA 9 #define GLINK_CMD_CLOSE_ACK 11 #define GLINK_CMD_TX_DATA_CONT 12 #define GLINK_CMD_READ_NOTIF 13 #define GLINK_CMD_RX_DONE_W_REUSE 14 #define GLINK_CMD_SIGNALS 15 #define GLINK_FEATURE_INTENTLESS BIT(1) #define NATIVE_DTR_SIG NATIVE_DSR_SIG #define NATIVE_DSR_SIG BIT(31) #define NATIVE_RTS_SIG NATIVE_CTS_SIG #define NATIVE_CTS_SIG BIT(30) static void qcom_glink_rx_done_work(struct work_struct *work); static struct glink_channel *qcom_glink_alloc_channel(struct qcom_glink *glink, const char *name) { struct glink_channel *channel; channel = kzalloc(sizeof(*channel), GFP_KERNEL); if (!channel) return ERR_PTR(-ENOMEM); /* Setup glink internal glink_channel data */ spin_lock_init(&channel->recv_lock); spin_lock_init(&channel->intent_lock); mutex_init(&channel->intent_req_lock); channel->glink = glink; channel->name = kstrdup(name, GFP_KERNEL); if (!channel->name) { kfree(channel); return ERR_PTR(-ENOMEM); } init_completion(&channel->open_req); init_completion(&channel->open_ack); init_waitqueue_head(&channel->intent_req_wq); INIT_LIST_HEAD(&channel->done_intents); INIT_WORK(&channel->intent_work, qcom_glink_rx_done_work); idr_init(&channel->liids); idr_init(&channel->riids); kref_init(&channel->refcount); return channel; } static void qcom_glink_channel_release(struct kref *ref) { struct glink_channel *channel = container_of(ref, struct glink_channel, refcount); struct glink_core_rx_intent *intent; struct glink_core_rx_intent *tmp; unsigned long flags; int iid; /* cancel pending rx_done work */ cancel_work_sync(&channel->intent_work); spin_lock_irqsave(&channel->intent_lock, flags); /* Free all non-reuse intents pending rx_done work */ list_for_each_entry_safe(intent, tmp, &channel->done_intents, node) { if (!intent->reuse) { kfree(intent->data); kfree(intent); } } idr_for_each_entry(&channel->liids, tmp, iid) { kfree(tmp->data); kfree(tmp); } idr_destroy(&channel->liids); idr_for_each_entry(&channel->riids, tmp, iid) kfree(tmp); idr_destroy(&channel->riids); spin_unlock_irqrestore(&channel->intent_lock, flags); kfree(channel->name); kfree(channel); } static size_t qcom_glink_rx_avail(struct qcom_glink *glink) { return glink->rx_pipe->avail(glink->rx_pipe); } static void qcom_glink_rx_peek(struct qcom_glink *glink, void *data, unsigned int offset, size_t count) { glink->rx_pipe->peek(glink->rx_pipe, data, offset, count); } static void qcom_glink_rx_advance(struct qcom_glink *glink, size_t count) { glink->rx_pipe->advance(glink->rx_pipe, count); } static size_t qcom_glink_tx_avail(struct qcom_glink *glink) { return glink->tx_pipe->avail(glink->tx_pipe); } static void qcom_glink_tx_write(struct qcom_glink *glink, const void *hdr, size_t hlen, const void *data, size_t dlen) { glink->tx_pipe->write(glink->tx_pipe, hdr, hlen, data, dlen); } static void qcom_glink_tx_kick(struct qcom_glink *glink) { glink->tx_pipe->kick(glink->tx_pipe); } static void qcom_glink_send_read_notify(struct qcom_glink *glink) { struct glink_msg msg; msg.cmd = cpu_to_le16(GLINK_CMD_READ_NOTIF); msg.param1 = 0; msg.param2 = 0; qcom_glink_tx_write(glink, &msg, sizeof(msg), NULL, 0); qcom_glink_tx_kick(glink); } static int qcom_glink_tx(struct qcom_glink *glink, const void *hdr, size_t hlen, const void *data, size_t dlen, bool wait) { unsigned int tlen = hlen + dlen; unsigned long flags; int ret = 0; /* Reject packets that are too big */ if (tlen >= glink->tx_pipe->length) return -EINVAL; spin_lock_irqsave(&glink->tx_lock, flags); if (glink->abort_tx) { ret = -EIO; goto out; } while (qcom_glink_tx_avail(glink) < tlen) { if (!wait) { ret = -EAGAIN; goto out; } if (glink->abort_tx) { ret = -EIO; goto out; } if (!glink->sent_read_notify) { glink->sent_read_notify = true; qcom_glink_send_read_notify(glink); } /* Wait without holding the tx_lock */ spin_unlock_irqrestore(&glink->tx_lock, flags); wait_event_timeout(glink->tx_avail_notify, qcom_glink_tx_avail(glink) >= tlen, 10 * HZ); spin_lock_irqsave(&glink->tx_lock, flags); if (qcom_glink_tx_avail(glink) >= tlen) glink->sent_read_notify = false; } qcom_glink_tx_write(glink, hdr, hlen, data, dlen); qcom_glink_tx_kick(glink); out: spin_unlock_irqrestore(&glink->tx_lock, flags); return ret; } static int qcom_glink_send_version(struct qcom_glink *glink) { struct glink_msg msg; msg.cmd = cpu_to_le16(GLINK_CMD_VERSION); msg.param1 = cpu_to_le16(GLINK_VERSION_1); msg.param2 = cpu_to_le32(glink->features); return qcom_glink_tx(glink, &msg, sizeof(msg), NULL, 0, true); } static void qcom_glink_send_version_ack(struct qcom_glink *glink) { struct glink_msg msg; msg.cmd = cpu_to_le16(GLINK_CMD_VERSION_ACK); msg.param1 = cpu_to_le16(GLINK_VERSION_1); msg.param2 = cpu_to_le32(glink->features); qcom_glink_tx(glink, &msg, sizeof(msg), NULL, 0, true); } static void qcom_glink_send_open_ack(struct qcom_glink *glink, struct glink_channel *channel) { struct glink_msg msg; msg.cmd = cpu_to_le16(GLINK_CMD_OPEN_ACK); msg.param1 = cpu_to_le16(channel->rcid); msg.param2 = cpu_to_le32(0); qcom_glink_tx(glink, &msg, sizeof(msg), NULL, 0, true); } static void qcom_glink_handle_intent_req_ack(struct qcom_glink *glink, unsigned int cid, bool granted) { struct glink_channel *channel; unsigned long flags; spin_lock_irqsave(&glink->idr_lock, flags); channel = idr_find(&glink->rcids, cid); spin_unlock_irqrestore(&glink->idr_lock, flags); if (!channel) { dev_err(glink->dev, "unable to find channel\n"); return; } WRITE_ONCE(channel->intent_req_result, granted); wake_up_all(&channel->intent_req_wq); } static void qcom_glink_intent_req_abort(struct glink_channel *channel) { WRITE_ONCE(channel->intent_req_result, 0); wake_up_all(&channel->intent_req_wq); } /** * qcom_glink_send_open_req() - send a GLINK_CMD_OPEN request to the remote * @glink: Ptr to the glink edge * @channel: Ptr to the channel that the open req is sent * * Allocates a local channel id and sends a GLINK_CMD_OPEN message to the remote. * Will return with refcount held, regardless of outcome. * * Return: 0 on success, negative errno otherwise. */ static int qcom_glink_send_open_req(struct qcom_glink *glink, struct glink_channel *channel) { struct { struct glink_msg msg; u8 name[GLINK_NAME_SIZE]; } __packed req; int name_len = strlen(channel->name) + 1; int req_len = ALIGN(sizeof(req.msg) + name_len, 8); int ret; unsigned long flags; kref_get(&channel->refcount); spin_lock_irqsave(&glink->idr_lock, flags); ret = idr_alloc_cyclic(&glink->lcids, channel, RPM_GLINK_CID_MIN, RPM_GLINK_CID_MAX, GFP_ATOMIC); spin_unlock_irqrestore(&glink->idr_lock, flags); if (ret < 0) return ret; channel->lcid = ret; req.msg.cmd = cpu_to_le16(GLINK_CMD_OPEN); req.msg.param1 = cpu_to_le16(channel->lcid); req.msg.param2 = cpu_to_le32(name_len); strcpy(req.name, channel->name); ret = qcom_glink_tx(glink, &req, req_len, NULL, 0, true); if (ret) goto remove_idr; return 0; remove_idr: spin_lock_irqsave(&glink->idr_lock, flags); idr_remove(&glink->lcids, channel->lcid); channel->lcid = 0; spin_unlock_irqrestore(&glink->idr_lock, flags); return ret; } static void qcom_glink_send_close_req(struct qcom_glink *glink, struct glink_channel *channel) { struct glink_msg req; req.cmd = cpu_to_le16(GLINK_CMD_CLOSE); req.param1 = cpu_to_le16(channel->lcid); req.param2 = 0; qcom_glink_tx(glink, &req, sizeof(req), NULL, 0, true); } static void qcom_glink_send_close_ack(struct qcom_glink *glink, unsigned int rcid) { struct glink_msg req; req.cmd = cpu_to_le16(GLINK_CMD_CLOSE_ACK); req.param1 = cpu_to_le16(rcid); req.param2 = 0; qcom_glink_tx(glink, &req, sizeof(req), NULL, 0, true); } static void qcom_glink_rx_done_work(struct work_struct *work) { struct glink_channel *channel = container_of(work, struct glink_channel, intent_work); struct qcom_glink *glink = channel->glink; struct glink_core_rx_intent *intent, *tmp; struct { u16 id; u16 lcid; u32 liid; } __packed cmd; unsigned int cid = channel->lcid; unsigned int iid; bool reuse; unsigned long flags; spin_lock_irqsave(&channel->intent_lock, flags); list_for_each_entry_safe(intent, tmp, &channel->done_intents, node) { list_del(&intent->node); spin_unlock_irqrestore(&channel->intent_lock, flags); iid = intent->id; reuse = intent->reuse; cmd.id = reuse ? GLINK_CMD_RX_DONE_W_REUSE : GLINK_CMD_RX_DONE; cmd.lcid = cid; cmd.liid = iid; qcom_glink_tx(glink, &cmd, sizeof(cmd), NULL, 0, true); if (!reuse) { kfree(intent->data); kfree(intent); } spin_lock_irqsave(&channel->intent_lock, flags); } spin_unlock_irqrestore(&channel->intent_lock, flags); } static void qcom_glink_rx_done(struct qcom_glink *glink, struct glink_channel *channel, struct glink_core_rx_intent *intent) { /* We don't send RX_DONE to intentless systems */ if (glink->intentless) { kfree(intent->data); kfree(intent); return; } /* Take it off the tree of receive intents */ if (!intent->reuse) { spin_lock(&channel->intent_lock); idr_remove(&channel->liids, intent->id); spin_unlock(&channel->intent_lock); } /* Schedule the sending of a rx_done indication */ spin_lock(&channel->intent_lock); list_add_tail(&intent->node, &channel->done_intents); spin_unlock(&channel->intent_lock); schedule_work(&channel->intent_work); } /** * qcom_glink_receive_version() - receive version/features from remote system * * @glink: pointer to transport interface * @version: remote version * @features: remote features * * This function is called in response to a remote-initiated version/feature * negotiation sequence. */ static void qcom_glink_receive_version(struct qcom_glink *glink, u32 version, u32 features) { switch (version) { case 0: break; case GLINK_VERSION_1: glink->features &= features; fallthrough; default: qcom_glink_send_version_ack(glink); break; } } /** * qcom_glink_receive_version_ack() - receive negotiation ack from remote system * * @glink: pointer to transport interface * @version: remote version response * @features: remote features response * * This function is called in response to a local-initiated version/feature * negotiation sequence and is the counter-offer from the remote side based * upon the initial version and feature set requested. */ static void qcom_glink_receive_version_ack(struct qcom_glink *glink, u32 version, u32 features) { switch (version) { case 0: /* Version negotiation failed */ break; case GLINK_VERSION_1: if (features == glink->features) break; glink->features &= features; fallthrough; default: qcom_glink_send_version(glink); break; } } /** * qcom_glink_send_intent_req_ack() - convert an rx intent request ack cmd to * wire format and transmit * @glink: The transport to transmit on. * @channel: The glink channel * @granted: The request response to encode. * * Return: 0 on success or standard Linux error code. */ static int qcom_glink_send_intent_req_ack(struct qcom_glink *glink, struct glink_channel *channel, bool granted) { struct glink_msg msg; msg.cmd = cpu_to_le16(GLINK_CMD_RX_INTENT_REQ_ACK); msg.param1 = cpu_to_le16(channel->lcid); msg.param2 = cpu_to_le32(granted); qcom_glink_tx(glink, &msg, sizeof(msg), NULL, 0, true); return 0; } /** * qcom_glink_advertise_intent - convert an rx intent cmd to wire format and * transmit * @glink: The transport to transmit on. * @channel: The local channel * @intent: The intent to pass on to remote. * * Return: 0 on success or standard Linux error code. */ static int qcom_glink_advertise_intent(struct qcom_glink *glink, struct glink_channel *channel, struct glink_core_rx_intent *intent) { struct command { __le16 id; __le16 lcid; __le32 count; __le32 size; __le32 liid; } __packed; struct command cmd; cmd.id = cpu_to_le16(GLINK_CMD_INTENT); cmd.lcid = cpu_to_le16(channel->lcid); cmd.count = cpu_to_le32(1); cmd.size = cpu_to_le32(intent->size); cmd.liid = cpu_to_le32(intent->id); qcom_glink_tx(glink, &cmd, sizeof(cmd), NULL, 0, true); return 0; } static struct glink_core_rx_intent * qcom_glink_alloc_intent(struct qcom_glink *glink, struct glink_channel *channel, size_t size, bool reuseable) { struct glink_core_rx_intent *intent; int ret; unsigned long flags; intent = kzalloc(sizeof(*intent), GFP_KERNEL); if (!intent) return NULL; intent->data = kzalloc(size, GFP_KERNEL); if (!intent->data) goto free_intent; spin_lock_irqsave(&channel->intent_lock, flags); ret = idr_alloc_cyclic(&channel->liids, intent, 1, -1, GFP_ATOMIC); if (ret < 0) { spin_unlock_irqrestore(&channel->intent_lock, flags); goto free_data; } spin_unlock_irqrestore(&channel->intent_lock, flags); intent->id = ret; intent->size = size; intent->reuse = reuseable; return intent; free_data: kfree(intent->data); free_intent: kfree(intent); return NULL; } static void qcom_glink_handle_rx_done(struct qcom_glink *glink, u32 cid, uint32_t iid, bool reuse) { struct glink_core_rx_intent *intent; struct glink_channel *channel; unsigned long flags; spin_lock_irqsave(&glink->idr_lock, flags); channel = idr_find(&glink->rcids, cid); spin_unlock_irqrestore(&glink->idr_lock, flags); if (!channel) { dev_err(glink->dev, "invalid channel id received\n"); return; } spin_lock_irqsave(&channel->intent_lock, flags); intent = idr_find(&channel->riids, iid); if (!intent) { spin_unlock_irqrestore(&channel->intent_lock, flags); dev_err(glink->dev, "invalid intent id received\n"); return; } intent->in_use = false; if (!reuse) { idr_remove(&channel->riids, intent->id); kfree(intent); } spin_unlock_irqrestore(&channel->intent_lock, flags); if (reuse) { WRITE_ONCE(channel->intent_received, true); wake_up_all(&channel->intent_req_wq); } } /** * qcom_glink_handle_intent_req() - Receive a request for rx_intent * from remote side * @glink: Pointer to the transport interface * @cid: Remote channel ID * @size: size of the intent * * The function searches for the local channel to which the request for * rx_intent has arrived and allocates and notifies the remote back */ static void qcom_glink_handle_intent_req(struct qcom_glink *glink, u32 cid, size_t size) { struct glink_core_rx_intent *intent; struct glink_channel *channel; unsigned long flags; spin_lock_irqsave(&glink->idr_lock, flags); channel = idr_find(&glink->rcids, cid); spin_unlock_irqrestore(&glink->idr_lock, flags); if (!channel) { pr_err("%s channel not found for cid %d\n", __func__, cid); return; } intent = qcom_glink_alloc_intent(glink, channel, size, false); if (intent) qcom_glink_advertise_intent(glink, channel, intent); qcom_glink_send_intent_req_ack(glink, channel, !!intent); } static int qcom_glink_rx_defer(struct qcom_glink *glink, size_t extra) { struct glink_defer_cmd *dcmd; extra = ALIGN(extra, 8); if (qcom_glink_rx_avail(glink) < sizeof(struct glink_msg) + extra) { dev_dbg(glink->dev, "Insufficient data in rx fifo"); return -ENXIO; } dcmd = kzalloc(struct_size(dcmd, data, extra), GFP_ATOMIC); if (!dcmd) return -ENOMEM; INIT_LIST_HEAD(&dcmd->node); qcom_glink_rx_peek(glink, &dcmd->msg, 0, sizeof(dcmd->msg) + extra); spin_lock(&glink->rx_lock); list_add_tail(&dcmd->node, &glink->rx_queue); spin_unlock(&glink->rx_lock); schedule_work(&glink->rx_work); qcom_glink_rx_advance(glink, sizeof(dcmd->msg) + extra); return 0; } static int qcom_glink_rx_data(struct qcom_glink *glink, size_t avail) { struct glink_core_rx_intent *intent; struct glink_channel *channel; struct { struct glink_msg msg; __le32 chunk_size; __le32 left_size; } __packed hdr; unsigned int chunk_size; unsigned int left_size; unsigned int rcid; unsigned int liid; int ret = 0; unsigned long flags; if (avail < sizeof(hdr)) { dev_dbg(glink->dev, "Not enough data in fifo\n"); return -EAGAIN; } qcom_glink_rx_peek(glink, &hdr, 0, sizeof(hdr)); chunk_size = le32_to_cpu(hdr.chunk_size); left_size = le32_to_cpu(hdr.left_size); if (avail < sizeof(hdr) + chunk_size) { dev_dbg(glink->dev, "Payload not yet in fifo\n"); return -EAGAIN; } rcid = le16_to_cpu(hdr.msg.param1); spin_lock_irqsave(&glink->idr_lock, flags); channel = idr_find(&glink->rcids, rcid); spin_unlock_irqrestore(&glink->idr_lock, flags); if (!channel) { dev_dbg(glink->dev, "Data on non-existing channel\n"); /* Drop the message */ goto advance_rx; } if (glink->intentless) { /* Might have an ongoing, fragmented, message to append */ if (!channel->buf) { intent = kzalloc(sizeof(*intent), GFP_ATOMIC); if (!intent) return -ENOMEM; intent->data = kmalloc(chunk_size + left_size, GFP_ATOMIC); if (!intent->data) { kfree(intent); return -ENOMEM; } intent->id = 0xbabababa; intent->size = chunk_size + left_size; intent->offset = 0; channel->buf = intent; } else { intent = channel->buf; } } else { liid = le32_to_cpu(hdr.msg.param2); spin_lock_irqsave(&channel->intent_lock, flags); intent = idr_find(&channel->liids, liid); spin_unlock_irqrestore(&channel->intent_lock, flags); if (!intent) { dev_err(glink->dev, "no intent found for channel %s intent %d", channel->name, liid); ret = -ENOENT; goto advance_rx; } } if (intent->size - intent->offset < chunk_size) { dev_err(glink->dev, "Insufficient space in intent\n"); /* The packet header lied, drop payload */ goto advance_rx; } qcom_glink_rx_peek(glink, intent->data + intent->offset, sizeof(hdr), chunk_size); intent->offset += chunk_size; /* Handle message when no fragments remain to be received */ if (!left_size) { spin_lock(&channel->recv_lock); if (channel->ept.cb) { channel->ept.cb(channel->ept.rpdev, intent->data, intent->offset, channel->ept.priv, RPMSG_ADDR_ANY); } spin_unlock(&channel->recv_lock); intent->offset = 0; channel->buf = NULL; qcom_glink_rx_done(glink, channel, intent); } advance_rx: qcom_glink_rx_advance(glink, ALIGN(sizeof(hdr) + chunk_size, 8)); return ret; } static void qcom_glink_handle_intent(struct qcom_glink *glink, unsigned int cid, unsigned int count, size_t avail) { struct glink_core_rx_intent *intent; struct glink_channel *channel; struct intent_pair { __le32 size; __le32 iid; }; struct { struct glink_msg msg; struct intent_pair intents[]; } __packed * msg; const size_t msglen = struct_size(msg, intents, count); int ret; int i; unsigned long flags; if (avail < msglen) { dev_dbg(glink->dev, "Not enough data in fifo\n"); return; } spin_lock_irqsave(&glink->idr_lock, flags); channel = idr_find(&glink->rcids, cid); spin_unlock_irqrestore(&glink->idr_lock, flags); if (!channel) { dev_err(glink->dev, "intents for non-existing channel\n"); qcom_glink_rx_advance(glink, ALIGN(msglen, 8)); return; } msg = kmalloc(msglen, GFP_ATOMIC); if (!msg) return; qcom_glink_rx_peek(glink, msg, 0, msglen); for (i = 0; i < count; ++i) { intent = kzalloc(sizeof(*intent), GFP_ATOMIC); if (!intent) break; intent->id = le32_to_cpu(msg->intents[i].iid); intent->size = le32_to_cpu(msg->intents[i].size); spin_lock_irqsave(&channel->intent_lock, flags); ret = idr_alloc(&channel->riids, intent, intent->id, intent->id + 1, GFP_ATOMIC); spin_unlock_irqrestore(&channel->intent_lock, flags); if (ret < 0) dev_err(glink->dev, "failed to store remote intent\n"); } WRITE_ONCE(channel->intent_received, true); wake_up_all(&channel->intent_req_wq); kfree(msg); qcom_glink_rx_advance(glink, ALIGN(msglen, 8)); } static int qcom_glink_rx_open_ack(struct qcom_glink *glink, unsigned int lcid) { struct glink_channel *channel; spin_lock(&glink->idr_lock); channel = idr_find(&glink->lcids, lcid); spin_unlock(&glink->idr_lock); if (!channel) { dev_err(glink->dev, "Invalid open ack packet\n"); return -EINVAL; } complete_all(&channel->open_ack); return 0; } /** * qcom_glink_set_flow_control() - convert a signal cmd to wire format and transmit * @ept: Rpmsg endpoint for channel. * @pause: Pause transmission * @dst: destination address of the endpoint * * Return: 0 on success or standard Linux error code. */ static int qcom_glink_set_flow_control(struct rpmsg_endpoint *ept, bool pause, u32 dst) { struct glink_channel *channel = to_glink_channel(ept); struct qcom_glink *glink = channel->glink; struct glink_msg msg; u32 sigs = 0; if (pause) sigs |= NATIVE_DTR_SIG | NATIVE_RTS_SIG; msg.cmd = cpu_to_le16(GLINK_CMD_SIGNALS); msg.param1 = cpu_to_le16(channel->lcid); msg.param2 = cpu_to_le32(sigs); return qcom_glink_tx(glink, &msg, sizeof(msg), NULL, 0, true); } static void qcom_glink_handle_signals(struct qcom_glink *glink, unsigned int rcid, unsigned int sigs) { struct glink_channel *channel; unsigned long flags; bool enable; spin_lock_irqsave(&glink->idr_lock, flags); channel = idr_find(&glink->rcids, rcid); spin_unlock_irqrestore(&glink->idr_lock, flags); if (!channel) { dev_err(glink->dev, "signal for non-existing channel\n"); return; } enable = sigs & NATIVE_DSR_SIG || sigs & NATIVE_CTS_SIG; if (channel->ept.flow_cb) channel->ept.flow_cb(channel->ept.rpdev, channel->ept.priv, enable); } void qcom_glink_native_rx(struct qcom_glink *glink) { struct glink_msg msg; unsigned int param1; unsigned int param2; unsigned int avail; unsigned int cmd; int ret = 0; /* To wakeup any blocking writers */ wake_up_all(&glink->tx_avail_notify); for (;;) { avail = qcom_glink_rx_avail(glink); if (avail < sizeof(msg)) break; qcom_glink_rx_peek(glink, &msg, 0, sizeof(msg)); cmd = le16_to_cpu(msg.cmd); param1 = le16_to_cpu(msg.param1); param2 = le32_to_cpu(msg.param2); switch (cmd) { case GLINK_CMD_VERSION: case GLINK_CMD_VERSION_ACK: case GLINK_CMD_CLOSE: case GLINK_CMD_CLOSE_ACK: case GLINK_CMD_RX_INTENT_REQ: ret = qcom_glink_rx_defer(glink, 0); break; case GLINK_CMD_OPEN_ACK: ret = qcom_glink_rx_open_ack(glink, param1); qcom_glink_rx_advance(glink, ALIGN(sizeof(msg), 8)); break; case GLINK_CMD_OPEN: ret = qcom_glink_rx_defer(glink, param2); break; case GLINK_CMD_TX_DATA: case GLINK_CMD_TX_DATA_CONT: ret = qcom_glink_rx_data(glink, avail); break; case GLINK_CMD_READ_NOTIF: qcom_glink_rx_advance(glink, ALIGN(sizeof(msg), 8)); qcom_glink_tx_kick(glink); break; case GLINK_CMD_INTENT: qcom_glink_handle_intent(glink, param1, param2, avail); break; case GLINK_CMD_RX_DONE: qcom_glink_handle_rx_done(glink, param1, param2, false); qcom_glink_rx_advance(glink, ALIGN(sizeof(msg), 8)); break; case GLINK_CMD_RX_DONE_W_REUSE: qcom_glink_handle_rx_done(glink, param1, param2, true); qcom_glink_rx_advance(glink, ALIGN(sizeof(msg), 8)); break; case GLINK_CMD_RX_INTENT_REQ_ACK: qcom_glink_handle_intent_req_ack(glink, param1, param2); qcom_glink_rx_advance(glink, ALIGN(sizeof(msg), 8)); break; case GLINK_CMD_SIGNALS: qcom_glink_handle_signals(glink, param1, param2); qcom_glink_rx_advance(glink, ALIGN(sizeof(msg), 8)); break; default: dev_err(glink->dev, "unhandled rx cmd: %d\n", cmd); ret = -EINVAL; break; } if (ret) break; } } EXPORT_SYMBOL(qcom_glink_native_rx); /* Locally initiated rpmsg_create_ept */ static struct glink_channel *qcom_glink_create_local(struct qcom_glink *glink, const char *name) { struct glink_channel *channel; int ret; unsigned long flags; channel = qcom_glink_alloc_channel(glink, name); if (IS_ERR(channel)) return ERR_CAST(channel); ret = qcom_glink_send_open_req(glink, channel); if (ret) goto release_channel; ret = wait_for_completion_timeout(&channel->open_ack, 5 * HZ); if (!ret) goto err_timeout; ret = wait_for_completion_timeout(&channel->open_req, 5 * HZ); if (!ret) goto err_timeout; qcom_glink_send_open_ack(glink, channel); return channel; err_timeout: /* qcom_glink_send_open_req() did register the channel in lcids*/ spin_lock_irqsave(&glink->idr_lock, flags); idr_remove(&glink->lcids, channel->lcid); spin_unlock_irqrestore(&glink->idr_lock, flags); release_channel: /* Release qcom_glink_send_open_req() reference */ kref_put(&channel->refcount, qcom_glink_channel_release); /* Release qcom_glink_alloc_channel() reference */ kref_put(&channel->refcount, qcom_glink_channel_release); return ERR_PTR(-ETIMEDOUT); } /* Remote initiated rpmsg_create_ept */ static int qcom_glink_create_remote(struct qcom_glink *glink, struct glink_channel *channel) { int ret; qcom_glink_send_open_ack(glink, channel); ret = qcom_glink_send_open_req(glink, channel); if (ret) goto close_link; ret = wait_for_completion_timeout(&channel->open_ack, 5 * HZ); if (!ret) { ret = -ETIMEDOUT; goto close_link; } return 0; close_link: /* * Send a close request to "undo" our open-ack. The close-ack will * release qcom_glink_send_open_req() reference and the last reference * will be relesed after receiving remote_close or transport unregister * by calling qcom_glink_native_remove(). */ qcom_glink_send_close_req(glink, channel); return ret; } static struct rpmsg_endpoint *qcom_glink_create_ept(struct rpmsg_device *rpdev, rpmsg_rx_cb_t cb, void *priv, struct rpmsg_channel_info chinfo) { struct glink_channel *parent = to_glink_channel(rpdev->ept); struct glink_channel *channel; struct qcom_glink *glink = parent->glink; struct rpmsg_endpoint *ept; const char *name = chinfo.name; int cid; int ret; unsigned long flags; spin_lock_irqsave(&glink->idr_lock, flags); idr_for_each_entry(&glink->rcids, channel, cid) { if (!strcmp(channel->name, name)) break; } spin_unlock_irqrestore(&glink->idr_lock, flags); if (!channel) { channel = qcom_glink_create_local(glink, name); if (IS_ERR(channel)) return NULL; } else { ret = qcom_glink_create_remote(glink, channel); if (ret) return NULL; } ept = &channel->ept; ept->rpdev = rpdev; ept->cb = cb; ept->priv = priv; ept->ops = &glink_endpoint_ops; return ept; } static int qcom_glink_announce_create(struct rpmsg_device *rpdev) { struct glink_channel *channel = to_glink_channel(rpdev->ept); struct device_node *np = rpdev->dev.of_node; struct qcom_glink *glink = channel->glink; struct glink_core_rx_intent *intent; const struct property *prop = NULL; __be32 defaults[] = { cpu_to_be32(SZ_1K), cpu_to_be32(5) }; int num_intents; int num_groups = 1; __be32 *val = defaults; int size; if (glink->intentless || !completion_done(&channel->open_ack)) return 0; prop = of_find_property(np, "qcom,intents", NULL); if (prop) { val = prop->value; num_groups = prop->length / sizeof(u32) / 2; } /* Channel is now open, advertise base set of intents */ while (num_groups--) { size = be32_to_cpup(val++); num_intents = be32_to_cpup(val++); while (num_intents--) { intent = qcom_glink_alloc_intent(glink, channel, size, true); if (!intent) break; qcom_glink_advertise_intent(glink, channel, intent); } } return 0; } static void qcom_glink_destroy_ept(struct rpmsg_endpoint *ept) { struct glink_channel *channel = to_glink_channel(ept); struct qcom_glink *glink = channel->glink; unsigned long flags; spin_lock_irqsave(&channel->recv_lock, flags); channel->ept.cb = NULL; spin_unlock_irqrestore(&channel->recv_lock, flags); /* Decouple the potential rpdev from the channel */ channel->rpdev = NULL; qcom_glink_send_close_req(glink, channel); } static int qcom_glink_request_intent(struct qcom_glink *glink, struct glink_channel *channel, size_t size) { struct { u16 id; u16 cid; u32 size; } __packed cmd; int ret; mutex_lock(&channel->intent_req_lock); WRITE_ONCE(channel->intent_req_result, -1); WRITE_ONCE(channel->intent_received, false); cmd.id = GLINK_CMD_RX_INTENT_REQ; cmd.cid = channel->lcid; cmd.size = size; ret = qcom_glink_tx(glink, &cmd, sizeof(cmd), NULL, 0, true); if (ret) goto unlock; ret = wait_event_timeout(channel->intent_req_wq, READ_ONCE(channel->intent_req_result) >= 0 && READ_ONCE(channel->intent_received), 10 * HZ); if (!ret) { dev_err(glink->dev, "intent request timed out\n"); ret = -ETIMEDOUT; } else { ret = READ_ONCE(channel->intent_req_result) ? 0 : -ECANCELED; } unlock: mutex_unlock(&channel->intent_req_lock); return ret; } static int __qcom_glink_send(struct glink_channel *channel, void *data, int len, bool wait) { struct qcom_glink *glink = channel->glink; struct glink_core_rx_intent *intent = NULL; struct glink_core_rx_intent *tmp; int iid = 0; struct { struct glink_msg msg; __le32 chunk_size; __le32 left_size; } __packed req; int ret; unsigned long flags; int chunk_size = len; size_t offset = 0; if (!glink->intentless) { while (!intent) { spin_lock_irqsave(&channel->intent_lock, flags); idr_for_each_entry(&channel->riids, tmp, iid) { if (tmp->size >= len && !tmp->in_use) { if (!intent) intent = tmp; else if (intent->size > tmp->size) intent = tmp; if (intent->size == len) break; } } if (intent) intent->in_use = true; spin_unlock_irqrestore(&channel->intent_lock, flags); /* We found an available intent */ if (intent) break; if (!wait) return -EBUSY; ret = qcom_glink_request_intent(glink, channel, len); if (ret < 0) return ret; } iid = intent->id; } while (offset < len) { chunk_size = len - offset; if (chunk_size > SZ_8K && wait) chunk_size = SZ_8K; req.msg.cmd = cpu_to_le16(offset == 0 ? GLINK_CMD_TX_DATA : GLINK_CMD_TX_DATA_CONT); req.msg.param1 = cpu_to_le16(channel->lcid); req.msg.param2 = cpu_to_le32(iid); req.chunk_size = cpu_to_le32(chunk_size); req.left_size = cpu_to_le32(len - offset - chunk_size); ret = qcom_glink_tx(glink, &req, sizeof(req), data + offset, chunk_size, wait); if (ret) { /* Mark intent available if we failed */ if (intent) intent->in_use = false; return ret; } offset += chunk_size; } return 0; } static int qcom_glink_send(struct rpmsg_endpoint *ept, void *data, int len) { struct glink_channel *channel = to_glink_channel(ept); return __qcom_glink_send(channel, data, len, true); } static int qcom_glink_trysend(struct rpmsg_endpoint *ept, void *data, int len) { struct glink_channel *channel = to_glink_channel(ept); return __qcom_glink_send(channel, data, len, false); } static int qcom_glink_sendto(struct rpmsg_endpoint *ept, void *data, int len, u32 dst) { struct glink_channel *channel = to_glink_channel(ept); return __qcom_glink_send(channel, data, len, true); } static int qcom_glink_trysendto(struct rpmsg_endpoint *ept, void *data, int len, u32 dst) { struct glink_channel *channel = to_glink_channel(ept); return __qcom_glink_send(channel, data, len, false); } /* * Finds the device_node for the glink child interested in this channel. */ static struct device_node *qcom_glink_match_channel(struct device_node *node, const char *channel) { struct device_node *child; const char *name; const char *key; int ret; for_each_available_child_of_node(node, child) { key = "qcom,glink-channels"; ret = of_property_read_string(child, key, &name); if (ret) continue; if (strcmp(name, channel) == 0) return child; } return NULL; } static const struct rpmsg_device_ops glink_device_ops = { .create_ept = qcom_glink_create_ept, .announce_create = qcom_glink_announce_create, }; static const struct rpmsg_endpoint_ops glink_endpoint_ops = { .destroy_ept = qcom_glink_destroy_ept, .send = qcom_glink_send, .sendto = qcom_glink_sendto, .trysend = qcom_glink_trysend, .trysendto = qcom_glink_trysendto, .set_flow_control = qcom_glink_set_flow_control, }; static void qcom_glink_rpdev_release(struct device *dev) { struct rpmsg_device *rpdev = to_rpmsg_device(dev); kfree(rpdev->driver_override); kfree(rpdev); } static int qcom_glink_rx_open(struct qcom_glink *glink, unsigned int rcid, char *name) { struct glink_channel *channel; struct rpmsg_device *rpdev; bool create_device = false; struct device_node *node; int lcid; int ret; unsigned long flags; spin_lock_irqsave(&glink->idr_lock, flags); idr_for_each_entry(&glink->lcids, channel, lcid) { if (!strcmp(channel->name, name)) break; } spin_unlock_irqrestore(&glink->idr_lock, flags); if (!channel) { channel = qcom_glink_alloc_channel(glink, name); if (IS_ERR(channel)) return PTR_ERR(channel); /* The opening dance was initiated by the remote */ create_device = true; } spin_lock_irqsave(&glink->idr_lock, flags); ret = idr_alloc(&glink->rcids, channel, rcid, rcid + 1, GFP_ATOMIC); if (ret < 0) { dev_err(glink->dev, "Unable to insert channel into rcid list\n"); spin_unlock_irqrestore(&glink->idr_lock, flags); goto free_channel; } channel->rcid = ret; spin_unlock_irqrestore(&glink->idr_lock, flags); complete_all(&channel->open_req); if (create_device) { rpdev = kzalloc(sizeof(*rpdev), GFP_KERNEL); if (!rpdev) { ret = -ENOMEM; goto rcid_remove; } rpdev->ept = &channel->ept; strscpy_pad(rpdev->id.name, name, RPMSG_NAME_SIZE); rpdev->src = RPMSG_ADDR_ANY; rpdev->dst = RPMSG_ADDR_ANY; rpdev->ops = &glink_device_ops; node = qcom_glink_match_channel(glink->dev->of_node, name); rpdev->dev.of_node = node; rpdev->dev.parent = glink->dev; rpdev->dev.release = qcom_glink_rpdev_release; ret = rpmsg_register_device(rpdev); if (ret) goto rcid_remove; channel->rpdev = rpdev; } return 0; rcid_remove: spin_lock_irqsave(&glink->idr_lock, flags); idr_remove(&glink->rcids, channel->rcid); channel->rcid = 0; spin_unlock_irqrestore(&glink->idr_lock, flags); free_channel: /* Release the reference, iff we took it */ if (create_device) kref_put(&channel->refcount, qcom_glink_channel_release); return ret; } static void qcom_glink_rx_close(struct qcom_glink *glink, unsigned int rcid) { struct rpmsg_channel_info chinfo; struct glink_channel *channel; unsigned long flags; spin_lock_irqsave(&glink->idr_lock, flags); channel = idr_find(&glink->rcids, rcid); spin_unlock_irqrestore(&glink->idr_lock, flags); if (WARN(!channel, "close request on unknown channel\n")) return; /* cancel pending rx_done work */ cancel_work_sync(&channel->intent_work); if (channel->rpdev) { strscpy_pad(chinfo.name, channel->name, sizeof(chinfo.name)); chinfo.src = RPMSG_ADDR_ANY; chinfo.dst = RPMSG_ADDR_ANY; rpmsg_unregister_device(glink->dev, &chinfo); } channel->rpdev = NULL; qcom_glink_send_close_ack(glink, channel->rcid); spin_lock_irqsave(&glink->idr_lock, flags); idr_remove(&glink->rcids, channel->rcid); channel->rcid = 0; spin_unlock_irqrestore(&glink->idr_lock, flags); kref_put(&channel->refcount, qcom_glink_channel_release); } static void qcom_glink_rx_close_ack(struct qcom_glink *glink, unsigned int lcid) { struct rpmsg_channel_info chinfo; struct glink_channel *channel; unsigned long flags; /* To wakeup any blocking writers */ wake_up_all(&glink->tx_avail_notify); spin_lock_irqsave(&glink->idr_lock, flags); channel = idr_find(&glink->lcids, lcid); if (WARN(!channel, "close ack on unknown channel\n")) { spin_unlock_irqrestore(&glink->idr_lock, flags); return; } idr_remove(&glink->lcids, channel->lcid); channel->lcid = 0; spin_unlock_irqrestore(&glink->idr_lock, flags); /* Decouple the potential rpdev from the channel */ if (channel->rpdev) { strscpy(chinfo.name, channel->name, sizeof(chinfo.name)); chinfo.src = RPMSG_ADDR_ANY; chinfo.dst = RPMSG_ADDR_ANY; rpmsg_unregister_device(glink->dev, &chinfo); } channel->rpdev = NULL; kref_put(&channel->refcount, qcom_glink_channel_release); } static void qcom_glink_work(struct work_struct *work) { struct qcom_glink *glink = container_of(work, struct qcom_glink, rx_work); struct glink_defer_cmd *dcmd; struct glink_msg *msg; unsigned long flags; unsigned int param1; unsigned int param2; unsigned int cmd; for (;;) { spin_lock_irqsave(&glink->rx_lock, flags); if (list_empty(&glink->rx_queue)) { spin_unlock_irqrestore(&glink->rx_lock, flags); break; } dcmd = list_first_entry(&glink->rx_queue, struct glink_defer_cmd, node); list_del(&dcmd->node); spin_unlock_irqrestore(&glink->rx_lock, flags); msg = &dcmd->msg; cmd = le16_to_cpu(msg->cmd); param1 = le16_to_cpu(msg->param1); param2 = le32_to_cpu(msg->param2); switch (cmd) { case GLINK_CMD_VERSION: qcom_glink_receive_version(glink, param1, param2); break; case GLINK_CMD_VERSION_ACK: qcom_glink_receive_version_ack(glink, param1, param2); break; case GLINK_CMD_OPEN: qcom_glink_rx_open(glink, param1, msg->data); break; case GLINK_CMD_CLOSE: qcom_glink_rx_close(glink, param1); break; case GLINK_CMD_CLOSE_ACK: qcom_glink_rx_close_ack(glink, param1); break; case GLINK_CMD_RX_INTENT_REQ: qcom_glink_handle_intent_req(glink, param1, param2); break; default: WARN(1, "Unknown defer object %d\n", cmd); break; } kfree(dcmd); } } static void qcom_glink_cancel_rx_work(struct qcom_glink *glink) { struct glink_defer_cmd *dcmd; struct glink_defer_cmd *tmp; /* cancel any pending deferred rx_work */ cancel_work_sync(&glink->rx_work); list_for_each_entry_safe(dcmd, tmp, &glink->rx_queue, node) kfree(dcmd); } static ssize_t rpmsg_name_show(struct device *dev, struct device_attribute *attr, char *buf) { int ret = 0; const char *name; ret = of_property_read_string(dev->of_node, "label", &name); if (ret < 0) name = dev->of_node->name; return sysfs_emit(buf, "%s\n", name); } static DEVICE_ATTR_RO(rpmsg_name); static struct attribute *qcom_glink_attrs[] = { &dev_attr_rpmsg_name.attr, NULL }; ATTRIBUTE_GROUPS(qcom_glink); static void qcom_glink_device_release(struct device *dev) { struct rpmsg_device *rpdev = to_rpmsg_device(dev); struct glink_channel *channel = to_glink_channel(rpdev->ept); /* Release qcom_glink_alloc_channel() reference */ kref_put(&channel->refcount, qcom_glink_channel_release); kfree(rpdev->driver_override); kfree(rpdev); } static int qcom_glink_create_chrdev(struct qcom_glink *glink) { struct rpmsg_device *rpdev; struct glink_channel *channel; rpdev = kzalloc(sizeof(*rpdev), GFP_KERNEL); if (!rpdev) return -ENOMEM; channel = qcom_glink_alloc_channel(glink, "rpmsg_chrdev"); if (IS_ERR(channel)) { kfree(rpdev); return PTR_ERR(channel); } channel->rpdev = rpdev; rpdev->ept = &channel->ept; rpdev->ops = &glink_device_ops; rpdev->dev.parent = glink->dev; rpdev->dev.release = qcom_glink_device_release; return rpmsg_ctrldev_register_device(rpdev); } struct qcom_glink *qcom_glink_native_probe(struct device *dev, unsigned long features, struct qcom_glink_pipe *rx, struct qcom_glink_pipe *tx, bool intentless) { int ret; struct qcom_glink *glink; glink = devm_kzalloc(dev, sizeof(*glink), GFP_KERNEL); if (!glink) return ERR_PTR(-ENOMEM); glink->dev = dev; glink->tx_pipe = tx; glink->rx_pipe = rx; glink->features = features; glink->intentless = intentless; spin_lock_init(&glink->tx_lock); spin_lock_init(&glink->rx_lock); INIT_LIST_HEAD(&glink->rx_queue); INIT_WORK(&glink->rx_work, qcom_glink_work); init_waitqueue_head(&glink->tx_avail_notify); spin_lock_init(&glink->idr_lock); idr_init(&glink->lcids); idr_init(&glink->rcids); glink->dev->groups = qcom_glink_groups; ret = device_add_groups(dev, qcom_glink_groups); if (ret) dev_err(dev, "failed to add groups\n"); ret = qcom_glink_send_version(glink); if (ret) return ERR_PTR(ret); ret = qcom_glink_create_chrdev(glink); if (ret) dev_err(glink->dev, "failed to register chrdev\n"); return glink; } EXPORT_SYMBOL_GPL(qcom_glink_native_probe); static int qcom_glink_remove_device(struct device *dev, void *data) { device_unregister(dev); return 0; } void qcom_glink_native_remove(struct qcom_glink *glink) { struct glink_channel *channel; unsigned long flags; int cid; int ret; qcom_glink_cancel_rx_work(glink); /* Fail all attempts at sending messages */ spin_lock_irqsave(&glink->tx_lock, flags); glink->abort_tx = true; wake_up_all(&glink->tx_avail_notify); spin_unlock_irqrestore(&glink->tx_lock, flags); /* Abort any senders waiting for intent requests */ spin_lock_irqsave(&glink->idr_lock, flags); idr_for_each_entry(&glink->lcids, channel, cid) qcom_glink_intent_req_abort(channel); spin_unlock_irqrestore(&glink->idr_lock, flags); ret = device_for_each_child(glink->dev, NULL, qcom_glink_remove_device); if (ret) dev_warn(glink->dev, "Can't remove GLINK devices: %d\n", ret); /* Release any defunct local channels, waiting for close-ack */ idr_for_each_entry(&glink->lcids, channel, cid) kref_put(&channel->refcount, qcom_glink_channel_release); /* Release any defunct local channels, waiting for close-req */ idr_for_each_entry(&glink->rcids, channel, cid) kref_put(&channel->refcount, qcom_glink_channel_release); idr_destroy(&glink->lcids); idr_destroy(&glink->rcids); } EXPORT_SYMBOL_GPL(qcom_glink_native_remove); MODULE_DESCRIPTION("Qualcomm GLINK driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/rpmsg/qcom_glink_native.c
// SPDX-License-Identifier: GPL-2.0 /* * remote processor messaging bus * * Copyright (C) 2011 Texas Instruments, Inc. * Copyright (C) 2011 Google, Inc. * * Ohad Ben-Cohen <[email protected]> * Brian Swetland <[email protected]> */ #define pr_fmt(fmt) "%s: " fmt, __func__ #include <linux/kernel.h> #include <linux/module.h> #include <linux/rpmsg.h> #include <linux/of_device.h> #include <linux/pm_domain.h> #include <linux/slab.h> #include "rpmsg_internal.h" struct class *rpmsg_class; EXPORT_SYMBOL(rpmsg_class); /** * rpmsg_create_channel() - create a new rpmsg channel * using its name and address info. * @rpdev: rpmsg device * @chinfo: channel_info to bind * * Return: a pointer to the new rpmsg device on success, or NULL on error. */ struct rpmsg_device *rpmsg_create_channel(struct rpmsg_device *rpdev, struct rpmsg_channel_info *chinfo) { if (WARN_ON(!rpdev)) return NULL; if (!rpdev->ops || !rpdev->ops->create_channel) { dev_err(&rpdev->dev, "no create_channel ops found\n"); return NULL; } return rpdev->ops->create_channel(rpdev, chinfo); } EXPORT_SYMBOL(rpmsg_create_channel); /** * rpmsg_release_channel() - release a rpmsg channel * using its name and address info. * @rpdev: rpmsg device * @chinfo: channel_info to bind * * Return: 0 on success or an appropriate error value. */ int rpmsg_release_channel(struct rpmsg_device *rpdev, struct rpmsg_channel_info *chinfo) { if (WARN_ON(!rpdev)) return -EINVAL; if (!rpdev->ops || !rpdev->ops->release_channel) { dev_err(&rpdev->dev, "no release_channel ops found\n"); return -ENXIO; } return rpdev->ops->release_channel(rpdev, chinfo); } EXPORT_SYMBOL(rpmsg_release_channel); /** * rpmsg_create_ept() - create a new rpmsg_endpoint * @rpdev: rpmsg channel device * @cb: rx callback handler * @priv: private data for the driver's use * @chinfo: channel_info with the local rpmsg address to bind with @cb * * Every rpmsg address in the system is bound to an rx callback (so when * inbound messages arrive, they are dispatched by the rpmsg bus using the * appropriate callback handler) by means of an rpmsg_endpoint struct. * * This function allows drivers to create such an endpoint, and by that, * bind a callback, and possibly some private data too, to an rpmsg address * (either one that is known in advance, or one that will be dynamically * assigned for them). * * Simple rpmsg drivers need not call rpmsg_create_ept, because an endpoint * is already created for them when they are probed by the rpmsg bus * (using the rx callback provided when they registered to the rpmsg bus). * * So things should just work for simple drivers: they already have an * endpoint, their rx callback is bound to their rpmsg address, and when * relevant inbound messages arrive (i.e. messages which their dst address * equals to the src address of their rpmsg channel), the driver's handler * is invoked to process it. * * That said, more complicated drivers might need to allocate * additional rpmsg addresses, and bind them to different rx callbacks. * To accomplish that, those drivers need to call this function. * * Drivers should provide their @rpdev channel (so the new endpoint would belong * to the same remote processor their channel belongs to), an rx callback * function, an optional private data (which is provided back when the * rx callback is invoked), and an address they want to bind with the * callback. If @addr is RPMSG_ADDR_ANY, then rpmsg_create_ept will * dynamically assign them an available rpmsg address (drivers should have * a very good reason why not to always use RPMSG_ADDR_ANY here). * * Return: a pointer to the endpoint on success, or NULL on error. */ struct rpmsg_endpoint *rpmsg_create_ept(struct rpmsg_device *rpdev, rpmsg_rx_cb_t cb, void *priv, struct rpmsg_channel_info chinfo) { if (WARN_ON(!rpdev)) return NULL; return rpdev->ops->create_ept(rpdev, cb, priv, chinfo); } EXPORT_SYMBOL(rpmsg_create_ept); /** * rpmsg_destroy_ept() - destroy an existing rpmsg endpoint * @ept: endpoing to destroy * * Should be used by drivers to destroy an rpmsg endpoint previously * created with rpmsg_create_ept(). As with other types of "free" NULL * is a valid parameter. */ void rpmsg_destroy_ept(struct rpmsg_endpoint *ept) { if (ept && ept->ops) ept->ops->destroy_ept(ept); } EXPORT_SYMBOL(rpmsg_destroy_ept); /** * rpmsg_send() - send a message across to the remote processor * @ept: the rpmsg endpoint * @data: payload of message * @len: length of payload * * This function sends @data of length @len on the @ept endpoint. * The message will be sent to the remote processor which the @ept * endpoint belongs to, using @ept's address and its associated rpmsg * device destination addresses. * In case there are no TX buffers available, the function will block until * one becomes available, or a timeout of 15 seconds elapses. When the latter * happens, -ERESTARTSYS is returned. * * Can only be called from process context (for now). * * Return: 0 on success and an appropriate error value on failure. */ int rpmsg_send(struct rpmsg_endpoint *ept, void *data, int len) { if (WARN_ON(!ept)) return -EINVAL; if (!ept->ops->send) return -ENXIO; return ept->ops->send(ept, data, len); } EXPORT_SYMBOL(rpmsg_send); /** * rpmsg_sendto() - send a message across to the remote processor, specify dst * @ept: the rpmsg endpoint * @data: payload of message * @len: length of payload * @dst: destination address * * This function sends @data of length @len to the remote @dst address. * The message will be sent to the remote processor which the @ept * endpoint belongs to, using @ept's address as source. * In case there are no TX buffers available, the function will block until * one becomes available, or a timeout of 15 seconds elapses. When the latter * happens, -ERESTARTSYS is returned. * * Can only be called from process context (for now). * * Return: 0 on success and an appropriate error value on failure. */ int rpmsg_sendto(struct rpmsg_endpoint *ept, void *data, int len, u32 dst) { if (WARN_ON(!ept)) return -EINVAL; if (!ept->ops->sendto) return -ENXIO; return ept->ops->sendto(ept, data, len, dst); } EXPORT_SYMBOL(rpmsg_sendto); /** * rpmsg_send_offchannel() - send a message using explicit src/dst addresses * @ept: the rpmsg endpoint * @src: source address * @dst: destination address * @data: payload of message * @len: length of payload * * This function sends @data of length @len to the remote @dst address, * and uses @src as the source address. * The message will be sent to the remote processor which the @ept * endpoint belongs to. * In case there are no TX buffers available, the function will block until * one becomes available, or a timeout of 15 seconds elapses. When the latter * happens, -ERESTARTSYS is returned. * * Can only be called from process context (for now). * * Return: 0 on success and an appropriate error value on failure. */ int rpmsg_send_offchannel(struct rpmsg_endpoint *ept, u32 src, u32 dst, void *data, int len) { if (WARN_ON(!ept)) return -EINVAL; if (!ept->ops->send_offchannel) return -ENXIO; return ept->ops->send_offchannel(ept, src, dst, data, len); } EXPORT_SYMBOL(rpmsg_send_offchannel); /** * rpmsg_trysend() - send a message across to the remote processor * @ept: the rpmsg endpoint * @data: payload of message * @len: length of payload * * This function sends @data of length @len on the @ept endpoint. * The message will be sent to the remote processor which the @ept * endpoint belongs to, using @ept's address as source and its associated * rpdev's address as destination. * In case there are no TX buffers available, the function will immediately * return -ENOMEM without waiting until one becomes available. * * Can only be called from process context (for now). * * Return: 0 on success and an appropriate error value on failure. */ int rpmsg_trysend(struct rpmsg_endpoint *ept, void *data, int len) { if (WARN_ON(!ept)) return -EINVAL; if (!ept->ops->trysend) return -ENXIO; return ept->ops->trysend(ept, data, len); } EXPORT_SYMBOL(rpmsg_trysend); /** * rpmsg_trysendto() - send a message across to the remote processor, specify dst * @ept: the rpmsg endpoint * @data: payload of message * @len: length of payload * @dst: destination address * * This function sends @data of length @len to the remote @dst address. * The message will be sent to the remote processor which the @ept * endpoint belongs to, using @ept's address as source. * In case there are no TX buffers available, the function will immediately * return -ENOMEM without waiting until one becomes available. * * Can only be called from process context (for now). * * Return: 0 on success and an appropriate error value on failure. */ int rpmsg_trysendto(struct rpmsg_endpoint *ept, void *data, int len, u32 dst) { if (WARN_ON(!ept)) return -EINVAL; if (!ept->ops->trysendto) return -ENXIO; return ept->ops->trysendto(ept, data, len, dst); } EXPORT_SYMBOL(rpmsg_trysendto); /** * rpmsg_poll() - poll the endpoint's send buffers * @ept: the rpmsg endpoint * @filp: file for poll_wait() * @wait: poll_table for poll_wait() * * Return: mask representing the current state of the endpoint's send buffers */ __poll_t rpmsg_poll(struct rpmsg_endpoint *ept, struct file *filp, poll_table *wait) { if (WARN_ON(!ept)) return 0; if (!ept->ops->poll) return 0; return ept->ops->poll(ept, filp, wait); } EXPORT_SYMBOL(rpmsg_poll); /** * rpmsg_trysend_offchannel() - send a message using explicit src/dst addresses * @ept: the rpmsg endpoint * @src: source address * @dst: destination address * @data: payload of message * @len: length of payload * * This function sends @data of length @len to the remote @dst address, * and uses @src as the source address. * The message will be sent to the remote processor which the @ept * endpoint belongs to. * In case there are no TX buffers available, the function will immediately * return -ENOMEM without waiting until one becomes available. * * Can only be called from process context (for now). * * Return: 0 on success and an appropriate error value on failure. */ int rpmsg_trysend_offchannel(struct rpmsg_endpoint *ept, u32 src, u32 dst, void *data, int len) { if (WARN_ON(!ept)) return -EINVAL; if (!ept->ops->trysend_offchannel) return -ENXIO; return ept->ops->trysend_offchannel(ept, src, dst, data, len); } EXPORT_SYMBOL(rpmsg_trysend_offchannel); /** * rpmsg_set_flow_control() - request remote to pause/resume transmission * @ept: the rpmsg endpoint * @pause: pause transmission * @dst: destination address of the endpoint * * Return: 0 on success and an appropriate error value on failure. */ int rpmsg_set_flow_control(struct rpmsg_endpoint *ept, bool pause, u32 dst) { if (WARN_ON(!ept)) return -EINVAL; if (!ept->ops->set_flow_control) return -EOPNOTSUPP; return ept->ops->set_flow_control(ept, pause, dst); } EXPORT_SYMBOL_GPL(rpmsg_set_flow_control); /** * rpmsg_get_mtu() - get maximum transmission buffer size for sending message. * @ept: the rpmsg endpoint * * This function returns maximum buffer size available for a single outgoing message. * * Return: the maximum transmission size on success and an appropriate error * value on failure. */ ssize_t rpmsg_get_mtu(struct rpmsg_endpoint *ept) { if (WARN_ON(!ept)) return -EINVAL; if (!ept->ops->get_mtu) return -ENOTSUPP; return ept->ops->get_mtu(ept); } EXPORT_SYMBOL(rpmsg_get_mtu); /* * match a rpmsg channel with a channel info struct. * this is used to make sure we're not creating rpmsg devices for channels * that already exist. */ static int rpmsg_device_match(struct device *dev, void *data) { struct rpmsg_channel_info *chinfo = data; struct rpmsg_device *rpdev = to_rpmsg_device(dev); if (chinfo->src != RPMSG_ADDR_ANY && chinfo->src != rpdev->src) return 0; if (chinfo->dst != RPMSG_ADDR_ANY && chinfo->dst != rpdev->dst) return 0; if (strncmp(chinfo->name, rpdev->id.name, RPMSG_NAME_SIZE)) return 0; /* found a match ! */ return 1; } struct device *rpmsg_find_device(struct device *parent, struct rpmsg_channel_info *chinfo) { return device_find_child(parent, chinfo, rpmsg_device_match); } EXPORT_SYMBOL(rpmsg_find_device); /* sysfs show configuration fields */ #define rpmsg_show_attr(field, path, format_string) \ static ssize_t \ field##_show(struct device *dev, \ struct device_attribute *attr, char *buf) \ { \ struct rpmsg_device *rpdev = to_rpmsg_device(dev); \ \ return sprintf(buf, format_string, rpdev->path); \ } \ static DEVICE_ATTR_RO(field); #define rpmsg_string_attr(field, member) \ static ssize_t \ field##_store(struct device *dev, struct device_attribute *attr, \ const char *buf, size_t sz) \ { \ struct rpmsg_device *rpdev = to_rpmsg_device(dev); \ const char *old; \ char *new; \ \ new = kstrndup(buf, sz, GFP_KERNEL); \ if (!new) \ return -ENOMEM; \ new[strcspn(new, "\n")] = '\0'; \ \ device_lock(dev); \ old = rpdev->member; \ if (strlen(new)) { \ rpdev->member = new; \ } else { \ kfree(new); \ rpdev->member = NULL; \ } \ device_unlock(dev); \ \ kfree(old); \ \ return sz; \ } \ static ssize_t \ field##_show(struct device *dev, \ struct device_attribute *attr, char *buf) \ { \ struct rpmsg_device *rpdev = to_rpmsg_device(dev); \ \ return sprintf(buf, "%s\n", rpdev->member); \ } \ static DEVICE_ATTR_RW(field) /* for more info, see Documentation/ABI/testing/sysfs-bus-rpmsg */ rpmsg_show_attr(name, id.name, "%s\n"); rpmsg_show_attr(src, src, "0x%x\n"); rpmsg_show_attr(dst, dst, "0x%x\n"); rpmsg_show_attr(announce, announce ? "true" : "false", "%s\n"); rpmsg_string_attr(driver_override, driver_override); static ssize_t modalias_show(struct device *dev, struct device_attribute *attr, char *buf) { struct rpmsg_device *rpdev = to_rpmsg_device(dev); ssize_t len; len = of_device_modalias(dev, buf, PAGE_SIZE); if (len != -ENODEV) return len; return sprintf(buf, RPMSG_DEVICE_MODALIAS_FMT "\n", rpdev->id.name); } static DEVICE_ATTR_RO(modalias); static struct attribute *rpmsg_dev_attrs[] = { &dev_attr_name.attr, &dev_attr_modalias.attr, &dev_attr_dst.attr, &dev_attr_src.attr, &dev_attr_announce.attr, &dev_attr_driver_override.attr, NULL, }; ATTRIBUTE_GROUPS(rpmsg_dev); /* rpmsg devices and drivers are matched using the service name */ static inline int rpmsg_id_match(const struct rpmsg_device *rpdev, const struct rpmsg_device_id *id) { return strncmp(id->name, rpdev->id.name, RPMSG_NAME_SIZE) == 0; } /* match rpmsg channel and rpmsg driver */ static int rpmsg_dev_match(struct device *dev, struct device_driver *drv) { struct rpmsg_device *rpdev = to_rpmsg_device(dev); struct rpmsg_driver *rpdrv = to_rpmsg_driver(drv); const struct rpmsg_device_id *ids = rpdrv->id_table; unsigned int i; if (rpdev->driver_override) return !strcmp(rpdev->driver_override, drv->name); if (ids) for (i = 0; ids[i].name[0]; i++) if (rpmsg_id_match(rpdev, &ids[i])) { rpdev->id.driver_data = ids[i].driver_data; return 1; } return of_driver_match_device(dev, drv); } static int rpmsg_uevent(const struct device *dev, struct kobj_uevent_env *env) { const struct rpmsg_device *rpdev = to_rpmsg_device(dev); int ret; ret = of_device_uevent_modalias(dev, env); if (ret != -ENODEV) return ret; return add_uevent_var(env, "MODALIAS=" RPMSG_DEVICE_MODALIAS_FMT, rpdev->id.name); } /* * when an rpmsg driver is probed with a channel, we seamlessly create * it an endpoint, binding its rx callback to a unique local rpmsg * address. * * if we need to, we also announce about this channel to the remote * processor (needed in case the driver is exposing an rpmsg service). */ static int rpmsg_dev_probe(struct device *dev) { struct rpmsg_device *rpdev = to_rpmsg_device(dev); struct rpmsg_driver *rpdrv = to_rpmsg_driver(rpdev->dev.driver); struct rpmsg_channel_info chinfo = {}; struct rpmsg_endpoint *ept = NULL; int err; err = dev_pm_domain_attach(dev, true); if (err) goto out; if (rpdrv->callback) { strncpy(chinfo.name, rpdev->id.name, RPMSG_NAME_SIZE); chinfo.src = rpdev->src; chinfo.dst = RPMSG_ADDR_ANY; ept = rpmsg_create_ept(rpdev, rpdrv->callback, NULL, chinfo); if (!ept) { dev_err(dev, "failed to create endpoint\n"); err = -ENOMEM; goto out; } rpdev->ept = ept; rpdev->src = ept->addr; ept->flow_cb = rpdrv->flowcontrol; } err = rpdrv->probe(rpdev); if (err) { dev_err(dev, "%s: failed: %d\n", __func__, err); goto destroy_ept; } if (ept && rpdev->ops->announce_create) { err = rpdev->ops->announce_create(rpdev); if (err) { dev_err(dev, "failed to announce creation\n"); goto remove_rpdev; } } return 0; remove_rpdev: if (rpdrv->remove) rpdrv->remove(rpdev); destroy_ept: if (ept) rpmsg_destroy_ept(ept); out: return err; } static void rpmsg_dev_remove(struct device *dev) { struct rpmsg_device *rpdev = to_rpmsg_device(dev); struct rpmsg_driver *rpdrv = to_rpmsg_driver(rpdev->dev.driver); if (rpdev->ops->announce_destroy) rpdev->ops->announce_destroy(rpdev); if (rpdrv->remove) rpdrv->remove(rpdev); dev_pm_domain_detach(dev, true); if (rpdev->ept) rpmsg_destroy_ept(rpdev->ept); } static struct bus_type rpmsg_bus = { .name = "rpmsg", .match = rpmsg_dev_match, .dev_groups = rpmsg_dev_groups, .uevent = rpmsg_uevent, .probe = rpmsg_dev_probe, .remove = rpmsg_dev_remove, }; /* * A helper for registering rpmsg device with driver override and name. * Drivers should not be using it, but instead rpmsg_register_device(). */ int rpmsg_register_device_override(struct rpmsg_device *rpdev, const char *driver_override) { struct device *dev = &rpdev->dev; int ret; if (driver_override) strscpy_pad(rpdev->id.name, driver_override, RPMSG_NAME_SIZE); dev_set_name(dev, "%s.%s.%d.%d", dev_name(dev->parent), rpdev->id.name, rpdev->src, rpdev->dst); dev->bus = &rpmsg_bus; device_initialize(dev); if (driver_override) { ret = driver_set_override(dev, &rpdev->driver_override, driver_override, strlen(driver_override)); if (ret) { dev_err(dev, "device_set_override failed: %d\n", ret); put_device(dev); return ret; } } ret = device_add(dev); if (ret) { dev_err(dev, "device_add failed: %d\n", ret); kfree(rpdev->driver_override); rpdev->driver_override = NULL; put_device(dev); } return ret; } EXPORT_SYMBOL(rpmsg_register_device_override); int rpmsg_register_device(struct rpmsg_device *rpdev) { return rpmsg_register_device_override(rpdev, NULL); } EXPORT_SYMBOL(rpmsg_register_device); /* * find an existing channel using its name + address properties, * and destroy it */ int rpmsg_unregister_device(struct device *parent, struct rpmsg_channel_info *chinfo) { struct device *dev; dev = rpmsg_find_device(parent, chinfo); if (!dev) return -EINVAL; device_unregister(dev); put_device(dev); return 0; } EXPORT_SYMBOL(rpmsg_unregister_device); /** * __register_rpmsg_driver() - register an rpmsg driver with the rpmsg bus * @rpdrv: pointer to a struct rpmsg_driver * @owner: owning module/driver * * Return: 0 on success, and an appropriate error value on failure. */ int __register_rpmsg_driver(struct rpmsg_driver *rpdrv, struct module *owner) { rpdrv->drv.bus = &rpmsg_bus; rpdrv->drv.owner = owner; return driver_register(&rpdrv->drv); } EXPORT_SYMBOL(__register_rpmsg_driver); /** * unregister_rpmsg_driver() - unregister an rpmsg driver from the rpmsg bus * @rpdrv: pointer to a struct rpmsg_driver * * Return: 0 on success, and an appropriate error value on failure. */ void unregister_rpmsg_driver(struct rpmsg_driver *rpdrv) { driver_unregister(&rpdrv->drv); } EXPORT_SYMBOL(unregister_rpmsg_driver); static int __init rpmsg_init(void) { int ret; rpmsg_class = class_create("rpmsg"); if (IS_ERR(rpmsg_class)) { pr_err("failed to create rpmsg class\n"); return PTR_ERR(rpmsg_class); } ret = bus_register(&rpmsg_bus); if (ret) { pr_err("failed to register rpmsg bus: %d\n", ret); class_destroy(rpmsg_class); } return ret; } postcore_initcall(rpmsg_init); static void __exit rpmsg_fini(void) { bus_unregister(&rpmsg_bus); class_destroy(rpmsg_class); } module_exit(rpmsg_fini); MODULE_DESCRIPTION("remote processor messaging bus"); MODULE_LICENSE("GPL v2");
linux-master
drivers/rpmsg/rpmsg_core.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (c) 2015, Sony Mobile Communications AB. * Copyright (c) 2012-2013, The Linux Foundation. All rights reserved. */ #include <linux/interrupt.h> #include <linux/io.h> #include <linux/mailbox_client.h> #include <linux/mfd/syscon.h> #include <linux/module.h> #include <linux/of_irq.h> #include <linux/of_platform.h> #include <linux/platform_device.h> #include <linux/regmap.h> #include <linux/sched.h> #include <linux/sizes.h> #include <linux/slab.h> #include <linux/soc/qcom/smem.h> #include <linux/wait.h> #include <linux/rpmsg.h> #include <linux/rpmsg/qcom_smd.h> #include "rpmsg_internal.h" /* * The Qualcomm Shared Memory communication solution provides point-to-point * channels for clients to send and receive streaming or packet based data. * * Each channel consists of a control item (channel info) and a ring buffer * pair. The channel info carry information related to channel state, flow * control and the offsets within the ring buffer. * * All allocated channels are listed in an allocation table, identifying the * pair of items by name, type and remote processor. * * Upon creating a new channel the remote processor allocates channel info and * ring buffer items from the smem heap and populate the allocation table. An * interrupt is sent to the other end of the channel and a scan for new * channels should be done. A channel never goes away, it will only change * state. * * The remote processor signals it intent for bring up the communication * channel by setting the state of its end of the channel to "opening" and * sends out an interrupt. We detect this change and register a smd device to * consume the channel. Upon finding a consumer we finish the handshake and the * channel is up. * * Upon closing a channel, the remote processor will update the state of its * end of the channel and signal us, we will then unregister any attached * device and close our end of the channel. * * Devices attached to a channel can use the qcom_smd_send function to push * data to the channel, this is done by copying the data into the tx ring * buffer, updating the pointers in the channel info and signaling the remote * processor. * * The remote processor does the equivalent when it transfer data and upon * receiving the interrupt we check the channel info for new data and delivers * this to the attached device. If the device is not ready to receive the data * we leave it in the ring buffer for now. */ struct smd_channel_info; struct smd_channel_info_pair; struct smd_channel_info_word; struct smd_channel_info_word_pair; static const struct rpmsg_endpoint_ops qcom_smd_endpoint_ops; #define SMD_ALLOC_TBL_COUNT 2 #define SMD_ALLOC_TBL_SIZE 64 /* * This lists the various smem heap items relevant for the allocation table and * smd channel entries. */ static const struct { unsigned alloc_tbl_id; unsigned info_base_id; unsigned fifo_base_id; } smem_items[SMD_ALLOC_TBL_COUNT] = { { .alloc_tbl_id = 13, .info_base_id = 14, .fifo_base_id = 338 }, { .alloc_tbl_id = 266, .info_base_id = 138, .fifo_base_id = 202, }, }; /** * struct qcom_smd_edge - representing a remote processor * @dev: device associated with this edge * @name: name of this edge * @of_node: of_node handle for information related to this edge * @edge_id: identifier of this edge * @remote_pid: identifier of remote processor * @irq: interrupt for signals on this edge * @ipc_regmap: regmap handle holding the outgoing ipc register * @ipc_offset: offset within @ipc_regmap of the register for ipc * @ipc_bit: bit in the register at @ipc_offset of @ipc_regmap * @mbox_client: mailbox client handle * @mbox_chan: apcs ipc mailbox channel handle * @channels: list of all channels detected on this edge * @channels_lock: guard for modifications of @channels * @allocated: array of bitmaps representing already allocated channels * @smem_available: last available amount of smem triggering a channel scan * @new_channel_event: wait queue for new channel events * @scan_work: work item for discovering new channels * @state_work: work item for edge state changes */ struct qcom_smd_edge { struct device dev; const char *name; struct device_node *of_node; unsigned edge_id; unsigned remote_pid; int irq; struct regmap *ipc_regmap; int ipc_offset; int ipc_bit; struct mbox_client mbox_client; struct mbox_chan *mbox_chan; struct list_head channels; spinlock_t channels_lock; DECLARE_BITMAP(allocated[SMD_ALLOC_TBL_COUNT], SMD_ALLOC_TBL_SIZE); unsigned smem_available; wait_queue_head_t new_channel_event; struct work_struct scan_work; struct work_struct state_work; }; /* * SMD channel states. */ enum smd_channel_state { SMD_CHANNEL_CLOSED, SMD_CHANNEL_OPENING, SMD_CHANNEL_OPENED, SMD_CHANNEL_FLUSHING, SMD_CHANNEL_CLOSING, SMD_CHANNEL_RESET, SMD_CHANNEL_RESET_OPENING }; struct qcom_smd_device { struct rpmsg_device rpdev; struct qcom_smd_edge *edge; }; struct qcom_smd_endpoint { struct rpmsg_endpoint ept; struct qcom_smd_channel *qsch; }; #define to_smd_device(r) container_of(r, struct qcom_smd_device, rpdev) #define to_smd_edge(d) container_of(d, struct qcom_smd_edge, dev) #define to_smd_endpoint(e) container_of(e, struct qcom_smd_endpoint, ept) /** * struct qcom_smd_channel - smd channel struct * @edge: qcom_smd_edge this channel is living on * @qsept: reference to a associated smd endpoint * @registered: flag to indicate if the channel is registered * @name: name of the channel * @state: local state of the channel * @remote_state: remote state of the channel * @state_change_event: state change event * @info: byte aligned outgoing/incoming channel info * @info_word: word aligned outgoing/incoming channel info * @tx_lock: lock to make writes to the channel mutually exclusive * @fblockread_event: wakeup event tied to tx fBLOCKREADINTR * @tx_fifo: pointer to the outgoing ring buffer * @rx_fifo: pointer to the incoming ring buffer * @fifo_size: size of each ring buffer * @bounce_buffer: bounce buffer for reading wrapped packets * @cb: callback function registered for this channel * @recv_lock: guard for rx info modifications and cb pointer * @pkt_size: size of the currently handled packet * @drvdata: driver private data * @list: lite entry for @channels in qcom_smd_edge */ struct qcom_smd_channel { struct qcom_smd_edge *edge; struct qcom_smd_endpoint *qsept; bool registered; char *name; enum smd_channel_state state; enum smd_channel_state remote_state; wait_queue_head_t state_change_event; struct smd_channel_info_pair *info; struct smd_channel_info_word_pair *info_word; spinlock_t tx_lock; wait_queue_head_t fblockread_event; void *tx_fifo; void *rx_fifo; int fifo_size; void *bounce_buffer; spinlock_t recv_lock; int pkt_size; void *drvdata; struct list_head list; }; /* * Format of the smd_info smem items, for byte aligned channels. */ struct smd_channel_info { __le32 state; u8 fDSR; u8 fCTS; u8 fCD; u8 fRI; u8 fHEAD; u8 fTAIL; u8 fSTATE; u8 fBLOCKREADINTR; __le32 tail; __le32 head; }; struct smd_channel_info_pair { struct smd_channel_info tx; struct smd_channel_info rx; }; /* * Format of the smd_info smem items, for word aligned channels. */ struct smd_channel_info_word { __le32 state; __le32 fDSR; __le32 fCTS; __le32 fCD; __le32 fRI; __le32 fHEAD; __le32 fTAIL; __le32 fSTATE; __le32 fBLOCKREADINTR; __le32 tail; __le32 head; }; struct smd_channel_info_word_pair { struct smd_channel_info_word tx; struct smd_channel_info_word rx; }; #define GET_RX_CHANNEL_FLAG(channel, param) \ ({ \ BUILD_BUG_ON(sizeof(channel->info->rx.param) != sizeof(u8)); \ channel->info_word ? \ le32_to_cpu(channel->info_word->rx.param) : \ channel->info->rx.param; \ }) #define GET_RX_CHANNEL_INFO(channel, param) \ ({ \ BUILD_BUG_ON(sizeof(channel->info->rx.param) != sizeof(u32)); \ le32_to_cpu(channel->info_word ? \ channel->info_word->rx.param : \ channel->info->rx.param); \ }) #define SET_RX_CHANNEL_FLAG(channel, param, value) \ ({ \ BUILD_BUG_ON(sizeof(channel->info->rx.param) != sizeof(u8)); \ if (channel->info_word) \ channel->info_word->rx.param = cpu_to_le32(value); \ else \ channel->info->rx.param = value; \ }) #define SET_RX_CHANNEL_INFO(channel, param, value) \ ({ \ BUILD_BUG_ON(sizeof(channel->info->rx.param) != sizeof(u32)); \ if (channel->info_word) \ channel->info_word->rx.param = cpu_to_le32(value); \ else \ channel->info->rx.param = cpu_to_le32(value); \ }) #define GET_TX_CHANNEL_FLAG(channel, param) \ ({ \ BUILD_BUG_ON(sizeof(channel->info->tx.param) != sizeof(u8)); \ channel->info_word ? \ le32_to_cpu(channel->info_word->tx.param) : \ channel->info->tx.param; \ }) #define GET_TX_CHANNEL_INFO(channel, param) \ ({ \ BUILD_BUG_ON(sizeof(channel->info->tx.param) != sizeof(u32)); \ le32_to_cpu(channel->info_word ? \ channel->info_word->tx.param : \ channel->info->tx.param); \ }) #define SET_TX_CHANNEL_FLAG(channel, param, value) \ ({ \ BUILD_BUG_ON(sizeof(channel->info->tx.param) != sizeof(u8)); \ if (channel->info_word) \ channel->info_word->tx.param = cpu_to_le32(value); \ else \ channel->info->tx.param = value; \ }) #define SET_TX_CHANNEL_INFO(channel, param, value) \ ({ \ BUILD_BUG_ON(sizeof(channel->info->tx.param) != sizeof(u32)); \ if (channel->info_word) \ channel->info_word->tx.param = cpu_to_le32(value); \ else \ channel->info->tx.param = cpu_to_le32(value); \ }) /** * struct qcom_smd_alloc_entry - channel allocation entry * @name: channel name * @cid: channel index * @flags: channel flags and edge id * @ref_count: reference count of the channel */ struct qcom_smd_alloc_entry { u8 name[20]; __le32 cid; __le32 flags; __le32 ref_count; } __packed; #define SMD_CHANNEL_FLAGS_EDGE_MASK 0xff #define SMD_CHANNEL_FLAGS_STREAM BIT(8) #define SMD_CHANNEL_FLAGS_PACKET BIT(9) /* * Each smd packet contains a 20 byte header, with the first 4 being the length * of the packet. */ #define SMD_PACKET_HEADER_LEN 20 /* * Signal the remote processor associated with 'channel'. */ static void qcom_smd_signal_channel(struct qcom_smd_channel *channel) { struct qcom_smd_edge *edge = channel->edge; if (edge->mbox_chan) { /* * We can ignore a failing mbox_send_message() as the only * possible cause is that the FIFO in the framework is full of * other writes to the same bit. */ mbox_send_message(edge->mbox_chan, NULL); mbox_client_txdone(edge->mbox_chan, 0); } else { regmap_write(edge->ipc_regmap, edge->ipc_offset, BIT(edge->ipc_bit)); } } /* * Initialize the tx channel info */ static void qcom_smd_channel_reset(struct qcom_smd_channel *channel) { SET_TX_CHANNEL_INFO(channel, state, SMD_CHANNEL_CLOSED); SET_TX_CHANNEL_FLAG(channel, fDSR, 0); SET_TX_CHANNEL_FLAG(channel, fCTS, 0); SET_TX_CHANNEL_FLAG(channel, fCD, 0); SET_TX_CHANNEL_FLAG(channel, fRI, 0); SET_TX_CHANNEL_FLAG(channel, fHEAD, 0); SET_TX_CHANNEL_FLAG(channel, fTAIL, 0); SET_TX_CHANNEL_FLAG(channel, fSTATE, 1); SET_TX_CHANNEL_FLAG(channel, fBLOCKREADINTR, 1); SET_TX_CHANNEL_INFO(channel, head, 0); SET_RX_CHANNEL_INFO(channel, tail, 0); qcom_smd_signal_channel(channel); channel->state = SMD_CHANNEL_CLOSED; channel->pkt_size = 0; } /* * Set the callback for a channel, with appropriate locking */ static void qcom_smd_channel_set_callback(struct qcom_smd_channel *channel, rpmsg_rx_cb_t cb) { struct rpmsg_endpoint *ept = &channel->qsept->ept; unsigned long flags; spin_lock_irqsave(&channel->recv_lock, flags); ept->cb = cb; spin_unlock_irqrestore(&channel->recv_lock, flags); }; /* * Calculate the amount of data available in the rx fifo */ static size_t qcom_smd_channel_get_rx_avail(struct qcom_smd_channel *channel) { unsigned head; unsigned tail; head = GET_RX_CHANNEL_INFO(channel, head); tail = GET_RX_CHANNEL_INFO(channel, tail); return (head - tail) & (channel->fifo_size - 1); } /* * Set tx channel state and inform the remote processor */ static void qcom_smd_channel_set_state(struct qcom_smd_channel *channel, int state) { struct qcom_smd_edge *edge = channel->edge; bool is_open = state == SMD_CHANNEL_OPENED; if (channel->state == state) return; dev_dbg(&edge->dev, "set_state(%s, %d)\n", channel->name, state); SET_TX_CHANNEL_FLAG(channel, fDSR, is_open); SET_TX_CHANNEL_FLAG(channel, fCTS, is_open); SET_TX_CHANNEL_FLAG(channel, fCD, is_open); SET_TX_CHANNEL_INFO(channel, state, state); SET_TX_CHANNEL_FLAG(channel, fSTATE, 1); channel->state = state; qcom_smd_signal_channel(channel); } /* * Copy count bytes of data using 32bit accesses, if that's required. */ static void smd_copy_to_fifo(void __iomem *dst, const void *src, size_t count, bool word_aligned) { if (word_aligned) { __iowrite32_copy(dst, src, count / sizeof(u32)); } else { memcpy_toio(dst, src, count); } } /* * Copy count bytes of data using 32bit accesses, if that is required. */ static void smd_copy_from_fifo(void *dst, const void __iomem *src, size_t count, bool word_aligned) { if (word_aligned) { __ioread32_copy(dst, src, count / sizeof(u32)); } else { memcpy_fromio(dst, src, count); } } /* * Read count bytes of data from the rx fifo into buf, but don't advance the * tail. */ static size_t qcom_smd_channel_peek(struct qcom_smd_channel *channel, void *buf, size_t count) { bool word_aligned; unsigned tail; size_t len; word_aligned = channel->info_word; tail = GET_RX_CHANNEL_INFO(channel, tail); len = min_t(size_t, count, channel->fifo_size - tail); if (len) { smd_copy_from_fifo(buf, channel->rx_fifo + tail, len, word_aligned); } if (len != count) { smd_copy_from_fifo(buf + len, channel->rx_fifo, count - len, word_aligned); } return count; } /* * Advance the rx tail by count bytes. */ static void qcom_smd_channel_advance(struct qcom_smd_channel *channel, size_t count) { unsigned tail; tail = GET_RX_CHANNEL_INFO(channel, tail); tail += count; tail &= (channel->fifo_size - 1); SET_RX_CHANNEL_INFO(channel, tail, tail); } /* * Read out a single packet from the rx fifo and deliver it to the device */ static int qcom_smd_channel_recv_single(struct qcom_smd_channel *channel) { struct rpmsg_endpoint *ept = &channel->qsept->ept; unsigned tail; size_t len; void *ptr; int ret; tail = GET_RX_CHANNEL_INFO(channel, tail); /* Use bounce buffer if the data wraps */ if (tail + channel->pkt_size >= channel->fifo_size) { ptr = channel->bounce_buffer; len = qcom_smd_channel_peek(channel, ptr, channel->pkt_size); } else { ptr = channel->rx_fifo + tail; len = channel->pkt_size; } ret = ept->cb(ept->rpdev, ptr, len, ept->priv, RPMSG_ADDR_ANY); if (ret < 0) return ret; /* Only forward the tail if the client consumed the data */ qcom_smd_channel_advance(channel, len); channel->pkt_size = 0; return 0; } /* * Per channel interrupt handling */ static bool qcom_smd_channel_intr(struct qcom_smd_channel *channel) { bool need_state_scan = false; int remote_state; __le32 pktlen; int avail; int ret; /* Handle state changes */ remote_state = GET_RX_CHANNEL_INFO(channel, state); if (remote_state != channel->remote_state) { channel->remote_state = remote_state; need_state_scan = true; wake_up_interruptible_all(&channel->state_change_event); } /* Indicate that we have seen any state change */ SET_RX_CHANNEL_FLAG(channel, fSTATE, 0); /* Signal waiting qcom_smd_send() about the interrupt */ if (!GET_TX_CHANNEL_FLAG(channel, fBLOCKREADINTR)) wake_up_interruptible_all(&channel->fblockread_event); /* Don't consume any data until we've opened the channel */ if (channel->state != SMD_CHANNEL_OPENED) goto out; /* Indicate that we've seen the new data */ SET_RX_CHANNEL_FLAG(channel, fHEAD, 0); /* Consume data */ for (;;) { avail = qcom_smd_channel_get_rx_avail(channel); if (!channel->pkt_size && avail >= SMD_PACKET_HEADER_LEN) { qcom_smd_channel_peek(channel, &pktlen, sizeof(pktlen)); qcom_smd_channel_advance(channel, SMD_PACKET_HEADER_LEN); channel->pkt_size = le32_to_cpu(pktlen); } else if (channel->pkt_size && avail >= channel->pkt_size) { ret = qcom_smd_channel_recv_single(channel); if (ret) break; } else { break; } } /* Indicate that we have seen and updated tail */ SET_RX_CHANNEL_FLAG(channel, fTAIL, 1); /* Signal the remote that we've consumed the data (if requested) */ if (!GET_RX_CHANNEL_FLAG(channel, fBLOCKREADINTR)) { /* Ensure ordering of channel info updates */ wmb(); qcom_smd_signal_channel(channel); } out: return need_state_scan; } /* * The edge interrupts are triggered by the remote processor on state changes, * channel info updates or when new channels are created. */ static irqreturn_t qcom_smd_edge_intr(int irq, void *data) { struct qcom_smd_edge *edge = data; struct qcom_smd_channel *channel; unsigned available; bool kick_scanner = false; bool kick_state = false; /* * Handle state changes or data on each of the channels on this edge */ spin_lock(&edge->channels_lock); list_for_each_entry(channel, &edge->channels, list) { spin_lock(&channel->recv_lock); kick_state |= qcom_smd_channel_intr(channel); spin_unlock(&channel->recv_lock); } spin_unlock(&edge->channels_lock); /* * Creating a new channel requires allocating an smem entry, so we only * have to scan if the amount of available space in smem have changed * since last scan. */ available = qcom_smem_get_free_space(edge->remote_pid); if (available != edge->smem_available) { edge->smem_available = available; kick_scanner = true; } if (kick_scanner) schedule_work(&edge->scan_work); if (kick_state) schedule_work(&edge->state_work); return IRQ_HANDLED; } /* * Calculate how much space is available in the tx fifo. */ static size_t qcom_smd_get_tx_avail(struct qcom_smd_channel *channel) { unsigned head; unsigned tail; unsigned mask = channel->fifo_size - 1; head = GET_TX_CHANNEL_INFO(channel, head); tail = GET_TX_CHANNEL_INFO(channel, tail); return mask - ((head - tail) & mask); } /* * Write count bytes of data into channel, possibly wrapping in the ring buffer */ static int qcom_smd_write_fifo(struct qcom_smd_channel *channel, const void *data, size_t count) { bool word_aligned; unsigned head; size_t len; word_aligned = channel->info_word; head = GET_TX_CHANNEL_INFO(channel, head); len = min_t(size_t, count, channel->fifo_size - head); if (len) { smd_copy_to_fifo(channel->tx_fifo + head, data, len, word_aligned); } if (len != count) { smd_copy_to_fifo(channel->tx_fifo, data + len, count - len, word_aligned); } head += count; head &= (channel->fifo_size - 1); SET_TX_CHANNEL_INFO(channel, head, head); return count; } /** * __qcom_smd_send - write data to smd channel * @channel: channel handle * @data: buffer of data to write * @len: number of bytes to write * @wait: flag to indicate if write can wait * * This is a blocking write of len bytes into the channel's tx ring buffer and * signal the remote end. It will sleep until there is enough space available * in the tx buffer, utilizing the fBLOCKREADINTR signaling mechanism to avoid * polling. */ static int __qcom_smd_send(struct qcom_smd_channel *channel, const void *data, int len, bool wait) { __le32 hdr[5] = { cpu_to_le32(len), }; int tlen = sizeof(hdr) + len; unsigned long flags; int ret; /* Word aligned channels only accept word size aligned data */ if (channel->info_word && len % 4) return -EINVAL; /* Reject packets that are too big */ if (tlen >= channel->fifo_size) return -EINVAL; /* Highlight the fact that if we enter the loop below we might sleep */ if (wait) might_sleep(); spin_lock_irqsave(&channel->tx_lock, flags); while (qcom_smd_get_tx_avail(channel) < tlen && channel->state == SMD_CHANNEL_OPENED) { if (!wait) { ret = -EAGAIN; goto out_unlock; } SET_TX_CHANNEL_FLAG(channel, fBLOCKREADINTR, 0); /* Wait without holding the tx_lock */ spin_unlock_irqrestore(&channel->tx_lock, flags); ret = wait_event_interruptible(channel->fblockread_event, qcom_smd_get_tx_avail(channel) >= tlen || channel->state != SMD_CHANNEL_OPENED); if (ret) return ret; spin_lock_irqsave(&channel->tx_lock, flags); SET_TX_CHANNEL_FLAG(channel, fBLOCKREADINTR, 1); } /* Fail if the channel was closed */ if (channel->state != SMD_CHANNEL_OPENED) { ret = -EPIPE; goto out_unlock; } SET_TX_CHANNEL_FLAG(channel, fTAIL, 0); qcom_smd_write_fifo(channel, hdr, sizeof(hdr)); qcom_smd_write_fifo(channel, data, len); SET_TX_CHANNEL_FLAG(channel, fHEAD, 1); /* Ensure ordering of channel info updates */ wmb(); qcom_smd_signal_channel(channel); out_unlock: spin_unlock_irqrestore(&channel->tx_lock, flags); return ret; } /* * Helper for opening a channel */ static int qcom_smd_channel_open(struct qcom_smd_channel *channel, rpmsg_rx_cb_t cb) { struct qcom_smd_edge *edge = channel->edge; size_t bb_size; int ret; /* * Packets are maximum 4k, but reduce if the fifo is smaller */ bb_size = min(channel->fifo_size, SZ_4K); channel->bounce_buffer = kmalloc(bb_size, GFP_KERNEL); if (!channel->bounce_buffer) return -ENOMEM; qcom_smd_channel_set_callback(channel, cb); qcom_smd_channel_set_state(channel, SMD_CHANNEL_OPENING); /* Wait for remote to enter opening or opened */ ret = wait_event_interruptible_timeout(channel->state_change_event, channel->remote_state == SMD_CHANNEL_OPENING || channel->remote_state == SMD_CHANNEL_OPENED, HZ); if (!ret) { dev_err(&edge->dev, "remote side did not enter opening state\n"); goto out_close_timeout; } qcom_smd_channel_set_state(channel, SMD_CHANNEL_OPENED); /* Wait for remote to enter opened */ ret = wait_event_interruptible_timeout(channel->state_change_event, channel->remote_state == SMD_CHANNEL_OPENED, HZ); if (!ret) { dev_err(&edge->dev, "remote side did not enter open state\n"); goto out_close_timeout; } return 0; out_close_timeout: qcom_smd_channel_set_state(channel, SMD_CHANNEL_CLOSED); return -ETIMEDOUT; } /* * Helper for closing and resetting a channel */ static void qcom_smd_channel_close(struct qcom_smd_channel *channel) { qcom_smd_channel_set_callback(channel, NULL); kfree(channel->bounce_buffer); channel->bounce_buffer = NULL; qcom_smd_channel_set_state(channel, SMD_CHANNEL_CLOSED); qcom_smd_channel_reset(channel); } static struct qcom_smd_channel * qcom_smd_find_channel(struct qcom_smd_edge *edge, const char *name) { struct qcom_smd_channel *channel; struct qcom_smd_channel *ret = NULL; unsigned long flags; spin_lock_irqsave(&edge->channels_lock, flags); list_for_each_entry(channel, &edge->channels, list) { if (!strcmp(channel->name, name)) { ret = channel; break; } } spin_unlock_irqrestore(&edge->channels_lock, flags); return ret; } static void __ept_release(struct kref *kref) { struct rpmsg_endpoint *ept = container_of(kref, struct rpmsg_endpoint, refcount); kfree(to_smd_endpoint(ept)); } static struct rpmsg_endpoint *qcom_smd_create_ept(struct rpmsg_device *rpdev, rpmsg_rx_cb_t cb, void *priv, struct rpmsg_channel_info chinfo) { struct qcom_smd_endpoint *qsept; struct qcom_smd_channel *channel; struct qcom_smd_device *qsdev = to_smd_device(rpdev); struct qcom_smd_edge *edge = qsdev->edge; struct rpmsg_endpoint *ept; const char *name = chinfo.name; int ret; /* Wait up to HZ for the channel to appear */ ret = wait_event_interruptible_timeout(edge->new_channel_event, (channel = qcom_smd_find_channel(edge, name)) != NULL, HZ); if (!ret) return NULL; if (channel->state != SMD_CHANNEL_CLOSED) { dev_err(&rpdev->dev, "channel %s is busy\n", channel->name); return NULL; } qsept = kzalloc(sizeof(*qsept), GFP_KERNEL); if (!qsept) return NULL; ept = &qsept->ept; kref_init(&ept->refcount); ept->rpdev = rpdev; ept->cb = cb; ept->priv = priv; ept->ops = &qcom_smd_endpoint_ops; channel->qsept = qsept; qsept->qsch = channel; ret = qcom_smd_channel_open(channel, cb); if (ret) goto free_ept; return ept; free_ept: channel->qsept = NULL; kref_put(&ept->refcount, __ept_release); return NULL; } static void qcom_smd_destroy_ept(struct rpmsg_endpoint *ept) { struct qcom_smd_endpoint *qsept = to_smd_endpoint(ept); struct qcom_smd_channel *ch = qsept->qsch; qcom_smd_channel_close(ch); ch->qsept = NULL; kref_put(&ept->refcount, __ept_release); } static int qcom_smd_send(struct rpmsg_endpoint *ept, void *data, int len) { struct qcom_smd_endpoint *qsept = to_smd_endpoint(ept); return __qcom_smd_send(qsept->qsch, data, len, true); } static int qcom_smd_trysend(struct rpmsg_endpoint *ept, void *data, int len) { struct qcom_smd_endpoint *qsept = to_smd_endpoint(ept); return __qcom_smd_send(qsept->qsch, data, len, false); } static int qcom_smd_sendto(struct rpmsg_endpoint *ept, void *data, int len, u32 dst) { struct qcom_smd_endpoint *qsept = to_smd_endpoint(ept); return __qcom_smd_send(qsept->qsch, data, len, true); } static int qcom_smd_trysendto(struct rpmsg_endpoint *ept, void *data, int len, u32 dst) { struct qcom_smd_endpoint *qsept = to_smd_endpoint(ept); return __qcom_smd_send(qsept->qsch, data, len, false); } static __poll_t qcom_smd_poll(struct rpmsg_endpoint *ept, struct file *filp, poll_table *wait) { struct qcom_smd_endpoint *qsept = to_smd_endpoint(ept); struct qcom_smd_channel *channel = qsept->qsch; __poll_t mask = 0; poll_wait(filp, &channel->fblockread_event, wait); if (qcom_smd_get_tx_avail(channel) > 20) mask |= EPOLLOUT | EPOLLWRNORM; return mask; } /* * Finds the device_node for the smd child interested in this channel. */ static struct device_node *qcom_smd_match_channel(struct device_node *edge_node, const char *channel) { struct device_node *child; const char *name; const char *key; int ret; for_each_available_child_of_node(edge_node, child) { key = "qcom,smd-channels"; ret = of_property_read_string(child, key, &name); if (ret) continue; if (strcmp(name, channel) == 0) return child; } return NULL; } static int qcom_smd_announce_create(struct rpmsg_device *rpdev) { struct qcom_smd_endpoint *qept = to_smd_endpoint(rpdev->ept); struct qcom_smd_channel *channel = qept->qsch; unsigned long flags; bool kick_state; spin_lock_irqsave(&channel->recv_lock, flags); kick_state = qcom_smd_channel_intr(channel); spin_unlock_irqrestore(&channel->recv_lock, flags); if (kick_state) schedule_work(&channel->edge->state_work); return 0; } static const struct rpmsg_device_ops qcom_smd_device_ops = { .create_ept = qcom_smd_create_ept, .announce_create = qcom_smd_announce_create, }; static const struct rpmsg_endpoint_ops qcom_smd_endpoint_ops = { .destroy_ept = qcom_smd_destroy_ept, .send = qcom_smd_send, .sendto = qcom_smd_sendto, .trysend = qcom_smd_trysend, .trysendto = qcom_smd_trysendto, .poll = qcom_smd_poll, }; static void qcom_smd_release_device(struct device *dev) { struct rpmsg_device *rpdev = to_rpmsg_device(dev); struct qcom_smd_device *qsdev = to_smd_device(rpdev); kfree(qsdev); } /* * Create a smd client device for channel that is being opened. */ static int qcom_smd_create_device(struct qcom_smd_channel *channel) { struct qcom_smd_device *qsdev; struct rpmsg_device *rpdev; struct qcom_smd_edge *edge = channel->edge; dev_dbg(&edge->dev, "registering '%s'\n", channel->name); qsdev = kzalloc(sizeof(*qsdev), GFP_KERNEL); if (!qsdev) return -ENOMEM; /* Link qsdev to our SMD edge */ qsdev->edge = edge; /* Assign callbacks for rpmsg_device */ qsdev->rpdev.ops = &qcom_smd_device_ops; /* Assign public information to the rpmsg_device */ rpdev = &qsdev->rpdev; strscpy_pad(rpdev->id.name, channel->name, RPMSG_NAME_SIZE); rpdev->src = RPMSG_ADDR_ANY; rpdev->dst = RPMSG_ADDR_ANY; rpdev->dev.of_node = qcom_smd_match_channel(edge->of_node, channel->name); rpdev->dev.parent = &edge->dev; rpdev->dev.release = qcom_smd_release_device; return rpmsg_register_device(rpdev); } static int qcom_smd_create_chrdev(struct qcom_smd_edge *edge) { struct qcom_smd_device *qsdev; qsdev = kzalloc(sizeof(*qsdev), GFP_KERNEL); if (!qsdev) return -ENOMEM; qsdev->edge = edge; qsdev->rpdev.ops = &qcom_smd_device_ops; qsdev->rpdev.dev.parent = &edge->dev; qsdev->rpdev.dev.release = qcom_smd_release_device; return rpmsg_ctrldev_register_device(&qsdev->rpdev); } /* * Allocate the qcom_smd_channel object for a newly found smd channel, * retrieving and validating the smem items involved. */ static struct qcom_smd_channel *qcom_smd_create_channel(struct qcom_smd_edge *edge, unsigned smem_info_item, unsigned smem_fifo_item, char *name) { struct qcom_smd_channel *channel; size_t fifo_size; size_t info_size; void *fifo_base; void *info; int ret; channel = kzalloc(sizeof(*channel), GFP_KERNEL); if (!channel) return ERR_PTR(-ENOMEM); channel->edge = edge; channel->name = kstrdup(name, GFP_KERNEL); if (!channel->name) { ret = -ENOMEM; goto free_channel; } spin_lock_init(&channel->tx_lock); spin_lock_init(&channel->recv_lock); init_waitqueue_head(&channel->fblockread_event); init_waitqueue_head(&channel->state_change_event); info = qcom_smem_get(edge->remote_pid, smem_info_item, &info_size); if (IS_ERR(info)) { ret = PTR_ERR(info); goto free_name_and_channel; } /* * Use the size of the item to figure out which channel info struct to * use. */ if (info_size == 2 * sizeof(struct smd_channel_info_word)) { channel->info_word = info; } else if (info_size == 2 * sizeof(struct smd_channel_info)) { channel->info = info; } else { dev_err(&edge->dev, "channel info of size %zu not supported\n", info_size); ret = -EINVAL; goto free_name_and_channel; } fifo_base = qcom_smem_get(edge->remote_pid, smem_fifo_item, &fifo_size); if (IS_ERR(fifo_base)) { ret = PTR_ERR(fifo_base); goto free_name_and_channel; } /* The channel consist of a rx and tx fifo of equal size */ fifo_size /= 2; dev_dbg(&edge->dev, "new channel '%s' info-size: %zu fifo-size: %zu\n", name, info_size, fifo_size); channel->tx_fifo = fifo_base; channel->rx_fifo = fifo_base + fifo_size; channel->fifo_size = fifo_size; qcom_smd_channel_reset(channel); return channel; free_name_and_channel: kfree(channel->name); free_channel: kfree(channel); return ERR_PTR(ret); } /* * Scans the allocation table for any newly allocated channels, calls * qcom_smd_create_channel() to create representations of these and add * them to the edge's list of channels. */ static void qcom_channel_scan_worker(struct work_struct *work) { struct qcom_smd_edge *edge = container_of(work, struct qcom_smd_edge, scan_work); struct qcom_smd_alloc_entry *alloc_tbl; struct qcom_smd_alloc_entry *entry; struct qcom_smd_channel *channel; unsigned long flags; unsigned fifo_id; unsigned info_id; int tbl; int i; u32 eflags, cid; for (tbl = 0; tbl < SMD_ALLOC_TBL_COUNT; tbl++) { alloc_tbl = qcom_smem_get(edge->remote_pid, smem_items[tbl].alloc_tbl_id, NULL); if (IS_ERR(alloc_tbl)) continue; for (i = 0; i < SMD_ALLOC_TBL_SIZE; i++) { entry = &alloc_tbl[i]; eflags = le32_to_cpu(entry->flags); if (test_bit(i, edge->allocated[tbl])) continue; if (entry->ref_count == 0) continue; if (!entry->name[0]) continue; if (!(eflags & SMD_CHANNEL_FLAGS_PACKET)) continue; if ((eflags & SMD_CHANNEL_FLAGS_EDGE_MASK) != edge->edge_id) continue; cid = le32_to_cpu(entry->cid); info_id = smem_items[tbl].info_base_id + cid; fifo_id = smem_items[tbl].fifo_base_id + cid; channel = qcom_smd_create_channel(edge, info_id, fifo_id, entry->name); if (IS_ERR(channel)) continue; spin_lock_irqsave(&edge->channels_lock, flags); list_add(&channel->list, &edge->channels); spin_unlock_irqrestore(&edge->channels_lock, flags); dev_dbg(&edge->dev, "new channel found: '%s'\n", channel->name); set_bit(i, edge->allocated[tbl]); wake_up_interruptible_all(&edge->new_channel_event); } } schedule_work(&edge->state_work); } /* * This per edge worker scans smem for any new channels and register these. It * then scans all registered channels for state changes that should be handled * by creating or destroying smd client devices for the registered channels. * * LOCKING: edge->channels_lock only needs to cover the list operations, as the * worker is killed before any channels are deallocated */ static void qcom_channel_state_worker(struct work_struct *work) { struct qcom_smd_channel *channel; struct qcom_smd_edge *edge = container_of(work, struct qcom_smd_edge, state_work); struct rpmsg_channel_info chinfo; unsigned remote_state; unsigned long flags; /* * Register a device for any closed channel where the remote processor * is showing interest in opening the channel. */ spin_lock_irqsave(&edge->channels_lock, flags); list_for_each_entry(channel, &edge->channels, list) { if (channel->state != SMD_CHANNEL_CLOSED) continue; /* * Always open rpm_requests, even when already opened which is * required on some SoCs like msm8953. */ remote_state = GET_RX_CHANNEL_INFO(channel, state); if (remote_state != SMD_CHANNEL_OPENING && remote_state != SMD_CHANNEL_OPENED && strcmp(channel->name, "rpm_requests")) continue; if (channel->registered) continue; spin_unlock_irqrestore(&edge->channels_lock, flags); qcom_smd_create_device(channel); spin_lock_irqsave(&edge->channels_lock, flags); channel->registered = true; } /* * Unregister the device for any channel that is opened where the * remote processor is closing the channel. */ list_for_each_entry(channel, &edge->channels, list) { if (channel->state != SMD_CHANNEL_OPENING && channel->state != SMD_CHANNEL_OPENED) continue; remote_state = GET_RX_CHANNEL_INFO(channel, state); if (remote_state == SMD_CHANNEL_OPENING || remote_state == SMD_CHANNEL_OPENED) continue; spin_unlock_irqrestore(&edge->channels_lock, flags); strscpy_pad(chinfo.name, channel->name, sizeof(chinfo.name)); chinfo.src = RPMSG_ADDR_ANY; chinfo.dst = RPMSG_ADDR_ANY; rpmsg_unregister_device(&edge->dev, &chinfo); channel->registered = false; spin_lock_irqsave(&edge->channels_lock, flags); } spin_unlock_irqrestore(&edge->channels_lock, flags); } /* * Parses an of_node describing an edge. */ static int qcom_smd_parse_edge(struct device *dev, struct device_node *node, struct qcom_smd_edge *edge) { struct device_node *syscon_np; const char *key; int irq; int ret; INIT_LIST_HEAD(&edge->channels); spin_lock_init(&edge->channels_lock); INIT_WORK(&edge->scan_work, qcom_channel_scan_worker); INIT_WORK(&edge->state_work, qcom_channel_state_worker); edge->of_node = of_node_get(node); key = "qcom,smd-edge"; ret = of_property_read_u32(node, key, &edge->edge_id); if (ret) { dev_err(dev, "edge missing %s property\n", key); goto put_node; } edge->remote_pid = QCOM_SMEM_HOST_ANY; key = "qcom,remote-pid"; of_property_read_u32(node, key, &edge->remote_pid); edge->mbox_client.dev = dev; edge->mbox_client.knows_txdone = true; edge->mbox_chan = mbox_request_channel(&edge->mbox_client, 0); if (IS_ERR(edge->mbox_chan)) { if (PTR_ERR(edge->mbox_chan) != -ENODEV) { ret = PTR_ERR(edge->mbox_chan); goto put_node; } edge->mbox_chan = NULL; syscon_np = of_parse_phandle(node, "qcom,ipc", 0); if (!syscon_np) { dev_err(dev, "no qcom,ipc node\n"); ret = -ENODEV; goto put_node; } edge->ipc_regmap = syscon_node_to_regmap(syscon_np); of_node_put(syscon_np); if (IS_ERR(edge->ipc_regmap)) { ret = PTR_ERR(edge->ipc_regmap); goto put_node; } key = "qcom,ipc"; ret = of_property_read_u32_index(node, key, 1, &edge->ipc_offset); if (ret < 0) { dev_err(dev, "no offset in %s\n", key); goto put_node; } ret = of_property_read_u32_index(node, key, 2, &edge->ipc_bit); if (ret < 0) { dev_err(dev, "no bit in %s\n", key); goto put_node; } } ret = of_property_read_string(node, "label", &edge->name); if (ret < 0) edge->name = node->name; irq = irq_of_parse_and_map(node, 0); if (!irq) { dev_err(dev, "required smd interrupt missing\n"); ret = -EINVAL; goto put_node; } ret = devm_request_irq(dev, irq, qcom_smd_edge_intr, IRQF_TRIGGER_RISING, node->name, edge); if (ret) { dev_err(dev, "failed to request smd irq\n"); goto put_node; } edge->irq = irq; return 0; put_node: of_node_put(node); edge->of_node = NULL; return ret; } /* * Release function for an edge. * Reset the state of each associated channel and free the edge context. */ static void qcom_smd_edge_release(struct device *dev) { struct qcom_smd_channel *channel, *tmp; struct qcom_smd_edge *edge = to_smd_edge(dev); list_for_each_entry_safe(channel, tmp, &edge->channels, list) { list_del(&channel->list); kfree(channel->name); kfree(channel); } kfree(edge); } static ssize_t rpmsg_name_show(struct device *dev, struct device_attribute *attr, char *buf) { struct qcom_smd_edge *edge = to_smd_edge(dev); return sprintf(buf, "%s\n", edge->name); } static DEVICE_ATTR_RO(rpmsg_name); static struct attribute *qcom_smd_edge_attrs[] = { &dev_attr_rpmsg_name.attr, NULL }; ATTRIBUTE_GROUPS(qcom_smd_edge); /** * qcom_smd_register_edge() - register an edge based on an device_node * @parent: parent device for the edge * @node: device_node describing the edge * * Return: an edge reference, or negative ERR_PTR() on failure. */ struct qcom_smd_edge *qcom_smd_register_edge(struct device *parent, struct device_node *node) { struct qcom_smd_edge *edge; int ret; if (!qcom_smem_is_available()) return ERR_PTR(-EPROBE_DEFER); edge = kzalloc(sizeof(*edge), GFP_KERNEL); if (!edge) return ERR_PTR(-ENOMEM); init_waitqueue_head(&edge->new_channel_event); edge->dev.parent = parent; edge->dev.release = qcom_smd_edge_release; edge->dev.of_node = node; edge->dev.groups = qcom_smd_edge_groups; dev_set_name(&edge->dev, "%s:%pOFn", dev_name(parent), node); ret = device_register(&edge->dev); if (ret) { pr_err("failed to register smd edge\n"); put_device(&edge->dev); return ERR_PTR(ret); } ret = qcom_smd_parse_edge(&edge->dev, node, edge); if (ret) { dev_err(&edge->dev, "failed to parse smd edge\n"); goto unregister_dev; } ret = qcom_smd_create_chrdev(edge); if (ret) { dev_err(&edge->dev, "failed to register chrdev for edge\n"); goto unregister_dev; } schedule_work(&edge->scan_work); return edge; unregister_dev: if (!IS_ERR_OR_NULL(edge->mbox_chan)) mbox_free_channel(edge->mbox_chan); device_unregister(&edge->dev); return ERR_PTR(ret); } EXPORT_SYMBOL(qcom_smd_register_edge); static int qcom_smd_remove_device(struct device *dev, void *data) { device_unregister(dev); return 0; } /** * qcom_smd_unregister_edge() - release an edge and its children * @edge: edge reference acquired from qcom_smd_register_edge */ void qcom_smd_unregister_edge(struct qcom_smd_edge *edge) { int ret; disable_irq(edge->irq); cancel_work_sync(&edge->scan_work); cancel_work_sync(&edge->state_work); ret = device_for_each_child(&edge->dev, NULL, qcom_smd_remove_device); if (ret) dev_warn(&edge->dev, "can't remove smd device: %d\n", ret); mbox_free_channel(edge->mbox_chan); device_unregister(&edge->dev); } EXPORT_SYMBOL(qcom_smd_unregister_edge); static int qcom_smd_probe(struct platform_device *pdev) { struct device_node *node; if (!qcom_smem_is_available()) return -EPROBE_DEFER; for_each_available_child_of_node(pdev->dev.of_node, node) qcom_smd_register_edge(&pdev->dev, node); return 0; } static int qcom_smd_remove_edge(struct device *dev, void *data) { struct qcom_smd_edge *edge = to_smd_edge(dev); qcom_smd_unregister_edge(edge); return 0; } /* * Shut down all smd clients by making sure that each edge stops processing * events and scanning for new channels, then call destroy on the devices. */ static void qcom_smd_remove(struct platform_device *pdev) { /* * qcom_smd_remove_edge always returns zero, so there is no need to * check the return value of device_for_each_child. */ device_for_each_child(&pdev->dev, NULL, qcom_smd_remove_edge); } static const struct of_device_id qcom_smd_of_match[] = { { .compatible = "qcom,smd" }, {} }; MODULE_DEVICE_TABLE(of, qcom_smd_of_match); static struct platform_driver qcom_smd_driver = { .probe = qcom_smd_probe, .remove_new = qcom_smd_remove, .driver = { .name = "qcom-smd", .of_match_table = qcom_smd_of_match, }, }; static int __init qcom_smd_init(void) { return platform_driver_register(&qcom_smd_driver); } arch_initcall(qcom_smd_init); static void __exit qcom_smd_exit(void) { platform_driver_unregister(&qcom_smd_driver); } module_exit(qcom_smd_exit); MODULE_AUTHOR("Bjorn Andersson <[email protected]>"); MODULE_DESCRIPTION("Qualcomm Shared Memory Driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/rpmsg/qcom_smd.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (c) 2016, Linaro Ltd */ #include <linux/io.h> #include <linux/module.h> #include <linux/of.h> #include <linux/of_address.h> #include <linux/of_irq.h> #include <linux/interrupt.h> #include <linux/platform_device.h> #include <linux/mailbox_client.h> #include <linux/mfd/syscon.h> #include <linux/slab.h> #include <linux/rpmsg.h> #include <linux/idr.h> #include <linux/circ_buf.h> #include <linux/soc/qcom/smem.h> #include <linux/sizes.h> #include <linux/delay.h> #include <linux/regmap.h> #include <linux/workqueue.h> #include <linux/list.h> #include <linux/rpmsg/qcom_glink.h> #include "qcom_glink_native.h" #define FIFO_FULL_RESERVE 8 #define FIFO_ALIGNMENT 8 #define TX_BLOCKED_CMD_RESERVE 8 /* size of struct read_notif_request */ #define SMEM_GLINK_NATIVE_XPRT_DESCRIPTOR 478 #define SMEM_GLINK_NATIVE_XPRT_FIFO_0 479 #define SMEM_GLINK_NATIVE_XPRT_FIFO_1 480 struct qcom_glink_smem { struct device dev; int irq; struct qcom_glink *glink; struct mbox_client mbox_client; struct mbox_chan *mbox_chan; u32 remote_pid; }; struct glink_smem_pipe { struct qcom_glink_pipe native; __le32 *tail; __le32 *head; void *fifo; struct qcom_glink_smem *smem; }; #define to_smem_pipe(p) container_of(p, struct glink_smem_pipe, native) static size_t glink_smem_rx_avail(struct qcom_glink_pipe *np) { struct glink_smem_pipe *pipe = to_smem_pipe(np); struct qcom_glink_smem *smem = pipe->smem; size_t len; void *fifo; u32 head; u32 tail; if (!pipe->fifo) { fifo = qcom_smem_get(smem->remote_pid, SMEM_GLINK_NATIVE_XPRT_FIFO_1, &len); if (IS_ERR(fifo)) { pr_err("failed to acquire RX fifo handle: %ld\n", PTR_ERR(fifo)); return 0; } pipe->fifo = fifo; pipe->native.length = len; } head = le32_to_cpu(*pipe->head); tail = le32_to_cpu(*pipe->tail); if (head < tail) return pipe->native.length - tail + head; else return head - tail; } static void glink_smem_rx_peek(struct qcom_glink_pipe *np, void *data, unsigned int offset, size_t count) { struct glink_smem_pipe *pipe = to_smem_pipe(np); size_t len; u32 tail; tail = le32_to_cpu(*pipe->tail); tail += offset; if (tail >= pipe->native.length) tail -= pipe->native.length; len = min_t(size_t, count, pipe->native.length - tail); if (len) memcpy_fromio(data, pipe->fifo + tail, len); if (len != count) memcpy_fromio(data + len, pipe->fifo, (count - len)); } static void glink_smem_rx_advance(struct qcom_glink_pipe *np, size_t count) { struct glink_smem_pipe *pipe = to_smem_pipe(np); u32 tail; tail = le32_to_cpu(*pipe->tail); tail += count; if (tail >= pipe->native.length) tail -= pipe->native.length; *pipe->tail = cpu_to_le32(tail); } static size_t glink_smem_tx_avail(struct qcom_glink_pipe *np) { struct glink_smem_pipe *pipe = to_smem_pipe(np); u32 head; u32 tail; u32 avail; head = le32_to_cpu(*pipe->head); tail = le32_to_cpu(*pipe->tail); if (tail <= head) avail = pipe->native.length - head + tail; else avail = tail - head; if (avail < (FIFO_FULL_RESERVE + TX_BLOCKED_CMD_RESERVE)) avail = 0; else avail -= FIFO_FULL_RESERVE + TX_BLOCKED_CMD_RESERVE; return avail; } static unsigned int glink_smem_tx_write_one(struct glink_smem_pipe *pipe, unsigned int head, const void *data, size_t count) { size_t len; len = min_t(size_t, count, pipe->native.length - head); if (len) memcpy(pipe->fifo + head, data, len); if (len != count) memcpy(pipe->fifo, data + len, count - len); head += count; if (head >= pipe->native.length) head -= pipe->native.length; return head; } static void glink_smem_tx_write(struct qcom_glink_pipe *glink_pipe, const void *hdr, size_t hlen, const void *data, size_t dlen) { struct glink_smem_pipe *pipe = to_smem_pipe(glink_pipe); unsigned int head; head = le32_to_cpu(*pipe->head); head = glink_smem_tx_write_one(pipe, head, hdr, hlen); head = glink_smem_tx_write_one(pipe, head, data, dlen); /* Ensure head is always aligned to 8 bytes */ head = ALIGN(head, 8); if (head >= pipe->native.length) head -= pipe->native.length; /* Ensure ordering of fifo and head update */ wmb(); *pipe->head = cpu_to_le32(head); } static void glink_smem_tx_kick(struct qcom_glink_pipe *glink_pipe) { struct glink_smem_pipe *pipe = to_smem_pipe(glink_pipe); struct qcom_glink_smem *smem = pipe->smem; mbox_send_message(smem->mbox_chan, NULL); mbox_client_txdone(smem->mbox_chan, 0); } static irqreturn_t qcom_glink_smem_intr(int irq, void *data) { struct qcom_glink_smem *smem = data; qcom_glink_native_rx(smem->glink); return IRQ_HANDLED; } static void qcom_glink_smem_release(struct device *dev) { struct qcom_glink_smem *smem = container_of(dev, struct qcom_glink_smem, dev); kfree(smem); } struct qcom_glink_smem *qcom_glink_smem_register(struct device *parent, struct device_node *node) { struct glink_smem_pipe *rx_pipe; struct glink_smem_pipe *tx_pipe; struct qcom_glink_smem *smem; struct qcom_glink *glink; struct device *dev; u32 remote_pid; __le32 *descs; size_t size; int ret; smem = kzalloc(sizeof(*smem), GFP_KERNEL); if (!smem) return ERR_PTR(-ENOMEM); dev = &smem->dev; dev->parent = parent; dev->of_node = node; dev->release = qcom_glink_smem_release; dev_set_name(dev, "%s:%pOFn", dev_name(parent->parent), node); ret = device_register(dev); if (ret) { pr_err("failed to register glink edge\n"); put_device(dev); return ERR_PTR(ret); } ret = of_property_read_u32(dev->of_node, "qcom,remote-pid", &remote_pid); if (ret) { dev_err(dev, "failed to parse qcom,remote-pid\n"); goto err_put_dev; } smem->remote_pid = remote_pid; rx_pipe = devm_kzalloc(dev, sizeof(*rx_pipe), GFP_KERNEL); tx_pipe = devm_kzalloc(dev, sizeof(*tx_pipe), GFP_KERNEL); if (!rx_pipe || !tx_pipe) { ret = -ENOMEM; goto err_put_dev; } ret = qcom_smem_alloc(remote_pid, SMEM_GLINK_NATIVE_XPRT_DESCRIPTOR, 32); if (ret && ret != -EEXIST) { dev_err(dev, "failed to allocate glink descriptors\n"); goto err_put_dev; } descs = qcom_smem_get(remote_pid, SMEM_GLINK_NATIVE_XPRT_DESCRIPTOR, &size); if (IS_ERR(descs)) { dev_err(dev, "failed to acquire xprt descriptor\n"); ret = PTR_ERR(descs); goto err_put_dev; } if (size != 32) { dev_err(dev, "glink descriptor of invalid size\n"); ret = -EINVAL; goto err_put_dev; } tx_pipe->tail = &descs[0]; tx_pipe->head = &descs[1]; rx_pipe->tail = &descs[2]; rx_pipe->head = &descs[3]; ret = qcom_smem_alloc(remote_pid, SMEM_GLINK_NATIVE_XPRT_FIFO_0, SZ_16K); if (ret && ret != -EEXIST) { dev_err(dev, "failed to allocate TX fifo\n"); goto err_put_dev; } tx_pipe->fifo = qcom_smem_get(remote_pid, SMEM_GLINK_NATIVE_XPRT_FIFO_0, &tx_pipe->native.length); if (IS_ERR(tx_pipe->fifo)) { dev_err(dev, "failed to acquire TX fifo\n"); ret = PTR_ERR(tx_pipe->fifo); goto err_put_dev; } smem->irq = of_irq_get(smem->dev.of_node, 0); ret = devm_request_irq(&smem->dev, smem->irq, qcom_glink_smem_intr, IRQF_NO_SUSPEND | IRQF_NO_AUTOEN, "glink-smem", smem); if (ret) { dev_err(&smem->dev, "failed to request IRQ\n"); goto err_put_dev; } smem->mbox_client.dev = &smem->dev; smem->mbox_client.knows_txdone = true; smem->mbox_chan = mbox_request_channel(&smem->mbox_client, 0); if (IS_ERR(smem->mbox_chan)) { ret = dev_err_probe(&smem->dev, PTR_ERR(smem->mbox_chan), "failed to acquire IPC channel\n"); goto err_put_dev; } rx_pipe->smem = smem; rx_pipe->native.avail = glink_smem_rx_avail; rx_pipe->native.peek = glink_smem_rx_peek; rx_pipe->native.advance = glink_smem_rx_advance; tx_pipe->smem = smem; tx_pipe->native.avail = glink_smem_tx_avail; tx_pipe->native.write = glink_smem_tx_write; tx_pipe->native.kick = glink_smem_tx_kick; *rx_pipe->tail = 0; *tx_pipe->head = 0; glink = qcom_glink_native_probe(dev, GLINK_FEATURE_INTENT_REUSE, &rx_pipe->native, &tx_pipe->native, false); if (IS_ERR(glink)) { ret = PTR_ERR(glink); goto err_free_mbox; } smem->glink = glink; enable_irq(smem->irq); return smem; err_free_mbox: mbox_free_channel(smem->mbox_chan); err_put_dev: device_unregister(dev); return ERR_PTR(ret); } EXPORT_SYMBOL_GPL(qcom_glink_smem_register); void qcom_glink_smem_unregister(struct qcom_glink_smem *smem) { struct qcom_glink *glink = smem->glink; disable_irq(smem->irq); qcom_glink_native_remove(glink); mbox_free_channel(smem->mbox_chan); device_unregister(&smem->dev); } EXPORT_SYMBOL_GPL(qcom_glink_smem_unregister); MODULE_AUTHOR("Bjorn Andersson <[email protected]>"); MODULE_DESCRIPTION("Qualcomm GLINK SMEM driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/rpmsg/qcom_glink_smem.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2022, STMicroelectronics * Copyright (c) 2016, Linaro Ltd. * Copyright (c) 2012, Michal Simek <[email protected]> * Copyright (c) 2012, PetaLogix * Copyright (c) 2011, Texas Instruments, Inc. * Copyright (c) 2011, Google, Inc. * * Based on rpmsg performance statistics driver by Michal Simek, which in turn * was based on TI & Google OMX rpmsg driver. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/cdev.h> #include <linux/device.h> #include <linux/fs.h> #include <linux/idr.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/rpmsg.h> #include <linux/skbuff.h> #include <linux/slab.h> #include <linux/uaccess.h> #include <uapi/linux/rpmsg.h> #include "rpmsg_char.h" #include "rpmsg_internal.h" #define RPMSG_DEV_MAX (MINORMASK + 1) static dev_t rpmsg_major; static DEFINE_IDA(rpmsg_ctrl_ida); static DEFINE_IDA(rpmsg_minor_ida); #define dev_to_ctrldev(dev) container_of(dev, struct rpmsg_ctrldev, dev) #define cdev_to_ctrldev(i_cdev) container_of(i_cdev, struct rpmsg_ctrldev, cdev) /** * struct rpmsg_ctrldev - control device for instantiating endpoint devices * @rpdev: underlaying rpmsg device * @cdev: cdev for the ctrl device * @dev: device for the ctrl device * @ctrl_lock: serialize the ioctrls. */ struct rpmsg_ctrldev { struct rpmsg_device *rpdev; struct cdev cdev; struct device dev; struct mutex ctrl_lock; }; static int rpmsg_ctrldev_open(struct inode *inode, struct file *filp) { struct rpmsg_ctrldev *ctrldev = cdev_to_ctrldev(inode->i_cdev); get_device(&ctrldev->dev); filp->private_data = ctrldev; return 0; } static int rpmsg_ctrldev_release(struct inode *inode, struct file *filp) { struct rpmsg_ctrldev *ctrldev = cdev_to_ctrldev(inode->i_cdev); put_device(&ctrldev->dev); return 0; } static long rpmsg_ctrldev_ioctl(struct file *fp, unsigned int cmd, unsigned long arg) { struct rpmsg_ctrldev *ctrldev = fp->private_data; void __user *argp = (void __user *)arg; struct rpmsg_endpoint_info eptinfo; struct rpmsg_channel_info chinfo; struct rpmsg_device *rpdev; int ret = 0; if (copy_from_user(&eptinfo, argp, sizeof(eptinfo))) return -EFAULT; memcpy(chinfo.name, eptinfo.name, RPMSG_NAME_SIZE); chinfo.name[RPMSG_NAME_SIZE - 1] = '\0'; chinfo.src = eptinfo.src; chinfo.dst = eptinfo.dst; mutex_lock(&ctrldev->ctrl_lock); switch (cmd) { case RPMSG_CREATE_EPT_IOCTL: ret = rpmsg_chrdev_eptdev_create(ctrldev->rpdev, &ctrldev->dev, chinfo); break; case RPMSG_CREATE_DEV_IOCTL: rpdev = rpmsg_create_channel(ctrldev->rpdev, &chinfo); if (!rpdev) { dev_err(&ctrldev->dev, "failed to create %s channel\n", chinfo.name); ret = -ENXIO; } break; case RPMSG_RELEASE_DEV_IOCTL: ret = rpmsg_release_channel(ctrldev->rpdev, &chinfo); if (ret) dev_err(&ctrldev->dev, "failed to release %s channel (%d)\n", chinfo.name, ret); break; default: ret = -EINVAL; } mutex_unlock(&ctrldev->ctrl_lock); return ret; }; static const struct file_operations rpmsg_ctrldev_fops = { .owner = THIS_MODULE, .open = rpmsg_ctrldev_open, .release = rpmsg_ctrldev_release, .unlocked_ioctl = rpmsg_ctrldev_ioctl, .compat_ioctl = compat_ptr_ioctl, }; static void rpmsg_ctrldev_release_device(struct device *dev) { struct rpmsg_ctrldev *ctrldev = dev_to_ctrldev(dev); ida_simple_remove(&rpmsg_ctrl_ida, dev->id); ida_simple_remove(&rpmsg_minor_ida, MINOR(dev->devt)); kfree(ctrldev); } static int rpmsg_ctrldev_probe(struct rpmsg_device *rpdev) { struct rpmsg_ctrldev *ctrldev; struct device *dev; int ret; ctrldev = kzalloc(sizeof(*ctrldev), GFP_KERNEL); if (!ctrldev) return -ENOMEM; ctrldev->rpdev = rpdev; dev = &ctrldev->dev; device_initialize(dev); dev->parent = &rpdev->dev; dev->class = rpmsg_class; mutex_init(&ctrldev->ctrl_lock); cdev_init(&ctrldev->cdev, &rpmsg_ctrldev_fops); ctrldev->cdev.owner = THIS_MODULE; ret = ida_simple_get(&rpmsg_minor_ida, 0, RPMSG_DEV_MAX, GFP_KERNEL); if (ret < 0) goto free_ctrldev; dev->devt = MKDEV(MAJOR(rpmsg_major), ret); ret = ida_simple_get(&rpmsg_ctrl_ida, 0, 0, GFP_KERNEL); if (ret < 0) goto free_minor_ida; dev->id = ret; dev_set_name(&ctrldev->dev, "rpmsg_ctrl%d", ret); ret = cdev_device_add(&ctrldev->cdev, &ctrldev->dev); if (ret) goto free_ctrl_ida; /* We can now rely on the release function for cleanup */ dev->release = rpmsg_ctrldev_release_device; dev_set_drvdata(&rpdev->dev, ctrldev); return ret; free_ctrl_ida: ida_simple_remove(&rpmsg_ctrl_ida, dev->id); free_minor_ida: ida_simple_remove(&rpmsg_minor_ida, MINOR(dev->devt)); free_ctrldev: put_device(dev); kfree(ctrldev); return ret; } static void rpmsg_ctrldev_remove(struct rpmsg_device *rpdev) { struct rpmsg_ctrldev *ctrldev = dev_get_drvdata(&rpdev->dev); int ret; mutex_lock(&ctrldev->ctrl_lock); /* Destroy all endpoints */ ret = device_for_each_child(&ctrldev->dev, NULL, rpmsg_chrdev_eptdev_destroy); if (ret) dev_warn(&rpdev->dev, "failed to nuke endpoints: %d\n", ret); mutex_unlock(&ctrldev->ctrl_lock); cdev_device_del(&ctrldev->cdev, &ctrldev->dev); put_device(&ctrldev->dev); } static struct rpmsg_driver rpmsg_ctrldev_driver = { .probe = rpmsg_ctrldev_probe, .remove = rpmsg_ctrldev_remove, .drv = { .name = "rpmsg_ctrl", }, }; static int rpmsg_ctrldev_init(void) { int ret; ret = alloc_chrdev_region(&rpmsg_major, 0, RPMSG_DEV_MAX, "rpmsg_ctrl"); if (ret < 0) { pr_err("failed to allocate char dev region\n"); return ret; } ret = register_rpmsg_driver(&rpmsg_ctrldev_driver); if (ret < 0) { pr_err("failed to register rpmsg driver\n"); unregister_chrdev_region(rpmsg_major, RPMSG_DEV_MAX); } return ret; } postcore_initcall(rpmsg_ctrldev_init); static void rpmsg_ctrldev_exit(void) { unregister_rpmsg_driver(&rpmsg_ctrldev_driver); unregister_chrdev_region(rpmsg_major, RPMSG_DEV_MAX); } module_exit(rpmsg_ctrldev_exit); MODULE_DESCRIPTION("rpmsg control interface"); MODULE_ALIAS("rpmsg:" KBUILD_MODNAME); MODULE_LICENSE("GPL v2");
linux-master
drivers/rpmsg/rpmsg_ctrl.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (c) 2016-2017, Linaro Ltd */ #include <linux/idr.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/list.h> #include <linux/mfd/syscon.h> #include <linux/module.h> #include <linux/of.h> #include <linux/of_address.h> #include <linux/of_irq.h> #include <linux/platform_device.h> #include <linux/regmap.h> #include <linux/rpmsg.h> #include <linux/slab.h> #include <linux/workqueue.h> #include <linux/mailbox_client.h> #include "rpmsg_internal.h" #include "qcom_glink_native.h" #define RPM_TOC_SIZE 256 #define RPM_TOC_MAGIC 0x67727430 /* grt0 */ #define RPM_TOC_MAX_ENTRIES ((RPM_TOC_SIZE - sizeof(struct rpm_toc)) / \ sizeof(struct rpm_toc_entry)) #define RPM_TX_FIFO_ID 0x61703272 /* ap2r */ #define RPM_RX_FIFO_ID 0x72326170 /* r2ap */ #define to_rpm_pipe(p) container_of(p, struct glink_rpm_pipe, native) struct rpm_toc_entry { __le32 id; __le32 offset; __le32 size; } __packed; struct rpm_toc { __le32 magic; __le32 count; struct rpm_toc_entry entries[]; } __packed; struct glink_rpm_pipe { struct qcom_glink_pipe native; void __iomem *tail; void __iomem *head; void __iomem *fifo; }; struct glink_rpm { struct qcom_glink *glink; int irq; struct mbox_client mbox_client; struct mbox_chan *mbox_chan; struct glink_rpm_pipe rx_pipe; struct glink_rpm_pipe tx_pipe; }; static size_t glink_rpm_rx_avail(struct qcom_glink_pipe *glink_pipe) { struct glink_rpm_pipe *pipe = to_rpm_pipe(glink_pipe); unsigned int head; unsigned int tail; head = readl(pipe->head); tail = readl(pipe->tail); if (head < tail) return pipe->native.length - tail + head; else return head - tail; } static void glink_rpm_rx_peek(struct qcom_glink_pipe *glink_pipe, void *data, unsigned int offset, size_t count) { struct glink_rpm_pipe *pipe = to_rpm_pipe(glink_pipe); unsigned int tail; size_t len; tail = readl(pipe->tail); tail += offset; if (tail >= pipe->native.length) tail -= pipe->native.length; len = min_t(size_t, count, pipe->native.length - tail); if (len) { __ioread32_copy(data, pipe->fifo + tail, len / sizeof(u32)); } if (len != count) { __ioread32_copy(data + len, pipe->fifo, (count - len) / sizeof(u32)); } } static void glink_rpm_rx_advance(struct qcom_glink_pipe *glink_pipe, size_t count) { struct glink_rpm_pipe *pipe = to_rpm_pipe(glink_pipe); unsigned int tail; tail = readl(pipe->tail); tail += count; if (tail >= pipe->native.length) tail -= pipe->native.length; writel(tail, pipe->tail); } static size_t glink_rpm_tx_avail(struct qcom_glink_pipe *glink_pipe) { struct glink_rpm_pipe *pipe = to_rpm_pipe(glink_pipe); unsigned int head; unsigned int tail; head = readl(pipe->head); tail = readl(pipe->tail); if (tail <= head) return pipe->native.length - head + tail; else return tail - head; } static unsigned int glink_rpm_tx_write_one(struct glink_rpm_pipe *pipe, unsigned int head, const void *data, size_t count) { size_t len; len = min_t(size_t, count, pipe->native.length - head); if (len) { __iowrite32_copy(pipe->fifo + head, data, len / sizeof(u32)); } if (len != count) { __iowrite32_copy(pipe->fifo, data + len, (count - len) / sizeof(u32)); } head += count; if (head >= pipe->native.length) head -= pipe->native.length; return head; } static void glink_rpm_tx_write(struct qcom_glink_pipe *glink_pipe, const void *hdr, size_t hlen, const void *data, size_t dlen) { struct glink_rpm_pipe *pipe = to_rpm_pipe(glink_pipe); size_t tlen = hlen + dlen; size_t aligned_dlen; unsigned int head; char padding[8] = {0}; size_t pad; /* Header length comes from glink native and is always 4 byte aligned */ if (WARN(hlen % 4, "Glink Header length must be 4 bytes aligned\n")) return; /* * Move the unaligned tail of the message to the padding chunk, to * ensure word aligned accesses */ aligned_dlen = ALIGN_DOWN(dlen, 4); if (aligned_dlen != dlen) memcpy(padding, data + aligned_dlen, dlen - aligned_dlen); head = readl(pipe->head); head = glink_rpm_tx_write_one(pipe, head, hdr, hlen); head = glink_rpm_tx_write_one(pipe, head, data, aligned_dlen); pad = ALIGN(tlen, 8) - ALIGN_DOWN(tlen, 4); if (pad) head = glink_rpm_tx_write_one(pipe, head, padding, pad); writel(head, pipe->head); } static void glink_rpm_tx_kick(struct qcom_glink_pipe *glink_pipe) { struct glink_rpm_pipe *pipe = to_rpm_pipe(glink_pipe); struct glink_rpm *rpm = container_of(pipe, struct glink_rpm, tx_pipe); mbox_send_message(rpm->mbox_chan, NULL); mbox_client_txdone(rpm->mbox_chan, 0); } static irqreturn_t qcom_glink_rpm_intr(int irq, void *data) { struct glink_rpm *rpm = data; qcom_glink_native_rx(rpm->glink); return IRQ_HANDLED; } static int glink_rpm_parse_toc(struct device *dev, void __iomem *msg_ram, size_t msg_ram_size, struct glink_rpm_pipe *rx, struct glink_rpm_pipe *tx) { struct rpm_toc *toc; int num_entries; unsigned int id; size_t offset; size_t size; void *buf; int i; buf = kzalloc(RPM_TOC_SIZE, GFP_KERNEL); if (!buf) return -ENOMEM; __ioread32_copy(buf, msg_ram + msg_ram_size - RPM_TOC_SIZE, RPM_TOC_SIZE / sizeof(u32)); toc = buf; if (le32_to_cpu(toc->magic) != RPM_TOC_MAGIC) { dev_err(dev, "RPM TOC has invalid magic\n"); goto err_inval; } num_entries = le32_to_cpu(toc->count); if (num_entries > RPM_TOC_MAX_ENTRIES) { dev_err(dev, "Invalid number of toc entries\n"); goto err_inval; } for (i = 0; i < num_entries; i++) { id = le32_to_cpu(toc->entries[i].id); offset = le32_to_cpu(toc->entries[i].offset); size = le32_to_cpu(toc->entries[i].size); if (offset > msg_ram_size || offset + size > msg_ram_size) { dev_err(dev, "TOC entry with invalid size\n"); continue; } switch (id) { case RPM_RX_FIFO_ID: rx->native.length = size; rx->tail = msg_ram + offset; rx->head = msg_ram + offset + sizeof(u32); rx->fifo = msg_ram + offset + 2 * sizeof(u32); break; case RPM_TX_FIFO_ID: tx->native.length = size; tx->tail = msg_ram + offset; tx->head = msg_ram + offset + sizeof(u32); tx->fifo = msg_ram + offset + 2 * sizeof(u32); break; } } if (!rx->fifo || !tx->fifo) { dev_err(dev, "Unable to find rx and tx descriptors\n"); goto err_inval; } kfree(buf); return 0; err_inval: kfree(buf); return -EINVAL; } static int glink_rpm_probe(struct platform_device *pdev) { struct qcom_glink *glink; struct glink_rpm *rpm; struct device_node *np; void __iomem *msg_ram; size_t msg_ram_size; struct device *dev = &pdev->dev; struct resource r; int ret; rpm = devm_kzalloc(&pdev->dev, sizeof(*rpm), GFP_KERNEL); if (!rpm) return -ENOMEM; np = of_parse_phandle(dev->of_node, "qcom,rpm-msg-ram", 0); ret = of_address_to_resource(np, 0, &r); of_node_put(np); if (ret) return ret; msg_ram = devm_ioremap(dev, r.start, resource_size(&r)); msg_ram_size = resource_size(&r); if (!msg_ram) return -ENOMEM; ret = glink_rpm_parse_toc(dev, msg_ram, msg_ram_size, &rpm->rx_pipe, &rpm->tx_pipe); if (ret) return ret; rpm->irq = of_irq_get(dev->of_node, 0); ret = devm_request_irq(dev, rpm->irq, qcom_glink_rpm_intr, IRQF_NO_SUSPEND | IRQF_NO_AUTOEN, "glink-rpm", rpm); if (ret) { dev_err(dev, "failed to request IRQ\n"); return ret; } rpm->mbox_client.dev = dev; rpm->mbox_client.knows_txdone = true; rpm->mbox_chan = mbox_request_channel(&rpm->mbox_client, 0); if (IS_ERR(rpm->mbox_chan)) return dev_err_probe(dev, PTR_ERR(rpm->mbox_chan), "failed to acquire IPC channel\n"); /* Pipe specific accessors */ rpm->rx_pipe.native.avail = glink_rpm_rx_avail; rpm->rx_pipe.native.peek = glink_rpm_rx_peek; rpm->rx_pipe.native.advance = glink_rpm_rx_advance; rpm->tx_pipe.native.avail = glink_rpm_tx_avail; rpm->tx_pipe.native.write = glink_rpm_tx_write; rpm->tx_pipe.native.kick = glink_rpm_tx_kick; writel(0, rpm->tx_pipe.head); writel(0, rpm->rx_pipe.tail); glink = qcom_glink_native_probe(dev, 0, &rpm->rx_pipe.native, &rpm->tx_pipe.native, true); if (IS_ERR(glink)) { mbox_free_channel(rpm->mbox_chan); return PTR_ERR(glink); } rpm->glink = glink; platform_set_drvdata(pdev, rpm); enable_irq(rpm->irq); return 0; } static void glink_rpm_remove(struct platform_device *pdev) { struct glink_rpm *rpm = platform_get_drvdata(pdev); struct qcom_glink *glink = rpm->glink; disable_irq(rpm->irq); qcom_glink_native_remove(glink); mbox_free_channel(rpm->mbox_chan); } static const struct of_device_id glink_rpm_of_match[] = { { .compatible = "qcom,glink-rpm" }, {} }; MODULE_DEVICE_TABLE(of, glink_rpm_of_match); static struct platform_driver glink_rpm_driver = { .probe = glink_rpm_probe, .remove_new = glink_rpm_remove, .driver = { .name = "qcom_glink_rpm", .of_match_table = glink_rpm_of_match, }, }; static int __init glink_rpm_init(void) { return platform_driver_register(&glink_rpm_driver); } subsys_initcall(glink_rpm_init); static void __exit glink_rpm_exit(void) { platform_driver_unregister(&glink_rpm_driver); } module_exit(glink_rpm_exit); MODULE_AUTHOR("Bjorn Andersson <[email protected]>"); MODULE_DESCRIPTION("Qualcomm GLINK RPM driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/rpmsg/qcom_glink_rpm.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2022, STMicroelectronics * Copyright (c) 2016, Linaro Ltd. * Copyright (c) 2012, Michal Simek <[email protected]> * Copyright (c) 2012, PetaLogix * Copyright (c) 2011, Texas Instruments, Inc. * Copyright (c) 2011, Google, Inc. * * Based on rpmsg performance statistics driver by Michal Simek, which in turn * was based on TI & Google OMX rpmsg driver. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/cdev.h> #include <linux/device.h> #include <linux/fs.h> #include <linux/idr.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/poll.h> #include <linux/rpmsg.h> #include <linux/skbuff.h> #include <linux/slab.h> #include <linux/uaccess.h> #include <uapi/linux/rpmsg.h> #include "rpmsg_char.h" #include "rpmsg_internal.h" #define RPMSG_DEV_MAX (MINORMASK + 1) static dev_t rpmsg_major; static DEFINE_IDA(rpmsg_ept_ida); static DEFINE_IDA(rpmsg_minor_ida); #define dev_to_eptdev(dev) container_of(dev, struct rpmsg_eptdev, dev) #define cdev_to_eptdev(i_cdev) container_of(i_cdev, struct rpmsg_eptdev, cdev) /** * struct rpmsg_eptdev - endpoint device context * @dev: endpoint device * @cdev: cdev for the endpoint device * @rpdev: underlaying rpmsg device * @chinfo: info used to open the endpoint * @ept_lock: synchronization of @ept modifications * @ept: rpmsg endpoint reference, when open * @queue_lock: synchronization of @queue operations * @queue: incoming message queue * @readq: wait object for incoming queue * @default_ept: set to channel default endpoint if the default endpoint should be re-used * on device open to prevent endpoint address update. * remote_flow_restricted: to indicate if the remote has requested for flow to be limited * remote_flow_updated: to indicate if the flow control has been requested */ struct rpmsg_eptdev { struct device dev; struct cdev cdev; struct rpmsg_device *rpdev; struct rpmsg_channel_info chinfo; struct mutex ept_lock; struct rpmsg_endpoint *ept; struct rpmsg_endpoint *default_ept; spinlock_t queue_lock; struct sk_buff_head queue; wait_queue_head_t readq; bool remote_flow_restricted; bool remote_flow_updated; }; int rpmsg_chrdev_eptdev_destroy(struct device *dev, void *data) { struct rpmsg_eptdev *eptdev = dev_to_eptdev(dev); mutex_lock(&eptdev->ept_lock); eptdev->rpdev = NULL; if (eptdev->ept) { /* The default endpoint is released by the rpmsg core */ if (!eptdev->default_ept) rpmsg_destroy_ept(eptdev->ept); eptdev->ept = NULL; } mutex_unlock(&eptdev->ept_lock); /* wake up any blocked readers */ wake_up_interruptible(&eptdev->readq); cdev_device_del(&eptdev->cdev, &eptdev->dev); put_device(&eptdev->dev); return 0; } EXPORT_SYMBOL(rpmsg_chrdev_eptdev_destroy); static int rpmsg_ept_cb(struct rpmsg_device *rpdev, void *buf, int len, void *priv, u32 addr) { struct rpmsg_eptdev *eptdev = priv; struct sk_buff *skb; skb = alloc_skb(len, GFP_ATOMIC); if (!skb) return -ENOMEM; skb_put_data(skb, buf, len); spin_lock(&eptdev->queue_lock); skb_queue_tail(&eptdev->queue, skb); spin_unlock(&eptdev->queue_lock); /* wake up any blocking processes, waiting for new data */ wake_up_interruptible(&eptdev->readq); return 0; } static int rpmsg_ept_flow_cb(struct rpmsg_device *rpdev, void *priv, bool enable) { struct rpmsg_eptdev *eptdev = priv; eptdev->remote_flow_restricted = enable; eptdev->remote_flow_updated = true; wake_up_interruptible(&eptdev->readq); return 0; } static int rpmsg_eptdev_open(struct inode *inode, struct file *filp) { struct rpmsg_eptdev *eptdev = cdev_to_eptdev(inode->i_cdev); struct rpmsg_endpoint *ept; struct rpmsg_device *rpdev = eptdev->rpdev; struct device *dev = &eptdev->dev; mutex_lock(&eptdev->ept_lock); if (eptdev->ept) { mutex_unlock(&eptdev->ept_lock); return -EBUSY; } if (!eptdev->rpdev) { mutex_unlock(&eptdev->ept_lock); return -ENETRESET; } get_device(dev); /* * If the default_ept is set, the rpmsg device default endpoint is used. * Else a new endpoint is created on open that will be destroyed on release. */ if (eptdev->default_ept) ept = eptdev->default_ept; else ept = rpmsg_create_ept(rpdev, rpmsg_ept_cb, eptdev, eptdev->chinfo); if (!ept) { dev_err(dev, "failed to open %s\n", eptdev->chinfo.name); put_device(dev); mutex_unlock(&eptdev->ept_lock); return -EINVAL; } ept->flow_cb = rpmsg_ept_flow_cb; eptdev->ept = ept; filp->private_data = eptdev; mutex_unlock(&eptdev->ept_lock); return 0; } static int rpmsg_eptdev_release(struct inode *inode, struct file *filp) { struct rpmsg_eptdev *eptdev = cdev_to_eptdev(inode->i_cdev); struct device *dev = &eptdev->dev; /* Close the endpoint, if it's not already destroyed by the parent */ mutex_lock(&eptdev->ept_lock); if (eptdev->ept) { if (!eptdev->default_ept) rpmsg_destroy_ept(eptdev->ept); eptdev->ept = NULL; } mutex_unlock(&eptdev->ept_lock); eptdev->remote_flow_updated = false; /* Discard all SKBs */ skb_queue_purge(&eptdev->queue); put_device(dev); return 0; } static ssize_t rpmsg_eptdev_read_iter(struct kiocb *iocb, struct iov_iter *to) { struct file *filp = iocb->ki_filp; struct rpmsg_eptdev *eptdev = filp->private_data; unsigned long flags; struct sk_buff *skb; int use; if (!eptdev->ept) return -EPIPE; spin_lock_irqsave(&eptdev->queue_lock, flags); /* Wait for data in the queue */ if (skb_queue_empty(&eptdev->queue)) { spin_unlock_irqrestore(&eptdev->queue_lock, flags); if (filp->f_flags & O_NONBLOCK) return -EAGAIN; /* Wait until we get data or the endpoint goes away */ if (wait_event_interruptible(eptdev->readq, !skb_queue_empty(&eptdev->queue) || !eptdev->ept)) return -ERESTARTSYS; /* We lost the endpoint while waiting */ if (!eptdev->ept) return -EPIPE; spin_lock_irqsave(&eptdev->queue_lock, flags); } skb = skb_dequeue(&eptdev->queue); spin_unlock_irqrestore(&eptdev->queue_lock, flags); if (!skb) return -EFAULT; use = min_t(size_t, iov_iter_count(to), skb->len); if (copy_to_iter(skb->data, use, to) != use) use = -EFAULT; kfree_skb(skb); return use; } static ssize_t rpmsg_eptdev_write_iter(struct kiocb *iocb, struct iov_iter *from) { struct file *filp = iocb->ki_filp; struct rpmsg_eptdev *eptdev = filp->private_data; size_t len = iov_iter_count(from); void *kbuf; int ret; kbuf = kzalloc(len, GFP_KERNEL); if (!kbuf) return -ENOMEM; if (!copy_from_iter_full(kbuf, len, from)) { ret = -EFAULT; goto free_kbuf; } if (mutex_lock_interruptible(&eptdev->ept_lock)) { ret = -ERESTARTSYS; goto free_kbuf; } if (!eptdev->ept) { ret = -EPIPE; goto unlock_eptdev; } if (filp->f_flags & O_NONBLOCK) { ret = rpmsg_trysendto(eptdev->ept, kbuf, len, eptdev->chinfo.dst); if (ret == -ENOMEM) ret = -EAGAIN; } else { ret = rpmsg_sendto(eptdev->ept, kbuf, len, eptdev->chinfo.dst); } unlock_eptdev: mutex_unlock(&eptdev->ept_lock); free_kbuf: kfree(kbuf); return ret < 0 ? ret : len; } static __poll_t rpmsg_eptdev_poll(struct file *filp, poll_table *wait) { struct rpmsg_eptdev *eptdev = filp->private_data; __poll_t mask = 0; if (!eptdev->ept) return EPOLLERR; poll_wait(filp, &eptdev->readq, wait); if (!skb_queue_empty(&eptdev->queue)) mask |= EPOLLIN | EPOLLRDNORM; if (eptdev->remote_flow_updated) mask |= EPOLLPRI; mutex_lock(&eptdev->ept_lock); mask |= rpmsg_poll(eptdev->ept, filp, wait); mutex_unlock(&eptdev->ept_lock); return mask; } static long rpmsg_eptdev_ioctl(struct file *fp, unsigned int cmd, unsigned long arg) { struct rpmsg_eptdev *eptdev = fp->private_data; bool set; int ret; switch (cmd) { case RPMSG_GET_OUTGOING_FLOWCONTROL: eptdev->remote_flow_updated = false; ret = put_user(eptdev->remote_flow_restricted, (int __user *)arg); break; case RPMSG_SET_INCOMING_FLOWCONTROL: if (arg > 1) { ret = -EINVAL; break; } set = !!arg; ret = rpmsg_set_flow_control(eptdev->ept, set, eptdev->chinfo.dst); break; case RPMSG_DESTROY_EPT_IOCTL: /* Don't allow to destroy a default endpoint. */ if (eptdev->default_ept) { ret = -EINVAL; break; } ret = rpmsg_chrdev_eptdev_destroy(&eptdev->dev, NULL); break; default: ret = -EINVAL; } return ret; } static const struct file_operations rpmsg_eptdev_fops = { .owner = THIS_MODULE, .open = rpmsg_eptdev_open, .release = rpmsg_eptdev_release, .read_iter = rpmsg_eptdev_read_iter, .write_iter = rpmsg_eptdev_write_iter, .poll = rpmsg_eptdev_poll, .unlocked_ioctl = rpmsg_eptdev_ioctl, .compat_ioctl = compat_ptr_ioctl, }; static ssize_t name_show(struct device *dev, struct device_attribute *attr, char *buf) { struct rpmsg_eptdev *eptdev = dev_get_drvdata(dev); return sprintf(buf, "%s\n", eptdev->chinfo.name); } static DEVICE_ATTR_RO(name); static ssize_t src_show(struct device *dev, struct device_attribute *attr, char *buf) { struct rpmsg_eptdev *eptdev = dev_get_drvdata(dev); return sprintf(buf, "%d\n", eptdev->chinfo.src); } static DEVICE_ATTR_RO(src); static ssize_t dst_show(struct device *dev, struct device_attribute *attr, char *buf) { struct rpmsg_eptdev *eptdev = dev_get_drvdata(dev); return sprintf(buf, "%d\n", eptdev->chinfo.dst); } static DEVICE_ATTR_RO(dst); static struct attribute *rpmsg_eptdev_attrs[] = { &dev_attr_name.attr, &dev_attr_src.attr, &dev_attr_dst.attr, NULL }; ATTRIBUTE_GROUPS(rpmsg_eptdev); static void rpmsg_eptdev_release_device(struct device *dev) { struct rpmsg_eptdev *eptdev = dev_to_eptdev(dev); ida_simple_remove(&rpmsg_ept_ida, dev->id); ida_simple_remove(&rpmsg_minor_ida, MINOR(eptdev->dev.devt)); kfree(eptdev); } static struct rpmsg_eptdev *rpmsg_chrdev_eptdev_alloc(struct rpmsg_device *rpdev, struct device *parent) { struct rpmsg_eptdev *eptdev; struct device *dev; eptdev = kzalloc(sizeof(*eptdev), GFP_KERNEL); if (!eptdev) return ERR_PTR(-ENOMEM); dev = &eptdev->dev; eptdev->rpdev = rpdev; mutex_init(&eptdev->ept_lock); spin_lock_init(&eptdev->queue_lock); skb_queue_head_init(&eptdev->queue); init_waitqueue_head(&eptdev->readq); device_initialize(dev); dev->class = rpmsg_class; dev->parent = parent; dev->groups = rpmsg_eptdev_groups; dev_set_drvdata(dev, eptdev); cdev_init(&eptdev->cdev, &rpmsg_eptdev_fops); eptdev->cdev.owner = THIS_MODULE; return eptdev; } static int rpmsg_chrdev_eptdev_add(struct rpmsg_eptdev *eptdev, struct rpmsg_channel_info chinfo) { struct device *dev = &eptdev->dev; int ret; eptdev->chinfo = chinfo; ret = ida_simple_get(&rpmsg_minor_ida, 0, RPMSG_DEV_MAX, GFP_KERNEL); if (ret < 0) goto free_eptdev; dev->devt = MKDEV(MAJOR(rpmsg_major), ret); ret = ida_simple_get(&rpmsg_ept_ida, 0, 0, GFP_KERNEL); if (ret < 0) goto free_minor_ida; dev->id = ret; dev_set_name(dev, "rpmsg%d", ret); ret = cdev_device_add(&eptdev->cdev, &eptdev->dev); if (ret) goto free_ept_ida; /* We can now rely on the release function for cleanup */ dev->release = rpmsg_eptdev_release_device; return ret; free_ept_ida: ida_simple_remove(&rpmsg_ept_ida, dev->id); free_minor_ida: ida_simple_remove(&rpmsg_minor_ida, MINOR(dev->devt)); free_eptdev: put_device(dev); kfree(eptdev); return ret; } int rpmsg_chrdev_eptdev_create(struct rpmsg_device *rpdev, struct device *parent, struct rpmsg_channel_info chinfo) { struct rpmsg_eptdev *eptdev; eptdev = rpmsg_chrdev_eptdev_alloc(rpdev, parent); if (IS_ERR(eptdev)) return PTR_ERR(eptdev); return rpmsg_chrdev_eptdev_add(eptdev, chinfo); } EXPORT_SYMBOL(rpmsg_chrdev_eptdev_create); static int rpmsg_chrdev_probe(struct rpmsg_device *rpdev) { struct rpmsg_channel_info chinfo; struct rpmsg_eptdev *eptdev; struct device *dev = &rpdev->dev; memcpy(chinfo.name, rpdev->id.name, RPMSG_NAME_SIZE); chinfo.src = rpdev->src; chinfo.dst = rpdev->dst; eptdev = rpmsg_chrdev_eptdev_alloc(rpdev, dev); if (IS_ERR(eptdev)) return PTR_ERR(eptdev); /* Set the default_ept to the rpmsg device endpoint */ eptdev->default_ept = rpdev->ept; /* * The rpmsg_ept_cb uses *priv parameter to get its rpmsg_eptdev context. * Storedit in default_ept *priv field. */ eptdev->default_ept->priv = eptdev; return rpmsg_chrdev_eptdev_add(eptdev, chinfo); } static void rpmsg_chrdev_remove(struct rpmsg_device *rpdev) { int ret; ret = device_for_each_child(&rpdev->dev, NULL, rpmsg_chrdev_eptdev_destroy); if (ret) dev_warn(&rpdev->dev, "failed to destroy endpoints: %d\n", ret); } static struct rpmsg_device_id rpmsg_chrdev_id_table[] = { { .name = "rpmsg-raw" }, { }, }; static struct rpmsg_driver rpmsg_chrdev_driver = { .probe = rpmsg_chrdev_probe, .remove = rpmsg_chrdev_remove, .callback = rpmsg_ept_cb, .id_table = rpmsg_chrdev_id_table, .drv.name = "rpmsg_chrdev", }; static int rpmsg_chrdev_init(void) { int ret; ret = alloc_chrdev_region(&rpmsg_major, 0, RPMSG_DEV_MAX, "rpmsg_char"); if (ret < 0) { pr_err("failed to allocate char dev region\n"); return ret; } ret = register_rpmsg_driver(&rpmsg_chrdev_driver); if (ret < 0) { pr_err("rpmsg: failed to register rpmsg raw driver\n"); goto free_region; } return 0; free_region: unregister_chrdev_region(rpmsg_major, RPMSG_DEV_MAX); return ret; } postcore_initcall(rpmsg_chrdev_init); static void rpmsg_chrdev_exit(void) { unregister_rpmsg_driver(&rpmsg_chrdev_driver); unregister_chrdev_region(rpmsg_major, RPMSG_DEV_MAX); } module_exit(rpmsg_chrdev_exit); MODULE_ALIAS("rpmsg:rpmsg_chrdev"); MODULE_LICENSE("GPL v2");
linux-master
drivers/rpmsg/rpmsg_char.c
// SPDX-License-Identifier: GPL-2.0 /* * Renesas R-Mobile Reset Driver * * Copyright (C) 2014 Glider bvba */ #include <linux/io.h> #include <linux/module.h> #include <linux/notifier.h> #include <linux/of_address.h> #include <linux/platform_device.h> #include <linux/printk.h> #include <linux/reboot.h> /* SYSC Register Bank 2 */ #define RESCNT2 0x20 /* Reset Control Register 2 */ /* Reset Control Register 2 */ #define RESCNT2_PRES 0x80000000 /* Soft power-on reset */ static void __iomem *sysc_base2; static int rmobile_reset_handler(struct notifier_block *this, unsigned long mode, void *cmd) { pr_debug("%s %lu\n", __func__, mode); /* Let's assume we have acquired the HPB semaphore */ writel(RESCNT2_PRES, sysc_base2 + RESCNT2); return NOTIFY_DONE; } static struct notifier_block rmobile_reset_nb = { .notifier_call = rmobile_reset_handler, .priority = 192, }; static int rmobile_reset_probe(struct platform_device *pdev) { int error; sysc_base2 = of_iomap(pdev->dev.of_node, 1); if (!sysc_base2) return -ENODEV; error = register_restart_handler(&rmobile_reset_nb); if (error) { dev_err(&pdev->dev, "cannot register restart handler (err=%d)\n", error); goto fail_unmap; } return 0; fail_unmap: iounmap(sysc_base2); return error; } static int rmobile_reset_remove(struct platform_device *pdev) { unregister_restart_handler(&rmobile_reset_nb); iounmap(sysc_base2); return 0; } static const struct of_device_id rmobile_reset_of_match[] = { { .compatible = "renesas,sysc-rmobile", }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, rmobile_reset_of_match); static struct platform_driver rmobile_reset_driver = { .probe = rmobile_reset_probe, .remove = rmobile_reset_remove, .driver = { .name = "rmobile_reset", .of_match_table = rmobile_reset_of_match, }, }; module_platform_driver(rmobile_reset_driver); MODULE_DESCRIPTION("Renesas R-Mobile Reset Driver"); MODULE_AUTHOR("Geert Uytterhoeven <[email protected]>"); MODULE_LICENSE("GPL v2");
linux-master
drivers/power/reset/rmobile-reset.c
/* * Atmel SAMA5D2-Compatible Shutdown Controller (SHDWC) driver. * Found on some SoCs as the sama5d2 (obviously). * * Copyright (C) 2015 Atmel Corporation, * Nicolas Ferre <[email protected]> * * Evolved from driver at91-poweroff.c. * * This file is licensed under the terms of the GNU General Public * License version 2. This program is licensed "as is" without any * warranty of any kind, whether express or implied. * * TODO: * - addition to status of other wake-up inputs [1 - 15] * - Analog Comparator wake-up alarm * - Serial RX wake-up alarm * - low power debouncer */ #include <linux/clk.h> #include <linux/clk/at91_pmc.h> #include <linux/io.h> #include <linux/module.h> #include <linux/of.h> #include <linux/of_address.h> #include <linux/platform_device.h> #include <linux/printk.h> #include <soc/at91/at91sam9_ddrsdr.h> #define SLOW_CLOCK_FREQ 32768 #define AT91_SHDW_CR 0x00 /* Shut Down Control Register */ #define AT91_SHDW_SHDW BIT(0) /* Shut Down command */ #define AT91_SHDW_KEY (0xa5UL << 24) /* KEY Password */ #define AT91_SHDW_MR 0x04 /* Shut Down Mode Register */ #define AT91_SHDW_WKUPDBC_SHIFT 24 #define AT91_SHDW_WKUPDBC_MASK GENMASK(26, 24) #define AT91_SHDW_WKUPDBC(x) (((x) << AT91_SHDW_WKUPDBC_SHIFT) \ & AT91_SHDW_WKUPDBC_MASK) #define AT91_SHDW_SR 0x08 /* Shut Down Status Register */ #define AT91_SHDW_WKUPIS_SHIFT 16 #define AT91_SHDW_WKUPIS_MASK GENMASK(31, 16) #define AT91_SHDW_WKUPIS(x) ((1 << (x)) << AT91_SHDW_WKUPIS_SHIFT \ & AT91_SHDW_WKUPIS_MASK) #define AT91_SHDW_WUIR 0x0c /* Shutdown Wake-up Inputs Register */ #define AT91_SHDW_WKUPEN_MASK GENMASK(15, 0) #define AT91_SHDW_WKUPEN(x) ((1 << (x)) & AT91_SHDW_WKUPEN_MASK) #define AT91_SHDW_WKUPT_SHIFT 16 #define AT91_SHDW_WKUPT_MASK GENMASK(31, 16) #define AT91_SHDW_WKUPT(x) ((1 << (x)) << AT91_SHDW_WKUPT_SHIFT \ & AT91_SHDW_WKUPT_MASK) #define SHDW_WK_PIN(reg, cfg) ((reg) & AT91_SHDW_WKUPIS((cfg)->wkup_pin_input)) #define SHDW_RTCWK(reg, cfg) (((reg) >> ((cfg)->sr_rtcwk_shift)) & 0x1) #define SHDW_RTTWK(reg, cfg) (((reg) >> ((cfg)->sr_rttwk_shift)) & 0x1) #define SHDW_RTCWKEN(cfg) (1 << ((cfg)->mr_rtcwk_shift)) #define SHDW_RTTWKEN(cfg) (1 << ((cfg)->mr_rttwk_shift)) #define DBC_PERIOD_US(x) DIV_ROUND_UP_ULL((1000000 * (x)), \ SLOW_CLOCK_FREQ) #define SHDW_CFG_NOT_USED (32) struct shdwc_reg_config { u8 wkup_pin_input; u8 mr_rtcwk_shift; u8 mr_rttwk_shift; u8 sr_rtcwk_shift; u8 sr_rttwk_shift; }; struct pmc_reg_config { u8 mckr; }; struct ddrc_reg_config { u32 type_offset; u32 type_mask; }; struct reg_config { struct shdwc_reg_config shdwc; struct pmc_reg_config pmc; struct ddrc_reg_config ddrc; }; struct shdwc { const struct reg_config *rcfg; struct clk *sclk; void __iomem *shdwc_base; void __iomem *mpddrc_base; void __iomem *pmc_base; }; /* * Hold configuration here, cannot be more than one instance of the driver * since pm_power_off itself is global. */ static struct shdwc *at91_shdwc; static const unsigned long long sdwc_dbc_period[] = { 0, 3, 32, 512, 4096, 32768, }; static void __init at91_wakeup_status(struct platform_device *pdev) { struct shdwc *shdw = platform_get_drvdata(pdev); const struct reg_config *rcfg = shdw->rcfg; u32 reg; char *reason = "unknown"; reg = readl(shdw->shdwc_base + AT91_SHDW_SR); dev_dbg(&pdev->dev, "%s: status = %#x\n", __func__, reg); /* Simple power-on, just bail out */ if (!reg) return; if (SHDW_WK_PIN(reg, &rcfg->shdwc)) reason = "WKUP pin"; else if (SHDW_RTCWK(reg, &rcfg->shdwc)) reason = "RTC"; else if (SHDW_RTTWK(reg, &rcfg->shdwc)) reason = "RTT"; pr_info("AT91: Wake-Up source: %s\n", reason); } static void at91_poweroff(void) { asm volatile( /* Align to cache lines */ ".balign 32\n\t" /* Ensure AT91_SHDW_CR is in the TLB by reading it */ " ldr r6, [%2, #" __stringify(AT91_SHDW_CR) "]\n\t" /* Power down SDRAM0 */ " tst %0, #0\n\t" " beq 1f\n\t" " str %1, [%0, #" __stringify(AT91_DDRSDRC_LPR) "]\n\t" /* Switch the master clock source to slow clock. */ "1: ldr r6, [%4, %5]\n\t" " bic r6, r6, #" __stringify(AT91_PMC_CSS) "\n\t" " str r6, [%4, %5]\n\t" /* Wait for clock switch. */ "2: ldr r6, [%4, #" __stringify(AT91_PMC_SR) "]\n\t" " tst r6, #" __stringify(AT91_PMC_MCKRDY) "\n\t" " beq 2b\n\t" /* Shutdown CPU */ " str %3, [%2, #" __stringify(AT91_SHDW_CR) "]\n\t" " b .\n\t" : : "r" (at91_shdwc->mpddrc_base), "r" cpu_to_le32(AT91_DDRSDRC_LPDDR2_PWOFF), "r" (at91_shdwc->shdwc_base), "r" cpu_to_le32(AT91_SHDW_KEY | AT91_SHDW_SHDW), "r" (at91_shdwc->pmc_base), "r" (at91_shdwc->rcfg->pmc.mckr) : "r6"); } static u32 at91_shdwc_debouncer_value(struct platform_device *pdev, u32 in_period_us) { int i; int max_idx = ARRAY_SIZE(sdwc_dbc_period) - 1; unsigned long long period_us; unsigned long long max_period_us = DBC_PERIOD_US(sdwc_dbc_period[max_idx]); if (in_period_us > max_period_us) { dev_warn(&pdev->dev, "debouncer period %u too big, reduced to %llu us\n", in_period_us, max_period_us); return max_idx; } for (i = max_idx - 1; i > 0; i--) { period_us = DBC_PERIOD_US(sdwc_dbc_period[i]); dev_dbg(&pdev->dev, "%s: ref[%d] = %llu\n", __func__, i, period_us); if (in_period_us > period_us) break; } return i + 1; } static u32 at91_shdwc_get_wakeup_input(struct platform_device *pdev, struct device_node *np) { struct device_node *cnp; u32 wk_input_mask; u32 wuir = 0; u32 wk_input; for_each_child_of_node(np, cnp) { if (of_property_read_u32(cnp, "reg", &wk_input)) { dev_warn(&pdev->dev, "reg property is missing for %pOF\n", cnp); continue; } wk_input_mask = 1 << wk_input; if (!(wk_input_mask & AT91_SHDW_WKUPEN_MASK)) { dev_warn(&pdev->dev, "wake-up input %d out of bounds ignore\n", wk_input); continue; } wuir |= wk_input_mask; if (of_property_read_bool(cnp, "atmel,wakeup-active-high")) wuir |= AT91_SHDW_WKUPT(wk_input); dev_dbg(&pdev->dev, "%s: (child %d) wuir = %#x\n", __func__, wk_input, wuir); } return wuir; } static void at91_shdwc_dt_configure(struct platform_device *pdev) { struct shdwc *shdw = platform_get_drvdata(pdev); const struct reg_config *rcfg = shdw->rcfg; struct device_node *np = pdev->dev.of_node; u32 mode = 0, tmp, input; if (!np) { dev_err(&pdev->dev, "device node not found\n"); return; } if (!of_property_read_u32(np, "debounce-delay-us", &tmp)) mode |= AT91_SHDW_WKUPDBC(at91_shdwc_debouncer_value(pdev, tmp)); if (of_property_read_bool(np, "atmel,wakeup-rtc-timer")) mode |= SHDW_RTCWKEN(&rcfg->shdwc); if (of_property_read_bool(np, "atmel,wakeup-rtt-timer")) mode |= SHDW_RTTWKEN(&rcfg->shdwc); dev_dbg(&pdev->dev, "%s: mode = %#x\n", __func__, mode); writel(mode, shdw->shdwc_base + AT91_SHDW_MR); input = at91_shdwc_get_wakeup_input(pdev, np); writel(input, shdw->shdwc_base + AT91_SHDW_WUIR); } static const struct reg_config sama5d2_reg_config = { .shdwc = { .wkup_pin_input = 0, .mr_rtcwk_shift = 17, .mr_rttwk_shift = SHDW_CFG_NOT_USED, .sr_rtcwk_shift = 5, .sr_rttwk_shift = SHDW_CFG_NOT_USED, }, .pmc = { .mckr = 0x30, }, .ddrc = { .type_offset = AT91_DDRSDRC_MDR, .type_mask = AT91_DDRSDRC_MD }, }; static const struct reg_config sam9x60_reg_config = { .shdwc = { .wkup_pin_input = 0, .mr_rtcwk_shift = 17, .mr_rttwk_shift = 16, .sr_rtcwk_shift = 5, .sr_rttwk_shift = 4, }, .pmc = { .mckr = 0x28, }, .ddrc = { .type_offset = AT91_DDRSDRC_MDR, .type_mask = AT91_DDRSDRC_MD }, }; static const struct reg_config sama7g5_reg_config = { .shdwc = { .wkup_pin_input = 0, .mr_rtcwk_shift = 17, .mr_rttwk_shift = 16, .sr_rtcwk_shift = 5, .sr_rttwk_shift = 4, }, .pmc = { .mckr = 0x28, }, }; static const struct of_device_id at91_shdwc_of_match[] = { { .compatible = "atmel,sama5d2-shdwc", .data = &sama5d2_reg_config, }, { .compatible = "microchip,sam9x60-shdwc", .data = &sam9x60_reg_config, }, { .compatible = "microchip,sama7g5-shdwc", .data = &sama7g5_reg_config, }, { /*sentinel*/ } }; MODULE_DEVICE_TABLE(of, at91_shdwc_of_match); static const struct of_device_id at91_pmc_ids[] = { { .compatible = "atmel,sama5d2-pmc" }, { .compatible = "microchip,sam9x60-pmc" }, { .compatible = "microchip,sama7g5-pmc" }, { /* Sentinel. */ } }; static int __init at91_shdwc_probe(struct platform_device *pdev) { const struct of_device_id *match; struct device_node *np; u32 ddr_type; int ret; if (!pdev->dev.of_node) return -ENODEV; if (at91_shdwc) return -EBUSY; at91_shdwc = devm_kzalloc(&pdev->dev, sizeof(*at91_shdwc), GFP_KERNEL); if (!at91_shdwc) return -ENOMEM; platform_set_drvdata(pdev, at91_shdwc); at91_shdwc->shdwc_base = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(at91_shdwc->shdwc_base)) return PTR_ERR(at91_shdwc->shdwc_base); match = of_match_node(at91_shdwc_of_match, pdev->dev.of_node); at91_shdwc->rcfg = match->data; at91_shdwc->sclk = devm_clk_get(&pdev->dev, NULL); if (IS_ERR(at91_shdwc->sclk)) return PTR_ERR(at91_shdwc->sclk); ret = clk_prepare_enable(at91_shdwc->sclk); if (ret) { dev_err(&pdev->dev, "Could not enable slow clock\n"); return ret; } at91_wakeup_status(pdev); at91_shdwc_dt_configure(pdev); np = of_find_matching_node(NULL, at91_pmc_ids); if (!np) { ret = -ENODEV; goto clk_disable; } at91_shdwc->pmc_base = of_iomap(np, 0); of_node_put(np); if (!at91_shdwc->pmc_base) { ret = -ENOMEM; goto clk_disable; } if (at91_shdwc->rcfg->ddrc.type_mask) { np = of_find_compatible_node(NULL, NULL, "atmel,sama5d3-ddramc"); if (!np) { ret = -ENODEV; goto unmap; } at91_shdwc->mpddrc_base = of_iomap(np, 0); of_node_put(np); if (!at91_shdwc->mpddrc_base) { ret = -ENOMEM; goto unmap; } ddr_type = readl(at91_shdwc->mpddrc_base + at91_shdwc->rcfg->ddrc.type_offset) & at91_shdwc->rcfg->ddrc.type_mask; if (ddr_type != AT91_DDRSDRC_MD_LPDDR2 && ddr_type != AT91_DDRSDRC_MD_LPDDR3) { iounmap(at91_shdwc->mpddrc_base); at91_shdwc->mpddrc_base = NULL; } } pm_power_off = at91_poweroff; return 0; unmap: iounmap(at91_shdwc->pmc_base); clk_disable: clk_disable_unprepare(at91_shdwc->sclk); return ret; } static int __exit at91_shdwc_remove(struct platform_device *pdev) { struct shdwc *shdw = platform_get_drvdata(pdev); if (pm_power_off == at91_poweroff) pm_power_off = NULL; /* Reset values to disable wake-up features */ writel(0, shdw->shdwc_base + AT91_SHDW_MR); writel(0, shdw->shdwc_base + AT91_SHDW_WUIR); if (shdw->mpddrc_base) iounmap(shdw->mpddrc_base); iounmap(shdw->pmc_base); clk_disable_unprepare(shdw->sclk); return 0; } static struct platform_driver at91_shdwc_driver = { .remove = __exit_p(at91_shdwc_remove), .driver = { .name = "at91-shdwc", .of_match_table = at91_shdwc_of_match, }, }; module_platform_driver_probe(at91_shdwc_driver, at91_shdwc_probe); MODULE_AUTHOR("Nicolas Ferre <[email protected]>"); MODULE_DESCRIPTION("Atmel shutdown controller driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/power/reset/at91-sama5d2_shdwc.c
// SPDX-License-Identifier: GPL-2.0-only /* Copyright (c) 2013, The Linux Foundation. All rights reserved. */ #include <linux/delay.h> #include <linux/err.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/io.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/module.h> #include <linux/reboot.h> #include <linux/pm.h> static void __iomem *msm_ps_hold; static int deassert_pshold(struct notifier_block *nb, unsigned long action, void *data) { writel(0, msm_ps_hold); mdelay(10000); return NOTIFY_DONE; } static struct notifier_block restart_nb = { .notifier_call = deassert_pshold, .priority = 128, }; static void do_msm_poweroff(void) { deassert_pshold(&restart_nb, 0, NULL); } static int msm_restart_probe(struct platform_device *pdev) { msm_ps_hold = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(msm_ps_hold)) return PTR_ERR(msm_ps_hold); register_restart_handler(&restart_nb); pm_power_off = do_msm_poweroff; return 0; } static const struct of_device_id of_msm_restart_match[] = { { .compatible = "qcom,pshold", }, {}, }; MODULE_DEVICE_TABLE(of, of_msm_restart_match); static struct platform_driver msm_restart_driver = { .probe = msm_restart_probe, .driver = { .name = "msm-restart", .of_match_table = of_match_ptr(of_msm_restart_match), }, }; static int __init msm_restart_init(void) { return platform_driver_register(&msm_restart_driver); } device_initcall(msm_restart_init);
linux-master
drivers/power/reset/msm-poweroff.c
// SPDX-License-Identifier: GPL-2.0-only /* * HiSilicon SoC reset code * * Copyright (c) 2014 HiSilicon Ltd. * Copyright (c) 2014 Linaro Ltd. * * Author: Haojian Zhuang <[email protected]> */ #include <linux/delay.h> #include <linux/io.h> #include <linux/module.h> #include <linux/notifier.h> #include <linux/of_address.h> #include <linux/platform_device.h> #include <linux/reboot.h> #include <asm/proc-fns.h> static void __iomem *base; static u32 reboot_offset; static int hisi_restart_handler(struct notifier_block *this, unsigned long mode, void *cmd) { writel_relaxed(0xdeadbeef, base + reboot_offset); while (1) cpu_do_idle(); return NOTIFY_DONE; } static struct notifier_block hisi_restart_nb = { .notifier_call = hisi_restart_handler, .priority = 128, }; static int hisi_reboot_probe(struct platform_device *pdev) { struct device_node *np = pdev->dev.of_node; int err; base = of_iomap(np, 0); if (!base) { WARN(1, "failed to map base address"); return -ENODEV; } if (of_property_read_u32(np, "reboot-offset", &reboot_offset) < 0) { pr_err("failed to find reboot-offset property\n"); iounmap(base); return -EINVAL; } err = register_restart_handler(&hisi_restart_nb); if (err) { dev_err(&pdev->dev, "cannot register restart handler (err=%d)\n", err); iounmap(base); } return err; } static const struct of_device_id hisi_reboot_of_match[] = { { .compatible = "hisilicon,sysctrl" }, {} }; MODULE_DEVICE_TABLE(of, hisi_reboot_of_match); static struct platform_driver hisi_reboot_driver = { .probe = hisi_reboot_probe, .driver = { .name = "hisi-reboot", .of_match_table = hisi_reboot_of_match, }, }; module_platform_driver(hisi_reboot_driver);
linux-master
drivers/power/reset/hisi-reboot.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * QNAP Turbo NAS Board power off. Can also be used on Synology devices. * * Copyright (C) 2012 Andrew Lunn <[email protected]> * * Based on the code from: * * Copyright (C) 2009 Martin Michlmayr <[email protected]> * Copyright (C) 2008 Byron Bradley <[email protected]> */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/serial_reg.h> #include <linux/of.h> #include <linux/io.h> #include <linux/clk.h> #define UART1_REG(x) (base + ((UART_##x) << 2)) struct power_off_cfg { u32 baud; char cmd; }; static const struct power_off_cfg qnap_power_off_cfg = { .baud = 19200, .cmd = 'A', }; static const struct power_off_cfg synology_power_off_cfg = { .baud = 9600, .cmd = '1', }; static const struct of_device_id qnap_power_off_of_match_table[] = { { .compatible = "qnap,power-off", .data = &qnap_power_off_cfg, }, { .compatible = "synology,power-off", .data = &synology_power_off_cfg, }, {} }; MODULE_DEVICE_TABLE(of, qnap_power_off_of_match_table); static void __iomem *base; static unsigned long tclk; static const struct power_off_cfg *cfg; static void qnap_power_off(void) { const unsigned divisor = ((tclk + (8 * cfg->baud)) / (16 * cfg->baud)); pr_err("%s: triggering power-off...\n", __func__); /* hijack UART1 and reset into sane state */ writel(0x83, UART1_REG(LCR)); writel(divisor & 0xff, UART1_REG(DLL)); writel((divisor >> 8) & 0xff, UART1_REG(DLM)); writel(0x03, UART1_REG(LCR)); writel(0x00, UART1_REG(IER)); writel(0x00, UART1_REG(FCR)); writel(0x00, UART1_REG(MCR)); /* send the power-off command to PIC */ writel(cfg->cmd, UART1_REG(TX)); } static int qnap_power_off_probe(struct platform_device *pdev) { struct device_node *np = pdev->dev.of_node; struct resource *res; struct clk *clk; const struct of_device_id *match = of_match_node(qnap_power_off_of_match_table, np); cfg = match->data; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(&pdev->dev, "Missing resource"); return -EINVAL; } base = devm_ioremap(&pdev->dev, res->start, resource_size(res)); if (!base) { dev_err(&pdev->dev, "Unable to map resource"); return -EINVAL; } /* We need to know tclk in order to calculate the UART divisor */ clk = devm_clk_get(&pdev->dev, NULL); if (IS_ERR(clk)) { dev_err(&pdev->dev, "Clk missing"); return PTR_ERR(clk); } tclk = clk_get_rate(clk); /* Check that nothing else has already setup a handler */ if (pm_power_off) { dev_err(&pdev->dev, "pm_power_off already claimed for %ps", pm_power_off); return -EBUSY; } pm_power_off = qnap_power_off; return 0; } static int qnap_power_off_remove(struct platform_device *pdev) { pm_power_off = NULL; return 0; } static struct platform_driver qnap_power_off_driver = { .probe = qnap_power_off_probe, .remove = qnap_power_off_remove, .driver = { .name = "qnap_power_off", .of_match_table = of_match_ptr(qnap_power_off_of_match_table), }, }; module_platform_driver(qnap_power_off_driver); MODULE_AUTHOR("Andrew Lunn <[email protected]>"); MODULE_DESCRIPTION("QNAP Power off driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/power/reset/qnap-poweroff.c
// SPDX-License-Identifier: GPL-2.0-only /* * Toggles a GPIO pin to power down a device * * Jamie Lentin <[email protected]> * Andrew Lunn <[email protected]> * * Copyright (C) 2012 Jamie Lentin */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/platform_device.h> #include <linux/property.h> #include <linux/gpio/consumer.h> #include <linux/mod_devicetable.h> #include <linux/module.h> #define DEFAULT_TIMEOUT_MS 3000 /* * Hold configuration here, cannot be more than one instance of the driver * since pm_power_off itself is global. */ static struct gpio_desc *reset_gpio; static u32 timeout = DEFAULT_TIMEOUT_MS; static u32 active_delay = 100; static u32 inactive_delay = 100; static void gpio_poweroff_do_poweroff(void) { BUG_ON(!reset_gpio); /* drive it active, also inactive->active edge */ gpiod_direction_output(reset_gpio, 1); mdelay(active_delay); /* drive inactive, also active->inactive edge */ gpiod_set_value_cansleep(reset_gpio, 0); mdelay(inactive_delay); /* drive it active, also inactive->active edge */ gpiod_set_value_cansleep(reset_gpio, 1); /* give it some time */ mdelay(timeout); WARN_ON(1); } static int gpio_poweroff_probe(struct platform_device *pdev) { bool input = false; enum gpiod_flags flags; /* If a pm_power_off function has already been added, leave it alone */ if (pm_power_off != NULL) { dev_err(&pdev->dev, "%s: pm_power_off function already registered\n", __func__); return -EBUSY; } input = device_property_read_bool(&pdev->dev, "input"); if (input) flags = GPIOD_IN; else flags = GPIOD_OUT_LOW; device_property_read_u32(&pdev->dev, "active-delay-ms", &active_delay); device_property_read_u32(&pdev->dev, "inactive-delay-ms", &inactive_delay); device_property_read_u32(&pdev->dev, "timeout-ms", &timeout); reset_gpio = devm_gpiod_get(&pdev->dev, NULL, flags); if (IS_ERR(reset_gpio)) return PTR_ERR(reset_gpio); pm_power_off = &gpio_poweroff_do_poweroff; return 0; } static int gpio_poweroff_remove(struct platform_device *pdev) { if (pm_power_off == &gpio_poweroff_do_poweroff) pm_power_off = NULL; return 0; } static const struct of_device_id of_gpio_poweroff_match[] = { { .compatible = "gpio-poweroff", }, {}, }; MODULE_DEVICE_TABLE(of, of_gpio_poweroff_match); static struct platform_driver gpio_poweroff_driver = { .probe = gpio_poweroff_probe, .remove = gpio_poweroff_remove, .driver = { .name = "poweroff-gpio", .of_match_table = of_gpio_poweroff_match, }, }; module_platform_driver(gpio_poweroff_driver); MODULE_AUTHOR("Jamie Lentin <[email protected]>"); MODULE_DESCRIPTION("GPIO poweroff driver"); MODULE_ALIAS("platform:poweroff-gpio");
linux-master
drivers/power/reset/gpio-poweroff.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2021 Emil Renner Berthing */ #include <linux/mfd/tps65086.h> #include <linux/mod_devicetable.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/reboot.h> struct tps65086_restart { struct notifier_block handler; struct device *dev; }; static int tps65086_restart_notify(struct notifier_block *this, unsigned long mode, void *cmd) { struct tps65086_restart *tps65086_restart = container_of(this, struct tps65086_restart, handler); struct tps65086 *tps65086 = dev_get_drvdata(tps65086_restart->dev->parent); int ret; ret = regmap_write(tps65086->regmap, TPS65086_FORCESHUTDN, 1); if (ret) { dev_err(tps65086_restart->dev, "%s: error writing to tps65086 pmic: %d\n", __func__, ret); return NOTIFY_DONE; } /* give it a little time */ mdelay(200); WARN_ON(1); return NOTIFY_DONE; } static int tps65086_restart_probe(struct platform_device *pdev) { struct tps65086_restart *tps65086_restart; int ret; tps65086_restart = devm_kzalloc(&pdev->dev, sizeof(*tps65086_restart), GFP_KERNEL); if (!tps65086_restart) return -ENOMEM; platform_set_drvdata(pdev, tps65086_restart); tps65086_restart->handler.notifier_call = tps65086_restart_notify; tps65086_restart->handler.priority = 192; tps65086_restart->dev = &pdev->dev; ret = register_restart_handler(&tps65086_restart->handler); if (ret) { dev_err(&pdev->dev, "%s: cannot register restart handler: %d\n", __func__, ret); return -ENODEV; } return 0; } static int tps65086_restart_remove(struct platform_device *pdev) { struct tps65086_restart *tps65086_restart = platform_get_drvdata(pdev); int ret; ret = unregister_restart_handler(&tps65086_restart->handler); if (ret) { dev_err(&pdev->dev, "%s: cannot unregister restart handler: %d\n", __func__, ret); return -ENODEV; } return 0; } static const struct platform_device_id tps65086_restart_id_table[] = { { "tps65086-reset", }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(platform, tps65086_restart_id_table); static struct platform_driver tps65086_restart_driver = { .driver = { .name = "tps65086-restart", }, .probe = tps65086_restart_probe, .remove = tps65086_restart_remove, .id_table = tps65086_restart_id_table, }; module_platform_driver(tps65086_restart_driver); MODULE_AUTHOR("Emil Renner Berthing <[email protected]>"); MODULE_DESCRIPTION("TPS65086 restart driver");
linux-master
drivers/power/reset/tps65086-restart.c
// SPDX-License-Identifier: GPL-2.0+ /* * Poweroff & reset driver for Actions Semi ATC260x PMICs * * Copyright (c) 2020 Cristian Ciocaltea <[email protected]> */ #include <linux/delay.h> #include <linux/mfd/atc260x/core.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/reboot.h> #include <linux/regmap.h> struct atc260x_pwrc { struct device *dev; struct regmap *regmap; struct notifier_block restart_nb; int (*do_poweroff)(const struct atc260x_pwrc *pwrc, bool restart); }; /* Global variable needed only for pm_power_off */ static struct atc260x_pwrc *atc260x_pwrc_data; static int atc2603c_do_poweroff(const struct atc260x_pwrc *pwrc, bool restart) { int ret, deep_sleep = 0; uint reg_mask, reg_val; /* S4-Deep Sleep Mode is NOT available for WALL/USB power */ if (!restart && !power_supply_is_system_supplied()) { deep_sleep = 1; dev_info(pwrc->dev, "Enabling S4-Deep Sleep Mode"); } /* Update wakeup sources */ reg_val = ATC2603C_PMU_SYS_CTL0_ONOFF_LONG_WK_EN | (restart ? ATC2603C_PMU_SYS_CTL0_RESET_WK_EN : ATC2603C_PMU_SYS_CTL0_ONOFF_SHORT_WK_EN); ret = regmap_update_bits(pwrc->regmap, ATC2603C_PMU_SYS_CTL0, ATC2603C_PMU_SYS_CTL0_WK_ALL, reg_val); if (ret) dev_warn(pwrc->dev, "failed to write SYS_CTL0: %d\n", ret); /* Update power mode */ reg_mask = ATC2603C_PMU_SYS_CTL3_EN_S2 | ATC2603C_PMU_SYS_CTL3_EN_S3; ret = regmap_update_bits(pwrc->regmap, ATC2603C_PMU_SYS_CTL3, reg_mask, deep_sleep ? 0 : ATC2603C_PMU_SYS_CTL3_EN_S3); if (ret) { dev_err(pwrc->dev, "failed to write SYS_CTL3: %d\n", ret); return ret; } /* Trigger poweroff / restart sequence */ reg_mask = restart ? ATC2603C_PMU_SYS_CTL0_RESTART_EN : ATC2603C_PMU_SYS_CTL1_EN_S1; reg_val = restart ? ATC2603C_PMU_SYS_CTL0_RESTART_EN : 0; ret = regmap_update_bits(pwrc->regmap, restart ? ATC2603C_PMU_SYS_CTL0 : ATC2603C_PMU_SYS_CTL1, reg_mask, reg_val); if (ret) { dev_err(pwrc->dev, "failed to write SYS_CTL%d: %d\n", restart ? 0 : 1, ret); return ret; } /* Wait for trigger completion */ mdelay(200); return 0; } static int atc2609a_do_poweroff(const struct atc260x_pwrc *pwrc, bool restart) { int ret, deep_sleep = 0; uint reg_mask, reg_val; /* S4-Deep Sleep Mode is NOT available for WALL/USB power */ if (!restart && !power_supply_is_system_supplied()) { deep_sleep = 1; dev_info(pwrc->dev, "Enabling S4-Deep Sleep Mode"); } /* Update wakeup sources */ reg_val = ATC2609A_PMU_SYS_CTL0_ONOFF_LONG_WK_EN | (restart ? ATC2609A_PMU_SYS_CTL0_RESET_WK_EN : ATC2609A_PMU_SYS_CTL0_ONOFF_SHORT_WK_EN); ret = regmap_update_bits(pwrc->regmap, ATC2609A_PMU_SYS_CTL0, ATC2609A_PMU_SYS_CTL0_WK_ALL, reg_val); if (ret) dev_warn(pwrc->dev, "failed to write SYS_CTL0: %d\n", ret); /* Update power mode */ reg_mask = ATC2609A_PMU_SYS_CTL3_EN_S2 | ATC2609A_PMU_SYS_CTL3_EN_S3; ret = regmap_update_bits(pwrc->regmap, ATC2609A_PMU_SYS_CTL3, reg_mask, deep_sleep ? 0 : ATC2609A_PMU_SYS_CTL3_EN_S3); if (ret) { dev_err(pwrc->dev, "failed to write SYS_CTL3: %d\n", ret); return ret; } /* Trigger poweroff / restart sequence */ reg_mask = restart ? ATC2609A_PMU_SYS_CTL0_RESTART_EN : ATC2609A_PMU_SYS_CTL1_EN_S1; reg_val = restart ? ATC2609A_PMU_SYS_CTL0_RESTART_EN : 0; ret = regmap_update_bits(pwrc->regmap, restart ? ATC2609A_PMU_SYS_CTL0 : ATC2609A_PMU_SYS_CTL1, reg_mask, reg_val); if (ret) { dev_err(pwrc->dev, "failed to write SYS_CTL%d: %d\n", restart ? 0 : 1, ret); return ret; } /* Wait for trigger completion */ mdelay(200); return 0; } static int atc2603c_init(const struct atc260x_pwrc *pwrc) { int ret; /* * Delay transition from S2/S3 to S1 in order to avoid * DDR init failure in Bootloader. */ ret = regmap_update_bits(pwrc->regmap, ATC2603C_PMU_SYS_CTL3, ATC2603C_PMU_SYS_CTL3_S2S3TOS1_TIMER_EN, ATC2603C_PMU_SYS_CTL3_S2S3TOS1_TIMER_EN); if (ret) dev_warn(pwrc->dev, "failed to write SYS_CTL3: %d\n", ret); /* Set wakeup sources */ ret = regmap_update_bits(pwrc->regmap, ATC2603C_PMU_SYS_CTL0, ATC2603C_PMU_SYS_CTL0_WK_ALL, ATC2603C_PMU_SYS_CTL0_HDSW_WK_EN | ATC2603C_PMU_SYS_CTL0_ONOFF_LONG_WK_EN); if (ret) dev_warn(pwrc->dev, "failed to write SYS_CTL0: %d\n", ret); return ret; } static int atc2609a_init(const struct atc260x_pwrc *pwrc) { int ret; /* Set wakeup sources */ ret = regmap_update_bits(pwrc->regmap, ATC2609A_PMU_SYS_CTL0, ATC2609A_PMU_SYS_CTL0_WK_ALL, ATC2609A_PMU_SYS_CTL0_HDSW_WK_EN | ATC2609A_PMU_SYS_CTL0_ONOFF_LONG_WK_EN); if (ret) dev_warn(pwrc->dev, "failed to write SYS_CTL0: %d\n", ret); return ret; } static void atc260x_pwrc_pm_handler(void) { atc260x_pwrc_data->do_poweroff(atc260x_pwrc_data, false); WARN_ONCE(1, "Unable to power off system\n"); } static int atc260x_pwrc_restart_handler(struct notifier_block *nb, unsigned long mode, void *cmd) { struct atc260x_pwrc *pwrc = container_of(nb, struct atc260x_pwrc, restart_nb); pwrc->do_poweroff(pwrc, true); return NOTIFY_DONE; } static int atc260x_pwrc_probe(struct platform_device *pdev) { struct atc260x *atc260x = dev_get_drvdata(pdev->dev.parent); struct atc260x_pwrc *priv; int ret; priv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; priv->dev = &pdev->dev; priv->regmap = atc260x->regmap; priv->restart_nb.notifier_call = atc260x_pwrc_restart_handler; priv->restart_nb.priority = 192; switch (atc260x->ic_type) { case ATC2603C: priv->do_poweroff = atc2603c_do_poweroff; ret = atc2603c_init(priv); break; case ATC2609A: priv->do_poweroff = atc2609a_do_poweroff; ret = atc2609a_init(priv); break; default: dev_err(priv->dev, "Poweroff not supported for ATC260x PMIC type: %u\n", atc260x->ic_type); return -EINVAL; } if (ret) return ret; platform_set_drvdata(pdev, priv); if (!pm_power_off) { atc260x_pwrc_data = priv; pm_power_off = atc260x_pwrc_pm_handler; } else { dev_warn(priv->dev, "Poweroff callback already assigned\n"); } ret = register_restart_handler(&priv->restart_nb); if (ret) dev_err(priv->dev, "failed to register restart handler: %d\n", ret); return ret; } static int atc260x_pwrc_remove(struct platform_device *pdev) { struct atc260x_pwrc *priv = platform_get_drvdata(pdev); if (atc260x_pwrc_data == priv) { pm_power_off = NULL; atc260x_pwrc_data = NULL; } unregister_restart_handler(&priv->restart_nb); return 0; } static struct platform_driver atc260x_pwrc_driver = { .probe = atc260x_pwrc_probe, .remove = atc260x_pwrc_remove, .driver = { .name = "atc260x-pwrc", }, }; module_platform_driver(atc260x_pwrc_driver); MODULE_DESCRIPTION("Poweroff & reset driver for ATC260x PMICs"); MODULE_AUTHOR("Cristian Ciocaltea <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/power/reset/atc260x-poweroff.c
// SPDX-License-Identifier: GPL-2.0 /* * Gemini power management controller * Copyright (C) 2017 Linus Walleij <[email protected]> * * Inspired by code from the SL3516 board support by Jason Lee * Inspired by code from Janos Laube <[email protected]> */ #include <linux/of.h> #include <linux/of_platform.h> #include <linux/platform_device.h> #include <linux/pm.h> #include <linux/bitops.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/reboot.h> #define GEMINI_PWC_ID 0x00010500 #define GEMINI_PWC_IDREG 0x00 #define GEMINI_PWC_CTRLREG 0x04 #define GEMINI_PWC_STATREG 0x08 #define GEMINI_CTRL_SHUTDOWN BIT(0) #define GEMINI_CTRL_ENABLE BIT(1) #define GEMINI_CTRL_IRQ_CLR BIT(2) #define GEMINI_STAT_CIR BIT(4) #define GEMINI_STAT_RTC BIT(5) #define GEMINI_STAT_POWERBUTTON BIT(6) struct gemini_powercon { struct device *dev; void __iomem *base; }; static irqreturn_t gemini_powerbutton_interrupt(int irq, void *data) { struct gemini_powercon *gpw = data; u32 val; /* ACK the IRQ */ val = readl(gpw->base + GEMINI_PWC_CTRLREG); val |= GEMINI_CTRL_IRQ_CLR; writel(val, gpw->base + GEMINI_PWC_CTRLREG); val = readl(gpw->base + GEMINI_PWC_STATREG); val &= 0x70U; switch (val) { case GEMINI_STAT_CIR: /* * We do not yet have a driver for the infrared * controller so it can cause spurious poweroff * events. Ignore those for now. */ dev_info(gpw->dev, "infrared poweroff - ignored\n"); break; case GEMINI_STAT_RTC: dev_info(gpw->dev, "RTC poweroff\n"); orderly_poweroff(true); break; case GEMINI_STAT_POWERBUTTON: dev_info(gpw->dev, "poweroff button pressed\n"); orderly_poweroff(true); break; default: dev_info(gpw->dev, "other power management IRQ\n"); break; } return IRQ_HANDLED; } /* This callback needs this static local as it has void as argument */ static struct gemini_powercon *gpw_poweroff; static void gemini_poweroff(void) { struct gemini_powercon *gpw = gpw_poweroff; u32 val; dev_crit(gpw->dev, "Gemini power off\n"); val = readl(gpw->base + GEMINI_PWC_CTRLREG); val |= GEMINI_CTRL_ENABLE | GEMINI_CTRL_IRQ_CLR; writel(val, gpw->base + GEMINI_PWC_CTRLREG); val &= ~GEMINI_CTRL_ENABLE; val |= GEMINI_CTRL_SHUTDOWN; writel(val, gpw->base + GEMINI_PWC_CTRLREG); } static int gemini_poweroff_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct gemini_powercon *gpw; u32 val; int irq; int ret; gpw = devm_kzalloc(dev, sizeof(*gpw), GFP_KERNEL); if (!gpw) return -ENOMEM; gpw->base = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(gpw->base)) return PTR_ERR(gpw->base); irq = platform_get_irq(pdev, 0); if (irq < 0) return irq; gpw->dev = dev; val = readl(gpw->base + GEMINI_PWC_IDREG); val &= 0xFFFFFF00U; if (val != GEMINI_PWC_ID) { dev_err(dev, "wrong power controller ID: %08x\n", val); return -ENODEV; } /* * Enable the power controller. This is crucial on Gemini * systems: if this is not done, pressing the power button * will result in unconditional poweroff without any warning. * This makes the kernel handle the poweroff. */ val = readl(gpw->base + GEMINI_PWC_CTRLREG); val |= GEMINI_CTRL_ENABLE; writel(val, gpw->base + GEMINI_PWC_CTRLREG); /* Clear the IRQ */ val = readl(gpw->base + GEMINI_PWC_CTRLREG); val |= GEMINI_CTRL_IRQ_CLR; writel(val, gpw->base + GEMINI_PWC_CTRLREG); /* Wait for this to clear */ val = readl(gpw->base + GEMINI_PWC_STATREG); while (val & 0x70U) val = readl(gpw->base + GEMINI_PWC_STATREG); /* Clear the IRQ again */ val = readl(gpw->base + GEMINI_PWC_CTRLREG); val |= GEMINI_CTRL_IRQ_CLR; writel(val, gpw->base + GEMINI_PWC_CTRLREG); ret = devm_request_irq(dev, irq, gemini_powerbutton_interrupt, 0, "poweroff", gpw); if (ret) return ret; pm_power_off = gemini_poweroff; gpw_poweroff = gpw; dev_info(dev, "Gemini poweroff driver registered\n"); return 0; } static const struct of_device_id gemini_poweroff_of_match[] = { { .compatible = "cortina,gemini-power-controller", }, {} }; static struct platform_driver gemini_poweroff_driver = { .probe = gemini_poweroff_probe, .driver = { .name = "gemini-poweroff", .of_match_table = gemini_poweroff_of_match, }, }; builtin_platform_driver(gemini_poweroff_driver);
linux-master
drivers/power/reset/gemini-poweroff.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (c) 2016, Fuzhou Rockchip Electronics Co., Ltd */ #include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/reboot.h> #include <linux/regmap.h> #include <linux/mfd/syscon.h> #include <linux/reboot-mode.h> struct syscon_reboot_mode { struct regmap *map; struct reboot_mode_driver reboot; u32 offset; u32 mask; }; static int syscon_reboot_mode_write(struct reboot_mode_driver *reboot, unsigned int magic) { struct syscon_reboot_mode *syscon_rbm; int ret; syscon_rbm = container_of(reboot, struct syscon_reboot_mode, reboot); ret = regmap_update_bits(syscon_rbm->map, syscon_rbm->offset, syscon_rbm->mask, magic); if (ret < 0) dev_err(reboot->dev, "update reboot mode bits failed\n"); return ret; } static int syscon_reboot_mode_probe(struct platform_device *pdev) { int ret; struct syscon_reboot_mode *syscon_rbm; syscon_rbm = devm_kzalloc(&pdev->dev, sizeof(*syscon_rbm), GFP_KERNEL); if (!syscon_rbm) return -ENOMEM; syscon_rbm->reboot.dev = &pdev->dev; syscon_rbm->reboot.write = syscon_reboot_mode_write; syscon_rbm->mask = 0xffffffff; syscon_rbm->map = syscon_node_to_regmap(pdev->dev.parent->of_node); if (IS_ERR(syscon_rbm->map)) return PTR_ERR(syscon_rbm->map); if (of_property_read_u32(pdev->dev.of_node, "offset", &syscon_rbm->offset)) return -EINVAL; of_property_read_u32(pdev->dev.of_node, "mask", &syscon_rbm->mask); ret = devm_reboot_mode_register(&pdev->dev, &syscon_rbm->reboot); if (ret) dev_err(&pdev->dev, "can't register reboot mode\n"); return ret; } static const struct of_device_id syscon_reboot_mode_of_match[] = { { .compatible = "syscon-reboot-mode" }, {} }; MODULE_DEVICE_TABLE(of, syscon_reboot_mode_of_match); static struct platform_driver syscon_reboot_mode_driver = { .probe = syscon_reboot_mode_probe, .driver = { .name = "syscon-reboot-mode", .of_match_table = syscon_reboot_mode_of_match, }, }; module_platform_driver(syscon_reboot_mode_driver); MODULE_AUTHOR("Andy Yan <[email protected]"); MODULE_DESCRIPTION("SYSCON reboot mode driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/power/reset/syscon-reboot-mode.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * LTC2952 (PowerPath) driver * * Copyright (C) 2014, Xsens Technologies BV <[email protected]> * Maintainer: René Moll <[email protected]> * * ---------------------------------------- * - Description * ---------------------------------------- * * This driver is to be used with an external PowerPath Controller (LTC2952). * Its function is to determine when a external shut down is triggered * and react by properly shutting down the system. * * This driver expects a device tree with a ltc2952 entry for pin mapping. * * ---------------------------------------- * - GPIO * ---------------------------------------- * * The following GPIOs are used: * - trigger (input) * A level change indicates the shut-down trigger. If it's state reverts * within the time-out defined by trigger_delay, the shut down is not * executed. If no pin is assigned to this input, the driver will start the * watchdog toggle immediately. The chip will only power off the system if * it is requested to do so through the kill line. * * - watchdog (output) * Once a shut down is triggered, the driver will toggle this signal, * with an internal (wde_interval) to stall the hardware shut down. * * - kill (output) * The last action during shut down is triggering this signalling, such * that the PowerPath Control will power down the hardware. * * ---------------------------------------- * - Interrupts * ---------------------------------------- * * The driver requires a non-shared, edge-triggered interrupt on the trigger * GPIO. */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/device.h> #include <linux/platform_device.h> #include <linux/ktime.h> #include <linux/slab.h> #include <linux/kmod.h> #include <linux/module.h> #include <linux/panic_notifier.h> #include <linux/mod_devicetable.h> #include <linux/gpio/consumer.h> #include <linux/reboot.h> #include <linux/property.h> struct ltc2952_poweroff { struct hrtimer timer_trigger; struct hrtimer timer_wde; ktime_t trigger_delay; ktime_t wde_interval; struct device *dev; struct gpio_desc *gpio_trigger; struct gpio_desc *gpio_watchdog; struct gpio_desc *gpio_kill; bool kernel_panic; struct notifier_block panic_notifier; }; #define to_ltc2952(p, m) container_of(p, struct ltc2952_poweroff, m) /* * This global variable is only needed for pm_power_off. We should * remove it entirely once we don't need the global state anymore. */ static struct ltc2952_poweroff *ltc2952_data; /** * ltc2952_poweroff_timer_wde - Timer callback * Toggles the watchdog reset signal each wde_interval * * @timer: corresponding timer * * Returns HRTIMER_RESTART for an infinite loop which will only stop when the * machine actually shuts down */ static enum hrtimer_restart ltc2952_poweroff_timer_wde(struct hrtimer *timer) { int state; struct ltc2952_poweroff *data = to_ltc2952(timer, timer_wde); if (data->kernel_panic) return HRTIMER_NORESTART; state = gpiod_get_value(data->gpio_watchdog); gpiod_set_value(data->gpio_watchdog, !state); hrtimer_forward_now(timer, data->wde_interval); return HRTIMER_RESTART; } static void ltc2952_poweroff_start_wde(struct ltc2952_poweroff *data) { hrtimer_start(&data->timer_wde, data->wde_interval, HRTIMER_MODE_REL); } static enum hrtimer_restart ltc2952_poweroff_timer_trigger(struct hrtimer *timer) { struct ltc2952_poweroff *data = to_ltc2952(timer, timer_trigger); ltc2952_poweroff_start_wde(data); dev_info(data->dev, "executing shutdown\n"); orderly_poweroff(true); return HRTIMER_NORESTART; } /** * ltc2952_poweroff_handler - Interrupt handler * Triggered each time the trigger signal changes state and (de)activates a * time-out (timer_trigger). Once the time-out is actually reached the shut * down is executed. * * @irq: IRQ number * @dev_id: pointer to the main data structure */ static irqreturn_t ltc2952_poweroff_handler(int irq, void *dev_id) { struct ltc2952_poweroff *data = dev_id; if (data->kernel_panic || hrtimer_active(&data->timer_wde)) { /* shutdown is already triggered, nothing to do any more */ return IRQ_HANDLED; } if (gpiod_get_value(data->gpio_trigger)) { hrtimer_start(&data->timer_trigger, data->trigger_delay, HRTIMER_MODE_REL); } else { hrtimer_cancel(&data->timer_trigger); } return IRQ_HANDLED; } static void ltc2952_poweroff_kill(void) { gpiod_set_value(ltc2952_data->gpio_kill, 1); } static void ltc2952_poweroff_default(struct ltc2952_poweroff *data) { data->wde_interval = 300L * NSEC_PER_MSEC; data->trigger_delay = ktime_set(2, 500L * NSEC_PER_MSEC); hrtimer_init(&data->timer_trigger, CLOCK_MONOTONIC, HRTIMER_MODE_REL); data->timer_trigger.function = ltc2952_poweroff_timer_trigger; hrtimer_init(&data->timer_wde, CLOCK_MONOTONIC, HRTIMER_MODE_REL); data->timer_wde.function = ltc2952_poweroff_timer_wde; } static int ltc2952_poweroff_init(struct platform_device *pdev) { int ret; u32 trigger_delay_ms; struct ltc2952_poweroff *data = platform_get_drvdata(pdev); ltc2952_poweroff_default(data); if (!device_property_read_u32(&pdev->dev, "trigger-delay-ms", &trigger_delay_ms)) { data->trigger_delay = ktime_set(trigger_delay_ms / MSEC_PER_SEC, (trigger_delay_ms % MSEC_PER_SEC) * NSEC_PER_MSEC); } data->gpio_watchdog = devm_gpiod_get(&pdev->dev, "watchdog", GPIOD_OUT_LOW); if (IS_ERR(data->gpio_watchdog)) { ret = PTR_ERR(data->gpio_watchdog); dev_err(&pdev->dev, "unable to claim gpio \"watchdog\"\n"); return ret; } data->gpio_kill = devm_gpiod_get(&pdev->dev, "kill", GPIOD_OUT_LOW); if (IS_ERR(data->gpio_kill)) { ret = PTR_ERR(data->gpio_kill); dev_err(&pdev->dev, "unable to claim gpio \"kill\"\n"); return ret; } data->gpio_trigger = devm_gpiod_get_optional(&pdev->dev, "trigger", GPIOD_IN); if (IS_ERR(data->gpio_trigger)) { /* * It's not a problem if the trigger gpio isn't available, but * it is worth a warning if its use was defined in the device * tree. */ dev_err(&pdev->dev, "unable to claim gpio \"trigger\"\n"); data->gpio_trigger = NULL; } if (devm_request_irq(&pdev->dev, gpiod_to_irq(data->gpio_trigger), ltc2952_poweroff_handler, (IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING), "ltc2952-poweroff", data)) { /* * Some things may have happened: * - No trigger input was defined * - Claiming the GPIO failed * - We could not map to an IRQ * - We couldn't register an interrupt handler * * None of these really are problems, but all of them * disqualify the push button from controlling the power. * * It is therefore important to note that if the ltc2952 * detects a button press for long enough, it will still start * its own powerdown window and cut the power on us if we don't * start the watchdog trigger. */ if (data->gpio_trigger) { dev_warn(&pdev->dev, "unable to configure the trigger interrupt\n"); devm_gpiod_put(&pdev->dev, data->gpio_trigger); data->gpio_trigger = NULL; } dev_info(&pdev->dev, "power down trigger input will not be used\n"); ltc2952_poweroff_start_wde(data); } return 0; } static int ltc2952_poweroff_notify_panic(struct notifier_block *nb, unsigned long code, void *unused) { struct ltc2952_poweroff *data = to_ltc2952(nb, panic_notifier); data->kernel_panic = true; return NOTIFY_DONE; } static int ltc2952_poweroff_probe(struct platform_device *pdev) { int ret; struct ltc2952_poweroff *data; if (pm_power_off) { dev_err(&pdev->dev, "pm_power_off already registered"); return -EBUSY; } data = devm_kzalloc(&pdev->dev, sizeof(*data), GFP_KERNEL); if (!data) return -ENOMEM; data->dev = &pdev->dev; platform_set_drvdata(pdev, data); ret = ltc2952_poweroff_init(pdev); if (ret) return ret; /* TODO: remove ltc2952_data */ ltc2952_data = data; pm_power_off = ltc2952_poweroff_kill; data->panic_notifier.notifier_call = ltc2952_poweroff_notify_panic; atomic_notifier_chain_register(&panic_notifier_list, &data->panic_notifier); dev_info(&pdev->dev, "probe successful\n"); return 0; } static int ltc2952_poweroff_remove(struct platform_device *pdev) { struct ltc2952_poweroff *data = platform_get_drvdata(pdev); pm_power_off = NULL; hrtimer_cancel(&data->timer_trigger); hrtimer_cancel(&data->timer_wde); atomic_notifier_chain_unregister(&panic_notifier_list, &data->panic_notifier); return 0; } static const struct of_device_id of_ltc2952_poweroff_match[] = { { .compatible = "lltc,ltc2952"}, {}, }; MODULE_DEVICE_TABLE(of, of_ltc2952_poweroff_match); static struct platform_driver ltc2952_poweroff_driver = { .probe = ltc2952_poweroff_probe, .remove = ltc2952_poweroff_remove, .driver = { .name = "ltc2952-poweroff", .of_match_table = of_ltc2952_poweroff_match, }, }; module_platform_driver(ltc2952_poweroff_driver); MODULE_AUTHOR("René Moll <[email protected]>"); MODULE_DESCRIPTION("LTC PowerPath power-off driver");
linux-master
drivers/power/reset/ltc2952-poweroff.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (C) 2016 Imagination Technologies * Author: Paul Burton <[email protected]> */ #include <linux/delay.h> #include <linux/io.h> #include <linux/module.h> #include <linux/pci.h> #include <linux/pm.h> static struct pci_dev *pm_dev; static resource_size_t io_offset; enum piix4_pm_io_reg { PIIX4_FUNC3IO_PMSTS = 0x00, #define PIIX4_FUNC3IO_PMSTS_PWRBTN_STS BIT(8) PIIX4_FUNC3IO_PMCNTRL = 0x04, #define PIIX4_FUNC3IO_PMCNTRL_SUS_EN BIT(13) #define PIIX4_FUNC3IO_PMCNTRL_SUS_TYP_SOFF (0x0 << 10) }; #define PIIX4_SUSPEND_MAGIC 0x00120002 static const int piix4_pm_io_region = PCI_BRIDGE_RESOURCES; static void piix4_poweroff(void) { int spec_devid; u16 sts; /* Ensure the power button status is clear */ while (1) { sts = inw(io_offset + PIIX4_FUNC3IO_PMSTS); if (!(sts & PIIX4_FUNC3IO_PMSTS_PWRBTN_STS)) break; outw(sts, io_offset + PIIX4_FUNC3IO_PMSTS); } /* Enable entry to suspend */ outw(PIIX4_FUNC3IO_PMCNTRL_SUS_TYP_SOFF | PIIX4_FUNC3IO_PMCNTRL_SUS_EN, io_offset + PIIX4_FUNC3IO_PMCNTRL); /* If the special cycle occurs too soon this doesn't work... */ mdelay(10); /* * The PIIX4 will enter the suspend state only after seeing a special * cycle with the correct magic data on the PCI bus. Generate that * cycle now. */ spec_devid = PCI_DEVID(0, PCI_DEVFN(0x1f, 0x7)); pci_bus_write_config_dword(pm_dev->bus, spec_devid, 0, PIIX4_SUSPEND_MAGIC); /* Give the system some time to power down, then error */ mdelay(1000); pr_emerg("Unable to poweroff system\n"); } static int piix4_poweroff_probe(struct pci_dev *dev, const struct pci_device_id *id) { int res; if (pm_dev) return -EINVAL; /* Request access to the PIIX4 PM IO registers */ res = pci_request_region(dev, piix4_pm_io_region, "PIIX4 PM IO registers"); if (res) { dev_err(&dev->dev, "failed to request PM IO registers: %d\n", res); return res; } pm_dev = dev; io_offset = pci_resource_start(dev, piix4_pm_io_region); pm_power_off = piix4_poweroff; return 0; } static void piix4_poweroff_remove(struct pci_dev *dev) { if (pm_power_off == piix4_poweroff) pm_power_off = NULL; pci_release_region(dev, piix4_pm_io_region); pm_dev = NULL; } static const struct pci_device_id piix4_poweroff_ids[] = { { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371AB_3) }, { 0 }, }; static struct pci_driver piix4_poweroff_driver = { .name = "piix4-poweroff", .id_table = piix4_poweroff_ids, .probe = piix4_poweroff_probe, .remove = piix4_poweroff_remove, }; module_pci_driver(piix4_poweroff_driver); MODULE_AUTHOR("Paul Burton <[email protected]>"); MODULE_LICENSE("GPL");
linux-master
drivers/power/reset/piix4-poweroff.c
// SPDX-License-Identifier: GPL-2.0-only /* * Power off driver for ams AS3722 device. * * Copyright (c) 2013, NVIDIA CORPORATION. All rights reserved. * * Author: Laxman Dewangan <[email protected]> */ #include <linux/mfd/as3722.h> #include <linux/module.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/slab.h> struct as3722_poweroff { struct device *dev; struct as3722 *as3722; }; static struct as3722_poweroff *as3722_pm_poweroff; static void as3722_pm_power_off(void) { int ret; if (!as3722_pm_poweroff) { pr_err("AS3722 poweroff is not initialised\n"); return; } ret = as3722_update_bits(as3722_pm_poweroff->as3722, AS3722_RESET_CONTROL_REG, AS3722_POWER_OFF, AS3722_POWER_OFF); if (ret < 0) dev_err(as3722_pm_poweroff->dev, "RESET_CONTROL_REG update failed, %d\n", ret); } static int as3722_poweroff_probe(struct platform_device *pdev) { struct as3722_poweroff *as3722_poweroff; struct device_node *np = pdev->dev.parent->of_node; if (!np) return -EINVAL; if (!of_property_read_bool(np, "ams,system-power-controller")) return 0; as3722_poweroff = devm_kzalloc(&pdev->dev, sizeof(*as3722_poweroff), GFP_KERNEL); if (!as3722_poweroff) return -ENOMEM; as3722_poweroff->as3722 = dev_get_drvdata(pdev->dev.parent); as3722_poweroff->dev = &pdev->dev; as3722_pm_poweroff = as3722_poweroff; if (!pm_power_off) pm_power_off = as3722_pm_power_off; return 0; } static int as3722_poweroff_remove(struct platform_device *pdev) { if (pm_power_off == as3722_pm_power_off) pm_power_off = NULL; as3722_pm_poweroff = NULL; return 0; } static struct platform_driver as3722_poweroff_driver = { .driver = { .name = "as3722-power-off", }, .probe = as3722_poweroff_probe, .remove = as3722_poweroff_remove, }; module_platform_driver(as3722_poweroff_driver); MODULE_DESCRIPTION("Power off driver for ams AS3722 PMIC Device"); MODULE_ALIAS("platform:as3722-power-off"); MODULE_AUTHOR("Laxman Dewangan <[email protected]>");
linux-master
drivers/power/reset/as3722-poweroff.c
// SPDX-License-Identifier: GPL-2.0-only /* * TI keystone reboot driver * * Copyright (C) 2014 Texas Instruments Incorporated. https://www.ti.com/ * * Author: Ivan Khoronzhuk <[email protected]> */ #include <linux/io.h> #include <linux/module.h> #include <linux/notifier.h> #include <linux/platform_device.h> #include <linux/reboot.h> #include <linux/regmap.h> #include <linux/mfd/syscon.h> #include <linux/of.h> #define RSTYPE_RG 0x0 #define RSCTRL_RG 0x4 #define RSCFG_RG 0x8 #define RSISO_RG 0xc #define RSCTRL_KEY_MASK 0x0000ffff #define RSCTRL_RESET_MASK BIT(16) #define RSCTRL_KEY 0x5a69 #define RSMUX_OMODE_MASK 0xe #define RSMUX_OMODE_RESET_ON 0xa #define RSMUX_OMODE_RESET_OFF 0x0 #define RSMUX_LOCK_MASK 0x1 #define RSMUX_LOCK_SET 0x1 #define RSCFG_RSTYPE_SOFT 0x300f #define RSCFG_RSTYPE_HARD 0x0 #define WDT_MUX_NUMBER 0x4 static int rspll_offset; static struct regmap *pllctrl_regs; /** * rsctrl_enable_rspll_write - enable access to RSCTRL, RSCFG * To be able to access to RSCTRL, RSCFG registers * we have to write a key before */ static inline int rsctrl_enable_rspll_write(void) { return regmap_update_bits(pllctrl_regs, rspll_offset + RSCTRL_RG, RSCTRL_KEY_MASK, RSCTRL_KEY); } static int rsctrl_restart_handler(struct notifier_block *this, unsigned long mode, void *cmd) { /* enable write access to RSTCTRL */ rsctrl_enable_rspll_write(); /* reset the SOC */ regmap_update_bits(pllctrl_regs, rspll_offset + RSCTRL_RG, RSCTRL_RESET_MASK, 0); return NOTIFY_DONE; } static struct notifier_block rsctrl_restart_nb = { .notifier_call = rsctrl_restart_handler, .priority = 128, }; static const struct of_device_id rsctrl_of_match[] = { {.compatible = "ti,keystone-reset", }, {}, }; MODULE_DEVICE_TABLE(of, rsctrl_of_match); static int rsctrl_probe(struct platform_device *pdev) { int i; int ret; u32 val; unsigned int rg; u32 rsmux_offset; struct regmap *devctrl_regs; struct device *dev = &pdev->dev; struct device_node *np = dev->of_node; if (!np) return -ENODEV; /* get regmaps */ pllctrl_regs = syscon_regmap_lookup_by_phandle(np, "ti,syscon-pll"); if (IS_ERR(pllctrl_regs)) return PTR_ERR(pllctrl_regs); devctrl_regs = syscon_regmap_lookup_by_phandle(np, "ti,syscon-dev"); if (IS_ERR(devctrl_regs)) return PTR_ERR(devctrl_regs); ret = of_property_read_u32_index(np, "ti,syscon-pll", 1, &rspll_offset); if (ret) { dev_err(dev, "couldn't read the reset pll offset!\n"); return -EINVAL; } ret = of_property_read_u32_index(np, "ti,syscon-dev", 1, &rsmux_offset); if (ret) { dev_err(dev, "couldn't read the rsmux offset!\n"); return -EINVAL; } /* set soft/hard reset */ val = of_property_read_bool(np, "ti,soft-reset"); val = val ? RSCFG_RSTYPE_SOFT : RSCFG_RSTYPE_HARD; ret = rsctrl_enable_rspll_write(); if (ret) return ret; ret = regmap_write(pllctrl_regs, rspll_offset + RSCFG_RG, val); if (ret) return ret; /* disable a reset isolation for all module clocks */ ret = regmap_write(pllctrl_regs, rspll_offset + RSISO_RG, 0); if (ret) return ret; /* enable a reset for watchdogs from wdt-list */ for (i = 0; i < WDT_MUX_NUMBER; i++) { ret = of_property_read_u32_index(np, "ti,wdt-list", i, &val); if (ret == -EOVERFLOW && !i) { dev_err(dev, "ti,wdt-list property has to contain at" "least one entry\n"); return -EINVAL; } else if (ret) { break; } if (val >= WDT_MUX_NUMBER) { dev_err(dev, "ti,wdt-list property can contain " "only numbers < 4\n"); return -EINVAL; } rg = rsmux_offset + val * 4; ret = regmap_update_bits(devctrl_regs, rg, RSMUX_OMODE_MASK, RSMUX_OMODE_RESET_ON | RSMUX_LOCK_SET); if (ret) return ret; } ret = register_restart_handler(&rsctrl_restart_nb); if (ret) dev_err(dev, "cannot register restart handler (err=%d)\n", ret); return ret; } static struct platform_driver rsctrl_driver = { .probe = rsctrl_probe, .driver = { .name = KBUILD_MODNAME, .of_match_table = rsctrl_of_match, }, }; module_platform_driver(rsctrl_driver); MODULE_AUTHOR("Ivan Khoronzhuk <[email protected]>"); MODULE_DESCRIPTION("Texas Instruments keystone reset driver"); MODULE_ALIAS("platform:" KBUILD_MODNAME);
linux-master
drivers/power/reset/keystone-reset.c
// SPDX-License-Identifier: GPL-2.0-only // Copyright (C) 2013 Broadcom Corporation #include <linux/bitops.h> #include <linux/device.h> #include <linux/errno.h> #include <linux/init.h> #include <linux/io.h> #include <linux/jiffies.h> #include <linux/notifier.h> #include <linux/of_address.h> #include <linux/of_irq.h> #include <linux/of_platform.h> #include <linux/platform_device.h> #include <linux/printk.h> #include <linux/reboot.h> #include <linux/regmap.h> #include <linux/smp.h> #include <linux/mfd/syscon.h> #define RESET_SOURCE_ENABLE_REG 1 #define SW_MASTER_RESET_REG 2 static struct regmap *regmap; static u32 rst_src_en; static u32 sw_mstr_rst; struct reset_reg_mask { u32 rst_src_en_mask; u32 sw_mstr_rst_mask; }; static const struct reset_reg_mask *reset_masks; static int brcmstb_restart_handler(struct notifier_block *this, unsigned long mode, void *cmd) { int rc; u32 tmp; rc = regmap_write(regmap, rst_src_en, reset_masks->rst_src_en_mask); if (rc) { pr_err("failed to write rst_src_en (%d)\n", rc); return NOTIFY_DONE; } rc = regmap_read(regmap, rst_src_en, &tmp); if (rc) { pr_err("failed to read rst_src_en (%d)\n", rc); return NOTIFY_DONE; } rc = regmap_write(regmap, sw_mstr_rst, reset_masks->sw_mstr_rst_mask); if (rc) { pr_err("failed to write sw_mstr_rst (%d)\n", rc); return NOTIFY_DONE; } rc = regmap_read(regmap, sw_mstr_rst, &tmp); if (rc) { pr_err("failed to read sw_mstr_rst (%d)\n", rc); return NOTIFY_DONE; } while (1) ; return NOTIFY_DONE; } static struct notifier_block brcmstb_restart_nb = { .notifier_call = brcmstb_restart_handler, .priority = 128, }; static const struct reset_reg_mask reset_bits_40nm = { .rst_src_en_mask = BIT(0), .sw_mstr_rst_mask = BIT(0), }; static const struct reset_reg_mask reset_bits_65nm = { .rst_src_en_mask = BIT(3), .sw_mstr_rst_mask = BIT(31), }; static const struct of_device_id of_match[] = { { .compatible = "brcm,brcmstb-reboot", .data = &reset_bits_40nm }, { .compatible = "brcm,bcm7038-reboot", .data = &reset_bits_65nm }, {}, }; static int brcmstb_reboot_probe(struct platform_device *pdev) { int rc; struct device_node *np = pdev->dev.of_node; const struct of_device_id *of_id; of_id = of_match_node(of_match, np); if (!of_id) { pr_err("failed to look up compatible string\n"); return -EINVAL; } reset_masks = of_id->data; regmap = syscon_regmap_lookup_by_phandle(np, "syscon"); if (IS_ERR(regmap)) { pr_err("failed to get syscon phandle\n"); return -EINVAL; } rc = of_property_read_u32_index(np, "syscon", RESET_SOURCE_ENABLE_REG, &rst_src_en); if (rc) { pr_err("can't get rst_src_en offset (%d)\n", rc); return -EINVAL; } rc = of_property_read_u32_index(np, "syscon", SW_MASTER_RESET_REG, &sw_mstr_rst); if (rc) { pr_err("can't get sw_mstr_rst offset (%d)\n", rc); return -EINVAL; } rc = register_restart_handler(&brcmstb_restart_nb); if (rc) dev_err(&pdev->dev, "cannot register restart handler (err=%d)\n", rc); return rc; } static struct platform_driver brcmstb_reboot_driver = { .probe = brcmstb_reboot_probe, .driver = { .name = "brcmstb-reboot", .of_match_table = of_match, }, }; static int __init brcmstb_reboot_init(void) { return platform_driver_probe(&brcmstb_reboot_driver, brcmstb_reboot_probe); } subsys_initcall(brcmstb_reboot_init);
linux-master
drivers/power/reset/brcmstb-reboot.c
// SPDX-License-Identifier: GPL-2.0 /* * Power off through MediaTek PMIC * * Copyright (C) 2018 MediaTek Inc. * * Author: Sean Wang <[email protected]> * */ #include <linux/err.h> #include <linux/module.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/mfd/mt6397/core.h> #include <linux/mfd/mt6397/rtc.h> struct mt6323_pwrc { struct device *dev; struct regmap *regmap; u32 base; }; static struct mt6323_pwrc *mt_pwrc; static void mt6323_do_pwroff(void) { struct mt6323_pwrc *pwrc = mt_pwrc; unsigned int val; int ret; regmap_write(pwrc->regmap, pwrc->base + RTC_BBPU, RTC_BBPU_KEY); regmap_write(pwrc->regmap, pwrc->base + RTC_WRTGR_MT6323, 1); ret = regmap_read_poll_timeout(pwrc->regmap, pwrc->base + RTC_BBPU, val, !(val & RTC_BBPU_CBUSY), MTK_RTC_POLL_DELAY_US, MTK_RTC_POLL_TIMEOUT); if (ret) dev_err(pwrc->dev, "failed to write BBPU: %d\n", ret); /* Wait some time until system down, otherwise, notice with a warn */ mdelay(1000); WARN_ONCE(1, "Unable to power off system\n"); } static int mt6323_pwrc_probe(struct platform_device *pdev) { struct mt6397_chip *mt6397_chip = dev_get_drvdata(pdev->dev.parent); struct mt6323_pwrc *pwrc; struct resource *res; pwrc = devm_kzalloc(&pdev->dev, sizeof(*pwrc), GFP_KERNEL); if (!pwrc) return -ENOMEM; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) return -EINVAL; pwrc->base = res->start; pwrc->regmap = mt6397_chip->regmap; pwrc->dev = &pdev->dev; mt_pwrc = pwrc; pm_power_off = &mt6323_do_pwroff; return 0; } static int mt6323_pwrc_remove(struct platform_device *pdev) { if (pm_power_off == &mt6323_do_pwroff) pm_power_off = NULL; return 0; } static const struct of_device_id mt6323_pwrc_dt_match[] = { { .compatible = "mediatek,mt6323-pwrc" }, {}, }; MODULE_DEVICE_TABLE(of, mt6323_pwrc_dt_match); static struct platform_driver mt6323_pwrc_driver = { .probe = mt6323_pwrc_probe, .remove = mt6323_pwrc_remove, .driver = { .name = "mt6323-pwrc", .of_match_table = mt6323_pwrc_dt_match, }, }; module_platform_driver(mt6323_pwrc_driver); MODULE_DESCRIPTION("Poweroff driver for MT6323 PMIC"); MODULE_AUTHOR("Sean Wang <[email protected]>");
linux-master
drivers/power/reset/mt6323-poweroff.c
/* * Atmel AT91 SAM9 & SAMA5 SoCs reset code * * Copyright (C) 2007 Atmel Corporation. * Copyright (C) BitBox Ltd 2010 * Copyright (C) 2011 Jean-Christophe PLAGNIOL-VILLARD <[email protected]> * Copyright (C) 2014 Free Electrons * * This file is licensed under the terms of the GNU General Public * License version 2. This program is licensed "as is" without any * warranty of any kind, whether express or implied. */ #include <linux/clk.h> #include <linux/io.h> #include <linux/module.h> #include <linux/of_address.h> #include <linux/platform_device.h> #include <linux/reboot.h> #include <linux/reset-controller.h> #include <linux/power/power_on_reason.h> #include <soc/at91/at91sam9_ddrsdr.h> #include <soc/at91/at91sam9_sdramc.h> #include <dt-bindings/reset/sama7g5-reset.h> #define AT91_RSTC_CR 0x00 /* Reset Controller Control Register */ #define AT91_RSTC_PROCRST BIT(0) /* Processor Reset */ #define AT91_RSTC_PERRST BIT(2) /* Peripheral Reset */ #define AT91_RSTC_EXTRST BIT(3) /* External Reset */ #define AT91_RSTC_KEY (0xa5 << 24) /* KEY Password */ #define AT91_RSTC_SR 0x04 /* Reset Controller Status Register */ #define AT91_RSTC_URSTS BIT(0) /* User Reset Status */ #define AT91_RSTC_RSTTYP GENMASK(10, 8) /* Reset Type */ #define AT91_RSTC_NRSTL BIT(16) /* NRST Pin Level */ #define AT91_RSTC_SRCMP BIT(17) /* Software Reset Command in Progress */ #define AT91_RSTC_MR 0x08 /* Reset Controller Mode Register */ #define AT91_RSTC_URSTEN BIT(0) /* User Reset Enable */ #define AT91_RSTC_URSTASYNC BIT(2) /* User Reset Asynchronous Control */ #define AT91_RSTC_URSTIEN BIT(4) /* User Reset Interrupt Enable */ #define AT91_RSTC_ERSTL GENMASK(11, 8) /* External Reset Length */ /** * enum reset_type - reset types * @RESET_TYPE_GENERAL: first power-up reset * @RESET_TYPE_WAKEUP: return from backup mode * @RESET_TYPE_WATCHDOG: watchdog fault * @RESET_TYPE_SOFTWARE: processor reset required by software * @RESET_TYPE_USER: NRST pin detected low * @RESET_TYPE_CPU_FAIL: CPU clock failure detection * @RESET_TYPE_XTAL_FAIL: 32KHz crystal failure dectection fault * @RESET_TYPE_ULP2: ULP2 reset */ enum reset_type { RESET_TYPE_GENERAL = 0, RESET_TYPE_WAKEUP = 1, RESET_TYPE_WATCHDOG = 2, RESET_TYPE_SOFTWARE = 3, RESET_TYPE_USER = 4, RESET_TYPE_CPU_FAIL = 6, RESET_TYPE_XTAL_FAIL = 7, RESET_TYPE_ULP2 = 8, }; /** * struct at91_reset - AT91 reset specific data structure * @rstc_base: base address for system reset * @ramc_base: array with base addresses of RAM controllers * @dev_base: base address for devices reset * @sclk: slow clock * @data: platform specific reset data * @rcdev: reset controller device * @lock: lock for devices reset register access * @nb: reset notifier block * @args: SoC specific system reset arguments * @ramc_lpr: SDRAM Controller Low Power Register */ struct at91_reset { void __iomem *rstc_base; void __iomem *ramc_base[2]; void __iomem *dev_base; struct clk *sclk; const struct at91_reset_data *data; struct reset_controller_dev rcdev; spinlock_t lock; struct notifier_block nb; u32 args; u32 ramc_lpr; }; #define to_at91_reset(r) container_of(r, struct at91_reset, rcdev) /** * struct at91_reset_data - AT91 reset data * @reset_args: SoC specific system reset arguments * @n_device_reset: number of device resets * @device_reset_min_id: min id for device reset * @device_reset_max_id: max id for device reset */ struct at91_reset_data { u32 reset_args; u32 n_device_reset; u8 device_reset_min_id; u8 device_reset_max_id; }; /* * unless the SDRAM is cleanly shutdown before we hit the * reset register it can be left driving the data bus and * killing the chance of a subsequent boot from NAND */ static int at91_reset(struct notifier_block *this, unsigned long mode, void *cmd) { struct at91_reset *reset = container_of(this, struct at91_reset, nb); asm volatile( /* Align to cache lines */ ".balign 32\n\t" /* Disable SDRAM0 accesses */ " tst %0, #0\n\t" " beq 1f\n\t" " str %3, [%0, #" __stringify(AT91_DDRSDRC_RTR) "]\n\t" /* Power down SDRAM0 */ " str %4, [%0, %6]\n\t" /* Disable SDRAM1 accesses */ "1: tst %1, #0\n\t" " beq 2f\n\t" " strne %3, [%1, #" __stringify(AT91_DDRSDRC_RTR) "]\n\t" /* Power down SDRAM1 */ " strne %4, [%1, %6]\n\t" /* Reset CPU */ "2: str %5, [%2, #" __stringify(AT91_RSTC_CR) "]\n\t" " b .\n\t" : : "r" (reset->ramc_base[0]), "r" (reset->ramc_base[1]), "r" (reset->rstc_base), "r" (1), "r" cpu_to_le32(AT91_DDRSDRC_LPCB_POWER_DOWN), "r" (reset->data->reset_args), "r" (reset->ramc_lpr) : "r4"); return NOTIFY_DONE; } static const char *at91_reset_reason(struct at91_reset *reset) { u32 reg = readl(reset->rstc_base + AT91_RSTC_SR); const char *reason; switch ((reg & AT91_RSTC_RSTTYP) >> 8) { case RESET_TYPE_GENERAL: reason = POWER_ON_REASON_REGULAR; break; case RESET_TYPE_WAKEUP: reason = POWER_ON_REASON_RTC; break; case RESET_TYPE_WATCHDOG: reason = POWER_ON_REASON_WATCHDOG; break; case RESET_TYPE_SOFTWARE: reason = POWER_ON_REASON_SOFTWARE; break; case RESET_TYPE_USER: reason = POWER_ON_REASON_RST_BTN; break; case RESET_TYPE_CPU_FAIL: reason = POWER_ON_REASON_CPU_CLK_FAIL; break; case RESET_TYPE_XTAL_FAIL: reason = POWER_ON_REASON_XTAL_FAIL; break; case RESET_TYPE_ULP2: reason = POWER_ON_REASON_BROWN_OUT; break; default: reason = POWER_ON_REASON_UNKNOWN; break; } return reason; } static ssize_t power_on_reason_show(struct device *dev, struct device_attribute *attr, char *buf) { struct platform_device *pdev = to_platform_device(dev); struct at91_reset *reset = platform_get_drvdata(pdev); return sprintf(buf, "%s\n", at91_reset_reason(reset)); } static DEVICE_ATTR_RO(power_on_reason); static const struct of_device_id at91_ramc_of_match[] = { { .compatible = "atmel,at91sam9260-sdramc", .data = (void *)AT91_SDRAMC_LPR, }, { .compatible = "atmel,at91sam9g45-ddramc", .data = (void *)AT91_DDRSDRC_LPR, }, { /* sentinel */ } }; static const struct at91_reset_data sam9260 = { .reset_args = AT91_RSTC_KEY | AT91_RSTC_PERRST | AT91_RSTC_PROCRST, }; static const struct at91_reset_data samx7 = { .reset_args = AT91_RSTC_KEY | AT91_RSTC_PROCRST, }; static const struct at91_reset_data sama7g5 = { .reset_args = AT91_RSTC_KEY | AT91_RSTC_PROCRST, .n_device_reset = 3, .device_reset_min_id = SAMA7G5_RESET_USB_PHY1, .device_reset_max_id = SAMA7G5_RESET_USB_PHY3, }; static const struct of_device_id at91_reset_of_match[] = { { .compatible = "atmel,at91sam9260-rstc", .data = &sam9260, }, { .compatible = "atmel,at91sam9g45-rstc", .data = &sam9260, }, { .compatible = "atmel,sama5d3-rstc", .data = &sam9260, }, { .compatible = "atmel,samx7-rstc", .data = &samx7, }, { .compatible = "microchip,sam9x60-rstc", .data = &samx7, }, { .compatible = "microchip,sama7g5-rstc", .data = &sama7g5, }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, at91_reset_of_match); static int at91_reset_update(struct reset_controller_dev *rcdev, unsigned long id, bool assert) { struct at91_reset *reset = to_at91_reset(rcdev); unsigned long flags; u32 val; spin_lock_irqsave(&reset->lock, flags); val = readl_relaxed(reset->dev_base); if (assert) val |= BIT(id); else val &= ~BIT(id); writel_relaxed(val, reset->dev_base); spin_unlock_irqrestore(&reset->lock, flags); return 0; } static int at91_reset_assert(struct reset_controller_dev *rcdev, unsigned long id) { return at91_reset_update(rcdev, id, true); } static int at91_reset_deassert(struct reset_controller_dev *rcdev, unsigned long id) { return at91_reset_update(rcdev, id, false); } static int at91_reset_dev_status(struct reset_controller_dev *rcdev, unsigned long id) { struct at91_reset *reset = to_at91_reset(rcdev); u32 val; val = readl_relaxed(reset->dev_base); return !!(val & BIT(id)); } static const struct reset_control_ops at91_reset_ops = { .assert = at91_reset_assert, .deassert = at91_reset_deassert, .status = at91_reset_dev_status, }; static int at91_reset_of_xlate(struct reset_controller_dev *rcdev, const struct of_phandle_args *reset_spec) { struct at91_reset *reset = to_at91_reset(rcdev); if (!reset->data->n_device_reset || (reset_spec->args[0] < reset->data->device_reset_min_id || reset_spec->args[0] > reset->data->device_reset_max_id)) return -EINVAL; return reset_spec->args[0]; } static int at91_rcdev_init(struct at91_reset *reset, struct platform_device *pdev) { if (!reset->data->n_device_reset) return 0; reset->dev_base = devm_of_iomap(&pdev->dev, pdev->dev.of_node, 1, NULL); if (IS_ERR(reset->dev_base)) return -ENODEV; spin_lock_init(&reset->lock); reset->rcdev.ops = &at91_reset_ops; reset->rcdev.owner = THIS_MODULE; reset->rcdev.of_node = pdev->dev.of_node; reset->rcdev.nr_resets = reset->data->n_device_reset; reset->rcdev.of_reset_n_cells = 1; reset->rcdev.of_xlate = at91_reset_of_xlate; return devm_reset_controller_register(&pdev->dev, &reset->rcdev); } static int __init at91_reset_probe(struct platform_device *pdev) { const struct of_device_id *match; struct at91_reset *reset; struct device_node *np; int ret, idx = 0; reset = devm_kzalloc(&pdev->dev, sizeof(*reset), GFP_KERNEL); if (!reset) return -ENOMEM; reset->rstc_base = devm_of_iomap(&pdev->dev, pdev->dev.of_node, 0, NULL); if (IS_ERR(reset->rstc_base)) { dev_err(&pdev->dev, "Could not map reset controller address\n"); return -ENODEV; } if (!of_device_is_compatible(pdev->dev.of_node, "atmel,sama5d3-rstc")) { /* we need to shutdown the ddr controller, so get ramc base */ for_each_matching_node_and_match(np, at91_ramc_of_match, &match) { reset->ramc_lpr = (u32)match->data; reset->ramc_base[idx] = devm_of_iomap(&pdev->dev, np, 0, NULL); if (IS_ERR(reset->ramc_base[idx])) { dev_err(&pdev->dev, "Could not map ram controller address\n"); of_node_put(np); return -ENODEV; } idx++; } } reset->data = device_get_match_data(&pdev->dev); if (!reset->data) return -ENODEV; reset->nb.notifier_call = at91_reset; reset->nb.priority = 192; reset->sclk = devm_clk_get(&pdev->dev, NULL); if (IS_ERR(reset->sclk)) return PTR_ERR(reset->sclk); ret = clk_prepare_enable(reset->sclk); if (ret) { dev_err(&pdev->dev, "Could not enable slow clock\n"); return ret; } platform_set_drvdata(pdev, reset); ret = at91_rcdev_init(reset, pdev); if (ret) goto disable_clk; if (of_device_is_compatible(pdev->dev.of_node, "microchip,sam9x60-rstc")) { u32 val = readl(reset->rstc_base + AT91_RSTC_MR); writel(AT91_RSTC_KEY | AT91_RSTC_URSTASYNC | val, reset->rstc_base + AT91_RSTC_MR); } ret = register_restart_handler(&reset->nb); if (ret) goto disable_clk; ret = device_create_file(&pdev->dev, &dev_attr_power_on_reason); if (ret) { dev_err(&pdev->dev, "Could not create sysfs entry\n"); return ret; } dev_info(&pdev->dev, "Starting after %s\n", at91_reset_reason(reset)); return 0; disable_clk: clk_disable_unprepare(reset->sclk); return ret; } static int __exit at91_reset_remove(struct platform_device *pdev) { struct at91_reset *reset = platform_get_drvdata(pdev); unregister_restart_handler(&reset->nb); clk_disable_unprepare(reset->sclk); return 0; } static struct platform_driver at91_reset_driver = { .remove = __exit_p(at91_reset_remove), .driver = { .name = "at91-reset", .of_match_table = at91_reset_of_match, }, }; module_platform_driver_probe(at91_reset_driver, at91_reset_probe); MODULE_AUTHOR("Atmel Corporation"); MODULE_DESCRIPTION("Reset driver for Atmel SoCs"); MODULE_LICENSE("GPL v2");
linux-master
drivers/power/reset/at91-reset.c
// SPDX-License-Identifier: GPL-2.0-only or BSD-3-Clause /* * Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. */ #include <linux/acpi.h> #include <linux/device.h> #include <linux/devm-helpers.h> #include <linux/interrupt.h> #include <linux/kernel.h> #include <linux/mod_devicetable.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/pm.h> #include <linux/reboot.h> #include <linux/types.h> struct pwr_mlxbf { struct work_struct send_work; const char *hid; }; static void pwr_mlxbf_send_work(struct work_struct *work) { acpi_bus_generate_netlink_event("button/power.*", "Power Button", 0x80, 1); } static irqreturn_t pwr_mlxbf_irq(int irq, void *ptr) { const char *rst_pwr_hid = "MLNXBF24"; const char *low_pwr_hid = "MLNXBF29"; struct pwr_mlxbf *priv = ptr; if (!strncmp(priv->hid, rst_pwr_hid, 8)) emergency_restart(); if (!strncmp(priv->hid, low_pwr_hid, 8)) schedule_work(&priv->send_work); return IRQ_HANDLED; } static int pwr_mlxbf_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct acpi_device *adev; struct pwr_mlxbf *priv; const char *hid; int irq, err; priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; adev = ACPI_COMPANION(dev); if (!adev) return -ENXIO; hid = acpi_device_hid(adev); priv->hid = hid; irq = acpi_dev_gpio_irq_get(ACPI_COMPANION(dev), 0); if (irq < 0) return dev_err_probe(dev, irq, "Error getting %s irq.\n", priv->hid); err = devm_work_autocancel(dev, &priv->send_work, pwr_mlxbf_send_work); if (err) return err; err = devm_request_irq(dev, irq, pwr_mlxbf_irq, 0, hid, priv); if (err) dev_err(dev, "Failed request of %s irq\n", priv->hid); return err; } static const struct acpi_device_id __maybe_unused pwr_mlxbf_acpi_match[] = { { "MLNXBF24", 0 }, { "MLNXBF29", 0 }, {}, }; MODULE_DEVICE_TABLE(acpi, pwr_mlxbf_acpi_match); static struct platform_driver pwr_mlxbf_driver = { .driver = { .name = "pwr_mlxbf", .acpi_match_table = pwr_mlxbf_acpi_match, }, .probe = pwr_mlxbf_probe, }; module_platform_driver(pwr_mlxbf_driver); MODULE_DESCRIPTION("Mellanox BlueField power driver"); MODULE_AUTHOR("Asmaa Mnebhi <[email protected]>"); MODULE_LICENSE("Dual BSD/GPL");
linux-master
drivers/power/reset/pwr-mlxbf.c
// SPDX-License-Identifier: GPL-2.0-only /* * Power off by restarting and let u-boot keep hold of the machine * until the user presses a button for example. * * Andrew Lunn <[email protected]> * * Copyright (C) 2012 Andrew Lunn */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/of_platform.h> #include <linux/module.h> #include <linux/reboot.h> static void restart_poweroff_do_poweroff(void) { reboot_mode = REBOOT_HARD; machine_restart(NULL); } static int restart_poweroff_probe(struct platform_device *pdev) { /* If a pm_power_off function has already been added, leave it alone */ if (pm_power_off != NULL) { dev_err(&pdev->dev, "pm_power_off function already registered"); return -EBUSY; } pm_power_off = &restart_poweroff_do_poweroff; return 0; } static int restart_poweroff_remove(struct platform_device *pdev) { if (pm_power_off == &restart_poweroff_do_poweroff) pm_power_off = NULL; return 0; } static const struct of_device_id of_restart_poweroff_match[] = { { .compatible = "restart-poweroff", }, {}, }; MODULE_DEVICE_TABLE(of, of_restart_poweroff_match); static struct platform_driver restart_poweroff_driver = { .probe = restart_poweroff_probe, .remove = restart_poweroff_remove, .driver = { .name = "poweroff-restart", .of_match_table = of_restart_poweroff_match, }, }; module_platform_driver(restart_poweroff_driver); MODULE_AUTHOR("Andrew Lunn <[email protected]"); MODULE_DESCRIPTION("restart poweroff driver"); MODULE_ALIAS("platform:poweroff-restart");
linux-master
drivers/power/reset/restart-poweroff.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * AppliedMicro X-Gene SoC Reboot Driver * * Copyright (c) 2013, Applied Micro Circuits Corporation * Author: Feng Kan <[email protected]> * Author: Loc Ho <[email protected]> * * This driver provides system reboot functionality for APM X-Gene SoC. * For system shutdown, this is board specify. If a board designer * implements GPIO shutdown, use the gpio-poweroff.c driver. */ #include <linux/delay.h> #include <linux/io.h> #include <linux/notifier.h> #include <linux/of.h> #include <linux/of_address.h> #include <linux/platform_device.h> #include <linux/reboot.h> #include <linux/stat.h> #include <linux/slab.h> struct xgene_reboot_context { struct device *dev; void *csr; u32 mask; struct notifier_block restart_handler; }; static int xgene_restart_handler(struct notifier_block *this, unsigned long mode, void *cmd) { struct xgene_reboot_context *ctx = container_of(this, struct xgene_reboot_context, restart_handler); /* Issue the reboot */ writel(ctx->mask, ctx->csr); mdelay(1000); dev_emerg(ctx->dev, "Unable to restart system\n"); return NOTIFY_DONE; } static int xgene_reboot_probe(struct platform_device *pdev) { struct xgene_reboot_context *ctx; struct device *dev = &pdev->dev; int err; ctx = devm_kzalloc(dev, sizeof(*ctx), GFP_KERNEL); if (!ctx) return -ENOMEM; ctx->csr = of_iomap(dev->of_node, 0); if (!ctx->csr) { dev_err(dev, "can not map resource\n"); return -ENODEV; } if (of_property_read_u32(dev->of_node, "mask", &ctx->mask)) ctx->mask = 0xFFFFFFFF; ctx->dev = dev; ctx->restart_handler.notifier_call = xgene_restart_handler; ctx->restart_handler.priority = 128; err = register_restart_handler(&ctx->restart_handler); if (err) { iounmap(ctx->csr); dev_err(dev, "cannot register restart handler (err=%d)\n", err); } return err; } static const struct of_device_id xgene_reboot_of_match[] = { { .compatible = "apm,xgene-reboot" }, {} }; static struct platform_driver xgene_reboot_driver = { .probe = xgene_reboot_probe, .driver = { .name = "xgene-reboot", .of_match_table = xgene_reboot_of_match, }, }; static int __init xgene_reboot_init(void) { return platform_driver_register(&xgene_reboot_driver); } device_initcall(xgene_reboot_init);
linux-master
drivers/power/reset/xgene-reboot.c
/* * Atmel AT91 SAM9 SoCs reset code * * Copyright (C) 2007 Atmel Corporation. * Copyright (C) 2011 Jean-Christophe PLAGNIOL-VILLARD <[email protected]> * Copyright (C) 2014 Free Electrons * * This file is licensed under the terms of the GNU General Public * License version 2. This program is licensed "as is" without any * warranty of any kind, whether express or implied. */ #include <linux/clk.h> #include <linux/io.h> #include <linux/module.h> #include <linux/of.h> #include <linux/of_address.h> #include <linux/platform_device.h> #include <linux/printk.h> #include <soc/at91/at91sam9_ddrsdr.h> #define AT91_SHDW_CR 0x00 /* Shut Down Control Register */ #define AT91_SHDW_SHDW BIT(0) /* Shut Down command */ #define AT91_SHDW_KEY (0xa5 << 24) /* KEY Password */ #define AT91_SHDW_MR 0x04 /* Shut Down Mode Register */ #define AT91_SHDW_WKMODE0 GENMASK(2, 0) /* Wake-up 0 Mode Selection */ #define AT91_SHDW_CPTWK0_MAX 0xf /* Maximum Counter On Wake Up 0 */ #define AT91_SHDW_CPTWK0 (AT91_SHDW_CPTWK0_MAX << 4) /* Counter On Wake Up 0 */ #define AT91_SHDW_CPTWK0_(x) ((x) << 4) #define AT91_SHDW_RTTWKEN BIT(16) /* Real Time Timer Wake-up Enable */ #define AT91_SHDW_RTCWKEN BIT(17) /* Real Time Clock Wake-up Enable */ #define AT91_SHDW_SR 0x08 /* Shut Down Status Register */ #define AT91_SHDW_WAKEUP0 BIT(0) /* Wake-up 0 Status */ #define AT91_SHDW_RTTWK BIT(16) /* Real-time Timer Wake-up */ #define AT91_SHDW_RTCWK BIT(17) /* Real-time Clock Wake-up [SAM9RL] */ enum wakeup_type { AT91_SHDW_WKMODE0_NONE = 0, AT91_SHDW_WKMODE0_HIGH = 1, AT91_SHDW_WKMODE0_LOW = 2, AT91_SHDW_WKMODE0_ANYLEVEL = 3, }; static const char *shdwc_wakeup_modes[] = { [AT91_SHDW_WKMODE0_NONE] = "none", [AT91_SHDW_WKMODE0_HIGH] = "high", [AT91_SHDW_WKMODE0_LOW] = "low", [AT91_SHDW_WKMODE0_ANYLEVEL] = "any", }; static struct shdwc { struct clk *sclk; void __iomem *shdwc_base; void __iomem *mpddrc_base; } at91_shdwc; static void __init at91_wakeup_status(struct platform_device *pdev) { const char *reason; u32 reg = readl(at91_shdwc.shdwc_base + AT91_SHDW_SR); /* Simple power-on, just bail out */ if (!reg) return; if (reg & AT91_SHDW_RTTWK) reason = "RTT"; else if (reg & AT91_SHDW_RTCWK) reason = "RTC"; else reason = "unknown"; dev_info(&pdev->dev, "Wake-Up source: %s\n", reason); } static void at91_poweroff(void) { asm volatile( /* Align to cache lines */ ".balign 32\n\t" /* Ensure AT91_SHDW_CR is in the TLB by reading it */ " ldr r6, [%2, #" __stringify(AT91_SHDW_CR) "]\n\t" /* Power down SDRAM0 */ " tst %0, #0\n\t" " beq 1f\n\t" " str %1, [%0, #" __stringify(AT91_DDRSDRC_LPR) "]\n\t" /* Shutdown CPU */ "1: str %3, [%2, #" __stringify(AT91_SHDW_CR) "]\n\t" " b .\n\t" : : "r" (at91_shdwc.mpddrc_base), "r" cpu_to_le32(AT91_DDRSDRC_LPDDR2_PWOFF), "r" (at91_shdwc.shdwc_base), "r" cpu_to_le32(AT91_SHDW_KEY | AT91_SHDW_SHDW) : "r6"); } static int at91_poweroff_get_wakeup_mode(struct device_node *np) { const char *pm; unsigned int i; int err; err = of_property_read_string(np, "atmel,wakeup-mode", &pm); if (err < 0) return AT91_SHDW_WKMODE0_ANYLEVEL; for (i = 0; i < ARRAY_SIZE(shdwc_wakeup_modes); i++) if (!strcasecmp(pm, shdwc_wakeup_modes[i])) return i; return -ENODEV; } static void at91_poweroff_dt_set_wakeup_mode(struct platform_device *pdev) { struct device_node *np = pdev->dev.of_node; int wakeup_mode; u32 mode = 0, tmp; wakeup_mode = at91_poweroff_get_wakeup_mode(np); if (wakeup_mode < 0) { dev_warn(&pdev->dev, "shdwc unknown wakeup mode\n"); return; } if (!of_property_read_u32(np, "atmel,wakeup-counter", &tmp)) { if (tmp > AT91_SHDW_CPTWK0_MAX) { dev_warn(&pdev->dev, "shdwc wakeup counter 0x%x > 0x%x reduce it to 0x%x\n", tmp, AT91_SHDW_CPTWK0_MAX, AT91_SHDW_CPTWK0_MAX); tmp = AT91_SHDW_CPTWK0_MAX; } mode |= AT91_SHDW_CPTWK0_(tmp); } if (of_property_read_bool(np, "atmel,wakeup-rtc-timer")) mode |= AT91_SHDW_RTCWKEN; if (of_property_read_bool(np, "atmel,wakeup-rtt-timer")) mode |= AT91_SHDW_RTTWKEN; writel(wakeup_mode | mode, at91_shdwc.shdwc_base + AT91_SHDW_MR); } static int __init at91_poweroff_probe(struct platform_device *pdev) { struct device_node *np; u32 ddr_type; int ret; at91_shdwc.shdwc_base = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(at91_shdwc.shdwc_base)) return PTR_ERR(at91_shdwc.shdwc_base); at91_shdwc.sclk = devm_clk_get(&pdev->dev, NULL); if (IS_ERR(at91_shdwc.sclk)) return PTR_ERR(at91_shdwc.sclk); ret = clk_prepare_enable(at91_shdwc.sclk); if (ret) { dev_err(&pdev->dev, "Could not enable slow clock\n"); return ret; } at91_wakeup_status(pdev); if (pdev->dev.of_node) at91_poweroff_dt_set_wakeup_mode(pdev); np = of_find_compatible_node(NULL, NULL, "atmel,sama5d3-ddramc"); if (np) { at91_shdwc.mpddrc_base = of_iomap(np, 0); of_node_put(np); if (!at91_shdwc.mpddrc_base) { ret = -ENOMEM; goto clk_disable; } ddr_type = readl(at91_shdwc.mpddrc_base + AT91_DDRSDRC_MDR) & AT91_DDRSDRC_MD; if (ddr_type != AT91_DDRSDRC_MD_LPDDR2 && ddr_type != AT91_DDRSDRC_MD_LPDDR3) { iounmap(at91_shdwc.mpddrc_base); at91_shdwc.mpddrc_base = NULL; } } pm_power_off = at91_poweroff; return 0; clk_disable: clk_disable_unprepare(at91_shdwc.sclk); return ret; } static int __exit at91_poweroff_remove(struct platform_device *pdev) { if (pm_power_off == at91_poweroff) pm_power_off = NULL; if (at91_shdwc.mpddrc_base) iounmap(at91_shdwc.mpddrc_base); clk_disable_unprepare(at91_shdwc.sclk); return 0; } static const struct of_device_id at91_poweroff_of_match[] = { { .compatible = "atmel,at91sam9260-shdwc", }, { .compatible = "atmel,at91sam9rl-shdwc", }, { .compatible = "atmel,at91sam9x5-shdwc", }, { /*sentinel*/ } }; MODULE_DEVICE_TABLE(of, at91_poweroff_of_match); static struct platform_driver at91_poweroff_driver = { .remove = __exit_p(at91_poweroff_remove), .driver = { .name = "at91-poweroff", .of_match_table = at91_poweroff_of_match, }, }; module_platform_driver_probe(at91_poweroff_driver, at91_poweroff_probe); MODULE_AUTHOR("Atmel Corporation"); MODULE_DESCRIPTION("Shutdown driver for Atmel SoCs"); MODULE_LICENSE("GPL v2");
linux-master
drivers/power/reset/at91-poweroff.c
// SPDX-License-Identifier: (GPL-2.0 OR MIT) /* * Microsemi MIPS SoC reset driver * * License: Dual MIT/GPL * Copyright (c) 2017 Microsemi Corporation */ #include <linux/delay.h> #include <linux/io.h> #include <linux/notifier.h> #include <linux/mod_devicetable.h> #include <linux/mfd/syscon.h> #include <linux/platform_device.h> #include <linux/property.h> #include <linux/reboot.h> #include <linux/regmap.h> struct reset_props { const char *syscon; u32 protect_reg; u32 vcore_protect; u32 if_si_owner_bit; }; struct ocelot_reset_context { void __iomem *base; struct regmap *cpu_ctrl; const struct reset_props *props; struct notifier_block restart_handler; }; #define BIT_OFF_INVALID 32 #define SOFT_CHIP_RST BIT(0) #define ICPU_CFG_CPU_SYSTEM_CTRL_GENERAL_CTRL 0x24 #define IF_SI_OWNER_MASK GENMASK(1, 0) #define IF_SI_OWNER_SISL 0 #define IF_SI_OWNER_SIBM 1 #define IF_SI_OWNER_SIMC 2 static int ocelot_restart_handle(struct notifier_block *this, unsigned long mode, void *cmd) { struct ocelot_reset_context *ctx = container_of(this, struct ocelot_reset_context, restart_handler); u32 if_si_owner_bit = ctx->props->if_si_owner_bit; /* Make sure the core is not protected from reset */ regmap_update_bits(ctx->cpu_ctrl, ctx->props->protect_reg, ctx->props->vcore_protect, 0); /* Make the SI back to boot mode */ if (if_si_owner_bit != BIT_OFF_INVALID) regmap_update_bits(ctx->cpu_ctrl, ICPU_CFG_CPU_SYSTEM_CTRL_GENERAL_CTRL, IF_SI_OWNER_MASK << if_si_owner_bit, IF_SI_OWNER_SIBM << if_si_owner_bit); pr_emerg("Resetting SoC\n"); writel(SOFT_CHIP_RST, ctx->base); pr_emerg("Unable to restart system\n"); return NOTIFY_DONE; } static int ocelot_reset_probe(struct platform_device *pdev) { struct ocelot_reset_context *ctx; struct device *dev = &pdev->dev; int err; ctx = devm_kzalloc(&pdev->dev, sizeof(*ctx), GFP_KERNEL); if (!ctx) return -ENOMEM; ctx->base = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(ctx->base)) return PTR_ERR(ctx->base); ctx->props = device_get_match_data(dev); ctx->cpu_ctrl = syscon_regmap_lookup_by_compatible(ctx->props->syscon); if (IS_ERR(ctx->cpu_ctrl)) { dev_err(dev, "No syscon map: %s\n", ctx->props->syscon); return PTR_ERR(ctx->cpu_ctrl); } ctx->restart_handler.notifier_call = ocelot_restart_handle; ctx->restart_handler.priority = 192; err = register_restart_handler(&ctx->restart_handler); if (err) dev_err(dev, "can't register restart notifier (err=%d)\n", err); return err; } static const struct reset_props reset_props_jaguar2 = { .syscon = "mscc,ocelot-cpu-syscon", .protect_reg = 0x20, .vcore_protect = BIT(2), .if_si_owner_bit = 6, }; static const struct reset_props reset_props_luton = { .syscon = "mscc,ocelot-cpu-syscon", .protect_reg = 0x20, .vcore_protect = BIT(2), .if_si_owner_bit = BIT_OFF_INVALID, /* n/a */ }; static const struct reset_props reset_props_ocelot = { .syscon = "mscc,ocelot-cpu-syscon", .protect_reg = 0x20, .vcore_protect = BIT(2), .if_si_owner_bit = 4, }; static const struct reset_props reset_props_sparx5 = { .syscon = "microchip,sparx5-cpu-syscon", .protect_reg = 0x84, .vcore_protect = BIT(10), .if_si_owner_bit = 6, }; static const struct of_device_id ocelot_reset_of_match[] = { { .compatible = "mscc,jaguar2-chip-reset", .data = &reset_props_jaguar2 }, { .compatible = "mscc,luton-chip-reset", .data = &reset_props_luton }, { .compatible = "mscc,ocelot-chip-reset", .data = &reset_props_ocelot }, { .compatible = "microchip,sparx5-chip-reset", .data = &reset_props_sparx5 }, { /*sentinel*/ } }; static struct platform_driver ocelot_reset_driver = { .probe = ocelot_reset_probe, .driver = { .name = "ocelot-chip-reset", .of_match_table = ocelot_reset_of_match, }, }; builtin_platform_driver(ocelot_reset_driver);
linux-master
drivers/power/reset/ocelot-reset.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Generic Syscon Poweroff Driver * * Copyright (c) 2015, National Instruments Corp. * Author: Moritz Fischer <[email protected]> */ #include <linux/delay.h> #include <linux/io.h> #include <linux/notifier.h> #include <linux/mfd/syscon.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/pm.h> #include <linux/regmap.h> static struct regmap *map; static u32 offset; static u32 value; static u32 mask; static void syscon_poweroff(void) { /* Issue the poweroff */ regmap_update_bits(map, offset, mask, value); mdelay(1000); pr_emerg("Unable to poweroff system\n"); } static int syscon_poweroff_probe(struct platform_device *pdev) { int mask_err, value_err; map = syscon_regmap_lookup_by_phandle(pdev->dev.of_node, "regmap"); if (IS_ERR(map)) { dev_err(&pdev->dev, "unable to get syscon"); return PTR_ERR(map); } if (of_property_read_u32(pdev->dev.of_node, "offset", &offset)) { dev_err(&pdev->dev, "unable to read 'offset'"); return -EINVAL; } value_err = of_property_read_u32(pdev->dev.of_node, "value", &value); mask_err = of_property_read_u32(pdev->dev.of_node, "mask", &mask); if (value_err && mask_err) { dev_err(&pdev->dev, "unable to read 'value' and 'mask'"); return -EINVAL; } if (value_err) { /* support old binding */ value = mask; mask = 0xFFFFFFFF; } else if (mask_err) { /* support value without mask*/ mask = 0xFFFFFFFF; } if (pm_power_off) { dev_err(&pdev->dev, "pm_power_off already claimed for %ps", pm_power_off); return -EBUSY; } pm_power_off = syscon_poweroff; return 0; } static int syscon_poweroff_remove(struct platform_device *pdev) { if (pm_power_off == syscon_poweroff) pm_power_off = NULL; return 0; } static const struct of_device_id syscon_poweroff_of_match[] = { { .compatible = "syscon-poweroff" }, {} }; static struct platform_driver syscon_poweroff_driver = { .probe = syscon_poweroff_probe, .remove = syscon_poweroff_remove, .driver = { .name = "syscon-poweroff", .of_match_table = syscon_poweroff_of_match, }, }; static int __init syscon_poweroff_register(void) { return platform_driver_register(&syscon_poweroff_driver); } device_initcall(syscon_poweroff_register);
linux-master
drivers/power/reset/syscon-poweroff.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (c) 2016, Fuzhou Rockchip Electronics Co., Ltd */ #include <linux/device.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/of.h> #include <linux/reboot.h> #include <linux/reboot-mode.h> #define PREFIX "mode-" struct mode_info { const char *mode; u32 magic; struct list_head list; }; static unsigned int get_reboot_mode_magic(struct reboot_mode_driver *reboot, const char *cmd) { const char *normal = "normal"; int magic = 0; struct mode_info *info; if (!cmd) cmd = normal; list_for_each_entry(info, &reboot->head, list) { if (!strcmp(info->mode, cmd)) { magic = info->magic; break; } } return magic; } static int reboot_mode_notify(struct notifier_block *this, unsigned long mode, void *cmd) { struct reboot_mode_driver *reboot; unsigned int magic; reboot = container_of(this, struct reboot_mode_driver, reboot_notifier); magic = get_reboot_mode_magic(reboot, cmd); if (magic) reboot->write(reboot, magic); return NOTIFY_DONE; } /** * reboot_mode_register - register a reboot mode driver * @reboot: reboot mode driver * * Returns: 0 on success or a negative error code on failure. */ int reboot_mode_register(struct reboot_mode_driver *reboot) { struct mode_info *info; struct property *prop; struct device_node *np = reboot->dev->of_node; size_t len = strlen(PREFIX); int ret; INIT_LIST_HEAD(&reboot->head); for_each_property_of_node(np, prop) { if (strncmp(prop->name, PREFIX, len)) continue; info = devm_kzalloc(reboot->dev, sizeof(*info), GFP_KERNEL); if (!info) { ret = -ENOMEM; goto error; } if (of_property_read_u32(np, prop->name, &info->magic)) { dev_err(reboot->dev, "reboot mode %s without magic number\n", info->mode); devm_kfree(reboot->dev, info); continue; } info->mode = kstrdup_const(prop->name + len, GFP_KERNEL); if (!info->mode) { ret = -ENOMEM; goto error; } else if (info->mode[0] == '\0') { kfree_const(info->mode); ret = -EINVAL; dev_err(reboot->dev, "invalid mode name(%s): too short!\n", prop->name); goto error; } list_add_tail(&info->list, &reboot->head); } reboot->reboot_notifier.notifier_call = reboot_mode_notify; register_reboot_notifier(&reboot->reboot_notifier); return 0; error: list_for_each_entry(info, &reboot->head, list) kfree_const(info->mode); return ret; } EXPORT_SYMBOL_GPL(reboot_mode_register); /** * reboot_mode_unregister - unregister a reboot mode driver * @reboot: reboot mode driver */ int reboot_mode_unregister(struct reboot_mode_driver *reboot) { struct mode_info *info; unregister_reboot_notifier(&reboot->reboot_notifier); list_for_each_entry(info, &reboot->head, list) kfree_const(info->mode); return 0; } EXPORT_SYMBOL_GPL(reboot_mode_unregister); static void devm_reboot_mode_release(struct device *dev, void *res) { reboot_mode_unregister(*(struct reboot_mode_driver **)res); } /** * devm_reboot_mode_register() - resource managed reboot_mode_register() * @dev: device to associate this resource with * @reboot: reboot mode driver * * Returns: 0 on success or a negative error code on failure. */ int devm_reboot_mode_register(struct device *dev, struct reboot_mode_driver *reboot) { struct reboot_mode_driver **dr; int rc; dr = devres_alloc(devm_reboot_mode_release, sizeof(*dr), GFP_KERNEL); if (!dr) return -ENOMEM; rc = reboot_mode_register(reboot); if (rc) { devres_free(dr); return rc; } *dr = reboot; devres_add(dev, dr); return 0; } EXPORT_SYMBOL_GPL(devm_reboot_mode_register); static int devm_reboot_mode_match(struct device *dev, void *res, void *data) { struct reboot_mode_driver **p = res; if (WARN_ON(!p || !*p)) return 0; return *p == data; } /** * devm_reboot_mode_unregister() - resource managed reboot_mode_unregister() * @dev: device to associate this resource with * @reboot: reboot mode driver */ void devm_reboot_mode_unregister(struct device *dev, struct reboot_mode_driver *reboot) { WARN_ON(devres_release(dev, devm_reboot_mode_release, devm_reboot_mode_match, reboot)); } EXPORT_SYMBOL_GPL(devm_reboot_mode_unregister); MODULE_AUTHOR("Andy Yan <[email protected]>"); MODULE_DESCRIPTION("System reboot mode core library"); MODULE_LICENSE("GPL v2");
linux-master
drivers/power/reset/reboot-mode.c
// SPDX-License-Identifier: GPL-2.0+ /* * Copyright (c) Vaisala Oyj. All rights reserved. */ #include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/of.h> #include <linux/nvmem-consumer.h> #include <linux/platform_device.h> #include <linux/reboot-mode.h> struct nvmem_reboot_mode { struct reboot_mode_driver reboot; struct nvmem_cell *cell; }; static int nvmem_reboot_mode_write(struct reboot_mode_driver *reboot, unsigned int magic) { int ret; struct nvmem_reboot_mode *nvmem_rbm; nvmem_rbm = container_of(reboot, struct nvmem_reboot_mode, reboot); ret = nvmem_cell_write(nvmem_rbm->cell, &magic, sizeof(magic)); if (ret < 0) dev_err(reboot->dev, "update reboot mode bits failed\n"); return ret; } static int nvmem_reboot_mode_probe(struct platform_device *pdev) { int ret; struct nvmem_reboot_mode *nvmem_rbm; nvmem_rbm = devm_kzalloc(&pdev->dev, sizeof(*nvmem_rbm), GFP_KERNEL); if (!nvmem_rbm) return -ENOMEM; nvmem_rbm->reboot.dev = &pdev->dev; nvmem_rbm->reboot.write = nvmem_reboot_mode_write; nvmem_rbm->cell = devm_nvmem_cell_get(&pdev->dev, "reboot-mode"); if (IS_ERR(nvmem_rbm->cell)) { dev_err(&pdev->dev, "failed to get the nvmem cell reboot-mode\n"); return PTR_ERR(nvmem_rbm->cell); } ret = devm_reboot_mode_register(&pdev->dev, &nvmem_rbm->reboot); if (ret) dev_err(&pdev->dev, "can't register reboot mode\n"); return ret; } static const struct of_device_id nvmem_reboot_mode_of_match[] = { { .compatible = "nvmem-reboot-mode" }, {} }; MODULE_DEVICE_TABLE(of, nvmem_reboot_mode_of_match); static struct platform_driver nvmem_reboot_mode_driver = { .probe = nvmem_reboot_mode_probe, .driver = { .name = "nvmem-reboot-mode", .of_match_table = nvmem_reboot_mode_of_match, }, }; module_platform_driver(nvmem_reboot_mode_driver); MODULE_AUTHOR("Nandor Han <[email protected]>"); MODULE_DESCRIPTION("NVMEM reboot mode driver"); MODULE_LICENSE("GPL");
linux-master
drivers/power/reset/nvmem-reboot-mode.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (C) 2014 Linaro Ltd. * * Author: Linus Walleij <[email protected]> */ #include <linux/init.h> #include <linux/mfd/syscon.h> #include <linux/reboot.h> #include <linux/regmap.h> #include <linux/of.h> #define INTEGRATOR_HDR_CTRL_OFFSET 0x0C #define INTEGRATOR_HDR_LOCK_OFFSET 0x14 #define INTEGRATOR_CM_CTRL_RESET (1 << 3) #define VERSATILE_SYS_LOCK_OFFSET 0x20 #define VERSATILE_SYS_RESETCTL_OFFSET 0x40 /* Magic unlocking token used on all Versatile boards */ #define VERSATILE_LOCK_VAL 0xA05F /* * We detect the different syscon types from the compatible strings. */ enum versatile_reboot { INTEGRATOR_REBOOT_CM, VERSATILE_REBOOT_CM, REALVIEW_REBOOT_EB, REALVIEW_REBOOT_PB1176, REALVIEW_REBOOT_PB11MP, REALVIEW_REBOOT_PBA8, REALVIEW_REBOOT_PBX, }; /* Pointer to the system controller */ static struct regmap *syscon_regmap; static enum versatile_reboot versatile_reboot_type; static const struct of_device_id versatile_reboot_of_match[] = { { .compatible = "arm,core-module-integrator", .data = (void *)INTEGRATOR_REBOOT_CM }, { .compatible = "arm,core-module-versatile", .data = (void *)VERSATILE_REBOOT_CM, }, { .compatible = "arm,realview-eb-syscon", .data = (void *)REALVIEW_REBOOT_EB, }, { .compatible = "arm,realview-pb1176-syscon", .data = (void *)REALVIEW_REBOOT_PB1176, }, { .compatible = "arm,realview-pb11mp-syscon", .data = (void *)REALVIEW_REBOOT_PB11MP, }, { .compatible = "arm,realview-pba8-syscon", .data = (void *)REALVIEW_REBOOT_PBA8, }, { .compatible = "arm,realview-pbx-syscon", .data = (void *)REALVIEW_REBOOT_PBX, }, {}, }; static int versatile_reboot(struct notifier_block *this, unsigned long mode, void *cmd) { /* Unlock the reset register */ /* Then hit reset on the different machines */ switch (versatile_reboot_type) { case INTEGRATOR_REBOOT_CM: regmap_write(syscon_regmap, INTEGRATOR_HDR_LOCK_OFFSET, VERSATILE_LOCK_VAL); regmap_update_bits(syscon_regmap, INTEGRATOR_HDR_CTRL_OFFSET, INTEGRATOR_CM_CTRL_RESET, INTEGRATOR_CM_CTRL_RESET); break; case VERSATILE_REBOOT_CM: regmap_write(syscon_regmap, VERSATILE_SYS_LOCK_OFFSET, VERSATILE_LOCK_VAL); regmap_update_bits(syscon_regmap, VERSATILE_SYS_RESETCTL_OFFSET, 0x0107, 0x0105); regmap_write(syscon_regmap, VERSATILE_SYS_LOCK_OFFSET, 0); break; case REALVIEW_REBOOT_EB: regmap_write(syscon_regmap, VERSATILE_SYS_LOCK_OFFSET, VERSATILE_LOCK_VAL); regmap_write(syscon_regmap, VERSATILE_SYS_RESETCTL_OFFSET, 0x0008); break; case REALVIEW_REBOOT_PB1176: regmap_write(syscon_regmap, VERSATILE_SYS_LOCK_OFFSET, VERSATILE_LOCK_VAL); regmap_write(syscon_regmap, VERSATILE_SYS_RESETCTL_OFFSET, 0x0100); break; case REALVIEW_REBOOT_PB11MP: case REALVIEW_REBOOT_PBA8: regmap_write(syscon_regmap, VERSATILE_SYS_LOCK_OFFSET, VERSATILE_LOCK_VAL); regmap_write(syscon_regmap, VERSATILE_SYS_RESETCTL_OFFSET, 0x0000); regmap_write(syscon_regmap, VERSATILE_SYS_RESETCTL_OFFSET, 0x0004); break; case REALVIEW_REBOOT_PBX: regmap_write(syscon_regmap, VERSATILE_SYS_LOCK_OFFSET, VERSATILE_LOCK_VAL); regmap_write(syscon_regmap, VERSATILE_SYS_RESETCTL_OFFSET, 0x00f0); regmap_write(syscon_regmap, VERSATILE_SYS_RESETCTL_OFFSET, 0x00f4); break; } dsb(); return NOTIFY_DONE; } static struct notifier_block versatile_reboot_nb = { .notifier_call = versatile_reboot, .priority = 192, }; static int __init versatile_reboot_probe(void) { const struct of_device_id *reboot_id; struct device_node *np; int err; np = of_find_matching_node_and_match(NULL, versatile_reboot_of_match, &reboot_id); if (!np) return -ENODEV; versatile_reboot_type = (enum versatile_reboot)reboot_id->data; syscon_regmap = syscon_node_to_regmap(np); of_node_put(np); if (IS_ERR(syscon_regmap)) return PTR_ERR(syscon_regmap); err = register_restart_handler(&versatile_reboot_nb); if (err) return err; pr_info("versatile reboot driver registered\n"); return 0; } device_initcall(versatile_reboot_probe);
linux-master
drivers/power/reset/arm-versatile-reboot.c
// SPDX-License-Identifier: GPL-2.0 /* * LinkStation power off restart driver * Copyright (C) 2020 Daniel González Cabanelas <[email protected]> */ #include <linux/module.h> #include <linux/notifier.h> #include <linux/of.h> #include <linux/of_mdio.h> #include <linux/of_platform.h> #include <linux/reboot.h> #include <linux/phy.h> /* Defines from the eth phy Marvell driver */ #define MII_MARVELL_COPPER_PAGE 0 #define MII_MARVELL_LED_PAGE 3 #define MII_MARVELL_WOL_PAGE 17 #define MII_MARVELL_PHY_PAGE 22 #define MII_PHY_LED_CTRL 16 #define MII_PHY_LED_POL_CTRL 17 #define MII_88E1318S_PHY_LED_TCR 18 #define MII_88E1318S_PHY_WOL_CTRL 16 #define MII_M1011_IEVENT 19 #define MII_88E1318S_PHY_LED_TCR_INTn_ENABLE BIT(7) #define MII_88E1318S_PHY_LED_TCR_FORCE_INT BIT(15) #define MII_88E1318S_PHY_WOL_CTRL_CLEAR_WOL_STATUS BIT(12) #define LED2_FORCE_ON (0x8 << 8) #define LEDMASK GENMASK(11,8) #define MII_88E1318S_PHY_LED_POL_LED2 BIT(4) struct power_off_cfg { char *mdio_node_name; void (*phy_set_reg)(bool restart); }; static struct phy_device *phydev; static const struct power_off_cfg *cfg; static void linkstation_mvphy_reg_intn(bool restart) { int rc = 0, saved_page; u16 data = 0; if (restart) data = MII_88E1318S_PHY_LED_TCR_FORCE_INT; saved_page = phy_select_page(phydev, MII_MARVELL_LED_PAGE); if (saved_page < 0) goto err; /* Force manual LED2 control to let INTn work */ __phy_modify(phydev, MII_PHY_LED_CTRL, LEDMASK, LED2_FORCE_ON); /* Set the LED[2]/INTn pin to the required state */ __phy_modify(phydev, MII_88E1318S_PHY_LED_TCR, MII_88E1318S_PHY_LED_TCR_FORCE_INT, MII_88E1318S_PHY_LED_TCR_INTn_ENABLE | data); if (!data) { /* Clear interrupts to ensure INTn won't be holded in high state */ __phy_write(phydev, MII_MARVELL_PHY_PAGE, MII_MARVELL_COPPER_PAGE); __phy_read(phydev, MII_M1011_IEVENT); /* If WOL was enabled and a magic packet was received before powering * off, we won't be able to wake up by sending another magic packet. * Clear WOL status. */ __phy_write(phydev, MII_MARVELL_PHY_PAGE, MII_MARVELL_WOL_PAGE); __phy_set_bits(phydev, MII_88E1318S_PHY_WOL_CTRL, MII_88E1318S_PHY_WOL_CTRL_CLEAR_WOL_STATUS); } err: rc = phy_restore_page(phydev, saved_page, rc); if (rc < 0) dev_err(&phydev->mdio.dev, "Write register failed, %d\n", rc); } static void readynas_mvphy_set_reg(bool restart) { int rc = 0, saved_page; u16 data = 0; if (restart) data = MII_88E1318S_PHY_LED_POL_LED2; saved_page = phy_select_page(phydev, MII_MARVELL_LED_PAGE); if (saved_page < 0) goto err; /* Set the LED[2].0 Polarity bit to the required state */ __phy_modify(phydev, MII_PHY_LED_POL_CTRL, MII_88E1318S_PHY_LED_POL_LED2, data); if (!data) { /* If WOL was enabled and a magic packet was received before powering * off, we won't be able to wake up by sending another magic packet. * Clear WOL status. */ __phy_write(phydev, MII_MARVELL_PHY_PAGE, MII_MARVELL_WOL_PAGE); __phy_set_bits(phydev, MII_88E1318S_PHY_WOL_CTRL, MII_88E1318S_PHY_WOL_CTRL_CLEAR_WOL_STATUS); } err: rc = phy_restore_page(phydev, saved_page, rc); if (rc < 0) dev_err(&phydev->mdio.dev, "Write register failed, %d\n", rc); } static const struct power_off_cfg linkstation_power_off_cfg = { .mdio_node_name = "mdio", .phy_set_reg = linkstation_mvphy_reg_intn, }; static const struct power_off_cfg readynas_power_off_cfg = { .mdio_node_name = "mdio-bus", .phy_set_reg = readynas_mvphy_set_reg, }; static int linkstation_reboot_notifier(struct notifier_block *nb, unsigned long action, void *unused) { if (action == SYS_RESTART) cfg->phy_set_reg(true); return NOTIFY_DONE; } static struct notifier_block linkstation_reboot_nb = { .notifier_call = linkstation_reboot_notifier, }; static void linkstation_poweroff(void) { unregister_reboot_notifier(&linkstation_reboot_nb); cfg->phy_set_reg(false); kernel_restart("Power off"); } static const struct of_device_id ls_poweroff_of_match[] = { { .compatible = "buffalo,ls421d", .data = &linkstation_power_off_cfg, }, { .compatible = "buffalo,ls421de", .data = &linkstation_power_off_cfg, }, { .compatible = "netgear,readynas-duo-v2", .data = &readynas_power_off_cfg, }, { }, }; static int __init linkstation_poweroff_init(void) { struct mii_bus *bus; struct device_node *dn; const struct of_device_id *match; dn = of_find_matching_node(NULL, ls_poweroff_of_match); if (!dn) return -ENODEV; of_node_put(dn); match = of_match_node(ls_poweroff_of_match, dn); cfg = match->data; dn = of_find_node_by_name(NULL, cfg->mdio_node_name); if (!dn) return -ENODEV; bus = of_mdio_find_bus(dn); of_node_put(dn); if (!bus) return -EPROBE_DEFER; phydev = phy_find_first(bus); put_device(&bus->dev); if (!phydev) return -EPROBE_DEFER; register_reboot_notifier(&linkstation_reboot_nb); pm_power_off = linkstation_poweroff; return 0; } static void __exit linkstation_poweroff_exit(void) { pm_power_off = NULL; unregister_reboot_notifier(&linkstation_reboot_nb); } module_init(linkstation_poweroff_init); module_exit(linkstation_poweroff_exit); MODULE_AUTHOR("Daniel González Cabanelas <[email protected]>"); MODULE_DESCRIPTION("LinkStation power off driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/power/reset/linkstation-poweroff.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Generic Syscon Reboot Driver * * Copyright (c) 2013, Applied Micro Circuits Corporation * Author: Feng Kan <[email protected]> */ #include <linux/delay.h> #include <linux/io.h> #include <linux/notifier.h> #include <linux/mfd/syscon.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/reboot.h> #include <linux/regmap.h> struct syscon_reboot_context { struct regmap *map; u32 offset; u32 value; u32 mask; struct notifier_block restart_handler; }; static int syscon_restart_handle(struct notifier_block *this, unsigned long mode, void *cmd) { struct syscon_reboot_context *ctx = container_of(this, struct syscon_reboot_context, restart_handler); /* Issue the reboot */ regmap_update_bits(ctx->map, ctx->offset, ctx->mask, ctx->value); mdelay(1000); pr_emerg("Unable to restart system\n"); return NOTIFY_DONE; } static int syscon_reboot_probe(struct platform_device *pdev) { struct syscon_reboot_context *ctx; struct device *dev = &pdev->dev; int mask_err, value_err; int priority; int err; ctx = devm_kzalloc(&pdev->dev, sizeof(*ctx), GFP_KERNEL); if (!ctx) return -ENOMEM; ctx->map = syscon_regmap_lookup_by_phandle(dev->of_node, "regmap"); if (IS_ERR(ctx->map)) { ctx->map = syscon_node_to_regmap(dev->parent->of_node); if (IS_ERR(ctx->map)) return PTR_ERR(ctx->map); } if (of_property_read_s32(pdev->dev.of_node, "priority", &priority)) priority = 192; if (of_property_read_u32(pdev->dev.of_node, "offset", &ctx->offset)) return -EINVAL; value_err = of_property_read_u32(pdev->dev.of_node, "value", &ctx->value); mask_err = of_property_read_u32(pdev->dev.of_node, "mask", &ctx->mask); if (value_err && mask_err) { dev_err(dev, "unable to read 'value' and 'mask'"); return -EINVAL; } if (value_err) { /* support old binding */ ctx->value = ctx->mask; ctx->mask = 0xFFFFFFFF; } else if (mask_err) { /* support value without mask*/ ctx->mask = 0xFFFFFFFF; } ctx->restart_handler.notifier_call = syscon_restart_handle; ctx->restart_handler.priority = priority; err = register_restart_handler(&ctx->restart_handler); if (err) dev_err(dev, "can't register restart notifier (err=%d)\n", err); return err; } static const struct of_device_id syscon_reboot_of_match[] = { { .compatible = "syscon-reboot" }, {} }; static struct platform_driver syscon_reboot_driver = { .probe = syscon_reboot_probe, .driver = { .name = "syscon-reboot", .of_match_table = syscon_reboot_of_match, }, }; builtin_platform_driver(syscon_reboot_driver);
linux-master
drivers/power/reset/syscon-reboot.c
// SPDX-License-Identifier: GPL-2.0-only /* * Toggles a GPIO pin to restart a device * * Copyright (C) 2014 Google, Inc. * * Based on the gpio-poweroff driver. */ #include <linux/reboot.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/platform_device.h> #include <linux/gpio/consumer.h> #include <linux/module.h> #include <linux/of.h> struct gpio_restart { struct gpio_desc *reset_gpio; struct notifier_block restart_handler; u32 active_delay_ms; u32 inactive_delay_ms; u32 wait_delay_ms; }; static int gpio_restart_notify(struct notifier_block *this, unsigned long mode, void *cmd) { struct gpio_restart *gpio_restart = container_of(this, struct gpio_restart, restart_handler); /* drive it active, also inactive->active edge */ gpiod_direction_output(gpio_restart->reset_gpio, 1); mdelay(gpio_restart->active_delay_ms); /* drive inactive, also active->inactive edge */ gpiod_set_value(gpio_restart->reset_gpio, 0); mdelay(gpio_restart->inactive_delay_ms); /* drive it active, also inactive->active edge */ gpiod_set_value(gpio_restart->reset_gpio, 1); /* give it some time */ mdelay(gpio_restart->wait_delay_ms); WARN_ON(1); return NOTIFY_DONE; } static int gpio_restart_probe(struct platform_device *pdev) { struct gpio_restart *gpio_restart; bool open_source = false; u32 property; int ret; gpio_restart = devm_kzalloc(&pdev->dev, sizeof(*gpio_restart), GFP_KERNEL); if (!gpio_restart) return -ENOMEM; open_source = of_property_read_bool(pdev->dev.of_node, "open-source"); gpio_restart->reset_gpio = devm_gpiod_get(&pdev->dev, NULL, open_source ? GPIOD_IN : GPIOD_OUT_LOW); ret = PTR_ERR_OR_ZERO(gpio_restart->reset_gpio); if (ret) { if (ret != -EPROBE_DEFER) dev_err(&pdev->dev, "Could not get reset GPIO\n"); return ret; } gpio_restart->restart_handler.notifier_call = gpio_restart_notify; gpio_restart->restart_handler.priority = 129; gpio_restart->active_delay_ms = 100; gpio_restart->inactive_delay_ms = 100; gpio_restart->wait_delay_ms = 3000; ret = of_property_read_u32(pdev->dev.of_node, "priority", &property); if (!ret) { if (property > 255) dev_err(&pdev->dev, "Invalid priority property: %u\n", property); else gpio_restart->restart_handler.priority = property; } of_property_read_u32(pdev->dev.of_node, "active-delay", &gpio_restart->active_delay_ms); of_property_read_u32(pdev->dev.of_node, "inactive-delay", &gpio_restart->inactive_delay_ms); of_property_read_u32(pdev->dev.of_node, "wait-delay", &gpio_restart->wait_delay_ms); platform_set_drvdata(pdev, gpio_restart); ret = register_restart_handler(&gpio_restart->restart_handler); if (ret) { dev_err(&pdev->dev, "%s: cannot register restart handler, %d\n", __func__, ret); return -ENODEV; } return 0; } static void gpio_restart_remove(struct platform_device *pdev) { struct gpio_restart *gpio_restart = platform_get_drvdata(pdev); int ret; ret = unregister_restart_handler(&gpio_restart->restart_handler); if (ret) { dev_err(&pdev->dev, "%s: cannot unregister restart handler, %d\n", __func__, ret); } } static const struct of_device_id of_gpio_restart_match[] = { { .compatible = "gpio-restart", }, {}, }; static struct platform_driver gpio_restart_driver = { .probe = gpio_restart_probe, .remove_new = gpio_restart_remove, .driver = { .name = "restart-gpio", .of_match_table = of_gpio_restart_match, }, }; module_platform_driver(gpio_restart_driver); MODULE_AUTHOR("David Riley <[email protected]>"); MODULE_DESCRIPTION("GPIO restart driver");
linux-master
drivers/power/reset/gpio-restart.c
// SPDX-License-Identifier: GPL-2.0-only /* * Reset driver for Axxia devices * * Copyright (C) 2014 LSI */ #include <linux/init.h> #include <linux/err.h> #include <linux/io.h> #include <linux/kernel.h> #include <linux/mfd/syscon.h> #include <linux/module.h> #include <linux/notifier.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/reboot.h> #include <linux/regmap.h> #define SC_CRIT_WRITE_KEY 0x1000 #define SC_LATCH_ON_RESET 0x1004 #define SC_RESET_CONTROL 0x1008 #define RSTCTL_RST_ZERO (1<<3) #define RSTCTL_RST_FAB (1<<2) #define RSTCTL_RST_CHIP (1<<1) #define RSTCTL_RST_SYS (1<<0) #define SC_EFUSE_INT_STATUS 0x180c #define EFUSE_READ_DONE (1<<31) static struct regmap *syscon; static int axxia_restart_handler(struct notifier_block *this, unsigned long mode, void *cmd) { /* Access Key (0xab) */ regmap_write(syscon, SC_CRIT_WRITE_KEY, 0xab); /* Select internal boot from 0xffff0000 */ regmap_write(syscon, SC_LATCH_ON_RESET, 0x00000040); /* Assert ResetReadDone (to avoid hanging in boot ROM) */ regmap_write(syscon, SC_EFUSE_INT_STATUS, EFUSE_READ_DONE); /* Assert chip reset */ regmap_update_bits(syscon, SC_RESET_CONTROL, RSTCTL_RST_CHIP, RSTCTL_RST_CHIP); return NOTIFY_DONE; } static struct notifier_block axxia_restart_nb = { .notifier_call = axxia_restart_handler, .priority = 128, }; static int axxia_reset_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; int err; syscon = syscon_regmap_lookup_by_phandle(dev->of_node, "syscon"); if (IS_ERR(syscon)) { pr_err("%pOFn: syscon lookup failed\n", dev->of_node); return PTR_ERR(syscon); } err = register_restart_handler(&axxia_restart_nb); if (err) dev_err(dev, "cannot register restart handler (err=%d)\n", err); return err; } static const struct of_device_id of_axxia_reset_match[] = { { .compatible = "lsi,axm55xx-reset", }, {}, }; MODULE_DEVICE_TABLE(of, of_axxia_reset_match); static struct platform_driver axxia_reset_driver = { .probe = axxia_reset_probe, .driver = { .name = "axxia-reset", .of_match_table = of_match_ptr(of_axxia_reset_match), }, }; static int __init axxia_reset_init(void) { return platform_driver_register(&axxia_reset_driver); } device_initcall(axxia_reset_init);
linux-master
drivers/power/reset/axxia-reset.c
// SPDX-License-Identifier: GPL-2.0+ /* * Copyright (c) 2023 Neil Armstrong <[email protected]> */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/mfd/rk808.h> #include <linux/regmap.h> #include <linux/module.h> #include <linux/reboot.h> #include <linux/i2c.h> /* * The Odroid Go Ultra has 2 PMICs: * - RK818 (manages the battery and USB-C power supply) * - RK817 * Both PMICs feeds power to the S922X SoC, so they must be powered-off in sequence. * Vendor does power-off the RK817 first, then the RK818 so here we follow this sequence. */ struct odroid_go_ultra_poweroff_data { struct device *dev; struct device *rk817; struct device *rk818; }; static int odroid_go_ultra_poweroff_prepare(struct sys_off_data *data) { struct odroid_go_ultra_poweroff_data *poweroff_data = data->cb_data; struct regmap *rk817, *rk818; int ret; /* RK817 Regmap */ rk817 = dev_get_regmap(poweroff_data->rk817, NULL); if (!rk817) { dev_err(poweroff_data->dev, "failed to get rk817 regmap\n"); return notifier_from_errno(-EINVAL); } /* RK818 Regmap */ rk818 = dev_get_regmap(poweroff_data->rk818, NULL); if (!rk818) { dev_err(poweroff_data->dev, "failed to get rk818 regmap\n"); return notifier_from_errno(-EINVAL); } dev_info(poweroff_data->dev, "Setting PMICs for power off"); /* RK817 */ ret = regmap_update_bits(rk817, RK817_SYS_CFG(3), DEV_OFF, DEV_OFF); if (ret) { dev_err(poweroff_data->dev, "failed to poweroff rk817\n"); return notifier_from_errno(ret); } /* RK818 */ ret = regmap_update_bits(rk818, RK818_DEVCTRL_REG, DEV_OFF, DEV_OFF); if (ret) { dev_err(poweroff_data->dev, "failed to poweroff rk818\n"); return notifier_from_errno(ret); } return NOTIFY_OK; } static void odroid_go_ultra_poweroff_put_pmic_device(void *data) { struct device *dev = data; put_device(dev); } static int odroid_go_ultra_poweroff_get_pmic_device(struct device *dev, const char *compatible, struct device **pmic) { struct device_node *pmic_node; struct i2c_client *pmic_client; pmic_node = of_find_compatible_node(NULL, NULL, compatible); if (!pmic_node) return -ENODEV; pmic_client = of_find_i2c_device_by_node(pmic_node); of_node_put(pmic_node); if (!pmic_client) return -EPROBE_DEFER; *pmic = &pmic_client->dev; return devm_add_action_or_reset(dev, odroid_go_ultra_poweroff_put_pmic_device, *pmic); } static int odroid_go_ultra_poweroff_probe(struct platform_device *pdev) { struct odroid_go_ultra_poweroff_data *poweroff_data; int ret; poweroff_data = devm_kzalloc(&pdev->dev, sizeof(*poweroff_data), GFP_KERNEL); if (!poweroff_data) return -ENOMEM; dev_set_drvdata(&pdev->dev, poweroff_data); /* RK818 PMIC Device */ ret = odroid_go_ultra_poweroff_get_pmic_device(&pdev->dev, "rockchip,rk818", &poweroff_data->rk818); if (ret) return dev_err_probe(&pdev->dev, ret, "failed to get rk818 mfd data\n"); /* RK817 PMIC Device */ ret = odroid_go_ultra_poweroff_get_pmic_device(&pdev->dev, "rockchip,rk817", &poweroff_data->rk817); if (ret) return dev_err_probe(&pdev->dev, ret, "failed to get rk817 mfd data\n"); /* Register as SYS_OFF_MODE_POWER_OFF_PREPARE because regmap_update_bits may sleep */ ret = devm_register_sys_off_handler(&pdev->dev, SYS_OFF_MODE_POWER_OFF_PREPARE, SYS_OFF_PRIO_DEFAULT, odroid_go_ultra_poweroff_prepare, poweroff_data); if (ret) return dev_err_probe(&pdev->dev, ret, "failed to register sys-off handler\n"); dev_info(&pdev->dev, "Registered Power-Off handler\n"); return 0; } static struct platform_device *pdev; static struct platform_driver odroid_go_ultra_poweroff_driver = { .driver = { .name = "odroid-go-ultra-poweroff", }, .probe = odroid_go_ultra_poweroff_probe, }; static int __init odroid_go_ultra_poweroff_init(void) { int ret; /* Only create when running on the Odroid Go Ultra device */ if (!of_device_is_compatible(of_root, "hardkernel,odroid-go-ultra")) return -ENODEV; ret = platform_driver_register(&odroid_go_ultra_poweroff_driver); if (ret) return ret; pdev = platform_device_register_resndata(NULL, "odroid-go-ultra-poweroff", -1, NULL, 0, NULL, 0); if (IS_ERR(pdev)) { platform_driver_unregister(&odroid_go_ultra_poweroff_driver); return PTR_ERR(pdev); } return 0; } static void __exit odroid_go_ultra_poweroff_exit(void) { /* Only delete when running on the Odroid Go Ultra device */ if (!of_device_is_compatible(of_root, "hardkernel,odroid-go-ultra")) return; platform_device_unregister(pdev); platform_driver_unregister(&odroid_go_ultra_poweroff_driver); } module_init(odroid_go_ultra_poweroff_init); module_exit(odroid_go_ultra_poweroff_exit); MODULE_AUTHOR("Neil Armstrong <[email protected]>"); MODULE_DESCRIPTION("Odroid Go Ultra poweroff driver"); MODULE_LICENSE("GPL");
linux-master
drivers/power/reset/odroid-go-ultra-poweroff.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (C) 2014 STMicroelectronics * * Power off Restart driver, used in STMicroelectronics devices. * * Author: Christophe Kerello <[email protected]> */ #include <linux/module.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/platform_device.h> #include <linux/mfd/syscon.h> #include <linux/reboot.h> #include <linux/regmap.h> struct reset_syscfg { struct regmap *regmap; /* syscfg used for reset */ unsigned int offset_rst; unsigned int mask_rst; /* syscfg used for unmask the reset */ unsigned int offset_rst_msk; unsigned int mask_rst_msk; }; /* STiH407 */ #define STIH407_SYSCFG_4000 0x0 #define STIH407_SYSCFG_4008 0x20 static struct reset_syscfg stih407_reset = { .offset_rst = STIH407_SYSCFG_4000, .mask_rst = BIT(0), .offset_rst_msk = STIH407_SYSCFG_4008, .mask_rst_msk = BIT(0) }; static struct reset_syscfg *st_restart_syscfg; static int st_restart(struct notifier_block *this, unsigned long mode, void *cmd) { /* reset syscfg updated */ regmap_update_bits(st_restart_syscfg->regmap, st_restart_syscfg->offset_rst, st_restart_syscfg->mask_rst, 0); /* unmask the reset */ regmap_update_bits(st_restart_syscfg->regmap, st_restart_syscfg->offset_rst_msk, st_restart_syscfg->mask_rst_msk, 0); return NOTIFY_DONE; } static struct notifier_block st_restart_nb = { .notifier_call = st_restart, .priority = 192, }; static const struct of_device_id st_reset_of_match[] = { { .compatible = "st,stih407-restart", .data = (void *)&stih407_reset, }, {} }; static int st_reset_probe(struct platform_device *pdev) { struct device_node *np = pdev->dev.of_node; const struct of_device_id *match; struct device *dev = &pdev->dev; match = of_match_device(st_reset_of_match, dev); if (!match) return -ENODEV; st_restart_syscfg = (struct reset_syscfg *)match->data; st_restart_syscfg->regmap = syscon_regmap_lookup_by_phandle(np, "st,syscfg"); if (IS_ERR(st_restart_syscfg->regmap)) { dev_err(dev, "No syscfg phandle specified\n"); return PTR_ERR(st_restart_syscfg->regmap); } return register_restart_handler(&st_restart_nb); } static struct platform_driver st_reset_driver = { .probe = st_reset_probe, .driver = { .name = "st_reset", .of_match_table = st_reset_of_match, }, }; static int __init st_reset_init(void) { return platform_driver_register(&st_reset_driver); } device_initcall(st_reset_init); MODULE_AUTHOR("Christophe Kerello <[email protected]>"); MODULE_DESCRIPTION("STMicroelectronics Power off Restart driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/power/reset/st-poweroff.c
// SPDX-License-Identifier: GPL-2.0-only // Copyright (C) 2016 Broadcom #include <linux/io.h> #include <linux/mod_devicetable.h> #include <linux/platform_device.h> #include <linux/reboot.h> #define RSTMGR_REG_WR_ACCESS_OFFSET 0 #define RSTMGR_REG_CHIP_SOFT_RST_OFFSET 4 #define RSTMGR_WR_PASSWORD 0xa5a5 #define RSTMGR_WR_PASSWORD_SHIFT 8 #define RSTMGR_WR_ACCESS_ENABLE 1 static void __iomem *kona_reset_base; static int kona_reset_handler(struct notifier_block *this, unsigned long mode, void *cmd) { /* * A soft reset is triggered by writing a 0 to bit 0 of the soft reset * register. To write to that register we must first write the password * and the enable bit in the write access enable register. */ writel((RSTMGR_WR_PASSWORD << RSTMGR_WR_PASSWORD_SHIFT) | RSTMGR_WR_ACCESS_ENABLE, kona_reset_base + RSTMGR_REG_WR_ACCESS_OFFSET); writel(0, kona_reset_base + RSTMGR_REG_CHIP_SOFT_RST_OFFSET); return NOTIFY_DONE; } static struct notifier_block kona_reset_nb = { .notifier_call = kona_reset_handler, .priority = 128, }; static int kona_reset_probe(struct platform_device *pdev) { kona_reset_base = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(kona_reset_base)) return PTR_ERR(kona_reset_base); return register_restart_handler(&kona_reset_nb); } static const struct of_device_id of_match[] = { { .compatible = "brcm,bcm21664-resetmgr" }, {}, }; static struct platform_driver bcm_kona_reset_driver = { .probe = kona_reset_probe, .driver = { .name = "brcm-kona-reset", .of_match_table = of_match, }, }; builtin_platform_driver(bcm_kona_reset_driver);
linux-master
drivers/power/reset/brcm-kona-reset.c
// SPDX-License-Identifier: GPL-2.0 /* * Copyright (C) 2018 Spreadtrum Communications Inc. * Copyright (C) 2018 Linaro Ltd. */ #include <linux/cpu.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/pm.h> #include <linux/regmap.h> #include <linux/syscore_ops.h> #define SC27XX_PWR_PD_HW 0xc2c #define SC27XX_PWR_OFF_EN BIT(0) #define SC27XX_SLP_CTRL 0xdf0 #define SC27XX_LDO_XTL_EN BIT(3) static struct regmap *regmap; /* * On Spreadtrum platform, we need power off system through external SC27xx * series PMICs, and it is one similar SPI bus mapped by regmap to access PMIC, * which is not fast io access. * * So before stopping other cores, we need release other cores' resource by * taking cpus down to avoid racing regmap or spi mutex lock when poweroff * system through PMIC. */ static void sc27xx_poweroff_shutdown(void) { #ifdef CONFIG_HOTPLUG_CPU int cpu; for_each_online_cpu(cpu) { if (cpu != smp_processor_id()) remove_cpu(cpu); } #endif } static struct syscore_ops poweroff_syscore_ops = { .shutdown = sc27xx_poweroff_shutdown, }; static void sc27xx_poweroff_do_poweroff(void) { /* Disable the external subsys connection's power firstly */ regmap_write(regmap, SC27XX_SLP_CTRL, SC27XX_LDO_XTL_EN); regmap_write(regmap, SC27XX_PWR_PD_HW, SC27XX_PWR_OFF_EN); } static int sc27xx_poweroff_probe(struct platform_device *pdev) { if (regmap) return -EINVAL; regmap = dev_get_regmap(pdev->dev.parent, NULL); if (!regmap) return -ENODEV; pm_power_off = sc27xx_poweroff_do_poweroff; register_syscore_ops(&poweroff_syscore_ops); return 0; } static struct platform_driver sc27xx_poweroff_driver = { .probe = sc27xx_poweroff_probe, .driver = { .name = "sc27xx-poweroff", }, }; module_platform_driver(sc27xx_poweroff_driver); MODULE_DESCRIPTION("Power off driver for SC27XX PMIC Device"); MODULE_AUTHOR("Baolin Wang <[email protected]>"); MODULE_LICENSE("GPL v2");
linux-master
drivers/power/reset/sc27xx-poweroff.c
// SPDX-License-Identifier: GPL-2.0 // Copyright (c) 2017-18 Linaro Limited #include <linux/delay.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/of.h> #include <linux/of_platform.h> #include <linux/platform_device.h> #include <linux/reboot.h> #include <linux/reboot-mode.h> #include <linux/regmap.h> #define PON_SOFT_RB_SPARE 0x8f #define GEN1_REASON_SHIFT 2 #define GEN2_REASON_SHIFT 1 #define NO_REASON_SHIFT 0 struct pm8916_pon { struct device *dev; struct regmap *regmap; u32 baseaddr; struct reboot_mode_driver reboot_mode; long reason_shift; }; static int pm8916_reboot_mode_write(struct reboot_mode_driver *reboot, unsigned int magic) { struct pm8916_pon *pon = container_of (reboot, struct pm8916_pon, reboot_mode); int ret; ret = regmap_update_bits(pon->regmap, pon->baseaddr + PON_SOFT_RB_SPARE, GENMASK(7, pon->reason_shift), magic << pon->reason_shift); if (ret < 0) dev_err(pon->dev, "update reboot mode bits failed\n"); return ret; } static int pm8916_pon_probe(struct platform_device *pdev) { struct pm8916_pon *pon; long reason_shift; int error; pon = devm_kzalloc(&pdev->dev, sizeof(*pon), GFP_KERNEL); if (!pon) return -ENOMEM; pon->dev = &pdev->dev; pon->regmap = dev_get_regmap(pdev->dev.parent, NULL); if (!pon->regmap) { dev_err(&pdev->dev, "failed to locate regmap\n"); return -ENODEV; } error = of_property_read_u32(pdev->dev.of_node, "reg", &pon->baseaddr); if (error) return error; reason_shift = (long)of_device_get_match_data(&pdev->dev); if (reason_shift != NO_REASON_SHIFT) { pon->reboot_mode.dev = &pdev->dev; pon->reason_shift = reason_shift; pon->reboot_mode.write = pm8916_reboot_mode_write; error = devm_reboot_mode_register(&pdev->dev, &pon->reboot_mode); if (error) { dev_err(&pdev->dev, "can't register reboot mode\n"); return error; } } platform_set_drvdata(pdev, pon); return devm_of_platform_populate(&pdev->dev); } static const struct of_device_id pm8916_pon_id_table[] = { { .compatible = "qcom,pm8916-pon", .data = (void *)GEN1_REASON_SHIFT }, { .compatible = "qcom,pm8941-pon", .data = (void *)NO_REASON_SHIFT }, { .compatible = "qcom,pms405-pon", .data = (void *)GEN1_REASON_SHIFT }, { .compatible = "qcom,pm8998-pon", .data = (void *)GEN2_REASON_SHIFT }, { .compatible = "qcom,pmk8350-pon", .data = (void *)GEN2_REASON_SHIFT }, { } }; MODULE_DEVICE_TABLE(of, pm8916_pon_id_table); static struct platform_driver pm8916_pon_driver = { .probe = pm8916_pon_probe, .driver = { .name = "pm8916-pon", .of_match_table = pm8916_pon_id_table, }, }; module_platform_driver(pm8916_pon_driver); MODULE_DESCRIPTION("pm8916 Power On driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/power/reset/qcom-pon.c
// SPDX-License-Identifier: GPL-2.0-only /* * Force-disables a regulator to power down a device * * Michael Klein <[email protected]> * * Copyright (C) 2020 Michael Klein * * Based on the gpio-poweroff driver. */ #include <linux/delay.h> #include <linux/module.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/pm.h> #include <linux/regulator/consumer.h> #define TIMEOUT_MS 3000 /* * Hold configuration here, cannot be more than one instance of the driver * since pm_power_off itself is global. */ static struct regulator *cpu_regulator; static void regulator_poweroff_do_poweroff(void) { if (cpu_regulator && regulator_is_enabled(cpu_regulator)) regulator_force_disable(cpu_regulator); /* give it some time */ mdelay(TIMEOUT_MS); WARN_ON(1); } static int regulator_poweroff_probe(struct platform_device *pdev) { /* If a pm_power_off function has already been added, leave it alone */ if (pm_power_off != NULL) { dev_err(&pdev->dev, "%s: pm_power_off function already registered\n", __func__); return -EBUSY; } cpu_regulator = devm_regulator_get(&pdev->dev, "cpu"); if (IS_ERR(cpu_regulator)) return PTR_ERR(cpu_regulator); pm_power_off = &regulator_poweroff_do_poweroff; return 0; } static int regulator_poweroff_remove(__maybe_unused struct platform_device *pdev) { if (pm_power_off == &regulator_poweroff_do_poweroff) pm_power_off = NULL; return 0; } static const struct of_device_id of_regulator_poweroff_match[] = { { .compatible = "regulator-poweroff", }, {}, }; MODULE_DEVICE_TABLE(of, of_regulator_poweroff_match); static struct platform_driver regulator_poweroff_driver = { .probe = regulator_poweroff_probe, .remove = regulator_poweroff_remove, .driver = { .name = "poweroff-regulator", .of_match_table = of_regulator_poweroff_match, }, }; module_platform_driver(regulator_poweroff_driver); MODULE_AUTHOR("Michael Klein <[email protected]>"); MODULE_DESCRIPTION("Regulator poweroff driver"); MODULE_ALIAS("platform:poweroff-regulator");
linux-master
drivers/power/reset/regulator-poweroff.c
// SPDX-License-Identifier: GPL-2.0-only /* * * Copyright (C) 2012 ARM Limited */ #include <linux/delay.h> #include <linux/notifier.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/platform_device.h> #include <linux/reboot.h> #include <linux/stat.h> #include <linux/vexpress.h> static void vexpress_reset_do(struct device *dev, const char *what) { int err = -ENOENT; struct regmap *reg = dev_get_drvdata(dev); if (reg) { err = regmap_write(reg, 0, 0); if (!err) mdelay(1000); } dev_emerg(dev, "Unable to %s (%d)\n", what, err); } static struct device *vexpress_power_off_device; static atomic_t vexpress_restart_nb_refcnt = ATOMIC_INIT(0); static void vexpress_power_off(void) { vexpress_reset_do(vexpress_power_off_device, "power off"); } static struct device *vexpress_restart_device; static int vexpress_restart(struct notifier_block *this, unsigned long mode, void *cmd) { vexpress_reset_do(vexpress_restart_device, "restart"); return NOTIFY_DONE; } static struct notifier_block vexpress_restart_nb = { .notifier_call = vexpress_restart, .priority = 128, }; static ssize_t vexpress_reset_active_show(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%d\n", vexpress_restart_device == dev); } static ssize_t vexpress_reset_active_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { long value; int err = kstrtol(buf, 0, &value); if (!err && value) vexpress_restart_device = dev; return err ? err : count; } static DEVICE_ATTR(active, S_IRUGO | S_IWUSR, vexpress_reset_active_show, vexpress_reset_active_store); enum vexpress_reset_func { FUNC_RESET, FUNC_SHUTDOWN, FUNC_REBOOT }; static const struct of_device_id vexpress_reset_of_match[] = { { .compatible = "arm,vexpress-reset", .data = (void *)FUNC_RESET, }, { .compatible = "arm,vexpress-shutdown", .data = (void *)FUNC_SHUTDOWN }, { .compatible = "arm,vexpress-reboot", .data = (void *)FUNC_REBOOT }, {} }; static int _vexpress_register_restart_handler(struct device *dev) { int err; vexpress_restart_device = dev; if (atomic_inc_return(&vexpress_restart_nb_refcnt) == 1) { err = register_restart_handler(&vexpress_restart_nb); if (err) { dev_err(dev, "cannot register restart handler (err=%d)\n", err); atomic_dec(&vexpress_restart_nb_refcnt); return err; } } device_create_file(dev, &dev_attr_active); return 0; } static int vexpress_reset_probe(struct platform_device *pdev) { const struct of_device_id *match = of_match_device(vexpress_reset_of_match, &pdev->dev); struct regmap *regmap; int ret = 0; if (!match) return -EINVAL; regmap = devm_regmap_init_vexpress_config(&pdev->dev); if (IS_ERR(regmap)) return PTR_ERR(regmap); dev_set_drvdata(&pdev->dev, regmap); switch ((enum vexpress_reset_func)match->data) { case FUNC_SHUTDOWN: vexpress_power_off_device = &pdev->dev; pm_power_off = vexpress_power_off; break; case FUNC_RESET: if (!vexpress_restart_device) ret = _vexpress_register_restart_handler(&pdev->dev); break; case FUNC_REBOOT: ret = _vexpress_register_restart_handler(&pdev->dev); break; } return ret; } static struct platform_driver vexpress_reset_driver = { .probe = vexpress_reset_probe, .driver = { .name = "vexpress-reset", .of_match_table = vexpress_reset_of_match, .suppress_bind_attrs = true, }, }; builtin_platform_driver(vexpress_reset_driver);
linux-master
drivers/power/reset/vexpress-poweroff.c
/* * 1-Wire implementation for Maxim Semiconductor * MAX7211/MAX17215 standalone fuel gauge chip * * Copyright (C) 2017 Radioavionica Corporation * Author: Alex A. Mihaylov <[email protected]> * * Use consistent with the GNU GPL is permitted, * provided that this copyright notice is * preserved in its entirety in all copies and derived works. * */ #include <linux/module.h> #include <linux/slab.h> #include <linux/w1.h> #include <linux/regmap.h> #include <linux/power_supply.h> #define W1_MAX1721X_FAMILY_ID 0x26 #define DEF_DEV_NAME_MAX17211 "MAX17211" #define DEF_DEV_NAME_MAX17215 "MAX17215" #define DEF_DEV_NAME_UNKNOWN "UNKNOWN" #define DEF_MFG_NAME "MAXIM" #define PSY_MAX_NAME_LEN 32 /* Number of valid register addresses in W1 mode */ #define MAX1721X_MAX_REG_NR 0x1EF /* Factory settings (nonvolatile registers) (W1 specific) */ #define MAX1721X_REG_NRSENSE 0x1CF /* RSense in 10^-5 Ohm */ /* Strings */ #define MAX1721X_REG_MFG_STR 0x1CC #define MAX1721X_REG_MFG_NUMB 3 #define MAX1721X_REG_DEV_STR 0x1DB #define MAX1721X_REG_DEV_NUMB 5 /* HEX Strings */ #define MAX1721X_REG_SER_HEX 0x1D8 /* MAX172XX Output Registers for W1 chips */ #define MAX172XX_REG_STATUS 0x000 /* status reg */ #define MAX172XX_BAT_PRESENT (1<<4) /* battery connected bit */ #define MAX172XX_REG_DEVNAME 0x021 /* chip config */ #define MAX172XX_DEV_MASK 0x000F /* chip type mask */ #define MAX172X1_DEV 0x0001 #define MAX172X5_DEV 0x0005 #define MAX172XX_REG_TEMP 0x008 /* Temperature */ #define MAX172XX_REG_BATT 0x0DA /* Battery voltage */ #define MAX172XX_REG_CURRENT 0x00A /* Actual current */ #define MAX172XX_REG_AVGCURRENT 0x00B /* Average current */ #define MAX172XX_REG_REPSOC 0x006 /* Percentage of charge */ #define MAX172XX_REG_DESIGNCAP 0x018 /* Design capacity */ #define MAX172XX_REG_REPCAP 0x005 /* Average capacity */ #define MAX172XX_REG_TTE 0x011 /* Time to empty */ #define MAX172XX_REG_TTF 0x020 /* Time to full */ struct max17211_device_info { char name[PSY_MAX_NAME_LEN]; struct power_supply *bat; struct power_supply_desc bat_desc; struct device *w1_dev; struct regmap *regmap; /* battery design format */ unsigned int rsense; /* in tenths uOhm */ char DeviceName[2 * MAX1721X_REG_DEV_NUMB + 1]; char ManufacturerName[2 * MAX1721X_REG_MFG_NUMB + 1]; char SerialNumber[13]; /* see get_sn_str() later for comment */ }; /* Convert regs value to power_supply units */ static inline int max172xx_time_to_ps(unsigned int reg) { return reg * 5625 / 1000; /* in sec. */ } static inline int max172xx_percent_to_ps(unsigned int reg) { return reg / 256; /* in percent from 0 to 100 */ } static inline int max172xx_voltage_to_ps(unsigned int reg) { return reg * 1250; /* in uV */ } static inline int max172xx_capacity_to_ps(unsigned int reg) { return reg * 500; /* in uAh */ } /* * Current and temperature is signed values, so unsigned regs * value must be converted to signed type */ static inline int max172xx_temperature_to_ps(unsigned int reg) { int val = (int16_t)(reg); return val * 10 / 256; /* in tenths of deg. C */ } /* * Calculating current registers resolution: * * RSense stored in 10^-5 Ohm, so measurement voltage must be * in 10^-11 Volts for get current in uA. * 16 bit current reg fullscale +/-51.2mV is 102400 uV. * So: 102400 / 65535 * 10^5 = 156252 */ static inline int max172xx_current_to_voltage(unsigned int reg) { int val = (int16_t)(reg); return val * 156252; } static inline struct max17211_device_info * to_device_info(struct power_supply *psy) { return power_supply_get_drvdata(psy); } static int max1721x_battery_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct max17211_device_info *info = to_device_info(psy); unsigned int reg = 0; int ret = 0; switch (psp) { case POWER_SUPPLY_PROP_PRESENT: /* * POWER_SUPPLY_PROP_PRESENT will always readable via * sysfs interface. Value return 0 if battery not * present or unaccessible via W1. */ val->intval = regmap_read(info->regmap, MAX172XX_REG_STATUS, &reg) ? 0 : !(reg & MAX172XX_BAT_PRESENT); break; case POWER_SUPPLY_PROP_CAPACITY: ret = regmap_read(info->regmap, MAX172XX_REG_REPSOC, &reg); val->intval = max172xx_percent_to_ps(reg); break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: ret = regmap_read(info->regmap, MAX172XX_REG_BATT, &reg); val->intval = max172xx_voltage_to_ps(reg); break; case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN: ret = regmap_read(info->regmap, MAX172XX_REG_DESIGNCAP, &reg); val->intval = max172xx_capacity_to_ps(reg); break; case POWER_SUPPLY_PROP_CHARGE_AVG: ret = regmap_read(info->regmap, MAX172XX_REG_REPCAP, &reg); val->intval = max172xx_capacity_to_ps(reg); break; case POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG: ret = regmap_read(info->regmap, MAX172XX_REG_TTE, &reg); val->intval = max172xx_time_to_ps(reg); break; case POWER_SUPPLY_PROP_TIME_TO_FULL_AVG: ret = regmap_read(info->regmap, MAX172XX_REG_TTF, &reg); val->intval = max172xx_time_to_ps(reg); break; case POWER_SUPPLY_PROP_TEMP: ret = regmap_read(info->regmap, MAX172XX_REG_TEMP, &reg); val->intval = max172xx_temperature_to_ps(reg); break; /* We need signed current, so must cast info->rsense to signed type */ case POWER_SUPPLY_PROP_CURRENT_NOW: ret = regmap_read(info->regmap, MAX172XX_REG_CURRENT, &reg); val->intval = max172xx_current_to_voltage(reg) / (int)info->rsense; break; case POWER_SUPPLY_PROP_CURRENT_AVG: ret = regmap_read(info->regmap, MAX172XX_REG_AVGCURRENT, &reg); val->intval = max172xx_current_to_voltage(reg) / (int)info->rsense; break; /* * Strings already received and inited by probe. * We do dummy read for check battery still available. */ case POWER_SUPPLY_PROP_MODEL_NAME: ret = regmap_read(info->regmap, MAX1721X_REG_DEV_STR, &reg); val->strval = info->DeviceName; break; case POWER_SUPPLY_PROP_MANUFACTURER: ret = regmap_read(info->regmap, MAX1721X_REG_MFG_STR, &reg); val->strval = info->ManufacturerName; break; case POWER_SUPPLY_PROP_SERIAL_NUMBER: ret = regmap_read(info->regmap, MAX1721X_REG_SER_HEX, &reg); val->strval = info->SerialNumber; break; default: ret = -EINVAL; } return ret; } static enum power_supply_property max1721x_battery_props[] = { /* int */ POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_CAPACITY, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN, POWER_SUPPLY_PROP_CHARGE_AVG, POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG, POWER_SUPPLY_PROP_TIME_TO_FULL_AVG, POWER_SUPPLY_PROP_TEMP, POWER_SUPPLY_PROP_CURRENT_NOW, POWER_SUPPLY_PROP_CURRENT_AVG, /* strings */ POWER_SUPPLY_PROP_MODEL_NAME, POWER_SUPPLY_PROP_MANUFACTURER, POWER_SUPPLY_PROP_SERIAL_NUMBER, }; static int get_string(struct max17211_device_info *info, uint16_t reg, uint8_t nr, char *str) { unsigned int val; if (!str || !(reg == MAX1721X_REG_MFG_STR || reg == MAX1721X_REG_DEV_STR)) return -EFAULT; while (nr--) { if (regmap_read(info->regmap, reg++, &val)) return -EFAULT; *str++ = val>>8 & 0x00FF; *str++ = val & 0x00FF; } return 0; } /* Maxim say: Serial number is a hex string up to 12 hex characters */ static int get_sn_string(struct max17211_device_info *info, char *str) { unsigned int val[3]; if (!str) return -EFAULT; if (regmap_read(info->regmap, MAX1721X_REG_SER_HEX, &val[0])) return -EFAULT; if (regmap_read(info->regmap, MAX1721X_REG_SER_HEX + 1, &val[1])) return -EFAULT; if (regmap_read(info->regmap, MAX1721X_REG_SER_HEX + 2, &val[2])) return -EFAULT; snprintf(str, 13, "%04X%04X%04X", val[0], val[1], val[2]); return 0; } /* * MAX1721x registers description for w1-regmap */ static const struct regmap_range max1721x_allow_range[] = { regmap_reg_range(0, 0xDF), /* volatile data */ regmap_reg_range(0x180, 0x1DF), /* non-volatile memory */ regmap_reg_range(0x1E0, 0x1EF), /* non-volatile history (unused) */ }; static const struct regmap_range max1721x_deny_range[] = { /* volatile data unused registers */ regmap_reg_range(0x24, 0x26), regmap_reg_range(0x30, 0x31), regmap_reg_range(0x33, 0x34), regmap_reg_range(0x37, 0x37), regmap_reg_range(0x3B, 0x3C), regmap_reg_range(0x40, 0x41), regmap_reg_range(0x43, 0x44), regmap_reg_range(0x47, 0x49), regmap_reg_range(0x4B, 0x4C), regmap_reg_range(0x4E, 0xAF), regmap_reg_range(0xB1, 0xB3), regmap_reg_range(0xB5, 0xB7), regmap_reg_range(0xBF, 0xD0), regmap_reg_range(0xDB, 0xDB), /* hole between volatile and non-volatile registers */ regmap_reg_range(0xE0, 0x17F), }; static const struct regmap_access_table max1721x_regs = { .yes_ranges = max1721x_allow_range, .n_yes_ranges = ARRAY_SIZE(max1721x_allow_range), .no_ranges = max1721x_deny_range, .n_no_ranges = ARRAY_SIZE(max1721x_deny_range), }; /* * Model Gauge M5 Algorithm output register * Volatile data (must not be cached) */ static const struct regmap_range max1721x_volatile_allow[] = { regmap_reg_range(0, 0xDF), }; static const struct regmap_access_table max1721x_volatile_regs = { .yes_ranges = max1721x_volatile_allow, .n_yes_ranges = ARRAY_SIZE(max1721x_volatile_allow), }; /* * W1-regmap config */ static const struct regmap_config max1721x_regmap_w1_config = { .reg_bits = 16, .val_bits = 16, .rd_table = &max1721x_regs, .volatile_table = &max1721x_volatile_regs, .max_register = MAX1721X_MAX_REG_NR, }; static int devm_w1_max1721x_add_device(struct w1_slave *sl) { struct power_supply_config psy_cfg = {}; struct max17211_device_info *info; info = devm_kzalloc(&sl->dev, sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; sl->family_data = (void *)info; info->w1_dev = &sl->dev; /* * power_supply class battery name translated from W1 slave device * unique ID (look like 26-0123456789AB) to "max1721x-0123456789AB\0" * so, 26 (device family) correspond to max1721x devices. * Device name still unique for any number of connected devices. */ snprintf(info->name, sizeof(info->name), "max1721x-%012X", (unsigned int)sl->reg_num.id); info->bat_desc.name = info->name; /* * FixMe: battery device name exceed max len for thermal_zone device * name and translation to thermal_zone must be disabled. */ info->bat_desc.no_thermal = true; info->bat_desc.type = POWER_SUPPLY_TYPE_BATTERY; info->bat_desc.properties = max1721x_battery_props; info->bat_desc.num_properties = ARRAY_SIZE(max1721x_battery_props); info->bat_desc.get_property = max1721x_battery_get_property; psy_cfg.drv_data = info; /* regmap init */ info->regmap = devm_regmap_init_w1(info->w1_dev, &max1721x_regmap_w1_config); if (IS_ERR(info->regmap)) { int err = PTR_ERR(info->regmap); dev_err(info->w1_dev, "Failed to allocate register map: %d\n", err); return err; } /* rsense init */ info->rsense = 0; if (regmap_read(info->regmap, MAX1721X_REG_NRSENSE, &info->rsense)) { dev_err(info->w1_dev, "Can't read RSense. Hardware error.\n"); return -ENODEV; } if (!info->rsense) { dev_warn(info->w1_dev, "RSense not calibrated, set 10 mOhms!\n"); info->rsense = 1000; /* in regs in 10^-5 */ } dev_info(info->w1_dev, "RSense: %d mOhms.\n", info->rsense / 100); if (get_string(info, MAX1721X_REG_MFG_STR, MAX1721X_REG_MFG_NUMB, info->ManufacturerName)) { dev_err(info->w1_dev, "Can't read manufacturer. Hardware error.\n"); return -ENODEV; } if (!info->ManufacturerName[0]) strscpy(info->ManufacturerName, DEF_MFG_NAME, 2 * MAX1721X_REG_MFG_NUMB); if (get_string(info, MAX1721X_REG_DEV_STR, MAX1721X_REG_DEV_NUMB, info->DeviceName)) { dev_err(info->w1_dev, "Can't read device. Hardware error.\n"); return -ENODEV; } if (!info->DeviceName[0]) { unsigned int dev_name; if (regmap_read(info->regmap, MAX172XX_REG_DEVNAME, &dev_name)) { dev_err(info->w1_dev, "Can't read device name reg.\n"); return -ENODEV; } switch (dev_name & MAX172XX_DEV_MASK) { case MAX172X1_DEV: strscpy(info->DeviceName, DEF_DEV_NAME_MAX17211, 2 * MAX1721X_REG_DEV_NUMB); break; case MAX172X5_DEV: strscpy(info->DeviceName, DEF_DEV_NAME_MAX17215, 2 * MAX1721X_REG_DEV_NUMB); break; default: strscpy(info->DeviceName, DEF_DEV_NAME_UNKNOWN, 2 * MAX1721X_REG_DEV_NUMB); } } if (get_sn_string(info, info->SerialNumber)) { dev_err(info->w1_dev, "Can't read serial. Hardware error.\n"); return -ENODEV; } info->bat = devm_power_supply_register(&sl->dev, &info->bat_desc, &psy_cfg); if (IS_ERR(info->bat)) { dev_err(info->w1_dev, "failed to register battery\n"); return PTR_ERR(info->bat); } return 0; } static const struct w1_family_ops w1_max1721x_fops = { .add_slave = devm_w1_max1721x_add_device, }; static struct w1_family w1_max1721x_family = { .fid = W1_MAX1721X_FAMILY_ID, .fops = &w1_max1721x_fops, }; module_w1_family(w1_max1721x_family); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Alex A. Mihaylov <[email protected]>"); MODULE_DESCRIPTION("Maxim MAX17211/MAX17215 Fuel Gauge IC driver"); MODULE_ALIAS("w1-family-" __stringify(W1_MAX1721X_FAMILY_ID));
linux-master
drivers/power/supply/max1721x_battery.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (C) ST-Ericsson SA 2012 * * Charger driver for AB8500 * * Author: * Johan Palsson <[email protected]> * Karl Komierowski <[email protected]> * Arun R Murthy <[email protected]> */ #include <linux/init.h> #include <linux/module.h> #include <linux/device.h> #include <linux/component.h> #include <linux/interrupt.h> #include <linux/delay.h> #include <linux/notifier.h> #include <linux/slab.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/completion.h> #include <linux/regulator/consumer.h> #include <linux/err.h> #include <linux/workqueue.h> #include <linux/kobject.h> #include <linux/of.h> #include <linux/mfd/core.h> #include <linux/mfd/abx500/ab8500.h> #include <linux/mfd/abx500.h> #include <linux/usb/otg.h> #include <linux/mutex.h> #include <linux/iio/consumer.h> #include "ab8500-bm.h" #include "ab8500-chargalg.h" /* Charger constants */ #define NO_PW_CONN 0 #define AC_PW_CONN 1 #define USB_PW_CONN 2 #define MAIN_WDOG_ENA 0x01 #define MAIN_WDOG_KICK 0x02 #define MAIN_WDOG_DIS 0x00 #define CHARG_WD_KICK 0x01 #define MAIN_CH_ENA 0x01 #define MAIN_CH_NO_OVERSHOOT_ENA_N 0x02 #define USB_CH_ENA 0x01 #define USB_CHG_NO_OVERSHOOT_ENA_N 0x02 #define MAIN_CH_DET 0x01 #define MAIN_CH_CV_ON 0x04 #define USB_CH_CV_ON 0x08 #define VBUS_DET_DBNC100 0x02 #define VBUS_DET_DBNC1 0x01 #define OTP_ENABLE_WD 0x01 #define DROP_COUNT_RESET 0x01 #define USB_CH_DET 0x01 #define MAIN_CH_INPUT_CURR_SHIFT 4 #define VBUS_IN_CURR_LIM_SHIFT 4 #define AUTO_VBUS_IN_CURR_LIM_SHIFT 4 #define VBUS_IN_CURR_LIM_RETRY_SET_TIME 30 /* seconds */ #define LED_INDICATOR_PWM_ENA 0x01 #define LED_INDICATOR_PWM_DIS 0x00 #define LED_IND_CUR_5MA 0x04 #define LED_INDICATOR_PWM_DUTY_252_256 0xBF /* HW failure constants */ #define MAIN_CH_TH_PROT 0x02 #define VBUS_CH_NOK 0x08 #define USB_CH_TH_PROT 0x02 #define VBUS_OVV_TH 0x01 #define MAIN_CH_NOK 0x01 #define VBUS_DET 0x80 #define MAIN_CH_STATUS2_MAINCHGDROP 0x80 #define MAIN_CH_STATUS2_MAINCHARGERDETDBNC 0x40 #define USB_CH_VBUSDROP 0x40 #define USB_CH_VBUSDETDBNC 0x01 /* UsbLineStatus register bit masks */ #define AB8500_USB_LINK_STATUS 0x78 #define AB8505_USB_LINK_STATUS 0xF8 #define AB8500_STD_HOST_SUSP 0x18 #define USB_LINK_STATUS_SHIFT 3 /* Watchdog timeout constant */ #define WD_TIMER 0x30 /* 4min */ #define WD_KICK_INTERVAL (60 * HZ) /* Lowest charger voltage is 3.39V -> 0x4E */ #define LOW_VOLT_REG 0x4E /* Step up/down delay in us */ #define STEP_UDELAY 1000 #define CHARGER_STATUS_POLL 10 /* in ms */ #define CHG_WD_INTERVAL (60 * HZ) #define AB8500_SW_CONTROL_FALLBACK 0x03 /* Wait for enumeration before charing in us */ #define WAIT_ACA_RID_ENUMERATION (5 * 1000) /*External charger control*/ #define AB8500_SYS_CHARGER_CONTROL_REG 0x52 #define EXTERNAL_CHARGER_DISABLE_REG_VAL 0x03 #define EXTERNAL_CHARGER_ENABLE_REG_VAL 0x07 /* UsbLineStatus register - usb types */ enum ab8500_charger_link_status { USB_STAT_NOT_CONFIGURED, USB_STAT_STD_HOST_NC, USB_STAT_STD_HOST_C_NS, USB_STAT_STD_HOST_C_S, USB_STAT_HOST_CHG_NM, USB_STAT_HOST_CHG_HS, USB_STAT_HOST_CHG_HS_CHIRP, USB_STAT_DEDICATED_CHG, USB_STAT_ACA_RID_A, USB_STAT_ACA_RID_B, USB_STAT_ACA_RID_C_NM, USB_STAT_ACA_RID_C_HS, USB_STAT_ACA_RID_C_HS_CHIRP, USB_STAT_HM_IDGND, USB_STAT_RESERVED, USB_STAT_NOT_VALID_LINK, USB_STAT_PHY_EN, USB_STAT_SUP_NO_IDGND_VBUS, USB_STAT_SUP_IDGND_VBUS, USB_STAT_CHARGER_LINE_1, USB_STAT_CARKIT_1, USB_STAT_CARKIT_2, USB_STAT_ACA_DOCK_CHARGER, }; enum ab8500_usb_state { AB8500_BM_USB_STATE_RESET_HS, /* HighSpeed Reset */ AB8500_BM_USB_STATE_RESET_FS, /* FullSpeed/LowSpeed Reset */ AB8500_BM_USB_STATE_CONFIGURED, AB8500_BM_USB_STATE_SUSPEND, AB8500_BM_USB_STATE_RESUME, AB8500_BM_USB_STATE_MAX, }; /* VBUS input current limits supported in AB8500 in uA */ #define USB_CH_IP_CUR_LVL_0P05 50000 #define USB_CH_IP_CUR_LVL_0P09 98000 #define USB_CH_IP_CUR_LVL_0P19 193000 #define USB_CH_IP_CUR_LVL_0P29 290000 #define USB_CH_IP_CUR_LVL_0P38 380000 #define USB_CH_IP_CUR_LVL_0P45 450000 #define USB_CH_IP_CUR_LVL_0P5 500000 #define USB_CH_IP_CUR_LVL_0P6 600000 #define USB_CH_IP_CUR_LVL_0P7 700000 #define USB_CH_IP_CUR_LVL_0P8 800000 #define USB_CH_IP_CUR_LVL_0P9 900000 #define USB_CH_IP_CUR_LVL_1P0 1000000 #define USB_CH_IP_CUR_LVL_1P1 1100000 #define USB_CH_IP_CUR_LVL_1P3 1300000 #define USB_CH_IP_CUR_LVL_1P4 1400000 #define USB_CH_IP_CUR_LVL_1P5 1500000 #define VBAT_TRESH_IP_CUR_RED 3800000 #define to_ab8500_charger_usb_device_info(x) container_of((x), \ struct ab8500_charger, usb_chg) #define to_ab8500_charger_ac_device_info(x) container_of((x), \ struct ab8500_charger, ac_chg) /** * struct ab8500_charger_interrupts - ab8500 interrupts * @name: name of the interrupt * @isr function pointer to the isr */ struct ab8500_charger_interrupts { char *name; irqreturn_t (*isr)(int irq, void *data); }; struct ab8500_charger_info { int charger_connected; int charger_online; int charger_voltage_uv; int cv_active; bool wd_expired; int charger_current_ua; }; struct ab8500_charger_event_flags { bool mainextchnotok; bool main_thermal_prot; bool usb_thermal_prot; bool vbus_ovv; bool usbchargernotok; bool chgwdexp; bool vbus_collapse; bool vbus_drop_end; }; struct ab8500_charger_usb_state { int usb_current_ua; int usb_current_tmp_ua; enum ab8500_usb_state state; enum ab8500_usb_state state_tmp; spinlock_t usb_lock; }; struct ab8500_charger_max_usb_in_curr { int usb_type_max_ua; int set_max_ua; int calculated_max_ua; }; /** * struct ab8500_charger - ab8500 Charger device information * @dev: Pointer to the structure device * @vbus_detected: VBUS detected * @vbus_detected_start: * VBUS detected during startup * @ac_conn: This will be true when the AC charger has been plugged * @vddadc_en_ac: Indicate if VDD ADC supply is enabled because AC * charger is enabled * @vddadc_en_usb: Indicate if VDD ADC supply is enabled because USB * charger is enabled * @vbat Battery voltage * @old_vbat Previously measured battery voltage * @usb_device_is_unrecognised USB device is unrecognised by the hardware * @autopower Indicate if we should have automatic pwron after pwrloss * @autopower_cfg platform specific power config support for "pwron after pwrloss" * @invalid_charger_detect_state State when forcing AB to use invalid charger * @is_aca_rid: Incicate if accessory is ACA type * @current_stepping_sessions: * Counter for current stepping sessions * @parent: Pointer to the struct ab8500 * @adc_main_charger_v ADC channel for main charger voltage * @adc_main_charger_c ADC channel for main charger current * @adc_vbus_v ADC channel for USB charger voltage * @adc_usb_charger_c ADC channel for USB charger current * @bm: Platform specific battery management information * @flags: Structure for information about events triggered * @usb_state: Structure for usb stack information * @max_usb_in_curr: Max USB charger input current * @ac_chg: AC charger power supply * @usb_chg: USB charger power supply * @ac: Structure that holds the AC charger properties * @usb: Structure that holds the USB charger properties * @regu: Pointer to the struct regulator * @charger_wq: Work queue for the IRQs and checking HW state * @usb_ipt_crnt_lock: Lock to protect VBUS input current setting from mutuals * @pm_lock: Lock to prevent system to suspend * @check_vbat_work Work for checking vbat threshold to adjust vbus current * @check_hw_failure_work: Work for checking HW state * @check_usbchgnotok_work: Work for checking USB charger not ok status * @kick_wd_work: Work for kicking the charger watchdog in case * of ABB rev 1.* due to the watchog logic bug * @ac_charger_attached_work: Work for checking if AC charger is still * connected * @usb_charger_attached_work: Work for checking if USB charger is still * connected * @ac_work: Work for checking AC charger connection * @detect_usb_type_work: Work for detecting the USB type connected * @usb_link_status_work: Work for checking the new USB link status * @usb_state_changed_work: Work for checking USB state * @attach_work: Work for detecting USB type * @vbus_drop_end_work: Work for detecting VBUS drop end * @check_main_thermal_prot_work: * Work for checking Main thermal status * @check_usb_thermal_prot_work: * Work for checking USB thermal status * @charger_attached_mutex: For controlling the wakelock */ struct ab8500_charger { struct device *dev; bool vbus_detected; bool vbus_detected_start; bool ac_conn; bool vddadc_en_ac; bool vddadc_en_usb; int vbat; int old_vbat; bool usb_device_is_unrecognised; bool autopower; bool autopower_cfg; int invalid_charger_detect_state; int is_aca_rid; atomic_t current_stepping_sessions; struct ab8500 *parent; struct iio_channel *adc_main_charger_v; struct iio_channel *adc_main_charger_c; struct iio_channel *adc_vbus_v; struct iio_channel *adc_usb_charger_c; struct ab8500_bm_data *bm; struct ab8500_charger_event_flags flags; struct ab8500_charger_usb_state usb_state; struct ab8500_charger_max_usb_in_curr max_usb_in_curr; struct ux500_charger ac_chg; struct ux500_charger usb_chg; struct ab8500_charger_info ac; struct ab8500_charger_info usb; struct regulator *regu; struct workqueue_struct *charger_wq; struct mutex usb_ipt_crnt_lock; struct delayed_work check_vbat_work; struct delayed_work check_hw_failure_work; struct delayed_work check_usbchgnotok_work; struct delayed_work kick_wd_work; struct delayed_work usb_state_changed_work; struct delayed_work attach_work; struct delayed_work ac_charger_attached_work; struct delayed_work usb_charger_attached_work; struct delayed_work vbus_drop_end_work; struct work_struct ac_work; struct work_struct detect_usb_type_work; struct work_struct usb_link_status_work; struct work_struct check_main_thermal_prot_work; struct work_struct check_usb_thermal_prot_work; struct usb_phy *usb_phy; struct notifier_block nb; struct mutex charger_attached_mutex; }; /* AC properties */ static enum power_supply_property ab8500_charger_ac_props[] = { POWER_SUPPLY_PROP_HEALTH, POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_VOLTAGE_AVG, POWER_SUPPLY_PROP_CURRENT_NOW, }; /* USB properties */ static enum power_supply_property ab8500_charger_usb_props[] = { POWER_SUPPLY_PROP_HEALTH, POWER_SUPPLY_PROP_CURRENT_AVG, POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_VOLTAGE_AVG, POWER_SUPPLY_PROP_CURRENT_NOW, }; /* * Function for enabling and disabling sw fallback mode * should always be disabled when no charger is connected. */ static void ab8500_enable_disable_sw_fallback(struct ab8500_charger *di, bool fallback) { u8 val; u8 reg; u8 bank; u8 bit; int ret; dev_dbg(di->dev, "SW Fallback: %d\n", fallback); if (is_ab8500(di->parent)) { bank = 0x15; reg = 0x0; bit = 3; } else { bank = AB8500_SYS_CTRL1_BLOCK; reg = AB8500_SW_CONTROL_FALLBACK; bit = 0; } /* read the register containing fallback bit */ ret = abx500_get_register_interruptible(di->dev, bank, reg, &val); if (ret < 0) { dev_err(di->dev, "%d read failed\n", __LINE__); return; } if (is_ab8500(di->parent)) { /* enable the OPT emulation registers */ ret = abx500_set_register_interruptible(di->dev, 0x11, 0x00, 0x2); if (ret) { dev_err(di->dev, "%d write failed\n", __LINE__); goto disable_otp; } } if (fallback) val |= (1 << bit); else val &= ~(1 << bit); /* write back the changed fallback bit value to register */ ret = abx500_set_register_interruptible(di->dev, bank, reg, val); if (ret) { dev_err(di->dev, "%d write failed\n", __LINE__); } disable_otp: if (is_ab8500(di->parent)) { /* disable the set OTP registers again */ ret = abx500_set_register_interruptible(di->dev, 0x11, 0x00, 0x0); if (ret) { dev_err(di->dev, "%d write failed\n", __LINE__); } } } /** * ab8500_power_supply_changed - a wrapper with local extensions for * power_supply_changed * @di: pointer to the ab8500_charger structure * @psy: pointer to power_supply_that have changed. * */ static void ab8500_power_supply_changed(struct ab8500_charger *di, struct power_supply *psy) { /* * This happens if we get notifications or interrupts and * the platform has been configured not to support one or * other type of charging. */ if (!psy) return; if (di->autopower_cfg) { if (!di->usb.charger_connected && !di->ac.charger_connected && di->autopower) { di->autopower = false; ab8500_enable_disable_sw_fallback(di, false); } else if (!di->autopower && (di->ac.charger_connected || di->usb.charger_connected)) { di->autopower = true; ab8500_enable_disable_sw_fallback(di, true); } } power_supply_changed(psy); } static void ab8500_charger_set_usb_connected(struct ab8500_charger *di, bool connected) { if (connected != di->usb.charger_connected) { dev_dbg(di->dev, "USB connected:%i\n", connected); di->usb.charger_connected = connected; if (!connected) di->flags.vbus_drop_end = false; /* * Sometimes the platform is configured not to support * USB charging and no psy has been created, but we still * will get these notifications. */ if (di->usb_chg.psy) { sysfs_notify(&di->usb_chg.psy->dev.kobj, NULL, "present"); } if (connected) { mutex_lock(&di->charger_attached_mutex); mutex_unlock(&di->charger_attached_mutex); if (is_ab8500(di->parent)) queue_delayed_work(di->charger_wq, &di->usb_charger_attached_work, HZ); } else { cancel_delayed_work_sync(&di->usb_charger_attached_work); mutex_lock(&di->charger_attached_mutex); mutex_unlock(&di->charger_attached_mutex); } } } /** * ab8500_charger_get_ac_voltage() - get ac charger voltage * @di: pointer to the ab8500_charger structure * * Returns ac charger voltage in microvolt (on success) */ static int ab8500_charger_get_ac_voltage(struct ab8500_charger *di) { int vch, ret; /* Only measure voltage if the charger is connected */ if (di->ac.charger_connected) { ret = iio_read_channel_processed(di->adc_main_charger_v, &vch); if (ret < 0) dev_err(di->dev, "%s ADC conv failed,\n", __func__); } else { vch = 0; } /* Convert to microvolt, IIO returns millivolt */ return vch * 1000; } /** * ab8500_charger_ac_cv() - check if the main charger is in CV mode * @di: pointer to the ab8500_charger structure * * Returns ac charger CV mode (on success) else error code */ static int ab8500_charger_ac_cv(struct ab8500_charger *di) { u8 val; int ret = 0; /* Only check CV mode if the charger is online */ if (di->ac.charger_online) { ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CH_STATUS1_REG, &val); if (ret < 0) { dev_err(di->dev, "%s ab8500 read failed\n", __func__); return 0; } if (val & MAIN_CH_CV_ON) ret = 1; else ret = 0; } return ret; } /** * ab8500_charger_get_vbus_voltage() - get vbus voltage * @di: pointer to the ab8500_charger structure * * This function returns the vbus voltage. * Returns vbus voltage in microvolt (on success) */ static int ab8500_charger_get_vbus_voltage(struct ab8500_charger *di) { int vch, ret; /* Only measure voltage if the charger is connected */ if (di->usb.charger_connected) { ret = iio_read_channel_processed(di->adc_vbus_v, &vch); if (ret < 0) dev_err(di->dev, "%s ADC conv failed,\n", __func__); } else { vch = 0; } /* Convert to microvolt, IIO returns millivolt */ return vch * 1000; } /** * ab8500_charger_get_usb_current() - get usb charger current * @di: pointer to the ab8500_charger structure * * This function returns the usb charger current. * Returns usb current in microamperes (on success) and error code on failure */ static int ab8500_charger_get_usb_current(struct ab8500_charger *di) { int ich, ret; /* Only measure current if the charger is online */ if (di->usb.charger_online) { ret = iio_read_channel_processed(di->adc_usb_charger_c, &ich); if (ret < 0) dev_err(di->dev, "%s ADC conv failed,\n", __func__); } else { ich = 0; } /* Return microamperes */ return ich * 1000; } /** * ab8500_charger_get_ac_current() - get ac charger current * @di: pointer to the ab8500_charger structure * * This function returns the ac charger current. * Returns ac current in microamperes (on success) and error code on failure. */ static int ab8500_charger_get_ac_current(struct ab8500_charger *di) { int ich, ret; /* Only measure current if the charger is online */ if (di->ac.charger_online) { ret = iio_read_channel_processed(di->adc_main_charger_c, &ich); if (ret < 0) dev_err(di->dev, "%s ADC conv failed,\n", __func__); } else { ich = 0; } /* Return microamperes */ return ich * 1000; } /** * ab8500_charger_usb_cv() - check if the usb charger is in CV mode * @di: pointer to the ab8500_charger structure * * Returns ac charger CV mode (on success) else error code */ static int ab8500_charger_usb_cv(struct ab8500_charger *di) { int ret; u8 val; /* Only check CV mode if the charger is online */ if (di->usb.charger_online) { ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CH_USBCH_STAT1_REG, &val); if (ret < 0) { dev_err(di->dev, "%s ab8500 read failed\n", __func__); return 0; } if (val & USB_CH_CV_ON) ret = 1; else ret = 0; } else { ret = 0; } return ret; } /** * ab8500_charger_detect_chargers() - Detect the connected chargers * @di: pointer to the ab8500_charger structure * @probe: if probe, don't delay and wait for HW * * Returns the type of charger connected. * For USB it will not mean we can actually charge from it * but that there is a USB cable connected that we have to * identify. This is used during startup when we don't get * interrupts of the charger detection * * Returns an integer value, that means, * NO_PW_CONN no power supply is connected * AC_PW_CONN if the AC power supply is connected * USB_PW_CONN if the USB power supply is connected * AC_PW_CONN + USB_PW_CONN if USB and AC power supplies are both connected */ static int ab8500_charger_detect_chargers(struct ab8500_charger *di, bool probe) { int result = NO_PW_CONN; int ret; u8 val; /* Check for AC charger */ ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CH_STATUS1_REG, &val); if (ret < 0) { dev_err(di->dev, "%s ab8500 read failed\n", __func__); return ret; } if (val & MAIN_CH_DET) result = AC_PW_CONN; /* Check for USB charger */ if (!probe) { /* * AB8500 says VBUS_DET_DBNC1 & VBUS_DET_DBNC100 * when disconnecting ACA even though no * charger was connected. Try waiting a little * longer than the 100 ms of VBUS_DET_DBNC100... */ msleep(110); } ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CH_USBCH_STAT1_REG, &val); if (ret < 0) { dev_err(di->dev, "%s ab8500 read failed\n", __func__); return ret; } dev_dbg(di->dev, "%s AB8500_CH_USBCH_STAT1_REG %x\n", __func__, val); if ((val & VBUS_DET_DBNC1) && (val & VBUS_DET_DBNC100)) result |= USB_PW_CONN; return result; } /** * ab8500_charger_max_usb_curr() - get the max curr for the USB type * @di: pointer to the ab8500_charger structure * @link_status: the identified USB type * * Get the maximum current that is allowed to be drawn from the host * based on the USB type. * Returns error code in case of failure else 0 on success */ static int ab8500_charger_max_usb_curr(struct ab8500_charger *di, enum ab8500_charger_link_status link_status) { int ret = 0; di->usb_device_is_unrecognised = false; /* * Platform only supports USB 2.0. * This means that charging current from USB source * is maximum 500 mA. Every occurrence of USB_STAT_*_HOST_* * should set USB_CH_IP_CUR_LVL_0P5. */ switch (link_status) { case USB_STAT_STD_HOST_NC: case USB_STAT_STD_HOST_C_NS: case USB_STAT_STD_HOST_C_S: dev_dbg(di->dev, "USB Type - Standard host is " "detected through USB driver\n"); di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P5; di->is_aca_rid = 0; break; case USB_STAT_HOST_CHG_HS_CHIRP: di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P5; di->is_aca_rid = 0; break; case USB_STAT_HOST_CHG_HS: di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P5; di->is_aca_rid = 0; break; case USB_STAT_ACA_RID_C_HS: di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P9; di->is_aca_rid = 0; break; case USB_STAT_ACA_RID_A: /* * Dedicated charger level minus maximum current accessory * can consume (900mA). Closest level is 500mA */ dev_dbg(di->dev, "USB_STAT_ACA_RID_A detected\n"); di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P5; di->is_aca_rid = 1; break; case USB_STAT_ACA_RID_B: /* * Dedicated charger level minus 120mA (20mA for ACA and * 100mA for potential accessory). Closest level is 1300mA */ di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_1P3; dev_dbg(di->dev, "USB Type - 0x%02x MaxCurr: %d", link_status, di->max_usb_in_curr.usb_type_max_ua); di->is_aca_rid = 1; break; case USB_STAT_HOST_CHG_NM: di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P5; di->is_aca_rid = 0; break; case USB_STAT_DEDICATED_CHG: di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_1P5; di->is_aca_rid = 0; break; case USB_STAT_ACA_RID_C_HS_CHIRP: case USB_STAT_ACA_RID_C_NM: di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_1P5; di->is_aca_rid = 1; break; case USB_STAT_NOT_CONFIGURED: if (di->vbus_detected) { di->usb_device_is_unrecognised = true; dev_dbg(di->dev, "USB Type - Legacy charger.\n"); di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_1P5; break; } fallthrough; case USB_STAT_HM_IDGND: dev_err(di->dev, "USB Type - Charging not allowed\n"); di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P05; ret = -ENXIO; break; case USB_STAT_RESERVED: if (is_ab8500(di->parent)) { di->flags.vbus_collapse = true; dev_err(di->dev, "USB Type - USB_STAT_RESERVED " "VBUS has collapsed\n"); ret = -ENXIO; break; } else { dev_dbg(di->dev, "USB Type - Charging not allowed\n"); di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P05; dev_dbg(di->dev, "USB Type - 0x%02x MaxCurr: %d", link_status, di->max_usb_in_curr.usb_type_max_ua); ret = -ENXIO; break; } case USB_STAT_CARKIT_1: case USB_STAT_CARKIT_2: case USB_STAT_ACA_DOCK_CHARGER: case USB_STAT_CHARGER_LINE_1: di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P5; dev_dbg(di->dev, "USB Type - 0x%02x MaxCurr: %d", link_status, di->max_usb_in_curr.usb_type_max_ua); break; case USB_STAT_NOT_VALID_LINK: dev_err(di->dev, "USB Type invalid - try charging anyway\n"); di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P5; break; default: dev_err(di->dev, "USB Type - Unknown\n"); di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P05; ret = -ENXIO; break; } di->max_usb_in_curr.set_max_ua = di->max_usb_in_curr.usb_type_max_ua; dev_dbg(di->dev, "USB Type - 0x%02x MaxCurr: %d", link_status, di->max_usb_in_curr.set_max_ua); return ret; } /** * ab8500_charger_read_usb_type() - read the type of usb connected * @di: pointer to the ab8500_charger structure * * Detect the type of the plugged USB * Returns error code in case of failure else 0 on success */ static int ab8500_charger_read_usb_type(struct ab8500_charger *di) { int ret; u8 val; ret = abx500_get_register_interruptible(di->dev, AB8500_INTERRUPT, AB8500_IT_SOURCE21_REG, &val); if (ret < 0) { dev_err(di->dev, "%s ab8500 read failed\n", __func__); return ret; } if (is_ab8500(di->parent)) ret = abx500_get_register_interruptible(di->dev, AB8500_USB, AB8500_USB_LINE_STAT_REG, &val); else ret = abx500_get_register_interruptible(di->dev, AB8500_USB, AB8500_USB_LINK1_STAT_REG, &val); if (ret < 0) { dev_err(di->dev, "%s ab8500 read failed\n", __func__); return ret; } /* get the USB type */ if (is_ab8500(di->parent)) val = (val & AB8500_USB_LINK_STATUS) >> USB_LINK_STATUS_SHIFT; else val = (val & AB8505_USB_LINK_STATUS) >> USB_LINK_STATUS_SHIFT; ret = ab8500_charger_max_usb_curr(di, (enum ab8500_charger_link_status) val); return ret; } /** * ab8500_charger_detect_usb_type() - get the type of usb connected * @di: pointer to the ab8500_charger structure * * Detect the type of the plugged USB * Returns error code in case of failure else 0 on success */ static int ab8500_charger_detect_usb_type(struct ab8500_charger *di) { int i, ret; u8 val; /* * On getting the VBUS rising edge detect interrupt there * is a 250ms delay after which the register UsbLineStatus * is filled with valid data. */ for (i = 0; i < 10; i++) { msleep(250); ret = abx500_get_register_interruptible(di->dev, AB8500_INTERRUPT, AB8500_IT_SOURCE21_REG, &val); dev_dbg(di->dev, "%s AB8500_IT_SOURCE21_REG %x\n", __func__, val); if (ret < 0) { dev_err(di->dev, "%s ab8500 read failed\n", __func__); return ret; } if (is_ab8500(di->parent)) ret = abx500_get_register_interruptible(di->dev, AB8500_USB, AB8500_USB_LINE_STAT_REG, &val); else ret = abx500_get_register_interruptible(di->dev, AB8500_USB, AB8500_USB_LINK1_STAT_REG, &val); if (ret < 0) { dev_err(di->dev, "%s ab8500 read failed\n", __func__); return ret; } dev_dbg(di->dev, "%s AB8500_USB_LINE_STAT_REG %x\n", __func__, val); /* * Until the IT source register is read the UsbLineStatus * register is not updated, hence doing the same * Revisit this: */ /* get the USB type */ if (is_ab8500(di->parent)) val = (val & AB8500_USB_LINK_STATUS) >> USB_LINK_STATUS_SHIFT; else val = (val & AB8505_USB_LINK_STATUS) >> USB_LINK_STATUS_SHIFT; if (val) break; } ret = ab8500_charger_max_usb_curr(di, (enum ab8500_charger_link_status) val); return ret; } /* * This array maps the raw hex value to charger voltage used by the AB8500 * Values taken from the UM0836, in microvolt. */ static int ab8500_charger_voltage_map[] = { 3500000, 3525000, 3550000, 3575000, 3600000, 3625000, 3650000, 3675000, 3700000, 3725000, 3750000, 3775000, 3800000, 3825000, 3850000, 3875000, 3900000, 3925000, 3950000, 3975000, 4000000, 4025000, 4050000, 4060000, 4070000, 4080000, 4090000, 4100000, 4110000, 4120000, 4130000, 4140000, 4150000, 4160000, 4170000, 4180000, 4190000, 4200000, 4210000, 4220000, 4230000, 4240000, 4250000, 4260000, 4270000, 4280000, 4290000, 4300000, 4310000, 4320000, 4330000, 4340000, 4350000, 4360000, 4370000, 4380000, 4390000, 4400000, 4410000, 4420000, 4430000, 4440000, 4450000, 4460000, 4470000, 4480000, 4490000, 4500000, 4510000, 4520000, 4530000, 4540000, 4550000, 4560000, 4570000, 4580000, 4590000, 4600000, }; static int ab8500_voltage_to_regval(int voltage_uv) { int i; /* Special case for voltage below 3.5V */ if (voltage_uv < ab8500_charger_voltage_map[0]) return LOW_VOLT_REG; for (i = 1; i < ARRAY_SIZE(ab8500_charger_voltage_map); i++) { if (voltage_uv < ab8500_charger_voltage_map[i]) return i - 1; } /* If not last element, return error */ i = ARRAY_SIZE(ab8500_charger_voltage_map) - 1; if (voltage_uv == ab8500_charger_voltage_map[i]) return i; else return -1; } /* This array maps the raw register value to charger input current */ static int ab8500_charge_input_curr_map[] = { 50000, 98000, 193000, 290000, 380000, 450000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1300000, 1400000, 1500000, }; /* This array maps the raw register value to charger output current */ static int ab8500_charge_output_curr_map[] = { 100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1200000, 1300000, 1400000, 1500000, 1500000, }; static int ab8500_current_to_regval(struct ab8500_charger *di, int curr_ua) { int i; if (curr_ua < ab8500_charge_output_curr_map[0]) return 0; for (i = 0; i < ARRAY_SIZE(ab8500_charge_output_curr_map); i++) { if (curr_ua < ab8500_charge_output_curr_map[i]) return i - 1; } /* If not last element, return error */ i = ARRAY_SIZE(ab8500_charge_output_curr_map) - 1; if (curr_ua == ab8500_charge_output_curr_map[i]) return i; else return -1; } static int ab8500_vbus_in_curr_to_regval(struct ab8500_charger *di, int curr_ua) { int i; if (curr_ua < ab8500_charge_input_curr_map[0]) return 0; for (i = 0; i < ARRAY_SIZE(ab8500_charge_input_curr_map); i++) { if (curr_ua < ab8500_charge_input_curr_map[i]) return i - 1; } /* If not last element, return error */ i = ARRAY_SIZE(ab8500_charge_input_curr_map) - 1; if (curr_ua == ab8500_charge_input_curr_map[i]) return i; else return -1; } /** * ab8500_charger_get_usb_cur() - get usb current * @di: pointer to the ab8500_charger structure * * The usb stack provides the maximum current that can be drawn from * the standard usb host. This will be in uA. * This function converts current in uA to a value that can be written * to the register. Returns -1 if charging is not allowed */ static int ab8500_charger_get_usb_cur(struct ab8500_charger *di) { int ret = 0; switch (di->usb_state.usb_current_ua) { case 100000: di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P09; break; case 200000: di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P19; break; case 300000: di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P29; break; case 400000: di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P38; break; case 500000: di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P5; break; default: di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P05; ret = -EPERM; break; } di->max_usb_in_curr.set_max_ua = di->max_usb_in_curr.usb_type_max_ua; return ret; } /** * ab8500_charger_check_continue_stepping() - Check to allow stepping * @di: pointer to the ab8500_charger structure * @reg: select what charger register to check * * Check if current stepping should be allowed to continue. * Checks if charger source has not collapsed. If it has, further stepping * is not allowed. */ static bool ab8500_charger_check_continue_stepping(struct ab8500_charger *di, int reg) { if (reg == AB8500_USBCH_IPT_CRNTLVL_REG) return !di->flags.vbus_drop_end; else return true; } /** * ab8500_charger_set_current() - set charger current * @di: pointer to the ab8500_charger structure * @ich_ua: charger current, in uA * @reg: select what charger register to set * * Set charger current. * There is no state machine in the AB to step up/down the charger * current to avoid dips and spikes on MAIN, VBUS and VBAT when * charging is started. Instead we need to implement * this charger current step-up/down here. * Returns error code in case of failure else 0(on success) */ static int ab8500_charger_set_current(struct ab8500_charger *di, int ich_ua, int reg) { int ret = 0; int curr_index, prev_curr_index, shift_value, i; u8 reg_value; u32 step_udelay; bool no_stepping = false; atomic_inc(&di->current_stepping_sessions); ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER, reg, &reg_value); if (ret < 0) { dev_err(di->dev, "%s read failed\n", __func__); goto exit_set_current; } switch (reg) { case AB8500_MCH_IPT_CURLVL_REG: shift_value = MAIN_CH_INPUT_CURR_SHIFT; prev_curr_index = (reg_value >> shift_value); curr_index = ab8500_current_to_regval(di, ich_ua); step_udelay = STEP_UDELAY; if (!di->ac.charger_connected) no_stepping = true; break; case AB8500_USBCH_IPT_CRNTLVL_REG: shift_value = VBUS_IN_CURR_LIM_SHIFT; prev_curr_index = (reg_value >> shift_value); curr_index = ab8500_vbus_in_curr_to_regval(di, ich_ua); step_udelay = STEP_UDELAY * 100; if (!di->usb.charger_connected) no_stepping = true; break; case AB8500_CH_OPT_CRNTLVL_REG: shift_value = 0; prev_curr_index = (reg_value >> shift_value); curr_index = ab8500_current_to_regval(di, ich_ua); step_udelay = STEP_UDELAY; if (curr_index && (curr_index - prev_curr_index) > 1) step_udelay *= 100; if (!di->usb.charger_connected && !di->ac.charger_connected) no_stepping = true; break; default: dev_err(di->dev, "%s current register not valid\n", __func__); ret = -ENXIO; goto exit_set_current; } if (curr_index < 0) { dev_err(di->dev, "requested current limit out-of-range\n"); ret = -ENXIO; goto exit_set_current; } /* only update current if it's been changed */ if (prev_curr_index == curr_index) { dev_dbg(di->dev, "%s current not changed for reg: 0x%02x\n", __func__, reg); ret = 0; goto exit_set_current; } dev_dbg(di->dev, "%s set charger current: %d uA for reg: 0x%02x\n", __func__, ich_ua, reg); if (no_stepping) { ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER, reg, (u8)curr_index << shift_value); if (ret) dev_err(di->dev, "%s write failed\n", __func__); } else if (prev_curr_index > curr_index) { for (i = prev_curr_index - 1; i >= curr_index; i--) { dev_dbg(di->dev, "curr change_1 to: %x for 0x%02x\n", (u8) i << shift_value, reg); ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER, reg, (u8)i << shift_value); if (ret) { dev_err(di->dev, "%s write failed\n", __func__); goto exit_set_current; } if (i != curr_index) usleep_range(step_udelay, step_udelay * 2); } } else { bool allow = true; for (i = prev_curr_index + 1; i <= curr_index && allow; i++) { dev_dbg(di->dev, "curr change_2 to: %x for 0x%02x\n", (u8)i << shift_value, reg); ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER, reg, (u8)i << shift_value); if (ret) { dev_err(di->dev, "%s write failed\n", __func__); goto exit_set_current; } if (i != curr_index) usleep_range(step_udelay, step_udelay * 2); allow = ab8500_charger_check_continue_stepping(di, reg); } } exit_set_current: atomic_dec(&di->current_stepping_sessions); return ret; } /** * ab8500_charger_set_vbus_in_curr() - set VBUS input current limit * @di: pointer to the ab8500_charger structure * @ich_in_ua: charger input current limit in microampere * * Sets the current that can be drawn from the USB host * Returns error code in case of failure else 0(on success) */ static int ab8500_charger_set_vbus_in_curr(struct ab8500_charger *di, int ich_in_ua) { int min_value; int ret; /* We should always use to lowest current limit */ min_value = min(di->bm->chg_params->usb_curr_max_ua, ich_in_ua); if (di->max_usb_in_curr.set_max_ua > 0) min_value = min(di->max_usb_in_curr.set_max_ua, min_value); if (di->usb_state.usb_current_ua >= 0) min_value = min(di->usb_state.usb_current_ua, min_value); switch (min_value) { case 100000: if (di->vbat < VBAT_TRESH_IP_CUR_RED) min_value = USB_CH_IP_CUR_LVL_0P05; break; case 500000: if (di->vbat < VBAT_TRESH_IP_CUR_RED) min_value = USB_CH_IP_CUR_LVL_0P45; break; default: break; } dev_info(di->dev, "VBUS input current limit set to %d uA\n", min_value); mutex_lock(&di->usb_ipt_crnt_lock); ret = ab8500_charger_set_current(di, min_value, AB8500_USBCH_IPT_CRNTLVL_REG); mutex_unlock(&di->usb_ipt_crnt_lock); return ret; } /** * ab8500_charger_set_main_in_curr() - set main charger input current * @di: pointer to the ab8500_charger structure * @ich_in_ua: input charger current, in uA * * Set main charger input current. * Returns error code in case of failure else 0(on success) */ static int ab8500_charger_set_main_in_curr(struct ab8500_charger *di, int ich_in_ua) { return ab8500_charger_set_current(di, ich_in_ua, AB8500_MCH_IPT_CURLVL_REG); } /** * ab8500_charger_set_output_curr() - set charger output current * @di: pointer to the ab8500_charger structure * @ich_out_ua: output charger current, in uA * * Set charger output current. * Returns error code in case of failure else 0(on success) */ static int ab8500_charger_set_output_curr(struct ab8500_charger *di, int ich_out_ua) { return ab8500_charger_set_current(di, ich_out_ua, AB8500_CH_OPT_CRNTLVL_REG); } /** * ab8500_charger_led_en() - turn on/off chargign led * @di: pointer to the ab8500_charger structure * @on: flag to turn on/off the chargign led * * Power ON/OFF charging LED indication * Returns error code in case of failure else 0(on success) */ static int ab8500_charger_led_en(struct ab8500_charger *di, int on) { int ret; if (on) { /* Power ON charging LED indicator, set LED current to 5mA */ ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_LED_INDICATOR_PWM_CTRL, (LED_IND_CUR_5MA | LED_INDICATOR_PWM_ENA)); if (ret) { dev_err(di->dev, "Power ON LED failed\n"); return ret; } /* LED indicator PWM duty cycle 252/256 */ ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_LED_INDICATOR_PWM_DUTY, LED_INDICATOR_PWM_DUTY_252_256); if (ret) { dev_err(di->dev, "Set LED PWM duty cycle failed\n"); return ret; } } else { /* Power off charging LED indicator */ ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_LED_INDICATOR_PWM_CTRL, LED_INDICATOR_PWM_DIS); if (ret) { dev_err(di->dev, "Power-off LED failed\n"); return ret; } } return ret; } /** * ab8500_charger_ac_en() - enable or disable ac charging * @di: pointer to the ab8500_charger structure * @enable: enable/disable flag * @vset_uv: charging voltage in microvolt * @iset_ua: charging current in microampere * * Enable/Disable AC/Mains charging and turns on/off the charging led * respectively. **/ static int ab8500_charger_ac_en(struct ux500_charger *charger, int enable, int vset_uv, int iset_ua) { int ret; int volt_index; int curr_index; int input_curr_index; u8 overshoot = 0; struct ab8500_charger *di = to_ab8500_charger_ac_device_info(charger); if (enable) { /* Check if AC is connected */ if (!di->ac.charger_connected) { dev_err(di->dev, "AC charger not connected\n"); return -ENXIO; } /* Enable AC charging */ dev_dbg(di->dev, "Enable AC: %duV %duA\n", vset_uv, iset_ua); /* * Due to a bug in AB8500, BTEMP_HIGH/LOW interrupts * will be triggered every time we enable the VDD ADC supply. * This will turn off charging for a short while. * It can be avoided by having the supply on when * there is a charger enabled. Normally the VDD ADC supply * is enabled every time a GPADC conversion is triggered. * We will force it to be enabled from this driver to have * the GPADC module independent of the AB8500 chargers */ if (!di->vddadc_en_ac) { ret = regulator_enable(di->regu); if (ret) dev_warn(di->dev, "Failed to enable regulator\n"); else di->vddadc_en_ac = true; } /* Check if the requested voltage or current is valid */ volt_index = ab8500_voltage_to_regval(vset_uv); curr_index = ab8500_current_to_regval(di, iset_ua); input_curr_index = ab8500_current_to_regval(di, di->bm->chg_params->ac_curr_max_ua); if (volt_index < 0 || curr_index < 0 || input_curr_index < 0) { dev_err(di->dev, "Charger voltage or current too high, " "charging not started\n"); return -ENXIO; } /* ChVoltLevel: maximum battery charging voltage */ ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CH_VOLT_LVL_REG, (u8) volt_index); if (ret) { dev_err(di->dev, "%s write failed\n", __func__); return ret; } /* MainChInputCurr: current that can be drawn from the charger*/ ret = ab8500_charger_set_main_in_curr(di, di->bm->chg_params->ac_curr_max_ua); if (ret) { dev_err(di->dev, "%s Failed to set MainChInputCurr\n", __func__); return ret; } /* ChOutputCurentLevel: protected output current */ ret = ab8500_charger_set_output_curr(di, iset_ua); if (ret) { dev_err(di->dev, "%s " "Failed to set ChOutputCurentLevel\n", __func__); return ret; } /* Check if VBAT overshoot control should be enabled */ if (!di->bm->enable_overshoot) overshoot = MAIN_CH_NO_OVERSHOOT_ENA_N; /* Enable Main Charger */ ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_MCH_CTRL1, MAIN_CH_ENA | overshoot); if (ret) { dev_err(di->dev, "%s write failed\n", __func__); return ret; } /* Power on charging LED indication */ ret = ab8500_charger_led_en(di, true); if (ret < 0) dev_err(di->dev, "failed to enable LED\n"); di->ac.charger_online = 1; } else { /* Disable AC charging */ if (is_ab8500_1p1_or_earlier(di->parent)) { /* * For ABB revision 1.0 and 1.1 there is a bug in the * watchdog logic. That means we have to continuously * kick the charger watchdog even when no charger is * connected. This is only valid once the AC charger * has been enabled. This is a bug that is not handled * by the algorithm and the watchdog have to be kicked * by the charger driver when the AC charger * is disabled */ if (di->ac_conn) { queue_delayed_work(di->charger_wq, &di->kick_wd_work, round_jiffies(WD_KICK_INTERVAL)); } /* * We can't turn off charging completely * due to a bug in AB8500 cut1. * If we do, charging will not start again. * That is why we set the lowest voltage * and current possible */ ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CH_VOLT_LVL_REG, CH_VOL_LVL_3P5); if (ret) { dev_err(di->dev, "%s write failed\n", __func__); return ret; } ret = ab8500_charger_set_output_curr(di, 0); if (ret) { dev_err(di->dev, "%s " "Failed to set ChOutputCurentLevel\n", __func__); return ret; } } else { ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_MCH_CTRL1, 0); if (ret) { dev_err(di->dev, "%s write failed\n", __func__); return ret; } } ret = ab8500_charger_led_en(di, false); if (ret < 0) dev_err(di->dev, "failed to disable LED\n"); di->ac.charger_online = 0; di->ac.wd_expired = false; /* Disable regulator if enabled */ if (di->vddadc_en_ac) { regulator_disable(di->regu); di->vddadc_en_ac = false; } dev_dbg(di->dev, "%s Disabled AC charging\n", __func__); } ab8500_power_supply_changed(di, di->ac_chg.psy); return ret; } /** * ab8500_charger_usb_en() - enable usb charging * @di: pointer to the ab8500_charger structure * @enable: enable/disable flag * @vset_uv: charging voltage in microvolt * @ich_out_ua: charger output current in microampere * * Enable/Disable USB charging and turns on/off the charging led respectively. * Returns error code in case of failure else 0(on success) */ static int ab8500_charger_usb_en(struct ux500_charger *charger, int enable, int vset_uv, int ich_out_ua) { int ret; int volt_index; int curr_index; u8 overshoot = 0; struct ab8500_charger *di = to_ab8500_charger_usb_device_info(charger); if (enable) { /* Check if USB is connected */ if (!di->usb.charger_connected) { dev_err(di->dev, "USB charger not connected\n"); return -ENXIO; } /* * Due to a bug in AB8500, BTEMP_HIGH/LOW interrupts * will be triggered every time we enable the VDD ADC supply. * This will turn off charging for a short while. * It can be avoided by having the supply on when * there is a charger enabled. Normally the VDD ADC supply * is enabled every time a GPADC conversion is triggered. * We will force it to be enabled from this driver to have * the GPADC module independent of the AB8500 chargers */ if (!di->vddadc_en_usb) { ret = regulator_enable(di->regu); if (ret) dev_warn(di->dev, "Failed to enable regulator\n"); else di->vddadc_en_usb = true; } /* Enable USB charging */ dev_dbg(di->dev, "Enable USB: %d uV %d uA\n", vset_uv, ich_out_ua); /* Check if the requested voltage or current is valid */ volt_index = ab8500_voltage_to_regval(vset_uv); curr_index = ab8500_current_to_regval(di, ich_out_ua); if (volt_index < 0 || curr_index < 0) { dev_err(di->dev, "Charger voltage or current too high, " "charging not started\n"); return -ENXIO; } /* * ChVoltLevel: max voltage up to which battery can be * charged */ ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CH_VOLT_LVL_REG, (u8) volt_index); if (ret) { dev_err(di->dev, "%s write failed\n", __func__); return ret; } /* Check if VBAT overshoot control should be enabled */ if (!di->bm->enable_overshoot) overshoot = USB_CHG_NO_OVERSHOOT_ENA_N; /* Enable USB Charger */ dev_dbg(di->dev, "Enabling USB with write to AB8500_USBCH_CTRL1_REG\n"); ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_USBCH_CTRL1_REG, USB_CH_ENA | overshoot); if (ret) { dev_err(di->dev, "%s write failed\n", __func__); return ret; } /* If success power on charging LED indication */ ret = ab8500_charger_led_en(di, true); if (ret < 0) dev_err(di->dev, "failed to enable LED\n"); di->usb.charger_online = 1; /* USBChInputCurr: current that can be drawn from the usb */ ret = ab8500_charger_set_vbus_in_curr(di, di->max_usb_in_curr.usb_type_max_ua); if (ret) { dev_err(di->dev, "setting USBChInputCurr failed\n"); return ret; } /* ChOutputCurentLevel: protected output current */ ret = ab8500_charger_set_output_curr(di, ich_out_ua); if (ret) { dev_err(di->dev, "%s " "Failed to set ChOutputCurentLevel\n", __func__); return ret; } queue_delayed_work(di->charger_wq, &di->check_vbat_work, HZ); } else { /* Disable USB charging */ dev_dbg(di->dev, "%s Disabled USB charging\n", __func__); ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_USBCH_CTRL1_REG, 0); if (ret) { dev_err(di->dev, "%s write failed\n", __func__); return ret; } ret = ab8500_charger_led_en(di, false); if (ret < 0) dev_err(di->dev, "failed to disable LED\n"); /* USBChInputCurr: current that can be drawn from the usb */ ret = ab8500_charger_set_vbus_in_curr(di, 0); if (ret) { dev_err(di->dev, "setting USBChInputCurr failed\n"); return ret; } /* ChOutputCurentLevel: protected output current */ ret = ab8500_charger_set_output_curr(di, 0); if (ret) { dev_err(di->dev, "%s " "Failed to reset ChOutputCurentLevel\n", __func__); return ret; } di->usb.charger_online = 0; di->usb.wd_expired = false; /* Disable regulator if enabled */ if (di->vddadc_en_usb) { regulator_disable(di->regu); di->vddadc_en_usb = false; } dev_dbg(di->dev, "%s Disabled USB charging\n", __func__); /* Cancel any pending Vbat check work */ cancel_delayed_work(&di->check_vbat_work); } ab8500_power_supply_changed(di, di->usb_chg.psy); return ret; } /** * ab8500_charger_usb_check_enable() - enable usb charging * @charger: pointer to the ux500_charger structure * @vset_uv: charging voltage in microvolt * @iset_ua: charger output current in microampere * * Check if the VBUS charger has been disconnected and reconnected without * AB8500 rising an interrupt. Returns 0 on success. */ static int ab8500_charger_usb_check_enable(struct ux500_charger *charger, int vset_uv, int iset_ua) { u8 usbch_ctrl1 = 0; int ret = 0; struct ab8500_charger *di = to_ab8500_charger_usb_device_info(charger); if (!di->usb.charger_connected) return ret; ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER, AB8500_USBCH_CTRL1_REG, &usbch_ctrl1); if (ret < 0) { dev_err(di->dev, "ab8500 read failed %d\n", __LINE__); return ret; } dev_dbg(di->dev, "USB charger ctrl: 0x%02x\n", usbch_ctrl1); if (!(usbch_ctrl1 & USB_CH_ENA)) { dev_info(di->dev, "Charging has been disabled abnormally and will be re-enabled\n"); ret = abx500_mask_and_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CHARGER_CTRL, DROP_COUNT_RESET, DROP_COUNT_RESET); if (ret < 0) { dev_err(di->dev, "ab8500 write failed %d\n", __LINE__); return ret; } ret = ab8500_charger_usb_en(&di->usb_chg, true, vset_uv, iset_ua); if (ret < 0) { dev_err(di->dev, "Failed to enable VBUS charger %d\n", __LINE__); return ret; } } return ret; } /** * ab8500_charger_ac_check_enable() - enable usb charging * @charger: pointer to the ux500_charger structure * @vset_uv: charging voltage in microvolt * @iset_ua: charger output current in micrompere * * Check if the AC charger has been disconnected and reconnected without * AB8500 rising an interrupt. Returns 0 on success. */ static int ab8500_charger_ac_check_enable(struct ux500_charger *charger, int vset_uv, int iset_ua) { u8 mainch_ctrl1 = 0; int ret = 0; struct ab8500_charger *di = to_ab8500_charger_ac_device_info(charger); if (!di->ac.charger_connected) return ret; ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER, AB8500_MCH_CTRL1, &mainch_ctrl1); if (ret < 0) { dev_err(di->dev, "ab8500 read failed %d\n", __LINE__); return ret; } dev_dbg(di->dev, "AC charger ctrl: 0x%02x\n", mainch_ctrl1); if (!(mainch_ctrl1 & MAIN_CH_ENA)) { dev_info(di->dev, "Charging has been disabled abnormally and will be re-enabled\n"); ret = abx500_mask_and_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CHARGER_CTRL, DROP_COUNT_RESET, DROP_COUNT_RESET); if (ret < 0) { dev_err(di->dev, "ab8500 write failed %d\n", __LINE__); return ret; } ret = ab8500_charger_ac_en(&di->usb_chg, true, vset_uv, iset_ua); if (ret < 0) { dev_err(di->dev, "failed to enable AC charger %d\n", __LINE__); return ret; } } return ret; } /** * ab8500_charger_watchdog_kick() - kick charger watchdog * @di: pointer to the ab8500_charger structure * * Kick charger watchdog * Returns error code in case of failure else 0(on success) */ static int ab8500_charger_watchdog_kick(struct ux500_charger *charger) { int ret; struct ab8500_charger *di; if (charger->psy->desc->type == POWER_SUPPLY_TYPE_MAINS) di = to_ab8500_charger_ac_device_info(charger); else if (charger->psy->desc->type == POWER_SUPPLY_TYPE_USB) di = to_ab8500_charger_usb_device_info(charger); else return -ENXIO; ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CHARG_WD_CTRL, CHARG_WD_KICK); if (ret) dev_err(di->dev, "Failed to kick WD!\n"); return ret; } /** * ab8500_charger_update_charger_current() - update charger current * @charger: pointer to the ab8500_charger structure * @ich_out_ua: desired output current in microampere * * Update the charger output current for the specified charger * Returns error code in case of failure else 0(on success) */ static int ab8500_charger_update_charger_current(struct ux500_charger *charger, int ich_out_ua) { int ret; struct ab8500_charger *di; if (charger->psy->desc->type == POWER_SUPPLY_TYPE_MAINS) di = to_ab8500_charger_ac_device_info(charger); else if (charger->psy->desc->type == POWER_SUPPLY_TYPE_USB) di = to_ab8500_charger_usb_device_info(charger); else return -ENXIO; ret = ab8500_charger_set_output_curr(di, ich_out_ua); if (ret) { dev_err(di->dev, "%s " "Failed to set ChOutputCurentLevel\n", __func__); return ret; } /* Reset the main and usb drop input current measurement counter */ ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CHARGER_CTRL, DROP_COUNT_RESET); if (ret) { dev_err(di->dev, "%s write failed\n", __func__); return ret; } return ret; } static int ab8500_charger_get_ext_psy_data(struct device *dev, void *data) { struct power_supply *psy; struct power_supply *ext = dev_get_drvdata(dev); const char **supplicants = (const char **)ext->supplied_to; struct ab8500_charger *di; union power_supply_propval ret; int j; struct ux500_charger *usb_chg; usb_chg = (struct ux500_charger *)data; psy = usb_chg->psy; di = to_ab8500_charger_usb_device_info(usb_chg); /* * For all psy where the driver name appears in any supplied_to * in practice what we will find will always be "ab8500_fg" as * the fuel gauge is responsible of keeping track of VBAT. */ j = match_string(supplicants, ext->num_supplicants, psy->desc->name); if (j < 0) return 0; /* Go through all properties for the psy */ for (j = 0; j < ext->desc->num_properties; j++) { enum power_supply_property prop; prop = ext->desc->properties[j]; if (power_supply_get_property(ext, prop, &ret)) continue; switch (prop) { case POWER_SUPPLY_PROP_VOLTAGE_NOW: switch (ext->desc->type) { case POWER_SUPPLY_TYPE_BATTERY: /* This will always be "ab8500_fg" */ dev_dbg(di->dev, "get VBAT from %s\n", dev_name(&ext->dev)); di->vbat = ret.intval; break; default: break; } break; default: break; } } return 0; } /** * ab8500_charger_check_vbat_work() - keep vbus current within spec * @work pointer to the work_struct structure * * Due to a asic bug it is necessary to lower the input current to the vbus * charger when charging with at some specific levels. This issue is only valid * for below a certain battery voltage. This function makes sure that * the allowed current limit isn't exceeded. */ static void ab8500_charger_check_vbat_work(struct work_struct *work) { int t = 10; struct ab8500_charger *di = container_of(work, struct ab8500_charger, check_vbat_work.work); class_for_each_device(power_supply_class, NULL, &di->usb_chg, ab8500_charger_get_ext_psy_data); /* First run old_vbat is 0. */ if (di->old_vbat == 0) di->old_vbat = di->vbat; if (!((di->old_vbat <= VBAT_TRESH_IP_CUR_RED && di->vbat <= VBAT_TRESH_IP_CUR_RED) || (di->old_vbat > VBAT_TRESH_IP_CUR_RED && di->vbat > VBAT_TRESH_IP_CUR_RED))) { dev_dbg(di->dev, "Vbat did cross threshold, curr: %d, new: %d," " old: %d\n", di->max_usb_in_curr.usb_type_max_ua, di->vbat, di->old_vbat); ab8500_charger_set_vbus_in_curr(di, di->max_usb_in_curr.usb_type_max_ua); power_supply_changed(di->usb_chg.psy); } di->old_vbat = di->vbat; /* * No need to check the battery voltage every second when not close to * the threshold. */ if (di->vbat < (VBAT_TRESH_IP_CUR_RED + 100000) && (di->vbat > (VBAT_TRESH_IP_CUR_RED - 100000))) t = 1; queue_delayed_work(di->charger_wq, &di->check_vbat_work, t * HZ); } /** * ab8500_charger_check_hw_failure_work() - check main charger failure * @work: pointer to the work_struct structure * * Work queue function for checking the main charger status */ static void ab8500_charger_check_hw_failure_work(struct work_struct *work) { int ret; u8 reg_value; struct ab8500_charger *di = container_of(work, struct ab8500_charger, check_hw_failure_work.work); /* Check if the status bits for HW failure is still active */ if (di->flags.mainextchnotok) { ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CH_STATUS2_REG, &reg_value); if (ret < 0) { dev_err(di->dev, "%s ab8500 read failed\n", __func__); return; } if (!(reg_value & MAIN_CH_NOK)) { di->flags.mainextchnotok = false; ab8500_power_supply_changed(di, di->ac_chg.psy); } } if (di->flags.vbus_ovv) { ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CH_USBCH_STAT2_REG, &reg_value); if (ret < 0) { dev_err(di->dev, "%s ab8500 read failed\n", __func__); return; } if (!(reg_value & VBUS_OVV_TH)) { di->flags.vbus_ovv = false; ab8500_power_supply_changed(di, di->usb_chg.psy); } } /* If we still have a failure, schedule a new check */ if (di->flags.mainextchnotok || di->flags.vbus_ovv) { queue_delayed_work(di->charger_wq, &di->check_hw_failure_work, round_jiffies(HZ)); } } /** * ab8500_charger_kick_watchdog_work() - kick the watchdog * @work: pointer to the work_struct structure * * Work queue function for kicking the charger watchdog. * * For ABB revision 1.0 and 1.1 there is a bug in the watchdog * logic. That means we have to continuously kick the charger * watchdog even when no charger is connected. This is only * valid once the AC charger has been enabled. This is * a bug that is not handled by the algorithm and the * watchdog have to be kicked by the charger driver * when the AC charger is disabled */ static void ab8500_charger_kick_watchdog_work(struct work_struct *work) { int ret; struct ab8500_charger *di = container_of(work, struct ab8500_charger, kick_wd_work.work); ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CHARG_WD_CTRL, CHARG_WD_KICK); if (ret) dev_err(di->dev, "Failed to kick WD!\n"); /* Schedule a new watchdog kick */ queue_delayed_work(di->charger_wq, &di->kick_wd_work, round_jiffies(WD_KICK_INTERVAL)); } /** * ab8500_charger_ac_work() - work to get and set main charger status * @work: pointer to the work_struct structure * * Work queue function for checking the main charger status */ static void ab8500_charger_ac_work(struct work_struct *work) { int ret; struct ab8500_charger *di = container_of(work, struct ab8500_charger, ac_work); /* * Since we can't be sure that the events are received * synchronously, we have the check if the main charger is * connected by reading the status register */ ret = ab8500_charger_detect_chargers(di, false); if (ret < 0) return; if (ret & AC_PW_CONN) { di->ac.charger_connected = 1; di->ac_conn = true; } else { di->ac.charger_connected = 0; } ab8500_power_supply_changed(di, di->ac_chg.psy); sysfs_notify(&di->ac_chg.psy->dev.kobj, NULL, "present"); } static void ab8500_charger_usb_attached_work(struct work_struct *work) { struct ab8500_charger *di = container_of(work, struct ab8500_charger, usb_charger_attached_work.work); int usbch = (USB_CH_VBUSDROP | USB_CH_VBUSDETDBNC); int ret, i; u8 statval; for (i = 0; i < 10; i++) { ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CH_USBCH_STAT1_REG, &statval); if (ret < 0) { dev_err(di->dev, "ab8500 read failed %d\n", __LINE__); goto reschedule; } if ((statval & usbch) != usbch) goto reschedule; msleep(CHARGER_STATUS_POLL); } ab8500_charger_usb_en(&di->usb_chg, 0, 0, 0); mutex_lock(&di->charger_attached_mutex); mutex_unlock(&di->charger_attached_mutex); return; reschedule: queue_delayed_work(di->charger_wq, &di->usb_charger_attached_work, HZ); } static void ab8500_charger_ac_attached_work(struct work_struct *work) { struct ab8500_charger *di = container_of(work, struct ab8500_charger, ac_charger_attached_work.work); int mainch = (MAIN_CH_STATUS2_MAINCHGDROP | MAIN_CH_STATUS2_MAINCHARGERDETDBNC); int ret, i; u8 statval; for (i = 0; i < 10; i++) { ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CH_STATUS2_REG, &statval); if (ret < 0) { dev_err(di->dev, "ab8500 read failed %d\n", __LINE__); goto reschedule; } if ((statval & mainch) != mainch) goto reschedule; msleep(CHARGER_STATUS_POLL); } ab8500_charger_ac_en(&di->ac_chg, 0, 0, 0); queue_work(di->charger_wq, &di->ac_work); mutex_lock(&di->charger_attached_mutex); mutex_unlock(&di->charger_attached_mutex); return; reschedule: queue_delayed_work(di->charger_wq, &di->ac_charger_attached_work, HZ); } /** * ab8500_charger_detect_usb_type_work() - work to detect USB type * @work: Pointer to the work_struct structure * * Detect the type of USB plugged */ static void ab8500_charger_detect_usb_type_work(struct work_struct *work) { int ret; struct ab8500_charger *di = container_of(work, struct ab8500_charger, detect_usb_type_work); /* * Since we can't be sure that the events are received * synchronously, we have the check if is * connected by reading the status register */ ret = ab8500_charger_detect_chargers(di, false); if (ret < 0) return; if (!(ret & USB_PW_CONN)) { dev_dbg(di->dev, "%s di->vbus_detected = false\n", __func__); di->vbus_detected = false; ab8500_charger_set_usb_connected(di, false); ab8500_power_supply_changed(di, di->usb_chg.psy); } else { dev_dbg(di->dev, "%s di->vbus_detected = true\n", __func__); di->vbus_detected = true; if (is_ab8500_1p1_or_earlier(di->parent)) { ret = ab8500_charger_detect_usb_type(di); if (!ret) { ab8500_charger_set_usb_connected(di, true); ab8500_power_supply_changed(di, di->usb_chg.psy); } } else { /* * For ABB cut2.0 and onwards we have an IRQ, * USB_LINK_STATUS that will be triggered when the USB * link status changes. The exception is USB connected * during startup. Then we don't get a * USB_LINK_STATUS IRQ */ if (di->vbus_detected_start) { di->vbus_detected_start = false; ret = ab8500_charger_detect_usb_type(di); if (!ret) { ab8500_charger_set_usb_connected(di, true); ab8500_power_supply_changed(di, di->usb_chg.psy); } } } } } /** * ab8500_charger_usb_link_attach_work() - work to detect USB type * @work: pointer to the work_struct structure * * Detect the type of USB plugged */ static void ab8500_charger_usb_link_attach_work(struct work_struct *work) { struct ab8500_charger *di = container_of(work, struct ab8500_charger, attach_work.work); int ret; /* Update maximum input current if USB enumeration is not detected */ if (!di->usb.charger_online) { ret = ab8500_charger_set_vbus_in_curr(di, di->max_usb_in_curr.usb_type_max_ua); if (ret) return; } ab8500_charger_set_usb_connected(di, true); ab8500_power_supply_changed(di, di->usb_chg.psy); } /** * ab8500_charger_usb_link_status_work() - work to detect USB type * @work: pointer to the work_struct structure * * Detect the type of USB plugged */ static void ab8500_charger_usb_link_status_work(struct work_struct *work) { int detected_chargers; int ret; u8 val; u8 link_status; struct ab8500_charger *di = container_of(work, struct ab8500_charger, usb_link_status_work); /* * Since we can't be sure that the events are received * synchronously, we have the check if is * connected by reading the status register */ detected_chargers = ab8500_charger_detect_chargers(di, false); if (detected_chargers < 0) return; /* * Some chargers that breaks the USB spec is * identified as invalid by AB8500 and it refuse * to start the charging process. but by jumping * through a few hoops it can be forced to start. */ if (is_ab8500(di->parent)) ret = abx500_get_register_interruptible(di->dev, AB8500_USB, AB8500_USB_LINE_STAT_REG, &val); else ret = abx500_get_register_interruptible(di->dev, AB8500_USB, AB8500_USB_LINK1_STAT_REG, &val); if (ret >= 0) dev_dbg(di->dev, "UsbLineStatus register = 0x%02x\n", val); else dev_dbg(di->dev, "Error reading USB link status\n"); if (is_ab8500(di->parent)) link_status = AB8500_USB_LINK_STATUS; else link_status = AB8505_USB_LINK_STATUS; if (detected_chargers & USB_PW_CONN) { if (((val & link_status) >> USB_LINK_STATUS_SHIFT) == USB_STAT_NOT_VALID_LINK && di->invalid_charger_detect_state == 0) { dev_dbg(di->dev, "Invalid charger detected, state= 0\n"); /*Enable charger*/ abx500_mask_and_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_USBCH_CTRL1_REG, USB_CH_ENA, USB_CH_ENA); /*Enable charger detection*/ abx500_mask_and_set_register_interruptible(di->dev, AB8500_USB, AB8500_USB_LINE_CTRL2_REG, USB_CH_DET, USB_CH_DET); di->invalid_charger_detect_state = 1; /*exit and wait for new link status interrupt.*/ return; } if (di->invalid_charger_detect_state == 1) { dev_dbg(di->dev, "Invalid charger detected, state= 1\n"); /*Stop charger detection*/ abx500_mask_and_set_register_interruptible(di->dev, AB8500_USB, AB8500_USB_LINE_CTRL2_REG, USB_CH_DET, 0x00); /*Check link status*/ if (is_ab8500(di->parent)) ret = abx500_get_register_interruptible(di->dev, AB8500_USB, AB8500_USB_LINE_STAT_REG, &val); else ret = abx500_get_register_interruptible(di->dev, AB8500_USB, AB8500_USB_LINK1_STAT_REG, &val); dev_dbg(di->dev, "USB link status= 0x%02x\n", (val & link_status) >> USB_LINK_STATUS_SHIFT); di->invalid_charger_detect_state = 2; } } else { di->invalid_charger_detect_state = 0; } if (!(detected_chargers & USB_PW_CONN)) { di->vbus_detected = false; ab8500_charger_set_usb_connected(di, false); ab8500_power_supply_changed(di, di->usb_chg.psy); return; } dev_dbg(di->dev,"%s di->vbus_detected = true\n",__func__); di->vbus_detected = true; ret = ab8500_charger_read_usb_type(di); if (ret) { if (ret == -ENXIO) { /* No valid charger type detected */ ab8500_charger_set_usb_connected(di, false); ab8500_power_supply_changed(di, di->usb_chg.psy); } return; } if (di->usb_device_is_unrecognised) { dev_dbg(di->dev, "Potential Legacy Charger device. " "Delay work for %d msec for USB enum " "to finish", WAIT_ACA_RID_ENUMERATION); queue_delayed_work(di->charger_wq, &di->attach_work, msecs_to_jiffies(WAIT_ACA_RID_ENUMERATION)); } else if (di->is_aca_rid == 1) { /* Only wait once */ di->is_aca_rid++; dev_dbg(di->dev, "%s Wait %d msec for USB enum to finish", __func__, WAIT_ACA_RID_ENUMERATION); queue_delayed_work(di->charger_wq, &di->attach_work, msecs_to_jiffies(WAIT_ACA_RID_ENUMERATION)); } else { queue_delayed_work(di->charger_wq, &di->attach_work, 0); } } static void ab8500_charger_usb_state_changed_work(struct work_struct *work) { int ret; unsigned long flags; struct ab8500_charger *di = container_of(work, struct ab8500_charger, usb_state_changed_work.work); if (!di->vbus_detected) { dev_dbg(di->dev, "%s !di->vbus_detected\n", __func__); return; } spin_lock_irqsave(&di->usb_state.usb_lock, flags); di->usb_state.state = di->usb_state.state_tmp; di->usb_state.usb_current_ua = di->usb_state.usb_current_tmp_ua; spin_unlock_irqrestore(&di->usb_state.usb_lock, flags); dev_dbg(di->dev, "%s USB state: 0x%02x uA: %d\n", __func__, di->usb_state.state, di->usb_state.usb_current_ua); switch (di->usb_state.state) { case AB8500_BM_USB_STATE_RESET_HS: case AB8500_BM_USB_STATE_RESET_FS: case AB8500_BM_USB_STATE_SUSPEND: case AB8500_BM_USB_STATE_MAX: ab8500_charger_set_usb_connected(di, false); ab8500_power_supply_changed(di, di->usb_chg.psy); break; case AB8500_BM_USB_STATE_RESUME: /* * when suspend->resume there should be delay * of 1sec for enabling charging */ msleep(1000); fallthrough; case AB8500_BM_USB_STATE_CONFIGURED: /* * USB is configured, enable charging with the charging * input current obtained from USB driver */ if (!ab8500_charger_get_usb_cur(di)) { /* Update maximum input current */ ret = ab8500_charger_set_vbus_in_curr(di, di->max_usb_in_curr.usb_type_max_ua); if (ret) return; ab8500_charger_set_usb_connected(di, true); ab8500_power_supply_changed(di, di->usb_chg.psy); } break; default: break; } } /** * ab8500_charger_check_usbchargernotok_work() - check USB chg not ok status * @work: pointer to the work_struct structure * * Work queue function for checking the USB charger Not OK status */ static void ab8500_charger_check_usbchargernotok_work(struct work_struct *work) { int ret; u8 reg_value; bool prev_status; struct ab8500_charger *di = container_of(work, struct ab8500_charger, check_usbchgnotok_work.work); /* Check if the status bit for usbchargernotok is still active */ ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CH_USBCH_STAT2_REG, &reg_value); if (ret < 0) { dev_err(di->dev, "%s ab8500 read failed\n", __func__); return; } prev_status = di->flags.usbchargernotok; if (reg_value & VBUS_CH_NOK) { di->flags.usbchargernotok = true; /* Check again in 1sec */ queue_delayed_work(di->charger_wq, &di->check_usbchgnotok_work, HZ); } else { di->flags.usbchargernotok = false; di->flags.vbus_collapse = false; } if (prev_status != di->flags.usbchargernotok) ab8500_power_supply_changed(di, di->usb_chg.psy); } /** * ab8500_charger_check_main_thermal_prot_work() - check main thermal status * @work: pointer to the work_struct structure * * Work queue function for checking the Main thermal prot status */ static void ab8500_charger_check_main_thermal_prot_work( struct work_struct *work) { int ret; u8 reg_value; struct ab8500_charger *di = container_of(work, struct ab8500_charger, check_main_thermal_prot_work); /* Check if the status bit for main_thermal_prot is still active */ ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CH_STATUS2_REG, &reg_value); if (ret < 0) { dev_err(di->dev, "%s ab8500 read failed\n", __func__); return; } if (reg_value & MAIN_CH_TH_PROT) di->flags.main_thermal_prot = true; else di->flags.main_thermal_prot = false; ab8500_power_supply_changed(di, di->ac_chg.psy); } /** * ab8500_charger_check_usb_thermal_prot_work() - check usb thermal status * @work: pointer to the work_struct structure * * Work queue function for checking the USB thermal prot status */ static void ab8500_charger_check_usb_thermal_prot_work( struct work_struct *work) { int ret; u8 reg_value; struct ab8500_charger *di = container_of(work, struct ab8500_charger, check_usb_thermal_prot_work); /* Check if the status bit for usb_thermal_prot is still active */ ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CH_USBCH_STAT2_REG, &reg_value); if (ret < 0) { dev_err(di->dev, "%s ab8500 read failed\n", __func__); return; } if (reg_value & USB_CH_TH_PROT) di->flags.usb_thermal_prot = true; else di->flags.usb_thermal_prot = false; ab8500_power_supply_changed(di, di->usb_chg.psy); } /** * ab8500_charger_mainchunplugdet_handler() - main charger unplugged * @irq: interrupt number * @_di: pointer to the ab8500_charger structure * * Returns IRQ status(IRQ_HANDLED) */ static irqreturn_t ab8500_charger_mainchunplugdet_handler(int irq, void *_di) { struct ab8500_charger *di = _di; dev_dbg(di->dev, "Main charger unplugged\n"); queue_work(di->charger_wq, &di->ac_work); cancel_delayed_work_sync(&di->ac_charger_attached_work); mutex_lock(&di->charger_attached_mutex); mutex_unlock(&di->charger_attached_mutex); return IRQ_HANDLED; } /** * ab8500_charger_mainchplugdet_handler() - main charger plugged * @irq: interrupt number * @_di: pointer to the ab8500_charger structure * * Returns IRQ status(IRQ_HANDLED) */ static irqreturn_t ab8500_charger_mainchplugdet_handler(int irq, void *_di) { struct ab8500_charger *di = _di; dev_dbg(di->dev, "Main charger plugged\n"); queue_work(di->charger_wq, &di->ac_work); mutex_lock(&di->charger_attached_mutex); mutex_unlock(&di->charger_attached_mutex); if (is_ab8500(di->parent)) queue_delayed_work(di->charger_wq, &di->ac_charger_attached_work, HZ); return IRQ_HANDLED; } /** * ab8500_charger_mainextchnotok_handler() - main charger not ok * @irq: interrupt number * @_di: pointer to the ab8500_charger structure * * Returns IRQ status(IRQ_HANDLED) */ static irqreturn_t ab8500_charger_mainextchnotok_handler(int irq, void *_di) { struct ab8500_charger *di = _di; dev_dbg(di->dev, "Main charger not ok\n"); di->flags.mainextchnotok = true; ab8500_power_supply_changed(di, di->ac_chg.psy); /* Schedule a new HW failure check */ queue_delayed_work(di->charger_wq, &di->check_hw_failure_work, 0); return IRQ_HANDLED; } /** * ab8500_charger_mainchthprotr_handler() - Die temp is above main charger * thermal protection threshold * @irq: interrupt number * @_di: pointer to the ab8500_charger structure * * Returns IRQ status(IRQ_HANDLED) */ static irqreturn_t ab8500_charger_mainchthprotr_handler(int irq, void *_di) { struct ab8500_charger *di = _di; dev_dbg(di->dev, "Die temp above Main charger thermal protection threshold\n"); queue_work(di->charger_wq, &di->check_main_thermal_prot_work); return IRQ_HANDLED; } /** * ab8500_charger_mainchthprotf_handler() - Die temp is below main charger * thermal protection threshold * @irq: interrupt number * @_di: pointer to the ab8500_charger structure * * Returns IRQ status(IRQ_HANDLED) */ static irqreturn_t ab8500_charger_mainchthprotf_handler(int irq, void *_di) { struct ab8500_charger *di = _di; dev_dbg(di->dev, "Die temp ok for Main charger thermal protection threshold\n"); queue_work(di->charger_wq, &di->check_main_thermal_prot_work); return IRQ_HANDLED; } static void ab8500_charger_vbus_drop_end_work(struct work_struct *work) { struct ab8500_charger *di = container_of(work, struct ab8500_charger, vbus_drop_end_work.work); int ret, curr_ua; u8 reg_value; di->flags.vbus_drop_end = false; /* Reset the drop counter */ abx500_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CHARGER_CTRL, 0x01); ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CH_USBCH_STAT2_REG, &reg_value); if (ret < 0) { dev_err(di->dev, "%s read failed\n", __func__); return; } curr_ua = ab8500_charge_input_curr_map[ reg_value >> AUTO_VBUS_IN_CURR_LIM_SHIFT]; if (di->max_usb_in_curr.calculated_max_ua != curr_ua) { /* USB source is collapsing */ di->max_usb_in_curr.calculated_max_ua = curr_ua; dev_dbg(di->dev, "VBUS input current limiting to %d uA\n", di->max_usb_in_curr.calculated_max_ua); } else { /* * USB source can not give more than this amount. * Taking more will collapse the source. */ di->max_usb_in_curr.set_max_ua = di->max_usb_in_curr.calculated_max_ua; dev_dbg(di->dev, "VBUS input current limited to %d uA\n", di->max_usb_in_curr.set_max_ua); } if (di->usb.charger_connected) ab8500_charger_set_vbus_in_curr(di, di->max_usb_in_curr.usb_type_max_ua); } /** * ab8500_charger_vbusdetf_handler() - VBUS falling detected * @irq: interrupt number * @_di: pointer to the ab8500_charger structure * * Returns IRQ status(IRQ_HANDLED) */ static irqreturn_t ab8500_charger_vbusdetf_handler(int irq, void *_di) { struct ab8500_charger *di = _di; di->vbus_detected = false; dev_dbg(di->dev, "VBUS falling detected\n"); queue_work(di->charger_wq, &di->detect_usb_type_work); return IRQ_HANDLED; } /** * ab8500_charger_vbusdetr_handler() - VBUS rising detected * @irq: interrupt number * @_di: pointer to the ab8500_charger structure * * Returns IRQ status(IRQ_HANDLED) */ static irqreturn_t ab8500_charger_vbusdetr_handler(int irq, void *_di) { struct ab8500_charger *di = _di; di->vbus_detected = true; dev_dbg(di->dev, "VBUS rising detected\n"); queue_work(di->charger_wq, &di->detect_usb_type_work); return IRQ_HANDLED; } /** * ab8500_charger_usblinkstatus_handler() - USB link status has changed * @irq: interrupt number * @_di: pointer to the ab8500_charger structure * * Returns IRQ status(IRQ_HANDLED) */ static irqreturn_t ab8500_charger_usblinkstatus_handler(int irq, void *_di) { struct ab8500_charger *di = _di; dev_dbg(di->dev, "USB link status changed\n"); queue_work(di->charger_wq, &di->usb_link_status_work); return IRQ_HANDLED; } /** * ab8500_charger_usbchthprotr_handler() - Die temp is above usb charger * thermal protection threshold * @irq: interrupt number * @_di: pointer to the ab8500_charger structure * * Returns IRQ status(IRQ_HANDLED) */ static irqreturn_t ab8500_charger_usbchthprotr_handler(int irq, void *_di) { struct ab8500_charger *di = _di; dev_dbg(di->dev, "Die temp above USB charger thermal protection threshold\n"); queue_work(di->charger_wq, &di->check_usb_thermal_prot_work); return IRQ_HANDLED; } /** * ab8500_charger_usbchthprotf_handler() - Die temp is below usb charger * thermal protection threshold * @irq: interrupt number * @_di: pointer to the ab8500_charger structure * * Returns IRQ status(IRQ_HANDLED) */ static irqreturn_t ab8500_charger_usbchthprotf_handler(int irq, void *_di) { struct ab8500_charger *di = _di; dev_dbg(di->dev, "Die temp ok for USB charger thermal protection threshold\n"); queue_work(di->charger_wq, &di->check_usb_thermal_prot_work); return IRQ_HANDLED; } /** * ab8500_charger_usbchargernotokr_handler() - USB charger not ok detected * @irq: interrupt number * @_di: pointer to the ab8500_charger structure * * Returns IRQ status(IRQ_HANDLED) */ static irqreturn_t ab8500_charger_usbchargernotokr_handler(int irq, void *_di) { struct ab8500_charger *di = _di; dev_dbg(di->dev, "Not allowed USB charger detected\n"); queue_delayed_work(di->charger_wq, &di->check_usbchgnotok_work, 0); return IRQ_HANDLED; } /** * ab8500_charger_chwdexp_handler() - Charger watchdog expired * @irq: interrupt number * @_di: pointer to the ab8500_charger structure * * Returns IRQ status(IRQ_HANDLED) */ static irqreturn_t ab8500_charger_chwdexp_handler(int irq, void *_di) { struct ab8500_charger *di = _di; dev_dbg(di->dev, "Charger watchdog expired\n"); /* * The charger that was online when the watchdog expired * needs to be restarted for charging to start again */ if (di->ac.charger_online) { di->ac.wd_expired = true; ab8500_power_supply_changed(di, di->ac_chg.psy); } if (di->usb.charger_online) { di->usb.wd_expired = true; ab8500_power_supply_changed(di, di->usb_chg.psy); } return IRQ_HANDLED; } /** * ab8500_charger_vbuschdropend_handler() - VBUS drop removed * @irq: interrupt number * @_di: pointer to the ab8500_charger structure * * Returns IRQ status(IRQ_HANDLED) */ static irqreturn_t ab8500_charger_vbuschdropend_handler(int irq, void *_di) { struct ab8500_charger *di = _di; dev_dbg(di->dev, "VBUS charger drop ended\n"); di->flags.vbus_drop_end = true; /* * VBUS might have dropped due to bad connection. * Schedule a new input limit set to the value SW requests. */ queue_delayed_work(di->charger_wq, &di->vbus_drop_end_work, round_jiffies(VBUS_IN_CURR_LIM_RETRY_SET_TIME * HZ)); return IRQ_HANDLED; } /** * ab8500_charger_vbusovv_handler() - VBUS overvoltage detected * @irq: interrupt number * @_di: pointer to the ab8500_charger structure * * Returns IRQ status(IRQ_HANDLED) */ static irqreturn_t ab8500_charger_vbusovv_handler(int irq, void *_di) { struct ab8500_charger *di = _di; dev_dbg(di->dev, "VBUS overvoltage detected\n"); di->flags.vbus_ovv = true; ab8500_power_supply_changed(di, di->usb_chg.psy); /* Schedule a new HW failure check */ queue_delayed_work(di->charger_wq, &di->check_hw_failure_work, 0); return IRQ_HANDLED; } /** * ab8500_charger_ac_get_property() - get the ac/mains properties * @psy: pointer to the power_supply structure * @psp: pointer to the power_supply_property structure * @val: pointer to the power_supply_propval union * * This function gets called when an application tries to get the ac/mains * properties by reading the sysfs files. * AC/Mains properties are online, present and voltage. * online: ac/mains charging is in progress or not * present: presence of the ac/mains * voltage: AC/Mains voltage * Returns error code in case of failure else 0(on success) */ static int ab8500_charger_ac_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct ab8500_charger *di; int ret; di = to_ab8500_charger_ac_device_info(psy_to_ux500_charger(psy)); switch (psp) { case POWER_SUPPLY_PROP_HEALTH: if (di->flags.mainextchnotok) val->intval = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE; else if (di->ac.wd_expired || di->usb.wd_expired) val->intval = POWER_SUPPLY_HEALTH_DEAD; else if (di->flags.main_thermal_prot) val->intval = POWER_SUPPLY_HEALTH_OVERHEAT; else val->intval = POWER_SUPPLY_HEALTH_GOOD; break; case POWER_SUPPLY_PROP_ONLINE: val->intval = di->ac.charger_online; break; case POWER_SUPPLY_PROP_PRESENT: val->intval = di->ac.charger_connected; break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: ret = ab8500_charger_get_ac_voltage(di); if (ret >= 0) di->ac.charger_voltage_uv = ret; /* On error, use previous value */ val->intval = di->ac.charger_voltage_uv; break; case POWER_SUPPLY_PROP_VOLTAGE_AVG: /* * This property is used to indicate when CV mode is entered * for the AC charger */ di->ac.cv_active = ab8500_charger_ac_cv(di); val->intval = di->ac.cv_active; break; case POWER_SUPPLY_PROP_CURRENT_NOW: ret = ab8500_charger_get_ac_current(di); if (ret >= 0) di->ac.charger_current_ua = ret; val->intval = di->ac.charger_current_ua; break; default: return -EINVAL; } return 0; } /** * ab8500_charger_usb_get_property() - get the usb properties * @psy: pointer to the power_supply structure * @psp: pointer to the power_supply_property structure * @val: pointer to the power_supply_propval union * * This function gets called when an application tries to get the usb * properties by reading the sysfs files. * USB properties are online, present and voltage. * online: usb charging is in progress or not * present: presence of the usb * voltage: vbus voltage * Returns error code in case of failure else 0(on success) */ static int ab8500_charger_usb_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct ab8500_charger *di; int ret; di = to_ab8500_charger_usb_device_info(psy_to_ux500_charger(psy)); switch (psp) { case POWER_SUPPLY_PROP_HEALTH: if (di->flags.usbchargernotok) val->intval = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE; else if (di->ac.wd_expired || di->usb.wd_expired) val->intval = POWER_SUPPLY_HEALTH_DEAD; else if (di->flags.usb_thermal_prot) val->intval = POWER_SUPPLY_HEALTH_OVERHEAT; else if (di->flags.vbus_ovv) val->intval = POWER_SUPPLY_HEALTH_OVERVOLTAGE; else val->intval = POWER_SUPPLY_HEALTH_GOOD; break; case POWER_SUPPLY_PROP_ONLINE: val->intval = di->usb.charger_online; break; case POWER_SUPPLY_PROP_PRESENT: val->intval = di->usb.charger_connected; break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: ret = ab8500_charger_get_vbus_voltage(di); if (ret >= 0) di->usb.charger_voltage_uv = ret; val->intval = di->usb.charger_voltage_uv; break; case POWER_SUPPLY_PROP_VOLTAGE_AVG: /* * This property is used to indicate when CV mode is entered * for the USB charger */ di->usb.cv_active = ab8500_charger_usb_cv(di); val->intval = di->usb.cv_active; break; case POWER_SUPPLY_PROP_CURRENT_NOW: ret = ab8500_charger_get_usb_current(di); if (ret >= 0) di->usb.charger_current_ua = ret; val->intval = di->usb.charger_current_ua; break; case POWER_SUPPLY_PROP_CURRENT_AVG: /* * This property is used to indicate when VBUS has collapsed * due to too high output current from the USB charger */ if (di->flags.vbus_collapse) val->intval = 1; else val->intval = 0; break; default: return -EINVAL; } return 0; } /** * ab8500_charger_init_hw_registers() - Set up charger related registers * @di: pointer to the ab8500_charger structure * * Set up charger OVV, watchdog and maximum voltage registers as well as * charging of the backup battery */ static int ab8500_charger_init_hw_registers(struct ab8500_charger *di) { int ret = 0; /* Setup maximum charger current and voltage for ABB cut2.0 */ if (!is_ab8500_1p1_or_earlier(di->parent)) { ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CH_VOLT_LVL_MAX_REG, CH_VOL_LVL_4P6); if (ret) { dev_err(di->dev, "failed to set CH_VOLT_LVL_MAX_REG\n"); goto out; } ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CH_OPT_CRNTLVL_MAX_REG, CH_OP_CUR_LVL_1P6); if (ret) { dev_err(di->dev, "failed to set CH_OPT_CRNTLVL_MAX_REG\n"); goto out; } } if (is_ab8505_2p0(di->parent)) ret = abx500_mask_and_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_USBCH_CTRL2_REG, VBUS_AUTO_IN_CURR_LIM_ENA, VBUS_AUTO_IN_CURR_LIM_ENA); else /* * VBUS OVV set to 6.3V and enable automatic current limitation */ ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_USBCH_CTRL2_REG, VBUS_OVV_SELECT_6P3V | VBUS_AUTO_IN_CURR_LIM_ENA); if (ret) { dev_err(di->dev, "failed to set automatic current limitation\n"); goto out; } /* Enable main watchdog in OTP */ ret = abx500_set_register_interruptible(di->dev, AB8500_OTP_EMUL, AB8500_OTP_CONF_15, OTP_ENABLE_WD); if (ret) { dev_err(di->dev, "failed to enable main WD in OTP\n"); goto out; } /* Enable main watchdog */ ret = abx500_set_register_interruptible(di->dev, AB8500_SYS_CTRL2_BLOCK, AB8500_MAIN_WDOG_CTRL_REG, MAIN_WDOG_ENA); if (ret) { dev_err(di->dev, "failed to enable main watchdog\n"); goto out; } /* * Due to internal synchronisation, Enable and Kick watchdog bits * cannot be enabled in a single write. * A minimum delay of 2*32 kHz period (62.5µs) must be inserted * between writing Enable then Kick bits. */ udelay(63); /* Kick main watchdog */ ret = abx500_set_register_interruptible(di->dev, AB8500_SYS_CTRL2_BLOCK, AB8500_MAIN_WDOG_CTRL_REG, (MAIN_WDOG_ENA | MAIN_WDOG_KICK)); if (ret) { dev_err(di->dev, "failed to kick main watchdog\n"); goto out; } /* Disable main watchdog */ ret = abx500_set_register_interruptible(di->dev, AB8500_SYS_CTRL2_BLOCK, AB8500_MAIN_WDOG_CTRL_REG, MAIN_WDOG_DIS); if (ret) { dev_err(di->dev, "failed to disable main watchdog\n"); goto out; } /* Set watchdog timeout */ ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CH_WD_TIMER_REG, WD_TIMER); if (ret) { dev_err(di->dev, "failed to set charger watchdog timeout\n"); goto out; } ret = ab8500_charger_led_en(di, false); if (ret < 0) { dev_err(di->dev, "failed to disable LED\n"); goto out; } ret = abx500_set_register_interruptible(di->dev, AB8500_RTC, AB8500_RTC_BACKUP_CHG_REG, (di->bm->bkup_bat_v & 0x3) | di->bm->bkup_bat_i); if (ret) { dev_err(di->dev, "failed to setup backup battery charging\n"); goto out; } /* Enable backup battery charging */ ret = abx500_mask_and_set_register_interruptible(di->dev, AB8500_RTC, AB8500_RTC_CTRL_REG, RTC_BUP_CH_ENA, RTC_BUP_CH_ENA); if (ret < 0) { dev_err(di->dev, "%s mask and set failed\n", __func__); goto out; } out: return ret; } /* * ab8500 charger driver interrupts and their respective isr */ static struct ab8500_charger_interrupts ab8500_charger_irq[] = { {"MAIN_CH_UNPLUG_DET", ab8500_charger_mainchunplugdet_handler}, {"MAIN_CHARGE_PLUG_DET", ab8500_charger_mainchplugdet_handler}, {"MAIN_EXT_CH_NOT_OK", ab8500_charger_mainextchnotok_handler}, {"MAIN_CH_TH_PROT_R", ab8500_charger_mainchthprotr_handler}, {"MAIN_CH_TH_PROT_F", ab8500_charger_mainchthprotf_handler}, {"VBUS_DET_F", ab8500_charger_vbusdetf_handler}, {"VBUS_DET_R", ab8500_charger_vbusdetr_handler}, {"USB_LINK_STATUS", ab8500_charger_usblinkstatus_handler}, {"USB_CH_TH_PROT_R", ab8500_charger_usbchthprotr_handler}, {"USB_CH_TH_PROT_F", ab8500_charger_usbchthprotf_handler}, {"USB_CHARGER_NOT_OKR", ab8500_charger_usbchargernotokr_handler}, {"VBUS_OVV", ab8500_charger_vbusovv_handler}, {"CH_WD_EXP", ab8500_charger_chwdexp_handler}, {"VBUS_CH_DROP_END", ab8500_charger_vbuschdropend_handler}, }; static int ab8500_charger_usb_notifier_call(struct notifier_block *nb, unsigned long event, void *power) { struct ab8500_charger *di = container_of(nb, struct ab8500_charger, nb); enum ab8500_usb_state bm_usb_state; /* * FIXME: it appears the AB8500 PHY never sends what it should here. * Fix the PHY driver to properly notify the desired current. * Also broadcast microampere and not milliampere. */ unsigned mA = *((unsigned *)power); if (event != USB_EVENT_VBUS) { dev_dbg(di->dev, "not a standard host, returning\n"); return NOTIFY_DONE; } /* TODO: State is fabricate here. See if charger really needs USB * state or if mA is enough */ if ((di->usb_state.usb_current_ua == 2000) && (mA > 2)) bm_usb_state = AB8500_BM_USB_STATE_RESUME; else if (mA == 0) bm_usb_state = AB8500_BM_USB_STATE_RESET_HS; else if (mA == 2) bm_usb_state = AB8500_BM_USB_STATE_SUSPEND; else if (mA >= 8) /* 8, 100, 500 */ bm_usb_state = AB8500_BM_USB_STATE_CONFIGURED; else /* Should never occur */ bm_usb_state = AB8500_BM_USB_STATE_RESET_FS; dev_dbg(di->dev, "%s usb_state: 0x%02x mA: %d\n", __func__, bm_usb_state, mA); spin_lock(&di->usb_state.usb_lock); di->usb_state.state_tmp = bm_usb_state; /* FIXME: broadcast ua instead, see above */ di->usb_state.usb_current_tmp_ua = mA * 1000; spin_unlock(&di->usb_state.usb_lock); /* * wait for some time until you get updates from the usb stack * and negotiations are completed */ queue_delayed_work(di->charger_wq, &di->usb_state_changed_work, HZ/2); return NOTIFY_OK; } static int __maybe_unused ab8500_charger_resume(struct device *dev) { int ret; struct ab8500_charger *di = dev_get_drvdata(dev); /* * For ABB revision 1.0 and 1.1 there is a bug in the watchdog * logic. That means we have to continuously kick the charger * watchdog even when no charger is connected. This is only * valid once the AC charger has been enabled. This is * a bug that is not handled by the algorithm and the * watchdog have to be kicked by the charger driver * when the AC charger is disabled */ if (di->ac_conn && is_ab8500_1p1_or_earlier(di->parent)) { ret = abx500_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CHARG_WD_CTRL, CHARG_WD_KICK); if (ret) dev_err(di->dev, "Failed to kick WD!\n"); /* If not already pending start a new timer */ queue_delayed_work(di->charger_wq, &di->kick_wd_work, round_jiffies(WD_KICK_INTERVAL)); } /* If we still have a HW failure, schedule a new check */ if (di->flags.mainextchnotok || di->flags.vbus_ovv) { queue_delayed_work(di->charger_wq, &di->check_hw_failure_work, 0); } if (di->flags.vbus_drop_end) queue_delayed_work(di->charger_wq, &di->vbus_drop_end_work, 0); return 0; } static int __maybe_unused ab8500_charger_suspend(struct device *dev) { struct ab8500_charger *di = dev_get_drvdata(dev); /* Cancel any pending jobs */ cancel_delayed_work(&di->check_hw_failure_work); cancel_delayed_work(&di->vbus_drop_end_work); flush_delayed_work(&di->attach_work); flush_delayed_work(&di->usb_charger_attached_work); flush_delayed_work(&di->ac_charger_attached_work); flush_delayed_work(&di->check_usbchgnotok_work); flush_delayed_work(&di->check_vbat_work); flush_delayed_work(&di->kick_wd_work); flush_work(&di->usb_link_status_work); flush_work(&di->ac_work); flush_work(&di->detect_usb_type_work); if (atomic_read(&di->current_stepping_sessions)) return -EAGAIN; return 0; } static char *supply_interface[] = { "ab8500_chargalg", "ab8500_fg", "ab8500_btemp", }; static const struct power_supply_desc ab8500_ac_chg_desc = { .name = "ab8500_ac", .type = POWER_SUPPLY_TYPE_MAINS, .properties = ab8500_charger_ac_props, .num_properties = ARRAY_SIZE(ab8500_charger_ac_props), .get_property = ab8500_charger_ac_get_property, }; static const struct power_supply_desc ab8500_usb_chg_desc = { .name = "ab8500_usb", .type = POWER_SUPPLY_TYPE_USB, .properties = ab8500_charger_usb_props, .num_properties = ARRAY_SIZE(ab8500_charger_usb_props), .get_property = ab8500_charger_usb_get_property, }; static int ab8500_charger_bind(struct device *dev) { struct ab8500_charger *di = dev_get_drvdata(dev); int ch_stat; int ret; /* Create a work queue for the charger */ di->charger_wq = alloc_ordered_workqueue("ab8500_charger_wq", WQ_MEM_RECLAIM); if (di->charger_wq == NULL) { dev_err(dev, "failed to create work queue\n"); return -ENOMEM; } ch_stat = ab8500_charger_detect_chargers(di, false); if (ch_stat & AC_PW_CONN) { if (is_ab8500(di->parent)) queue_delayed_work(di->charger_wq, &di->ac_charger_attached_work, HZ); } if (ch_stat & USB_PW_CONN) { if (is_ab8500(di->parent)) queue_delayed_work(di->charger_wq, &di->usb_charger_attached_work, HZ); di->vbus_detected = true; di->vbus_detected_start = true; queue_work(di->charger_wq, &di->detect_usb_type_work); } ret = component_bind_all(dev, di); if (ret) { dev_err(dev, "can't bind component devices\n"); destroy_workqueue(di->charger_wq); return ret; } return 0; } static void ab8500_charger_unbind(struct device *dev) { struct ab8500_charger *di = dev_get_drvdata(dev); int ret; /* Disable AC charging */ ab8500_charger_ac_en(&di->ac_chg, false, 0, 0); /* Disable USB charging */ ab8500_charger_usb_en(&di->usb_chg, false, 0, 0); /* Backup battery voltage and current disable */ ret = abx500_mask_and_set_register_interruptible(di->dev, AB8500_RTC, AB8500_RTC_CTRL_REG, RTC_BUP_CH_ENA, 0); if (ret < 0) dev_err(di->dev, "%s mask and set failed\n", __func__); /* Delete the work queue */ destroy_workqueue(di->charger_wq); /* Unbind fg, btemp, algorithm */ component_unbind_all(dev, di); } static const struct component_master_ops ab8500_charger_comp_ops = { .bind = ab8500_charger_bind, .unbind = ab8500_charger_unbind, }; static struct platform_driver *const ab8500_charger_component_drivers[] = { &ab8500_fg_driver, &ab8500_btemp_driver, &ab8500_chargalg_driver, }; static int ab8500_charger_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct device_node *np = dev->of_node; struct component_match *match = NULL; struct power_supply_config ac_psy_cfg = {}, usb_psy_cfg = {}; struct ab8500_charger *di; int charger_status; int i, irq; int ret; di = devm_kzalloc(dev, sizeof(*di), GFP_KERNEL); if (!di) return -ENOMEM; di->bm = &ab8500_bm_data; di->autopower_cfg = of_property_read_bool(np, "autopower_cfg"); /* get parent data */ di->dev = dev; di->parent = dev_get_drvdata(pdev->dev.parent); /* Get ADC channels */ if (!is_ab8505(di->parent)) { di->adc_main_charger_v = devm_iio_channel_get(dev, "main_charger_v"); if (IS_ERR(di->adc_main_charger_v)) { ret = dev_err_probe(dev, PTR_ERR(di->adc_main_charger_v), "failed to get ADC main charger voltage\n"); return ret; } di->adc_main_charger_c = devm_iio_channel_get(dev, "main_charger_c"); if (IS_ERR(di->adc_main_charger_c)) { ret = dev_err_probe(dev, PTR_ERR(di->adc_main_charger_c), "failed to get ADC main charger current\n"); return ret; } } di->adc_vbus_v = devm_iio_channel_get(dev, "vbus_v"); if (IS_ERR(di->adc_vbus_v)) { ret = dev_err_probe(dev, PTR_ERR(di->adc_vbus_v), "failed to get ADC USB charger voltage\n"); return ret; } di->adc_usb_charger_c = devm_iio_channel_get(dev, "usb_charger_c"); if (IS_ERR(di->adc_usb_charger_c)) { ret = dev_err_probe(dev, PTR_ERR(di->adc_usb_charger_c), "failed to get ADC USB charger current\n"); return ret; } /* * VDD ADC supply needs to be enabled from this driver when there * is a charger connected to avoid erroneous BTEMP_HIGH/LOW * interrupts during charging */ di->regu = devm_regulator_get(dev, "vddadc"); if (IS_ERR(di->regu)) { ret = PTR_ERR(di->regu); dev_err(dev, "failed to get vddadc regulator\n"); return ret; } /* Request interrupts */ for (i = 0; i < ARRAY_SIZE(ab8500_charger_irq); i++) { irq = platform_get_irq_byname(pdev, ab8500_charger_irq[i].name); if (irq < 0) return irq; ret = devm_request_threaded_irq(dev, irq, NULL, ab8500_charger_irq[i].isr, IRQF_SHARED | IRQF_NO_SUSPEND | IRQF_ONESHOT, ab8500_charger_irq[i].name, di); if (ret != 0) { dev_err(dev, "failed to request %s IRQ %d: %d\n" , ab8500_charger_irq[i].name, irq, ret); return ret; } dev_dbg(dev, "Requested %s IRQ %d: %d\n", ab8500_charger_irq[i].name, irq, ret); } /* initialize lock */ spin_lock_init(&di->usb_state.usb_lock); mutex_init(&di->usb_ipt_crnt_lock); di->autopower = false; di->invalid_charger_detect_state = 0; /* AC and USB supply config */ ac_psy_cfg.of_node = np; ac_psy_cfg.supplied_to = supply_interface; ac_psy_cfg.num_supplicants = ARRAY_SIZE(supply_interface); ac_psy_cfg.drv_data = &di->ac_chg; usb_psy_cfg.of_node = np; usb_psy_cfg.supplied_to = supply_interface; usb_psy_cfg.num_supplicants = ARRAY_SIZE(supply_interface); usb_psy_cfg.drv_data = &di->usb_chg; /* AC supply */ /* ux500_charger sub-class */ di->ac_chg.ops.enable = &ab8500_charger_ac_en; di->ac_chg.ops.check_enable = &ab8500_charger_ac_check_enable; di->ac_chg.ops.kick_wd = &ab8500_charger_watchdog_kick; di->ac_chg.ops.update_curr = &ab8500_charger_update_charger_current; di->ac_chg.max_out_volt_uv = ab8500_charger_voltage_map[ ARRAY_SIZE(ab8500_charger_voltage_map) - 1]; di->ac_chg.max_out_curr_ua = ab8500_charge_output_curr_map[ARRAY_SIZE(ab8500_charge_output_curr_map) - 1]; di->ac_chg.wdt_refresh = CHG_WD_INTERVAL; /* * The AB8505 only supports USB charging. If we are not the * AB8505, register an AC charger. * * TODO: if this should be opt-in, add DT properties for this. */ if (!is_ab8505(di->parent)) di->ac_chg.enabled = true; /* USB supply */ /* ux500_charger sub-class */ di->usb_chg.ops.enable = &ab8500_charger_usb_en; di->usb_chg.ops.check_enable = &ab8500_charger_usb_check_enable; di->usb_chg.ops.kick_wd = &ab8500_charger_watchdog_kick; di->usb_chg.ops.update_curr = &ab8500_charger_update_charger_current; di->usb_chg.max_out_volt_uv = ab8500_charger_voltage_map[ ARRAY_SIZE(ab8500_charger_voltage_map) - 1]; di->usb_chg.max_out_curr_ua = ab8500_charge_output_curr_map[ARRAY_SIZE(ab8500_charge_output_curr_map) - 1]; di->usb_chg.wdt_refresh = CHG_WD_INTERVAL; di->usb_state.usb_current_ua = -1; mutex_init(&di->charger_attached_mutex); /* Init work for HW failure check */ INIT_DEFERRABLE_WORK(&di->check_hw_failure_work, ab8500_charger_check_hw_failure_work); INIT_DEFERRABLE_WORK(&di->check_usbchgnotok_work, ab8500_charger_check_usbchargernotok_work); INIT_DELAYED_WORK(&di->ac_charger_attached_work, ab8500_charger_ac_attached_work); INIT_DELAYED_WORK(&di->usb_charger_attached_work, ab8500_charger_usb_attached_work); /* * For ABB revision 1.0 and 1.1 there is a bug in the watchdog * logic. That means we have to continuously kick the charger * watchdog even when no charger is connected. This is only * valid once the AC charger has been enabled. This is * a bug that is not handled by the algorithm and the * watchdog have to be kicked by the charger driver * when the AC charger is disabled */ INIT_DEFERRABLE_WORK(&di->kick_wd_work, ab8500_charger_kick_watchdog_work); INIT_DEFERRABLE_WORK(&di->check_vbat_work, ab8500_charger_check_vbat_work); INIT_DELAYED_WORK(&di->attach_work, ab8500_charger_usb_link_attach_work); INIT_DELAYED_WORK(&di->usb_state_changed_work, ab8500_charger_usb_state_changed_work); INIT_DELAYED_WORK(&di->vbus_drop_end_work, ab8500_charger_vbus_drop_end_work); /* Init work for charger detection */ INIT_WORK(&di->usb_link_status_work, ab8500_charger_usb_link_status_work); INIT_WORK(&di->ac_work, ab8500_charger_ac_work); INIT_WORK(&di->detect_usb_type_work, ab8500_charger_detect_usb_type_work); /* Init work for checking HW status */ INIT_WORK(&di->check_main_thermal_prot_work, ab8500_charger_check_main_thermal_prot_work); INIT_WORK(&di->check_usb_thermal_prot_work, ab8500_charger_check_usb_thermal_prot_work); /* Initialize OVV, and other registers */ ret = ab8500_charger_init_hw_registers(di); if (ret) { dev_err(dev, "failed to initialize ABB registers\n"); return ret; } /* Register AC charger class */ if (di->ac_chg.enabled) { di->ac_chg.psy = devm_power_supply_register(dev, &ab8500_ac_chg_desc, &ac_psy_cfg); if (IS_ERR(di->ac_chg.psy)) { dev_err(dev, "failed to register AC charger\n"); return PTR_ERR(di->ac_chg.psy); } } /* Register USB charger class */ di->usb_chg.psy = devm_power_supply_register(dev, &ab8500_usb_chg_desc, &usb_psy_cfg); if (IS_ERR(di->usb_chg.psy)) { dev_err(dev, "failed to register USB charger\n"); return PTR_ERR(di->usb_chg.psy); } /* * Check what battery we have, since we always have the USB * psy, use that as a handle. */ ret = ab8500_bm_of_probe(di->usb_chg.psy, di->bm); if (ret) return dev_err_probe(dev, ret, "failed to get battery information\n"); /* Identify the connected charger types during startup */ charger_status = ab8500_charger_detect_chargers(di, true); if (charger_status & AC_PW_CONN) { di->ac.charger_connected = 1; di->ac_conn = true; ab8500_power_supply_changed(di, di->ac_chg.psy); sysfs_notify(&di->ac_chg.psy->dev.kobj, NULL, "present"); } platform_set_drvdata(pdev, di); /* Create something that will match the subdrivers when we bind */ for (i = 0; i < ARRAY_SIZE(ab8500_charger_component_drivers); i++) { struct device_driver *drv = &ab8500_charger_component_drivers[i]->driver; struct device *p = NULL, *d; while ((d = platform_find_device_by_driver(p, drv))) { put_device(p); component_match_add(dev, &match, component_compare_dev, d); p = d; } put_device(p); } if (!match) { dev_err(dev, "no matching components\n"); ret = -ENODEV; goto remove_ab8500_bm; } if (IS_ERR(match)) { dev_err(dev, "could not create component match\n"); ret = PTR_ERR(match); goto remove_ab8500_bm; } di->usb_phy = usb_get_phy(USB_PHY_TYPE_USB2); if (IS_ERR_OR_NULL(di->usb_phy)) { dev_err(dev, "failed to get usb transceiver\n"); ret = -EINVAL; goto remove_ab8500_bm; } di->nb.notifier_call = ab8500_charger_usb_notifier_call; ret = usb_register_notifier(di->usb_phy, &di->nb); if (ret) { dev_err(dev, "failed to register usb notifier\n"); goto put_usb_phy; } ret = component_master_add_with_match(&pdev->dev, &ab8500_charger_comp_ops, match); if (ret) { dev_err(dev, "failed to add component master\n"); goto free_notifier; } return 0; free_notifier: usb_unregister_notifier(di->usb_phy, &di->nb); put_usb_phy: usb_put_phy(di->usb_phy); remove_ab8500_bm: ab8500_bm_of_remove(di->usb_chg.psy, di->bm); return ret; } static int ab8500_charger_remove(struct platform_device *pdev) { struct ab8500_charger *di = platform_get_drvdata(pdev); component_master_del(&pdev->dev, &ab8500_charger_comp_ops); usb_unregister_notifier(di->usb_phy, &di->nb); ab8500_bm_of_remove(di->usb_chg.psy, di->bm); usb_put_phy(di->usb_phy); return 0; } static SIMPLE_DEV_PM_OPS(ab8500_charger_pm_ops, ab8500_charger_suspend, ab8500_charger_resume); static const struct of_device_id ab8500_charger_match[] = { { .compatible = "stericsson,ab8500-charger", }, { }, }; MODULE_DEVICE_TABLE(of, ab8500_charger_match); static struct platform_driver ab8500_charger_driver = { .probe = ab8500_charger_probe, .remove = ab8500_charger_remove, .driver = { .name = "ab8500-charger", .of_match_table = ab8500_charger_match, .pm = &ab8500_charger_pm_ops, }, }; static int __init ab8500_charger_init(void) { int ret; ret = platform_register_drivers(ab8500_charger_component_drivers, ARRAY_SIZE(ab8500_charger_component_drivers)); if (ret) return ret; ret = platform_driver_register(&ab8500_charger_driver); if (ret) { platform_unregister_drivers(ab8500_charger_component_drivers, ARRAY_SIZE(ab8500_charger_component_drivers)); return ret; } return 0; } static void __exit ab8500_charger_exit(void) { platform_unregister_drivers(ab8500_charger_component_drivers, ARRAY_SIZE(ab8500_charger_component_drivers)); platform_driver_unregister(&ab8500_charger_driver); } module_init(ab8500_charger_init); module_exit(ab8500_charger_exit); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Johan Palsson, Karl Komierowski, Arun R Murthy"); MODULE_ALIAS("platform:ab8500-charger"); MODULE_DESCRIPTION("AB8500 charger management driver");
linux-master
drivers/power/supply/ab8500_charger.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2019-2020, The Linux Foundation. All rights reserved. * Copyright (c) 2022, Linaro Ltd */ #include <linux/auxiliary_bus.h> #include <linux/module.h> #include <linux/mutex.h> #include <linux/of_device.h> #include <linux/power_supply.h> #include <linux/soc/qcom/pdr.h> #include <linux/soc/qcom/pmic_glink.h> #include <linux/math.h> #include <linux/units.h> #define BATTMGR_CHEMISTRY_LEN 4 #define BATTMGR_STRING_LEN 128 enum qcom_battmgr_variant { QCOM_BATTMGR_SM8350, QCOM_BATTMGR_SC8280XP, }; #define BATTMGR_BAT_STATUS 0x1 #define BATTMGR_REQUEST_NOTIFICATION 0x4 #define BATTMGR_NOTIFICATION 0x7 #define NOTIF_BAT_PROPERTY 0x30 #define NOTIF_USB_PROPERTY 0x32 #define NOTIF_WLS_PROPERTY 0x34 #define NOTIF_BAT_INFO 0x81 #define NOTIF_BAT_STATUS 0x80 #define BATTMGR_BAT_INFO 0x9 #define BATTMGR_BAT_DISCHARGE_TIME 0xc #define BATTMGR_BAT_CHARGE_TIME 0xd #define BATTMGR_BAT_PROPERTY_GET 0x30 #define BATTMGR_BAT_PROPERTY_SET 0x31 #define BATT_STATUS 0 #define BATT_HEALTH 1 #define BATT_PRESENT 2 #define BATT_CHG_TYPE 3 #define BATT_CAPACITY 4 #define BATT_SOH 5 #define BATT_VOLT_OCV 6 #define BATT_VOLT_NOW 7 #define BATT_VOLT_MAX 8 #define BATT_CURR_NOW 9 #define BATT_CHG_CTRL_LIM 10 #define BATT_CHG_CTRL_LIM_MAX 11 #define BATT_TEMP 12 #define BATT_TECHNOLOGY 13 #define BATT_CHG_COUNTER 14 #define BATT_CYCLE_COUNT 15 #define BATT_CHG_FULL_DESIGN 16 #define BATT_CHG_FULL 17 #define BATT_MODEL_NAME 18 #define BATT_TTF_AVG 19 #define BATT_TTE_AVG 20 #define BATT_RESISTANCE 21 #define BATT_POWER_NOW 22 #define BATT_POWER_AVG 23 #define BATTMGR_USB_PROPERTY_GET 0x32 #define BATTMGR_USB_PROPERTY_SET 0x33 #define USB_ONLINE 0 #define USB_VOLT_NOW 1 #define USB_VOLT_MAX 2 #define USB_CURR_NOW 3 #define USB_CURR_MAX 4 #define USB_INPUT_CURR_LIMIT 5 #define USB_TYPE 6 #define USB_ADAP_TYPE 7 #define USB_MOISTURE_DET_EN 8 #define USB_MOISTURE_DET_STS 9 #define BATTMGR_WLS_PROPERTY_GET 0x34 #define BATTMGR_WLS_PROPERTY_SET 0x35 #define WLS_ONLINE 0 #define WLS_VOLT_NOW 1 #define WLS_VOLT_MAX 2 #define WLS_CURR_NOW 3 #define WLS_CURR_MAX 4 #define WLS_TYPE 5 #define WLS_BOOST_EN 6 struct qcom_battmgr_enable_request { struct pmic_glink_hdr hdr; __le32 battery_id; __le32 power_state; __le32 low_capacity; __le32 high_capacity; }; struct qcom_battmgr_property_request { struct pmic_glink_hdr hdr; __le32 battery; __le32 property; __le32 value; }; struct qcom_battmgr_update_request { struct pmic_glink_hdr hdr; u32 battery_id; }; struct qcom_battmgr_charge_time_request { struct pmic_glink_hdr hdr; __le32 battery_id; __le32 percent; __le32 reserved; }; struct qcom_battmgr_discharge_time_request { struct pmic_glink_hdr hdr; __le32 battery_id; __le32 rate; /* 0 for current rate */ __le32 reserved; }; struct qcom_battmgr_message { struct pmic_glink_hdr hdr; union { struct { __le32 property; __le32 value; __le32 result; } intval; struct { __le32 property; char model[BATTMGR_STRING_LEN]; } strval; struct { /* * 0: mWh * 1: mAh */ __le32 power_unit; __le32 design_capacity; __le32 last_full_capacity; /* * 0 nonrechargable * 1 rechargable */ __le32 battery_tech; __le32 design_voltage; /* mV */ __le32 capacity_low; __le32 capacity_warning; __le32 cycle_count; /* thousandth of persent */ __le32 accuracy; __le32 max_sample_time_ms; __le32 min_sample_time_ms; __le32 max_average_interval_ms; __le32 min_average_interval_ms; /* granularity between low and warning */ __le32 capacity_granularity1; /* granularity between warning and full */ __le32 capacity_granularity2; /* * 0: no * 1: cold * 2: hot */ __le32 swappable; __le32 capabilities; char model_number[BATTMGR_STRING_LEN]; char serial_number[BATTMGR_STRING_LEN]; char battery_type[BATTMGR_STRING_LEN]; char oem_info[BATTMGR_STRING_LEN]; char battery_chemistry[BATTMGR_CHEMISTRY_LEN]; char uid[BATTMGR_STRING_LEN]; __le32 critical_bias; u8 day; u8 month; __le16 year; __le32 battery_id; } info; struct { /* * BIT(0) discharging * BIT(1) charging * BIT(2) critical low */ __le32 battery_state; /* mWh or mAh, based on info->power_unit */ __le32 capacity; __le32 rate; /* mv */ __le32 battery_voltage; /* * BIT(0) power online * BIT(1) discharging * BIT(2) charging * BIT(3) battery critical */ __le32 power_state; /* * 1: AC * 2: USB * 3: Wireless */ __le32 charging_source; __le32 temperature; } status; __le32 time; __le32 notification; }; }; #define BATTMGR_CHARGING_SOURCE_AC 1 #define BATTMGR_CHARGING_SOURCE_USB 2 #define BATTMGR_CHARGING_SOURCE_WIRELESS 3 enum qcom_battmgr_unit { QCOM_BATTMGR_UNIT_mWh = 0, QCOM_BATTMGR_UNIT_mAh = 1 }; struct qcom_battmgr_info { bool valid; bool present; unsigned int charge_type; unsigned int design_capacity; unsigned int last_full_capacity; unsigned int voltage_max_design; unsigned int voltage_max; unsigned int capacity_low; unsigned int capacity_warning; unsigned int cycle_count; unsigned int charge_count; char model_number[BATTMGR_STRING_LEN]; char serial_number[BATTMGR_STRING_LEN]; char oem_info[BATTMGR_STRING_LEN]; unsigned char technology; unsigned char day; unsigned char month; unsigned short year; }; struct qcom_battmgr_status { unsigned int status; unsigned int health; unsigned int capacity; unsigned int percent; int current_now; int power_now; unsigned int voltage_now; unsigned int voltage_ocv; unsigned int temperature; unsigned int discharge_time; unsigned int charge_time; }; struct qcom_battmgr_ac { bool online; }; struct qcom_battmgr_usb { bool online; unsigned int voltage_now; unsigned int voltage_max; unsigned int current_now; unsigned int current_max; unsigned int current_limit; unsigned int usb_type; }; struct qcom_battmgr_wireless { bool online; unsigned int voltage_now; unsigned int voltage_max; unsigned int current_now; unsigned int current_max; }; struct qcom_battmgr { struct device *dev; struct pmic_glink_client *client; enum qcom_battmgr_variant variant; struct power_supply *ac_psy; struct power_supply *bat_psy; struct power_supply *usb_psy; struct power_supply *wls_psy; enum qcom_battmgr_unit unit; int error; struct completion ack; bool service_up; struct qcom_battmgr_info info; struct qcom_battmgr_status status; struct qcom_battmgr_ac ac; struct qcom_battmgr_usb usb; struct qcom_battmgr_wireless wireless; struct work_struct enable_work; /* * @lock is used to prevent concurrent power supply requests to the * firmware, as it then stops responding. */ struct mutex lock; }; static int qcom_battmgr_request(struct qcom_battmgr *battmgr, void *data, size_t len) { unsigned long left; int ret; reinit_completion(&battmgr->ack); battmgr->error = 0; ret = pmic_glink_send(battmgr->client, data, len); if (ret < 0) return ret; left = wait_for_completion_timeout(&battmgr->ack, HZ); if (!left) return -ETIMEDOUT; return battmgr->error; } static int qcom_battmgr_request_property(struct qcom_battmgr *battmgr, int opcode, int property, u32 value) { struct qcom_battmgr_property_request request = { .hdr.owner = cpu_to_le32(PMIC_GLINK_OWNER_BATTMGR), .hdr.type = cpu_to_le32(PMIC_GLINK_REQ_RESP), .hdr.opcode = cpu_to_le32(opcode), .battery = cpu_to_le32(0), .property = cpu_to_le32(property), .value = cpu_to_le32(value), }; return qcom_battmgr_request(battmgr, &request, sizeof(request)); } static int qcom_battmgr_update_status(struct qcom_battmgr *battmgr) { struct qcom_battmgr_update_request request = { .hdr.owner = cpu_to_le32(PMIC_GLINK_OWNER_BATTMGR), .hdr.type = cpu_to_le32(PMIC_GLINK_REQ_RESP), .hdr.opcode = cpu_to_le32(BATTMGR_BAT_STATUS), .battery_id = cpu_to_le32(0), }; return qcom_battmgr_request(battmgr, &request, sizeof(request)); } static int qcom_battmgr_update_info(struct qcom_battmgr *battmgr) { struct qcom_battmgr_update_request request = { .hdr.owner = cpu_to_le32(PMIC_GLINK_OWNER_BATTMGR), .hdr.type = cpu_to_le32(PMIC_GLINK_REQ_RESP), .hdr.opcode = cpu_to_le32(BATTMGR_BAT_INFO), .battery_id = cpu_to_le32(0), }; return qcom_battmgr_request(battmgr, &request, sizeof(request)); } static int qcom_battmgr_update_charge_time(struct qcom_battmgr *battmgr) { struct qcom_battmgr_charge_time_request request = { .hdr.owner = cpu_to_le32(PMIC_GLINK_OWNER_BATTMGR), .hdr.type = cpu_to_le32(PMIC_GLINK_REQ_RESP), .hdr.opcode = cpu_to_le32(BATTMGR_BAT_CHARGE_TIME), .battery_id = cpu_to_le32(0), .percent = cpu_to_le32(100), }; return qcom_battmgr_request(battmgr, &request, sizeof(request)); } static int qcom_battmgr_update_discharge_time(struct qcom_battmgr *battmgr) { struct qcom_battmgr_discharge_time_request request = { .hdr.owner = cpu_to_le32(PMIC_GLINK_OWNER_BATTMGR), .hdr.type = cpu_to_le32(PMIC_GLINK_REQ_RESP), .hdr.opcode = cpu_to_le32(BATTMGR_BAT_DISCHARGE_TIME), .battery_id = cpu_to_le32(0), .rate = cpu_to_le32(0), }; return qcom_battmgr_request(battmgr, &request, sizeof(request)); } static const u8 sm8350_bat_prop_map[] = { [POWER_SUPPLY_PROP_STATUS] = BATT_STATUS, [POWER_SUPPLY_PROP_HEALTH] = BATT_HEALTH, [POWER_SUPPLY_PROP_PRESENT] = BATT_PRESENT, [POWER_SUPPLY_PROP_CHARGE_TYPE] = BATT_CHG_TYPE, [POWER_SUPPLY_PROP_CAPACITY] = BATT_CAPACITY, [POWER_SUPPLY_PROP_VOLTAGE_OCV] = BATT_VOLT_OCV, [POWER_SUPPLY_PROP_VOLTAGE_NOW] = BATT_VOLT_NOW, [POWER_SUPPLY_PROP_VOLTAGE_MAX] = BATT_VOLT_MAX, [POWER_SUPPLY_PROP_CURRENT_NOW] = BATT_CURR_NOW, [POWER_SUPPLY_PROP_TEMP] = BATT_TEMP, [POWER_SUPPLY_PROP_TECHNOLOGY] = BATT_TECHNOLOGY, [POWER_SUPPLY_PROP_CHARGE_COUNTER] = BATT_CHG_COUNTER, [POWER_SUPPLY_PROP_CYCLE_COUNT] = BATT_CYCLE_COUNT, [POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN] = BATT_CHG_FULL_DESIGN, [POWER_SUPPLY_PROP_CHARGE_FULL] = BATT_CHG_FULL, [POWER_SUPPLY_PROP_MODEL_NAME] = BATT_MODEL_NAME, [POWER_SUPPLY_PROP_TIME_TO_FULL_AVG] = BATT_TTF_AVG, [POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG] = BATT_TTE_AVG, [POWER_SUPPLY_PROP_POWER_NOW] = BATT_POWER_NOW, }; static int qcom_battmgr_bat_sm8350_update(struct qcom_battmgr *battmgr, enum power_supply_property psp) { unsigned int prop; int ret; if (psp >= ARRAY_SIZE(sm8350_bat_prop_map)) return -EINVAL; prop = sm8350_bat_prop_map[psp]; mutex_lock(&battmgr->lock); ret = qcom_battmgr_request_property(battmgr, BATTMGR_BAT_PROPERTY_GET, prop, 0); mutex_unlock(&battmgr->lock); return ret; } static int qcom_battmgr_bat_sc8280xp_update(struct qcom_battmgr *battmgr, enum power_supply_property psp) { int ret; mutex_lock(&battmgr->lock); if (!battmgr->info.valid) { ret = qcom_battmgr_update_info(battmgr); if (ret < 0) goto out_unlock; battmgr->info.valid = true; } ret = qcom_battmgr_update_status(battmgr); if (ret < 0) goto out_unlock; if (psp == POWER_SUPPLY_PROP_TIME_TO_FULL_AVG) { ret = qcom_battmgr_update_charge_time(battmgr); if (ret < 0) { ret = -ENODATA; goto out_unlock; } } if (psp == POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG) { ret = qcom_battmgr_update_discharge_time(battmgr); if (ret < 0) { ret = -ENODATA; goto out_unlock; } } out_unlock: mutex_unlock(&battmgr->lock); return ret; } static int qcom_battmgr_bat_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct qcom_battmgr *battmgr = power_supply_get_drvdata(psy); enum qcom_battmgr_unit unit = battmgr->unit; int ret; if (!battmgr->service_up) return -ENODEV; if (battmgr->variant == QCOM_BATTMGR_SC8280XP) ret = qcom_battmgr_bat_sc8280xp_update(battmgr, psp); else ret = qcom_battmgr_bat_sm8350_update(battmgr, psp); if (ret < 0) return ret; switch (psp) { case POWER_SUPPLY_PROP_STATUS: val->intval = battmgr->status.status; break; case POWER_SUPPLY_PROP_CHARGE_TYPE: val->intval = battmgr->info.charge_type; break; case POWER_SUPPLY_PROP_HEALTH: val->intval = battmgr->status.health; break; case POWER_SUPPLY_PROP_PRESENT: val->intval = battmgr->info.present; break; case POWER_SUPPLY_PROP_TECHNOLOGY: val->intval = battmgr->info.technology; break; case POWER_SUPPLY_PROP_CYCLE_COUNT: val->intval = battmgr->info.cycle_count; break; case POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN: val->intval = battmgr->info.voltage_max_design; break; case POWER_SUPPLY_PROP_VOLTAGE_MAX: val->intval = battmgr->info.voltage_max; break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: val->intval = battmgr->status.voltage_now; break; case POWER_SUPPLY_PROP_VOLTAGE_OCV: val->intval = battmgr->status.voltage_ocv; break; case POWER_SUPPLY_PROP_CURRENT_NOW: val->intval = battmgr->status.current_now; break; case POWER_SUPPLY_PROP_POWER_NOW: val->intval = battmgr->status.power_now; break; case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN: if (unit != QCOM_BATTMGR_UNIT_mAh) return -ENODATA; val->intval = battmgr->info.design_capacity; break; case POWER_SUPPLY_PROP_CHARGE_FULL: if (unit != QCOM_BATTMGR_UNIT_mAh) return -ENODATA; val->intval = battmgr->info.last_full_capacity; break; case POWER_SUPPLY_PROP_CHARGE_EMPTY: if (unit != QCOM_BATTMGR_UNIT_mAh) return -ENODATA; val->intval = battmgr->info.capacity_low; break; case POWER_SUPPLY_PROP_CHARGE_NOW: if (unit != QCOM_BATTMGR_UNIT_mAh) return -ENODATA; val->intval = battmgr->status.capacity; break; case POWER_SUPPLY_PROP_CHARGE_COUNTER: val->intval = battmgr->info.charge_count; break; case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN: if (unit != QCOM_BATTMGR_UNIT_mWh) return -ENODATA; val->intval = battmgr->info.design_capacity; break; case POWER_SUPPLY_PROP_ENERGY_FULL: if (unit != QCOM_BATTMGR_UNIT_mWh) return -ENODATA; val->intval = battmgr->info.last_full_capacity; break; case POWER_SUPPLY_PROP_ENERGY_EMPTY: if (unit != QCOM_BATTMGR_UNIT_mWh) return -ENODATA; val->intval = battmgr->info.capacity_low; break; case POWER_SUPPLY_PROP_ENERGY_NOW: if (unit != QCOM_BATTMGR_UNIT_mWh) return -ENODATA; val->intval = battmgr->status.capacity; break; case POWER_SUPPLY_PROP_CAPACITY: val->intval = battmgr->status.percent; break; case POWER_SUPPLY_PROP_TEMP: val->intval = battmgr->status.temperature; break; case POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG: val->intval = battmgr->status.discharge_time; break; case POWER_SUPPLY_PROP_TIME_TO_FULL_AVG: val->intval = battmgr->status.charge_time; break; case POWER_SUPPLY_PROP_MANUFACTURE_YEAR: val->intval = battmgr->info.year; break; case POWER_SUPPLY_PROP_MANUFACTURE_MONTH: val->intval = battmgr->info.month; break; case POWER_SUPPLY_PROP_MANUFACTURE_DAY: val->intval = battmgr->info.day; break; case POWER_SUPPLY_PROP_MODEL_NAME: val->strval = battmgr->info.model_number; break; case POWER_SUPPLY_PROP_MANUFACTURER: val->strval = battmgr->info.oem_info; break; case POWER_SUPPLY_PROP_SERIAL_NUMBER: val->strval = battmgr->info.serial_number; break; default: return -EINVAL; } return 0; } static const enum power_supply_property sc8280xp_bat_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_TECHNOLOGY, POWER_SUPPLY_PROP_CYCLE_COUNT, POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_POWER_NOW, POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN, POWER_SUPPLY_PROP_CHARGE_FULL, POWER_SUPPLY_PROP_CHARGE_EMPTY, POWER_SUPPLY_PROP_CHARGE_NOW, POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN, POWER_SUPPLY_PROP_ENERGY_FULL, POWER_SUPPLY_PROP_ENERGY_EMPTY, POWER_SUPPLY_PROP_ENERGY_NOW, POWER_SUPPLY_PROP_TEMP, POWER_SUPPLY_PROP_MANUFACTURE_YEAR, POWER_SUPPLY_PROP_MANUFACTURE_MONTH, POWER_SUPPLY_PROP_MANUFACTURE_DAY, POWER_SUPPLY_PROP_MODEL_NAME, POWER_SUPPLY_PROP_MANUFACTURER, POWER_SUPPLY_PROP_SERIAL_NUMBER, }; static const struct power_supply_desc sc8280xp_bat_psy_desc = { .name = "qcom-battmgr-bat", .type = POWER_SUPPLY_TYPE_BATTERY, .properties = sc8280xp_bat_props, .num_properties = ARRAY_SIZE(sc8280xp_bat_props), .get_property = qcom_battmgr_bat_get_property, }; static const enum power_supply_property sm8350_bat_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_HEALTH, POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_CHARGE_TYPE, POWER_SUPPLY_PROP_CAPACITY, POWER_SUPPLY_PROP_VOLTAGE_OCV, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_VOLTAGE_MAX, POWER_SUPPLY_PROP_CURRENT_NOW, POWER_SUPPLY_PROP_TEMP, POWER_SUPPLY_PROP_TECHNOLOGY, POWER_SUPPLY_PROP_CHARGE_COUNTER, POWER_SUPPLY_PROP_CYCLE_COUNT, POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN, POWER_SUPPLY_PROP_CHARGE_FULL, POWER_SUPPLY_PROP_MODEL_NAME, POWER_SUPPLY_PROP_TIME_TO_FULL_AVG, POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG, POWER_SUPPLY_PROP_POWER_NOW, }; static const struct power_supply_desc sm8350_bat_psy_desc = { .name = "qcom-battmgr-bat", .type = POWER_SUPPLY_TYPE_BATTERY, .properties = sm8350_bat_props, .num_properties = ARRAY_SIZE(sm8350_bat_props), .get_property = qcom_battmgr_bat_get_property, }; static int qcom_battmgr_ac_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct qcom_battmgr *battmgr = power_supply_get_drvdata(psy); int ret; if (!battmgr->service_up) return -ENODEV; ret = qcom_battmgr_bat_sc8280xp_update(battmgr, psp); if (ret) return ret; switch (psp) { case POWER_SUPPLY_PROP_ONLINE: val->intval = battmgr->ac.online; break; default: return -EINVAL; } return 0; } static const enum power_supply_property sc8280xp_ac_props[] = { POWER_SUPPLY_PROP_ONLINE, }; static const struct power_supply_desc sc8280xp_ac_psy_desc = { .name = "qcom-battmgr-ac", .type = POWER_SUPPLY_TYPE_MAINS, .properties = sc8280xp_ac_props, .num_properties = ARRAY_SIZE(sc8280xp_ac_props), .get_property = qcom_battmgr_ac_get_property, }; static const u8 sm8350_usb_prop_map[] = { [POWER_SUPPLY_PROP_ONLINE] = USB_ONLINE, [POWER_SUPPLY_PROP_VOLTAGE_NOW] = USB_VOLT_NOW, [POWER_SUPPLY_PROP_VOLTAGE_MAX] = USB_VOLT_MAX, [POWER_SUPPLY_PROP_CURRENT_NOW] = USB_CURR_NOW, [POWER_SUPPLY_PROP_CURRENT_MAX] = USB_CURR_MAX, [POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT] = USB_INPUT_CURR_LIMIT, [POWER_SUPPLY_PROP_USB_TYPE] = USB_TYPE, }; static int qcom_battmgr_usb_sm8350_update(struct qcom_battmgr *battmgr, enum power_supply_property psp) { unsigned int prop; int ret; if (psp >= ARRAY_SIZE(sm8350_usb_prop_map)) return -EINVAL; prop = sm8350_usb_prop_map[psp]; mutex_lock(&battmgr->lock); ret = qcom_battmgr_request_property(battmgr, BATTMGR_USB_PROPERTY_GET, prop, 0); mutex_unlock(&battmgr->lock); return ret; } static int qcom_battmgr_usb_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct qcom_battmgr *battmgr = power_supply_get_drvdata(psy); int ret; if (!battmgr->service_up) return -ENODEV; if (battmgr->variant == QCOM_BATTMGR_SC8280XP) ret = qcom_battmgr_bat_sc8280xp_update(battmgr, psp); else ret = qcom_battmgr_usb_sm8350_update(battmgr, psp); if (ret) return ret; switch (psp) { case POWER_SUPPLY_PROP_ONLINE: val->intval = battmgr->usb.online; break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: val->intval = battmgr->usb.voltage_now; break; case POWER_SUPPLY_PROP_VOLTAGE_MAX: val->intval = battmgr->usb.voltage_max; break; case POWER_SUPPLY_PROP_CURRENT_NOW: val->intval = battmgr->usb.current_now; break; case POWER_SUPPLY_PROP_CURRENT_MAX: val->intval = battmgr->usb.current_max; break; case POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT: val->intval = battmgr->usb.current_limit; break; case POWER_SUPPLY_PROP_USB_TYPE: val->intval = battmgr->usb.usb_type; break; default: return -EINVAL; } return 0; } static const enum power_supply_usb_type usb_psy_supported_types[] = { POWER_SUPPLY_USB_TYPE_UNKNOWN, POWER_SUPPLY_USB_TYPE_SDP, POWER_SUPPLY_USB_TYPE_DCP, POWER_SUPPLY_USB_TYPE_CDP, POWER_SUPPLY_USB_TYPE_ACA, POWER_SUPPLY_USB_TYPE_C, POWER_SUPPLY_USB_TYPE_PD, POWER_SUPPLY_USB_TYPE_PD_DRP, POWER_SUPPLY_USB_TYPE_PD_PPS, POWER_SUPPLY_USB_TYPE_APPLE_BRICK_ID, }; static const enum power_supply_property sc8280xp_usb_props[] = { POWER_SUPPLY_PROP_ONLINE, }; static const struct power_supply_desc sc8280xp_usb_psy_desc = { .name = "qcom-battmgr-usb", .type = POWER_SUPPLY_TYPE_USB, .properties = sc8280xp_usb_props, .num_properties = ARRAY_SIZE(sc8280xp_usb_props), .get_property = qcom_battmgr_usb_get_property, .usb_types = usb_psy_supported_types, .num_usb_types = ARRAY_SIZE(usb_psy_supported_types), }; static const enum power_supply_property sm8350_usb_props[] = { POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_VOLTAGE_MAX, POWER_SUPPLY_PROP_CURRENT_NOW, POWER_SUPPLY_PROP_CURRENT_MAX, POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT, POWER_SUPPLY_PROP_USB_TYPE, }; static const struct power_supply_desc sm8350_usb_psy_desc = { .name = "qcom-battmgr-usb", .type = POWER_SUPPLY_TYPE_USB, .properties = sm8350_usb_props, .num_properties = ARRAY_SIZE(sm8350_usb_props), .get_property = qcom_battmgr_usb_get_property, .usb_types = usb_psy_supported_types, .num_usb_types = ARRAY_SIZE(usb_psy_supported_types), }; static const u8 sm8350_wls_prop_map[] = { [POWER_SUPPLY_PROP_ONLINE] = WLS_ONLINE, [POWER_SUPPLY_PROP_VOLTAGE_NOW] = WLS_VOLT_NOW, [POWER_SUPPLY_PROP_VOLTAGE_MAX] = WLS_VOLT_MAX, [POWER_SUPPLY_PROP_CURRENT_NOW] = WLS_CURR_NOW, [POWER_SUPPLY_PROP_CURRENT_MAX] = WLS_CURR_MAX, }; static int qcom_battmgr_wls_sm8350_update(struct qcom_battmgr *battmgr, enum power_supply_property psp) { unsigned int prop; int ret; if (psp >= ARRAY_SIZE(sm8350_wls_prop_map)) return -EINVAL; prop = sm8350_wls_prop_map[psp]; mutex_lock(&battmgr->lock); ret = qcom_battmgr_request_property(battmgr, BATTMGR_WLS_PROPERTY_GET, prop, 0); mutex_unlock(&battmgr->lock); return ret; } static int qcom_battmgr_wls_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct qcom_battmgr *battmgr = power_supply_get_drvdata(psy); int ret; if (!battmgr->service_up) return -ENODEV; if (battmgr->variant == QCOM_BATTMGR_SC8280XP) ret = qcom_battmgr_bat_sc8280xp_update(battmgr, psp); else ret = qcom_battmgr_wls_sm8350_update(battmgr, psp); if (ret < 0) return ret; switch (psp) { case POWER_SUPPLY_PROP_ONLINE: val->intval = battmgr->wireless.online; break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: val->intval = battmgr->wireless.voltage_now; break; case POWER_SUPPLY_PROP_VOLTAGE_MAX: val->intval = battmgr->wireless.voltage_max; break; case POWER_SUPPLY_PROP_CURRENT_NOW: val->intval = battmgr->wireless.current_now; break; case POWER_SUPPLY_PROP_CURRENT_MAX: val->intval = battmgr->wireless.current_max; break; default: return -EINVAL; } return 0; } static const enum power_supply_property sc8280xp_wls_props[] = { POWER_SUPPLY_PROP_ONLINE, }; static const struct power_supply_desc sc8280xp_wls_psy_desc = { .name = "qcom-battmgr-wls", .type = POWER_SUPPLY_TYPE_WIRELESS, .properties = sc8280xp_wls_props, .num_properties = ARRAY_SIZE(sc8280xp_wls_props), .get_property = qcom_battmgr_wls_get_property, }; static const enum power_supply_property sm8350_wls_props[] = { POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_VOLTAGE_MAX, POWER_SUPPLY_PROP_CURRENT_NOW, POWER_SUPPLY_PROP_CURRENT_MAX, }; static const struct power_supply_desc sm8350_wls_psy_desc = { .name = "qcom-battmgr-wls", .type = POWER_SUPPLY_TYPE_WIRELESS, .properties = sm8350_wls_props, .num_properties = ARRAY_SIZE(sm8350_wls_props), .get_property = qcom_battmgr_wls_get_property, }; static void qcom_battmgr_notification(struct qcom_battmgr *battmgr, const struct qcom_battmgr_message *msg, int len) { size_t payload_len = len - sizeof(struct pmic_glink_hdr); unsigned int notification; if (payload_len != sizeof(msg->notification)) { dev_warn(battmgr->dev, "ignoring notification with invalid length\n"); return; } notification = le32_to_cpu(msg->notification); switch (notification) { case NOTIF_BAT_INFO: battmgr->info.valid = false; fallthrough; case NOTIF_BAT_STATUS: case NOTIF_BAT_PROPERTY: power_supply_changed(battmgr->bat_psy); break; case NOTIF_USB_PROPERTY: power_supply_changed(battmgr->usb_psy); break; case NOTIF_WLS_PROPERTY: power_supply_changed(battmgr->wls_psy); break; default: dev_err(battmgr->dev, "unknown notification: %#x\n", notification); break; } } static void qcom_battmgr_sc8280xp_strcpy(char *dest, const char *src) { size_t len = src[0]; /* Some firmware versions return Pascal-style strings */ if (len < BATTMGR_STRING_LEN && len == strnlen(src + 1, BATTMGR_STRING_LEN - 1)) { memcpy(dest, src + 1, len); dest[len] = '\0'; } else { memcpy(dest, src, BATTMGR_STRING_LEN); } } static unsigned int qcom_battmgr_sc8280xp_parse_technology(const char *chemistry) { if (!strncmp(chemistry, "LIO", BATTMGR_CHEMISTRY_LEN)) return POWER_SUPPLY_TECHNOLOGY_LION; pr_err("Unknown battery technology '%s'\n", chemistry); return POWER_SUPPLY_TECHNOLOGY_UNKNOWN; } static unsigned int qcom_battmgr_sc8280xp_convert_temp(unsigned int temperature) { return DIV_ROUND_CLOSEST(temperature, 10); } static void qcom_battmgr_sc8280xp_callback(struct qcom_battmgr *battmgr, const struct qcom_battmgr_message *resp, size_t len) { unsigned int opcode = le32_to_cpu(resp->hdr.opcode); unsigned int source; unsigned int state; size_t payload_len = len - sizeof(struct pmic_glink_hdr); if (payload_len < sizeof(__le32)) { dev_warn(battmgr->dev, "invalid payload length for %#x: %zd\n", opcode, len); return; } switch (opcode) { case BATTMGR_REQUEST_NOTIFICATION: battmgr->error = 0; break; case BATTMGR_BAT_INFO: if (payload_len != sizeof(resp->info)) { dev_warn(battmgr->dev, "invalid payload length for battery information request: %zd\n", payload_len); battmgr->error = -ENODATA; return; } battmgr->unit = le32_to_cpu(resp->info.power_unit); battmgr->info.present = true; battmgr->info.design_capacity = le32_to_cpu(resp->info.design_capacity) * 1000; battmgr->info.last_full_capacity = le32_to_cpu(resp->info.last_full_capacity) * 1000; battmgr->info.voltage_max_design = le32_to_cpu(resp->info.design_voltage) * 1000; battmgr->info.capacity_low = le32_to_cpu(resp->info.capacity_low) * 1000; battmgr->info.cycle_count = le32_to_cpu(resp->info.cycle_count); qcom_battmgr_sc8280xp_strcpy(battmgr->info.model_number, resp->info.model_number); qcom_battmgr_sc8280xp_strcpy(battmgr->info.serial_number, resp->info.serial_number); battmgr->info.technology = qcom_battmgr_sc8280xp_parse_technology(resp->info.battery_chemistry); qcom_battmgr_sc8280xp_strcpy(battmgr->info.oem_info, resp->info.oem_info); battmgr->info.day = resp->info.day; battmgr->info.month = resp->info.month; battmgr->info.year = le16_to_cpu(resp->info.year); break; case BATTMGR_BAT_STATUS: if (payload_len != sizeof(resp->status)) { dev_warn(battmgr->dev, "invalid payload length for battery status request: %zd\n", payload_len); battmgr->error = -ENODATA; return; } state = le32_to_cpu(resp->status.battery_state); if (state & BIT(0)) battmgr->status.status = POWER_SUPPLY_STATUS_DISCHARGING; else if (state & BIT(1)) battmgr->status.status = POWER_SUPPLY_STATUS_CHARGING; else battmgr->status.status = POWER_SUPPLY_STATUS_NOT_CHARGING; battmgr->status.capacity = le32_to_cpu(resp->status.capacity) * 1000; battmgr->status.power_now = le32_to_cpu(resp->status.rate) * 1000; battmgr->status.voltage_now = le32_to_cpu(resp->status.battery_voltage) * 1000; battmgr->status.temperature = qcom_battmgr_sc8280xp_convert_temp(le32_to_cpu(resp->status.temperature)); source = le32_to_cpu(resp->status.charging_source); battmgr->ac.online = source == BATTMGR_CHARGING_SOURCE_AC; battmgr->usb.online = source == BATTMGR_CHARGING_SOURCE_USB; battmgr->wireless.online = source == BATTMGR_CHARGING_SOURCE_WIRELESS; break; case BATTMGR_BAT_DISCHARGE_TIME: battmgr->status.discharge_time = le32_to_cpu(resp->time); break; case BATTMGR_BAT_CHARGE_TIME: battmgr->status.charge_time = le32_to_cpu(resp->time); break; default: dev_warn(battmgr->dev, "unknown message %#x\n", opcode); break; } complete(&battmgr->ack); } static void qcom_battmgr_sm8350_callback(struct qcom_battmgr *battmgr, const struct qcom_battmgr_message *resp, size_t len) { unsigned int property; unsigned int opcode = le32_to_cpu(resp->hdr.opcode); size_t payload_len = len - sizeof(struct pmic_glink_hdr); unsigned int val; if (payload_len < sizeof(__le32)) { dev_warn(battmgr->dev, "invalid payload length for %#x: %zd\n", opcode, len); return; } switch (opcode) { case BATTMGR_BAT_PROPERTY_GET: property = le32_to_cpu(resp->intval.property); if (property == BATT_MODEL_NAME) { if (payload_len != sizeof(resp->strval)) { dev_warn(battmgr->dev, "invalid payload length for BATT_MODEL_NAME request: %zd\n", payload_len); battmgr->error = -ENODATA; return; } } else { if (payload_len != sizeof(resp->intval)) { dev_warn(battmgr->dev, "invalid payload length for %#x request: %zd\n", property, payload_len); battmgr->error = -ENODATA; return; } battmgr->error = le32_to_cpu(resp->intval.result); if (battmgr->error) goto out_complete; } switch (property) { case BATT_STATUS: battmgr->status.status = le32_to_cpu(resp->intval.value); break; case BATT_HEALTH: battmgr->status.health = le32_to_cpu(resp->intval.value); break; case BATT_PRESENT: battmgr->info.present = le32_to_cpu(resp->intval.value); break; case BATT_CHG_TYPE: battmgr->info.charge_type = le32_to_cpu(resp->intval.value); break; case BATT_CAPACITY: battmgr->status.percent = le32_to_cpu(resp->intval.value) / 100; break; case BATT_VOLT_OCV: battmgr->status.voltage_ocv = le32_to_cpu(resp->intval.value); break; case BATT_VOLT_NOW: battmgr->status.voltage_now = le32_to_cpu(resp->intval.value); break; case BATT_VOLT_MAX: battmgr->info.voltage_max = le32_to_cpu(resp->intval.value); break; case BATT_CURR_NOW: battmgr->status.current_now = le32_to_cpu(resp->intval.value); break; case BATT_TEMP: val = le32_to_cpu(resp->intval.value); battmgr->status.temperature = DIV_ROUND_CLOSEST(val, 10); break; case BATT_TECHNOLOGY: battmgr->info.technology = le32_to_cpu(resp->intval.value); break; case BATT_CHG_COUNTER: battmgr->info.charge_count = le32_to_cpu(resp->intval.value); break; case BATT_CYCLE_COUNT: battmgr->info.cycle_count = le32_to_cpu(resp->intval.value); break; case BATT_CHG_FULL_DESIGN: battmgr->info.design_capacity = le32_to_cpu(resp->intval.value); break; case BATT_CHG_FULL: battmgr->info.last_full_capacity = le32_to_cpu(resp->intval.value); break; case BATT_MODEL_NAME: strscpy(battmgr->info.model_number, resp->strval.model, BATTMGR_STRING_LEN); break; case BATT_TTF_AVG: battmgr->status.charge_time = le32_to_cpu(resp->intval.value); break; case BATT_TTE_AVG: battmgr->status.discharge_time = le32_to_cpu(resp->intval.value); break; case BATT_POWER_NOW: battmgr->status.power_now = le32_to_cpu(resp->intval.value); break; default: dev_warn(battmgr->dev, "unknown property %#x\n", property); break; } break; case BATTMGR_USB_PROPERTY_GET: property = le32_to_cpu(resp->intval.property); if (payload_len != sizeof(resp->intval)) { dev_warn(battmgr->dev, "invalid payload length for %#x request: %zd\n", property, payload_len); battmgr->error = -ENODATA; return; } battmgr->error = le32_to_cpu(resp->intval.result); if (battmgr->error) goto out_complete; switch (property) { case USB_ONLINE: battmgr->usb.online = le32_to_cpu(resp->intval.value); break; case USB_VOLT_NOW: battmgr->usb.voltage_now = le32_to_cpu(resp->intval.value); break; case USB_VOLT_MAX: battmgr->usb.voltage_max = le32_to_cpu(resp->intval.value); break; case USB_CURR_NOW: battmgr->usb.current_now = le32_to_cpu(resp->intval.value); break; case USB_CURR_MAX: battmgr->usb.current_max = le32_to_cpu(resp->intval.value); break; case USB_INPUT_CURR_LIMIT: battmgr->usb.current_limit = le32_to_cpu(resp->intval.value); break; case USB_TYPE: battmgr->usb.usb_type = le32_to_cpu(resp->intval.value); break; default: dev_warn(battmgr->dev, "unknown property %#x\n", property); break; } break; case BATTMGR_WLS_PROPERTY_GET: property = le32_to_cpu(resp->intval.property); if (payload_len != sizeof(resp->intval)) { dev_warn(battmgr->dev, "invalid payload length for %#x request: %zd\n", property, payload_len); battmgr->error = -ENODATA; return; } battmgr->error = le32_to_cpu(resp->intval.result); if (battmgr->error) goto out_complete; switch (property) { case WLS_ONLINE: battmgr->wireless.online = le32_to_cpu(resp->intval.value); break; case WLS_VOLT_NOW: battmgr->wireless.voltage_now = le32_to_cpu(resp->intval.value); break; case WLS_VOLT_MAX: battmgr->wireless.voltage_max = le32_to_cpu(resp->intval.value); break; case WLS_CURR_NOW: battmgr->wireless.current_now = le32_to_cpu(resp->intval.value); break; case WLS_CURR_MAX: battmgr->wireless.current_max = le32_to_cpu(resp->intval.value); break; default: dev_warn(battmgr->dev, "unknown property %#x\n", property); break; } break; case BATTMGR_REQUEST_NOTIFICATION: battmgr->error = 0; break; default: dev_warn(battmgr->dev, "unknown message %#x\n", opcode); break; } out_complete: complete(&battmgr->ack); } static void qcom_battmgr_callback(const void *data, size_t len, void *priv) { const struct pmic_glink_hdr *hdr = data; struct qcom_battmgr *battmgr = priv; unsigned int opcode = le32_to_cpu(hdr->opcode); if (opcode == BATTMGR_NOTIFICATION) qcom_battmgr_notification(battmgr, data, len); else if (battmgr->variant == QCOM_BATTMGR_SC8280XP) qcom_battmgr_sc8280xp_callback(battmgr, data, len); else qcom_battmgr_sm8350_callback(battmgr, data, len); } static void qcom_battmgr_enable_worker(struct work_struct *work) { struct qcom_battmgr *battmgr = container_of(work, struct qcom_battmgr, enable_work); struct qcom_battmgr_enable_request req = { .hdr.owner = PMIC_GLINK_OWNER_BATTMGR, .hdr.type = PMIC_GLINK_NOTIFY, .hdr.opcode = BATTMGR_REQUEST_NOTIFICATION, }; int ret; ret = qcom_battmgr_request(battmgr, &req, sizeof(req)); if (ret) dev_err(battmgr->dev, "failed to request power notifications\n"); } static void qcom_battmgr_pdr_notify(void *priv, int state) { struct qcom_battmgr *battmgr = priv; if (state == SERVREG_SERVICE_STATE_UP) { battmgr->service_up = true; schedule_work(&battmgr->enable_work); } else { battmgr->service_up = false; } } static const struct of_device_id qcom_battmgr_of_variants[] = { { .compatible = "qcom,sc8180x-pmic-glink", .data = (void *)QCOM_BATTMGR_SC8280XP }, { .compatible = "qcom,sc8280xp-pmic-glink", .data = (void *)QCOM_BATTMGR_SC8280XP }, /* Unmatched devices falls back to QCOM_BATTMGR_SM8350 */ {} }; static char *qcom_battmgr_battery[] = { "battery" }; static int qcom_battmgr_probe(struct auxiliary_device *adev, const struct auxiliary_device_id *id) { struct power_supply_config psy_cfg_supply = {}; struct power_supply_config psy_cfg = {}; const struct of_device_id *match; struct qcom_battmgr *battmgr; struct device *dev = &adev->dev; battmgr = devm_kzalloc(dev, sizeof(*battmgr), GFP_KERNEL); if (!battmgr) return -ENOMEM; battmgr->dev = dev; psy_cfg.drv_data = battmgr; psy_cfg.of_node = adev->dev.of_node; psy_cfg_supply.drv_data = battmgr; psy_cfg_supply.of_node = adev->dev.of_node; psy_cfg_supply.supplied_to = qcom_battmgr_battery; psy_cfg_supply.num_supplicants = 1; INIT_WORK(&battmgr->enable_work, qcom_battmgr_enable_worker); mutex_init(&battmgr->lock); init_completion(&battmgr->ack); match = of_match_device(qcom_battmgr_of_variants, dev->parent); if (match) battmgr->variant = (unsigned long)match->data; else battmgr->variant = QCOM_BATTMGR_SM8350; if (battmgr->variant == QCOM_BATTMGR_SC8280XP) { battmgr->bat_psy = devm_power_supply_register(dev, &sc8280xp_bat_psy_desc, &psy_cfg); if (IS_ERR(battmgr->bat_psy)) return dev_err_probe(dev, PTR_ERR(battmgr->bat_psy), "failed to register battery power supply\n"); battmgr->ac_psy = devm_power_supply_register(dev, &sc8280xp_ac_psy_desc, &psy_cfg_supply); if (IS_ERR(battmgr->ac_psy)) return dev_err_probe(dev, PTR_ERR(battmgr->ac_psy), "failed to register AC power supply\n"); battmgr->usb_psy = devm_power_supply_register(dev, &sc8280xp_usb_psy_desc, &psy_cfg_supply); if (IS_ERR(battmgr->usb_psy)) return dev_err_probe(dev, PTR_ERR(battmgr->usb_psy), "failed to register USB power supply\n"); battmgr->wls_psy = devm_power_supply_register(dev, &sc8280xp_wls_psy_desc, &psy_cfg_supply); if (IS_ERR(battmgr->wls_psy)) return dev_err_probe(dev, PTR_ERR(battmgr->wls_psy), "failed to register wireless charing power supply\n"); } else { battmgr->bat_psy = devm_power_supply_register(dev, &sm8350_bat_psy_desc, &psy_cfg); if (IS_ERR(battmgr->bat_psy)) return dev_err_probe(dev, PTR_ERR(battmgr->bat_psy), "failed to register battery power supply\n"); battmgr->usb_psy = devm_power_supply_register(dev, &sm8350_usb_psy_desc, &psy_cfg_supply); if (IS_ERR(battmgr->usb_psy)) return dev_err_probe(dev, PTR_ERR(battmgr->usb_psy), "failed to register USB power supply\n"); battmgr->wls_psy = devm_power_supply_register(dev, &sm8350_wls_psy_desc, &psy_cfg_supply); if (IS_ERR(battmgr->wls_psy)) return dev_err_probe(dev, PTR_ERR(battmgr->wls_psy), "failed to register wireless charing power supply\n"); } battmgr->client = devm_pmic_glink_register_client(dev, PMIC_GLINK_OWNER_BATTMGR, qcom_battmgr_callback, qcom_battmgr_pdr_notify, battmgr); return PTR_ERR_OR_ZERO(battmgr->client); } static const struct auxiliary_device_id qcom_battmgr_id_table[] = { { .name = "pmic_glink.power-supply", }, {}, }; MODULE_DEVICE_TABLE(auxiliary, qcom_battmgr_id_table); static struct auxiliary_driver qcom_battmgr_driver = { .name = "pmic_glink_power_supply", .probe = qcom_battmgr_probe, .id_table = qcom_battmgr_id_table, }; module_auxiliary_driver(qcom_battmgr_driver); MODULE_DESCRIPTION("Qualcomm PMIC GLINK battery manager driver"); MODULE_LICENSE("GPL");
linux-master
drivers/power/supply/qcom_battmgr.c
/* * Battery charger driver for TI BQ24735 * * Copyright (c) 2013, NVIDIA CORPORATION. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <linux/devm-helpers.h> #include <linux/err.h> #include <linux/i2c.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/of.h> #include <linux/gpio/consumer.h> #include <linux/power_supply.h> #include <linux/slab.h> #include <linux/power/bq24735-charger.h> /* BQ24735 available commands and their respective masks */ #define BQ24735_CHARGE_OPT 0x12 #define BQ24735_CHARGE_CURRENT 0x14 #define BQ24735_CHARGE_CURRENT_MASK 0x1fc0 #define BQ24735_CHARGE_VOLTAGE 0x15 #define BQ24735_CHARGE_VOLTAGE_MASK 0x7ff0 #define BQ24735_INPUT_CURRENT 0x3f #define BQ24735_INPUT_CURRENT_MASK 0x1f80 #define BQ24735_MANUFACTURER_ID 0xfe #define BQ24735_DEVICE_ID 0xff /* ChargeOptions bits of interest */ #define BQ24735_CHARGE_OPT_CHG_DISABLE (1 << 0) #define BQ24735_CHARGE_OPT_AC_PRESENT (1 << 4) struct bq24735 { struct power_supply *charger; struct power_supply_desc charger_desc; struct i2c_client *client; struct bq24735_platform *pdata; struct mutex lock; struct gpio_desc *status_gpio; struct delayed_work poll; u32 poll_interval; bool charging; }; static inline struct bq24735 *to_bq24735(struct power_supply *psy) { return power_supply_get_drvdata(psy); } static enum power_supply_property bq24735_charger_properties[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_ONLINE, }; static int bq24735_charger_property_is_writeable(struct power_supply *psy, enum power_supply_property psp) { switch (psp) { case POWER_SUPPLY_PROP_STATUS: return 1; default: break; } return 0; } static inline int bq24735_write_word(struct i2c_client *client, u8 reg, u16 value) { return i2c_smbus_write_word_data(client, reg, value); } static inline int bq24735_read_word(struct i2c_client *client, u8 reg) { return i2c_smbus_read_word_data(client, reg); } static int bq24735_update_word(struct i2c_client *client, u8 reg, u16 mask, u16 value) { unsigned int tmp; int ret; ret = bq24735_read_word(client, reg); if (ret < 0) return ret; tmp = ret & ~mask; tmp |= value & mask; return bq24735_write_word(client, reg, tmp); } static int bq24735_config_charger(struct bq24735 *charger) { struct bq24735_platform *pdata = charger->pdata; int ret; u16 value; if (pdata->ext_control) return 0; if (pdata->charge_current) { value = pdata->charge_current & BQ24735_CHARGE_CURRENT_MASK; ret = bq24735_write_word(charger->client, BQ24735_CHARGE_CURRENT, value); if (ret < 0) { dev_err(&charger->client->dev, "Failed to write charger current : %d\n", ret); return ret; } } if (pdata->charge_voltage) { value = pdata->charge_voltage & BQ24735_CHARGE_VOLTAGE_MASK; ret = bq24735_write_word(charger->client, BQ24735_CHARGE_VOLTAGE, value); if (ret < 0) { dev_err(&charger->client->dev, "Failed to write charger voltage : %d\n", ret); return ret; } } if (pdata->input_current) { value = pdata->input_current & BQ24735_INPUT_CURRENT_MASK; ret = bq24735_write_word(charger->client, BQ24735_INPUT_CURRENT, value); if (ret < 0) { dev_err(&charger->client->dev, "Failed to write input current : %d\n", ret); return ret; } } return 0; } static inline int bq24735_enable_charging(struct bq24735 *charger) { int ret; if (charger->pdata->ext_control) return 0; ret = bq24735_config_charger(charger); if (ret) return ret; return bq24735_update_word(charger->client, BQ24735_CHARGE_OPT, BQ24735_CHARGE_OPT_CHG_DISABLE, 0); } static inline int bq24735_disable_charging(struct bq24735 *charger) { if (charger->pdata->ext_control) return 0; return bq24735_update_word(charger->client, BQ24735_CHARGE_OPT, BQ24735_CHARGE_OPT_CHG_DISABLE, BQ24735_CHARGE_OPT_CHG_DISABLE); } static bool bq24735_charger_is_present(struct bq24735 *charger) { if (charger->status_gpio) { return !gpiod_get_value_cansleep(charger->status_gpio); } else { int ac = 0; ac = bq24735_read_word(charger->client, BQ24735_CHARGE_OPT); if (ac < 0) { dev_dbg(&charger->client->dev, "Failed to read charger options : %d\n", ac); return false; } return (ac & BQ24735_CHARGE_OPT_AC_PRESENT) ? true : false; } return false; } static int bq24735_charger_is_charging(struct bq24735 *charger) { int ret; if (!bq24735_charger_is_present(charger)) return 0; ret = bq24735_read_word(charger->client, BQ24735_CHARGE_OPT); if (ret < 0) return ret; return !(ret & BQ24735_CHARGE_OPT_CHG_DISABLE); } static void bq24735_update(struct bq24735 *charger) { mutex_lock(&charger->lock); if (charger->charging && bq24735_charger_is_present(charger)) bq24735_enable_charging(charger); else bq24735_disable_charging(charger); mutex_unlock(&charger->lock); power_supply_changed(charger->charger); } static irqreturn_t bq24735_charger_isr(int irq, void *devid) { struct power_supply *psy = devid; struct bq24735 *charger = to_bq24735(psy); bq24735_update(charger); return IRQ_HANDLED; } static void bq24735_poll(struct work_struct *work) { struct bq24735 *charger = container_of(work, struct bq24735, poll.work); bq24735_update(charger); schedule_delayed_work(&charger->poll, msecs_to_jiffies(charger->poll_interval)); } static int bq24735_charger_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct bq24735 *charger = to_bq24735(psy); switch (psp) { case POWER_SUPPLY_PROP_ONLINE: val->intval = bq24735_charger_is_present(charger) ? 1 : 0; break; case POWER_SUPPLY_PROP_STATUS: switch (bq24735_charger_is_charging(charger)) { case 1: val->intval = POWER_SUPPLY_STATUS_CHARGING; break; case 0: val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING; break; default: val->intval = POWER_SUPPLY_STATUS_UNKNOWN; break; } break; default: return -EINVAL; } return 0; } static int bq24735_charger_set_property(struct power_supply *psy, enum power_supply_property psp, const union power_supply_propval *val) { struct bq24735 *charger = to_bq24735(psy); int ret; switch (psp) { case POWER_SUPPLY_PROP_STATUS: switch (val->intval) { case POWER_SUPPLY_STATUS_CHARGING: mutex_lock(&charger->lock); charger->charging = true; ret = bq24735_enable_charging(charger); mutex_unlock(&charger->lock); if (ret) return ret; break; case POWER_SUPPLY_STATUS_DISCHARGING: case POWER_SUPPLY_STATUS_NOT_CHARGING: mutex_lock(&charger->lock); charger->charging = false; ret = bq24735_disable_charging(charger); mutex_unlock(&charger->lock); if (ret) return ret; break; default: return -EINVAL; } power_supply_changed(psy); break; default: return -EPERM; } return 0; } static struct bq24735_platform *bq24735_parse_dt_data(struct i2c_client *client) { struct bq24735_platform *pdata; struct device_node *np = client->dev.of_node; u32 val; int ret; pdata = devm_kzalloc(&client->dev, sizeof(*pdata), GFP_KERNEL); if (!pdata) { dev_err(&client->dev, "Memory alloc for bq24735 pdata failed\n"); return NULL; } ret = of_property_read_u32(np, "ti,charge-current", &val); if (!ret) pdata->charge_current = val; ret = of_property_read_u32(np, "ti,charge-voltage", &val); if (!ret) pdata->charge_voltage = val; ret = of_property_read_u32(np, "ti,input-current", &val); if (!ret) pdata->input_current = val; pdata->ext_control = of_property_read_bool(np, "ti,external-control"); return pdata; } static int bq24735_charger_probe(struct i2c_client *client) { int ret; struct bq24735 *charger; struct power_supply_desc *supply_desc; struct power_supply_config psy_cfg = {}; char *name; charger = devm_kzalloc(&client->dev, sizeof(*charger), GFP_KERNEL); if (!charger) return -ENOMEM; mutex_init(&charger->lock); charger->charging = true; charger->pdata = client->dev.platform_data; if (IS_ENABLED(CONFIG_OF) && !charger->pdata && client->dev.of_node) charger->pdata = bq24735_parse_dt_data(client); if (!charger->pdata) { dev_err(&client->dev, "no platform data provided\n"); return -EINVAL; } name = (char *)charger->pdata->name; if (!name) { name = devm_kasprintf(&client->dev, GFP_KERNEL, "bq24735@%s", dev_name(&client->dev)); if (!name) { dev_err(&client->dev, "Failed to alloc device name\n"); return -ENOMEM; } } charger->client = client; supply_desc = &charger->charger_desc; supply_desc->name = name; supply_desc->type = POWER_SUPPLY_TYPE_MAINS; supply_desc->properties = bq24735_charger_properties; supply_desc->num_properties = ARRAY_SIZE(bq24735_charger_properties); supply_desc->get_property = bq24735_charger_get_property; supply_desc->set_property = bq24735_charger_set_property; supply_desc->property_is_writeable = bq24735_charger_property_is_writeable; psy_cfg.supplied_to = charger->pdata->supplied_to; psy_cfg.num_supplicants = charger->pdata->num_supplicants; psy_cfg.of_node = client->dev.of_node; psy_cfg.drv_data = charger; i2c_set_clientdata(client, charger); charger->status_gpio = devm_gpiod_get_optional(&client->dev, "ti,ac-detect", GPIOD_IN); if (IS_ERR(charger->status_gpio)) { ret = PTR_ERR(charger->status_gpio); dev_err(&client->dev, "Getting gpio failed: %d\n", ret); return ret; } if (bq24735_charger_is_present(charger)) { ret = bq24735_read_word(client, BQ24735_MANUFACTURER_ID); if (ret < 0) { dev_err(&client->dev, "Failed to read manufacturer id : %d\n", ret); return ret; } else if (ret != 0x0040) { dev_err(&client->dev, "manufacturer id mismatch. 0x0040 != 0x%04x\n", ret); return -ENODEV; } ret = bq24735_read_word(client, BQ24735_DEVICE_ID); if (ret < 0) { dev_err(&client->dev, "Failed to read device id : %d\n", ret); return ret; } else if (ret != 0x000B) { dev_err(&client->dev, "device id mismatch. 0x000b != 0x%04x\n", ret); return -ENODEV; } ret = bq24735_enable_charging(charger); if (ret < 0) { dev_err(&client->dev, "Failed to enable charging\n"); return ret; } } charger->charger = devm_power_supply_register(&client->dev, supply_desc, &psy_cfg); if (IS_ERR(charger->charger)) { ret = PTR_ERR(charger->charger); dev_err(&client->dev, "Failed to register power supply: %d\n", ret); return ret; } if (client->irq) { ret = devm_request_threaded_irq(&client->dev, client->irq, NULL, bq24735_charger_isr, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING | IRQF_ONESHOT, supply_desc->name, charger->charger); if (ret) { dev_err(&client->dev, "Unable to register IRQ %d err %d\n", client->irq, ret); return ret; } } else { ret = device_property_read_u32(&client->dev, "poll-interval", &charger->poll_interval); if (ret) return 0; if (!charger->poll_interval) return 0; ret = devm_delayed_work_autocancel(&client->dev, &charger->poll, bq24735_poll); if (ret) return ret; schedule_delayed_work(&charger->poll, msecs_to_jiffies(charger->poll_interval)); } return 0; } static const struct i2c_device_id bq24735_charger_id[] = { { "bq24735-charger", 0 }, {} }; MODULE_DEVICE_TABLE(i2c, bq24735_charger_id); static const struct of_device_id bq24735_match_ids[] = { { .compatible = "ti,bq24735", }, { /* end */ } }; MODULE_DEVICE_TABLE(of, bq24735_match_ids); static struct i2c_driver bq24735_charger_driver = { .driver = { .name = "bq24735-charger", .of_match_table = bq24735_match_ids, }, .probe = bq24735_charger_probe, .id_table = bq24735_charger_id, }; module_i2c_driver(bq24735_charger_driver); MODULE_DESCRIPTION("bq24735 battery charging driver"); MODULE_AUTHOR("Darbha Sriharsha <[email protected]>"); MODULE_LICENSE("GPL v2");
linux-master
drivers/power/supply/bq24735-charger.c
// SPDX-License-Identifier: GPL-2.0-only /* * Battery driver for CPCAP PMIC * * Copyright (C) 2017 Tony Lindgren <[email protected]> * * Some parts of the code based on earlier Motorola mapphone Linux kernel * drivers: * * Copyright (C) 2009-2010 Motorola, Inc. */ #include <linux/delay.h> #include <linux/err.h> #include <linux/interrupt.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/reboot.h> #include <linux/regmap.h> #include <linux/nvmem-consumer.h> #include <linux/moduleparam.h> #include <linux/iio/consumer.h> #include <linux/iio/types.h> #include <linux/mfd/motorola-cpcap.h> /* * Register bit defines for CPCAP_REG_BPEOL. Some of these seem to * map to MC13783UG.pdf "Table 5-19. Register 13, Power Control 0" * to enable BATTDETEN, LOBAT and EOL features. We currently use * LOBAT interrupts instead of EOL. */ #define CPCAP_REG_BPEOL_BIT_EOL9 BIT(9) /* Set for EOL irq */ #define CPCAP_REG_BPEOL_BIT_EOL8 BIT(8) /* Set for EOL irq */ #define CPCAP_REG_BPEOL_BIT_UNKNOWN7 BIT(7) #define CPCAP_REG_BPEOL_BIT_UNKNOWN6 BIT(6) #define CPCAP_REG_BPEOL_BIT_UNKNOWN5 BIT(5) #define CPCAP_REG_BPEOL_BIT_EOL_MULTI BIT(4) /* Set for multiple EOL irqs */ #define CPCAP_REG_BPEOL_BIT_UNKNOWN3 BIT(3) #define CPCAP_REG_BPEOL_BIT_UNKNOWN2 BIT(2) #define CPCAP_REG_BPEOL_BIT_BATTDETEN BIT(1) /* Enable battery detect */ #define CPCAP_REG_BPEOL_BIT_EOLSEL BIT(0) /* BPDET = 0, EOL = 1 */ /* * Register bit defines for CPCAP_REG_CCC1. These seem similar to the twl6030 * coulomb counter registers rather than the mc13892 registers. Both twl6030 * and mc13892 set bits 2 and 1 to reset and clear registers. But mc13892 * sets bit 0 to start the coulomb counter while twl6030 sets bit 0 to stop * the coulomb counter like cpcap does. So for now, we use the twl6030 style * naming for the registers. */ #define CPCAP_REG_CCC1_ACTIVE_MODE1 BIT(4) /* Update rate */ #define CPCAP_REG_CCC1_ACTIVE_MODE0 BIT(3) /* Update rate */ #define CPCAP_REG_CCC1_AUTOCLEAR BIT(2) /* Resets sample registers */ #define CPCAP_REG_CCC1_CAL_EN BIT(1) /* Clears after write in 1s */ #define CPCAP_REG_CCC1_PAUSE BIT(0) /* Stop counters, allow write */ #define CPCAP_REG_CCC1_RESET_MASK (CPCAP_REG_CCC1_AUTOCLEAR | \ CPCAP_REG_CCC1_CAL_EN) #define CPCAP_REG_CCCC2_RATE1 BIT(5) #define CPCAP_REG_CCCC2_RATE0 BIT(4) #define CPCAP_REG_CCCC2_ENABLE BIT(3) #define CPCAP_BATTERY_CC_SAMPLE_PERIOD_MS 250 #define CPCAP_BATTERY_EB41_HW4X_ID 0x9E #define CPCAP_BATTERY_BW8X_ID 0x98 enum { CPCAP_BATTERY_IIO_BATTDET, CPCAP_BATTERY_IIO_VOLTAGE, CPCAP_BATTERY_IIO_CHRG_CURRENT, CPCAP_BATTERY_IIO_BATT_CURRENT, CPCAP_BATTERY_IIO_NR, }; enum cpcap_battery_irq_action { CPCAP_BATTERY_IRQ_ACTION_NONE, CPCAP_BATTERY_IRQ_ACTION_CC_CAL_DONE, CPCAP_BATTERY_IRQ_ACTION_BATTERY_LOW, CPCAP_BATTERY_IRQ_ACTION_POWEROFF, }; struct cpcap_interrupt_desc { const char *name; struct list_head node; int irq; enum cpcap_battery_irq_action action; }; struct cpcap_battery_config { int cd_factor; struct power_supply_info info; struct power_supply_battery_info bat; }; struct cpcap_coulomb_counter_data { s32 sample; /* 24 or 32 bits */ s32 accumulator; s16 offset; /* 9 bits */ s16 integrator; /* 13 or 16 bits */ }; enum cpcap_battery_state { CPCAP_BATTERY_STATE_PREVIOUS, CPCAP_BATTERY_STATE_LATEST, CPCAP_BATTERY_STATE_EMPTY, CPCAP_BATTERY_STATE_FULL, CPCAP_BATTERY_STATE_NR, }; struct cpcap_battery_state_data { int voltage; int current_ua; int counter_uah; int temperature; ktime_t time; struct cpcap_coulomb_counter_data cc; }; struct cpcap_battery_ddata { struct device *dev; struct regmap *reg; struct list_head irq_list; struct iio_channel *channels[CPCAP_BATTERY_IIO_NR]; struct power_supply *psy; struct cpcap_battery_config config; struct cpcap_battery_state_data state[CPCAP_BATTERY_STATE_NR]; u32 cc_lsb; /* μAms per LSB */ atomic_t active; int charge_full; int status; u16 vendor; bool check_nvmem; unsigned int is_full:1; }; #define CPCAP_NO_BATTERY -400 static bool ignore_temperature_probe; module_param(ignore_temperature_probe, bool, 0660); static struct cpcap_battery_state_data * cpcap_battery_get_state(struct cpcap_battery_ddata *ddata, enum cpcap_battery_state state) { if (state >= CPCAP_BATTERY_STATE_NR) return NULL; return &ddata->state[state]; } static struct cpcap_battery_state_data * cpcap_battery_latest(struct cpcap_battery_ddata *ddata) { return cpcap_battery_get_state(ddata, CPCAP_BATTERY_STATE_LATEST); } static struct cpcap_battery_state_data * cpcap_battery_previous(struct cpcap_battery_ddata *ddata) { return cpcap_battery_get_state(ddata, CPCAP_BATTERY_STATE_PREVIOUS); } static struct cpcap_battery_state_data * cpcap_battery_get_empty(struct cpcap_battery_ddata *ddata) { return cpcap_battery_get_state(ddata, CPCAP_BATTERY_STATE_EMPTY); } static struct cpcap_battery_state_data * cpcap_battery_get_full(struct cpcap_battery_ddata *ddata) { return cpcap_battery_get_state(ddata, CPCAP_BATTERY_STATE_FULL); } static int cpcap_charger_battery_temperature(struct cpcap_battery_ddata *ddata, int *value) { struct iio_channel *channel; int error; channel = ddata->channels[CPCAP_BATTERY_IIO_BATTDET]; error = iio_read_channel_processed(channel, value); if (error < 0) { if (!ignore_temperature_probe) dev_warn(ddata->dev, "%s failed: %i\n", __func__, error); *value = CPCAP_NO_BATTERY; return error; } *value /= 100; return 0; } static int cpcap_battery_get_voltage(struct cpcap_battery_ddata *ddata) { struct iio_channel *channel; int error, value = 0; channel = ddata->channels[CPCAP_BATTERY_IIO_VOLTAGE]; error = iio_read_channel_processed(channel, &value); if (error < 0) { dev_warn(ddata->dev, "%s failed: %i\n", __func__, error); return 0; } return value * 1000; } static int cpcap_battery_get_current(struct cpcap_battery_ddata *ddata) { struct iio_channel *channel; int error, value = 0; channel = ddata->channels[CPCAP_BATTERY_IIO_BATT_CURRENT]; error = iio_read_channel_processed(channel, &value); if (error < 0) { dev_warn(ddata->dev, "%s failed: %i\n", __func__, error); return 0; } return value * 1000; } /** * cpcap_battery_cc_raw_div - calculate and divide coulomb counter μAms values * @ddata: device driver data * @sample: coulomb counter sample value * @accumulator: coulomb counter integrator value * @offset: coulomb counter offset value * @divider: conversion divider * * Note that cc_lsb and cc_dur values are from Motorola Linux kernel * function data_get_avg_curr_ua() and seem to be based on measured test * results. It also has the following comment: * * Adjustment factors are applied here as a temp solution per the test * results. Need to work out a formal solution for this adjustment. * * A coulomb counter for similar hardware seems to be documented in * "TWL6030 Gas Gauging Basics (Rev. A)" swca095a.pdf in chapter * "10 Calculating Accumulated Current". We however follow what the * Motorola mapphone Linux kernel is doing as there may be either a * TI or ST coulomb counter in the PMIC. */ static int cpcap_battery_cc_raw_div(struct cpcap_battery_ddata *ddata, s32 sample, s32 accumulator, s16 offset, u32 divider) { s64 acc; if (!divider) return 0; acc = accumulator; acc -= (s64)sample * offset; acc *= ddata->cc_lsb; acc *= -1; acc = div_s64(acc, divider); return acc; } /* 3600000μAms = 1μAh */ static int cpcap_battery_cc_to_uah(struct cpcap_battery_ddata *ddata, s32 sample, s32 accumulator, s16 offset) { return cpcap_battery_cc_raw_div(ddata, sample, accumulator, offset, 3600000); } static int cpcap_battery_cc_to_ua(struct cpcap_battery_ddata *ddata, s32 sample, s32 accumulator, s16 offset) { return cpcap_battery_cc_raw_div(ddata, sample, accumulator, offset, sample * CPCAP_BATTERY_CC_SAMPLE_PERIOD_MS); } /** * cpcap_battery_read_accumulated - reads cpcap coulomb counter * @ddata: device driver data * @ccd: coulomb counter values * * Based on Motorola mapphone kernel function data_read_regs(). * Looking at the registers, the coulomb counter seems similar to * the coulomb counter in TWL6030. See "TWL6030 Gas Gauging Basics * (Rev. A) swca095a.pdf for "10 Calculating Accumulated Current". * * Note that swca095a.pdf instructs to stop the coulomb counter * before reading to avoid values changing. Motorola mapphone * Linux kernel does not do it, so let's assume they've verified * the data produced is correct. */ static int cpcap_battery_read_accumulated(struct cpcap_battery_ddata *ddata, struct cpcap_coulomb_counter_data *ccd) { u16 buf[7]; /* CPCAP_REG_CCS1 to CCI */ int error; ccd->sample = 0; ccd->accumulator = 0; ccd->offset = 0; ccd->integrator = 0; /* Read coulomb counter register range */ error = regmap_bulk_read(ddata->reg, CPCAP_REG_CCS1, buf, ARRAY_SIZE(buf)); if (error) return 0; /* Sample value CPCAP_REG_CCS1 & 2 */ ccd->sample = (buf[1] & 0x0fff) << 16; ccd->sample |= buf[0]; if (ddata->vendor == CPCAP_VENDOR_TI) ccd->sample = sign_extend32(24, ccd->sample); /* Accumulator value CPCAP_REG_CCA1 & 2 */ ccd->accumulator = ((s16)buf[3]) << 16; ccd->accumulator |= buf[2]; /* * Coulomb counter calibration offset is CPCAP_REG_CCM, * REG_CCO seems unused */ ccd->offset = buf[4]; ccd->offset = sign_extend32(ccd->offset, 9); /* Integrator register CPCAP_REG_CCI */ if (ddata->vendor == CPCAP_VENDOR_TI) ccd->integrator = sign_extend32(buf[6], 13); else ccd->integrator = (s16)buf[6]; return cpcap_battery_cc_to_uah(ddata, ccd->sample, ccd->accumulator, ccd->offset); } /* * Based on the values from Motorola mapphone Linux kernel for the * stock Droid 4 battery eb41. In the Motorola mapphone Linux * kernel tree the value for pm_cd_factor is passed to the kernel * via device tree. If it turns out to be something device specific * we can consider that too later. These values are also fine for * Bionic's hw4x. * * And looking at the battery full and shutdown values for the stock * kernel on droid 4, full is 4351000 and software initiates shutdown * at 3078000. The device will die around 2743000. */ static const struct cpcap_battery_config cpcap_battery_eb41_data = { .cd_factor = 0x3cc, .info.technology = POWER_SUPPLY_TECHNOLOGY_LION, .info.voltage_max_design = 4351000, .info.voltage_min_design = 3100000, .info.charge_full_design = 1740000, .bat.constant_charge_voltage_max_uv = 4200000, }; /* Values for the extended Droid Bionic battery bw8x. */ static const struct cpcap_battery_config cpcap_battery_bw8x_data = { .cd_factor = 0x3cc, .info.technology = POWER_SUPPLY_TECHNOLOGY_LION, .info.voltage_max_design = 4200000, .info.voltage_min_design = 3200000, .info.charge_full_design = 2760000, .bat.constant_charge_voltage_max_uv = 4200000, }; /* * Safe values for any lipo battery likely to fit into a mapphone * battery bay. */ static const struct cpcap_battery_config cpcap_battery_unkown_data = { .cd_factor = 0x3cc, .info.technology = POWER_SUPPLY_TECHNOLOGY_LION, .info.voltage_max_design = 4200000, .info.voltage_min_design = 3200000, .info.charge_full_design = 3000000, .bat.constant_charge_voltage_max_uv = 4200000, }; static int cpcap_battery_match_nvmem(struct device *dev, const void *data) { if (strcmp(dev_name(dev), "89-500029ba0f73") == 0) return 1; else return 0; } static void cpcap_battery_detect_battery_type(struct cpcap_battery_ddata *ddata) { struct nvmem_device *nvmem; u8 battery_id = 0; ddata->check_nvmem = false; nvmem = nvmem_device_find(NULL, &cpcap_battery_match_nvmem); if (IS_ERR_OR_NULL(nvmem)) { ddata->check_nvmem = true; dev_info_once(ddata->dev, "Can not find battery nvmem device. Assuming generic lipo battery\n"); } else if (nvmem_device_read(nvmem, 2, 1, &battery_id) < 0) { battery_id = 0; ddata->check_nvmem = true; dev_warn(ddata->dev, "Can not read battery nvmem device. Assuming generic lipo battery\n"); } switch (battery_id) { case CPCAP_BATTERY_EB41_HW4X_ID: ddata->config = cpcap_battery_eb41_data; break; case CPCAP_BATTERY_BW8X_ID: ddata->config = cpcap_battery_bw8x_data; break; default: ddata->config = cpcap_battery_unkown_data; } } /** * cpcap_battery_cc_get_avg_current - read cpcap coulumb counter * @ddata: cpcap battery driver device data */ static int cpcap_battery_cc_get_avg_current(struct cpcap_battery_ddata *ddata) { int value, acc, error; s32 sample; s16 offset; /* Coulomb counter integrator */ error = regmap_read(ddata->reg, CPCAP_REG_CCI, &value); if (error) return error; if (ddata->vendor == CPCAP_VENDOR_TI) { acc = sign_extend32(value, 13); sample = 1; } else { acc = (s16)value; sample = 4; } /* Coulomb counter calibration offset */ error = regmap_read(ddata->reg, CPCAP_REG_CCM, &value); if (error) return error; offset = sign_extend32(value, 9); return cpcap_battery_cc_to_ua(ddata, sample, acc, offset); } static int cpcap_battery_get_charger_status(struct cpcap_battery_ddata *ddata, int *val) { union power_supply_propval prop; struct power_supply *charger; int error; charger = power_supply_get_by_name("usb"); if (!charger) return -ENODEV; error = power_supply_get_property(charger, POWER_SUPPLY_PROP_STATUS, &prop); if (error) *val = POWER_SUPPLY_STATUS_UNKNOWN; else *val = prop.intval; power_supply_put(charger); return error; } static bool cpcap_battery_full(struct cpcap_battery_ddata *ddata) { struct cpcap_battery_state_data *state = cpcap_battery_latest(ddata); unsigned int vfull; int error, val; error = cpcap_battery_get_charger_status(ddata, &val); if (!error) { switch (val) { case POWER_SUPPLY_STATUS_DISCHARGING: dev_dbg(ddata->dev, "charger disconnected\n"); ddata->is_full = 0; break; case POWER_SUPPLY_STATUS_FULL: dev_dbg(ddata->dev, "charger full status\n"); ddata->is_full = 1; break; default: break; } } /* * The full battery voltage here can be inaccurate, it's used just to * filter out any trickle charging events. We clear the is_full status * on charger disconnect above anyways. */ vfull = ddata->config.bat.constant_charge_voltage_max_uv - 120000; if (ddata->is_full && state->voltage < vfull) ddata->is_full = 0; return ddata->is_full; } static bool cpcap_battery_low(struct cpcap_battery_ddata *ddata) { struct cpcap_battery_state_data *state = cpcap_battery_latest(ddata); static bool is_low; if (state->current_ua > 0 && (state->voltage <= 3350000 || is_low)) is_low = true; else is_low = false; return is_low; } static int cpcap_battery_update_status(struct cpcap_battery_ddata *ddata) { struct cpcap_battery_state_data state, *latest, *previous, *empty, *full; ktime_t now; int error; memset(&state, 0, sizeof(state)); now = ktime_get(); latest = cpcap_battery_latest(ddata); if (latest) { s64 delta_ms = ktime_to_ms(ktime_sub(now, latest->time)); if (delta_ms < CPCAP_BATTERY_CC_SAMPLE_PERIOD_MS) return delta_ms; } state.time = now; state.voltage = cpcap_battery_get_voltage(ddata); state.current_ua = cpcap_battery_get_current(ddata); state.counter_uah = cpcap_battery_read_accumulated(ddata, &state.cc); error = cpcap_charger_battery_temperature(ddata, &state.temperature); if (error) return error; previous = cpcap_battery_previous(ddata); memcpy(previous, latest, sizeof(*previous)); memcpy(latest, &state, sizeof(*latest)); if (cpcap_battery_full(ddata)) { full = cpcap_battery_get_full(ddata); memcpy(full, latest, sizeof(*full)); empty = cpcap_battery_get_empty(ddata); if (empty->voltage && empty->voltage != -1) { empty->voltage = -1; ddata->charge_full = empty->counter_uah - full->counter_uah; } else if (ddata->charge_full) { empty->voltage = -1; empty->counter_uah = full->counter_uah + ddata->charge_full; } } else if (cpcap_battery_low(ddata)) { empty = cpcap_battery_get_empty(ddata); memcpy(empty, latest, sizeof(*empty)); full = cpcap_battery_get_full(ddata); if (full->voltage) { full->voltage = 0; ddata->charge_full = empty->counter_uah - full->counter_uah; } } return 0; } /* * Update battery status when cpcap-charger calls power_supply_changed(). * This allows us to detect battery full condition before the charger * disconnects. */ static void cpcap_battery_external_power_changed(struct power_supply *psy) { union power_supply_propval prop; power_supply_get_property(psy, POWER_SUPPLY_PROP_STATUS, &prop); } static enum power_supply_property cpcap_battery_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_TECHNOLOGY, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN, POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN, POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE, POWER_SUPPLY_PROP_CURRENT_AVG, POWER_SUPPLY_PROP_CURRENT_NOW, POWER_SUPPLY_PROP_CHARGE_FULL, POWER_SUPPLY_PROP_CHARGE_NOW, POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN, POWER_SUPPLY_PROP_CHARGE_COUNTER, POWER_SUPPLY_PROP_POWER_NOW, POWER_SUPPLY_PROP_POWER_AVG, POWER_SUPPLY_PROP_CAPACITY, POWER_SUPPLY_PROP_CAPACITY_LEVEL, POWER_SUPPLY_PROP_SCOPE, POWER_SUPPLY_PROP_TEMP, }; static int cpcap_battery_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct cpcap_battery_ddata *ddata = power_supply_get_drvdata(psy); struct cpcap_battery_state_data *latest, *previous, *empty; u32 sample; s32 accumulator; int cached; s64 tmp; cached = cpcap_battery_update_status(ddata); if (cached < 0) return cached; latest = cpcap_battery_latest(ddata); previous = cpcap_battery_previous(ddata); if (ddata->check_nvmem) cpcap_battery_detect_battery_type(ddata); switch (psp) { case POWER_SUPPLY_PROP_PRESENT: if (latest->temperature > CPCAP_NO_BATTERY || ignore_temperature_probe) val->intval = 1; else val->intval = 0; break; case POWER_SUPPLY_PROP_STATUS: if (cpcap_battery_full(ddata)) { val->intval = POWER_SUPPLY_STATUS_FULL; break; } if (cpcap_battery_cc_get_avg_current(ddata) < 0) val->intval = POWER_SUPPLY_STATUS_CHARGING; else val->intval = POWER_SUPPLY_STATUS_DISCHARGING; break; case POWER_SUPPLY_PROP_TECHNOLOGY: val->intval = ddata->config.info.technology; break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: val->intval = cpcap_battery_get_voltage(ddata); break; case POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN: val->intval = ddata->config.info.voltage_max_design; break; case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN: val->intval = ddata->config.info.voltage_min_design; break; case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE: val->intval = ddata->config.bat.constant_charge_voltage_max_uv; break; case POWER_SUPPLY_PROP_CURRENT_AVG: sample = latest->cc.sample - previous->cc.sample; if (!sample) { val->intval = cpcap_battery_cc_get_avg_current(ddata); break; } accumulator = latest->cc.accumulator - previous->cc.accumulator; val->intval = cpcap_battery_cc_to_ua(ddata, sample, accumulator, latest->cc.offset); break; case POWER_SUPPLY_PROP_CURRENT_NOW: val->intval = latest->current_ua; break; case POWER_SUPPLY_PROP_CHARGE_COUNTER: val->intval = latest->counter_uah; break; case POWER_SUPPLY_PROP_POWER_NOW: tmp = (latest->voltage / 10000) * latest->current_ua; val->intval = div64_s64(tmp, 100); break; case POWER_SUPPLY_PROP_POWER_AVG: sample = latest->cc.sample - previous->cc.sample; if (!sample) { tmp = cpcap_battery_cc_get_avg_current(ddata); tmp *= (latest->voltage / 10000); val->intval = div64_s64(tmp, 100); break; } accumulator = latest->cc.accumulator - previous->cc.accumulator; tmp = cpcap_battery_cc_to_ua(ddata, sample, accumulator, latest->cc.offset); tmp *= ((latest->voltage + previous->voltage) / 20000); val->intval = div64_s64(tmp, 100); break; case POWER_SUPPLY_PROP_CAPACITY: empty = cpcap_battery_get_empty(ddata); if (!empty->voltage || !ddata->charge_full) return -ENODATA; /* (ddata->charge_full / 200) is needed for rounding */ val->intval = empty->counter_uah - latest->counter_uah + ddata->charge_full / 200; val->intval = clamp(val->intval, 0, ddata->charge_full); val->intval = val->intval * 100 / ddata->charge_full; break; case POWER_SUPPLY_PROP_CAPACITY_LEVEL: if (cpcap_battery_full(ddata)) val->intval = POWER_SUPPLY_CAPACITY_LEVEL_FULL; else if (latest->voltage >= 3750000) val->intval = POWER_SUPPLY_CAPACITY_LEVEL_HIGH; else if (latest->voltage >= 3300000) val->intval = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL; else if (latest->voltage > 3100000) val->intval = POWER_SUPPLY_CAPACITY_LEVEL_LOW; else if (latest->voltage <= 3100000) val->intval = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL; else val->intval = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN; break; case POWER_SUPPLY_PROP_CHARGE_NOW: empty = cpcap_battery_get_empty(ddata); if (!empty->voltage) return -ENODATA; val->intval = empty->counter_uah - latest->counter_uah; if (val->intval < 0) { /* Assume invalid config if CHARGE_NOW is -20% */ if (ddata->charge_full && abs(val->intval) > ddata->charge_full/5) { empty->voltage = 0; ddata->charge_full = 0; return -ENODATA; } val->intval = 0; } else if (ddata->charge_full && ddata->charge_full < val->intval) { /* Assume invalid config if CHARGE_NOW exceeds CHARGE_FULL by 20% */ if (val->intval > (6*ddata->charge_full)/5) { empty->voltage = 0; ddata->charge_full = 0; return -ENODATA; } val->intval = ddata->charge_full; } break; case POWER_SUPPLY_PROP_CHARGE_FULL: if (!ddata->charge_full) return -ENODATA; val->intval = ddata->charge_full; break; case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN: val->intval = ddata->config.info.charge_full_design; break; case POWER_SUPPLY_PROP_SCOPE: val->intval = POWER_SUPPLY_SCOPE_SYSTEM; break; case POWER_SUPPLY_PROP_TEMP: if (ignore_temperature_probe) return -ENODATA; val->intval = latest->temperature; break; default: return -EINVAL; } return 0; } static int cpcap_battery_update_charger(struct cpcap_battery_ddata *ddata, int const_charge_voltage) { union power_supply_propval prop; union power_supply_propval val; struct power_supply *charger; int error; charger = power_supply_get_by_name("usb"); if (!charger) return -ENODEV; error = power_supply_get_property(charger, POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE, &prop); if (error) goto out_put; /* Allow charger const voltage lower than battery const voltage */ if (const_charge_voltage > prop.intval) goto out_put; val.intval = const_charge_voltage; error = power_supply_set_property(charger, POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE, &val); out_put: power_supply_put(charger); return error; } static int cpcap_battery_set_property(struct power_supply *psy, enum power_supply_property psp, const union power_supply_propval *val) { struct cpcap_battery_ddata *ddata = power_supply_get_drvdata(psy); switch (psp) { case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE: if (val->intval < ddata->config.info.voltage_min_design) return -EINVAL; if (val->intval > ddata->config.info.voltage_max_design) return -EINVAL; ddata->config.bat.constant_charge_voltage_max_uv = val->intval; return cpcap_battery_update_charger(ddata, val->intval); case POWER_SUPPLY_PROP_CHARGE_FULL: if (val->intval < 0) return -EINVAL; if (val->intval > (6*ddata->config.info.charge_full_design)/5) return -EINVAL; ddata->charge_full = val->intval; return 0; default: return -EINVAL; } return 0; } static int cpcap_battery_property_is_writeable(struct power_supply *psy, enum power_supply_property psp) { switch (psp) { case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE: case POWER_SUPPLY_PROP_CHARGE_FULL: return 1; default: return 0; } } static irqreturn_t cpcap_battery_irq_thread(int irq, void *data) { struct cpcap_battery_ddata *ddata = data; struct cpcap_battery_state_data *latest; struct cpcap_interrupt_desc *d; if (!atomic_read(&ddata->active)) return IRQ_NONE; list_for_each_entry(d, &ddata->irq_list, node) { if (irq == d->irq) break; } if (list_entry_is_head(d, &ddata->irq_list, node)) return IRQ_NONE; latest = cpcap_battery_latest(ddata); switch (d->action) { case CPCAP_BATTERY_IRQ_ACTION_CC_CAL_DONE: dev_info(ddata->dev, "Coulomb counter calibration done\n"); break; case CPCAP_BATTERY_IRQ_ACTION_BATTERY_LOW: if (latest->current_ua >= 0) dev_warn(ddata->dev, "Battery low at %imV!\n", latest->voltage / 1000); break; case CPCAP_BATTERY_IRQ_ACTION_POWEROFF: if (latest->current_ua >= 0 && latest->voltage <= 3200000) { dev_emerg(ddata->dev, "Battery empty at %imV, powering off\n", latest->voltage / 1000); orderly_poweroff(true); } break; default: break; } power_supply_changed(ddata->psy); return IRQ_HANDLED; } static int cpcap_battery_init_irq(struct platform_device *pdev, struct cpcap_battery_ddata *ddata, const char *name) { struct cpcap_interrupt_desc *d; int irq, error; irq = platform_get_irq_byname(pdev, name); if (irq < 0) return irq; error = devm_request_threaded_irq(ddata->dev, irq, NULL, cpcap_battery_irq_thread, IRQF_SHARED | IRQF_ONESHOT, name, ddata); if (error) { dev_err(ddata->dev, "could not get irq %s: %i\n", name, error); return error; } d = devm_kzalloc(ddata->dev, sizeof(*d), GFP_KERNEL); if (!d) return -ENOMEM; d->name = name; d->irq = irq; if (!strncmp(name, "cccal", 5)) d->action = CPCAP_BATTERY_IRQ_ACTION_CC_CAL_DONE; else if (!strncmp(name, "lowbph", 6)) d->action = CPCAP_BATTERY_IRQ_ACTION_BATTERY_LOW; else if (!strncmp(name, "lowbpl", 6)) d->action = CPCAP_BATTERY_IRQ_ACTION_POWEROFF; list_add(&d->node, &ddata->irq_list); return 0; } static int cpcap_battery_init_interrupts(struct platform_device *pdev, struct cpcap_battery_ddata *ddata) { static const char * const cpcap_battery_irqs[] = { "eol", "lowbph", "lowbpl", "chrgcurr1", "battdetb" }; int i, error; for (i = 0; i < ARRAY_SIZE(cpcap_battery_irqs); i++) { error = cpcap_battery_init_irq(pdev, ddata, cpcap_battery_irqs[i]); if (error) return error; } /* Enable calibration interrupt if already available in dts */ cpcap_battery_init_irq(pdev, ddata, "cccal"); /* Enable low battery interrupts for 3.3V high and 3.1V low */ error = regmap_update_bits(ddata->reg, CPCAP_REG_BPEOL, 0xffff, CPCAP_REG_BPEOL_BIT_BATTDETEN); if (error) return error; return 0; } static int cpcap_battery_init_iio(struct cpcap_battery_ddata *ddata) { const char * const names[CPCAP_BATTERY_IIO_NR] = { "battdetb", "battp", "chg_isense", "batti", }; int error, i; for (i = 0; i < CPCAP_BATTERY_IIO_NR; i++) { ddata->channels[i] = devm_iio_channel_get(ddata->dev, names[i]); if (IS_ERR(ddata->channels[i])) { error = PTR_ERR(ddata->channels[i]); goto out_err; } if (!ddata->channels[i]->indio_dev) { error = -ENXIO; goto out_err; } } return 0; out_err: return dev_err_probe(ddata->dev, error, "could not initialize VBUS or ID IIO\n"); } /* Calibrate coulomb counter */ static int cpcap_battery_calibrate(struct cpcap_battery_ddata *ddata) { int error, ccc1, value; unsigned long timeout; error = regmap_read(ddata->reg, CPCAP_REG_CCC1, &ccc1); if (error) return error; timeout = jiffies + msecs_to_jiffies(6000); /* Start calibration */ error = regmap_update_bits(ddata->reg, CPCAP_REG_CCC1, 0xffff, CPCAP_REG_CCC1_CAL_EN); if (error) goto restore; while (time_before(jiffies, timeout)) { error = regmap_read(ddata->reg, CPCAP_REG_CCC1, &value); if (error) goto restore; if (!(value & CPCAP_REG_CCC1_CAL_EN)) break; error = regmap_read(ddata->reg, CPCAP_REG_CCM, &value); if (error) goto restore; msleep(300); } /* Read calibration offset from CCM */ error = regmap_read(ddata->reg, CPCAP_REG_CCM, &value); if (error) goto restore; dev_info(ddata->dev, "calibration done: 0x%04x\n", value); restore: if (error) dev_err(ddata->dev, "%s: error %i\n", __func__, error); error = regmap_update_bits(ddata->reg, CPCAP_REG_CCC1, 0xffff, ccc1); if (error) dev_err(ddata->dev, "%s: restore error %i\n", __func__, error); return error; } #ifdef CONFIG_OF static const struct of_device_id cpcap_battery_id_table[] = { { .compatible = "motorola,cpcap-battery", }, {}, }; MODULE_DEVICE_TABLE(of, cpcap_battery_id_table); #endif static const struct power_supply_desc cpcap_charger_battery_desc = { .name = "battery", .type = POWER_SUPPLY_TYPE_BATTERY, .properties = cpcap_battery_props, .num_properties = ARRAY_SIZE(cpcap_battery_props), .get_property = cpcap_battery_get_property, .set_property = cpcap_battery_set_property, .property_is_writeable = cpcap_battery_property_is_writeable, .external_power_changed = cpcap_battery_external_power_changed, }; static int cpcap_battery_probe(struct platform_device *pdev) { struct cpcap_battery_ddata *ddata; struct power_supply_config psy_cfg = {}; int error; ddata = devm_kzalloc(&pdev->dev, sizeof(*ddata), GFP_KERNEL); if (!ddata) return -ENOMEM; cpcap_battery_detect_battery_type(ddata); INIT_LIST_HEAD(&ddata->irq_list); ddata->dev = &pdev->dev; ddata->reg = dev_get_regmap(ddata->dev->parent, NULL); if (!ddata->reg) return -ENODEV; error = cpcap_get_vendor(ddata->dev, ddata->reg, &ddata->vendor); if (error) return error; switch (ddata->vendor) { case CPCAP_VENDOR_ST: ddata->cc_lsb = 95374; /* μAms per LSB */ break; case CPCAP_VENDOR_TI: ddata->cc_lsb = 91501; /* μAms per LSB */ break; default: return -EINVAL; } ddata->cc_lsb = (ddata->cc_lsb * ddata->config.cd_factor) / 1000; platform_set_drvdata(pdev, ddata); error = cpcap_battery_init_interrupts(pdev, ddata); if (error) return error; error = cpcap_battery_init_iio(ddata); if (error) return error; psy_cfg.of_node = pdev->dev.of_node; psy_cfg.drv_data = ddata; ddata->psy = devm_power_supply_register(ddata->dev, &cpcap_charger_battery_desc, &psy_cfg); error = PTR_ERR_OR_ZERO(ddata->psy); if (error) { dev_err(ddata->dev, "failed to register power supply\n"); return error; } atomic_set(&ddata->active, 1); error = cpcap_battery_calibrate(ddata); if (error) return error; return 0; } static int cpcap_battery_remove(struct platform_device *pdev) { struct cpcap_battery_ddata *ddata = platform_get_drvdata(pdev); int error; atomic_set(&ddata->active, 0); error = regmap_update_bits(ddata->reg, CPCAP_REG_BPEOL, 0xffff, 0); if (error) dev_err(&pdev->dev, "could not disable: %i\n", error); return 0; } static struct platform_driver cpcap_battery_driver = { .driver = { .name = "cpcap_battery", .of_match_table = of_match_ptr(cpcap_battery_id_table), }, .probe = cpcap_battery_probe, .remove = cpcap_battery_remove, }; module_platform_driver(cpcap_battery_driver); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Tony Lindgren <[email protected]>"); MODULE_DESCRIPTION("CPCAP PMIC Battery Driver");
linux-master
drivers/power/supply/cpcap-battery.c
// SPDX-License-Identifier: GPL-2.0 /* * Power supply driver for the goldfish emulator * * Copyright (C) 2008 Google, Inc. * Copyright (C) 2012 Intel, Inc. * Copyright (C) 2013 Intel, Inc. * Author: Mike Lockwood <[email protected]> */ #include <linux/module.h> #include <linux/err.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/types.h> #include <linux/pci.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/acpi.h> struct goldfish_battery_data { void __iomem *reg_base; int irq; spinlock_t lock; struct power_supply *battery; struct power_supply *ac; }; #define GOLDFISH_BATTERY_READ(data, addr) \ (readl(data->reg_base + addr)) #define GOLDFISH_BATTERY_WRITE(data, addr, x) \ (writel(x, data->reg_base + addr)) enum { /* status register */ BATTERY_INT_STATUS = 0x00, /* set this to enable IRQ */ BATTERY_INT_ENABLE = 0x04, BATTERY_AC_ONLINE = 0x08, BATTERY_STATUS = 0x0C, BATTERY_HEALTH = 0x10, BATTERY_PRESENT = 0x14, BATTERY_CAPACITY = 0x18, BATTERY_VOLTAGE = 0x1C, BATTERY_TEMP = 0x20, BATTERY_CHARGE_COUNTER = 0x24, BATTERY_VOLTAGE_MAX = 0x28, BATTERY_CURRENT_MAX = 0x2C, BATTERY_CURRENT_NOW = 0x30, BATTERY_CURRENT_AVG = 0x34, BATTERY_CHARGE_FULL_UAH = 0x38, BATTERY_CYCLE_COUNT = 0x40, BATTERY_STATUS_CHANGED = 1U << 0, AC_STATUS_CHANGED = 1U << 1, BATTERY_INT_MASK = BATTERY_STATUS_CHANGED | AC_STATUS_CHANGED, }; static int goldfish_ac_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct goldfish_battery_data *data = power_supply_get_drvdata(psy); int ret = 0; switch (psp) { case POWER_SUPPLY_PROP_ONLINE: val->intval = GOLDFISH_BATTERY_READ(data, BATTERY_AC_ONLINE); break; case POWER_SUPPLY_PROP_VOLTAGE_MAX: val->intval = GOLDFISH_BATTERY_READ(data, BATTERY_VOLTAGE_MAX); break; case POWER_SUPPLY_PROP_CURRENT_MAX: val->intval = GOLDFISH_BATTERY_READ(data, BATTERY_CURRENT_MAX); break; default: ret = -EINVAL; break; } return ret; } static int goldfish_battery_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct goldfish_battery_data *data = power_supply_get_drvdata(psy); int ret = 0; switch (psp) { case POWER_SUPPLY_PROP_STATUS: val->intval = GOLDFISH_BATTERY_READ(data, BATTERY_STATUS); break; case POWER_SUPPLY_PROP_HEALTH: val->intval = GOLDFISH_BATTERY_READ(data, BATTERY_HEALTH); break; case POWER_SUPPLY_PROP_PRESENT: val->intval = GOLDFISH_BATTERY_READ(data, BATTERY_PRESENT); break; case POWER_SUPPLY_PROP_TECHNOLOGY: val->intval = POWER_SUPPLY_TECHNOLOGY_LION; break; case POWER_SUPPLY_PROP_CAPACITY: val->intval = GOLDFISH_BATTERY_READ(data, BATTERY_CAPACITY); break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: val->intval = GOLDFISH_BATTERY_READ(data, BATTERY_VOLTAGE); break; case POWER_SUPPLY_PROP_TEMP: val->intval = GOLDFISH_BATTERY_READ(data, BATTERY_TEMP); break; case POWER_SUPPLY_PROP_CHARGE_COUNTER: val->intval = GOLDFISH_BATTERY_READ(data, BATTERY_CHARGE_COUNTER); break; case POWER_SUPPLY_PROP_CURRENT_NOW: val->intval = GOLDFISH_BATTERY_READ(data, BATTERY_CURRENT_NOW); break; case POWER_SUPPLY_PROP_CURRENT_AVG: val->intval = GOLDFISH_BATTERY_READ(data, BATTERY_CURRENT_AVG); break; case POWER_SUPPLY_PROP_CHARGE_FULL: val->intval = GOLDFISH_BATTERY_READ(data, BATTERY_CHARGE_FULL_UAH); break; case POWER_SUPPLY_PROP_CYCLE_COUNT: val->intval = GOLDFISH_BATTERY_READ(data, BATTERY_CYCLE_COUNT); break; default: ret = -EINVAL; break; } return ret; } static enum power_supply_property goldfish_battery_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_HEALTH, POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_TECHNOLOGY, POWER_SUPPLY_PROP_CAPACITY, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_TEMP, POWER_SUPPLY_PROP_CHARGE_COUNTER, POWER_SUPPLY_PROP_CURRENT_NOW, POWER_SUPPLY_PROP_CURRENT_AVG, POWER_SUPPLY_PROP_CHARGE_FULL, POWER_SUPPLY_PROP_CYCLE_COUNT, }; static enum power_supply_property goldfish_ac_props[] = { POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_VOLTAGE_MAX, POWER_SUPPLY_PROP_CURRENT_MAX, }; static irqreturn_t goldfish_battery_interrupt(int irq, void *dev_id) { unsigned long irq_flags; struct goldfish_battery_data *data = dev_id; uint32_t status; spin_lock_irqsave(&data->lock, irq_flags); /* read status flags, which will clear the interrupt */ status = GOLDFISH_BATTERY_READ(data, BATTERY_INT_STATUS); status &= BATTERY_INT_MASK; if (status & BATTERY_STATUS_CHANGED) power_supply_changed(data->battery); if (status & AC_STATUS_CHANGED) power_supply_changed(data->ac); spin_unlock_irqrestore(&data->lock, irq_flags); return status ? IRQ_HANDLED : IRQ_NONE; } static const struct power_supply_desc battery_desc = { .properties = goldfish_battery_props, .num_properties = ARRAY_SIZE(goldfish_battery_props), .get_property = goldfish_battery_get_property, .name = "battery", .type = POWER_SUPPLY_TYPE_BATTERY, }; static const struct power_supply_desc ac_desc = { .properties = goldfish_ac_props, .num_properties = ARRAY_SIZE(goldfish_ac_props), .get_property = goldfish_ac_get_property, .name = "ac", .type = POWER_SUPPLY_TYPE_MAINS, }; static int goldfish_battery_probe(struct platform_device *pdev) { int ret; struct resource *r; struct goldfish_battery_data *data; struct power_supply_config psy_cfg = {}; data = devm_kzalloc(&pdev->dev, sizeof(*data), GFP_KERNEL); if (data == NULL) return -ENOMEM; spin_lock_init(&data->lock); r = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (r == NULL) { dev_err(&pdev->dev, "platform_get_resource failed\n"); return -ENODEV; } data->reg_base = devm_ioremap(&pdev->dev, r->start, resource_size(r)); if (data->reg_base == NULL) { dev_err(&pdev->dev, "unable to remap MMIO\n"); return -ENOMEM; } data->irq = platform_get_irq(pdev, 0); if (data->irq < 0) return -ENODEV; ret = devm_request_irq(&pdev->dev, data->irq, goldfish_battery_interrupt, IRQF_SHARED, pdev->name, data); if (ret) return ret; psy_cfg.drv_data = data; data->ac = power_supply_register(&pdev->dev, &ac_desc, &psy_cfg); if (IS_ERR(data->ac)) return PTR_ERR(data->ac); data->battery = power_supply_register(&pdev->dev, &battery_desc, &psy_cfg); if (IS_ERR(data->battery)) { power_supply_unregister(data->ac); return PTR_ERR(data->battery); } platform_set_drvdata(pdev, data); GOLDFISH_BATTERY_WRITE(data, BATTERY_INT_ENABLE, BATTERY_INT_MASK); return 0; } static int goldfish_battery_remove(struct platform_device *pdev) { struct goldfish_battery_data *data = platform_get_drvdata(pdev); power_supply_unregister(data->battery); power_supply_unregister(data->ac); return 0; } static const struct of_device_id goldfish_battery_of_match[] = { { .compatible = "google,goldfish-battery", }, {}, }; MODULE_DEVICE_TABLE(of, goldfish_battery_of_match); #ifdef CONFIG_ACPI static const struct acpi_device_id goldfish_battery_acpi_match[] = { { "GFSH0001", 0 }, { }, }; MODULE_DEVICE_TABLE(acpi, goldfish_battery_acpi_match); #endif static struct platform_driver goldfish_battery_device = { .probe = goldfish_battery_probe, .remove = goldfish_battery_remove, .driver = { .name = "goldfish-battery", .of_match_table = goldfish_battery_of_match, .acpi_match_table = ACPI_PTR(goldfish_battery_acpi_match), } }; module_platform_driver(goldfish_battery_device); MODULE_AUTHOR("Mike Lockwood [email protected]"); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Battery driver for the Goldfish emulator");
linux-master
drivers/power/supply/goldfish_battery.c
// SPDX-License-Identifier: GPL-2.0+ /* * Power supply driver for the RICOH RN5T618 power management chip family * * Copyright (C) 2020 Andreas Kemnade */ #include <linux/kernel.h> #include <linux/device.h> #include <linux/bitops.h> #include <linux/errno.h> #include <linux/iio/consumer.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/mfd/rn5t618.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/regmap.h> #include <linux/slab.h> #define CHG_STATE_ADP_INPUT 0x40 #define CHG_STATE_USB_INPUT 0x80 #define CHG_STATE_MASK 0x1f #define CHG_STATE_CHG_OFF 0 #define CHG_STATE_CHG_READY_VADP 1 #define CHG_STATE_CHG_TRICKLE 2 #define CHG_STATE_CHG_RAPID 3 #define CHG_STATE_CHG_COMPLETE 4 #define CHG_STATE_SUSPEND 5 #define CHG_STATE_VCHG_OVER_VOL 6 #define CHG_STATE_BAT_ERROR 7 #define CHG_STATE_NO_BAT 8 #define CHG_STATE_BAT_OVER_VOL 9 #define CHG_STATE_BAT_TEMP_ERR 10 #define CHG_STATE_DIE_ERR 11 #define CHG_STATE_DIE_SHUTDOWN 12 #define CHG_STATE_NO_BAT2 13 #define CHG_STATE_CHG_READY_VUSB 14 #define GCHGDET_TYPE_MASK 0x30 #define GCHGDET_TYPE_SDP 0x00 #define GCHGDET_TYPE_CDP 0x10 #define GCHGDET_TYPE_DCP 0x20 #define FG_ENABLE 1 /* * Formula seems accurate for battery current, but for USB current around 70mA * per step was seen on Kobo Clara HD but all sources show the same formula * also fur USB current. To avoid accidentially unwanted high currents we stick * to that formula */ #define TO_CUR_REG(x) ((x) / 100000 - 1) #define FROM_CUR_REG(x) ((((x) & 0x1f) + 1) * 100000) #define CHG_MIN_CUR 100000 #define CHG_MAX_CUR 1800000 #define ADP_MAX_CUR 2500000 #define USB_MAX_CUR 1400000 struct rn5t618_power_info { struct rn5t618 *rn5t618; struct platform_device *pdev; struct power_supply *battery; struct power_supply *usb; struct power_supply *adp; struct iio_channel *channel_vusb; struct iio_channel *channel_vadp; int irq; }; static enum power_supply_usb_type rn5t618_usb_types[] = { POWER_SUPPLY_USB_TYPE_SDP, POWER_SUPPLY_USB_TYPE_DCP, POWER_SUPPLY_USB_TYPE_CDP, POWER_SUPPLY_USB_TYPE_UNKNOWN }; static enum power_supply_property rn5t618_usb_props[] = { /* input current limit is not very accurate */ POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_USB_TYPE, POWER_SUPPLY_PROP_ONLINE, }; static enum power_supply_property rn5t618_adp_props[] = { /* input current limit is not very accurate */ POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_ONLINE, }; static enum power_supply_property rn5t618_battery_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_CURRENT_NOW, POWER_SUPPLY_PROP_CAPACITY, POWER_SUPPLY_PROP_TEMP, POWER_SUPPLY_PROP_TIME_TO_EMPTY_NOW, POWER_SUPPLY_PROP_TIME_TO_FULL_NOW, POWER_SUPPLY_PROP_TECHNOLOGY, POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT, POWER_SUPPLY_PROP_CHARGE_FULL, POWER_SUPPLY_PROP_CHARGE_NOW, }; static int rn5t618_battery_read_doublereg(struct rn5t618_power_info *info, u8 reg, u16 *result) { int ret, i; u8 data[2]; u16 old, new; old = 0; /* Prevent races when registers are changing. */ for (i = 0; i < 3; i++) { ret = regmap_bulk_read(info->rn5t618->regmap, reg, data, sizeof(data)); if (ret) return ret; new = data[0] << 8; new |= data[1]; if (new == old) break; old = new; } *result = new; return 0; } static int rn5t618_decode_status(unsigned int status) { switch (status & CHG_STATE_MASK) { case CHG_STATE_CHG_OFF: case CHG_STATE_SUSPEND: case CHG_STATE_VCHG_OVER_VOL: case CHG_STATE_DIE_SHUTDOWN: return POWER_SUPPLY_STATUS_DISCHARGING; case CHG_STATE_CHG_TRICKLE: case CHG_STATE_CHG_RAPID: return POWER_SUPPLY_STATUS_CHARGING; case CHG_STATE_CHG_COMPLETE: return POWER_SUPPLY_STATUS_FULL; default: return POWER_SUPPLY_STATUS_NOT_CHARGING; } } static int rn5t618_battery_status(struct rn5t618_power_info *info, union power_supply_propval *val) { unsigned int v; int ret; ret = regmap_read(info->rn5t618->regmap, RN5T618_CHGSTATE, &v); if (ret) return ret; val->intval = POWER_SUPPLY_STATUS_UNKNOWN; if (v & 0xc0) { /* USB or ADP plugged */ val->intval = rn5t618_decode_status(v); } else val->intval = POWER_SUPPLY_STATUS_DISCHARGING; return ret; } static int rn5t618_battery_present(struct rn5t618_power_info *info, union power_supply_propval *val) { unsigned int v; int ret; ret = regmap_read(info->rn5t618->regmap, RN5T618_CHGSTATE, &v); if (ret) return ret; v &= CHG_STATE_MASK; if ((v == CHG_STATE_NO_BAT) || (v == CHG_STATE_NO_BAT2)) val->intval = 0; else val->intval = 1; return ret; } static int rn5t618_battery_voltage_now(struct rn5t618_power_info *info, union power_supply_propval *val) { u16 res; int ret; ret = rn5t618_battery_read_doublereg(info, RN5T618_VOLTAGE_1, &res); if (ret) return ret; val->intval = res * 2 * 2500 / 4095 * 1000; return 0; } static int rn5t618_battery_current_now(struct rn5t618_power_info *info, union power_supply_propval *val) { u16 res; int ret; ret = rn5t618_battery_read_doublereg(info, RN5T618_CC_AVEREG1, &res); if (ret) return ret; /* current is negative when discharging */ val->intval = sign_extend32(res, 13) * 1000; return 0; } static int rn5t618_battery_capacity(struct rn5t618_power_info *info, union power_supply_propval *val) { unsigned int v; int ret; ret = regmap_read(info->rn5t618->regmap, RN5T618_SOC, &v); if (ret) return ret; val->intval = v; return 0; } static int rn5t618_battery_temp(struct rn5t618_power_info *info, union power_supply_propval *val) { u16 res; int ret; ret = rn5t618_battery_read_doublereg(info, RN5T618_TEMP_1, &res); if (ret) return ret; val->intval = sign_extend32(res, 11) * 10 / 16; return 0; } static int rn5t618_battery_tte(struct rn5t618_power_info *info, union power_supply_propval *val) { u16 res; int ret; ret = rn5t618_battery_read_doublereg(info, RN5T618_TT_EMPTY_H, &res); if (ret) return ret; if (res == 65535) return -ENODATA; val->intval = res * 60; return 0; } static int rn5t618_battery_ttf(struct rn5t618_power_info *info, union power_supply_propval *val) { u16 res; int ret; ret = rn5t618_battery_read_doublereg(info, RN5T618_TT_FULL_H, &res); if (ret) return ret; if (res == 65535) return -ENODATA; val->intval = res * 60; return 0; } static int rn5t618_battery_set_current_limit(struct rn5t618_power_info *info, const union power_supply_propval *val) { if (val->intval < CHG_MIN_CUR) return -EINVAL; if (val->intval >= CHG_MAX_CUR) return -EINVAL; return regmap_update_bits(info->rn5t618->regmap, RN5T618_CHGISET, 0x1F, TO_CUR_REG(val->intval)); } static int rn5t618_battery_get_current_limit(struct rn5t618_power_info *info, union power_supply_propval *val) { unsigned int regval; int ret; ret = regmap_read(info->rn5t618->regmap, RN5T618_CHGISET, &regval); if (ret < 0) return ret; val->intval = FROM_CUR_REG(regval); return 0; } static int rn5t618_battery_charge_full(struct rn5t618_power_info *info, union power_supply_propval *val) { u16 res; int ret; ret = rn5t618_battery_read_doublereg(info, RN5T618_FA_CAP_H, &res); if (ret) return ret; val->intval = res * 1000; return 0; } static int rn5t618_battery_charge_now(struct rn5t618_power_info *info, union power_supply_propval *val) { u16 res; int ret; ret = rn5t618_battery_read_doublereg(info, RN5T618_RE_CAP_H, &res); if (ret) return ret; val->intval = res * 1000; return 0; } static int rn5t618_battery_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { int ret = 0; struct rn5t618_power_info *info = power_supply_get_drvdata(psy); switch (psp) { case POWER_SUPPLY_PROP_STATUS: ret = rn5t618_battery_status(info, val); break; case POWER_SUPPLY_PROP_PRESENT: ret = rn5t618_battery_present(info, val); break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: ret = rn5t618_battery_voltage_now(info, val); break; case POWER_SUPPLY_PROP_CURRENT_NOW: ret = rn5t618_battery_current_now(info, val); break; case POWER_SUPPLY_PROP_CAPACITY: ret = rn5t618_battery_capacity(info, val); break; case POWER_SUPPLY_PROP_TEMP: ret = rn5t618_battery_temp(info, val); break; case POWER_SUPPLY_PROP_TIME_TO_EMPTY_NOW: ret = rn5t618_battery_tte(info, val); break; case POWER_SUPPLY_PROP_TIME_TO_FULL_NOW: ret = rn5t618_battery_ttf(info, val); break; case POWER_SUPPLY_PROP_TECHNOLOGY: val->intval = POWER_SUPPLY_TECHNOLOGY_LION; break; case POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT: ret = rn5t618_battery_get_current_limit(info, val); break; case POWER_SUPPLY_PROP_CHARGE_FULL: ret = rn5t618_battery_charge_full(info, val); break; case POWER_SUPPLY_PROP_CHARGE_NOW: ret = rn5t618_battery_charge_now(info, val); break; default: return -EINVAL; } return ret; } static int rn5t618_battery_set_property(struct power_supply *psy, enum power_supply_property psp, const union power_supply_propval *val) { struct rn5t618_power_info *info = power_supply_get_drvdata(psy); switch (psp) { case POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT: return rn5t618_battery_set_current_limit(info, val); default: return -EINVAL; } } static int rn5t618_battery_property_is_writeable(struct power_supply *psy, enum power_supply_property psp) { switch (psp) { case POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT: return true; default: return false; } } static int rn5t618_adp_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct rn5t618_power_info *info = power_supply_get_drvdata(psy); unsigned int chgstate; unsigned int regval; bool online; int ret; ret = regmap_read(info->rn5t618->regmap, RN5T618_CHGSTATE, &chgstate); if (ret) return ret; online = !!(chgstate & CHG_STATE_ADP_INPUT); switch (psp) { case POWER_SUPPLY_PROP_ONLINE: val->intval = online; break; case POWER_SUPPLY_PROP_STATUS: if (!online) { val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING; break; } val->intval = rn5t618_decode_status(chgstate); if (val->intval != POWER_SUPPLY_STATUS_CHARGING) val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING; break; case POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT: ret = regmap_read(info->rn5t618->regmap, RN5T618_REGISET1, &regval); if (ret < 0) return ret; val->intval = FROM_CUR_REG(regval); break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: if (!info->channel_vadp) return -ENODATA; ret = iio_read_channel_processed_scale(info->channel_vadp, &val->intval, 1000); if (ret < 0) return ret; break; default: return -EINVAL; } return 0; } static int rn5t618_adp_set_property(struct power_supply *psy, enum power_supply_property psp, const union power_supply_propval *val) { struct rn5t618_power_info *info = power_supply_get_drvdata(psy); int ret; switch (psp) { case POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT: if (val->intval > ADP_MAX_CUR) return -EINVAL; if (val->intval < CHG_MIN_CUR) return -EINVAL; ret = regmap_write(info->rn5t618->regmap, RN5T618_REGISET1, TO_CUR_REG(val->intval)); if (ret < 0) return ret; break; default: return -EINVAL; } return 0; } static int rn5t618_adp_property_is_writeable(struct power_supply *psy, enum power_supply_property psp) { switch (psp) { case POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT: return true; default: return false; } } static int rc5t619_usb_get_type(struct rn5t618_power_info *info, union power_supply_propval *val) { unsigned int regval; int ret; ret = regmap_read(info->rn5t618->regmap, RN5T618_GCHGDET, &regval); if (ret < 0) return ret; switch (regval & GCHGDET_TYPE_MASK) { case GCHGDET_TYPE_SDP: val->intval = POWER_SUPPLY_USB_TYPE_SDP; break; case GCHGDET_TYPE_CDP: val->intval = POWER_SUPPLY_USB_TYPE_CDP; break; case GCHGDET_TYPE_DCP: val->intval = POWER_SUPPLY_USB_TYPE_DCP; break; default: val->intval = POWER_SUPPLY_USB_TYPE_UNKNOWN; } return 0; } static int rn5t618_usb_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct rn5t618_power_info *info = power_supply_get_drvdata(psy); unsigned int chgstate; unsigned int regval; bool online; int ret; ret = regmap_read(info->rn5t618->regmap, RN5T618_CHGSTATE, &chgstate); if (ret) return ret; online = !!(chgstate & CHG_STATE_USB_INPUT); switch (psp) { case POWER_SUPPLY_PROP_ONLINE: val->intval = online; break; case POWER_SUPPLY_PROP_STATUS: if (!online) { val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING; break; } val->intval = rn5t618_decode_status(chgstate); if (val->intval != POWER_SUPPLY_STATUS_CHARGING) val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING; break; case POWER_SUPPLY_PROP_USB_TYPE: if (!online || (info->rn5t618->variant != RC5T619)) return -ENODATA; return rc5t619_usb_get_type(info, val); case POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT: ret = regmap_read(info->rn5t618->regmap, RN5T618_CHGCTL1, &regval); if (ret < 0) return ret; val->intval = 0; if (regval & 2) { ret = regmap_read(info->rn5t618->regmap, RN5T618_REGISET2, &regval); if (ret < 0) return ret; val->intval = FROM_CUR_REG(regval); } break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: if (!info->channel_vusb) return -ENODATA; ret = iio_read_channel_processed_scale(info->channel_vusb, &val->intval, 1000); if (ret < 0) return ret; break; default: return -EINVAL; } return 0; } static int rn5t618_usb_set_property(struct power_supply *psy, enum power_supply_property psp, const union power_supply_propval *val) { struct rn5t618_power_info *info = power_supply_get_drvdata(psy); int ret; switch (psp) { case POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT: if (val->intval > USB_MAX_CUR) return -EINVAL; if (val->intval < CHG_MIN_CUR) return -EINVAL; ret = regmap_write(info->rn5t618->regmap, RN5T618_REGISET2, 0xE0 | TO_CUR_REG(val->intval)); if (ret < 0) return ret; break; default: return -EINVAL; } return 0; } static int rn5t618_usb_property_is_writeable(struct power_supply *psy, enum power_supply_property psp) { switch (psp) { case POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT: return true; default: return false; } } static const struct power_supply_desc rn5t618_battery_desc = { .name = "rn5t618-battery", .type = POWER_SUPPLY_TYPE_BATTERY, .properties = rn5t618_battery_props, .num_properties = ARRAY_SIZE(rn5t618_battery_props), .get_property = rn5t618_battery_get_property, .set_property = rn5t618_battery_set_property, .property_is_writeable = rn5t618_battery_property_is_writeable, }; static const struct power_supply_desc rn5t618_adp_desc = { .name = "rn5t618-adp", .type = POWER_SUPPLY_TYPE_MAINS, .properties = rn5t618_adp_props, .num_properties = ARRAY_SIZE(rn5t618_adp_props), .get_property = rn5t618_adp_get_property, .set_property = rn5t618_adp_set_property, .property_is_writeable = rn5t618_adp_property_is_writeable, }; static const struct power_supply_desc rn5t618_usb_desc = { .name = "rn5t618-usb", .type = POWER_SUPPLY_TYPE_USB, .usb_types = rn5t618_usb_types, .num_usb_types = ARRAY_SIZE(rn5t618_usb_types), .properties = rn5t618_usb_props, .num_properties = ARRAY_SIZE(rn5t618_usb_props), .get_property = rn5t618_usb_get_property, .set_property = rn5t618_usb_set_property, .property_is_writeable = rn5t618_usb_property_is_writeable, }; static irqreturn_t rn5t618_charger_irq(int irq, void *data) { struct device *dev = data; struct rn5t618_power_info *info = dev_get_drvdata(dev); unsigned int ctrl, stat1, stat2, err; regmap_read(info->rn5t618->regmap, RN5T618_CHGERR_IRR, &err); regmap_read(info->rn5t618->regmap, RN5T618_CHGCTRL_IRR, &ctrl); regmap_read(info->rn5t618->regmap, RN5T618_CHGSTAT_IRR1, &stat1); regmap_read(info->rn5t618->regmap, RN5T618_CHGSTAT_IRR2, &stat2); regmap_write(info->rn5t618->regmap, RN5T618_CHGERR_IRR, 0); regmap_write(info->rn5t618->regmap, RN5T618_CHGCTRL_IRR, 0); regmap_write(info->rn5t618->regmap, RN5T618_CHGSTAT_IRR1, 0); regmap_write(info->rn5t618->regmap, RN5T618_CHGSTAT_IRR2, 0); dev_dbg(dev, "chgerr: %x chgctrl: %x chgstat: %x chgstat2: %x\n", err, ctrl, stat1, stat2); power_supply_changed(info->usb); power_supply_changed(info->adp); power_supply_changed(info->battery); return IRQ_HANDLED; } static int rn5t618_power_probe(struct platform_device *pdev) { int ret = 0; unsigned int v; struct power_supply_config psy_cfg = {}; struct rn5t618_power_info *info; info = devm_kzalloc(&pdev->dev, sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; info->pdev = pdev; info->rn5t618 = dev_get_drvdata(pdev->dev.parent); info->irq = -1; platform_set_drvdata(pdev, info); info->channel_vusb = devm_iio_channel_get(&pdev->dev, "vusb"); if (IS_ERR(info->channel_vusb)) { if (PTR_ERR(info->channel_vusb) == -ENODEV) return -EPROBE_DEFER; return PTR_ERR(info->channel_vusb); } info->channel_vadp = devm_iio_channel_get(&pdev->dev, "vadp"); if (IS_ERR(info->channel_vadp)) { if (PTR_ERR(info->channel_vadp) == -ENODEV) return -EPROBE_DEFER; return PTR_ERR(info->channel_vadp); } ret = regmap_read(info->rn5t618->regmap, RN5T618_CONTROL, &v); if (ret) return ret; if (!(v & FG_ENABLE)) { /* E.g. the vendor kernels of various Kobo and Tolino Ebook * readers disable the fuel gauge on shutdown. If a kernel * without fuel gauge support is booted after that, the fuel * gauge will get decalibrated. */ dev_info(&pdev->dev, "Fuel gauge not enabled, enabling now\n"); dev_info(&pdev->dev, "Expect imprecise results\n"); regmap_update_bits(info->rn5t618->regmap, RN5T618_CONTROL, FG_ENABLE, FG_ENABLE); } psy_cfg.drv_data = info; info->battery = devm_power_supply_register(&pdev->dev, &rn5t618_battery_desc, &psy_cfg); if (IS_ERR(info->battery)) { ret = PTR_ERR(info->battery); dev_err(&pdev->dev, "failed to register battery: %d\n", ret); return ret; } info->adp = devm_power_supply_register(&pdev->dev, &rn5t618_adp_desc, &psy_cfg); if (IS_ERR(info->adp)) { ret = PTR_ERR(info->adp); dev_err(&pdev->dev, "failed to register adp: %d\n", ret); return ret; } info->usb = devm_power_supply_register(&pdev->dev, &rn5t618_usb_desc, &psy_cfg); if (IS_ERR(info->usb)) { ret = PTR_ERR(info->usb); dev_err(&pdev->dev, "failed to register usb: %d\n", ret); return ret; } if (info->rn5t618->irq_data) info->irq = regmap_irq_get_virq(info->rn5t618->irq_data, RN5T618_IRQ_CHG); if (info->irq < 0) info->irq = -1; else { ret = devm_request_threaded_irq(&pdev->dev, info->irq, NULL, rn5t618_charger_irq, IRQF_ONESHOT, "rn5t618_power", &pdev->dev); if (ret < 0) { dev_err(&pdev->dev, "request IRQ:%d fail\n", info->irq); info->irq = -1; } } return 0; } static struct platform_driver rn5t618_power_driver = { .driver = { .name = "rn5t618-power", }, .probe = rn5t618_power_probe, }; module_platform_driver(rn5t618_power_driver); MODULE_ALIAS("platform:rn5t618-power"); MODULE_DESCRIPTION("Power supply driver for RICOH RN5T618"); MODULE_LICENSE("GPL");
linux-master
drivers/power/supply/rn5t618_power.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * ISP1704 USB Charger Detection driver * * Copyright (C) 2010 Nokia Corporation * Copyright (C) 2012 - 2013 Pali Rohár <[email protected]> */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/err.h> #include <linux/init.h> #include <linux/types.h> #include <linux/device.h> #include <linux/sysfs.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/delay.h> #include <linux/of.h> #include <linux/gpio/consumer.h> #include <linux/usb/otg.h> #include <linux/usb/ulpi.h> #include <linux/usb/ch9.h> #include <linux/usb/gadget.h> /* Vendor specific Power Control register */ #define ISP1704_PWR_CTRL 0x3d #define ISP1704_PWR_CTRL_SWCTRL (1 << 0) #define ISP1704_PWR_CTRL_DET_COMP (1 << 1) #define ISP1704_PWR_CTRL_BVALID_RISE (1 << 2) #define ISP1704_PWR_CTRL_BVALID_FALL (1 << 3) #define ISP1704_PWR_CTRL_DP_WKPU_EN (1 << 4) #define ISP1704_PWR_CTRL_VDAT_DET (1 << 5) #define ISP1704_PWR_CTRL_DPVSRC_EN (1 << 6) #define ISP1704_PWR_CTRL_HWDETECT (1 << 7) #define NXP_VENDOR_ID 0x04cc static u16 isp170x_id[] = { 0x1704, 0x1707, }; struct isp1704_charger { struct device *dev; struct power_supply *psy; struct power_supply_desc psy_desc; struct gpio_desc *enable_gpio; struct usb_phy *phy; struct notifier_block nb; struct work_struct work; /* properties */ char model[8]; unsigned present:1; unsigned online:1; unsigned current_max; }; static inline int isp1704_read(struct isp1704_charger *isp, u32 reg) { return usb_phy_io_read(isp->phy, reg); } static inline int isp1704_write(struct isp1704_charger *isp, u32 reg, u32 val) { return usb_phy_io_write(isp->phy, val, reg); } static void isp1704_charger_set_power(struct isp1704_charger *isp, bool on) { gpiod_set_value(isp->enable_gpio, on); } /* * Determine is the charging port DCP (dedicated charger) or CDP (Host/HUB * chargers). * * REVISIT: The method is defined in Battery Charging Specification and is * applicable to any ULPI transceiver. Nothing isp170x specific here. */ static inline int isp1704_charger_type(struct isp1704_charger *isp) { u8 reg; u8 func_ctrl; u8 otg_ctrl; int type = POWER_SUPPLY_TYPE_USB_DCP; func_ctrl = isp1704_read(isp, ULPI_FUNC_CTRL); otg_ctrl = isp1704_read(isp, ULPI_OTG_CTRL); /* disable pulldowns */ reg = ULPI_OTG_CTRL_DM_PULLDOWN | ULPI_OTG_CTRL_DP_PULLDOWN; isp1704_write(isp, ULPI_CLR(ULPI_OTG_CTRL), reg); /* full speed */ isp1704_write(isp, ULPI_CLR(ULPI_FUNC_CTRL), ULPI_FUNC_CTRL_XCVRSEL_MASK); isp1704_write(isp, ULPI_SET(ULPI_FUNC_CTRL), ULPI_FUNC_CTRL_FULL_SPEED); /* Enable strong pull-up on DP (1.5K) and reset */ reg = ULPI_FUNC_CTRL_TERMSELECT | ULPI_FUNC_CTRL_RESET; isp1704_write(isp, ULPI_SET(ULPI_FUNC_CTRL), reg); usleep_range(1000, 2000); reg = isp1704_read(isp, ULPI_DEBUG); if ((reg & 3) != 3) type = POWER_SUPPLY_TYPE_USB_CDP; /* recover original state */ isp1704_write(isp, ULPI_FUNC_CTRL, func_ctrl); isp1704_write(isp, ULPI_OTG_CTRL, otg_ctrl); return type; } /* * ISP1704 detects PS/2 adapters as charger. To make sure the detected charger * is actually a dedicated charger, the following steps need to be taken. */ static inline int isp1704_charger_verify(struct isp1704_charger *isp) { int ret = 0; u8 r; /* Reset the transceiver */ r = isp1704_read(isp, ULPI_FUNC_CTRL); r |= ULPI_FUNC_CTRL_RESET; isp1704_write(isp, ULPI_FUNC_CTRL, r); usleep_range(1000, 2000); /* Set normal mode */ r &= ~(ULPI_FUNC_CTRL_RESET | ULPI_FUNC_CTRL_OPMODE_MASK); isp1704_write(isp, ULPI_FUNC_CTRL, r); /* Clear the DP and DM pull-down bits */ r = ULPI_OTG_CTRL_DP_PULLDOWN | ULPI_OTG_CTRL_DM_PULLDOWN; isp1704_write(isp, ULPI_CLR(ULPI_OTG_CTRL), r); /* Enable strong pull-up on DP (1.5K) and reset */ r = ULPI_FUNC_CTRL_TERMSELECT | ULPI_FUNC_CTRL_RESET; isp1704_write(isp, ULPI_SET(ULPI_FUNC_CTRL), r); usleep_range(1000, 2000); /* Read the line state */ if (!isp1704_read(isp, ULPI_DEBUG)) { /* Disable strong pull-up on DP (1.5K) */ isp1704_write(isp, ULPI_CLR(ULPI_FUNC_CTRL), ULPI_FUNC_CTRL_TERMSELECT); return 1; } /* Is it a charger or PS/2 connection */ /* Enable weak pull-up resistor on DP */ isp1704_write(isp, ULPI_SET(ISP1704_PWR_CTRL), ISP1704_PWR_CTRL_DP_WKPU_EN); /* Disable strong pull-up on DP (1.5K) */ isp1704_write(isp, ULPI_CLR(ULPI_FUNC_CTRL), ULPI_FUNC_CTRL_TERMSELECT); /* Enable weak pull-down resistor on DM */ isp1704_write(isp, ULPI_SET(ULPI_OTG_CTRL), ULPI_OTG_CTRL_DM_PULLDOWN); /* It's a charger if the line states are clear */ if (!(isp1704_read(isp, ULPI_DEBUG))) ret = 1; /* Disable weak pull-up resistor on DP */ isp1704_write(isp, ULPI_CLR(ISP1704_PWR_CTRL), ISP1704_PWR_CTRL_DP_WKPU_EN); return ret; } static inline int isp1704_charger_detect(struct isp1704_charger *isp) { unsigned long timeout; u8 pwr_ctrl; int ret = 0; pwr_ctrl = isp1704_read(isp, ISP1704_PWR_CTRL); /* set SW control bit in PWR_CTRL register */ isp1704_write(isp, ISP1704_PWR_CTRL, ISP1704_PWR_CTRL_SWCTRL); /* enable manual charger detection */ isp1704_write(isp, ULPI_SET(ISP1704_PWR_CTRL), ISP1704_PWR_CTRL_SWCTRL | ISP1704_PWR_CTRL_DPVSRC_EN); usleep_range(1000, 2000); timeout = jiffies + msecs_to_jiffies(300); do { /* Check if there is a charger */ if (isp1704_read(isp, ISP1704_PWR_CTRL) & ISP1704_PWR_CTRL_VDAT_DET) { ret = isp1704_charger_verify(isp); break; } } while (!time_after(jiffies, timeout) && isp->online); /* recover original state */ isp1704_write(isp, ISP1704_PWR_CTRL, pwr_ctrl); return ret; } static inline int isp1704_charger_detect_dcp(struct isp1704_charger *isp) { if (isp1704_charger_detect(isp) && isp1704_charger_type(isp) == POWER_SUPPLY_TYPE_USB_DCP) return true; else return false; } static void isp1704_charger_work(struct work_struct *data) { struct isp1704_charger *isp = container_of(data, struct isp1704_charger, work); static DEFINE_MUTEX(lock); mutex_lock(&lock); switch (isp->phy->last_event) { case USB_EVENT_VBUS: /* do not call wall charger detection more times */ if (!isp->present) { isp->online = true; isp->present = 1; isp1704_charger_set_power(isp, 1); /* detect wall charger */ if (isp1704_charger_detect_dcp(isp)) { isp->psy_desc.type = POWER_SUPPLY_TYPE_USB_DCP; isp->current_max = 1800; } else { isp->psy_desc.type = POWER_SUPPLY_TYPE_USB; isp->current_max = 500; } /* enable data pullups */ if (isp->phy->otg->gadget) usb_gadget_connect(isp->phy->otg->gadget); } if (isp->psy_desc.type != POWER_SUPPLY_TYPE_USB_DCP) { /* * Only 500mA here or high speed chirp * handshaking may break */ if (isp->current_max > 500) isp->current_max = 500; if (isp->current_max > 100) isp->psy_desc.type = POWER_SUPPLY_TYPE_USB_CDP; } break; case USB_EVENT_NONE: isp->online = false; isp->present = 0; isp->current_max = 0; isp->psy_desc.type = POWER_SUPPLY_TYPE_USB; /* * Disable data pullups. We need to prevent the controller from * enumerating. * * FIXME: This is here to allow charger detection with Host/HUB * chargers. The pullups may be enabled elsewhere, so this can * not be the final solution. */ if (isp->phy->otg->gadget) usb_gadget_disconnect(isp->phy->otg->gadget); isp1704_charger_set_power(isp, 0); break; default: goto out; } power_supply_changed(isp->psy); out: mutex_unlock(&lock); } static int isp1704_notifier_call(struct notifier_block *nb, unsigned long val, void *v) { struct isp1704_charger *isp = container_of(nb, struct isp1704_charger, nb); schedule_work(&isp->work); return NOTIFY_OK; } static int isp1704_charger_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct isp1704_charger *isp = power_supply_get_drvdata(psy); switch (psp) { case POWER_SUPPLY_PROP_PRESENT: val->intval = isp->present; break; case POWER_SUPPLY_PROP_ONLINE: val->intval = isp->online; break; case POWER_SUPPLY_PROP_CURRENT_MAX: val->intval = isp->current_max; break; case POWER_SUPPLY_PROP_MODEL_NAME: val->strval = isp->model; break; case POWER_SUPPLY_PROP_MANUFACTURER: val->strval = "NXP"; break; default: return -EINVAL; } return 0; } static enum power_supply_property power_props[] = { POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_CURRENT_MAX, POWER_SUPPLY_PROP_MODEL_NAME, POWER_SUPPLY_PROP_MANUFACTURER, }; static inline int isp1704_test_ulpi(struct isp1704_charger *isp) { int vendor; int product; int i; int ret; /* Test ULPI interface */ ret = isp1704_write(isp, ULPI_SCRATCH, 0xaa); if (ret < 0) return ret; ret = isp1704_read(isp, ULPI_SCRATCH); if (ret < 0) return ret; if (ret != 0xaa) return -ENODEV; /* Verify the product and vendor id matches */ vendor = isp1704_read(isp, ULPI_VENDOR_ID_LOW); vendor |= isp1704_read(isp, ULPI_VENDOR_ID_HIGH) << 8; if (vendor != NXP_VENDOR_ID) return -ENODEV; product = isp1704_read(isp, ULPI_PRODUCT_ID_LOW); product |= isp1704_read(isp, ULPI_PRODUCT_ID_HIGH) << 8; for (i = 0; i < ARRAY_SIZE(isp170x_id); i++) { if (product == isp170x_id[i]) { sprintf(isp->model, "isp%x", product); return product; } } dev_err(isp->dev, "product id %x not matching known ids", product); return -ENODEV; } static int isp1704_charger_probe(struct platform_device *pdev) { struct isp1704_charger *isp; int ret = -ENODEV; struct power_supply_config psy_cfg = {}; isp = devm_kzalloc(&pdev->dev, sizeof(*isp), GFP_KERNEL); if (!isp) return -ENOMEM; isp->enable_gpio = devm_gpiod_get(&pdev->dev, "nxp,enable", GPIOD_OUT_HIGH); if (IS_ERR(isp->enable_gpio)) { ret = PTR_ERR(isp->enable_gpio); dev_err(&pdev->dev, "Could not get reset gpio: %d\n", ret); return ret; } if (pdev->dev.of_node) isp->phy = devm_usb_get_phy_by_phandle(&pdev->dev, "usb-phy", 0); else isp->phy = devm_usb_get_phy(&pdev->dev, USB_PHY_TYPE_USB2); if (IS_ERR(isp->phy)) { ret = PTR_ERR(isp->phy); dev_err(&pdev->dev, "usb_get_phy failed\n"); goto fail0; } isp->dev = &pdev->dev; platform_set_drvdata(pdev, isp); isp1704_charger_set_power(isp, 1); ret = isp1704_test_ulpi(isp); if (ret < 0) { dev_err(&pdev->dev, "isp1704_test_ulpi failed\n"); goto fail1; } isp->psy_desc.name = "isp1704"; isp->psy_desc.type = POWER_SUPPLY_TYPE_USB; isp->psy_desc.properties = power_props; isp->psy_desc.num_properties = ARRAY_SIZE(power_props); isp->psy_desc.get_property = isp1704_charger_get_property; psy_cfg.drv_data = isp; isp->psy = power_supply_register(isp->dev, &isp->psy_desc, &psy_cfg); if (IS_ERR(isp->psy)) { ret = PTR_ERR(isp->psy); dev_err(&pdev->dev, "power_supply_register failed\n"); goto fail1; } /* * REVISIT: using work in order to allow the usb notifications to be * made atomically in the future. */ INIT_WORK(&isp->work, isp1704_charger_work); isp->nb.notifier_call = isp1704_notifier_call; ret = usb_register_notifier(isp->phy, &isp->nb); if (ret) { dev_err(&pdev->dev, "usb_register_notifier failed\n"); goto fail2; } dev_info(isp->dev, "registered with product id %s\n", isp->model); /* * Taking over the D+ pullup. * * FIXME: The device will be disconnected if it was already * enumerated. The charger driver should be always loaded before any * gadget is loaded. */ if (isp->phy->otg->gadget) usb_gadget_disconnect(isp->phy->otg->gadget); if (isp->phy->last_event == USB_EVENT_NONE) isp1704_charger_set_power(isp, 0); /* Detect charger if VBUS is valid (the cable was already plugged). */ if (isp->phy->last_event == USB_EVENT_VBUS && !isp->phy->otg->default_a) schedule_work(&isp->work); return 0; fail2: power_supply_unregister(isp->psy); fail1: isp1704_charger_set_power(isp, 0); fail0: dev_err(&pdev->dev, "failed to register isp1704 with error %d\n", ret); return ret; } static int isp1704_charger_remove(struct platform_device *pdev) { struct isp1704_charger *isp = platform_get_drvdata(pdev); usb_unregister_notifier(isp->phy, &isp->nb); power_supply_unregister(isp->psy); isp1704_charger_set_power(isp, 0); return 0; } #ifdef CONFIG_OF static const struct of_device_id omap_isp1704_of_match[] = { { .compatible = "nxp,isp1704", }, { .compatible = "nxp,isp1707", }, {}, }; MODULE_DEVICE_TABLE(of, omap_isp1704_of_match); #endif static struct platform_driver isp1704_charger_driver = { .driver = { .name = "isp1704_charger", .of_match_table = of_match_ptr(omap_isp1704_of_match), }, .probe = isp1704_charger_probe, .remove = isp1704_charger_remove, }; module_platform_driver(isp1704_charger_driver); MODULE_ALIAS("platform:isp1704_charger"); MODULE_AUTHOR("Nokia Corporation"); MODULE_DESCRIPTION("ISP170x USB Charger driver"); MODULE_LICENSE("GPL");
linux-master
drivers/power/supply/isp1704_charger.c
// SPDX-License-Identifier: GPL-2.0+ // // max14577_charger.c - Battery charger driver for the Maxim 14577/77836 // // Copyright (C) 2013,2014 Samsung Electronics // Krzysztof Kozlowski <[email protected]> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/mfd/max14577-private.h> #include <linux/mfd/max14577.h> struct max14577_charger { struct device *dev; struct max14577 *max14577; struct power_supply *charger; struct max14577_charger_platform_data *pdata; }; /* * Helper function for mapping values of STATUS2/CHGTYP register on max14577 * and max77836 chipsets to enum maxim_muic_charger_type. */ static enum max14577_muic_charger_type maxim_get_charger_type( enum maxim_device_type dev_type, u8 val) { switch (val) { case MAX14577_CHARGER_TYPE_NONE: case MAX14577_CHARGER_TYPE_USB: case MAX14577_CHARGER_TYPE_DOWNSTREAM_PORT: case MAX14577_CHARGER_TYPE_DEDICATED_CHG: case MAX14577_CHARGER_TYPE_SPECIAL_500MA: case MAX14577_CHARGER_TYPE_SPECIAL_1A: return val; case MAX14577_CHARGER_TYPE_DEAD_BATTERY: case MAX14577_CHARGER_TYPE_RESERVED: if (dev_type == MAXIM_DEVICE_TYPE_MAX77836) val |= 0x8; return val; default: WARN_ONCE(1, "max14577: Unsupported chgtyp register value 0x%02x", val); return val; } } static int max14577_get_charger_state(struct max14577_charger *chg, int *val) { struct regmap *rmap = chg->max14577->regmap; int ret; u8 reg_data; /* * Charging occurs only if: * - CHGCTRL2/MBCHOSTEN == 1 * - STATUS2/CGMBC == 1 * * TODO: * - handle FULL after Top-off timer (EOC register may be off * and the charger won't be charging although MBCHOSTEN is on) * - handle properly dead-battery charging (respect timer) * - handle timers (fast-charge and prequal) /MBCCHGERR/ */ ret = max14577_read_reg(rmap, MAX14577_CHG_REG_CHG_CTRL2, &reg_data); if (ret < 0) goto out; if ((reg_data & CHGCTRL2_MBCHOSTEN_MASK) == 0) { *val = POWER_SUPPLY_STATUS_DISCHARGING; goto out; } ret = max14577_read_reg(rmap, MAX14577_CHG_REG_STATUS3, &reg_data); if (ret < 0) goto out; if (reg_data & STATUS3_CGMBC_MASK) { /* Charger or USB-cable is connected */ if (reg_data & STATUS3_EOC_MASK) *val = POWER_SUPPLY_STATUS_FULL; else *val = POWER_SUPPLY_STATUS_CHARGING; goto out; } *val = POWER_SUPPLY_STATUS_DISCHARGING; out: return ret; } /* * Supported charge types: * - POWER_SUPPLY_CHARGE_TYPE_NONE * - POWER_SUPPLY_CHARGE_TYPE_FAST */ static int max14577_get_charge_type(struct max14577_charger *chg, int *val) { int ret, charging; /* * TODO: CHARGE_TYPE_TRICKLE (VCHGR_RC or EOC)? * As spec says: * [after reaching EOC interrupt] * "When the battery is fully charged, the 30-minute (typ) * top-off timer starts. The device continues to trickle * charge the battery until the top-off timer runs out." */ ret = max14577_get_charger_state(chg, &charging); if (ret < 0) return ret; if (charging == POWER_SUPPLY_STATUS_CHARGING) *val = POWER_SUPPLY_CHARGE_TYPE_FAST; else *val = POWER_SUPPLY_CHARGE_TYPE_NONE; return 0; } static int max14577_get_online(struct max14577_charger *chg, int *val) { struct regmap *rmap = chg->max14577->regmap; u8 reg_data; int ret; enum max14577_muic_charger_type chg_type; ret = max14577_read_reg(rmap, MAX14577_MUIC_REG_STATUS2, &reg_data); if (ret < 0) return ret; reg_data = ((reg_data & STATUS2_CHGTYP_MASK) >> STATUS2_CHGTYP_SHIFT); chg_type = maxim_get_charger_type(chg->max14577->dev_type, reg_data); switch (chg_type) { case MAX14577_CHARGER_TYPE_USB: case MAX14577_CHARGER_TYPE_DEDICATED_CHG: case MAX14577_CHARGER_TYPE_SPECIAL_500MA: case MAX14577_CHARGER_TYPE_SPECIAL_1A: case MAX14577_CHARGER_TYPE_DEAD_BATTERY: case MAX77836_CHARGER_TYPE_SPECIAL_BIAS: *val = 1; break; case MAX14577_CHARGER_TYPE_NONE: case MAX14577_CHARGER_TYPE_DOWNSTREAM_PORT: case MAX14577_CHARGER_TYPE_RESERVED: case MAX77836_CHARGER_TYPE_RESERVED: default: *val = 0; } return 0; } /* * Supported health statuses: * - POWER_SUPPLY_HEALTH_DEAD * - POWER_SUPPLY_HEALTH_OVERVOLTAGE * - POWER_SUPPLY_HEALTH_GOOD */ static int max14577_get_battery_health(struct max14577_charger *chg, int *val) { struct regmap *rmap = chg->max14577->regmap; int ret; u8 reg_data; enum max14577_muic_charger_type chg_type; ret = max14577_read_reg(rmap, MAX14577_MUIC_REG_STATUS2, &reg_data); if (ret < 0) goto out; reg_data = ((reg_data & STATUS2_CHGTYP_MASK) >> STATUS2_CHGTYP_SHIFT); chg_type = maxim_get_charger_type(chg->max14577->dev_type, reg_data); if (chg_type == MAX14577_CHARGER_TYPE_DEAD_BATTERY) { *val = POWER_SUPPLY_HEALTH_DEAD; goto out; } ret = max14577_read_reg(rmap, MAX14577_CHG_REG_STATUS3, &reg_data); if (ret < 0) goto out; if (reg_data & STATUS3_OVP_MASK) { *val = POWER_SUPPLY_HEALTH_OVERVOLTAGE; goto out; } /* Not dead, not overvoltage */ *val = POWER_SUPPLY_HEALTH_GOOD; out: return ret; } /* * Always returns 1. * The max14577 chip doesn't report any status of battery presence. * Lets assume that it will always be used with some battery. */ static int max14577_get_present(struct max14577_charger *chg, int *val) { *val = 1; return 0; } static int max14577_set_fast_charge_timer(struct max14577_charger *chg, unsigned long hours) { u8 reg_data; switch (hours) { case 5 ... 7: reg_data = hours - 3; break; case 0: /* Disable */ reg_data = 0x7; break; default: dev_err(chg->dev, "Wrong value for Fast-Charge Timer: %lu\n", hours); return -EINVAL; } reg_data <<= CHGCTRL1_TCHW_SHIFT; return max14577_update_reg(chg->max14577->regmap, MAX14577_REG_CHGCTRL1, CHGCTRL1_TCHW_MASK, reg_data); } static int max14577_init_constant_voltage(struct max14577_charger *chg, unsigned int uvolt) { u8 reg_data; if (uvolt < MAXIM_CHARGER_CONSTANT_VOLTAGE_MIN || uvolt > MAXIM_CHARGER_CONSTANT_VOLTAGE_MAX) return -EINVAL; if (uvolt == 4200000) reg_data = 0x0; else if (uvolt == MAXIM_CHARGER_CONSTANT_VOLTAGE_MAX) reg_data = 0x1f; else if (uvolt <= 4280000) { unsigned int val = uvolt; val -= MAXIM_CHARGER_CONSTANT_VOLTAGE_MIN; val /= MAXIM_CHARGER_CONSTANT_VOLTAGE_STEP; if (uvolt <= 4180000) reg_data = 0x1 + val; else reg_data = val; /* Fix for gap between 4.18V and 4.22V */ } else return -EINVAL; reg_data <<= CHGCTRL3_MBCCVWRC_SHIFT; return max14577_write_reg(chg->max14577->regmap, MAX14577_CHG_REG_CHG_CTRL3, reg_data); } static int max14577_init_eoc(struct max14577_charger *chg, unsigned int uamp) { unsigned int current_bits; u8 reg_data; switch (chg->max14577->dev_type) { case MAXIM_DEVICE_TYPE_MAX77836: if (uamp < 5000) return -EINVAL; /* Requested current is too low */ if (uamp >= 7500 && uamp < 10000) current_bits = 0x0; else if (uamp <= 50000) { /* <5000, 7499> and <10000, 50000> */ current_bits = uamp / 5000; } else { uamp = min(uamp, 100000U) - 50000U; current_bits = 0xa + uamp / 10000; } break; case MAXIM_DEVICE_TYPE_MAX14577: default: if (uamp < MAX14577_CHARGER_EOC_CURRENT_LIMIT_MIN) return -EINVAL; /* Requested current is too low */ uamp = min(uamp, MAX14577_CHARGER_EOC_CURRENT_LIMIT_MAX); uamp -= MAX14577_CHARGER_EOC_CURRENT_LIMIT_MIN; current_bits = uamp / MAX14577_CHARGER_EOC_CURRENT_LIMIT_STEP; break; } reg_data = current_bits << CHGCTRL5_EOCS_SHIFT; return max14577_update_reg(chg->max14577->regmap, MAX14577_CHG_REG_CHG_CTRL5, CHGCTRL5_EOCS_MASK, reg_data); } static int max14577_init_fast_charge(struct max14577_charger *chg, unsigned int uamp) { u8 reg_data; int ret; const struct maxim_charger_current *limits = &maxim_charger_currents[chg->max14577->dev_type]; ret = maxim_charger_calc_reg_current(limits, uamp, uamp, &reg_data); if (ret) { dev_err(chg->dev, "Wrong value for fast charge: %u\n", uamp); return ret; } return max14577_update_reg(chg->max14577->regmap, MAX14577_CHG_REG_CHG_CTRL4, CHGCTRL4_MBCICHWRCL_MASK | CHGCTRL4_MBCICHWRCH_MASK, reg_data); } /* * Sets charger registers to proper and safe default values. * Some of these values are equal to defaults in MAX14577E * data sheet but there are minor differences. */ static int max14577_charger_reg_init(struct max14577_charger *chg) { struct regmap *rmap = chg->max14577->regmap; u8 reg_data; int ret; /* * Charger-Type Manual Detection, default off (set CHGTYPMAN to 0) * Charger-Detection Enable, default on (set CHGDETEN to 1) * Combined mask of CHGDETEN and CHGTYPMAN will zero the CHGTYPMAN bit */ reg_data = 0x1 << CDETCTRL1_CHGDETEN_SHIFT; max14577_update_reg(rmap, MAX14577_REG_CDETCTRL1, CDETCTRL1_CHGDETEN_MASK | CDETCTRL1_CHGTYPMAN_MASK, reg_data); /* * Wall-Adapter Rapid Charge, default on * Battery-Charger, default on */ reg_data = 0x1 << CHGCTRL2_VCHGR_RC_SHIFT; reg_data |= 0x1 << CHGCTRL2_MBCHOSTEN_SHIFT; max14577_write_reg(rmap, MAX14577_REG_CHGCTRL2, reg_data); /* Auto Charging Stop, default off */ reg_data = 0x0 << CHGCTRL6_AUTOSTOP_SHIFT; max14577_write_reg(rmap, MAX14577_REG_CHGCTRL6, reg_data); ret = max14577_init_constant_voltage(chg, chg->pdata->constant_uvolt); if (ret) return ret; ret = max14577_init_eoc(chg, chg->pdata->eoc_uamp); if (ret) return ret; ret = max14577_init_fast_charge(chg, chg->pdata->fast_charge_uamp); if (ret) return ret; ret = max14577_set_fast_charge_timer(chg, MAXIM_CHARGER_FAST_CHARGE_TIMER_DEFAULT); if (ret) return ret; /* Initialize Overvoltage-Protection Threshold */ switch (chg->pdata->ovp_uvolt) { case 7500000: reg_data = 0x0; break; case 6000000: case 6500000: case 7000000: reg_data = 0x1 + (chg->pdata->ovp_uvolt - 6000000) / 500000; break; default: dev_err(chg->dev, "Wrong value for OVP: %u\n", chg->pdata->ovp_uvolt); return -EINVAL; } reg_data <<= CHGCTRL7_OTPCGHCVS_SHIFT; max14577_write_reg(rmap, MAX14577_REG_CHGCTRL7, reg_data); return 0; } /* Support property from charger */ static enum power_supply_property max14577_charger_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_CHARGE_TYPE, POWER_SUPPLY_PROP_HEALTH, POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_MODEL_NAME, POWER_SUPPLY_PROP_MANUFACTURER, }; static const char * const model_names[] = { [MAXIM_DEVICE_TYPE_UNKNOWN] = "MAX14577-like", [MAXIM_DEVICE_TYPE_MAX14577] = "MAX14577", [MAXIM_DEVICE_TYPE_MAX77836] = "MAX77836", }; static const char *manufacturer = "Maxim Integrated"; static int max14577_charger_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct max14577_charger *chg = power_supply_get_drvdata(psy); int ret = 0; switch (psp) { case POWER_SUPPLY_PROP_STATUS: ret = max14577_get_charger_state(chg, &val->intval); break; case POWER_SUPPLY_PROP_CHARGE_TYPE: ret = max14577_get_charge_type(chg, &val->intval); break; case POWER_SUPPLY_PROP_HEALTH: ret = max14577_get_battery_health(chg, &val->intval); break; case POWER_SUPPLY_PROP_PRESENT: ret = max14577_get_present(chg, &val->intval); break; case POWER_SUPPLY_PROP_ONLINE: ret = max14577_get_online(chg, &val->intval); break; case POWER_SUPPLY_PROP_MODEL_NAME: BUILD_BUG_ON(ARRAY_SIZE(model_names) != MAXIM_DEVICE_TYPE_NUM); val->strval = model_names[chg->max14577->dev_type]; break; case POWER_SUPPLY_PROP_MANUFACTURER: val->strval = manufacturer; break; default: return -EINVAL; } return ret; } static const struct power_supply_desc max14577_charger_desc = { .name = "max14577-charger", .type = POWER_SUPPLY_TYPE_BATTERY, .properties = max14577_charger_props, .num_properties = ARRAY_SIZE(max14577_charger_props), .get_property = max14577_charger_get_property, }; #ifdef CONFIG_OF static struct max14577_charger_platform_data *max14577_charger_dt_init( struct platform_device *pdev) { struct max14577_charger_platform_data *pdata; struct device_node *np = pdev->dev.of_node; int ret; if (!np) { dev_err(&pdev->dev, "No charger OF node\n"); return ERR_PTR(-EINVAL); } pdata = devm_kzalloc(&pdev->dev, sizeof(*pdata), GFP_KERNEL); if (!pdata) return ERR_PTR(-ENOMEM); ret = of_property_read_u32(np, "maxim,constant-uvolt", &pdata->constant_uvolt); if (ret) { dev_err(&pdev->dev, "Cannot parse maxim,constant-uvolt field from DT\n"); return ERR_PTR(ret); } ret = of_property_read_u32(np, "maxim,fast-charge-uamp", &pdata->fast_charge_uamp); if (ret) { dev_err(&pdev->dev, "Cannot parse maxim,fast-charge-uamp field from DT\n"); return ERR_PTR(ret); } ret = of_property_read_u32(np, "maxim,eoc-uamp", &pdata->eoc_uamp); if (ret) { dev_err(&pdev->dev, "Cannot parse maxim,eoc-uamp field from DT\n"); return ERR_PTR(ret); } ret = of_property_read_u32(np, "maxim,ovp-uvolt", &pdata->ovp_uvolt); if (ret) { dev_err(&pdev->dev, "Cannot parse maxim,ovp-uvolt field from DT\n"); return ERR_PTR(ret); } return pdata; } #else /* CONFIG_OF */ static struct max14577_charger_platform_data *max14577_charger_dt_init( struct platform_device *pdev) { return NULL; } #endif /* CONFIG_OF */ static ssize_t show_fast_charge_timer(struct device *dev, struct device_attribute *attr, char *buf) { struct max14577_charger *chg = dev_get_drvdata(dev); u8 reg_data; int ret; unsigned int val; ret = max14577_read_reg(chg->max14577->regmap, MAX14577_REG_CHGCTRL1, &reg_data); if (ret) return ret; reg_data &= CHGCTRL1_TCHW_MASK; reg_data >>= CHGCTRL1_TCHW_SHIFT; switch (reg_data) { case 0x2 ... 0x4: val = reg_data + 3; break; case 0x7: val = 0; break; default: val = 5; break; } return sysfs_emit(buf, "%u\n", val); } static ssize_t store_fast_charge_timer(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct max14577_charger *chg = dev_get_drvdata(dev); unsigned long val; int ret; ret = kstrtoul(buf, 10, &val); if (ret) return ret; ret = max14577_set_fast_charge_timer(chg, val); if (ret) return ret; return count; } static DEVICE_ATTR(fast_charge_timer, S_IRUGO | S_IWUSR, show_fast_charge_timer, store_fast_charge_timer); static int max14577_charger_probe(struct platform_device *pdev) { struct max14577_charger *chg; struct power_supply_config psy_cfg = {}; struct max14577 *max14577 = dev_get_drvdata(pdev->dev.parent); int ret; chg = devm_kzalloc(&pdev->dev, sizeof(*chg), GFP_KERNEL); if (!chg) return -ENOMEM; platform_set_drvdata(pdev, chg); chg->dev = &pdev->dev; chg->max14577 = max14577; chg->pdata = max14577_charger_dt_init(pdev); if (IS_ERR_OR_NULL(chg->pdata)) return PTR_ERR(chg->pdata); ret = max14577_charger_reg_init(chg); if (ret) return ret; ret = device_create_file(&pdev->dev, &dev_attr_fast_charge_timer); if (ret) { dev_err(&pdev->dev, "failed: create sysfs entry\n"); return ret; } psy_cfg.drv_data = chg; chg->charger = power_supply_register(&pdev->dev, &max14577_charger_desc, &psy_cfg); if (IS_ERR(chg->charger)) { dev_err(&pdev->dev, "failed: power supply register\n"); ret = PTR_ERR(chg->charger); goto err; } /* Check for valid values for charger */ BUILD_BUG_ON(MAX14577_CHARGER_EOC_CURRENT_LIMIT_MIN + MAX14577_CHARGER_EOC_CURRENT_LIMIT_STEP * 0xf != MAX14577_CHARGER_EOC_CURRENT_LIMIT_MAX); return 0; err: device_remove_file(&pdev->dev, &dev_attr_fast_charge_timer); return ret; } static int max14577_charger_remove(struct platform_device *pdev) { struct max14577_charger *chg = platform_get_drvdata(pdev); device_remove_file(&pdev->dev, &dev_attr_fast_charge_timer); power_supply_unregister(chg->charger); return 0; } static const struct platform_device_id max14577_charger_id[] = { { "max14577-charger", MAXIM_DEVICE_TYPE_MAX14577, }, { "max77836-charger", MAXIM_DEVICE_TYPE_MAX77836, }, { } }; MODULE_DEVICE_TABLE(platform, max14577_charger_id); static const struct of_device_id of_max14577_charger_dt_match[] = { { .compatible = "maxim,max14577-charger", .data = (void *)MAXIM_DEVICE_TYPE_MAX14577, }, { .compatible = "maxim,max77836-charger", .data = (void *)MAXIM_DEVICE_TYPE_MAX77836, }, { }, }; MODULE_DEVICE_TABLE(of, of_max14577_charger_dt_match); static struct platform_driver max14577_charger_driver = { .driver = { .name = "max14577-charger", .of_match_table = of_max14577_charger_dt_match, }, .probe = max14577_charger_probe, .remove = max14577_charger_remove, .id_table = max14577_charger_id, }; module_platform_driver(max14577_charger_driver); MODULE_AUTHOR("Krzysztof Kozlowski <[email protected]>"); MODULE_DESCRIPTION("Maxim 14577/77836 charger driver"); MODULE_LICENSE("GPL");
linux-master
drivers/power/supply/max14577_charger.c
// SPDX-License-Identifier: GPL-2.0-only /* * Sysfs interface for the universal power supply monitor class * * Copyright © 2007 David Woodhouse <[email protected]> * Copyright © 2007 Anton Vorontsov <[email protected]> * Copyright © 2004 Szabolcs Gyurko * Copyright © 2003 Ian Molton <[email protected]> * * Modified: 2004, Oct Szabolcs Gyurko */ #include <linux/ctype.h> #include <linux/device.h> #include <linux/power_supply.h> #include <linux/slab.h> #include <linux/stat.h> #include "power_supply.h" #define MAX_PROP_NAME_LEN 30 struct power_supply_attr { const char *prop_name; char attr_name[MAX_PROP_NAME_LEN + 1]; struct device_attribute dev_attr; const char * const *text_values; int text_values_len; }; #define _POWER_SUPPLY_ATTR(_name, _text, _len) \ [POWER_SUPPLY_PROP_ ## _name] = \ { \ .prop_name = #_name, \ .attr_name = #_name "\0", \ .text_values = _text, \ .text_values_len = _len, \ } #define POWER_SUPPLY_ATTR(_name) _POWER_SUPPLY_ATTR(_name, NULL, 0) #define _POWER_SUPPLY_ENUM_ATTR(_name, _text) \ _POWER_SUPPLY_ATTR(_name, _text, ARRAY_SIZE(_text)) #define POWER_SUPPLY_ENUM_ATTR(_name) \ _POWER_SUPPLY_ENUM_ATTR(_name, POWER_SUPPLY_ ## _name ## _TEXT) static const char * const POWER_SUPPLY_TYPE_TEXT[] = { [POWER_SUPPLY_TYPE_UNKNOWN] = "Unknown", [POWER_SUPPLY_TYPE_BATTERY] = "Battery", [POWER_SUPPLY_TYPE_UPS] = "UPS", [POWER_SUPPLY_TYPE_MAINS] = "Mains", [POWER_SUPPLY_TYPE_USB] = "USB", [POWER_SUPPLY_TYPE_USB_DCP] = "USB_DCP", [POWER_SUPPLY_TYPE_USB_CDP] = "USB_CDP", [POWER_SUPPLY_TYPE_USB_ACA] = "USB_ACA", [POWER_SUPPLY_TYPE_USB_TYPE_C] = "USB_C", [POWER_SUPPLY_TYPE_USB_PD] = "USB_PD", [POWER_SUPPLY_TYPE_USB_PD_DRP] = "USB_PD_DRP", [POWER_SUPPLY_TYPE_APPLE_BRICK_ID] = "BrickID", [POWER_SUPPLY_TYPE_WIRELESS] = "Wireless", }; static const char * const POWER_SUPPLY_USB_TYPE_TEXT[] = { [POWER_SUPPLY_USB_TYPE_UNKNOWN] = "Unknown", [POWER_SUPPLY_USB_TYPE_SDP] = "SDP", [POWER_SUPPLY_USB_TYPE_DCP] = "DCP", [POWER_SUPPLY_USB_TYPE_CDP] = "CDP", [POWER_SUPPLY_USB_TYPE_ACA] = "ACA", [POWER_SUPPLY_USB_TYPE_C] = "C", [POWER_SUPPLY_USB_TYPE_PD] = "PD", [POWER_SUPPLY_USB_TYPE_PD_DRP] = "PD_DRP", [POWER_SUPPLY_USB_TYPE_PD_PPS] = "PD_PPS", [POWER_SUPPLY_USB_TYPE_APPLE_BRICK_ID] = "BrickID", }; static const char * const POWER_SUPPLY_STATUS_TEXT[] = { [POWER_SUPPLY_STATUS_UNKNOWN] = "Unknown", [POWER_SUPPLY_STATUS_CHARGING] = "Charging", [POWER_SUPPLY_STATUS_DISCHARGING] = "Discharging", [POWER_SUPPLY_STATUS_NOT_CHARGING] = "Not charging", [POWER_SUPPLY_STATUS_FULL] = "Full", }; static const char * const POWER_SUPPLY_CHARGE_TYPE_TEXT[] = { [POWER_SUPPLY_CHARGE_TYPE_UNKNOWN] = "Unknown", [POWER_SUPPLY_CHARGE_TYPE_NONE] = "N/A", [POWER_SUPPLY_CHARGE_TYPE_TRICKLE] = "Trickle", [POWER_SUPPLY_CHARGE_TYPE_FAST] = "Fast", [POWER_SUPPLY_CHARGE_TYPE_STANDARD] = "Standard", [POWER_SUPPLY_CHARGE_TYPE_ADAPTIVE] = "Adaptive", [POWER_SUPPLY_CHARGE_TYPE_CUSTOM] = "Custom", [POWER_SUPPLY_CHARGE_TYPE_LONGLIFE] = "Long Life", [POWER_SUPPLY_CHARGE_TYPE_BYPASS] = "Bypass", }; static const char * const POWER_SUPPLY_HEALTH_TEXT[] = { [POWER_SUPPLY_HEALTH_UNKNOWN] = "Unknown", [POWER_SUPPLY_HEALTH_GOOD] = "Good", [POWER_SUPPLY_HEALTH_OVERHEAT] = "Overheat", [POWER_SUPPLY_HEALTH_DEAD] = "Dead", [POWER_SUPPLY_HEALTH_OVERVOLTAGE] = "Over voltage", [POWER_SUPPLY_HEALTH_UNSPEC_FAILURE] = "Unspecified failure", [POWER_SUPPLY_HEALTH_COLD] = "Cold", [POWER_SUPPLY_HEALTH_WATCHDOG_TIMER_EXPIRE] = "Watchdog timer expire", [POWER_SUPPLY_HEALTH_SAFETY_TIMER_EXPIRE] = "Safety timer expire", [POWER_SUPPLY_HEALTH_OVERCURRENT] = "Over current", [POWER_SUPPLY_HEALTH_CALIBRATION_REQUIRED] = "Calibration required", [POWER_SUPPLY_HEALTH_WARM] = "Warm", [POWER_SUPPLY_HEALTH_COOL] = "Cool", [POWER_SUPPLY_HEALTH_HOT] = "Hot", [POWER_SUPPLY_HEALTH_NO_BATTERY] = "No battery", }; static const char * const POWER_SUPPLY_TECHNOLOGY_TEXT[] = { [POWER_SUPPLY_TECHNOLOGY_UNKNOWN] = "Unknown", [POWER_SUPPLY_TECHNOLOGY_NiMH] = "NiMH", [POWER_SUPPLY_TECHNOLOGY_LION] = "Li-ion", [POWER_SUPPLY_TECHNOLOGY_LIPO] = "Li-poly", [POWER_SUPPLY_TECHNOLOGY_LiFe] = "LiFe", [POWER_SUPPLY_TECHNOLOGY_NiCd] = "NiCd", [POWER_SUPPLY_TECHNOLOGY_LiMn] = "LiMn", }; static const char * const POWER_SUPPLY_CAPACITY_LEVEL_TEXT[] = { [POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN] = "Unknown", [POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL] = "Critical", [POWER_SUPPLY_CAPACITY_LEVEL_LOW] = "Low", [POWER_SUPPLY_CAPACITY_LEVEL_NORMAL] = "Normal", [POWER_SUPPLY_CAPACITY_LEVEL_HIGH] = "High", [POWER_SUPPLY_CAPACITY_LEVEL_FULL] = "Full", }; static const char * const POWER_SUPPLY_SCOPE_TEXT[] = { [POWER_SUPPLY_SCOPE_UNKNOWN] = "Unknown", [POWER_SUPPLY_SCOPE_SYSTEM] = "System", [POWER_SUPPLY_SCOPE_DEVICE] = "Device", }; static const char * const POWER_SUPPLY_CHARGE_BEHAVIOUR_TEXT[] = { [POWER_SUPPLY_CHARGE_BEHAVIOUR_AUTO] = "auto", [POWER_SUPPLY_CHARGE_BEHAVIOUR_INHIBIT_CHARGE] = "inhibit-charge", [POWER_SUPPLY_CHARGE_BEHAVIOUR_FORCE_DISCHARGE] = "force-discharge", }; static struct power_supply_attr power_supply_attrs[] = { /* Properties of type `int' */ POWER_SUPPLY_ENUM_ATTR(STATUS), POWER_SUPPLY_ENUM_ATTR(CHARGE_TYPE), POWER_SUPPLY_ENUM_ATTR(HEALTH), POWER_SUPPLY_ATTR(PRESENT), POWER_SUPPLY_ATTR(ONLINE), POWER_SUPPLY_ATTR(AUTHENTIC), POWER_SUPPLY_ENUM_ATTR(TECHNOLOGY), POWER_SUPPLY_ATTR(CYCLE_COUNT), POWER_SUPPLY_ATTR(VOLTAGE_MAX), POWER_SUPPLY_ATTR(VOLTAGE_MIN), POWER_SUPPLY_ATTR(VOLTAGE_MAX_DESIGN), POWER_SUPPLY_ATTR(VOLTAGE_MIN_DESIGN), POWER_SUPPLY_ATTR(VOLTAGE_NOW), POWER_SUPPLY_ATTR(VOLTAGE_AVG), POWER_SUPPLY_ATTR(VOLTAGE_OCV), POWER_SUPPLY_ATTR(VOLTAGE_BOOT), POWER_SUPPLY_ATTR(CURRENT_MAX), POWER_SUPPLY_ATTR(CURRENT_NOW), POWER_SUPPLY_ATTR(CURRENT_AVG), POWER_SUPPLY_ATTR(CURRENT_BOOT), POWER_SUPPLY_ATTR(POWER_NOW), POWER_SUPPLY_ATTR(POWER_AVG), POWER_SUPPLY_ATTR(CHARGE_FULL_DESIGN), POWER_SUPPLY_ATTR(CHARGE_EMPTY_DESIGN), POWER_SUPPLY_ATTR(CHARGE_FULL), POWER_SUPPLY_ATTR(CHARGE_EMPTY), POWER_SUPPLY_ATTR(CHARGE_NOW), POWER_SUPPLY_ATTR(CHARGE_AVG), POWER_SUPPLY_ATTR(CHARGE_COUNTER), POWER_SUPPLY_ATTR(CONSTANT_CHARGE_CURRENT), POWER_SUPPLY_ATTR(CONSTANT_CHARGE_CURRENT_MAX), POWER_SUPPLY_ATTR(CONSTANT_CHARGE_VOLTAGE), POWER_SUPPLY_ATTR(CONSTANT_CHARGE_VOLTAGE_MAX), POWER_SUPPLY_ATTR(CHARGE_CONTROL_LIMIT), POWER_SUPPLY_ATTR(CHARGE_CONTROL_LIMIT_MAX), POWER_SUPPLY_ATTR(CHARGE_CONTROL_START_THRESHOLD), POWER_SUPPLY_ATTR(CHARGE_CONTROL_END_THRESHOLD), POWER_SUPPLY_ENUM_ATTR(CHARGE_BEHAVIOUR), POWER_SUPPLY_ATTR(INPUT_CURRENT_LIMIT), POWER_SUPPLY_ATTR(INPUT_VOLTAGE_LIMIT), POWER_SUPPLY_ATTR(INPUT_POWER_LIMIT), POWER_SUPPLY_ATTR(ENERGY_FULL_DESIGN), POWER_SUPPLY_ATTR(ENERGY_EMPTY_DESIGN), POWER_SUPPLY_ATTR(ENERGY_FULL), POWER_SUPPLY_ATTR(ENERGY_EMPTY), POWER_SUPPLY_ATTR(ENERGY_NOW), POWER_SUPPLY_ATTR(ENERGY_AVG), POWER_SUPPLY_ATTR(CAPACITY), POWER_SUPPLY_ATTR(CAPACITY_ALERT_MIN), POWER_SUPPLY_ATTR(CAPACITY_ALERT_MAX), POWER_SUPPLY_ATTR(CAPACITY_ERROR_MARGIN), POWER_SUPPLY_ENUM_ATTR(CAPACITY_LEVEL), POWER_SUPPLY_ATTR(TEMP), POWER_SUPPLY_ATTR(TEMP_MAX), POWER_SUPPLY_ATTR(TEMP_MIN), POWER_SUPPLY_ATTR(TEMP_ALERT_MIN), POWER_SUPPLY_ATTR(TEMP_ALERT_MAX), POWER_SUPPLY_ATTR(TEMP_AMBIENT), POWER_SUPPLY_ATTR(TEMP_AMBIENT_ALERT_MIN), POWER_SUPPLY_ATTR(TEMP_AMBIENT_ALERT_MAX), POWER_SUPPLY_ATTR(TIME_TO_EMPTY_NOW), POWER_SUPPLY_ATTR(TIME_TO_EMPTY_AVG), POWER_SUPPLY_ATTR(TIME_TO_FULL_NOW), POWER_SUPPLY_ATTR(TIME_TO_FULL_AVG), POWER_SUPPLY_ENUM_ATTR(TYPE), POWER_SUPPLY_ATTR(USB_TYPE), POWER_SUPPLY_ENUM_ATTR(SCOPE), POWER_SUPPLY_ATTR(PRECHARGE_CURRENT), POWER_SUPPLY_ATTR(CHARGE_TERM_CURRENT), POWER_SUPPLY_ATTR(CALIBRATE), POWER_SUPPLY_ATTR(MANUFACTURE_YEAR), POWER_SUPPLY_ATTR(MANUFACTURE_MONTH), POWER_SUPPLY_ATTR(MANUFACTURE_DAY), /* Properties of type `const char *' */ POWER_SUPPLY_ATTR(MODEL_NAME), POWER_SUPPLY_ATTR(MANUFACTURER), POWER_SUPPLY_ATTR(SERIAL_NUMBER), }; #define POWER_SUPPLY_ATTR_CNT ARRAY_SIZE(power_supply_attrs) static struct attribute * __power_supply_attrs[POWER_SUPPLY_ATTR_CNT + 1]; static struct power_supply_attr *to_ps_attr(struct device_attribute *attr) { return container_of(attr, struct power_supply_attr, dev_attr); } static enum power_supply_property dev_attr_psp(struct device_attribute *attr) { return to_ps_attr(attr) - power_supply_attrs; } static ssize_t power_supply_show_usb_type(struct device *dev, const struct power_supply_desc *desc, union power_supply_propval *value, char *buf) { enum power_supply_usb_type usb_type; ssize_t count = 0; bool match = false; int i; for (i = 0; i < desc->num_usb_types; ++i) { usb_type = desc->usb_types[i]; if (value->intval == usb_type) { count += sysfs_emit_at(buf, count, "[%s] ", POWER_SUPPLY_USB_TYPE_TEXT[usb_type]); match = true; } else { count += sysfs_emit_at(buf, count, "%s ", POWER_SUPPLY_USB_TYPE_TEXT[usb_type]); } } if (!match) { dev_warn(dev, "driver reporting unsupported connected type\n"); return -EINVAL; } if (count) buf[count - 1] = '\n'; return count; } static ssize_t power_supply_show_property(struct device *dev, struct device_attribute *attr, char *buf) { ssize_t ret; struct power_supply *psy = dev_get_drvdata(dev); struct power_supply_attr *ps_attr = to_ps_attr(attr); enum power_supply_property psp = dev_attr_psp(attr); union power_supply_propval value; if (psp == POWER_SUPPLY_PROP_TYPE) { value.intval = psy->desc->type; } else { ret = power_supply_get_property(psy, psp, &value); if (ret < 0) { if (ret == -ENODATA) dev_dbg_ratelimited(dev, "driver has no data for `%s' property\n", attr->attr.name); else if (ret != -ENODEV && ret != -EAGAIN) dev_err_ratelimited(dev, "driver failed to report `%s' property: %zd\n", attr->attr.name, ret); return ret; } } if (ps_attr->text_values_len > 0 && value.intval < ps_attr->text_values_len && value.intval >= 0) { return sysfs_emit(buf, "%s\n", ps_attr->text_values[value.intval]); } switch (psp) { case POWER_SUPPLY_PROP_USB_TYPE: ret = power_supply_show_usb_type(dev, psy->desc, &value, buf); break; case POWER_SUPPLY_PROP_MODEL_NAME ... POWER_SUPPLY_PROP_SERIAL_NUMBER: ret = sysfs_emit(buf, "%s\n", value.strval); break; default: ret = sysfs_emit(buf, "%d\n", value.intval); } return ret; } static ssize_t power_supply_store_property(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { ssize_t ret; struct power_supply *psy = dev_get_drvdata(dev); struct power_supply_attr *ps_attr = to_ps_attr(attr); enum power_supply_property psp = dev_attr_psp(attr); union power_supply_propval value; ret = -EINVAL; if (ps_attr->text_values_len > 0) { ret = __sysfs_match_string(ps_attr->text_values, ps_attr->text_values_len, buf); } /* * If no match was found, then check to see if it is an integer. * Integer values are valid for enums in addition to the text value. */ if (ret < 0) { long long_val; ret = kstrtol(buf, 10, &long_val); if (ret < 0) return ret; ret = long_val; } value.intval = ret; ret = power_supply_set_property(psy, psp, &value); if (ret < 0) return ret; return count; } static umode_t power_supply_attr_is_visible(struct kobject *kobj, struct attribute *attr, int attrno) { struct device *dev = kobj_to_dev(kobj); struct power_supply *psy = dev_get_drvdata(dev); umode_t mode = S_IRUSR | S_IRGRP | S_IROTH; int i; if (!power_supply_attrs[attrno].prop_name) return 0; if (attrno == POWER_SUPPLY_PROP_TYPE) return mode; for (i = 0; i < psy->desc->num_properties; i++) { int property = psy->desc->properties[i]; if (property == attrno) { if (psy->desc->property_is_writeable && psy->desc->property_is_writeable(psy, property) > 0) mode |= S_IWUSR; return mode; } } if (power_supply_battery_info_has_prop(psy->battery_info, attrno)) return mode; return 0; } static const struct attribute_group power_supply_attr_group = { .attrs = __power_supply_attrs, .is_visible = power_supply_attr_is_visible, }; static const struct attribute_group *power_supply_attr_groups[] = { &power_supply_attr_group, NULL, }; static void str_to_lower(char *str) { while (*str) { *str = tolower(*str); str++; } } void power_supply_init_attrs(struct device_type *dev_type) { int i; dev_type->groups = power_supply_attr_groups; for (i = 0; i < ARRAY_SIZE(power_supply_attrs); i++) { struct device_attribute *attr; if (!power_supply_attrs[i].prop_name) { pr_warn("%s: Property %d skipped because it is missing from power_supply_attrs\n", __func__, i); sprintf(power_supply_attrs[i].attr_name, "_err_%d", i); } else { str_to_lower(power_supply_attrs[i].attr_name); } attr = &power_supply_attrs[i].dev_attr; attr->attr.name = power_supply_attrs[i].attr_name; attr->show = power_supply_show_property; attr->store = power_supply_store_property; __power_supply_attrs[i] = &attr->attr; } } static int add_prop_uevent(const struct device *dev, struct kobj_uevent_env *env, enum power_supply_property prop, char *prop_buf) { int ret = 0; struct power_supply_attr *pwr_attr; struct device_attribute *dev_attr; char *line; pwr_attr = &power_supply_attrs[prop]; dev_attr = &pwr_attr->dev_attr; ret = power_supply_show_property((struct device *)dev, dev_attr, prop_buf); if (ret == -ENODEV || ret == -ENODATA) { /* * When a battery is absent, we expect -ENODEV. Don't abort; * send the uevent with at least the PRESENT=0 property */ return 0; } if (ret < 0) return ret; line = strchr(prop_buf, '\n'); if (line) *line = 0; return add_uevent_var(env, "POWER_SUPPLY_%s=%s", pwr_attr->prop_name, prop_buf); } int power_supply_uevent(const struct device *dev, struct kobj_uevent_env *env) { const struct power_supply *psy = dev_get_drvdata(dev); const enum power_supply_property *battery_props = power_supply_battery_info_properties; unsigned long psy_drv_properties[POWER_SUPPLY_ATTR_CNT / sizeof(unsigned long) + 1] = {0}; int ret = 0, j; char *prop_buf; if (!psy || !psy->desc) { dev_dbg(dev, "No power supply yet\n"); return ret; } ret = add_uevent_var(env, "POWER_SUPPLY_NAME=%s", psy->desc->name); if (ret) return ret; prop_buf = (char *)get_zeroed_page(GFP_KERNEL); if (!prop_buf) return -ENOMEM; ret = add_prop_uevent(dev, env, POWER_SUPPLY_PROP_TYPE, prop_buf); if (ret) goto out; for (j = 0; j < psy->desc->num_properties; j++) { set_bit(psy->desc->properties[j], psy_drv_properties); ret = add_prop_uevent(dev, env, psy->desc->properties[j], prop_buf); if (ret) goto out; } for (j = 0; j < power_supply_battery_info_properties_size; j++) { if (test_bit(battery_props[j], psy_drv_properties)) continue; if (!power_supply_battery_info_has_prop(psy->battery_info, battery_props[j])) continue; ret = add_prop_uevent(dev, env, battery_props[j], prop_buf); if (ret) goto out; } out: free_page((unsigned long)prop_buf); return ret; } ssize_t power_supply_charge_behaviour_show(struct device *dev, unsigned int available_behaviours, enum power_supply_charge_behaviour current_behaviour, char *buf) { bool match = false, available, active; ssize_t count = 0; int i; for (i = 0; i < ARRAY_SIZE(POWER_SUPPLY_CHARGE_BEHAVIOUR_TEXT); i++) { available = available_behaviours & BIT(i); active = i == current_behaviour; if (available && active) { count += sysfs_emit_at(buf, count, "[%s] ", POWER_SUPPLY_CHARGE_BEHAVIOUR_TEXT[i]); match = true; } else if (available) { count += sysfs_emit_at(buf, count, "%s ", POWER_SUPPLY_CHARGE_BEHAVIOUR_TEXT[i]); } } if (!match) { dev_warn(dev, "driver reporting unsupported charge behaviour\n"); return -EINVAL; } if (count) buf[count - 1] = '\n'; return count; } EXPORT_SYMBOL_GPL(power_supply_charge_behaviour_show); int power_supply_charge_behaviour_parse(unsigned int available_behaviours, const char *buf) { int i = sysfs_match_string(POWER_SUPPLY_CHARGE_BEHAVIOUR_TEXT, buf); if (i < 0) return i; if (available_behaviours & BIT(i)) return i; return -EINVAL; } EXPORT_SYMBOL_GPL(power_supply_charge_behaviour_parse);
linux-master
drivers/power/supply/power_supply_sysfs.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Batttery Driver for Dialog DA9052 PMICs * * Copyright(c) 2011 Dialog Semiconductor Ltd. * * Author: David Dajun Chen <[email protected]> */ #include <linux/delay.h> #include <linux/freezer.h> #include <linux/fs.h> #include <linux/jiffies.h> #include <linux/module.h> #include <linux/timer.h> #include <linux/uaccess.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/mfd/da9052/da9052.h> #include <linux/mfd/da9052/pdata.h> #include <linux/mfd/da9052/reg.h> /* STATIC CONFIGURATION */ #define DA9052_BAT_CUTOFF_VOLT 2800 #define DA9052_BAT_TSH 62000 #define DA9052_BAT_LOW_CAP 4 #define DA9052_AVG_SZ 4 #define DA9052_VC_TBL_SZ 68 #define DA9052_VC_TBL_REF_SZ 3 #define DA9052_ISET_USB_MASK 0x0F #define DA9052_CHG_USB_ILIM_MASK 0x40 #define DA9052_CHG_LIM_COLS 16 #define DA9052_MEAN(x, y) ((x + y) / 2) enum charger_type_enum { DA9052_NOCHARGER = 1, DA9052_CHARGER, }; static const u16 da9052_chg_current_lim[2][DA9052_CHG_LIM_COLS] = { {70, 80, 90, 100, 110, 120, 400, 450, 500, 550, 600, 650, 700, 900, 1100, 1300}, {80, 90, 100, 110, 120, 400, 450, 500, 550, 600, 800, 1000, 1200, 1400, 1600, 1800}, }; static const u16 vc_tbl_ref[3] = {10, 25, 40}; /* Lookup table for voltage vs capacity */ static u32 const vc_tbl[3][68][2] = { /* For temperature 10 degree Celsius */ { {4082, 100}, {4036, 98}, {4020, 96}, {4008, 95}, {3997, 93}, {3983, 91}, {3964, 90}, {3943, 88}, {3926, 87}, {3912, 85}, {3900, 84}, {3890, 82}, {3881, 80}, {3873, 79}, {3865, 77}, {3857, 76}, {3848, 74}, {3839, 73}, {3829, 71}, {3820, 70}, {3811, 68}, {3802, 67}, {3794, 65}, {3785, 64}, {3778, 62}, {3770, 61}, {3763, 59}, {3756, 58}, {3750, 56}, {3744, 55}, {3738, 53}, {3732, 52}, {3727, 50}, {3722, 49}, {3717, 47}, {3712, 46}, {3708, 44}, {3703, 43}, {3700, 41}, {3696, 40}, {3693, 38}, {3691, 37}, {3688, 35}, {3686, 34}, {3683, 32}, {3681, 31}, {3678, 29}, {3675, 28}, {3672, 26}, {3669, 25}, {3665, 23}, {3661, 22}, {3656, 21}, {3651, 19}, {3645, 18}, {3639, 16}, {3631, 15}, {3622, 13}, {3611, 12}, {3600, 10}, {3587, 9}, {3572, 7}, {3548, 6}, {3503, 5}, {3420, 3}, {3268, 2}, {2992, 1}, {2746, 0} }, /* For temperature 25 degree Celsius */ { {4102, 100}, {4065, 98}, {4048, 96}, {4034, 95}, {4021, 93}, {4011, 92}, {4001, 90}, {3986, 88}, {3968, 87}, {3952, 85}, {3938, 84}, {3926, 82}, {3916, 81}, {3908, 79}, {3900, 77}, {3892, 76}, {3883, 74}, {3874, 73}, {3864, 71}, {3855, 70}, {3846, 68}, {3836, 67}, {3827, 65}, {3819, 64}, {3810, 62}, {3801, 61}, {3793, 59}, {3786, 58}, {3778, 56}, {3772, 55}, {3765, 53}, {3759, 52}, {3754, 50}, {3748, 49}, {3743, 47}, {3738, 46}, {3733, 44}, {3728, 43}, {3724, 41}, {3720, 40}, {3716, 38}, {3712, 37}, {3709, 35}, {3706, 34}, {3703, 33}, {3701, 31}, {3698, 30}, {3696, 28}, {3693, 27}, {3690, 25}, {3687, 24}, {3683, 22}, {3680, 21}, {3675, 19}, {3671, 18}, {3666, 17}, {3660, 15}, {3654, 14}, {3647, 12}, {3639, 11}, {3630, 9}, {3621, 8}, {3613, 6}, {3606, 5}, {3597, 4}, {3582, 2}, {3546, 1}, {2747, 0} }, /* For temperature 40 degree Celsius */ { {4114, 100}, {4081, 98}, {4065, 96}, {4050, 95}, {4036, 93}, {4024, 92}, {4013, 90}, {4002, 88}, {3990, 87}, {3976, 85}, {3962, 84}, {3950, 82}, {3939, 81}, {3930, 79}, {3921, 77}, {3912, 76}, {3902, 74}, {3893, 73}, {3883, 71}, {3874, 70}, {3865, 68}, {3856, 67}, {3847, 65}, {3838, 64}, {3829, 62}, {3820, 61}, {3812, 59}, {3803, 58}, {3795, 56}, {3787, 55}, {3780, 53}, {3773, 52}, {3767, 50}, {3761, 49}, {3756, 47}, {3751, 46}, {3746, 44}, {3741, 43}, {3736, 41}, {3732, 40}, {3728, 38}, {3724, 37}, {3720, 35}, {3716, 34}, {3713, 33}, {3710, 31}, {3707, 30}, {3704, 28}, {3701, 27}, {3698, 25}, {3695, 24}, {3691, 22}, {3686, 21}, {3681, 19}, {3676, 18}, {3671, 17}, {3666, 15}, {3661, 14}, {3655, 12}, {3648, 11}, {3640, 9}, {3632, 8}, {3622, 6}, {3616, 5}, {3611, 4}, {3604, 2}, {3594, 1}, {2747, 0} } }; struct da9052_battery { struct da9052 *da9052; struct power_supply *psy; struct notifier_block nb; int charger_type; int status; int health; }; static inline int volt_reg_to_mV(int value) { return ((value * 1000) / 512) + 2500; } static inline int ichg_reg_to_mA(int value) { return (value * 3900) / 1000; } static int da9052_read_chgend_current(struct da9052_battery *bat, int *current_mA) { int ret; if (bat->status == POWER_SUPPLY_STATUS_DISCHARGING) return -EINVAL; ret = da9052_reg_read(bat->da9052, DA9052_ICHG_END_REG); if (ret < 0) return ret; *current_mA = ichg_reg_to_mA(ret & DA9052_ICHGEND_ICHGEND); return 0; } static int da9052_read_chg_current(struct da9052_battery *bat, int *current_mA) { int ret; if (bat->status == POWER_SUPPLY_STATUS_DISCHARGING) return -EINVAL; ret = da9052_reg_read(bat->da9052, DA9052_ICHG_AV_REG); if (ret < 0) return ret; *current_mA = ichg_reg_to_mA(ret & DA9052_ICHGAV_ICHGAV); return 0; } static int da9052_bat_check_status(struct da9052_battery *bat, int *status) { u8 v[2] = {0, 0}; u8 bat_status; u8 chg_end; int ret; int chg_current; int chg_end_current; bool dcinsel; bool dcindet; bool vbussel; bool vbusdet; bool dc; bool vbus; ret = da9052_group_read(bat->da9052, DA9052_STATUS_A_REG, 2, v); if (ret < 0) return ret; bat_status = v[0]; chg_end = v[1]; dcinsel = bat_status & DA9052_STATUSA_DCINSEL; dcindet = bat_status & DA9052_STATUSA_DCINDET; vbussel = bat_status & DA9052_STATUSA_VBUSSEL; vbusdet = bat_status & DA9052_STATUSA_VBUSDET; dc = dcinsel && dcindet; vbus = vbussel && vbusdet; /* Preference to WALL(DCIN) charger unit */ if (dc || vbus) { bat->charger_type = DA9052_CHARGER; /* If charging end flag is set and Charging current is greater * than charging end limit then battery is charging */ if ((chg_end & DA9052_STATUSB_CHGEND) != 0) { ret = da9052_read_chg_current(bat, &chg_current); if (ret < 0) return ret; ret = da9052_read_chgend_current(bat, &chg_end_current); if (ret < 0) return ret; if (chg_current >= chg_end_current) bat->status = POWER_SUPPLY_STATUS_CHARGING; else bat->status = POWER_SUPPLY_STATUS_NOT_CHARGING; } else { /* If Charging end flag is cleared then battery is * charging */ bat->status = POWER_SUPPLY_STATUS_CHARGING; } } else if (dcindet || vbusdet) { bat->charger_type = DA9052_CHARGER; bat->status = POWER_SUPPLY_STATUS_NOT_CHARGING; } else { bat->charger_type = DA9052_NOCHARGER; bat->status = POWER_SUPPLY_STATUS_DISCHARGING; } if (status != NULL) *status = bat->status; return 0; } static int da9052_bat_read_volt(struct da9052_battery *bat, int *volt_mV) { int volt; volt = da9052_adc_manual_read(bat->da9052, DA9052_ADC_MAN_MUXSEL_VBAT); if (volt < 0) return volt; *volt_mV = volt_reg_to_mV(volt); return 0; } static int da9052_bat_check_presence(struct da9052_battery *bat, int *illegal) { int bat_temp; bat_temp = da9052_adc_read_temp(bat->da9052); if (bat_temp < 0) return bat_temp; if (bat_temp > DA9052_BAT_TSH) *illegal = 1; else *illegal = 0; return 0; } static int da9052_bat_interpolate(int vbat_lower, int vbat_upper, int level_lower, int level_upper, int bat_voltage) { int tmp; tmp = ((level_upper - level_lower) * 1000) / (vbat_upper - vbat_lower); tmp = level_lower + (((bat_voltage - vbat_lower) * tmp) / 1000); return tmp; } static unsigned char da9052_determine_vc_tbl_index(unsigned char adc_temp) { int i; if (adc_temp <= vc_tbl_ref[0]) return 0; if (adc_temp > vc_tbl_ref[DA9052_VC_TBL_REF_SZ - 1]) return DA9052_VC_TBL_REF_SZ - 1; for (i = 0; i < DA9052_VC_TBL_REF_SZ - 1; i++) { if ((adc_temp > vc_tbl_ref[i]) && (adc_temp <= DA9052_MEAN(vc_tbl_ref[i], vc_tbl_ref[i + 1]))) return i; if ((adc_temp > DA9052_MEAN(vc_tbl_ref[i], vc_tbl_ref[i + 1])) && (adc_temp <= vc_tbl_ref[i])) return i + 1; } /* * For some reason authors of the driver didn't presume that we can * end up here. It might be OK, but might be not, no one knows for * sure. Go check your battery, is it on fire? */ WARN_ON(1); return 0; } static int da9052_bat_read_capacity(struct da9052_battery *bat, int *capacity) { int adc_temp; int bat_voltage; int vbat_lower; int vbat_upper; int level_upper; int level_lower; int ret; int flag; int i = 0; int j; ret = da9052_bat_read_volt(bat, &bat_voltage); if (ret < 0) return ret; adc_temp = da9052_adc_read_temp(bat->da9052); if (adc_temp < 0) return adc_temp; i = da9052_determine_vc_tbl_index(adc_temp); if (bat_voltage >= vc_tbl[i][0][0]) { *capacity = 100; return 0; } if (bat_voltage <= vc_tbl[i][DA9052_VC_TBL_SZ - 1][0]) { *capacity = 0; return 0; } flag = 0; for (j = 0; j < (DA9052_VC_TBL_SZ-1); j++) { if ((bat_voltage <= vc_tbl[i][j][0]) && (bat_voltage >= vc_tbl[i][j + 1][0])) { vbat_upper = vc_tbl[i][j][0]; vbat_lower = vc_tbl[i][j + 1][0]; level_upper = vc_tbl[i][j][1]; level_lower = vc_tbl[i][j + 1][1]; flag = 1; break; } } if (!flag) return -EIO; *capacity = da9052_bat_interpolate(vbat_lower, vbat_upper, level_lower, level_upper, bat_voltage); return 0; } static int da9052_bat_check_health(struct da9052_battery *bat, int *health) { int ret; int bat_illegal; int capacity; ret = da9052_bat_check_presence(bat, &bat_illegal); if (ret < 0) return ret; if (bat_illegal) { bat->health = POWER_SUPPLY_HEALTH_UNKNOWN; return 0; } if (bat->health != POWER_SUPPLY_HEALTH_OVERHEAT) { ret = da9052_bat_read_capacity(bat, &capacity); if (ret < 0) return ret; if (capacity < DA9052_BAT_LOW_CAP) bat->health = POWER_SUPPLY_HEALTH_DEAD; else bat->health = POWER_SUPPLY_HEALTH_GOOD; } *health = bat->health; return 0; } static irqreturn_t da9052_bat_irq(int irq, void *data) { struct da9052_battery *bat = data; int virq; virq = regmap_irq_get_virq(bat->da9052->irq_data, irq); irq -= virq; if (irq == DA9052_IRQ_CHGEND) bat->status = POWER_SUPPLY_STATUS_FULL; else da9052_bat_check_status(bat, NULL); if (irq == DA9052_IRQ_CHGEND || irq == DA9052_IRQ_DCIN || irq == DA9052_IRQ_VBUS || irq == DA9052_IRQ_TBAT) { power_supply_changed(bat->psy); } return IRQ_HANDLED; } static int da9052_USB_current_notifier(struct notifier_block *nb, unsigned long events, void *data) { u8 row; u8 col; int *current_mA = data; int ret; struct da9052_battery *bat = container_of(nb, struct da9052_battery, nb); if (bat->status == POWER_SUPPLY_STATUS_DISCHARGING) return -EPERM; ret = da9052_reg_read(bat->da9052, DA9052_CHGBUCK_REG); if (ret & DA9052_CHG_USB_ILIM_MASK) return -EPERM; if (bat->da9052->chip_id == DA9052) row = 0; else row = 1; if (*current_mA < da9052_chg_current_lim[row][0] || *current_mA > da9052_chg_current_lim[row][DA9052_CHG_LIM_COLS - 1]) return -EINVAL; for (col = 0; col <= DA9052_CHG_LIM_COLS - 1 ; col++) { if (*current_mA <= da9052_chg_current_lim[row][col]) break; } return da9052_reg_update(bat->da9052, DA9052_ISET_REG, DA9052_ISET_USB_MASK, col); } static int da9052_bat_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { int ret; int illegal; struct da9052_battery *bat = power_supply_get_drvdata(psy); ret = da9052_bat_check_presence(bat, &illegal); if (ret < 0) return ret; if (illegal && psp != POWER_SUPPLY_PROP_PRESENT) return -ENODEV; switch (psp) { case POWER_SUPPLY_PROP_STATUS: ret = da9052_bat_check_status(bat, &val->intval); break; case POWER_SUPPLY_PROP_ONLINE: val->intval = (bat->charger_type == DA9052_NOCHARGER) ? 0 : 1; break; case POWER_SUPPLY_PROP_PRESENT: ret = da9052_bat_check_presence(bat, &val->intval); break; case POWER_SUPPLY_PROP_HEALTH: ret = da9052_bat_check_health(bat, &val->intval); break; case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN: val->intval = DA9052_BAT_CUTOFF_VOLT * 1000; break; case POWER_SUPPLY_PROP_VOLTAGE_AVG: ret = da9052_bat_read_volt(bat, &val->intval); break; case POWER_SUPPLY_PROP_CURRENT_AVG: ret = da9052_read_chg_current(bat, &val->intval); break; case POWER_SUPPLY_PROP_CAPACITY: ret = da9052_bat_read_capacity(bat, &val->intval); break; case POWER_SUPPLY_PROP_TEMP: val->intval = da9052_adc_read_temp(bat->da9052); ret = val->intval; break; case POWER_SUPPLY_PROP_TECHNOLOGY: val->intval = POWER_SUPPLY_TECHNOLOGY_LION; break; default: return -EINVAL; } return ret; } static enum power_supply_property da9052_bat_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_HEALTH, POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN, POWER_SUPPLY_PROP_VOLTAGE_AVG, POWER_SUPPLY_PROP_CURRENT_AVG, POWER_SUPPLY_PROP_CAPACITY, POWER_SUPPLY_PROP_TEMP, POWER_SUPPLY_PROP_TECHNOLOGY, }; static struct power_supply_desc psy_desc = { .name = "da9052-bat", .type = POWER_SUPPLY_TYPE_BATTERY, .properties = da9052_bat_props, .num_properties = ARRAY_SIZE(da9052_bat_props), .get_property = da9052_bat_get_property, }; static char *da9052_bat_irqs[] = { "BATT TEMP", "DCIN DET", "DCIN REM", "VBUS DET", "VBUS REM", "CHG END", }; static int da9052_bat_irq_bits[] = { DA9052_IRQ_TBAT, DA9052_IRQ_DCIN, DA9052_IRQ_DCINREM, DA9052_IRQ_VBUS, DA9052_IRQ_VBUSREM, DA9052_IRQ_CHGEND, }; static s32 da9052_bat_probe(struct platform_device *pdev) { struct da9052_pdata *pdata; struct da9052_battery *bat; struct power_supply_config psy_cfg = {}; int ret; int i; bat = devm_kzalloc(&pdev->dev, sizeof(struct da9052_battery), GFP_KERNEL); if (!bat) return -ENOMEM; psy_cfg.drv_data = bat; bat->da9052 = dev_get_drvdata(pdev->dev.parent); bat->charger_type = DA9052_NOCHARGER; bat->status = POWER_SUPPLY_STATUS_UNKNOWN; bat->health = POWER_SUPPLY_HEALTH_UNKNOWN; bat->nb.notifier_call = da9052_USB_current_notifier; pdata = bat->da9052->dev->platform_data; if (pdata != NULL && pdata->use_for_apm) psy_desc.use_for_apm = pdata->use_for_apm; else psy_desc.use_for_apm = 1; for (i = 0; i < ARRAY_SIZE(da9052_bat_irqs); i++) { ret = da9052_request_irq(bat->da9052, da9052_bat_irq_bits[i], da9052_bat_irqs[i], da9052_bat_irq, bat); if (ret != 0) { dev_err(bat->da9052->dev, "DA9052 failed to request %s IRQ: %d\n", da9052_bat_irqs[i], ret); goto err; } } bat->psy = power_supply_register(&pdev->dev, &psy_desc, &psy_cfg); if (IS_ERR(bat->psy)) { ret = PTR_ERR(bat->psy); goto err; } platform_set_drvdata(pdev, bat); return 0; err: while (--i >= 0) da9052_free_irq(bat->da9052, da9052_bat_irq_bits[i], bat); return ret; } static int da9052_bat_remove(struct platform_device *pdev) { int i; struct da9052_battery *bat = platform_get_drvdata(pdev); for (i = 0; i < ARRAY_SIZE(da9052_bat_irqs); i++) da9052_free_irq(bat->da9052, da9052_bat_irq_bits[i], bat); power_supply_unregister(bat->psy); return 0; } static struct platform_driver da9052_bat_driver = { .probe = da9052_bat_probe, .remove = da9052_bat_remove, .driver = { .name = "da9052-bat", }, }; module_platform_driver(da9052_bat_driver); MODULE_DESCRIPTION("DA9052 BAT Device Driver"); MODULE_AUTHOR("David Dajun Chen <[email protected]>"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:da9052-bat");
linux-master
drivers/power/supply/da9052-battery.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * bq2415x charger driver * * Copyright (C) 2011-2013 Pali Rohár <[email protected]> * * Datasheets: * https://www.ti.com/product/bq24150 * https://www.ti.com/product/bq24150a * https://www.ti.com/product/bq24152 * https://www.ti.com/product/bq24153 * https://www.ti.com/product/bq24153a * https://www.ti.com/product/bq24155 * https://www.ti.com/product/bq24157s * https://www.ti.com/product/bq24158 */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/param.h> #include <linux/err.h> #include <linux/workqueue.h> #include <linux/sysfs.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/idr.h> #include <linux/i2c.h> #include <linux/slab.h> #include <linux/acpi.h> #include <linux/power/bq2415x_charger.h> /* timeout for resetting chip timer */ #define BQ2415X_TIMER_TIMEOUT 10 #define BQ2415X_REG_STATUS 0x00 #define BQ2415X_REG_CONTROL 0x01 #define BQ2415X_REG_VOLTAGE 0x02 #define BQ2415X_REG_VENDER 0x03 #define BQ2415X_REG_CURRENT 0x04 /* reset state for all registers */ #define BQ2415X_RESET_STATUS BIT(6) #define BQ2415X_RESET_CONTROL (BIT(4)|BIT(5)) #define BQ2415X_RESET_VOLTAGE (BIT(1)|BIT(3)) #define BQ2415X_RESET_CURRENT (BIT(0)|BIT(3)|BIT(7)) /* status register */ #define BQ2415X_BIT_TMR_RST 7 #define BQ2415X_BIT_OTG 7 #define BQ2415X_BIT_EN_STAT 6 #define BQ2415X_MASK_STAT (BIT(4)|BIT(5)) #define BQ2415X_SHIFT_STAT 4 #define BQ2415X_BIT_BOOST 3 #define BQ2415X_MASK_FAULT (BIT(0)|BIT(1)|BIT(2)) #define BQ2415X_SHIFT_FAULT 0 /* control register */ #define BQ2415X_MASK_LIMIT (BIT(6)|BIT(7)) #define BQ2415X_SHIFT_LIMIT 6 #define BQ2415X_MASK_VLOWV (BIT(4)|BIT(5)) #define BQ2415X_SHIFT_VLOWV 4 #define BQ2415X_BIT_TE 3 #define BQ2415X_BIT_CE 2 #define BQ2415X_BIT_HZ_MODE 1 #define BQ2415X_BIT_OPA_MODE 0 /* voltage register */ #define BQ2415X_MASK_VO (BIT(2)|BIT(3)|BIT(4)|BIT(5)|BIT(6)|BIT(7)) #define BQ2415X_SHIFT_VO 2 #define BQ2415X_BIT_OTG_PL 1 #define BQ2415X_BIT_OTG_EN 0 /* vender register */ #define BQ2415X_MASK_VENDER (BIT(5)|BIT(6)|BIT(7)) #define BQ2415X_SHIFT_VENDER 5 #define BQ2415X_MASK_PN (BIT(3)|BIT(4)) #define BQ2415X_SHIFT_PN 3 #define BQ2415X_MASK_REVISION (BIT(0)|BIT(1)|BIT(2)) #define BQ2415X_SHIFT_REVISION 0 /* current register */ #define BQ2415X_MASK_RESET BIT(7) #define BQ2415X_MASK_VI_CHRG (BIT(4)|BIT(5)|BIT(6)) #define BQ2415X_SHIFT_VI_CHRG 4 /* N/A BIT(3) */ #define BQ2415X_MASK_VI_TERM (BIT(0)|BIT(1)|BIT(2)) #define BQ2415X_SHIFT_VI_TERM 0 enum bq2415x_command { BQ2415X_TIMER_RESET, BQ2415X_OTG_STATUS, BQ2415X_STAT_PIN_STATUS, BQ2415X_STAT_PIN_ENABLE, BQ2415X_STAT_PIN_DISABLE, BQ2415X_CHARGE_STATUS, BQ2415X_BOOST_STATUS, BQ2415X_FAULT_STATUS, BQ2415X_CHARGE_TERMINATION_STATUS, BQ2415X_CHARGE_TERMINATION_ENABLE, BQ2415X_CHARGE_TERMINATION_DISABLE, BQ2415X_CHARGER_STATUS, BQ2415X_CHARGER_ENABLE, BQ2415X_CHARGER_DISABLE, BQ2415X_HIGH_IMPEDANCE_STATUS, BQ2415X_HIGH_IMPEDANCE_ENABLE, BQ2415X_HIGH_IMPEDANCE_DISABLE, BQ2415X_BOOST_MODE_STATUS, BQ2415X_BOOST_MODE_ENABLE, BQ2415X_BOOST_MODE_DISABLE, BQ2415X_OTG_LEVEL, BQ2415X_OTG_ACTIVATE_HIGH, BQ2415X_OTG_ACTIVATE_LOW, BQ2415X_OTG_PIN_STATUS, BQ2415X_OTG_PIN_ENABLE, BQ2415X_OTG_PIN_DISABLE, BQ2415X_VENDER_CODE, BQ2415X_PART_NUMBER, BQ2415X_REVISION, }; enum bq2415x_chip { BQUNKNOWN, BQ24150, BQ24150A, BQ24151, BQ24151A, BQ24152, BQ24153, BQ24153A, BQ24155, BQ24156, BQ24156A, BQ24157S, BQ24158, }; static char *bq2415x_chip_name[] = { "unknown", "bq24150", "bq24150a", "bq24151", "bq24151a", "bq24152", "bq24153", "bq24153a", "bq24155", "bq24156", "bq24156a", "bq24157s", "bq24158", }; struct bq2415x_device { struct device *dev; struct bq2415x_platform_data init_data; struct power_supply *charger; struct power_supply_desc charger_desc; struct delayed_work work; struct device_node *notify_node; struct notifier_block nb; enum bq2415x_mode reported_mode;/* mode reported by hook function */ enum bq2415x_mode mode; /* currently configured mode */ enum bq2415x_chip chip; const char *timer_error; char *model; char *name; int autotimer; /* 1 - if driver automatically reset timer, 0 - not */ int automode; /* 1 - enabled, 0 - disabled; -1 - not supported */ int id; }; /* each registered chip must have unique id */ static DEFINE_IDR(bq2415x_id); static DEFINE_MUTEX(bq2415x_id_mutex); static DEFINE_MUTEX(bq2415x_timer_mutex); static DEFINE_MUTEX(bq2415x_i2c_mutex); /**** i2c read functions ****/ /* read value from register */ static int bq2415x_i2c_read(struct bq2415x_device *bq, u8 reg) { struct i2c_client *client = to_i2c_client(bq->dev); struct i2c_msg msg[2]; u8 val; int ret; if (!client->adapter) return -ENODEV; msg[0].addr = client->addr; msg[0].flags = 0; msg[0].buf = &reg; msg[0].len = sizeof(reg); msg[1].addr = client->addr; msg[1].flags = I2C_M_RD; msg[1].buf = &val; msg[1].len = sizeof(val); mutex_lock(&bq2415x_i2c_mutex); ret = i2c_transfer(client->adapter, msg, ARRAY_SIZE(msg)); mutex_unlock(&bq2415x_i2c_mutex); if (ret < 0) return ret; return val; } /* read value from register, apply mask and right shift it */ static int bq2415x_i2c_read_mask(struct bq2415x_device *bq, u8 reg, u8 mask, u8 shift) { int ret; if (shift > 8) return -EINVAL; ret = bq2415x_i2c_read(bq, reg); if (ret < 0) return ret; return (ret & mask) >> shift; } /* read value from register and return one specified bit */ static int bq2415x_i2c_read_bit(struct bq2415x_device *bq, u8 reg, u8 bit) { if (bit > 8) return -EINVAL; return bq2415x_i2c_read_mask(bq, reg, BIT(bit), bit); } /**** i2c write functions ****/ /* write value to register */ static int bq2415x_i2c_write(struct bq2415x_device *bq, u8 reg, u8 val) { struct i2c_client *client = to_i2c_client(bq->dev); struct i2c_msg msg[1]; u8 data[2]; int ret; data[0] = reg; data[1] = val; msg[0].addr = client->addr; msg[0].flags = 0; msg[0].buf = data; msg[0].len = ARRAY_SIZE(data); mutex_lock(&bq2415x_i2c_mutex); ret = i2c_transfer(client->adapter, msg, ARRAY_SIZE(msg)); mutex_unlock(&bq2415x_i2c_mutex); /* i2c_transfer returns number of messages transferred */ if (ret < 0) return ret; else if (ret != 1) return -EIO; return 0; } /* read value from register, change it with mask left shifted and write back */ static int bq2415x_i2c_write_mask(struct bq2415x_device *bq, u8 reg, u8 val, u8 mask, u8 shift) { int ret; if (shift > 8) return -EINVAL; ret = bq2415x_i2c_read(bq, reg); if (ret < 0) return ret; ret &= ~mask; ret |= val << shift; return bq2415x_i2c_write(bq, reg, ret); } /* change only one bit in register */ static int bq2415x_i2c_write_bit(struct bq2415x_device *bq, u8 reg, bool val, u8 bit) { if (bit > 8) return -EINVAL; return bq2415x_i2c_write_mask(bq, reg, val, BIT(bit), bit); } /**** global functions ****/ /* exec command function */ static int bq2415x_exec_command(struct bq2415x_device *bq, enum bq2415x_command command) { int ret; switch (command) { case BQ2415X_TIMER_RESET: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_STATUS, 1, BQ2415X_BIT_TMR_RST); case BQ2415X_OTG_STATUS: return bq2415x_i2c_read_bit(bq, BQ2415X_REG_STATUS, BQ2415X_BIT_OTG); case BQ2415X_STAT_PIN_STATUS: return bq2415x_i2c_read_bit(bq, BQ2415X_REG_STATUS, BQ2415X_BIT_EN_STAT); case BQ2415X_STAT_PIN_ENABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_STATUS, 1, BQ2415X_BIT_EN_STAT); case BQ2415X_STAT_PIN_DISABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_STATUS, 0, BQ2415X_BIT_EN_STAT); case BQ2415X_CHARGE_STATUS: return bq2415x_i2c_read_mask(bq, BQ2415X_REG_STATUS, BQ2415X_MASK_STAT, BQ2415X_SHIFT_STAT); case BQ2415X_BOOST_STATUS: return bq2415x_i2c_read_bit(bq, BQ2415X_REG_STATUS, BQ2415X_BIT_BOOST); case BQ2415X_FAULT_STATUS: return bq2415x_i2c_read_mask(bq, BQ2415X_REG_STATUS, BQ2415X_MASK_FAULT, BQ2415X_SHIFT_FAULT); case BQ2415X_CHARGE_TERMINATION_STATUS: return bq2415x_i2c_read_bit(bq, BQ2415X_REG_CONTROL, BQ2415X_BIT_TE); case BQ2415X_CHARGE_TERMINATION_ENABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_CONTROL, 1, BQ2415X_BIT_TE); case BQ2415X_CHARGE_TERMINATION_DISABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_CONTROL, 0, BQ2415X_BIT_TE); case BQ2415X_CHARGER_STATUS: ret = bq2415x_i2c_read_bit(bq, BQ2415X_REG_CONTROL, BQ2415X_BIT_CE); if (ret < 0) return ret; return ret > 0 ? 0 : 1; case BQ2415X_CHARGER_ENABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_CONTROL, 0, BQ2415X_BIT_CE); case BQ2415X_CHARGER_DISABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_CONTROL, 1, BQ2415X_BIT_CE); case BQ2415X_HIGH_IMPEDANCE_STATUS: return bq2415x_i2c_read_bit(bq, BQ2415X_REG_CONTROL, BQ2415X_BIT_HZ_MODE); case BQ2415X_HIGH_IMPEDANCE_ENABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_CONTROL, 1, BQ2415X_BIT_HZ_MODE); case BQ2415X_HIGH_IMPEDANCE_DISABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_CONTROL, 0, BQ2415X_BIT_HZ_MODE); case BQ2415X_BOOST_MODE_STATUS: return bq2415x_i2c_read_bit(bq, BQ2415X_REG_CONTROL, BQ2415X_BIT_OPA_MODE); case BQ2415X_BOOST_MODE_ENABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_CONTROL, 1, BQ2415X_BIT_OPA_MODE); case BQ2415X_BOOST_MODE_DISABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_CONTROL, 0, BQ2415X_BIT_OPA_MODE); case BQ2415X_OTG_LEVEL: return bq2415x_i2c_read_bit(bq, BQ2415X_REG_VOLTAGE, BQ2415X_BIT_OTG_PL); case BQ2415X_OTG_ACTIVATE_HIGH: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_VOLTAGE, 1, BQ2415X_BIT_OTG_PL); case BQ2415X_OTG_ACTIVATE_LOW: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_VOLTAGE, 0, BQ2415X_BIT_OTG_PL); case BQ2415X_OTG_PIN_STATUS: return bq2415x_i2c_read_bit(bq, BQ2415X_REG_VOLTAGE, BQ2415X_BIT_OTG_EN); case BQ2415X_OTG_PIN_ENABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_VOLTAGE, 1, BQ2415X_BIT_OTG_EN); case BQ2415X_OTG_PIN_DISABLE: return bq2415x_i2c_write_bit(bq, BQ2415X_REG_VOLTAGE, 0, BQ2415X_BIT_OTG_EN); case BQ2415X_VENDER_CODE: return bq2415x_i2c_read_mask(bq, BQ2415X_REG_VENDER, BQ2415X_MASK_VENDER, BQ2415X_SHIFT_VENDER); case BQ2415X_PART_NUMBER: return bq2415x_i2c_read_mask(bq, BQ2415X_REG_VENDER, BQ2415X_MASK_PN, BQ2415X_SHIFT_PN); case BQ2415X_REVISION: return bq2415x_i2c_read_mask(bq, BQ2415X_REG_VENDER, BQ2415X_MASK_REVISION, BQ2415X_SHIFT_REVISION); } return -EINVAL; } /* detect chip type */ static enum bq2415x_chip bq2415x_detect_chip(struct bq2415x_device *bq) { struct i2c_client *client = to_i2c_client(bq->dev); int ret = bq2415x_exec_command(bq, BQ2415X_PART_NUMBER); if (ret < 0) return ret; switch (client->addr) { case 0x6b: switch (ret) { case 0: if (bq->chip == BQ24151A) return bq->chip; return BQ24151; case 1: if (bq->chip == BQ24150A || bq->chip == BQ24152 || bq->chip == BQ24155) return bq->chip; return BQ24150; case 2: if (bq->chip == BQ24153A) return bq->chip; return BQ24153; default: return BQUNKNOWN; } break; case 0x6a: switch (ret) { case 0: if (bq->chip == BQ24156A) return bq->chip; return BQ24156; case 2: if (bq->chip == BQ24157S) return bq->chip; return BQ24158; default: return BQUNKNOWN; } break; } return BQUNKNOWN; } /* detect chip revision */ static int bq2415x_detect_revision(struct bq2415x_device *bq) { int ret = bq2415x_exec_command(bq, BQ2415X_REVISION); int chip = bq2415x_detect_chip(bq); if (ret < 0 || chip < 0) return -1; switch (chip) { case BQ24150: case BQ24150A: case BQ24151: case BQ24151A: case BQ24152: if (ret >= 0 && ret <= 3) return ret; return -1; case BQ24153: case BQ24153A: case BQ24156: case BQ24156A: case BQ24157S: case BQ24158: if (ret == 3) return 0; else if (ret == 1) return 1; return -1; case BQ24155: if (ret == 3) return 3; return -1; case BQUNKNOWN: return -1; } return -1; } /* return chip vender code */ static int bq2415x_get_vender_code(struct bq2415x_device *bq) { int ret; ret = bq2415x_exec_command(bq, BQ2415X_VENDER_CODE); if (ret < 0) return 0; /* convert to binary */ return (ret & 0x1) + ((ret >> 1) & 0x1) * 10 + ((ret >> 2) & 0x1) * 100; } /* reset all chip registers to default state */ static void bq2415x_reset_chip(struct bq2415x_device *bq) { bq2415x_i2c_write(bq, BQ2415X_REG_CURRENT, BQ2415X_RESET_CURRENT); bq2415x_i2c_write(bq, BQ2415X_REG_VOLTAGE, BQ2415X_RESET_VOLTAGE); bq2415x_i2c_write(bq, BQ2415X_REG_CONTROL, BQ2415X_RESET_CONTROL); bq2415x_i2c_write(bq, BQ2415X_REG_STATUS, BQ2415X_RESET_STATUS); bq->timer_error = NULL; } /**** properties functions ****/ /* set current limit in mA */ static int bq2415x_set_current_limit(struct bq2415x_device *bq, int mA) { int val; if (mA <= 100) val = 0; else if (mA <= 500) val = 1; else if (mA <= 800) val = 2; else val = 3; return bq2415x_i2c_write_mask(bq, BQ2415X_REG_CONTROL, val, BQ2415X_MASK_LIMIT, BQ2415X_SHIFT_LIMIT); } /* get current limit in mA */ static int bq2415x_get_current_limit(struct bq2415x_device *bq) { int ret; ret = bq2415x_i2c_read_mask(bq, BQ2415X_REG_CONTROL, BQ2415X_MASK_LIMIT, BQ2415X_SHIFT_LIMIT); if (ret < 0) return ret; else if (ret == 0) return 100; else if (ret == 1) return 500; else if (ret == 2) return 800; else if (ret == 3) return 1800; return -EINVAL; } /* set weak battery voltage in mV */ static int bq2415x_set_weak_battery_voltage(struct bq2415x_device *bq, int mV) { int val; /* round to 100mV */ if (mV <= 3400 + 50) val = 0; else if (mV <= 3500 + 50) val = 1; else if (mV <= 3600 + 50) val = 2; else val = 3; return bq2415x_i2c_write_mask(bq, BQ2415X_REG_CONTROL, val, BQ2415X_MASK_VLOWV, BQ2415X_SHIFT_VLOWV); } /* get weak battery voltage in mV */ static int bq2415x_get_weak_battery_voltage(struct bq2415x_device *bq) { int ret; ret = bq2415x_i2c_read_mask(bq, BQ2415X_REG_CONTROL, BQ2415X_MASK_VLOWV, BQ2415X_SHIFT_VLOWV); if (ret < 0) return ret; return 100 * (34 + ret); } /* set battery regulation voltage in mV */ static int bq2415x_set_battery_regulation_voltage(struct bq2415x_device *bq, int mV) { int val = (mV/10 - 350) / 2; /* * According to datasheet, maximum battery regulation voltage is * 4440mV which is b101111 = 47. */ if (val < 0) val = 0; else if (val > 47) return -EINVAL; return bq2415x_i2c_write_mask(bq, BQ2415X_REG_VOLTAGE, val, BQ2415X_MASK_VO, BQ2415X_SHIFT_VO); } /* get battery regulation voltage in mV */ static int bq2415x_get_battery_regulation_voltage(struct bq2415x_device *bq) { int ret = bq2415x_i2c_read_mask(bq, BQ2415X_REG_VOLTAGE, BQ2415X_MASK_VO, BQ2415X_SHIFT_VO); if (ret < 0) return ret; return 10 * (350 + 2*ret); } /* set charge current in mA (platform data must provide resistor sense) */ static int bq2415x_set_charge_current(struct bq2415x_device *bq, int mA) { int val; if (bq->init_data.resistor_sense <= 0) return -EINVAL; val = (mA * bq->init_data.resistor_sense - 37400) / 6800; if (val < 0) val = 0; else if (val > 7) val = 7; return bq2415x_i2c_write_mask(bq, BQ2415X_REG_CURRENT, val, BQ2415X_MASK_VI_CHRG | BQ2415X_MASK_RESET, BQ2415X_SHIFT_VI_CHRG); } /* get charge current in mA (platform data must provide resistor sense) */ static int bq2415x_get_charge_current(struct bq2415x_device *bq) { int ret; if (bq->init_data.resistor_sense <= 0) return -EINVAL; ret = bq2415x_i2c_read_mask(bq, BQ2415X_REG_CURRENT, BQ2415X_MASK_VI_CHRG, BQ2415X_SHIFT_VI_CHRG); if (ret < 0) return ret; return (37400 + 6800*ret) / bq->init_data.resistor_sense; } /* set termination current in mA (platform data must provide resistor sense) */ static int bq2415x_set_termination_current(struct bq2415x_device *bq, int mA) { int val; if (bq->init_data.resistor_sense <= 0) return -EINVAL; val = (mA * bq->init_data.resistor_sense - 3400) / 3400; if (val < 0) val = 0; else if (val > 7) val = 7; return bq2415x_i2c_write_mask(bq, BQ2415X_REG_CURRENT, val, BQ2415X_MASK_VI_TERM | BQ2415X_MASK_RESET, BQ2415X_SHIFT_VI_TERM); } /* get termination current in mA (platform data must provide resistor sense) */ static int bq2415x_get_termination_current(struct bq2415x_device *bq) { int ret; if (bq->init_data.resistor_sense <= 0) return -EINVAL; ret = bq2415x_i2c_read_mask(bq, BQ2415X_REG_CURRENT, BQ2415X_MASK_VI_TERM, BQ2415X_SHIFT_VI_TERM); if (ret < 0) return ret; return (3400 + 3400*ret) / bq->init_data.resistor_sense; } /* set default value of property */ #define bq2415x_set_default_value(bq, prop) \ do { \ int ret = 0; \ if (bq->init_data.prop != -1) \ ret = bq2415x_set_##prop(bq, bq->init_data.prop); \ if (ret < 0) \ return ret; \ } while (0) /* set default values of all properties */ static int bq2415x_set_defaults(struct bq2415x_device *bq) { bq2415x_exec_command(bq, BQ2415X_BOOST_MODE_DISABLE); bq2415x_exec_command(bq, BQ2415X_CHARGER_DISABLE); bq2415x_exec_command(bq, BQ2415X_CHARGE_TERMINATION_DISABLE); bq2415x_set_default_value(bq, current_limit); bq2415x_set_default_value(bq, weak_battery_voltage); bq2415x_set_default_value(bq, battery_regulation_voltage); if (bq->init_data.resistor_sense > 0) { bq2415x_set_default_value(bq, charge_current); bq2415x_set_default_value(bq, termination_current); bq2415x_exec_command(bq, BQ2415X_CHARGE_TERMINATION_ENABLE); } bq2415x_exec_command(bq, BQ2415X_CHARGER_ENABLE); return 0; } /**** charger mode functions ****/ /* set charger mode */ static int bq2415x_set_mode(struct bq2415x_device *bq, enum bq2415x_mode mode) { int ret = 0; int charger = 0; int boost = 0; if (mode == BQ2415X_MODE_BOOST) boost = 1; else if (mode != BQ2415X_MODE_OFF) charger = 1; if (!charger) ret = bq2415x_exec_command(bq, BQ2415X_CHARGER_DISABLE); if (!boost) ret = bq2415x_exec_command(bq, BQ2415X_BOOST_MODE_DISABLE); if (ret < 0) return ret; switch (mode) { case BQ2415X_MODE_OFF: dev_dbg(bq->dev, "changing mode to: Offline\n"); ret = bq2415x_set_current_limit(bq, 100); break; case BQ2415X_MODE_NONE: dev_dbg(bq->dev, "changing mode to: N/A\n"); ret = bq2415x_set_current_limit(bq, 100); break; case BQ2415X_MODE_HOST_CHARGER: dev_dbg(bq->dev, "changing mode to: Host/HUB charger\n"); ret = bq2415x_set_current_limit(bq, 500); break; case BQ2415X_MODE_DEDICATED_CHARGER: dev_dbg(bq->dev, "changing mode to: Dedicated charger\n"); ret = bq2415x_set_current_limit(bq, 1800); break; case BQ2415X_MODE_BOOST: /* Boost mode */ dev_dbg(bq->dev, "changing mode to: Boost\n"); ret = bq2415x_set_current_limit(bq, 100); break; } if (ret < 0) return ret; if (charger) ret = bq2415x_exec_command(bq, BQ2415X_CHARGER_ENABLE); else if (boost) ret = bq2415x_exec_command(bq, BQ2415X_BOOST_MODE_ENABLE); if (ret < 0) return ret; bq2415x_set_default_value(bq, weak_battery_voltage); bq2415x_set_default_value(bq, battery_regulation_voltage); bq->mode = mode; sysfs_notify(&bq->charger->dev.kobj, NULL, "mode"); return 0; } static bool bq2415x_update_reported_mode(struct bq2415x_device *bq, int mA) { enum bq2415x_mode mode; if (mA == 0) mode = BQ2415X_MODE_OFF; else if (mA < 500) mode = BQ2415X_MODE_NONE; else if (mA < 1800) mode = BQ2415X_MODE_HOST_CHARGER; else mode = BQ2415X_MODE_DEDICATED_CHARGER; if (bq->reported_mode == mode) return false; bq->reported_mode = mode; return true; } static int bq2415x_notifier_call(struct notifier_block *nb, unsigned long val, void *v) { struct bq2415x_device *bq = container_of(nb, struct bq2415x_device, nb); struct power_supply *psy = v; union power_supply_propval prop; int ret; if (val != PSY_EVENT_PROP_CHANGED) return NOTIFY_OK; /* Ignore event if it was not send by notify_node/notify_device */ if (bq->notify_node) { if (!psy->dev.parent || psy->dev.parent->of_node != bq->notify_node) return NOTIFY_OK; } else if (bq->init_data.notify_device) { if (strcmp(psy->desc->name, bq->init_data.notify_device) != 0) return NOTIFY_OK; } dev_dbg(bq->dev, "notifier call was called\n"); ret = power_supply_get_property(psy, POWER_SUPPLY_PROP_CURRENT_MAX, &prop); if (ret != 0) return NOTIFY_OK; if (!bq2415x_update_reported_mode(bq, prop.intval)) return NOTIFY_OK; /* if automode is not enabled do not tell about reported_mode */ if (bq->automode < 1) return NOTIFY_OK; schedule_delayed_work(&bq->work, 0); return NOTIFY_OK; } /**** timer functions ****/ /* enable/disable auto resetting chip timer */ static void bq2415x_set_autotimer(struct bq2415x_device *bq, int state) { mutex_lock(&bq2415x_timer_mutex); if (bq->autotimer == state) { mutex_unlock(&bq2415x_timer_mutex); return; } bq->autotimer = state; if (state) { schedule_delayed_work(&bq->work, BQ2415X_TIMER_TIMEOUT * HZ); bq2415x_exec_command(bq, BQ2415X_TIMER_RESET); bq->timer_error = NULL; } else { cancel_delayed_work_sync(&bq->work); } mutex_unlock(&bq2415x_timer_mutex); } /* called by bq2415x_timer_work on timer error */ static void bq2415x_timer_error(struct bq2415x_device *bq, const char *msg) { bq->timer_error = msg; sysfs_notify(&bq->charger->dev.kobj, NULL, "timer"); dev_err(bq->dev, "%s\n", msg); if (bq->automode > 0) bq->automode = 0; bq2415x_set_mode(bq, BQ2415X_MODE_OFF); bq2415x_set_autotimer(bq, 0); } /* delayed work function for auto resetting chip timer */ static void bq2415x_timer_work(struct work_struct *work) { struct bq2415x_device *bq = container_of(work, struct bq2415x_device, work.work); int ret; int error; int boost; if (bq->automode > 0 && (bq->reported_mode != bq->mode)) { sysfs_notify(&bq->charger->dev.kobj, NULL, "reported_mode"); bq2415x_set_mode(bq, bq->reported_mode); } if (!bq->autotimer) return; ret = bq2415x_exec_command(bq, BQ2415X_TIMER_RESET); if (ret < 0) { bq2415x_timer_error(bq, "Resetting timer failed"); return; } boost = bq2415x_exec_command(bq, BQ2415X_BOOST_MODE_STATUS); if (boost < 0) { bq2415x_timer_error(bq, "Unknown error"); return; } error = bq2415x_exec_command(bq, BQ2415X_FAULT_STATUS); if (error < 0) { bq2415x_timer_error(bq, "Unknown error"); return; } if (boost) { switch (error) { /* Non fatal errors, chip is OK */ case 0: /* No error */ break; case 6: /* Timer expired */ dev_err(bq->dev, "Timer expired\n"); break; case 3: /* Battery voltage too low */ dev_err(bq->dev, "Battery voltage to low\n"); break; /* Fatal errors, disable and reset chip */ case 1: /* Overvoltage protection (chip fried) */ bq2415x_timer_error(bq, "Overvoltage protection (chip fried)"); return; case 2: /* Overload */ bq2415x_timer_error(bq, "Overload"); return; case 4: /* Battery overvoltage protection */ bq2415x_timer_error(bq, "Battery overvoltage protection"); return; case 5: /* Thermal shutdown (too hot) */ bq2415x_timer_error(bq, "Thermal shutdown (too hot)"); return; case 7: /* N/A */ bq2415x_timer_error(bq, "Unknown error"); return; } } else { switch (error) { /* Non fatal errors, chip is OK */ case 0: /* No error */ break; case 2: /* Sleep mode */ dev_err(bq->dev, "Sleep mode\n"); break; case 3: /* Poor input source */ dev_err(bq->dev, "Poor input source\n"); break; case 6: /* Timer expired */ dev_err(bq->dev, "Timer expired\n"); break; case 7: /* No battery */ dev_err(bq->dev, "No battery\n"); break; /* Fatal errors, disable and reset chip */ case 1: /* Overvoltage protection (chip fried) */ bq2415x_timer_error(bq, "Overvoltage protection (chip fried)"); return; case 4: /* Battery overvoltage protection */ bq2415x_timer_error(bq, "Battery overvoltage protection"); return; case 5: /* Thermal shutdown (too hot) */ bq2415x_timer_error(bq, "Thermal shutdown (too hot)"); return; } } schedule_delayed_work(&bq->work, BQ2415X_TIMER_TIMEOUT * HZ); } /**** power supply interface code ****/ static enum power_supply_property bq2415x_power_supply_props[] = { /* TODO: maybe add more power supply properties */ POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_MODEL_NAME, }; static int bq2415x_power_supply_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct bq2415x_device *bq = power_supply_get_drvdata(psy); int ret; switch (psp) { case POWER_SUPPLY_PROP_STATUS: ret = bq2415x_exec_command(bq, BQ2415X_CHARGE_STATUS); if (ret < 0) return ret; else if (ret == 0) /* Ready */ val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING; else if (ret == 1) /* Charge in progress */ val->intval = POWER_SUPPLY_STATUS_CHARGING; else if (ret == 2) /* Charge done */ val->intval = POWER_SUPPLY_STATUS_FULL; else val->intval = POWER_SUPPLY_STATUS_UNKNOWN; break; case POWER_SUPPLY_PROP_MODEL_NAME: val->strval = bq->model; break; default: return -EINVAL; } return 0; } static void bq2415x_power_supply_exit(struct bq2415x_device *bq) { bq->autotimer = 0; if (bq->automode > 0) bq->automode = 0; cancel_delayed_work_sync(&bq->work); power_supply_unregister(bq->charger); kfree(bq->model); } /**** additional sysfs entries for power supply interface ****/ /* show *_status entries */ static ssize_t bq2415x_sysfs_show_status(struct device *dev, struct device_attribute *attr, char *buf) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); enum bq2415x_command command; int ret; if (strcmp(attr->attr.name, "otg_status") == 0) command = BQ2415X_OTG_STATUS; else if (strcmp(attr->attr.name, "charge_status") == 0) command = BQ2415X_CHARGE_STATUS; else if (strcmp(attr->attr.name, "boost_status") == 0) command = BQ2415X_BOOST_STATUS; else if (strcmp(attr->attr.name, "fault_status") == 0) command = BQ2415X_FAULT_STATUS; else return -EINVAL; ret = bq2415x_exec_command(bq, command); if (ret < 0) return ret; return sysfs_emit(buf, "%d\n", ret); } /* * set timer entry: * auto - enable auto mode * off - disable auto mode * (other values) - reset chip timer */ static ssize_t bq2415x_sysfs_set_timer(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); int ret = 0; if (strncmp(buf, "auto", 4) == 0) bq2415x_set_autotimer(bq, 1); else if (strncmp(buf, "off", 3) == 0) bq2415x_set_autotimer(bq, 0); else ret = bq2415x_exec_command(bq, BQ2415X_TIMER_RESET); if (ret < 0) return ret; return count; } /* show timer entry (auto or off) */ static ssize_t bq2415x_sysfs_show_timer(struct device *dev, struct device_attribute *attr, char *buf) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); if (bq->timer_error) return sysfs_emit(buf, "%s\n", bq->timer_error); if (bq->autotimer) return sysfs_emit(buf, "auto\n"); return sysfs_emit(buf, "off\n"); } /* * set mode entry: * auto - if automode is supported, enable it and set mode to reported * none - disable charger and boost mode * host - charging mode for host/hub chargers (current limit 500mA) * dedicated - charging mode for dedicated chargers (unlimited current limit) * boost - disable charger and enable boost mode */ static ssize_t bq2415x_sysfs_set_mode(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); enum bq2415x_mode mode; int ret = 0; if (strncmp(buf, "auto", 4) == 0) { if (bq->automode < 0) return -EINVAL; bq->automode = 1; mode = bq->reported_mode; } else if (strncmp(buf, "off", 3) == 0) { if (bq->automode > 0) bq->automode = 0; mode = BQ2415X_MODE_OFF; } else if (strncmp(buf, "none", 4) == 0) { if (bq->automode > 0) bq->automode = 0; mode = BQ2415X_MODE_NONE; } else if (strncmp(buf, "host", 4) == 0) { if (bq->automode > 0) bq->automode = 0; mode = BQ2415X_MODE_HOST_CHARGER; } else if (strncmp(buf, "dedicated", 9) == 0) { if (bq->automode > 0) bq->automode = 0; mode = BQ2415X_MODE_DEDICATED_CHARGER; } else if (strncmp(buf, "boost", 5) == 0) { if (bq->automode > 0) bq->automode = 0; mode = BQ2415X_MODE_BOOST; } else if (strncmp(buf, "reset", 5) == 0) { bq2415x_reset_chip(bq); bq2415x_set_defaults(bq); if (bq->automode <= 0) return count; bq->automode = 1; mode = bq->reported_mode; } else { return -EINVAL; } ret = bq2415x_set_mode(bq, mode); if (ret < 0) return ret; return count; } /* show mode entry (auto, none, host, dedicated or boost) */ static ssize_t bq2415x_sysfs_show_mode(struct device *dev, struct device_attribute *attr, char *buf) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); ssize_t ret = 0; if (bq->automode > 0) ret += sysfs_emit_at(buf, ret, "auto ("); switch (bq->mode) { case BQ2415X_MODE_OFF: ret += sysfs_emit_at(buf, ret, "off"); break; case BQ2415X_MODE_NONE: ret += sysfs_emit_at(buf, ret, "none"); break; case BQ2415X_MODE_HOST_CHARGER: ret += sysfs_emit_at(buf, ret, "host"); break; case BQ2415X_MODE_DEDICATED_CHARGER: ret += sysfs_emit_at(buf, ret, "dedicated"); break; case BQ2415X_MODE_BOOST: ret += sysfs_emit_at(buf, ret, "boost"); break; } if (bq->automode > 0) ret += sysfs_emit_at(buf, ret, ")"); ret += sysfs_emit_at(buf, ret, "\n"); return ret; } /* show reported_mode entry (none, host, dedicated or boost) */ static ssize_t bq2415x_sysfs_show_reported_mode(struct device *dev, struct device_attribute *attr, char *buf) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); if (bq->automode < 0) return -EINVAL; switch (bq->reported_mode) { case BQ2415X_MODE_OFF: return sysfs_emit(buf, "off\n"); case BQ2415X_MODE_NONE: return sysfs_emit(buf, "none\n"); case BQ2415X_MODE_HOST_CHARGER: return sysfs_emit(buf, "host\n"); case BQ2415X_MODE_DEDICATED_CHARGER: return sysfs_emit(buf, "dedicated\n"); case BQ2415X_MODE_BOOST: return sysfs_emit(buf, "boost\n"); } return -EINVAL; } /* directly set raw value to chip register, format: 'register value' */ static ssize_t bq2415x_sysfs_set_registers(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); ssize_t ret = 0; unsigned int reg; unsigned int val; if (sscanf(buf, "%x %x", &reg, &val) != 2) return -EINVAL; if (reg > 4 || val > 255) return -EINVAL; ret = bq2415x_i2c_write(bq, reg, val); if (ret < 0) return ret; return count; } /* print value of chip register, format: 'register=value' */ static ssize_t bq2415x_sysfs_print_reg(struct bq2415x_device *bq, u8 reg, char *buf) { int ret = bq2415x_i2c_read(bq, reg); if (ret < 0) return sysfs_emit(buf, "%#.2x=error %d\n", reg, ret); return sysfs_emit(buf, "%#.2x=%#.2x\n", reg, ret); } /* show all raw values of chip register, format per line: 'register=value' */ static ssize_t bq2415x_sysfs_show_registers(struct device *dev, struct device_attribute *attr, char *buf) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); ssize_t ret = 0; ret += bq2415x_sysfs_print_reg(bq, BQ2415X_REG_STATUS, buf+ret); ret += bq2415x_sysfs_print_reg(bq, BQ2415X_REG_CONTROL, buf+ret); ret += bq2415x_sysfs_print_reg(bq, BQ2415X_REG_VOLTAGE, buf+ret); ret += bq2415x_sysfs_print_reg(bq, BQ2415X_REG_VENDER, buf+ret); ret += bq2415x_sysfs_print_reg(bq, BQ2415X_REG_CURRENT, buf+ret); return ret; } /* set current and voltage limit entries (in mA or mV) */ static ssize_t bq2415x_sysfs_set_limit(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); long val; int ret; if (kstrtol(buf, 10, &val) < 0) return -EINVAL; if (strcmp(attr->attr.name, "current_limit") == 0) ret = bq2415x_set_current_limit(bq, val); else if (strcmp(attr->attr.name, "weak_battery_voltage") == 0) ret = bq2415x_set_weak_battery_voltage(bq, val); else if (strcmp(attr->attr.name, "battery_regulation_voltage") == 0) ret = bq2415x_set_battery_regulation_voltage(bq, val); else if (strcmp(attr->attr.name, "charge_current") == 0) ret = bq2415x_set_charge_current(bq, val); else if (strcmp(attr->attr.name, "termination_current") == 0) ret = bq2415x_set_termination_current(bq, val); else return -EINVAL; if (ret < 0) return ret; return count; } /* show current and voltage limit entries (in mA or mV) */ static ssize_t bq2415x_sysfs_show_limit(struct device *dev, struct device_attribute *attr, char *buf) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); int ret; if (strcmp(attr->attr.name, "current_limit") == 0) ret = bq2415x_get_current_limit(bq); else if (strcmp(attr->attr.name, "weak_battery_voltage") == 0) ret = bq2415x_get_weak_battery_voltage(bq); else if (strcmp(attr->attr.name, "battery_regulation_voltage") == 0) ret = bq2415x_get_battery_regulation_voltage(bq); else if (strcmp(attr->attr.name, "charge_current") == 0) ret = bq2415x_get_charge_current(bq); else if (strcmp(attr->attr.name, "termination_current") == 0) ret = bq2415x_get_termination_current(bq); else return -EINVAL; if (ret < 0) return ret; return sysfs_emit(buf, "%d\n", ret); } /* set *_enable entries */ static ssize_t bq2415x_sysfs_set_enable(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); enum bq2415x_command command; long val; int ret; if (kstrtol(buf, 10, &val) < 0) return -EINVAL; if (strcmp(attr->attr.name, "charge_termination_enable") == 0) command = val ? BQ2415X_CHARGE_TERMINATION_ENABLE : BQ2415X_CHARGE_TERMINATION_DISABLE; else if (strcmp(attr->attr.name, "high_impedance_enable") == 0) command = val ? BQ2415X_HIGH_IMPEDANCE_ENABLE : BQ2415X_HIGH_IMPEDANCE_DISABLE; else if (strcmp(attr->attr.name, "otg_pin_enable") == 0) command = val ? BQ2415X_OTG_PIN_ENABLE : BQ2415X_OTG_PIN_DISABLE; else if (strcmp(attr->attr.name, "stat_pin_enable") == 0) command = val ? BQ2415X_STAT_PIN_ENABLE : BQ2415X_STAT_PIN_DISABLE; else return -EINVAL; ret = bq2415x_exec_command(bq, command); if (ret < 0) return ret; return count; } /* show *_enable entries */ static ssize_t bq2415x_sysfs_show_enable(struct device *dev, struct device_attribute *attr, char *buf) { struct power_supply *psy = dev_get_drvdata(dev); struct bq2415x_device *bq = power_supply_get_drvdata(psy); enum bq2415x_command command; int ret; if (strcmp(attr->attr.name, "charge_termination_enable") == 0) command = BQ2415X_CHARGE_TERMINATION_STATUS; else if (strcmp(attr->attr.name, "high_impedance_enable") == 0) command = BQ2415X_HIGH_IMPEDANCE_STATUS; else if (strcmp(attr->attr.name, "otg_pin_enable") == 0) command = BQ2415X_OTG_PIN_STATUS; else if (strcmp(attr->attr.name, "stat_pin_enable") == 0) command = BQ2415X_STAT_PIN_STATUS; else return -EINVAL; ret = bq2415x_exec_command(bq, command); if (ret < 0) return ret; return sysfs_emit(buf, "%d\n", ret); } static DEVICE_ATTR(current_limit, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_limit, bq2415x_sysfs_set_limit); static DEVICE_ATTR(weak_battery_voltage, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_limit, bq2415x_sysfs_set_limit); static DEVICE_ATTR(battery_regulation_voltage, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_limit, bq2415x_sysfs_set_limit); static DEVICE_ATTR(charge_current, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_limit, bq2415x_sysfs_set_limit); static DEVICE_ATTR(termination_current, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_limit, bq2415x_sysfs_set_limit); static DEVICE_ATTR(charge_termination_enable, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_enable, bq2415x_sysfs_set_enable); static DEVICE_ATTR(high_impedance_enable, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_enable, bq2415x_sysfs_set_enable); static DEVICE_ATTR(otg_pin_enable, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_enable, bq2415x_sysfs_set_enable); static DEVICE_ATTR(stat_pin_enable, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_enable, bq2415x_sysfs_set_enable); static DEVICE_ATTR(reported_mode, S_IRUGO, bq2415x_sysfs_show_reported_mode, NULL); static DEVICE_ATTR(mode, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_mode, bq2415x_sysfs_set_mode); static DEVICE_ATTR(timer, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_timer, bq2415x_sysfs_set_timer); static DEVICE_ATTR(registers, S_IWUSR | S_IRUGO, bq2415x_sysfs_show_registers, bq2415x_sysfs_set_registers); static DEVICE_ATTR(otg_status, S_IRUGO, bq2415x_sysfs_show_status, NULL); static DEVICE_ATTR(charge_status, S_IRUGO, bq2415x_sysfs_show_status, NULL); static DEVICE_ATTR(boost_status, S_IRUGO, bq2415x_sysfs_show_status, NULL); static DEVICE_ATTR(fault_status, S_IRUGO, bq2415x_sysfs_show_status, NULL); static struct attribute *bq2415x_sysfs_attrs[] = { /* * TODO: some (appropriate) of these attrs should be switched to * use power supply class props. */ &dev_attr_current_limit.attr, &dev_attr_weak_battery_voltage.attr, &dev_attr_battery_regulation_voltage.attr, &dev_attr_charge_current.attr, &dev_attr_termination_current.attr, &dev_attr_charge_termination_enable.attr, &dev_attr_high_impedance_enable.attr, &dev_attr_otg_pin_enable.attr, &dev_attr_stat_pin_enable.attr, &dev_attr_reported_mode.attr, &dev_attr_mode.attr, &dev_attr_timer.attr, &dev_attr_registers.attr, &dev_attr_otg_status.attr, &dev_attr_charge_status.attr, &dev_attr_boost_status.attr, &dev_attr_fault_status.attr, NULL, }; ATTRIBUTE_GROUPS(bq2415x_sysfs); static int bq2415x_power_supply_init(struct bq2415x_device *bq) { int ret; int chip; char revstr[8]; struct power_supply_config psy_cfg = { .drv_data = bq, .of_node = bq->dev->of_node, .attr_grp = bq2415x_sysfs_groups, }; bq->charger_desc.name = bq->name; bq->charger_desc.type = POWER_SUPPLY_TYPE_USB; bq->charger_desc.properties = bq2415x_power_supply_props; bq->charger_desc.num_properties = ARRAY_SIZE(bq2415x_power_supply_props); bq->charger_desc.get_property = bq2415x_power_supply_get_property; ret = bq2415x_detect_chip(bq); if (ret < 0) chip = BQUNKNOWN; else chip = ret; ret = bq2415x_detect_revision(bq); if (ret < 0) strcpy(revstr, "unknown"); else sprintf(revstr, "1.%d", ret); bq->model = kasprintf(GFP_KERNEL, "chip %s, revision %s, vender code %.3d", bq2415x_chip_name[chip], revstr, bq2415x_get_vender_code(bq)); if (!bq->model) { dev_err(bq->dev, "failed to allocate model name\n"); return -ENOMEM; } bq->charger = power_supply_register(bq->dev, &bq->charger_desc, &psy_cfg); if (IS_ERR(bq->charger)) { kfree(bq->model); return PTR_ERR(bq->charger); } return 0; } /* main bq2415x probe function */ static int bq2415x_probe(struct i2c_client *client) { const struct i2c_device_id *id = i2c_client_get_device_id(client); int ret; int num; char *name = NULL; struct bq2415x_device *bq; struct device_node *np = client->dev.of_node; struct bq2415x_platform_data *pdata = client->dev.platform_data; const struct acpi_device_id *acpi_id = NULL; struct power_supply *notify_psy = NULL; union power_supply_propval prop; if (!np && !pdata && !ACPI_HANDLE(&client->dev)) { dev_err(&client->dev, "Neither devicetree, nor platform data, nor ACPI support\n"); return -ENODEV; } /* Get new ID for the new device */ mutex_lock(&bq2415x_id_mutex); num = idr_alloc(&bq2415x_id, client, 0, 0, GFP_KERNEL); mutex_unlock(&bq2415x_id_mutex); if (num < 0) return num; if (id) { name = kasprintf(GFP_KERNEL, "%s-%d", id->name, num); } else if (ACPI_HANDLE(&client->dev)) { acpi_id = acpi_match_device(client->dev.driver->acpi_match_table, &client->dev); if (!acpi_id) { dev_err(&client->dev, "failed to match device name\n"); ret = -ENODEV; goto error_1; } name = kasprintf(GFP_KERNEL, "%s-%d", acpi_id->id, num); } if (!name) { dev_err(&client->dev, "failed to allocate device name\n"); ret = -ENOMEM; goto error_1; } bq = devm_kzalloc(&client->dev, sizeof(*bq), GFP_KERNEL); if (!bq) { ret = -ENOMEM; goto error_2; } i2c_set_clientdata(client, bq); bq->id = num; bq->dev = &client->dev; if (id) bq->chip = id->driver_data; else if (ACPI_HANDLE(bq->dev)) bq->chip = acpi_id->driver_data; bq->name = name; bq->mode = BQ2415X_MODE_OFF; bq->reported_mode = BQ2415X_MODE_OFF; bq->autotimer = 0; bq->automode = 0; if (np || ACPI_HANDLE(bq->dev)) { ret = device_property_read_u32(bq->dev, "ti,current-limit", &bq->init_data.current_limit); if (ret) goto error_2; ret = device_property_read_u32(bq->dev, "ti,weak-battery-voltage", &bq->init_data.weak_battery_voltage); if (ret) goto error_2; ret = device_property_read_u32(bq->dev, "ti,battery-regulation-voltage", &bq->init_data.battery_regulation_voltage); if (ret) goto error_2; ret = device_property_read_u32(bq->dev, "ti,charge-current", &bq->init_data.charge_current); if (ret) goto error_2; ret = device_property_read_u32(bq->dev, "ti,termination-current", &bq->init_data.termination_current); if (ret) goto error_2; ret = device_property_read_u32(bq->dev, "ti,resistor-sense", &bq->init_data.resistor_sense); if (ret) goto error_2; if (np) bq->notify_node = of_parse_phandle(np, "ti,usb-charger-detection", 0); } else { memcpy(&bq->init_data, pdata, sizeof(bq->init_data)); } bq2415x_reset_chip(bq); ret = bq2415x_power_supply_init(bq); if (ret) { dev_err(bq->dev, "failed to register power supply: %d\n", ret); goto error_2; } ret = bq2415x_set_defaults(bq); if (ret) { dev_err(bq->dev, "failed to set default values: %d\n", ret); goto error_3; } if (bq->notify_node || bq->init_data.notify_device) { bq->nb.notifier_call = bq2415x_notifier_call; ret = power_supply_reg_notifier(&bq->nb); if (ret) { dev_err(bq->dev, "failed to reg notifier: %d\n", ret); goto error_3; } bq->automode = 1; dev_info(bq->dev, "automode supported, waiting for events\n"); } else { bq->automode = -1; dev_info(bq->dev, "automode not supported\n"); } /* Query for initial reported_mode and set it */ if (bq->nb.notifier_call) { if (np) { notify_psy = power_supply_get_by_phandle(np, "ti,usb-charger-detection"); if (IS_ERR(notify_psy)) notify_psy = NULL; } else if (bq->init_data.notify_device) { notify_psy = power_supply_get_by_name( bq->init_data.notify_device); } } if (notify_psy) { ret = power_supply_get_property(notify_psy, POWER_SUPPLY_PROP_CURRENT_MAX, &prop); power_supply_put(notify_psy); if (ret == 0) { bq2415x_update_reported_mode(bq, prop.intval); bq2415x_set_mode(bq, bq->reported_mode); } } INIT_DELAYED_WORK(&bq->work, bq2415x_timer_work); bq2415x_set_autotimer(bq, 1); dev_info(bq->dev, "driver registered\n"); return 0; error_3: bq2415x_power_supply_exit(bq); error_2: if (bq) of_node_put(bq->notify_node); kfree(name); error_1: mutex_lock(&bq2415x_id_mutex); idr_remove(&bq2415x_id, num); mutex_unlock(&bq2415x_id_mutex); return ret; } /* main bq2415x remove function */ static void bq2415x_remove(struct i2c_client *client) { struct bq2415x_device *bq = i2c_get_clientdata(client); if (bq->nb.notifier_call) power_supply_unreg_notifier(&bq->nb); of_node_put(bq->notify_node); bq2415x_power_supply_exit(bq); bq2415x_reset_chip(bq); mutex_lock(&bq2415x_id_mutex); idr_remove(&bq2415x_id, bq->id); mutex_unlock(&bq2415x_id_mutex); dev_info(bq->dev, "driver unregistered\n"); kfree(bq->name); } static const struct i2c_device_id bq2415x_i2c_id_table[] = { { "bq2415x", BQUNKNOWN }, { "bq24150", BQ24150 }, { "bq24150a", BQ24150A }, { "bq24151", BQ24151 }, { "bq24151a", BQ24151A }, { "bq24152", BQ24152 }, { "bq24153", BQ24153 }, { "bq24153a", BQ24153A }, { "bq24155", BQ24155 }, { "bq24156", BQ24156 }, { "bq24156a", BQ24156A }, { "bq24157s", BQ24157S }, { "bq24158", BQ24158 }, {}, }; MODULE_DEVICE_TABLE(i2c, bq2415x_i2c_id_table); #ifdef CONFIG_ACPI static const struct acpi_device_id bq2415x_i2c_acpi_match[] = { { "BQ2415X", BQUNKNOWN }, { "BQ241500", BQ24150 }, { "BQA24150", BQ24150A }, { "BQ241510", BQ24151 }, { "BQA24151", BQ24151A }, { "BQ241520", BQ24152 }, { "BQ241530", BQ24153 }, { "BQA24153", BQ24153A }, { "BQ241550", BQ24155 }, { "BQ241560", BQ24156 }, { "BQA24156", BQ24156A }, { "BQS24157", BQ24157S }, { "BQ241580", BQ24158 }, {}, }; MODULE_DEVICE_TABLE(acpi, bq2415x_i2c_acpi_match); #endif #ifdef CONFIG_OF static const struct of_device_id bq2415x_of_match_table[] = { { .compatible = "ti,bq24150" }, { .compatible = "ti,bq24150a" }, { .compatible = "ti,bq24151" }, { .compatible = "ti,bq24151a" }, { .compatible = "ti,bq24152" }, { .compatible = "ti,bq24153" }, { .compatible = "ti,bq24153a" }, { .compatible = "ti,bq24155" }, { .compatible = "ti,bq24156" }, { .compatible = "ti,bq24156a" }, { .compatible = "ti,bq24157s" }, { .compatible = "ti,bq24158" }, {}, }; MODULE_DEVICE_TABLE(of, bq2415x_of_match_table); #endif static struct i2c_driver bq2415x_driver = { .driver = { .name = "bq2415x-charger", .of_match_table = of_match_ptr(bq2415x_of_match_table), .acpi_match_table = ACPI_PTR(bq2415x_i2c_acpi_match), }, .probe = bq2415x_probe, .remove = bq2415x_remove, .id_table = bq2415x_i2c_id_table, }; module_i2c_driver(bq2415x_driver); MODULE_AUTHOR("Pali Rohár <[email protected]>"); MODULE_DESCRIPTION("bq2415x charger driver"); MODULE_LICENSE("GPL");
linux-master
drivers/power/supply/bq2415x_charger.c
// SPDX-License-Identifier: GPL-2.0 /* * Generic battery driver using IIO * Copyright (C) 2012, Anish Kumar <[email protected]> * Copyright (c) 2023, Sebastian Reichel <[email protected]> */ #include <linux/interrupt.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/gpio/consumer.h> #include <linux/err.h> #include <linux/timer.h> #include <linux/jiffies.h> #include <linux/errno.h> #include <linux/init.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/iio/consumer.h> #include <linux/iio/types.h> #include <linux/of.h> #include <linux/devm-helpers.h> #define JITTER_DEFAULT 10 /* hope 10ms is enough */ enum gab_chan_type { GAB_VOLTAGE = 0, GAB_CURRENT, GAB_POWER, GAB_TEMP, GAB_MAX_CHAN_TYPE }; /* * gab_chan_name suggests the standard channel names for commonly used * channel types. */ static const char *const gab_chan_name[] = { [GAB_VOLTAGE] = "voltage", [GAB_CURRENT] = "current", [GAB_POWER] = "power", [GAB_TEMP] = "temperature", }; struct gab { struct power_supply *psy; struct power_supply_desc psy_desc; struct iio_channel *channel[GAB_MAX_CHAN_TYPE]; struct delayed_work bat_work; int status; struct gpio_desc *charge_finished; }; static struct gab *to_generic_bat(struct power_supply *psy) { return power_supply_get_drvdata(psy); } static void gab_ext_power_changed(struct power_supply *psy) { struct gab *adc_bat = to_generic_bat(psy); schedule_delayed_work(&adc_bat->bat_work, msecs_to_jiffies(0)); } static const enum power_supply_property gab_props[] = { POWER_SUPPLY_PROP_STATUS, }; /* * This properties are set based on the received platform data and this * should correspond one-to-one with enum chan_type. */ static const enum power_supply_property gab_dyn_props[] = { POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_CURRENT_NOW, POWER_SUPPLY_PROP_POWER_NOW, POWER_SUPPLY_PROP_TEMP, }; static bool gab_charge_finished(struct gab *adc_bat) { if (!adc_bat->charge_finished) return false; return gpiod_get_value(adc_bat->charge_finished); } static int gab_read_channel(struct gab *adc_bat, enum gab_chan_type channel, int *result) { int ret; ret = iio_read_channel_processed(adc_bat->channel[channel], result); if (ret < 0) dev_err(&adc_bat->psy->dev, "read channel error: %d\n", ret); else *result *= 1000; return ret; } static int gab_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct gab *adc_bat = to_generic_bat(psy); switch (psp) { case POWER_SUPPLY_PROP_STATUS: val->intval = adc_bat->status; return 0; case POWER_SUPPLY_PROP_VOLTAGE_NOW: return gab_read_channel(adc_bat, GAB_VOLTAGE, &val->intval); case POWER_SUPPLY_PROP_CURRENT_NOW: return gab_read_channel(adc_bat, GAB_CURRENT, &val->intval); case POWER_SUPPLY_PROP_POWER_NOW: return gab_read_channel(adc_bat, GAB_POWER, &val->intval); case POWER_SUPPLY_PROP_TEMP: return gab_read_channel(adc_bat, GAB_TEMP, &val->intval); default: return -EINVAL; } } static void gab_work(struct work_struct *work) { struct gab *adc_bat; struct delayed_work *delayed_work; int status; delayed_work = to_delayed_work(work); adc_bat = container_of(delayed_work, struct gab, bat_work); status = adc_bat->status; if (!power_supply_am_i_supplied(adc_bat->psy)) adc_bat->status = POWER_SUPPLY_STATUS_DISCHARGING; else if (gab_charge_finished(adc_bat)) adc_bat->status = POWER_SUPPLY_STATUS_NOT_CHARGING; else adc_bat->status = POWER_SUPPLY_STATUS_CHARGING; if (status != adc_bat->status) power_supply_changed(adc_bat->psy); } static irqreturn_t gab_charged(int irq, void *dev_id) { struct gab *adc_bat = dev_id; schedule_delayed_work(&adc_bat->bat_work, msecs_to_jiffies(JITTER_DEFAULT)); return IRQ_HANDLED; } static int gab_probe(struct platform_device *pdev) { struct gab *adc_bat; struct power_supply_desc *psy_desc; struct power_supply_config psy_cfg = {}; enum power_supply_property *properties; int ret = 0; int chan; int index = ARRAY_SIZE(gab_props); bool any = false; adc_bat = devm_kzalloc(&pdev->dev, sizeof(*adc_bat), GFP_KERNEL); if (!adc_bat) return -ENOMEM; psy_cfg.of_node = pdev->dev.of_node; psy_cfg.drv_data = adc_bat; psy_desc = &adc_bat->psy_desc; psy_desc->name = dev_name(&pdev->dev); /* bootup default values for the battery */ adc_bat->status = POWER_SUPPLY_STATUS_DISCHARGING; psy_desc->type = POWER_SUPPLY_TYPE_BATTERY; psy_desc->get_property = gab_get_property; psy_desc->external_power_changed = gab_ext_power_changed; /* * copying the static properties and allocating extra memory for holding * the extra configurable properties received from platform data. */ properties = devm_kcalloc(&pdev->dev, ARRAY_SIZE(gab_props) + ARRAY_SIZE(gab_chan_name), sizeof(*properties), GFP_KERNEL); if (!properties) return -ENOMEM; memcpy(properties, gab_props, sizeof(gab_props)); /* * getting channel from iio and copying the battery properties * based on the channel supported by consumer device. */ for (chan = 0; chan < ARRAY_SIZE(gab_chan_name); chan++) { adc_bat->channel[chan] = devm_iio_channel_get(&pdev->dev, gab_chan_name[chan]); if (IS_ERR(adc_bat->channel[chan])) { ret = PTR_ERR(adc_bat->channel[chan]); if (ret != -ENODEV) return dev_err_probe(&pdev->dev, ret, "Failed to get ADC channel %s\n", gab_chan_name[chan]); adc_bat->channel[chan] = NULL; } else if (adc_bat->channel[chan]) { /* copying properties for supported channels only */ int index2; for (index2 = 0; index2 < index; index2++) { if (properties[index2] == gab_dyn_props[chan]) break; /* already known */ } if (index2 == index) /* really new */ properties[index++] = gab_dyn_props[chan]; any = true; } } /* none of the channels are supported so let's bail out */ if (!any) return dev_err_probe(&pdev->dev, -ENODEV, "Failed to get any ADC channel\n"); /* * Total number of properties is equal to static properties * plus the dynamic properties.Some properties may not be set * as come channels may be not be supported by the device.So * we need to take care of that. */ psy_desc->properties = properties; psy_desc->num_properties = index; adc_bat->psy = devm_power_supply_register(&pdev->dev, psy_desc, &psy_cfg); if (IS_ERR(adc_bat->psy)) return dev_err_probe(&pdev->dev, PTR_ERR(adc_bat->psy), "Failed to register power-supply device\n"); ret = devm_delayed_work_autocancel(&pdev->dev, &adc_bat->bat_work, gab_work); if (ret) return dev_err_probe(&pdev->dev, ret, "Failed to register delayed work\n"); adc_bat->charge_finished = devm_gpiod_get_optional(&pdev->dev, "charged", GPIOD_IN); if (adc_bat->charge_finished) { int irq; irq = gpiod_to_irq(adc_bat->charge_finished); ret = devm_request_any_context_irq(&pdev->dev, irq, gab_charged, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, "battery charged", adc_bat); if (ret < 0) return dev_err_probe(&pdev->dev, ret, "Failed to register irq\n"); } platform_set_drvdata(pdev, adc_bat); /* Schedule timer to check current status */ schedule_delayed_work(&adc_bat->bat_work, msecs_to_jiffies(0)); return 0; } static int __maybe_unused gab_suspend(struct device *dev) { struct gab *adc_bat = dev_get_drvdata(dev); cancel_delayed_work_sync(&adc_bat->bat_work); adc_bat->status = POWER_SUPPLY_STATUS_UNKNOWN; return 0; } static int __maybe_unused gab_resume(struct device *dev) { struct gab *adc_bat = dev_get_drvdata(dev); /* Schedule timer to check current status */ schedule_delayed_work(&adc_bat->bat_work, msecs_to_jiffies(JITTER_DEFAULT)); return 0; } static SIMPLE_DEV_PM_OPS(gab_pm_ops, gab_suspend, gab_resume); static const struct of_device_id gab_match[] = { { .compatible = "adc-battery" }, { } }; MODULE_DEVICE_TABLE(of, gab_match); static struct platform_driver gab_driver = { .driver = { .name = "generic-adc-battery", .pm = &gab_pm_ops, .of_match_table = gab_match, }, .probe = gab_probe, }; module_platform_driver(gab_driver); MODULE_AUTHOR("anish kumar <[email protected]>"); MODULE_DESCRIPTION("generic battery driver using IIO"); MODULE_LICENSE("GPL");
linux-master
drivers/power/supply/generic-adc-battery.c
// SPDX-License-Identifier: GPL-2.0 // Copyright (C) 2018 Spreadtrum Communications Inc. #include <linux/module.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/usb/phy.h> #include <linux/regmap.h> #include <linux/notifier.h> #include <linux/of.h> /* PMIC global registers definition */ #define SC2731_CHARGE_STATUS 0xedc #define SC2731_CHARGE_FULL BIT(4) #define SC2731_MODULE_EN1 0xc0c #define SC2731_CHARGE_EN BIT(5) /* SC2731 switch charger registers definition */ #define SC2731_CHG_CFG0 0x0 #define SC2731_CHG_CFG1 0x4 #define SC2731_CHG_CFG2 0x8 #define SC2731_CHG_CFG3 0xc #define SC2731_CHG_CFG4 0x10 #define SC2731_CHG_CFG5 0x28 /* SC2731_CHG_CFG0 register definition */ #define SC2731_PRECHG_RNG_SHIFT 11 #define SC2731_PRECHG_RNG_MASK GENMASK(12, 11) #define SC2731_TERMINATION_VOL_MASK GENMASK(2, 1) #define SC2731_TERMINATION_VOL_SHIFT 1 #define SC2731_TERMINATION_VOL_CAL_MASK GENMASK(8, 3) #define SC2731_TERMINATION_VOL_CAL_SHIFT 3 #define SC2731_TERMINATION_CUR_MASK GENMASK(2, 0) #define SC2731_CC_EN BIT(13) #define SC2731_CHARGER_PD BIT(0) /* SC2731_CHG_CFG1 register definition */ #define SC2731_CUR_MASK GENMASK(5, 0) /* SC2731_CHG_CFG5 register definition */ #define SC2731_CUR_LIMIT_SHIFT 8 #define SC2731_CUR_LIMIT_MASK GENMASK(9, 8) /* Default current definition (unit is mA) */ #define SC2731_CURRENT_LIMIT_100 100 #define SC2731_CURRENT_LIMIT_500 500 #define SC2731_CURRENT_LIMIT_900 900 #define SC2731_CURRENT_LIMIT_2000 2000 #define SC2731_CURRENT_PRECHG 450 #define SC2731_CURRENT_STEP 50 struct sc2731_charger_info { struct device *dev; struct regmap *regmap; struct usb_phy *usb_phy; struct notifier_block usb_notify; struct power_supply *psy_usb; struct work_struct work; struct mutex lock; bool charging; u32 base; u32 limit; }; static void sc2731_charger_stop_charge(struct sc2731_charger_info *info) { regmap_update_bits(info->regmap, info->base + SC2731_CHG_CFG0, SC2731_CC_EN, 0); regmap_update_bits(info->regmap, info->base + SC2731_CHG_CFG0, SC2731_CHARGER_PD, SC2731_CHARGER_PD); } static int sc2731_charger_start_charge(struct sc2731_charger_info *info) { int ret; /* Enable charger constant current mode */ ret = regmap_update_bits(info->regmap, info->base + SC2731_CHG_CFG0, SC2731_CC_EN, SC2731_CC_EN); if (ret) return ret; /* Start charging */ return regmap_update_bits(info->regmap, info->base + SC2731_CHG_CFG0, SC2731_CHARGER_PD, 0); } static int sc2731_charger_set_current_limit(struct sc2731_charger_info *info, u32 limit) { u32 val; if (limit <= SC2731_CURRENT_LIMIT_100) val = 0; else if (limit <= SC2731_CURRENT_LIMIT_500) val = 3; else if (limit <= SC2731_CURRENT_LIMIT_900) val = 2; else val = 1; return regmap_update_bits(info->regmap, info->base + SC2731_CHG_CFG5, SC2731_CUR_LIMIT_MASK, val << SC2731_CUR_LIMIT_SHIFT); } static int sc2731_charger_set_current(struct sc2731_charger_info *info, u32 cur) { u32 val; int ret; if (cur > SC2731_CURRENT_LIMIT_2000) cur = SC2731_CURRENT_LIMIT_2000; else if (cur < SC2731_CURRENT_PRECHG) cur = SC2731_CURRENT_PRECHG; /* Calculate the step value, each step is 50 mA */ val = (cur - SC2731_CURRENT_PRECHG) / SC2731_CURRENT_STEP; /* Set pre-charge current as 450 mA */ ret = regmap_update_bits(info->regmap, info->base + SC2731_CHG_CFG0, SC2731_PRECHG_RNG_MASK, 0x3 << SC2731_PRECHG_RNG_SHIFT); if (ret) return ret; return regmap_update_bits(info->regmap, info->base + SC2731_CHG_CFG1, SC2731_CUR_MASK, val); } static int sc2731_charger_get_status(struct sc2731_charger_info *info) { u32 val; int ret; ret = regmap_read(info->regmap, SC2731_CHARGE_STATUS, &val); if (ret) return ret; if (val & SC2731_CHARGE_FULL) return POWER_SUPPLY_STATUS_FULL; return POWER_SUPPLY_STATUS_CHARGING; } static int sc2731_charger_get_current(struct sc2731_charger_info *info, u32 *cur) { int ret; u32 val; ret = regmap_read(info->regmap, info->base + SC2731_CHG_CFG1, &val); if (ret) return ret; val &= SC2731_CUR_MASK; *cur = val * SC2731_CURRENT_STEP + SC2731_CURRENT_PRECHG; return 0; } static int sc2731_charger_get_current_limit(struct sc2731_charger_info *info, u32 *cur) { int ret; u32 val; ret = regmap_read(info->regmap, info->base + SC2731_CHG_CFG5, &val); if (ret) return ret; val = (val & SC2731_CUR_LIMIT_MASK) >> SC2731_CUR_LIMIT_SHIFT; switch (val) { case 0: *cur = SC2731_CURRENT_LIMIT_100; break; case 1: *cur = SC2731_CURRENT_LIMIT_2000; break; case 2: *cur = SC2731_CURRENT_LIMIT_900; break; case 3: *cur = SC2731_CURRENT_LIMIT_500; break; default: return -EINVAL; } return 0; } static int sc2731_charger_usb_set_property(struct power_supply *psy, enum power_supply_property psp, const union power_supply_propval *val) { struct sc2731_charger_info *info = power_supply_get_drvdata(psy); int ret; mutex_lock(&info->lock); if (!info->charging) { mutex_unlock(&info->lock); return -ENODEV; } switch (psp) { case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT: ret = sc2731_charger_set_current(info, val->intval / 1000); if (ret < 0) dev_err(info->dev, "set charge current failed\n"); break; case POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT: ret = sc2731_charger_set_current_limit(info, val->intval / 1000); if (ret < 0) dev_err(info->dev, "set input current limit failed\n"); break; default: ret = -EINVAL; } mutex_unlock(&info->lock); return ret; } static int sc2731_charger_usb_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct sc2731_charger_info *info = power_supply_get_drvdata(psy); int ret = 0; u32 cur; mutex_lock(&info->lock); switch (psp) { case POWER_SUPPLY_PROP_STATUS: if (info->charging) val->intval = sc2731_charger_get_status(info); else val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING; break; case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT: if (!info->charging) { val->intval = 0; } else { ret = sc2731_charger_get_current(info, &cur); if (ret) goto out; val->intval = cur * 1000; } break; case POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT: if (!info->charging) { val->intval = 0; } else { ret = sc2731_charger_get_current_limit(info, &cur); if (ret) goto out; val->intval = cur * 1000; } break; default: ret = -EINVAL; } out: mutex_unlock(&info->lock); return ret; } static int sc2731_charger_property_is_writeable(struct power_supply *psy, enum power_supply_property psp) { int ret; switch (psp) { case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT: case POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT: ret = 1; break; default: ret = 0; } return ret; } static enum power_supply_property sc2731_usb_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT, POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT, }; static const struct power_supply_desc sc2731_charger_desc = { .name = "sc2731_charger", .type = POWER_SUPPLY_TYPE_USB, .properties = sc2731_usb_props, .num_properties = ARRAY_SIZE(sc2731_usb_props), .get_property = sc2731_charger_usb_get_property, .set_property = sc2731_charger_usb_set_property, .property_is_writeable = sc2731_charger_property_is_writeable, }; static void sc2731_charger_work(struct work_struct *data) { struct sc2731_charger_info *info = container_of(data, struct sc2731_charger_info, work); int ret; mutex_lock(&info->lock); if (info->limit > 0 && !info->charging) { /* set current limitation and start to charge */ ret = sc2731_charger_set_current_limit(info, info->limit); if (ret) goto out; ret = sc2731_charger_set_current(info, info->limit); if (ret) goto out; ret = sc2731_charger_start_charge(info); if (ret) goto out; info->charging = true; } else if (!info->limit && info->charging) { /* Stop charging */ info->charging = false; sc2731_charger_stop_charge(info); } out: mutex_unlock(&info->lock); } static int sc2731_charger_usb_change(struct notifier_block *nb, unsigned long limit, void *data) { struct sc2731_charger_info *info = container_of(nb, struct sc2731_charger_info, usb_notify); info->limit = limit; schedule_work(&info->work); return NOTIFY_OK; } static int sc2731_charger_hw_init(struct sc2731_charger_info *info) { struct power_supply_battery_info *bat_info; u32 term_currrent, term_voltage, cur_val, vol_val; int ret; /* Enable charger module */ ret = regmap_update_bits(info->regmap, SC2731_MODULE_EN1, SC2731_CHARGE_EN, SC2731_CHARGE_EN); if (ret) return ret; ret = power_supply_get_battery_info(info->psy_usb, &bat_info); if (ret) { dev_warn(info->dev, "no battery information is supplied\n"); /* * If no battery information is supplied, we should set * default charge termination current to 120 mA, and default * charge termination voltage to 4.35V. */ cur_val = 0x2; vol_val = 0x1; } else { term_currrent = bat_info->charge_term_current_ua / 1000; if (term_currrent <= 90) cur_val = 0; else if (term_currrent >= 265) cur_val = 0x7; else cur_val = ((term_currrent - 90) / 25) + 1; term_voltage = bat_info->constant_charge_voltage_max_uv / 1000; if (term_voltage > 4500) term_voltage = 4500; if (term_voltage > 4200) vol_val = (term_voltage - 4200) / 100; else vol_val = 0; power_supply_put_battery_info(info->psy_usb, bat_info); } /* Set charge termination current */ ret = regmap_update_bits(info->regmap, info->base + SC2731_CHG_CFG2, SC2731_TERMINATION_CUR_MASK, cur_val); if (ret) goto error; /* Set charge termination voltage */ ret = regmap_update_bits(info->regmap, info->base + SC2731_CHG_CFG0, SC2731_TERMINATION_VOL_MASK | SC2731_TERMINATION_VOL_CAL_MASK, (vol_val << SC2731_TERMINATION_VOL_SHIFT) | (0x6 << SC2731_TERMINATION_VOL_CAL_SHIFT)); if (ret) goto error; return 0; error: regmap_update_bits(info->regmap, SC2731_MODULE_EN1, SC2731_CHARGE_EN, 0); return ret; } static void sc2731_charger_detect_status(struct sc2731_charger_info *info) { unsigned int min, max; /* * If the USB charger status has been USB_CHARGER_PRESENT before * registering the notifier, we should start to charge with getting * the charge current. */ if (info->usb_phy->chg_state != USB_CHARGER_PRESENT) return; usb_phy_get_charger_current(info->usb_phy, &min, &max); info->limit = min; schedule_work(&info->work); } static int sc2731_charger_probe(struct platform_device *pdev) { struct device_node *np = pdev->dev.of_node; struct sc2731_charger_info *info; struct power_supply_config charger_cfg = { }; int ret; info = devm_kzalloc(&pdev->dev, sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; mutex_init(&info->lock); info->dev = &pdev->dev; INIT_WORK(&info->work, sc2731_charger_work); info->regmap = dev_get_regmap(pdev->dev.parent, NULL); if (!info->regmap) { dev_err(&pdev->dev, "failed to get charger regmap\n"); return -ENODEV; } ret = of_property_read_u32(np, "reg", &info->base); if (ret) { dev_err(&pdev->dev, "failed to get register address\n"); return -ENODEV; } charger_cfg.drv_data = info; charger_cfg.of_node = np; info->psy_usb = devm_power_supply_register(&pdev->dev, &sc2731_charger_desc, &charger_cfg); if (IS_ERR(info->psy_usb)) { dev_err(&pdev->dev, "failed to register power supply\n"); return PTR_ERR(info->psy_usb); } ret = sc2731_charger_hw_init(info); if (ret) return ret; info->usb_phy = devm_usb_get_phy_by_phandle(&pdev->dev, "phys", 0); if (IS_ERR(info->usb_phy)) { dev_err(&pdev->dev, "failed to find USB phy\n"); return PTR_ERR(info->usb_phy); } info->usb_notify.notifier_call = sc2731_charger_usb_change; ret = usb_register_notifier(info->usb_phy, &info->usb_notify); if (ret) { dev_err(&pdev->dev, "failed to register notifier: %d\n", ret); return ret; } sc2731_charger_detect_status(info); return 0; } static int sc2731_charger_remove(struct platform_device *pdev) { struct sc2731_charger_info *info = platform_get_drvdata(pdev); usb_unregister_notifier(info->usb_phy, &info->usb_notify); return 0; } static const struct of_device_id sc2731_charger_of_match[] = { { .compatible = "sprd,sc2731-charger", }, { } }; MODULE_DEVICE_TABLE(of, sc2731_charger_of_match); static struct platform_driver sc2731_charger_driver = { .driver = { .name = "sc2731-charger", .of_match_table = sc2731_charger_of_match, }, .probe = sc2731_charger_probe, .remove = sc2731_charger_remove, }; module_platform_driver(sc2731_charger_driver); MODULE_DESCRIPTION("Spreadtrum SC2731 Charger Driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/power/supply/sc2731_charger.c
// SPDX-License-Identifier: GPL-2.0-only /* * 1-wire client/driver for the Maxim/Dallas DS2780 Stand-Alone Fuel Gauge IC * * Copyright (C) 2010 Indesign, LLC * * Author: Clifton Barnes <[email protected]> * * Based on ds2760_battery and ds2782_battery drivers */ #include <linux/module.h> #include <linux/slab.h> #include <linux/param.h> #include <linux/pm.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/idr.h> #include <linux/w1.h> #include "../../w1/slaves/w1_ds2780.h" /* Current unit measurement in uA for a 1 milli-ohm sense resistor */ #define DS2780_CURRENT_UNITS 1563 /* Charge unit measurement in uAh for a 1 milli-ohm sense resistor */ #define DS2780_CHARGE_UNITS 6250 /* Number of bytes in user EEPROM space */ #define DS2780_USER_EEPROM_SIZE (DS2780_EEPROM_BLOCK0_END - \ DS2780_EEPROM_BLOCK0_START + 1) /* Number of bytes in parameter EEPROM space */ #define DS2780_PARAM_EEPROM_SIZE (DS2780_EEPROM_BLOCK1_END - \ DS2780_EEPROM_BLOCK1_START + 1) struct ds2780_device_info { struct device *dev; struct power_supply *bat; struct power_supply_desc bat_desc; struct device *w1_dev; }; enum current_types { CURRENT_NOW, CURRENT_AVG, }; static const char model[] = "DS2780"; static const char manufacturer[] = "Maxim/Dallas"; static inline struct ds2780_device_info * to_ds2780_device_info(struct power_supply *psy) { return power_supply_get_drvdata(psy); } static inline int ds2780_battery_io(struct ds2780_device_info *dev_info, char *buf, int addr, size_t count, int io) { return w1_ds2780_io(dev_info->w1_dev, buf, addr, count, io); } static inline int ds2780_read8(struct ds2780_device_info *dev_info, u8 *val, int addr) { return ds2780_battery_io(dev_info, val, addr, sizeof(u8), 0); } static int ds2780_read16(struct ds2780_device_info *dev_info, s16 *val, int addr) { int ret; u8 raw[2]; ret = ds2780_battery_io(dev_info, raw, addr, sizeof(raw), 0); if (ret < 0) return ret; *val = (raw[0] << 8) | raw[1]; return 0; } static inline int ds2780_read_block(struct ds2780_device_info *dev_info, u8 *val, int addr, size_t count) { return ds2780_battery_io(dev_info, val, addr, count, 0); } static inline int ds2780_write(struct ds2780_device_info *dev_info, u8 *val, int addr, size_t count) { return ds2780_battery_io(dev_info, val, addr, count, 1); } static inline int ds2780_store_eeprom(struct device *dev, int addr) { return w1_ds2780_eeprom_cmd(dev, addr, W1_DS2780_COPY_DATA); } static inline int ds2780_recall_eeprom(struct device *dev, int addr) { return w1_ds2780_eeprom_cmd(dev, addr, W1_DS2780_RECALL_DATA); } static int ds2780_save_eeprom(struct ds2780_device_info *dev_info, int reg) { int ret; ret = ds2780_store_eeprom(dev_info->w1_dev, reg); if (ret < 0) return ret; ret = ds2780_recall_eeprom(dev_info->w1_dev, reg); if (ret < 0) return ret; return 0; } /* Set sense resistor value in mhos */ static int ds2780_set_sense_register(struct ds2780_device_info *dev_info, u8 conductance) { int ret; ret = ds2780_write(dev_info, &conductance, DS2780_RSNSP_REG, sizeof(u8)); if (ret < 0) return ret; return ds2780_save_eeprom(dev_info, DS2780_RSNSP_REG); } /* Get RSGAIN value from 0 to 1.999 in steps of 0.001 */ static int ds2780_get_rsgain_register(struct ds2780_device_info *dev_info, u16 *rsgain) { return ds2780_read16(dev_info, rsgain, DS2780_RSGAIN_MSB_REG); } /* Set RSGAIN value from 0 to 1.999 in steps of 0.001 */ static int ds2780_set_rsgain_register(struct ds2780_device_info *dev_info, u16 rsgain) { int ret; u8 raw[] = {rsgain >> 8, rsgain & 0xFF}; ret = ds2780_write(dev_info, raw, DS2780_RSGAIN_MSB_REG, sizeof(raw)); if (ret < 0) return ret; return ds2780_save_eeprom(dev_info, DS2780_RSGAIN_MSB_REG); } static int ds2780_get_voltage(struct ds2780_device_info *dev_info, int *voltage_uV) { int ret; s16 voltage_raw; /* * The voltage value is located in 10 bits across the voltage MSB * and LSB registers in two's complement form * Sign bit of the voltage value is in bit 7 of the voltage MSB register * Bits 9 - 3 of the voltage value are in bits 6 - 0 of the * voltage MSB register * Bits 2 - 0 of the voltage value are in bits 7 - 5 of the * voltage LSB register */ ret = ds2780_read16(dev_info, &voltage_raw, DS2780_VOLT_MSB_REG); if (ret < 0) return ret; /* * DS2780 reports voltage in units of 4.88mV, but the battery class * reports in units of uV, so convert by multiplying by 4880. */ *voltage_uV = (voltage_raw / 32) * 4880; return 0; } static int ds2780_get_temperature(struct ds2780_device_info *dev_info, int *temperature) { int ret; s16 temperature_raw; /* * The temperature value is located in 10 bits across the temperature * MSB and LSB registers in two's complement form * Sign bit of the temperature value is in bit 7 of the temperature * MSB register * Bits 9 - 3 of the temperature value are in bits 6 - 0 of the * temperature MSB register * Bits 2 - 0 of the temperature value are in bits 7 - 5 of the * temperature LSB register */ ret = ds2780_read16(dev_info, &temperature_raw, DS2780_TEMP_MSB_REG); if (ret < 0) return ret; /* * Temperature is measured in units of 0.125 degrees celcius, the * power_supply class measures temperature in tenths of degrees * celsius. The temperature value is stored as a 10 bit number, plus * sign in the upper bits of a 16 bit register. */ *temperature = ((temperature_raw / 32) * 125) / 100; return 0; } static int ds2780_get_current(struct ds2780_device_info *dev_info, enum current_types type, int *current_uA) { int ret, sense_res; s16 current_raw; u8 sense_res_raw, reg_msb; /* * The units of measurement for current are dependent on the value of * the sense resistor. */ ret = ds2780_read8(dev_info, &sense_res_raw, DS2780_RSNSP_REG); if (ret < 0) return ret; if (sense_res_raw == 0) { dev_err(dev_info->dev, "sense resistor value is 0\n"); return -EINVAL; } sense_res = 1000 / sense_res_raw; if (type == CURRENT_NOW) reg_msb = DS2780_CURRENT_MSB_REG; else if (type == CURRENT_AVG) reg_msb = DS2780_IAVG_MSB_REG; else return -EINVAL; /* * The current value is located in 16 bits across the current MSB * and LSB registers in two's complement form * Sign bit of the current value is in bit 7 of the current MSB register * Bits 14 - 8 of the current value are in bits 6 - 0 of the current * MSB register * Bits 7 - 0 of the current value are in bits 7 - 0 of the current * LSB register */ ret = ds2780_read16(dev_info, &current_raw, reg_msb); if (ret < 0) return ret; *current_uA = current_raw * (DS2780_CURRENT_UNITS / sense_res); return 0; } static int ds2780_get_accumulated_current(struct ds2780_device_info *dev_info, int *accumulated_current) { int ret, sense_res; s16 current_raw; u8 sense_res_raw; /* * The units of measurement for accumulated current are dependent on * the value of the sense resistor. */ ret = ds2780_read8(dev_info, &sense_res_raw, DS2780_RSNSP_REG); if (ret < 0) return ret; if (sense_res_raw == 0) { dev_err(dev_info->dev, "sense resistor value is 0\n"); return -ENXIO; } sense_res = 1000 / sense_res_raw; /* * The ACR value is located in 16 bits across the ACR MSB and * LSB registers * Bits 15 - 8 of the ACR value are in bits 7 - 0 of the ACR * MSB register * Bits 7 - 0 of the ACR value are in bits 7 - 0 of the ACR * LSB register */ ret = ds2780_read16(dev_info, &current_raw, DS2780_ACR_MSB_REG); if (ret < 0) return ret; *accumulated_current = current_raw * (DS2780_CHARGE_UNITS / sense_res); return 0; } static int ds2780_get_capacity(struct ds2780_device_info *dev_info, int *capacity) { int ret; u8 raw; ret = ds2780_read8(dev_info, &raw, DS2780_RARC_REG); if (ret < 0) return ret; *capacity = raw; return raw; } static int ds2780_get_status(struct ds2780_device_info *dev_info, int *status) { int ret, current_uA, capacity; ret = ds2780_get_current(dev_info, CURRENT_NOW, &current_uA); if (ret < 0) return ret; ret = ds2780_get_capacity(dev_info, &capacity); if (ret < 0) return ret; if (capacity == 100) *status = POWER_SUPPLY_STATUS_FULL; else if (current_uA == 0) *status = POWER_SUPPLY_STATUS_NOT_CHARGING; else if (current_uA < 0) *status = POWER_SUPPLY_STATUS_DISCHARGING; else *status = POWER_SUPPLY_STATUS_CHARGING; return 0; } static int ds2780_get_charge_now(struct ds2780_device_info *dev_info, int *charge_now) { int ret; u16 charge_raw; /* * The RAAC value is located in 16 bits across the RAAC MSB and * LSB registers * Bits 15 - 8 of the RAAC value are in bits 7 - 0 of the RAAC * MSB register * Bits 7 - 0 of the RAAC value are in bits 7 - 0 of the RAAC * LSB register */ ret = ds2780_read16(dev_info, &charge_raw, DS2780_RAAC_MSB_REG); if (ret < 0) return ret; *charge_now = charge_raw * 1600; return 0; } static int ds2780_get_control_register(struct ds2780_device_info *dev_info, u8 *control_reg) { return ds2780_read8(dev_info, control_reg, DS2780_CONTROL_REG); } static int ds2780_set_control_register(struct ds2780_device_info *dev_info, u8 control_reg) { int ret; ret = ds2780_write(dev_info, &control_reg, DS2780_CONTROL_REG, sizeof(u8)); if (ret < 0) return ret; return ds2780_save_eeprom(dev_info, DS2780_CONTROL_REG); } static int ds2780_battery_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { int ret = 0; struct ds2780_device_info *dev_info = to_ds2780_device_info(psy); switch (psp) { case POWER_SUPPLY_PROP_VOLTAGE_NOW: ret = ds2780_get_voltage(dev_info, &val->intval); break; case POWER_SUPPLY_PROP_TEMP: ret = ds2780_get_temperature(dev_info, &val->intval); break; case POWER_SUPPLY_PROP_MODEL_NAME: val->strval = model; break; case POWER_SUPPLY_PROP_MANUFACTURER: val->strval = manufacturer; break; case POWER_SUPPLY_PROP_CURRENT_NOW: ret = ds2780_get_current(dev_info, CURRENT_NOW, &val->intval); break; case POWER_SUPPLY_PROP_CURRENT_AVG: ret = ds2780_get_current(dev_info, CURRENT_AVG, &val->intval); break; case POWER_SUPPLY_PROP_STATUS: ret = ds2780_get_status(dev_info, &val->intval); break; case POWER_SUPPLY_PROP_CAPACITY: ret = ds2780_get_capacity(dev_info, &val->intval); break; case POWER_SUPPLY_PROP_CHARGE_COUNTER: ret = ds2780_get_accumulated_current(dev_info, &val->intval); break; case POWER_SUPPLY_PROP_CHARGE_NOW: ret = ds2780_get_charge_now(dev_info, &val->intval); break; default: ret = -EINVAL; } return ret; } static enum power_supply_property ds2780_battery_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_TEMP, POWER_SUPPLY_PROP_MODEL_NAME, POWER_SUPPLY_PROP_MANUFACTURER, POWER_SUPPLY_PROP_CURRENT_NOW, POWER_SUPPLY_PROP_CURRENT_AVG, POWER_SUPPLY_PROP_CAPACITY, POWER_SUPPLY_PROP_CHARGE_COUNTER, POWER_SUPPLY_PROP_CHARGE_NOW, }; static ssize_t ds2780_get_pmod_enabled(struct device *dev, struct device_attribute *attr, char *buf) { int ret; u8 control_reg; struct power_supply *psy = to_power_supply(dev); struct ds2780_device_info *dev_info = to_ds2780_device_info(psy); /* Get power mode */ ret = ds2780_get_control_register(dev_info, &control_reg); if (ret < 0) return ret; return sysfs_emit(buf, "%d\n", !!(control_reg & DS2780_CONTROL_REG_PMOD)); } static ssize_t ds2780_set_pmod_enabled(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int ret; u8 control_reg, new_setting; struct power_supply *psy = to_power_supply(dev); struct ds2780_device_info *dev_info = to_ds2780_device_info(psy); /* Set power mode */ ret = ds2780_get_control_register(dev_info, &control_reg); if (ret < 0) return ret; ret = kstrtou8(buf, 0, &new_setting); if (ret < 0) return ret; if ((new_setting != 0) && (new_setting != 1)) { dev_err(dev_info->dev, "Invalid pmod setting (0 or 1)\n"); return -EINVAL; } if (new_setting) control_reg |= DS2780_CONTROL_REG_PMOD; else control_reg &= ~DS2780_CONTROL_REG_PMOD; ret = ds2780_set_control_register(dev_info, control_reg); if (ret < 0) return ret; return count; } static ssize_t ds2780_get_sense_resistor_value(struct device *dev, struct device_attribute *attr, char *buf) { int ret; u8 sense_resistor; struct power_supply *psy = to_power_supply(dev); struct ds2780_device_info *dev_info = to_ds2780_device_info(psy); ret = ds2780_read8(dev_info, &sense_resistor, DS2780_RSNSP_REG); if (ret < 0) return ret; ret = sysfs_emit(buf, "%d\n", sense_resistor); return ret; } static ssize_t ds2780_set_sense_resistor_value(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int ret; u8 new_setting; struct power_supply *psy = to_power_supply(dev); struct ds2780_device_info *dev_info = to_ds2780_device_info(psy); ret = kstrtou8(buf, 0, &new_setting); if (ret < 0) return ret; ret = ds2780_set_sense_register(dev_info, new_setting); if (ret < 0) return ret; return count; } static ssize_t ds2780_get_rsgain_setting(struct device *dev, struct device_attribute *attr, char *buf) { int ret; u16 rsgain; struct power_supply *psy = to_power_supply(dev); struct ds2780_device_info *dev_info = to_ds2780_device_info(psy); ret = ds2780_get_rsgain_register(dev_info, &rsgain); if (ret < 0) return ret; return sysfs_emit(buf, "%d\n", rsgain); } static ssize_t ds2780_set_rsgain_setting(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int ret; u16 new_setting; struct power_supply *psy = to_power_supply(dev); struct ds2780_device_info *dev_info = to_ds2780_device_info(psy); ret = kstrtou16(buf, 0, &new_setting); if (ret < 0) return ret; /* Gain can only be from 0 to 1.999 in steps of .001 */ if (new_setting > 1999) { dev_err(dev_info->dev, "Invalid rsgain setting (0 - 1999)\n"); return -EINVAL; } ret = ds2780_set_rsgain_register(dev_info, new_setting); if (ret < 0) return ret; return count; } static ssize_t ds2780_get_pio_pin(struct device *dev, struct device_attribute *attr, char *buf) { int ret; u8 sfr; struct power_supply *psy = to_power_supply(dev); struct ds2780_device_info *dev_info = to_ds2780_device_info(psy); ret = ds2780_read8(dev_info, &sfr, DS2780_SFR_REG); if (ret < 0) return ret; ret = sysfs_emit(buf, "%d\n", sfr & DS2780_SFR_REG_PIOSC); return ret; } static ssize_t ds2780_set_pio_pin(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int ret; u8 new_setting; struct power_supply *psy = to_power_supply(dev); struct ds2780_device_info *dev_info = to_ds2780_device_info(psy); ret = kstrtou8(buf, 0, &new_setting); if (ret < 0) return ret; if ((new_setting != 0) && (new_setting != 1)) { dev_err(dev_info->dev, "Invalid pio_pin setting (0 or 1)\n"); return -EINVAL; } ret = ds2780_write(dev_info, &new_setting, DS2780_SFR_REG, sizeof(u8)); if (ret < 0) return ret; return count; } static ssize_t ds2780_read_param_eeprom_bin(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct device *dev = kobj_to_dev(kobj); struct power_supply *psy = to_power_supply(dev); struct ds2780_device_info *dev_info = to_ds2780_device_info(psy); return ds2780_read_block(dev_info, buf, DS2780_EEPROM_BLOCK1_START + off, count); } static ssize_t ds2780_write_param_eeprom_bin(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct device *dev = kobj_to_dev(kobj); struct power_supply *psy = to_power_supply(dev); struct ds2780_device_info *dev_info = to_ds2780_device_info(psy); int ret; ret = ds2780_write(dev_info, buf, DS2780_EEPROM_BLOCK1_START + off, count); if (ret < 0) return ret; ret = ds2780_save_eeprom(dev_info, DS2780_EEPROM_BLOCK1_START); if (ret < 0) return ret; return count; } static struct bin_attribute ds2780_param_eeprom_bin_attr = { .attr = { .name = "param_eeprom", .mode = S_IRUGO | S_IWUSR, }, .size = DS2780_PARAM_EEPROM_SIZE, .read = ds2780_read_param_eeprom_bin, .write = ds2780_write_param_eeprom_bin, }; static ssize_t ds2780_read_user_eeprom_bin(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct device *dev = kobj_to_dev(kobj); struct power_supply *psy = to_power_supply(dev); struct ds2780_device_info *dev_info = to_ds2780_device_info(psy); return ds2780_read_block(dev_info, buf, DS2780_EEPROM_BLOCK0_START + off, count); } static ssize_t ds2780_write_user_eeprom_bin(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { struct device *dev = kobj_to_dev(kobj); struct power_supply *psy = to_power_supply(dev); struct ds2780_device_info *dev_info = to_ds2780_device_info(psy); int ret; ret = ds2780_write(dev_info, buf, DS2780_EEPROM_BLOCK0_START + off, count); if (ret < 0) return ret; ret = ds2780_save_eeprom(dev_info, DS2780_EEPROM_BLOCK0_START); if (ret < 0) return ret; return count; } static struct bin_attribute ds2780_user_eeprom_bin_attr = { .attr = { .name = "user_eeprom", .mode = S_IRUGO | S_IWUSR, }, .size = DS2780_USER_EEPROM_SIZE, .read = ds2780_read_user_eeprom_bin, .write = ds2780_write_user_eeprom_bin, }; static DEVICE_ATTR(pmod_enabled, S_IRUGO | S_IWUSR, ds2780_get_pmod_enabled, ds2780_set_pmod_enabled); static DEVICE_ATTR(sense_resistor_value, S_IRUGO | S_IWUSR, ds2780_get_sense_resistor_value, ds2780_set_sense_resistor_value); static DEVICE_ATTR(rsgain_setting, S_IRUGO | S_IWUSR, ds2780_get_rsgain_setting, ds2780_set_rsgain_setting); static DEVICE_ATTR(pio_pin, S_IRUGO | S_IWUSR, ds2780_get_pio_pin, ds2780_set_pio_pin); static struct attribute *ds2780_sysfs_attrs[] = { &dev_attr_pmod_enabled.attr, &dev_attr_sense_resistor_value.attr, &dev_attr_rsgain_setting.attr, &dev_attr_pio_pin.attr, NULL }; static struct bin_attribute *ds2780_sysfs_bin_attrs[] = { &ds2780_param_eeprom_bin_attr, &ds2780_user_eeprom_bin_attr, NULL }; static const struct attribute_group ds2780_sysfs_group = { .attrs = ds2780_sysfs_attrs, .bin_attrs = ds2780_sysfs_bin_attrs, }; static const struct attribute_group *ds2780_sysfs_groups[] = { &ds2780_sysfs_group, NULL, }; static int ds2780_battery_probe(struct platform_device *pdev) { struct power_supply_config psy_cfg = {}; struct ds2780_device_info *dev_info; dev_info = devm_kzalloc(&pdev->dev, sizeof(*dev_info), GFP_KERNEL); if (!dev_info) return -ENOMEM; platform_set_drvdata(pdev, dev_info); dev_info->dev = &pdev->dev; dev_info->w1_dev = pdev->dev.parent; dev_info->bat_desc.name = dev_name(&pdev->dev); dev_info->bat_desc.type = POWER_SUPPLY_TYPE_BATTERY; dev_info->bat_desc.properties = ds2780_battery_props; dev_info->bat_desc.num_properties = ARRAY_SIZE(ds2780_battery_props); dev_info->bat_desc.get_property = ds2780_battery_get_property; psy_cfg.drv_data = dev_info; psy_cfg.attr_grp = ds2780_sysfs_groups; dev_info->bat = devm_power_supply_register(&pdev->dev, &dev_info->bat_desc, &psy_cfg); if (IS_ERR(dev_info->bat)) { dev_err(dev_info->dev, "failed to register battery\n"); return PTR_ERR(dev_info->bat); } return 0; } static struct platform_driver ds2780_battery_driver = { .driver = { .name = "ds2780-battery", }, .probe = ds2780_battery_probe, }; module_platform_driver(ds2780_battery_driver); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Clifton Barnes <[email protected]>"); MODULE_DESCRIPTION("Maxim/Dallas DS2780 Stand-Alone Fuel Gauge IC driver"); MODULE_ALIAS("platform:ds2780-battery");
linux-master
drivers/power/supply/ds2780_battery.c
// SPDX-License-Identifier: GPL-2.0-only /* * Battery and Power Management code for the Sharp SL-5x00 * * Copyright (C) 2009 Thomas Kunze * * based on tosa_battery.c */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/power_supply.h> #include <linux/delay.h> #include <linux/spinlock.h> #include <linux/interrupt.h> #include <linux/gpio/driver.h> #include <linux/gpio/machine.h> #include <linux/gpio/consumer.h> #include <linux/mfd/ucb1x00.h> #include <asm/mach/sharpsl_param.h> #include <asm/mach-types.h> #include <mach/collie.h> static DEFINE_MUTEX(bat_lock); /* protects gpio pins */ static struct work_struct bat_work; static struct ucb1x00 *ucb; struct collie_bat { int status; struct power_supply *psy; int full_chrg; struct mutex work_lock; /* protects data */ bool (*is_present)(struct collie_bat *bat); struct gpio_desc *gpio_full; struct gpio_desc *gpio_charge_on; int technology; struct gpio_desc *gpio_bat; int adc_bat; int adc_bat_divider; int bat_max; int bat_min; struct gpio_desc *gpio_temp; int adc_temp; int adc_temp_divider; }; static struct collie_bat collie_bat_main; static unsigned long collie_read_bat(struct collie_bat *bat) { unsigned long value = 0; if (!bat->gpio_bat || bat->adc_bat < 0) return 0; mutex_lock(&bat_lock); gpiod_set_value(bat->gpio_bat, 1); msleep(5); ucb1x00_adc_enable(ucb); value = ucb1x00_adc_read(ucb, bat->adc_bat, UCB_SYNC); ucb1x00_adc_disable(ucb); gpiod_set_value(bat->gpio_bat, 0); mutex_unlock(&bat_lock); value = value * 1000000 / bat->adc_bat_divider; return value; } static unsigned long collie_read_temp(struct collie_bat *bat) { unsigned long value = 0; if (!bat->gpio_temp || bat->adc_temp < 0) return 0; mutex_lock(&bat_lock); gpiod_set_value(bat->gpio_temp, 1); msleep(5); ucb1x00_adc_enable(ucb); value = ucb1x00_adc_read(ucb, bat->adc_temp, UCB_SYNC); ucb1x00_adc_disable(ucb); gpiod_set_value(bat->gpio_temp, 0); mutex_unlock(&bat_lock); value = value * 10000 / bat->adc_temp_divider; return value; } static int collie_bat_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { int ret = 0; struct collie_bat *bat = power_supply_get_drvdata(psy); if (bat->is_present && !bat->is_present(bat) && psp != POWER_SUPPLY_PROP_PRESENT) { return -ENODEV; } switch (psp) { case POWER_SUPPLY_PROP_STATUS: val->intval = bat->status; break; case POWER_SUPPLY_PROP_TECHNOLOGY: val->intval = bat->technology; break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: val->intval = collie_read_bat(bat); break; case POWER_SUPPLY_PROP_VOLTAGE_MAX: if (bat->full_chrg == -1) val->intval = bat->bat_max; else val->intval = bat->full_chrg; break; case POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN: val->intval = bat->bat_max; break; case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN: val->intval = bat->bat_min; break; case POWER_SUPPLY_PROP_TEMP: val->intval = collie_read_temp(bat); break; case POWER_SUPPLY_PROP_PRESENT: val->intval = bat->is_present ? bat->is_present(bat) : 1; break; default: ret = -EINVAL; break; } return ret; } static void collie_bat_external_power_changed(struct power_supply *psy) { schedule_work(&bat_work); } static irqreturn_t collie_bat_gpio_isr(int irq, void *data) { pr_info("collie_bat_gpio irq\n"); schedule_work(&bat_work); return IRQ_HANDLED; } static void collie_bat_update(struct collie_bat *bat) { int old; struct power_supply *psy = bat->psy; mutex_lock(&bat->work_lock); old = bat->status; if (bat->is_present && !bat->is_present(bat)) { printk(KERN_NOTICE "%s not present\n", psy->desc->name); bat->status = POWER_SUPPLY_STATUS_UNKNOWN; bat->full_chrg = -1; } else if (power_supply_am_i_supplied(psy)) { if (bat->status == POWER_SUPPLY_STATUS_DISCHARGING) { gpiod_set_value(bat->gpio_charge_on, 1); mdelay(15); } if (gpiod_get_value(bat->gpio_full)) { if (old == POWER_SUPPLY_STATUS_CHARGING || bat->full_chrg == -1) bat->full_chrg = collie_read_bat(bat); gpiod_set_value(bat->gpio_charge_on, 0); bat->status = POWER_SUPPLY_STATUS_FULL; } else { gpiod_set_value(bat->gpio_charge_on, 1); bat->status = POWER_SUPPLY_STATUS_CHARGING; } } else { gpiod_set_value(bat->gpio_charge_on, 0); bat->status = POWER_SUPPLY_STATUS_DISCHARGING; } if (old != bat->status) power_supply_changed(psy); mutex_unlock(&bat->work_lock); } static void collie_bat_work(struct work_struct *work) { collie_bat_update(&collie_bat_main); } static enum power_supply_property collie_bat_main_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_TECHNOLOGY, POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN, POWER_SUPPLY_PROP_VOLTAGE_MAX, POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_TEMP, }; static enum power_supply_property collie_bat_bu_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_TECHNOLOGY, POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN, POWER_SUPPLY_PROP_VOLTAGE_MAX, POWER_SUPPLY_PROP_PRESENT, }; static const struct power_supply_desc collie_bat_main_desc = { .name = "main-battery", .type = POWER_SUPPLY_TYPE_BATTERY, .properties = collie_bat_main_props, .num_properties = ARRAY_SIZE(collie_bat_main_props), .get_property = collie_bat_get_property, .external_power_changed = collie_bat_external_power_changed, .use_for_apm = 1, }; static struct collie_bat collie_bat_main = { .status = POWER_SUPPLY_STATUS_DISCHARGING, .full_chrg = -1, .psy = NULL, .gpio_full = NULL, .gpio_charge_on = NULL, .technology = POWER_SUPPLY_TECHNOLOGY_LIPO, .gpio_bat = NULL, .adc_bat = UCB_ADC_INP_AD1, .adc_bat_divider = 155, .bat_max = 4310000, .bat_min = 1551 * 1000000 / 414, .gpio_temp = NULL, .adc_temp = UCB_ADC_INP_AD0, .adc_temp_divider = 10000, }; static const struct power_supply_desc collie_bat_bu_desc = { .name = "backup-battery", .type = POWER_SUPPLY_TYPE_BATTERY, .properties = collie_bat_bu_props, .num_properties = ARRAY_SIZE(collie_bat_bu_props), .get_property = collie_bat_get_property, .external_power_changed = collie_bat_external_power_changed, }; static struct collie_bat collie_bat_bu = { .status = POWER_SUPPLY_STATUS_UNKNOWN, .full_chrg = -1, .psy = NULL, .gpio_full = NULL, .gpio_charge_on = NULL, .technology = POWER_SUPPLY_TECHNOLOGY_LiMn, .gpio_bat = NULL, .adc_bat = UCB_ADC_INP_AD1, .adc_bat_divider = 155, .bat_max = 3000000, .bat_min = 1900000, .gpio_temp = NULL, .adc_temp = -1, .adc_temp_divider = -1, }; /* Obtained but unused GPIO */ static struct gpio_desc *collie_mbat_low; #ifdef CONFIG_PM static int wakeup_enabled; static int collie_bat_suspend(struct ucb1x00_dev *dev) { /* flush all pending status updates */ flush_work(&bat_work); if (device_may_wakeup(&dev->ucb->dev) && collie_bat_main.status == POWER_SUPPLY_STATUS_CHARGING) wakeup_enabled = !enable_irq_wake(gpiod_to_irq(collie_bat_main.gpio_full)); else wakeup_enabled = 0; return 0; } static int collie_bat_resume(struct ucb1x00_dev *dev) { if (wakeup_enabled) disable_irq_wake(gpiod_to_irq(collie_bat_main.gpio_full)); /* things may have changed while we were away */ schedule_work(&bat_work); return 0; } #else #define collie_bat_suspend NULL #define collie_bat_resume NULL #endif static int collie_bat_probe(struct ucb1x00_dev *dev) { int ret; struct power_supply_config psy_main_cfg = {}, psy_bu_cfg = {}; struct gpio_chip *gc = &dev->ucb->gpio; if (!machine_is_collie()) return -ENODEV; ucb = dev->ucb; /* Obtain all the main battery GPIOs */ collie_bat_main.gpio_full = gpiod_get(&dev->ucb->dev, "main battery full", GPIOD_IN); if (IS_ERR(collie_bat_main.gpio_full)) return PTR_ERR(collie_bat_main.gpio_full); collie_mbat_low = gpiod_get(&dev->ucb->dev, "main battery low", GPIOD_IN); if (IS_ERR(collie_mbat_low)) { ret = PTR_ERR(collie_mbat_low); goto err_put_gpio_full; } collie_bat_main.gpio_charge_on = gpiod_get(&dev->ucb->dev, "main charge on", GPIOD_OUT_LOW); if (IS_ERR(collie_bat_main.gpio_charge_on)) { ret = PTR_ERR(collie_bat_main.gpio_charge_on); goto err_put_mbat_low; } /* COLLIE_GPIO_MBAT_ON = GPIO 7 on the UCB (TC35143) */ collie_bat_main.gpio_bat = gpiochip_request_own_desc(gc, 7, "main battery", GPIO_ACTIVE_HIGH, GPIOD_OUT_LOW); if (IS_ERR(collie_bat_main.gpio_bat)) { ret = PTR_ERR(collie_bat_main.gpio_bat); goto err_put_gpio_charge_on; } /* COLLIE_GPIO_TMP_ON = GPIO 9 on the UCB (TC35143) */ collie_bat_main.gpio_temp = gpiochip_request_own_desc(gc, 9, "main battery temp", GPIO_ACTIVE_HIGH, GPIOD_OUT_LOW); if (IS_ERR(collie_bat_main.gpio_temp)) { ret = PTR_ERR(collie_bat_main.gpio_temp); goto err_free_gpio_bat; } /* * Obtain the backup battery COLLIE_GPIO_BBAT_ON which is * GPIO 8 on the UCB (TC35143) */ collie_bat_bu.gpio_bat = gpiochip_request_own_desc(gc, 8, "backup battery", GPIO_ACTIVE_HIGH, GPIOD_OUT_LOW); if (IS_ERR(collie_bat_bu.gpio_bat)) { ret = PTR_ERR(collie_bat_bu.gpio_bat); goto err_free_gpio_temp; } mutex_init(&collie_bat_main.work_lock); INIT_WORK(&bat_work, collie_bat_work); psy_main_cfg.drv_data = &collie_bat_main; collie_bat_main.psy = power_supply_register(&dev->ucb->dev, &collie_bat_main_desc, &psy_main_cfg); if (IS_ERR(collie_bat_main.psy)) { ret = PTR_ERR(collie_bat_main.psy); goto err_psy_reg_main; } psy_bu_cfg.drv_data = &collie_bat_bu; collie_bat_bu.psy = power_supply_register(&dev->ucb->dev, &collie_bat_bu_desc, &psy_bu_cfg); if (IS_ERR(collie_bat_bu.psy)) { ret = PTR_ERR(collie_bat_bu.psy); goto err_psy_reg_bu; } ret = request_irq(gpiod_to_irq(collie_bat_main.gpio_full), collie_bat_gpio_isr, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, "main full", &collie_bat_main); if (ret) goto err_irq; device_init_wakeup(&ucb->dev, 1); schedule_work(&bat_work); return 0; err_irq: power_supply_unregister(collie_bat_bu.psy); err_psy_reg_bu: power_supply_unregister(collie_bat_main.psy); err_psy_reg_main: /* see comment in collie_bat_remove */ cancel_work_sync(&bat_work); gpiochip_free_own_desc(collie_bat_bu.gpio_bat); err_free_gpio_temp: gpiochip_free_own_desc(collie_bat_main.gpio_temp); err_free_gpio_bat: gpiochip_free_own_desc(collie_bat_main.gpio_bat); err_put_gpio_charge_on: gpiod_put(collie_bat_main.gpio_charge_on); err_put_mbat_low: gpiod_put(collie_mbat_low); err_put_gpio_full: gpiod_put(collie_bat_main.gpio_full); return ret; } static void collie_bat_remove(struct ucb1x00_dev *dev) { free_irq(gpiod_to_irq(collie_bat_main.gpio_full), &collie_bat_main); power_supply_unregister(collie_bat_bu.psy); power_supply_unregister(collie_bat_main.psy); /* These are obtained from the machine */ gpiod_put(collie_bat_main.gpio_full); gpiod_put(collie_mbat_low); gpiod_put(collie_bat_main.gpio_charge_on); /* These are directly from the UCB so let's free them */ gpiochip_free_own_desc(collie_bat_main.gpio_bat); gpiochip_free_own_desc(collie_bat_main.gpio_temp); gpiochip_free_own_desc(collie_bat_bu.gpio_bat); /* * Now cancel the bat_work. We won't get any more schedules, * since all sources (isr and external_power_changed) are * unregistered now. */ cancel_work_sync(&bat_work); } static struct ucb1x00_driver collie_bat_driver = { .add = collie_bat_probe, .remove = collie_bat_remove, .suspend = collie_bat_suspend, .resume = collie_bat_resume, }; static int __init collie_bat_init(void) { return ucb1x00_register_driver(&collie_bat_driver); } static void __exit collie_bat_exit(void) { ucb1x00_unregister_driver(&collie_bat_driver); } module_init(collie_bat_init); module_exit(collie_bat_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Thomas Kunze"); MODULE_DESCRIPTION("Collie battery driver");
linux-master
drivers/power/supply/collie_battery.c
// SPDX-License-Identifier: GPL-2.0-only /* * Battery driver for wm8350 PMIC * * Copyright 2007, 2008 Wolfson Microelectronics PLC. * * Based on OLPC Battery Driver * * Copyright 2006 David Woodhouse <[email protected]> */ #include <linux/module.h> #include <linux/err.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/mfd/wm8350/supply.h> #include <linux/mfd/wm8350/core.h> #include <linux/mfd/wm8350/comparator.h> static int wm8350_read_battery_uvolts(struct wm8350 *wm8350) { return wm8350_read_auxadc(wm8350, WM8350_AUXADC_BATT, 0, 0) * WM8350_AUX_COEFF; } static int wm8350_read_line_uvolts(struct wm8350 *wm8350) { return wm8350_read_auxadc(wm8350, WM8350_AUXADC_LINE, 0, 0) * WM8350_AUX_COEFF; } static int wm8350_read_usb_uvolts(struct wm8350 *wm8350) { return wm8350_read_auxadc(wm8350, WM8350_AUXADC_USB, 0, 0) * WM8350_AUX_COEFF; } #define WM8350_BATT_SUPPLY 1 #define WM8350_USB_SUPPLY 2 #define WM8350_LINE_SUPPLY 4 static inline int wm8350_charge_time_min(struct wm8350 *wm8350, int min) { if (!wm8350->power.rev_g_coeff) return (((min - 30) / 15) & 0xf) << 8; else return (((min - 30) / 30) & 0xf) << 8; } static int wm8350_get_supplies(struct wm8350 *wm8350) { u16 sm, ov, co, chrg; int supplies = 0; sm = wm8350_reg_read(wm8350, WM8350_STATE_MACHINE_STATUS); ov = wm8350_reg_read(wm8350, WM8350_MISC_OVERRIDES); co = wm8350_reg_read(wm8350, WM8350_COMPARATOR_OVERRIDES); chrg = wm8350_reg_read(wm8350, WM8350_BATTERY_CHARGER_CONTROL_2); /* USB_SM */ sm = (sm & WM8350_USB_SM_MASK) >> WM8350_USB_SM_SHIFT; /* CHG_ISEL */ chrg &= WM8350_CHG_ISEL_MASK; /* If the USB state machine is active then we're using that with or * without battery, otherwise check for wall supply */ if (((sm == WM8350_USB_SM_100_SLV) || (sm == WM8350_USB_SM_500_SLV) || (sm == WM8350_USB_SM_STDBY_SLV)) && !(ov & WM8350_USB_LIMIT_OVRDE)) supplies = WM8350_USB_SUPPLY; else if (((sm == WM8350_USB_SM_100_SLV) || (sm == WM8350_USB_SM_500_SLV) || (sm == WM8350_USB_SM_STDBY_SLV)) && (ov & WM8350_USB_LIMIT_OVRDE) && (chrg == 0)) supplies = WM8350_USB_SUPPLY | WM8350_BATT_SUPPLY; else if (co & WM8350_WALL_FB_OVRDE) supplies = WM8350_LINE_SUPPLY; else supplies = WM8350_BATT_SUPPLY; return supplies; } static int wm8350_charger_config(struct wm8350 *wm8350, struct wm8350_charger_policy *policy) { u16 reg, eoc_mA, fast_limit_mA; if (!policy) { dev_warn(wm8350->dev, "No charger policy, charger not configured.\n"); return -EINVAL; } /* make sure USB fast charge current is not > 500mA */ if (policy->fast_limit_USB_mA > 500) { dev_err(wm8350->dev, "USB fast charge > 500mA\n"); return -EINVAL; } eoc_mA = WM8350_CHG_EOC_mA(policy->eoc_mA); wm8350_reg_unlock(wm8350); reg = wm8350_reg_read(wm8350, WM8350_BATTERY_CHARGER_CONTROL_1) & WM8350_CHG_ENA_R168; wm8350_reg_write(wm8350, WM8350_BATTERY_CHARGER_CONTROL_1, reg | eoc_mA | policy->trickle_start_mV | WM8350_CHG_TRICKLE_TEMP_CHOKE | WM8350_CHG_TRICKLE_USB_CHOKE | WM8350_CHG_FAST_USB_THROTTLE); if (wm8350_get_supplies(wm8350) & WM8350_USB_SUPPLY) { fast_limit_mA = WM8350_CHG_FAST_LIMIT_mA(policy->fast_limit_USB_mA); wm8350_reg_write(wm8350, WM8350_BATTERY_CHARGER_CONTROL_2, policy->charge_mV | policy->trickle_charge_USB_mA | fast_limit_mA | wm8350_charge_time_min(wm8350, policy->charge_timeout)); } else { fast_limit_mA = WM8350_CHG_FAST_LIMIT_mA(policy->fast_limit_mA); wm8350_reg_write(wm8350, WM8350_BATTERY_CHARGER_CONTROL_2, policy->charge_mV | policy->trickle_charge_mA | fast_limit_mA | wm8350_charge_time_min(wm8350, policy->charge_timeout)); } wm8350_reg_lock(wm8350); return 0; } static int wm8350_batt_status(struct wm8350 *wm8350) { u16 state; state = wm8350_reg_read(wm8350, WM8350_BATTERY_CHARGER_CONTROL_2); state &= WM8350_CHG_STS_MASK; switch (state) { case WM8350_CHG_STS_OFF: return POWER_SUPPLY_STATUS_DISCHARGING; case WM8350_CHG_STS_TRICKLE: case WM8350_CHG_STS_FAST: return POWER_SUPPLY_STATUS_CHARGING; default: return POWER_SUPPLY_STATUS_UNKNOWN; } } static ssize_t charger_state_show(struct device *dev, struct device_attribute *attr, char *buf) { struct wm8350 *wm8350 = dev_get_drvdata(dev); char *charge; int state; state = wm8350_reg_read(wm8350, WM8350_BATTERY_CHARGER_CONTROL_2) & WM8350_CHG_STS_MASK; switch (state) { case WM8350_CHG_STS_OFF: charge = "Charger Off"; break; case WM8350_CHG_STS_TRICKLE: charge = "Trickle Charging"; break; case WM8350_CHG_STS_FAST: charge = "Fast Charging"; break; default: return 0; } return sysfs_emit(buf, "%s\n", charge); } static DEVICE_ATTR_RO(charger_state); static irqreturn_t wm8350_charger_handler(int irq, void *data) { struct wm8350 *wm8350 = data; struct wm8350_power *power = &wm8350->power; struct wm8350_charger_policy *policy = power->policy; switch (irq - wm8350->irq_base) { case WM8350_IRQ_CHG_BAT_FAIL: dev_err(wm8350->dev, "battery failed\n"); break; case WM8350_IRQ_CHG_TO: dev_err(wm8350->dev, "charger timeout\n"); power_supply_changed(power->battery); break; case WM8350_IRQ_CHG_BAT_HOT: case WM8350_IRQ_CHG_BAT_COLD: case WM8350_IRQ_CHG_START: case WM8350_IRQ_CHG_END: power_supply_changed(power->battery); break; case WM8350_IRQ_CHG_FAST_RDY: dev_dbg(wm8350->dev, "fast charger ready\n"); wm8350_charger_config(wm8350, policy); wm8350_reg_unlock(wm8350); wm8350_set_bits(wm8350, WM8350_BATTERY_CHARGER_CONTROL_1, WM8350_CHG_FAST); wm8350_reg_lock(wm8350); break; case WM8350_IRQ_CHG_VBATT_LT_3P9: dev_warn(wm8350->dev, "battery < 3.9V\n"); break; case WM8350_IRQ_CHG_VBATT_LT_3P1: dev_warn(wm8350->dev, "battery < 3.1V\n"); break; case WM8350_IRQ_CHG_VBATT_LT_2P85: dev_warn(wm8350->dev, "battery < 2.85V\n"); break; /* Supply change. We will overnotify but it should do * no harm. */ case WM8350_IRQ_EXT_USB_FB: case WM8350_IRQ_EXT_WALL_FB: wm8350_charger_config(wm8350, policy); fallthrough; case WM8350_IRQ_EXT_BAT_FB: power_supply_changed(power->battery); power_supply_changed(power->usb); power_supply_changed(power->ac); break; default: dev_err(wm8350->dev, "Unknown interrupt %d\n", irq); } return IRQ_HANDLED; } /********************************************************************* * AC Power *********************************************************************/ static int wm8350_ac_get_prop(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct wm8350 *wm8350 = dev_get_drvdata(psy->dev.parent); int ret = 0; switch (psp) { case POWER_SUPPLY_PROP_ONLINE: val->intval = !!(wm8350_get_supplies(wm8350) & WM8350_LINE_SUPPLY); break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: val->intval = wm8350_read_line_uvolts(wm8350); break; default: ret = -EINVAL; break; } return ret; } static enum power_supply_property wm8350_ac_props[] = { POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_VOLTAGE_NOW, }; /********************************************************************* * USB Power *********************************************************************/ static int wm8350_usb_get_prop(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct wm8350 *wm8350 = dev_get_drvdata(psy->dev.parent); int ret = 0; switch (psp) { case POWER_SUPPLY_PROP_ONLINE: val->intval = !!(wm8350_get_supplies(wm8350) & WM8350_USB_SUPPLY); break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: val->intval = wm8350_read_usb_uvolts(wm8350); break; default: ret = -EINVAL; break; } return ret; } static enum power_supply_property wm8350_usb_props[] = { POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_VOLTAGE_NOW, }; /********************************************************************* * Battery properties *********************************************************************/ static int wm8350_bat_check_health(struct wm8350 *wm8350) { u16 reg; if (wm8350_read_battery_uvolts(wm8350) < 2850000) return POWER_SUPPLY_HEALTH_UNSPEC_FAILURE; reg = wm8350_reg_read(wm8350, WM8350_CHARGER_OVERRIDES); if (reg & WM8350_CHG_BATT_HOT_OVRDE) return POWER_SUPPLY_HEALTH_OVERHEAT; if (reg & WM8350_CHG_BATT_COLD_OVRDE) return POWER_SUPPLY_HEALTH_COLD; return POWER_SUPPLY_HEALTH_GOOD; } static int wm8350_bat_get_charge_type(struct wm8350 *wm8350) { int state; state = wm8350_reg_read(wm8350, WM8350_BATTERY_CHARGER_CONTROL_2) & WM8350_CHG_STS_MASK; switch (state) { case WM8350_CHG_STS_OFF: return POWER_SUPPLY_CHARGE_TYPE_NONE; case WM8350_CHG_STS_TRICKLE: return POWER_SUPPLY_CHARGE_TYPE_TRICKLE; case WM8350_CHG_STS_FAST: return POWER_SUPPLY_CHARGE_TYPE_FAST; default: return POWER_SUPPLY_CHARGE_TYPE_UNKNOWN; } } static int wm8350_bat_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct wm8350 *wm8350 = dev_get_drvdata(psy->dev.parent); int ret = 0; switch (psp) { case POWER_SUPPLY_PROP_STATUS: val->intval = wm8350_batt_status(wm8350); break; case POWER_SUPPLY_PROP_ONLINE: val->intval = !!(wm8350_get_supplies(wm8350) & WM8350_BATT_SUPPLY); break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: val->intval = wm8350_read_battery_uvolts(wm8350); break; case POWER_SUPPLY_PROP_HEALTH: val->intval = wm8350_bat_check_health(wm8350); break; case POWER_SUPPLY_PROP_CHARGE_TYPE: val->intval = wm8350_bat_get_charge_type(wm8350); break; default: ret = -EINVAL; break; } return ret; } static enum power_supply_property wm8350_bat_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_HEALTH, POWER_SUPPLY_PROP_CHARGE_TYPE, }; static const struct power_supply_desc wm8350_ac_desc = { .name = "wm8350-ac", .type = POWER_SUPPLY_TYPE_MAINS, .properties = wm8350_ac_props, .num_properties = ARRAY_SIZE(wm8350_ac_props), .get_property = wm8350_ac_get_prop, }; static const struct power_supply_desc wm8350_battery_desc = { .name = "wm8350-battery", .properties = wm8350_bat_props, .num_properties = ARRAY_SIZE(wm8350_bat_props), .get_property = wm8350_bat_get_property, .use_for_apm = 1, }; static const struct power_supply_desc wm8350_usb_desc = { .name = "wm8350-usb", .type = POWER_SUPPLY_TYPE_USB, .properties = wm8350_usb_props, .num_properties = ARRAY_SIZE(wm8350_usb_props), .get_property = wm8350_usb_get_prop, }; /********************************************************************* * Initialisation *********************************************************************/ static int wm8350_init_charger(struct wm8350 *wm8350) { int ret; /* register our interest in charger events */ ret = wm8350_register_irq(wm8350, WM8350_IRQ_CHG_BAT_HOT, wm8350_charger_handler, 0, "Battery hot", wm8350); if (ret) goto err; ret = wm8350_register_irq(wm8350, WM8350_IRQ_CHG_BAT_COLD, wm8350_charger_handler, 0, "Battery cold", wm8350); if (ret) goto free_chg_bat_hot; ret = wm8350_register_irq(wm8350, WM8350_IRQ_CHG_BAT_FAIL, wm8350_charger_handler, 0, "Battery fail", wm8350); if (ret) goto free_chg_bat_cold; ret = wm8350_register_irq(wm8350, WM8350_IRQ_CHG_TO, wm8350_charger_handler, 0, "Charger timeout", wm8350); if (ret) goto free_chg_bat_fail; ret = wm8350_register_irq(wm8350, WM8350_IRQ_CHG_END, wm8350_charger_handler, 0, "Charge end", wm8350); if (ret) goto free_chg_to; ret = wm8350_register_irq(wm8350, WM8350_IRQ_CHG_START, wm8350_charger_handler, 0, "Charge start", wm8350); if (ret) goto free_chg_end; ret = wm8350_register_irq(wm8350, WM8350_IRQ_CHG_FAST_RDY, wm8350_charger_handler, 0, "Fast charge ready", wm8350); if (ret) goto free_chg_start; ret = wm8350_register_irq(wm8350, WM8350_IRQ_CHG_VBATT_LT_3P9, wm8350_charger_handler, 0, "Battery <3.9V", wm8350); if (ret) goto free_chg_fast_rdy; ret = wm8350_register_irq(wm8350, WM8350_IRQ_CHG_VBATT_LT_3P1, wm8350_charger_handler, 0, "Battery <3.1V", wm8350); if (ret) goto free_chg_vbatt_lt_3p9; ret = wm8350_register_irq(wm8350, WM8350_IRQ_CHG_VBATT_LT_2P85, wm8350_charger_handler, 0, "Battery <2.85V", wm8350); if (ret) goto free_chg_vbatt_lt_3p1; /* and supply change events */ ret = wm8350_register_irq(wm8350, WM8350_IRQ_EXT_USB_FB, wm8350_charger_handler, 0, "USB", wm8350); if (ret) goto free_chg_vbatt_lt_2p85; ret = wm8350_register_irq(wm8350, WM8350_IRQ_EXT_WALL_FB, wm8350_charger_handler, 0, "Wall", wm8350); if (ret) goto free_ext_usb_fb; ret = wm8350_register_irq(wm8350, WM8350_IRQ_EXT_BAT_FB, wm8350_charger_handler, 0, "Battery", wm8350); if (ret) goto free_ext_wall_fb; return 0; free_ext_wall_fb: wm8350_free_irq(wm8350, WM8350_IRQ_EXT_WALL_FB, wm8350); free_ext_usb_fb: wm8350_free_irq(wm8350, WM8350_IRQ_EXT_USB_FB, wm8350); free_chg_vbatt_lt_2p85: wm8350_free_irq(wm8350, WM8350_IRQ_CHG_VBATT_LT_2P85, wm8350); free_chg_vbatt_lt_3p1: wm8350_free_irq(wm8350, WM8350_IRQ_CHG_VBATT_LT_3P1, wm8350); free_chg_vbatt_lt_3p9: wm8350_free_irq(wm8350, WM8350_IRQ_CHG_VBATT_LT_3P9, wm8350); free_chg_fast_rdy: wm8350_free_irq(wm8350, WM8350_IRQ_CHG_FAST_RDY, wm8350); free_chg_start: wm8350_free_irq(wm8350, WM8350_IRQ_CHG_START, wm8350); free_chg_end: wm8350_free_irq(wm8350, WM8350_IRQ_CHG_END, wm8350); free_chg_to: wm8350_free_irq(wm8350, WM8350_IRQ_CHG_TO, wm8350); free_chg_bat_fail: wm8350_free_irq(wm8350, WM8350_IRQ_CHG_BAT_FAIL, wm8350); free_chg_bat_cold: wm8350_free_irq(wm8350, WM8350_IRQ_CHG_BAT_COLD, wm8350); free_chg_bat_hot: wm8350_free_irq(wm8350, WM8350_IRQ_CHG_BAT_HOT, wm8350); err: return ret; } static void free_charger_irq(struct wm8350 *wm8350) { wm8350_free_irq(wm8350, WM8350_IRQ_CHG_BAT_HOT, wm8350); wm8350_free_irq(wm8350, WM8350_IRQ_CHG_BAT_COLD, wm8350); wm8350_free_irq(wm8350, WM8350_IRQ_CHG_BAT_FAIL, wm8350); wm8350_free_irq(wm8350, WM8350_IRQ_CHG_TO, wm8350); wm8350_free_irq(wm8350, WM8350_IRQ_CHG_END, wm8350); wm8350_free_irq(wm8350, WM8350_IRQ_CHG_START, wm8350); wm8350_free_irq(wm8350, WM8350_IRQ_CHG_FAST_RDY, wm8350); wm8350_free_irq(wm8350, WM8350_IRQ_CHG_VBATT_LT_3P9, wm8350); wm8350_free_irq(wm8350, WM8350_IRQ_CHG_VBATT_LT_3P1, wm8350); wm8350_free_irq(wm8350, WM8350_IRQ_CHG_VBATT_LT_2P85, wm8350); wm8350_free_irq(wm8350, WM8350_IRQ_EXT_USB_FB, wm8350); wm8350_free_irq(wm8350, WM8350_IRQ_EXT_WALL_FB, wm8350); wm8350_free_irq(wm8350, WM8350_IRQ_EXT_BAT_FB, wm8350); } static int wm8350_power_probe(struct platform_device *pdev) { struct wm8350 *wm8350 = platform_get_drvdata(pdev); struct wm8350_power *power = &wm8350->power; struct wm8350_charger_policy *policy = power->policy; int ret; power->ac = power_supply_register(&pdev->dev, &wm8350_ac_desc, NULL); if (IS_ERR(power->ac)) return PTR_ERR(power->ac); power->battery = power_supply_register(&pdev->dev, &wm8350_battery_desc, NULL); if (IS_ERR(power->battery)) { ret = PTR_ERR(power->battery); goto battery_failed; } power->usb = power_supply_register(&pdev->dev, &wm8350_usb_desc, NULL); if (IS_ERR(power->usb)) { ret = PTR_ERR(power->usb); goto usb_failed; } ret = device_create_file(&pdev->dev, &dev_attr_charger_state); if (ret < 0) dev_warn(wm8350->dev, "failed to add charge sysfs: %d\n", ret); ret = 0; wm8350_init_charger(wm8350); if (wm8350_charger_config(wm8350, policy) == 0) { wm8350_reg_unlock(wm8350); wm8350_set_bits(wm8350, WM8350_POWER_MGMT_5, WM8350_CHG_ENA); wm8350_reg_lock(wm8350); } return ret; usb_failed: power_supply_unregister(power->battery); battery_failed: power_supply_unregister(power->ac); return ret; } static int wm8350_power_remove(struct platform_device *pdev) { struct wm8350 *wm8350 = platform_get_drvdata(pdev); struct wm8350_power *power = &wm8350->power; free_charger_irq(wm8350); device_remove_file(&pdev->dev, &dev_attr_charger_state); power_supply_unregister(power->battery); power_supply_unregister(power->ac); power_supply_unregister(power->usb); return 0; } static struct platform_driver wm8350_power_driver = { .probe = wm8350_power_probe, .remove = wm8350_power_remove, .driver = { .name = "wm8350-power", }, }; module_platform_driver(wm8350_power_driver); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Power supply driver for WM8350"); MODULE_ALIAS("platform:wm8350-power");
linux-master
drivers/power/supply/wm8350_power.c
// SPDX-License-Identifier: GPL-2.0+ // // max77693_charger.c - Battery charger driver for the Maxim 77693 // // Copyright (C) 2014 Samsung Electronics // Krzysztof Kozlowski <[email protected]> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/regmap.h> #include <linux/mfd/max77693.h> #include <linux/mfd/max77693-common.h> #include <linux/mfd/max77693-private.h> #define MAX77693_CHARGER_NAME "max77693-charger" static const char *max77693_charger_model = "MAX77693"; static const char *max77693_charger_manufacturer = "Maxim Integrated"; struct max77693_charger { struct device *dev; struct max77693_dev *max77693; struct power_supply *charger; u32 constant_volt; u32 min_system_volt; u32 thermal_regulation_temp; u32 batttery_overcurrent; u32 charge_input_threshold_volt; }; static int max77693_get_charger_state(struct regmap *regmap, int *val) { int ret; unsigned int data; ret = regmap_read(regmap, MAX77693_CHG_REG_CHG_DETAILS_01, &data); if (ret < 0) return ret; data &= CHG_DETAILS_01_CHG_MASK; data >>= CHG_DETAILS_01_CHG_SHIFT; switch (data) { case MAX77693_CHARGING_PREQUALIFICATION: case MAX77693_CHARGING_FAST_CONST_CURRENT: case MAX77693_CHARGING_FAST_CONST_VOLTAGE: case MAX77693_CHARGING_TOP_OFF: /* In high temp the charging current is reduced, but still charging */ case MAX77693_CHARGING_HIGH_TEMP: *val = POWER_SUPPLY_STATUS_CHARGING; break; case MAX77693_CHARGING_DONE: *val = POWER_SUPPLY_STATUS_FULL; break; case MAX77693_CHARGING_TIMER_EXPIRED: case MAX77693_CHARGING_THERMISTOR_SUSPEND: *val = POWER_SUPPLY_STATUS_NOT_CHARGING; break; case MAX77693_CHARGING_OFF: case MAX77693_CHARGING_OVER_TEMP: case MAX77693_CHARGING_WATCHDOG_EXPIRED: *val = POWER_SUPPLY_STATUS_DISCHARGING; break; case MAX77693_CHARGING_RESERVED: default: *val = POWER_SUPPLY_STATUS_UNKNOWN; } return 0; } static int max77693_get_charge_type(struct regmap *regmap, int *val) { int ret; unsigned int data; ret = regmap_read(regmap, MAX77693_CHG_REG_CHG_DETAILS_01, &data); if (ret < 0) return ret; data &= CHG_DETAILS_01_CHG_MASK; data >>= CHG_DETAILS_01_CHG_SHIFT; switch (data) { case MAX77693_CHARGING_PREQUALIFICATION: /* * Top-off: trickle or fast? In top-off the current varies between * 100 and 250 mA. It is higher than prequalification current. */ case MAX77693_CHARGING_TOP_OFF: *val = POWER_SUPPLY_CHARGE_TYPE_TRICKLE; break; case MAX77693_CHARGING_FAST_CONST_CURRENT: case MAX77693_CHARGING_FAST_CONST_VOLTAGE: /* In high temp the charging current is reduced, but still charging */ case MAX77693_CHARGING_HIGH_TEMP: *val = POWER_SUPPLY_CHARGE_TYPE_FAST; break; case MAX77693_CHARGING_DONE: case MAX77693_CHARGING_TIMER_EXPIRED: case MAX77693_CHARGING_THERMISTOR_SUSPEND: case MAX77693_CHARGING_OFF: case MAX77693_CHARGING_OVER_TEMP: case MAX77693_CHARGING_WATCHDOG_EXPIRED: *val = POWER_SUPPLY_CHARGE_TYPE_NONE; break; case MAX77693_CHARGING_RESERVED: default: *val = POWER_SUPPLY_CHARGE_TYPE_UNKNOWN; } return 0; } /* * Supported health statuses: * - POWER_SUPPLY_HEALTH_DEAD * - POWER_SUPPLY_HEALTH_GOOD * - POWER_SUPPLY_HEALTH_OVERVOLTAGE * - POWER_SUPPLY_HEALTH_SAFETY_TIMER_EXPIRE * - POWER_SUPPLY_HEALTH_UNKNOWN * - POWER_SUPPLY_HEALTH_UNSPEC_FAILURE */ static int max77693_get_battery_health(struct regmap *regmap, int *val) { int ret; unsigned int data; ret = regmap_read(regmap, MAX77693_CHG_REG_CHG_DETAILS_01, &data); if (ret < 0) return ret; data &= CHG_DETAILS_01_BAT_MASK; data >>= CHG_DETAILS_01_BAT_SHIFT; switch (data) { case MAX77693_BATTERY_NOBAT: *val = POWER_SUPPLY_HEALTH_DEAD; break; case MAX77693_BATTERY_PREQUALIFICATION: case MAX77693_BATTERY_GOOD: case MAX77693_BATTERY_LOWVOLTAGE: *val = POWER_SUPPLY_HEALTH_GOOD; break; case MAX77693_BATTERY_TIMER_EXPIRED: /* * Took longer to charge than expected, charging suspended. * Damaged battery? */ *val = POWER_SUPPLY_HEALTH_SAFETY_TIMER_EXPIRE; break; case MAX77693_BATTERY_OVERVOLTAGE: *val = POWER_SUPPLY_HEALTH_OVERVOLTAGE; break; case MAX77693_BATTERY_OVERCURRENT: *val = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE; break; case MAX77693_BATTERY_RESERVED: default: *val = POWER_SUPPLY_HEALTH_UNKNOWN; break; } return 0; } static int max77693_get_present(struct regmap *regmap, int *val) { unsigned int data; int ret; /* * Read CHG_INT_OK register. High DETBAT bit here should be * equal to value 0x0 in CHG_DETAILS_01/BAT field. */ ret = regmap_read(regmap, MAX77693_CHG_REG_CHG_INT_OK, &data); if (ret < 0) return ret; *val = (data & CHG_INT_OK_DETBAT_MASK) ? 0 : 1; return 0; } static int max77693_get_online(struct regmap *regmap, int *val) { unsigned int data; int ret; ret = regmap_read(regmap, MAX77693_CHG_REG_CHG_INT_OK, &data); if (ret < 0) return ret; *val = (data & CHG_INT_OK_CHGIN_MASK) ? 1 : 0; return 0; } static enum power_supply_property max77693_charger_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_CHARGE_TYPE, POWER_SUPPLY_PROP_HEALTH, POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_MODEL_NAME, POWER_SUPPLY_PROP_MANUFACTURER, }; static int max77693_charger_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct max77693_charger *chg = power_supply_get_drvdata(psy); struct regmap *regmap = chg->max77693->regmap; int ret = 0; switch (psp) { case POWER_SUPPLY_PROP_STATUS: ret = max77693_get_charger_state(regmap, &val->intval); break; case POWER_SUPPLY_PROP_CHARGE_TYPE: ret = max77693_get_charge_type(regmap, &val->intval); break; case POWER_SUPPLY_PROP_HEALTH: ret = max77693_get_battery_health(regmap, &val->intval); break; case POWER_SUPPLY_PROP_PRESENT: ret = max77693_get_present(regmap, &val->intval); break; case POWER_SUPPLY_PROP_ONLINE: ret = max77693_get_online(regmap, &val->intval); break; case POWER_SUPPLY_PROP_MODEL_NAME: val->strval = max77693_charger_model; break; case POWER_SUPPLY_PROP_MANUFACTURER: val->strval = max77693_charger_manufacturer; break; default: return -EINVAL; } return ret; } static const struct power_supply_desc max77693_charger_desc = { .name = MAX77693_CHARGER_NAME, .type = POWER_SUPPLY_TYPE_BATTERY, .properties = max77693_charger_props, .num_properties = ARRAY_SIZE(max77693_charger_props), .get_property = max77693_charger_get_property, }; static ssize_t device_attr_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count, int (*fn)(struct max77693_charger *, unsigned long)) { struct max77693_charger *chg = dev_get_drvdata(dev); unsigned long val; int ret; ret = kstrtoul(buf, 10, &val); if (ret) return ret; ret = fn(chg, val); if (ret) return ret; return count; } static ssize_t fast_charge_timer_show(struct device *dev, struct device_attribute *attr, char *buf) { struct max77693_charger *chg = dev_get_drvdata(dev); unsigned int data, val; int ret; ret = regmap_read(chg->max77693->regmap, MAX77693_CHG_REG_CHG_CNFG_01, &data); if (ret < 0) return ret; data &= CHG_CNFG_01_FCHGTIME_MASK; data >>= CHG_CNFG_01_FCHGTIME_SHIFT; switch (data) { case 0x1 ... 0x7: /* Starting from 4 hours, step by 2 hours */ val = 4 + (data - 1) * 2; break; case 0x0: default: val = 0; break; } return sysfs_emit(buf, "%u\n", val); } static int max77693_set_fast_charge_timer(struct max77693_charger *chg, unsigned long hours) { unsigned int data; /* * 0x00 - disable * 0x01 - 4h * 0x02 - 6h * ... * 0x07 - 16h * Round down odd values. */ switch (hours) { case 4 ... 16: data = (hours - 4) / 2 + 1; break; case 0: /* Disable */ data = 0; break; default: return -EINVAL; } data <<= CHG_CNFG_01_FCHGTIME_SHIFT; return regmap_update_bits(chg->max77693->regmap, MAX77693_CHG_REG_CHG_CNFG_01, CHG_CNFG_01_FCHGTIME_MASK, data); } static ssize_t fast_charge_timer_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return device_attr_store(dev, attr, buf, count, max77693_set_fast_charge_timer); } static ssize_t top_off_threshold_current_show(struct device *dev, struct device_attribute *attr, char *buf) { struct max77693_charger *chg = dev_get_drvdata(dev); unsigned int data, val; int ret; ret = regmap_read(chg->max77693->regmap, MAX77693_CHG_REG_CHG_CNFG_03, &data); if (ret < 0) return ret; data &= CHG_CNFG_03_TOITH_MASK; data >>= CHG_CNFG_03_TOITH_SHIFT; if (data <= 0x04) val = 100000 + data * 25000; else val = data * 50000; return sysfs_emit(buf, "%u\n", val); } static int max77693_set_top_off_threshold_current(struct max77693_charger *chg, unsigned long uamp) { unsigned int data; if (uamp < 100000 || uamp > 350000) return -EINVAL; if (uamp <= 200000) data = (uamp - 100000) / 25000; else /* (200000, 350000> */ data = uamp / 50000; data <<= CHG_CNFG_03_TOITH_SHIFT; return regmap_update_bits(chg->max77693->regmap, MAX77693_CHG_REG_CHG_CNFG_03, CHG_CNFG_03_TOITH_MASK, data); } static ssize_t top_off_threshold_current_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return device_attr_store(dev, attr, buf, count, max77693_set_top_off_threshold_current); } static ssize_t top_off_timer_show(struct device *dev, struct device_attribute *attr, char *buf) { struct max77693_charger *chg = dev_get_drvdata(dev); unsigned int data, val; int ret; ret = regmap_read(chg->max77693->regmap, MAX77693_CHG_REG_CHG_CNFG_03, &data); if (ret < 0) return ret; data &= CHG_CNFG_03_TOTIME_MASK; data >>= CHG_CNFG_03_TOTIME_SHIFT; val = data * 10; return sysfs_emit(buf, "%u\n", val); } static int max77693_set_top_off_timer(struct max77693_charger *chg, unsigned long minutes) { unsigned int data; if (minutes > 70) return -EINVAL; data = minutes / 10; data <<= CHG_CNFG_03_TOTIME_SHIFT; return regmap_update_bits(chg->max77693->regmap, MAX77693_CHG_REG_CHG_CNFG_03, CHG_CNFG_03_TOTIME_MASK, data); } static ssize_t top_off_timer_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return device_attr_store(dev, attr, buf, count, max77693_set_top_off_timer); } static DEVICE_ATTR_RW(fast_charge_timer); static DEVICE_ATTR_RW(top_off_threshold_current); static DEVICE_ATTR_RW(top_off_timer); static int max77693_set_constant_volt(struct max77693_charger *chg, unsigned int uvolt) { unsigned int data; /* * 0x00 - 3.650 V * 0x01 - 3.675 V * ... * 0x1b - 4.325 V * 0x1c - 4.340 V * 0x1d - 4.350 V * 0x1e - 4.375 V * 0x1f - 4.400 V */ if (uvolt >= 3650000 && uvolt < 4340000) data = (uvolt - 3650000) / 25000; else if (uvolt >= 4340000 && uvolt < 4350000) data = 0x1c; else if (uvolt >= 4350000 && uvolt <= 4400000) data = 0x1d + (uvolt - 4350000) / 25000; else { dev_err(chg->dev, "Wrong value for charging constant voltage\n"); return -EINVAL; } data <<= CHG_CNFG_04_CHGCVPRM_SHIFT; dev_dbg(chg->dev, "Charging constant voltage: %u (0x%x)\n", uvolt, data); return regmap_update_bits(chg->max77693->regmap, MAX77693_CHG_REG_CHG_CNFG_04, CHG_CNFG_04_CHGCVPRM_MASK, data); } static int max77693_set_min_system_volt(struct max77693_charger *chg, unsigned int uvolt) { unsigned int data; if (uvolt < 3000000 || uvolt > 3700000) { dev_err(chg->dev, "Wrong value for minimum system regulation voltage\n"); return -EINVAL; } data = (uvolt - 3000000) / 100000; data <<= CHG_CNFG_04_MINVSYS_SHIFT; dev_dbg(chg->dev, "Minimum system regulation voltage: %u (0x%x)\n", uvolt, data); return regmap_update_bits(chg->max77693->regmap, MAX77693_CHG_REG_CHG_CNFG_04, CHG_CNFG_04_MINVSYS_MASK, data); } static int max77693_set_thermal_regulation_temp(struct max77693_charger *chg, unsigned int cels) { unsigned int data; switch (cels) { case 70: case 85: case 100: case 115: data = (cels - 70) / 15; break; default: dev_err(chg->dev, "Wrong value for thermal regulation loop temperature\n"); return -EINVAL; } data <<= CHG_CNFG_07_REGTEMP_SHIFT; dev_dbg(chg->dev, "Thermal regulation loop temperature: %u (0x%x)\n", cels, data); return regmap_update_bits(chg->max77693->regmap, MAX77693_CHG_REG_CHG_CNFG_07, CHG_CNFG_07_REGTEMP_MASK, data); } static int max77693_set_batttery_overcurrent(struct max77693_charger *chg, unsigned int uamp) { unsigned int data; if (uamp && (uamp < 2000000 || uamp > 3500000)) { dev_err(chg->dev, "Wrong value for battery overcurrent\n"); return -EINVAL; } if (uamp) data = ((uamp - 2000000) / 250000) + 1; else data = 0; /* disable */ data <<= CHG_CNFG_12_B2SOVRC_SHIFT; dev_dbg(chg->dev, "Battery overcurrent: %u (0x%x)\n", uamp, data); return regmap_update_bits(chg->max77693->regmap, MAX77693_CHG_REG_CHG_CNFG_12, CHG_CNFG_12_B2SOVRC_MASK, data); } static int max77693_set_charge_input_threshold_volt(struct max77693_charger *chg, unsigned int uvolt) { unsigned int data; switch (uvolt) { case 4300000: data = 0x0; break; case 4700000: case 4800000: case 4900000: data = (uvolt - 4700000) / 100000; break; default: dev_err(chg->dev, "Wrong value for charge input voltage regulation threshold\n"); return -EINVAL; } data <<= CHG_CNFG_12_VCHGINREG_SHIFT; dev_dbg(chg->dev, "Charge input voltage regulation threshold: %u (0x%x)\n", uvolt, data); return regmap_update_bits(chg->max77693->regmap, MAX77693_CHG_REG_CHG_CNFG_12, CHG_CNFG_12_VCHGINREG_MASK, data); } /* * Sets charger registers to proper and safe default values. */ static int max77693_reg_init(struct max77693_charger *chg) { int ret; unsigned int data; /* Unlock charger register protection */ data = (0x3 << CHG_CNFG_06_CHGPROT_SHIFT); ret = regmap_update_bits(chg->max77693->regmap, MAX77693_CHG_REG_CHG_CNFG_06, CHG_CNFG_06_CHGPROT_MASK, data); if (ret) { dev_err(chg->dev, "Error unlocking registers: %d\n", ret); return ret; } ret = max77693_set_fast_charge_timer(chg, DEFAULT_FAST_CHARGE_TIMER); if (ret) return ret; ret = max77693_set_top_off_threshold_current(chg, DEFAULT_TOP_OFF_THRESHOLD_CURRENT); if (ret) return ret; ret = max77693_set_top_off_timer(chg, DEFAULT_TOP_OFF_TIMER); if (ret) return ret; ret = max77693_set_constant_volt(chg, chg->constant_volt); if (ret) return ret; ret = max77693_set_min_system_volt(chg, chg->min_system_volt); if (ret) return ret; ret = max77693_set_thermal_regulation_temp(chg, chg->thermal_regulation_temp); if (ret) return ret; ret = max77693_set_batttery_overcurrent(chg, chg->batttery_overcurrent); if (ret) return ret; return max77693_set_charge_input_threshold_volt(chg, chg->charge_input_threshold_volt); } #ifdef CONFIG_OF static int max77693_dt_init(struct device *dev, struct max77693_charger *chg) { struct device_node *np = dev->of_node; if (!np) { dev_err(dev, "no charger OF node\n"); return -EINVAL; } if (of_property_read_u32(np, "maxim,constant-microvolt", &chg->constant_volt)) chg->constant_volt = DEFAULT_CONSTANT_VOLT; if (of_property_read_u32(np, "maxim,min-system-microvolt", &chg->min_system_volt)) chg->min_system_volt = DEFAULT_MIN_SYSTEM_VOLT; if (of_property_read_u32(np, "maxim,thermal-regulation-celsius", &chg->thermal_regulation_temp)) chg->thermal_regulation_temp = DEFAULT_THERMAL_REGULATION_TEMP; if (of_property_read_u32(np, "maxim,battery-overcurrent-microamp", &chg->batttery_overcurrent)) chg->batttery_overcurrent = DEFAULT_BATTERY_OVERCURRENT; if (of_property_read_u32(np, "maxim,charge-input-threshold-microvolt", &chg->charge_input_threshold_volt)) chg->charge_input_threshold_volt = DEFAULT_CHARGER_INPUT_THRESHOLD_VOLT; return 0; } #else /* CONFIG_OF */ static int max77693_dt_init(struct device *dev, struct max77693_charger *chg) { return 0; } #endif /* CONFIG_OF */ static int max77693_charger_probe(struct platform_device *pdev) { struct max77693_charger *chg; struct power_supply_config psy_cfg = {}; struct max77693_dev *max77693 = dev_get_drvdata(pdev->dev.parent); int ret; chg = devm_kzalloc(&pdev->dev, sizeof(*chg), GFP_KERNEL); if (!chg) return -ENOMEM; platform_set_drvdata(pdev, chg); chg->dev = &pdev->dev; chg->max77693 = max77693; ret = max77693_dt_init(&pdev->dev, chg); if (ret) return ret; ret = max77693_reg_init(chg); if (ret) return ret; psy_cfg.drv_data = chg; ret = device_create_file(&pdev->dev, &dev_attr_fast_charge_timer); if (ret) { dev_err(&pdev->dev, "failed: create fast charge timer sysfs entry\n"); goto err; } ret = device_create_file(&pdev->dev, &dev_attr_top_off_threshold_current); if (ret) { dev_err(&pdev->dev, "failed: create top off current sysfs entry\n"); goto err; } ret = device_create_file(&pdev->dev, &dev_attr_top_off_timer); if (ret) { dev_err(&pdev->dev, "failed: create top off timer sysfs entry\n"); goto err; } chg->charger = power_supply_register(&pdev->dev, &max77693_charger_desc, &psy_cfg); if (IS_ERR(chg->charger)) { dev_err(&pdev->dev, "failed: power supply register\n"); ret = PTR_ERR(chg->charger); goto err; } return 0; err: device_remove_file(&pdev->dev, &dev_attr_top_off_timer); device_remove_file(&pdev->dev, &dev_attr_top_off_threshold_current); device_remove_file(&pdev->dev, &dev_attr_fast_charge_timer); return ret; } static int max77693_charger_remove(struct platform_device *pdev) { struct max77693_charger *chg = platform_get_drvdata(pdev); device_remove_file(&pdev->dev, &dev_attr_top_off_timer); device_remove_file(&pdev->dev, &dev_attr_top_off_threshold_current); device_remove_file(&pdev->dev, &dev_attr_fast_charge_timer); power_supply_unregister(chg->charger); return 0; } static const struct platform_device_id max77693_charger_id[] = { { "max77693-charger", 0, }, { } }; MODULE_DEVICE_TABLE(platform, max77693_charger_id); static struct platform_driver max77693_charger_driver = { .driver = { .name = "max77693-charger", }, .probe = max77693_charger_probe, .remove = max77693_charger_remove, .id_table = max77693_charger_id, }; module_platform_driver(max77693_charger_driver); MODULE_AUTHOR("Krzysztof Kozlowski <[email protected]>"); MODULE_DESCRIPTION("Maxim 77693 charger driver"); MODULE_LICENSE("GPL");
linux-master
drivers/power/supply/max77693_charger.c
// SPDX-License-Identifier: GPL-2.0-only /* * Battery driver for Marvell 88PM860x PMIC * * Copyright (c) 2012 Marvell International Ltd. * Author: Jett Zhou <[email protected]> * Haojian Zhuang <[email protected]> */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/power_supply.h> #include <linux/mfd/88pm860x.h> #include <linux/delay.h> #include <linux/uaccess.h> #include <asm/div64.h> /* bit definitions of Status Query Interface 2 */ #define STATUS2_CHG (1 << 2) /* bit definitions of Reset Out Register */ #define RESET_SW_PD (1 << 7) /* bit definitions of PreReg 1 */ #define PREREG1_90MA (0x0) #define PREREG1_180MA (0x1) #define PREREG1_450MA (0x4) #define PREREG1_540MA (0x5) #define PREREG1_1350MA (0xE) #define PREREG1_VSYS_4_5V (3 << 4) /* bit definitions of Charger Control 1 Register */ #define CC1_MODE_OFF (0) #define CC1_MODE_PRECHARGE (1) #define CC1_MODE_FASTCHARGE (2) #define CC1_MODE_PULSECHARGE (3) #define CC1_ITERM_20MA (0 << 2) #define CC1_ITERM_60MA (2 << 2) #define CC1_VFCHG_4_2V (9 << 4) /* bit definitions of Charger Control 2 Register */ #define CC2_ICHG_100MA (0x1) #define CC2_ICHG_500MA (0x9) #define CC2_ICHG_1000MA (0x13) /* bit definitions of Charger Control 3 Register */ #define CC3_180MIN_TIMEOUT (0x6 << 4) #define CC3_270MIN_TIMEOUT (0x7 << 4) #define CC3_360MIN_TIMEOUT (0xA << 4) #define CC3_DISABLE_TIMEOUT (0xF << 4) /* bit definitions of Charger Control 4 Register */ #define CC4_IPRE_40MA (7) #define CC4_VPCHG_3_2V (3 << 4) #define CC4_IFCHG_MON_EN (1 << 6) #define CC4_BTEMP_MON_EN (1 << 7) /* bit definitions of Charger Control 6 Register */ #define CC6_BAT_OV_EN (1 << 2) #define CC6_BAT_UV_EN (1 << 3) #define CC6_UV_VBAT_SET (0x3 << 6) /* 2.8v */ /* bit definitions of Charger Control 7 Register */ #define CC7_BAT_REM_EN (1 << 3) #define CC7_IFSM_EN (1 << 7) /* bit definitions of Measurement Enable 1 Register */ #define MEAS1_VBAT (1 << 0) /* bit definitions of Measurement Enable 3 Register */ #define MEAS3_IBAT_EN (1 << 0) #define MEAS3_CC_EN (1 << 2) #define FSM_INIT 0 #define FSM_DISCHARGE 1 #define FSM_PRECHARGE 2 #define FSM_FASTCHARGE 3 #define PRECHARGE_THRESHOLD 3100 #define POWEROFF_THRESHOLD 3400 #define CHARGE_THRESHOLD 4000 #define DISCHARGE_THRESHOLD 4180 /* over-temperature on PM8606 setting */ #define OVER_TEMP_FLAG (1 << 6) #define OVTEMP_AUTORECOVER (1 << 3) /* over-voltage protect on vchg setting mv */ #define VCHG_NORMAL_LOW 4200 #define VCHG_NORMAL_CHECK 5800 #define VCHG_NORMAL_HIGH 6000 #define VCHG_OVP_LOW 5500 struct pm860x_charger_info { struct pm860x_chip *chip; struct i2c_client *i2c; struct i2c_client *i2c_8606; struct device *dev; struct power_supply *usb; struct mutex lock; int irq_nums; int irq[7]; unsigned state:3; /* fsm state */ unsigned online:1; /* usb charger */ unsigned present:1; /* battery present */ unsigned allowed:1; }; static char *pm860x_supplied_to[] = { "battery-monitor", }; static int measure_vchg(struct pm860x_charger_info *info, int *data) { unsigned char buf[2]; int ret = 0; ret = pm860x_bulk_read(info->i2c, PM8607_VCHG_MEAS1, 2, buf); if (ret < 0) return ret; *data = ((buf[0] & 0xff) << 4) | (buf[1] & 0x0f); /* V_BATT_MEAS(mV) = value * 5 * 1.8 * 1000 / (2^12) */ *data = ((*data & 0xfff) * 9 * 125) >> 9; dev_dbg(info->dev, "%s, vchg: %d mv\n", __func__, *data); return ret; } static void set_vchg_threshold(struct pm860x_charger_info *info, int min, int max) { int data; /* (tmp << 8) * / 5 / 1800 */ if (min <= 0) data = 0; else data = (min << 5) / 1125; pm860x_reg_write(info->i2c, PM8607_VCHG_LOWTH, data); dev_dbg(info->dev, "VCHG_LOWTH:%dmv, 0x%x\n", min, data); if (max <= 0) data = 0xff; else data = (max << 5) / 1125; pm860x_reg_write(info->i2c, PM8607_VCHG_HIGHTH, data); dev_dbg(info->dev, "VCHG_HIGHTH:%dmv, 0x%x\n", max, data); } static void set_vbatt_threshold(struct pm860x_charger_info *info, int min, int max) { int data; /* (tmp << 8) * 3 / 1800 */ if (min <= 0) data = 0; else data = (min << 5) / 675; pm860x_reg_write(info->i2c, PM8607_VBAT_LOWTH, data); dev_dbg(info->dev, "VBAT Min:%dmv, LOWTH:0x%x\n", min, data); if (max <= 0) data = 0xff; else data = (max << 5) / 675; pm860x_reg_write(info->i2c, PM8607_VBAT_HIGHTH, data); dev_dbg(info->dev, "VBAT Max:%dmv, HIGHTH:0x%x\n", max, data); return; } static int start_precharge(struct pm860x_charger_info *info) { int ret; dev_dbg(info->dev, "Start Pre-charging!\n"); set_vbatt_threshold(info, 0, 0); ret = pm860x_reg_write(info->i2c_8606, PM8606_PREREGULATORA, PREREG1_1350MA | PREREG1_VSYS_4_5V); if (ret < 0) goto out; /* stop charging */ ret = pm860x_set_bits(info->i2c, PM8607_CHG_CTRL1, 3, CC1_MODE_OFF); if (ret < 0) goto out; /* set 270 minutes timeout */ ret = pm860x_set_bits(info->i2c, PM8607_CHG_CTRL3, (0xf << 4), CC3_270MIN_TIMEOUT); if (ret < 0) goto out; /* set precharge current, termination voltage, IBAT & TBAT monitor */ ret = pm860x_reg_write(info->i2c, PM8607_CHG_CTRL4, CC4_IPRE_40MA | CC4_VPCHG_3_2V | CC4_IFCHG_MON_EN | CC4_BTEMP_MON_EN); if (ret < 0) goto out; ret = pm860x_set_bits(info->i2c, PM8607_CHG_CTRL7, CC7_BAT_REM_EN | CC7_IFSM_EN, CC7_BAT_REM_EN | CC7_IFSM_EN); if (ret < 0) goto out; /* trigger precharge */ ret = pm860x_set_bits(info->i2c, PM8607_CHG_CTRL1, 3, CC1_MODE_PRECHARGE); out: return ret; } static int start_fastcharge(struct pm860x_charger_info *info) { int ret; dev_dbg(info->dev, "Start Fast-charging!\n"); /* set fastcharge termination current & voltage, disable charging */ ret = pm860x_reg_write(info->i2c, PM8607_CHG_CTRL1, CC1_MODE_OFF | CC1_ITERM_60MA | CC1_VFCHG_4_2V); if (ret < 0) goto out; ret = pm860x_reg_write(info->i2c_8606, PM8606_PREREGULATORA, PREREG1_540MA | PREREG1_VSYS_4_5V); if (ret < 0) goto out; ret = pm860x_set_bits(info->i2c, PM8607_CHG_CTRL2, 0x1f, CC2_ICHG_500MA); if (ret < 0) goto out; /* set 270 minutes timeout */ ret = pm860x_set_bits(info->i2c, PM8607_CHG_CTRL3, (0xf << 4), CC3_270MIN_TIMEOUT); if (ret < 0) goto out; /* set IBAT & TBAT monitor */ ret = pm860x_set_bits(info->i2c, PM8607_CHG_CTRL4, CC4_IFCHG_MON_EN | CC4_BTEMP_MON_EN, CC4_IFCHG_MON_EN | CC4_BTEMP_MON_EN); if (ret < 0) goto out; ret = pm860x_set_bits(info->i2c, PM8607_CHG_CTRL6, CC6_BAT_OV_EN | CC6_BAT_UV_EN | CC6_UV_VBAT_SET, CC6_BAT_OV_EN | CC6_BAT_UV_EN | CC6_UV_VBAT_SET); if (ret < 0) goto out; ret = pm860x_set_bits(info->i2c, PM8607_CHG_CTRL7, CC7_BAT_REM_EN | CC7_IFSM_EN, CC7_BAT_REM_EN | CC7_IFSM_EN); if (ret < 0) goto out; /* launch fast-charge */ ret = pm860x_set_bits(info->i2c, PM8607_CHG_CTRL1, 3, CC1_MODE_FASTCHARGE); /* vchg threshold setting */ set_vchg_threshold(info, VCHG_NORMAL_LOW, VCHG_NORMAL_HIGH); out: return ret; } static void stop_charge(struct pm860x_charger_info *info, int vbatt) { dev_dbg(info->dev, "Stop charging!\n"); pm860x_set_bits(info->i2c, PM8607_CHG_CTRL1, 3, CC1_MODE_OFF); if (vbatt > CHARGE_THRESHOLD && info->online) set_vbatt_threshold(info, CHARGE_THRESHOLD, 0); } static void power_off_notification(struct pm860x_charger_info *info) { dev_dbg(info->dev, "Power-off notification!\n"); } static int set_charging_fsm(struct pm860x_charger_info *info) { struct power_supply *psy; union power_supply_propval data; unsigned char fsm_state[][16] = { "init", "discharge", "precharge", "fastcharge", }; int ret; int vbatt; psy = power_supply_get_by_name(pm860x_supplied_to[0]); if (!psy) return -EINVAL; ret = power_supply_get_property(psy, POWER_SUPPLY_PROP_VOLTAGE_NOW, &data); if (ret) { power_supply_put(psy); return ret; } vbatt = data.intval / 1000; ret = power_supply_get_property(psy, POWER_SUPPLY_PROP_PRESENT, &data); if (ret) { power_supply_put(psy); return ret; } power_supply_put(psy); mutex_lock(&info->lock); info->present = data.intval; dev_dbg(info->dev, "Entering FSM:%s, Charger:%s, Battery:%s, " "Allowed:%d\n", &fsm_state[info->state][0], (info->online) ? "online" : "N/A", (info->present) ? "present" : "N/A", info->allowed); dev_dbg(info->dev, "set_charging_fsm:vbatt:%d(mV)\n", vbatt); switch (info->state) { case FSM_INIT: if (info->online && info->present && info->allowed) { if (vbatt < PRECHARGE_THRESHOLD) { info->state = FSM_PRECHARGE; start_precharge(info); } else if (vbatt > DISCHARGE_THRESHOLD) { info->state = FSM_DISCHARGE; stop_charge(info, vbatt); } else if (vbatt < DISCHARGE_THRESHOLD) { info->state = FSM_FASTCHARGE; start_fastcharge(info); } } else { if (vbatt < POWEROFF_THRESHOLD) { power_off_notification(info); } else { info->state = FSM_DISCHARGE; stop_charge(info, vbatt); } } break; case FSM_PRECHARGE: if (info->online && info->present && info->allowed) { if (vbatt > PRECHARGE_THRESHOLD) { info->state = FSM_FASTCHARGE; start_fastcharge(info); } } else { info->state = FSM_DISCHARGE; stop_charge(info, vbatt); } break; case FSM_FASTCHARGE: if (info->online && info->present && info->allowed) { if (vbatt < PRECHARGE_THRESHOLD) { info->state = FSM_PRECHARGE; start_precharge(info); } } else { info->state = FSM_DISCHARGE; stop_charge(info, vbatt); } break; case FSM_DISCHARGE: if (info->online && info->present && info->allowed) { if (vbatt < PRECHARGE_THRESHOLD) { info->state = FSM_PRECHARGE; start_precharge(info); } else if (vbatt < DISCHARGE_THRESHOLD) { info->state = FSM_FASTCHARGE; start_fastcharge(info); } } else { if (vbatt < POWEROFF_THRESHOLD) power_off_notification(info); else if (vbatt > CHARGE_THRESHOLD && info->online) set_vbatt_threshold(info, CHARGE_THRESHOLD, 0); } break; default: dev_warn(info->dev, "FSM meets wrong state:%d\n", info->state); break; } dev_dbg(info->dev, "Out FSM:%s, Charger:%s, Battery:%s, Allowed:%d\n", &fsm_state[info->state][0], (info->online) ? "online" : "N/A", (info->present) ? "present" : "N/A", info->allowed); mutex_unlock(&info->lock); return 0; } static irqreturn_t pm860x_charger_handler(int irq, void *data) { struct pm860x_charger_info *info = data; int ret; mutex_lock(&info->lock); ret = pm860x_reg_read(info->i2c, PM8607_STATUS_2); if (ret < 0) { mutex_unlock(&info->lock); goto out; } if (ret & STATUS2_CHG) { info->online = 1; info->allowed = 1; } else { info->online = 0; info->allowed = 0; } mutex_unlock(&info->lock); dev_dbg(info->dev, "%s, Charger:%s, Allowed:%d\n", __func__, (info->online) ? "online" : "N/A", info->allowed); set_charging_fsm(info); power_supply_changed(info->usb); out: return IRQ_HANDLED; } static irqreturn_t pm860x_temp_handler(int irq, void *data) { struct power_supply *psy; struct pm860x_charger_info *info = data; union power_supply_propval temp; int value; int ret; psy = power_supply_get_by_name(pm860x_supplied_to[0]); if (!psy) return IRQ_HANDLED; ret = power_supply_get_property(psy, POWER_SUPPLY_PROP_TEMP, &temp); if (ret) goto out; value = temp.intval / 10; mutex_lock(&info->lock); /* Temperature < -10 C or >40 C, Will not allow charge */ if (value < -10 || value > 40) info->allowed = 0; else info->allowed = 1; dev_dbg(info->dev, "%s, Allowed: %d\n", __func__, info->allowed); mutex_unlock(&info->lock); set_charging_fsm(info); out: power_supply_put(psy); return IRQ_HANDLED; } static irqreturn_t pm860x_exception_handler(int irq, void *data) { struct pm860x_charger_info *info = data; mutex_lock(&info->lock); info->allowed = 0; mutex_unlock(&info->lock); dev_dbg(info->dev, "%s, irq: %d\n", __func__, irq); set_charging_fsm(info); return IRQ_HANDLED; } static irqreturn_t pm860x_done_handler(int irq, void *data) { struct pm860x_charger_info *info = data; struct power_supply *psy; union power_supply_propval val; int ret; int vbatt; mutex_lock(&info->lock); /* pre-charge done, will transimit to fast-charge stage */ if (info->state == FSM_PRECHARGE) { info->allowed = 1; goto out; } /* * Fast charge done, delay to read * the correct status of CHG_DET. */ mdelay(5); info->allowed = 0; psy = power_supply_get_by_name(pm860x_supplied_to[0]); if (!psy) goto out; ret = power_supply_get_property(psy, POWER_SUPPLY_PROP_VOLTAGE_NOW, &val); if (ret) goto out_psy_put; vbatt = val.intval / 1000; /* * CHG_DONE interrupt is faster than CHG_DET interrupt when * plug in/out usb, So we can not rely on info->online, we * need check pm8607 status register to check usb is online * or not, then we can decide it is real charge done * automatically or it is triggered by usb plug out; */ ret = pm860x_reg_read(info->i2c, PM8607_STATUS_2); if (ret < 0) goto out_psy_put; if (vbatt > CHARGE_THRESHOLD && ret & STATUS2_CHG) power_supply_set_property(psy, POWER_SUPPLY_PROP_CHARGE_FULL, &val); out_psy_put: power_supply_put(psy); out: mutex_unlock(&info->lock); dev_dbg(info->dev, "%s, Allowed: %d\n", __func__, info->allowed); set_charging_fsm(info); return IRQ_HANDLED; } static irqreturn_t pm860x_vbattery_handler(int irq, void *data) { struct pm860x_charger_info *info = data; mutex_lock(&info->lock); set_vbatt_threshold(info, 0, 0); if (info->present && info->online) info->allowed = 1; else info->allowed = 0; mutex_unlock(&info->lock); dev_dbg(info->dev, "%s, Allowed: %d\n", __func__, info->allowed); set_charging_fsm(info); return IRQ_HANDLED; } static irqreturn_t pm860x_vchg_handler(int irq, void *data) { struct pm860x_charger_info *info = data; int vchg = 0; if (info->present) goto out; measure_vchg(info, &vchg); mutex_lock(&info->lock); if (!info->online) { int status; /* check if over-temp on pm8606 or not */ status = pm860x_reg_read(info->i2c_8606, PM8606_FLAGS); if (status & OVER_TEMP_FLAG) { /* clear over temp flag and set auto recover */ pm860x_set_bits(info->i2c_8606, PM8606_FLAGS, OVER_TEMP_FLAG, OVER_TEMP_FLAG); pm860x_set_bits(info->i2c_8606, PM8606_VSYS, OVTEMP_AUTORECOVER, OVTEMP_AUTORECOVER); dev_dbg(info->dev, "%s, pm8606 over-temp occurred\n", __func__); } } if (vchg > VCHG_NORMAL_CHECK) { set_vchg_threshold(info, VCHG_OVP_LOW, 0); info->allowed = 0; dev_dbg(info->dev, "%s,pm8607 over-vchg occurred,vchg = %dmv\n", __func__, vchg); } else if (vchg < VCHG_OVP_LOW) { set_vchg_threshold(info, VCHG_NORMAL_LOW, VCHG_NORMAL_HIGH); info->allowed = 1; dev_dbg(info->dev, "%s,pm8607 over-vchg recover,vchg = %dmv\n", __func__, vchg); } mutex_unlock(&info->lock); dev_dbg(info->dev, "%s, Allowed: %d\n", __func__, info->allowed); set_charging_fsm(info); out: return IRQ_HANDLED; } static int pm860x_usb_get_prop(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct pm860x_charger_info *info = power_supply_get_drvdata(psy); switch (psp) { case POWER_SUPPLY_PROP_STATUS: if (info->state == FSM_FASTCHARGE || info->state == FSM_PRECHARGE) val->intval = POWER_SUPPLY_STATUS_CHARGING; else val->intval = POWER_SUPPLY_STATUS_DISCHARGING; break; case POWER_SUPPLY_PROP_ONLINE: val->intval = info->online; break; default: return -ENODEV; } return 0; } static enum power_supply_property pm860x_usb_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_ONLINE, }; static int pm860x_init_charger(struct pm860x_charger_info *info) { int ret; ret = pm860x_reg_read(info->i2c, PM8607_STATUS_2); if (ret < 0) return ret; mutex_lock(&info->lock); info->state = FSM_INIT; if (ret & STATUS2_CHG) { info->online = 1; info->allowed = 1; } else { info->online = 0; info->allowed = 0; } mutex_unlock(&info->lock); set_charging_fsm(info); return 0; } static struct pm860x_irq_desc { const char *name; irqreturn_t (*handler)(int irq, void *data); } pm860x_irq_descs[] = { { "usb supply detect", pm860x_charger_handler }, { "charge done", pm860x_done_handler }, { "charge timeout", pm860x_exception_handler }, { "charge fault", pm860x_exception_handler }, { "temperature", pm860x_temp_handler }, { "vbatt", pm860x_vbattery_handler }, { "vchg", pm860x_vchg_handler }, }; static const struct power_supply_desc pm860x_charger_desc = { .name = "usb", .type = POWER_SUPPLY_TYPE_USB, .properties = pm860x_usb_props, .num_properties = ARRAY_SIZE(pm860x_usb_props), .get_property = pm860x_usb_get_prop, }; static int pm860x_charger_probe(struct platform_device *pdev) { struct pm860x_chip *chip = dev_get_drvdata(pdev->dev.parent); struct power_supply_config psy_cfg = {}; struct pm860x_charger_info *info; int ret; int count; int i; int j; info = devm_kzalloc(&pdev->dev, sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; count = pdev->num_resources; for (i = 0, j = 0; i < count; i++) { info->irq[j] = platform_get_irq(pdev, i); if (info->irq[j] < 0) continue; j++; } info->irq_nums = j; info->chip = chip; info->i2c = (chip->id == CHIP_PM8607) ? chip->client : chip->companion; info->i2c_8606 = (chip->id == CHIP_PM8607) ? chip->companion : chip->client; if (!info->i2c_8606) { dev_err(&pdev->dev, "Missed I2C address of 88PM8606!\n"); return -EINVAL; } info->dev = &pdev->dev; /* set init value for the case we are not using battery */ set_vchg_threshold(info, VCHG_NORMAL_LOW, VCHG_OVP_LOW); mutex_init(&info->lock); platform_set_drvdata(pdev, info); psy_cfg.drv_data = info; psy_cfg.supplied_to = pm860x_supplied_to; psy_cfg.num_supplicants = ARRAY_SIZE(pm860x_supplied_to); info->usb = devm_power_supply_register(&pdev->dev, &pm860x_charger_desc, &psy_cfg); if (IS_ERR(info->usb)) { return PTR_ERR(info->usb); } pm860x_init_charger(info); for (i = 0; i < ARRAY_SIZE(info->irq); i++) { ret = devm_request_threaded_irq(&pdev->dev, info->irq[i], NULL, pm860x_irq_descs[i].handler, IRQF_ONESHOT, pm860x_irq_descs[i].name, info); if (ret < 0) { dev_err(chip->dev, "Failed to request IRQ: #%d: %d\n", info->irq[i], ret); return ret; } } return 0; } static struct platform_driver pm860x_charger_driver = { .driver = { .name = "88pm860x-charger", }, .probe = pm860x_charger_probe, }; module_platform_driver(pm860x_charger_driver); MODULE_DESCRIPTION("Marvell 88PM860x Charger driver"); MODULE_LICENSE("GPL");
linux-master
drivers/power/supply/88pm860x_charger.c
// SPDX-License-Identifier: GPL-2.0-only /* * PMU driver for Wolfson Microelectronics wm831x PMICs * * Copyright 2009 Wolfson Microelectronics PLC. */ #include <linux/module.h> #include <linux/err.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/slab.h> #include <linux/usb/phy.h> #include <linux/mfd/wm831x/core.h> #include <linux/mfd/wm831x/auxadc.h> #include <linux/mfd/wm831x/pmu.h> #include <linux/mfd/wm831x/pdata.h> struct wm831x_power { struct wm831x *wm831x; struct power_supply *wall; struct power_supply *usb; struct power_supply *battery; struct power_supply_desc wall_desc; struct power_supply_desc usb_desc; struct power_supply_desc battery_desc; char wall_name[20]; char usb_name[20]; char battery_name[20]; bool have_battery; struct usb_phy *usb_phy; struct notifier_block usb_notify; }; static int wm831x_power_check_online(struct wm831x *wm831x, int supply, union power_supply_propval *val) { int ret; ret = wm831x_reg_read(wm831x, WM831X_SYSTEM_STATUS); if (ret < 0) return ret; if (ret & supply) val->intval = 1; else val->intval = 0; return 0; } static int wm831x_power_read_voltage(struct wm831x *wm831x, enum wm831x_auxadc src, union power_supply_propval *val) { int ret; ret = wm831x_auxadc_read_uv(wm831x, src); if (ret >= 0) val->intval = ret; return ret; } /********************************************************************* * WALL Power *********************************************************************/ static int wm831x_wall_get_prop(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct wm831x_power *wm831x_power = dev_get_drvdata(psy->dev.parent); struct wm831x *wm831x = wm831x_power->wm831x; int ret = 0; switch (psp) { case POWER_SUPPLY_PROP_ONLINE: ret = wm831x_power_check_online(wm831x, WM831X_PWR_WALL, val); break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: ret = wm831x_power_read_voltage(wm831x, WM831X_AUX_WALL, val); break; default: ret = -EINVAL; break; } return ret; } static enum power_supply_property wm831x_wall_props[] = { POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_VOLTAGE_NOW, }; /********************************************************************* * USB Power *********************************************************************/ static int wm831x_usb_get_prop(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct wm831x_power *wm831x_power = dev_get_drvdata(psy->dev.parent); struct wm831x *wm831x = wm831x_power->wm831x; int ret = 0; switch (psp) { case POWER_SUPPLY_PROP_ONLINE: ret = wm831x_power_check_online(wm831x, WM831X_PWR_USB, val); break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: ret = wm831x_power_read_voltage(wm831x, WM831X_AUX_USB, val); break; default: ret = -EINVAL; break; } return ret; } static enum power_supply_property wm831x_usb_props[] = { POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_VOLTAGE_NOW, }; /* In milliamps */ static const unsigned int wm831x_usb_limits[] = { 0, 2, 100, 500, 900, 1500, 1800, 550, }; static int wm831x_usb_limit_change(struct notifier_block *nb, unsigned long limit, void *data) { struct wm831x_power *wm831x_power = container_of(nb, struct wm831x_power, usb_notify); unsigned int i, best; /* Find the highest supported limit */ best = 0; for (i = 0; i < ARRAY_SIZE(wm831x_usb_limits); i++) { if (limit >= wm831x_usb_limits[i] && wm831x_usb_limits[best] < wm831x_usb_limits[i]) best = i; } dev_dbg(wm831x_power->wm831x->dev, "Limiting USB current to %umA", wm831x_usb_limits[best]); wm831x_set_bits(wm831x_power->wm831x, WM831X_POWER_STATE, WM831X_USB_ILIM_MASK, best); return 0; } /********************************************************************* * Battery properties *********************************************************************/ struct chg_map { int val; int reg_val; }; static struct chg_map trickle_ilims[] = { { 50, 0 << WM831X_CHG_TRKL_ILIM_SHIFT }, { 100, 1 << WM831X_CHG_TRKL_ILIM_SHIFT }, { 150, 2 << WM831X_CHG_TRKL_ILIM_SHIFT }, { 200, 3 << WM831X_CHG_TRKL_ILIM_SHIFT }, }; static struct chg_map vsels[] = { { 4050, 0 << WM831X_CHG_VSEL_SHIFT }, { 4100, 1 << WM831X_CHG_VSEL_SHIFT }, { 4150, 2 << WM831X_CHG_VSEL_SHIFT }, { 4200, 3 << WM831X_CHG_VSEL_SHIFT }, }; static struct chg_map fast_ilims[] = { { 0, 0 << WM831X_CHG_FAST_ILIM_SHIFT }, { 50, 1 << WM831X_CHG_FAST_ILIM_SHIFT }, { 100, 2 << WM831X_CHG_FAST_ILIM_SHIFT }, { 150, 3 << WM831X_CHG_FAST_ILIM_SHIFT }, { 200, 4 << WM831X_CHG_FAST_ILIM_SHIFT }, { 250, 5 << WM831X_CHG_FAST_ILIM_SHIFT }, { 300, 6 << WM831X_CHG_FAST_ILIM_SHIFT }, { 350, 7 << WM831X_CHG_FAST_ILIM_SHIFT }, { 400, 8 << WM831X_CHG_FAST_ILIM_SHIFT }, { 450, 9 << WM831X_CHG_FAST_ILIM_SHIFT }, { 500, 10 << WM831X_CHG_FAST_ILIM_SHIFT }, { 600, 11 << WM831X_CHG_FAST_ILIM_SHIFT }, { 700, 12 << WM831X_CHG_FAST_ILIM_SHIFT }, { 800, 13 << WM831X_CHG_FAST_ILIM_SHIFT }, { 900, 14 << WM831X_CHG_FAST_ILIM_SHIFT }, { 1000, 15 << WM831X_CHG_FAST_ILIM_SHIFT }, }; static struct chg_map eoc_iterms[] = { { 20, 0 << WM831X_CHG_ITERM_SHIFT }, { 30, 1 << WM831X_CHG_ITERM_SHIFT }, { 40, 2 << WM831X_CHG_ITERM_SHIFT }, { 50, 3 << WM831X_CHG_ITERM_SHIFT }, { 60, 4 << WM831X_CHG_ITERM_SHIFT }, { 70, 5 << WM831X_CHG_ITERM_SHIFT }, { 80, 6 << WM831X_CHG_ITERM_SHIFT }, { 90, 7 << WM831X_CHG_ITERM_SHIFT }, }; static struct chg_map chg_times[] = { { 60, 0 << WM831X_CHG_TIME_SHIFT }, { 90, 1 << WM831X_CHG_TIME_SHIFT }, { 120, 2 << WM831X_CHG_TIME_SHIFT }, { 150, 3 << WM831X_CHG_TIME_SHIFT }, { 180, 4 << WM831X_CHG_TIME_SHIFT }, { 210, 5 << WM831X_CHG_TIME_SHIFT }, { 240, 6 << WM831X_CHG_TIME_SHIFT }, { 270, 7 << WM831X_CHG_TIME_SHIFT }, { 300, 8 << WM831X_CHG_TIME_SHIFT }, { 330, 9 << WM831X_CHG_TIME_SHIFT }, { 360, 10 << WM831X_CHG_TIME_SHIFT }, { 390, 11 << WM831X_CHG_TIME_SHIFT }, { 420, 12 << WM831X_CHG_TIME_SHIFT }, { 450, 13 << WM831X_CHG_TIME_SHIFT }, { 480, 14 << WM831X_CHG_TIME_SHIFT }, { 510, 15 << WM831X_CHG_TIME_SHIFT }, }; static void wm831x_battery_apply_config(struct wm831x *wm831x, struct chg_map *map, int count, int val, int *reg, const char *name, const char *units) { int i; for (i = 0; i < count; i++) if (val == map[i].val) break; if (i == count) { dev_err(wm831x->dev, "Invalid %s %d%s\n", name, val, units); } else { *reg |= map[i].reg_val; dev_dbg(wm831x->dev, "Set %s of %d%s\n", name, val, units); } } static void wm831x_config_battery(struct wm831x *wm831x) { struct wm831x_pdata *wm831x_pdata = wm831x->dev->platform_data; struct wm831x_battery_pdata *pdata; int ret, reg1, reg2; if (!wm831x_pdata || !wm831x_pdata->battery) { dev_warn(wm831x->dev, "No battery charger configuration\n"); return; } pdata = wm831x_pdata->battery; reg1 = 0; reg2 = 0; if (!pdata->enable) { dev_info(wm831x->dev, "Battery charger disabled\n"); return; } reg1 |= WM831X_CHG_ENA; if (pdata->off_mask) reg2 |= WM831X_CHG_OFF_MSK; if (pdata->fast_enable) reg1 |= WM831X_CHG_FAST; wm831x_battery_apply_config(wm831x, trickle_ilims, ARRAY_SIZE(trickle_ilims), pdata->trickle_ilim, &reg2, "trickle charge current limit", "mA"); wm831x_battery_apply_config(wm831x, vsels, ARRAY_SIZE(vsels), pdata->vsel, &reg2, "target voltage", "mV"); wm831x_battery_apply_config(wm831x, fast_ilims, ARRAY_SIZE(fast_ilims), pdata->fast_ilim, &reg2, "fast charge current limit", "mA"); wm831x_battery_apply_config(wm831x, eoc_iterms, ARRAY_SIZE(eoc_iterms), pdata->eoc_iterm, &reg1, "end of charge current threshold", "mA"); wm831x_battery_apply_config(wm831x, chg_times, ARRAY_SIZE(chg_times), pdata->timeout, &reg2, "charger timeout", "min"); ret = wm831x_reg_unlock(wm831x); if (ret != 0) { dev_err(wm831x->dev, "Failed to unlock registers: %d\n", ret); return; } ret = wm831x_set_bits(wm831x, WM831X_CHARGER_CONTROL_1, WM831X_CHG_ENA_MASK | WM831X_CHG_FAST_MASK | WM831X_CHG_ITERM_MASK, reg1); if (ret != 0) dev_err(wm831x->dev, "Failed to set charger control 1: %d\n", ret); ret = wm831x_set_bits(wm831x, WM831X_CHARGER_CONTROL_2, WM831X_CHG_OFF_MSK | WM831X_CHG_TIME_MASK | WM831X_CHG_FAST_ILIM_MASK | WM831X_CHG_TRKL_ILIM_MASK | WM831X_CHG_VSEL_MASK, reg2); if (ret != 0) dev_err(wm831x->dev, "Failed to set charger control 2: %d\n", ret); wm831x_reg_lock(wm831x); } static int wm831x_bat_check_status(struct wm831x *wm831x, int *status) { int ret; ret = wm831x_reg_read(wm831x, WM831X_SYSTEM_STATUS); if (ret < 0) return ret; if (ret & WM831X_PWR_SRC_BATT) { *status = POWER_SUPPLY_STATUS_DISCHARGING; return 0; } ret = wm831x_reg_read(wm831x, WM831X_CHARGER_STATUS); if (ret < 0) return ret; switch (ret & WM831X_CHG_STATE_MASK) { case WM831X_CHG_STATE_OFF: *status = POWER_SUPPLY_STATUS_NOT_CHARGING; break; case WM831X_CHG_STATE_TRICKLE: case WM831X_CHG_STATE_FAST: *status = POWER_SUPPLY_STATUS_CHARGING; break; default: *status = POWER_SUPPLY_STATUS_UNKNOWN; break; } return 0; } static int wm831x_bat_check_type(struct wm831x *wm831x, int *type) { int ret; ret = wm831x_reg_read(wm831x, WM831X_CHARGER_STATUS); if (ret < 0) return ret; switch (ret & WM831X_CHG_STATE_MASK) { case WM831X_CHG_STATE_TRICKLE: case WM831X_CHG_STATE_TRICKLE_OT: *type = POWER_SUPPLY_CHARGE_TYPE_TRICKLE; break; case WM831X_CHG_STATE_FAST: case WM831X_CHG_STATE_FAST_OT: *type = POWER_SUPPLY_CHARGE_TYPE_FAST; break; default: *type = POWER_SUPPLY_CHARGE_TYPE_NONE; break; } return 0; } static int wm831x_bat_check_health(struct wm831x *wm831x, int *health) { int ret; ret = wm831x_reg_read(wm831x, WM831X_CHARGER_STATUS); if (ret < 0) return ret; if (ret & WM831X_BATT_HOT_STS) { *health = POWER_SUPPLY_HEALTH_OVERHEAT; return 0; } if (ret & WM831X_BATT_COLD_STS) { *health = POWER_SUPPLY_HEALTH_COLD; return 0; } if (ret & WM831X_BATT_OV_STS) { *health = POWER_SUPPLY_HEALTH_OVERVOLTAGE; return 0; } switch (ret & WM831X_CHG_STATE_MASK) { case WM831X_CHG_STATE_TRICKLE_OT: case WM831X_CHG_STATE_FAST_OT: *health = POWER_SUPPLY_HEALTH_OVERHEAT; break; case WM831X_CHG_STATE_DEFECTIVE: *health = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE; break; default: *health = POWER_SUPPLY_HEALTH_GOOD; break; } return 0; } static int wm831x_bat_get_prop(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct wm831x_power *wm831x_power = dev_get_drvdata(psy->dev.parent); struct wm831x *wm831x = wm831x_power->wm831x; int ret = 0; switch (psp) { case POWER_SUPPLY_PROP_STATUS: ret = wm831x_bat_check_status(wm831x, &val->intval); break; case POWER_SUPPLY_PROP_ONLINE: ret = wm831x_power_check_online(wm831x, WM831X_PWR_SRC_BATT, val); break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: ret = wm831x_power_read_voltage(wm831x, WM831X_AUX_BATT, val); break; case POWER_SUPPLY_PROP_HEALTH: ret = wm831x_bat_check_health(wm831x, &val->intval); break; case POWER_SUPPLY_PROP_CHARGE_TYPE: ret = wm831x_bat_check_type(wm831x, &val->intval); break; default: ret = -EINVAL; break; } return ret; } static enum power_supply_property wm831x_bat_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_HEALTH, POWER_SUPPLY_PROP_CHARGE_TYPE, }; static const char *wm831x_bat_irqs[] = { "BATT HOT", "BATT COLD", "BATT FAIL", "OV", "END", "TO", "MODE", "START", }; static irqreturn_t wm831x_bat_irq(int irq, void *data) { struct wm831x_power *wm831x_power = data; struct wm831x *wm831x = wm831x_power->wm831x; dev_dbg(wm831x->dev, "Battery status changed: %d\n", irq); /* The battery charger is autonomous so we don't need to do * anything except kick user space */ if (wm831x_power->have_battery) power_supply_changed(wm831x_power->battery); return IRQ_HANDLED; } /********************************************************************* * Initialisation *********************************************************************/ static irqreturn_t wm831x_syslo_irq(int irq, void *data) { struct wm831x_power *wm831x_power = data; struct wm831x *wm831x = wm831x_power->wm831x; /* Not much we can actually *do* but tell people for * posterity, we're probably about to run out of power. */ dev_crit(wm831x->dev, "SYSVDD under voltage\n"); return IRQ_HANDLED; } static irqreturn_t wm831x_pwr_src_irq(int irq, void *data) { struct wm831x_power *wm831x_power = data; struct wm831x *wm831x = wm831x_power->wm831x; dev_dbg(wm831x->dev, "Power source changed\n"); /* Just notify for everything - little harm in overnotifying. */ if (wm831x_power->have_battery) power_supply_changed(wm831x_power->battery); power_supply_changed(wm831x_power->usb); power_supply_changed(wm831x_power->wall); return IRQ_HANDLED; } static int wm831x_power_probe(struct platform_device *pdev) { struct wm831x *wm831x = dev_get_drvdata(pdev->dev.parent); struct wm831x_pdata *wm831x_pdata = wm831x->dev->platform_data; struct wm831x_power *power; int ret, irq, i; power = devm_kzalloc(&pdev->dev, sizeof(struct wm831x_power), GFP_KERNEL); if (power == NULL) return -ENOMEM; power->wm831x = wm831x; platform_set_drvdata(pdev, power); if (wm831x_pdata && wm831x_pdata->wm831x_num) { snprintf(power->wall_name, sizeof(power->wall_name), "wm831x-wall.%d", wm831x_pdata->wm831x_num); snprintf(power->battery_name, sizeof(power->wall_name), "wm831x-battery.%d", wm831x_pdata->wm831x_num); snprintf(power->usb_name, sizeof(power->wall_name), "wm831x-usb.%d", wm831x_pdata->wm831x_num); } else { snprintf(power->wall_name, sizeof(power->wall_name), "wm831x-wall"); snprintf(power->battery_name, sizeof(power->wall_name), "wm831x-battery"); snprintf(power->usb_name, sizeof(power->wall_name), "wm831x-usb"); } /* We ignore configuration failures since we can still read back * the status without enabling the charger. */ wm831x_config_battery(wm831x); power->wall_desc.name = power->wall_name; power->wall_desc.type = POWER_SUPPLY_TYPE_MAINS; power->wall_desc.properties = wm831x_wall_props; power->wall_desc.num_properties = ARRAY_SIZE(wm831x_wall_props); power->wall_desc.get_property = wm831x_wall_get_prop; power->wall = power_supply_register(&pdev->dev, &power->wall_desc, NULL); if (IS_ERR(power->wall)) { ret = PTR_ERR(power->wall); goto err; } power->usb_desc.name = power->usb_name, power->usb_desc.type = POWER_SUPPLY_TYPE_USB; power->usb_desc.properties = wm831x_usb_props; power->usb_desc.num_properties = ARRAY_SIZE(wm831x_usb_props); power->usb_desc.get_property = wm831x_usb_get_prop; power->usb = power_supply_register(&pdev->dev, &power->usb_desc, NULL); if (IS_ERR(power->usb)) { ret = PTR_ERR(power->usb); goto err_wall; } ret = wm831x_reg_read(wm831x, WM831X_CHARGER_CONTROL_1); if (ret < 0) goto err_wall; power->have_battery = ret & WM831X_CHG_ENA; if (power->have_battery) { power->battery_desc.name = power->battery_name; power->battery_desc.properties = wm831x_bat_props; power->battery_desc.num_properties = ARRAY_SIZE(wm831x_bat_props); power->battery_desc.get_property = wm831x_bat_get_prop; power->battery_desc.use_for_apm = 1; power->battery = power_supply_register(&pdev->dev, &power->battery_desc, NULL); if (IS_ERR(power->battery)) { ret = PTR_ERR(power->battery); goto err_usb; } } irq = wm831x_irq(wm831x, platform_get_irq_byname(pdev, "SYSLO")); ret = request_threaded_irq(irq, NULL, wm831x_syslo_irq, IRQF_TRIGGER_RISING | IRQF_ONESHOT, "System power low", power); if (ret != 0) { dev_err(&pdev->dev, "Failed to request SYSLO IRQ %d: %d\n", irq, ret); goto err_battery; } irq = wm831x_irq(wm831x, platform_get_irq_byname(pdev, "PWR SRC")); ret = request_threaded_irq(irq, NULL, wm831x_pwr_src_irq, IRQF_TRIGGER_RISING | IRQF_ONESHOT, "Power source", power); if (ret != 0) { dev_err(&pdev->dev, "Failed to request PWR SRC IRQ %d: %d\n", irq, ret); goto err_syslo; } for (i = 0; i < ARRAY_SIZE(wm831x_bat_irqs); i++) { irq = wm831x_irq(wm831x, platform_get_irq_byname(pdev, wm831x_bat_irqs[i])); ret = request_threaded_irq(irq, NULL, wm831x_bat_irq, IRQF_TRIGGER_RISING | IRQF_ONESHOT, wm831x_bat_irqs[i], power); if (ret != 0) { dev_err(&pdev->dev, "Failed to request %s IRQ %d: %d\n", wm831x_bat_irqs[i], irq, ret); goto err_bat_irq; } } power->usb_phy = devm_usb_get_phy_by_phandle(&pdev->dev, "phys", 0); ret = PTR_ERR_OR_ZERO(power->usb_phy); switch (ret) { case 0: power->usb_notify.notifier_call = wm831x_usb_limit_change; ret = usb_register_notifier(power->usb_phy, &power->usb_notify); if (ret) { dev_err(&pdev->dev, "Failed to register notifier: %d\n", ret); goto err_bat_irq; } break; case -EINVAL: case -ENODEV: /* ignore missing usb-phy, it's optional */ power->usb_phy = NULL; ret = 0; break; default: dev_err(&pdev->dev, "Failed to find USB phy: %d\n", ret); fallthrough; case -EPROBE_DEFER: goto err_bat_irq; } return ret; err_bat_irq: --i; for (; i >= 0; i--) { irq = platform_get_irq_byname(pdev, wm831x_bat_irqs[i]); free_irq(irq, power); } irq = wm831x_irq(wm831x, platform_get_irq_byname(pdev, "PWR SRC")); free_irq(irq, power); err_syslo: irq = wm831x_irq(wm831x, platform_get_irq_byname(pdev, "SYSLO")); free_irq(irq, power); err_battery: if (power->have_battery) power_supply_unregister(power->battery); err_usb: power_supply_unregister(power->usb); err_wall: power_supply_unregister(power->wall); err: return ret; } static int wm831x_power_remove(struct platform_device *pdev) { struct wm831x_power *wm831x_power = platform_get_drvdata(pdev); struct wm831x *wm831x = wm831x_power->wm831x; int irq, i; if (wm831x_power->usb_phy) { usb_unregister_notifier(wm831x_power->usb_phy, &wm831x_power->usb_notify); } for (i = 0; i < ARRAY_SIZE(wm831x_bat_irqs); i++) { irq = wm831x_irq(wm831x, platform_get_irq_byname(pdev, wm831x_bat_irqs[i])); free_irq(irq, wm831x_power); } irq = wm831x_irq(wm831x, platform_get_irq_byname(pdev, "PWR SRC")); free_irq(irq, wm831x_power); irq = wm831x_irq(wm831x, platform_get_irq_byname(pdev, "SYSLO")); free_irq(irq, wm831x_power); if (wm831x_power->have_battery) power_supply_unregister(wm831x_power->battery); power_supply_unregister(wm831x_power->wall); power_supply_unregister(wm831x_power->usb); return 0; } static struct platform_driver wm831x_power_driver = { .probe = wm831x_power_probe, .remove = wm831x_power_remove, .driver = { .name = "wm831x-power", }, }; module_platform_driver(wm831x_power_driver); MODULE_DESCRIPTION("Power supply driver for WM831x PMICs"); MODULE_AUTHOR("Mark Brown <[email protected]>"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:wm831x-power");
linux-master
drivers/power/supply/wm831x_power.c
// SPDX-License-Identifier: GPL-2.0+ // // Fuel gauge driver for Maxim 17042 / 8966 / 8997 // Note that Maxim 8966 and 8997 are mfd and this is its subdevice. // // Copyright (C) 2011 Samsung Electronics // MyungJoo Ham <[email protected]> // // This driver is based on max17040_battery.c #include <linux/acpi.h> #include <linux/devm-helpers.h> #include <linux/init.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/i2c.h> #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/pm.h> #include <linux/mod_devicetable.h> #include <linux/power_supply.h> #include <linux/power/max17042_battery.h> #include <linux/of.h> #include <linux/regmap.h> /* Status register bits */ #define STATUS_POR_BIT (1 << 1) #define STATUS_BST_BIT (1 << 3) #define STATUS_VMN_BIT (1 << 8) #define STATUS_TMN_BIT (1 << 9) #define STATUS_SMN_BIT (1 << 10) #define STATUS_BI_BIT (1 << 11) #define STATUS_VMX_BIT (1 << 12) #define STATUS_TMX_BIT (1 << 13) #define STATUS_SMX_BIT (1 << 14) #define STATUS_BR_BIT (1 << 15) /* Interrupt mask bits */ #define CONFIG_ALRT_BIT_ENBL (1 << 2) #define VFSOC0_LOCK 0x0000 #define VFSOC0_UNLOCK 0x0080 #define MODEL_UNLOCK1 0X0059 #define MODEL_UNLOCK2 0X00C4 #define MODEL_LOCK1 0X0000 #define MODEL_LOCK2 0X0000 #define dQ_ACC_DIV 0x4 #define dP_ACC_100 0x1900 #define dP_ACC_200 0x3200 #define MAX17042_VMAX_TOLERANCE 50 /* 50 mV */ struct max17042_chip { struct i2c_client *client; struct regmap *regmap; struct power_supply *battery; enum max170xx_chip_type chip_type; struct max17042_platform_data *pdata; struct work_struct work; int init_complete; }; static enum power_supply_property max17042_battery_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_TECHNOLOGY, POWER_SUPPLY_PROP_CYCLE_COUNT, POWER_SUPPLY_PROP_VOLTAGE_MAX, POWER_SUPPLY_PROP_VOLTAGE_MIN, POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_VOLTAGE_AVG, POWER_SUPPLY_PROP_VOLTAGE_OCV, POWER_SUPPLY_PROP_CAPACITY, POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN, POWER_SUPPLY_PROP_CHARGE_FULL, POWER_SUPPLY_PROP_CHARGE_NOW, POWER_SUPPLY_PROP_CHARGE_COUNTER, POWER_SUPPLY_PROP_CHARGE_TERM_CURRENT, POWER_SUPPLY_PROP_TEMP, POWER_SUPPLY_PROP_TEMP_ALERT_MIN, POWER_SUPPLY_PROP_TEMP_ALERT_MAX, POWER_SUPPLY_PROP_TEMP_MIN, POWER_SUPPLY_PROP_TEMP_MAX, POWER_SUPPLY_PROP_HEALTH, POWER_SUPPLY_PROP_SCOPE, POWER_SUPPLY_PROP_TIME_TO_EMPTY_NOW, // these two have to be at the end on the list POWER_SUPPLY_PROP_CURRENT_NOW, POWER_SUPPLY_PROP_CURRENT_AVG, }; static int max17042_get_temperature(struct max17042_chip *chip, int *temp) { int ret; u32 data; struct regmap *map = chip->regmap; ret = regmap_read(map, MAX17042_TEMP, &data); if (ret < 0) return ret; *temp = sign_extend32(data, 15); /* The value is converted into deci-centigrade scale */ /* Units of LSB = 1 / 256 degree Celsius */ *temp = *temp * 10 / 256; return 0; } static int max17042_get_status(struct max17042_chip *chip, int *status) { int ret, charge_full, charge_now; int avg_current; u32 data; ret = power_supply_am_i_supplied(chip->battery); if (ret < 0) { *status = POWER_SUPPLY_STATUS_UNKNOWN; return 0; } if (ret == 0) { *status = POWER_SUPPLY_STATUS_DISCHARGING; return 0; } /* * The MAX170xx has builtin end-of-charge detection and will update * FullCAP to match RepCap when it detects end of charging. * * When this cycle the battery gets charged to a higher (calculated) * capacity then the previous cycle then FullCAP will get updated * continuously once end-of-charge detection kicks in, so allow the * 2 to differ a bit. */ ret = regmap_read(chip->regmap, MAX17042_FullCAP, &charge_full); if (ret < 0) return ret; ret = regmap_read(chip->regmap, MAX17042_RepCap, &charge_now); if (ret < 0) return ret; if ((charge_full - charge_now) <= MAX17042_FULL_THRESHOLD) { *status = POWER_SUPPLY_STATUS_FULL; return 0; } /* * Even though we are supplied, we may still be discharging if the * supply is e.g. only delivering 5V 0.5A. Check current if available. */ if (!chip->pdata->enable_current_sense) { *status = POWER_SUPPLY_STATUS_CHARGING; return 0; } ret = regmap_read(chip->regmap, MAX17042_AvgCurrent, &data); if (ret < 0) return ret; avg_current = sign_extend32(data, 15); avg_current *= 1562500 / chip->pdata->r_sns; if (avg_current > 0) *status = POWER_SUPPLY_STATUS_CHARGING; else *status = POWER_SUPPLY_STATUS_DISCHARGING; return 0; } static int max17042_get_battery_health(struct max17042_chip *chip, int *health) { int temp, vavg, vbatt, ret; u32 val; ret = regmap_read(chip->regmap, MAX17042_AvgVCELL, &val); if (ret < 0) goto health_error; /* bits [0-3] unused */ vavg = val * 625 / 8; /* Convert to millivolts */ vavg /= 1000; ret = regmap_read(chip->regmap, MAX17042_VCELL, &val); if (ret < 0) goto health_error; /* bits [0-3] unused */ vbatt = val * 625 / 8; /* Convert to millivolts */ vbatt /= 1000; if (vavg < chip->pdata->vmin) { *health = POWER_SUPPLY_HEALTH_DEAD; goto out; } if (vbatt > chip->pdata->vmax + MAX17042_VMAX_TOLERANCE) { *health = POWER_SUPPLY_HEALTH_OVERVOLTAGE; goto out; } ret = max17042_get_temperature(chip, &temp); if (ret < 0) goto health_error; if (temp < chip->pdata->temp_min) { *health = POWER_SUPPLY_HEALTH_COLD; goto out; } if (temp > chip->pdata->temp_max) { *health = POWER_SUPPLY_HEALTH_OVERHEAT; goto out; } *health = POWER_SUPPLY_HEALTH_GOOD; out: return 0; health_error: return ret; } static int max17042_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct max17042_chip *chip = power_supply_get_drvdata(psy); struct regmap *map = chip->regmap; int ret; u32 data; u64 data64; if (!chip->init_complete) return -EAGAIN; switch (psp) { case POWER_SUPPLY_PROP_STATUS: ret = max17042_get_status(chip, &val->intval); if (ret < 0) return ret; break; case POWER_SUPPLY_PROP_PRESENT: ret = regmap_read(map, MAX17042_STATUS, &data); if (ret < 0) return ret; if (data & MAX17042_STATUS_BattAbsent) val->intval = 0; else val->intval = 1; break; case POWER_SUPPLY_PROP_TECHNOLOGY: val->intval = POWER_SUPPLY_TECHNOLOGY_LION; break; case POWER_SUPPLY_PROP_CYCLE_COUNT: ret = regmap_read(map, MAX17042_Cycles, &data); if (ret < 0) return ret; val->intval = data; break; case POWER_SUPPLY_PROP_VOLTAGE_MAX: ret = regmap_read(map, MAX17042_MinMaxVolt, &data); if (ret < 0) return ret; val->intval = data >> 8; val->intval *= 20000; /* Units of LSB = 20mV */ break; case POWER_SUPPLY_PROP_VOLTAGE_MIN: ret = regmap_read(map, MAX17042_MinMaxVolt, &data); if (ret < 0) return ret; val->intval = (data & 0xff) * 20000; /* Units of 20mV */ break; case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN: if (chip->chip_type == MAXIM_DEVICE_TYPE_MAX17042) ret = regmap_read(map, MAX17042_V_empty, &data); else ret = regmap_read(map, MAX17047_V_empty, &data); if (ret < 0) return ret; val->intval = data >> 7; val->intval *= 10000; /* Units of LSB = 10mV */ break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: ret = regmap_read(map, MAX17042_VCELL, &data); if (ret < 0) return ret; val->intval = data * 625 / 8; break; case POWER_SUPPLY_PROP_VOLTAGE_AVG: ret = regmap_read(map, MAX17042_AvgVCELL, &data); if (ret < 0) return ret; val->intval = data * 625 / 8; break; case POWER_SUPPLY_PROP_VOLTAGE_OCV: ret = regmap_read(map, MAX17042_OCVInternal, &data); if (ret < 0) return ret; val->intval = data * 625 / 8; break; case POWER_SUPPLY_PROP_CAPACITY: if (chip->pdata->enable_current_sense) ret = regmap_read(map, MAX17042_RepSOC, &data); else ret = regmap_read(map, MAX17042_VFSOC, &data); if (ret < 0) return ret; val->intval = data >> 8; break; case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN: ret = regmap_read(map, MAX17042_DesignCap, &data); if (ret < 0) return ret; data64 = data * 5000000ll; do_div(data64, chip->pdata->r_sns); val->intval = data64; break; case POWER_SUPPLY_PROP_CHARGE_FULL: ret = regmap_read(map, MAX17042_FullCAP, &data); if (ret < 0) return ret; data64 = data * 5000000ll; do_div(data64, chip->pdata->r_sns); val->intval = data64; break; case POWER_SUPPLY_PROP_CHARGE_NOW: ret = regmap_read(map, MAX17042_RepCap, &data); if (ret < 0) return ret; data64 = data * 5000000ll; do_div(data64, chip->pdata->r_sns); val->intval = data64; break; case POWER_SUPPLY_PROP_CHARGE_COUNTER: ret = regmap_read(map, MAX17042_QH, &data); if (ret < 0) return ret; data64 = sign_extend64(data, 15) * 5000000ll; val->intval = div_s64(data64, chip->pdata->r_sns); break; case POWER_SUPPLY_PROP_TEMP: ret = max17042_get_temperature(chip, &val->intval); if (ret < 0) return ret; break; case POWER_SUPPLY_PROP_TEMP_ALERT_MIN: ret = regmap_read(map, MAX17042_TALRT_Th, &data); if (ret < 0) return ret; /* LSB is Alert Minimum. In deci-centigrade */ val->intval = sign_extend32(data & 0xff, 7) * 10; break; case POWER_SUPPLY_PROP_TEMP_ALERT_MAX: ret = regmap_read(map, MAX17042_TALRT_Th, &data); if (ret < 0) return ret; /* MSB is Alert Maximum. In deci-centigrade */ val->intval = sign_extend32(data >> 8, 7) * 10; break; case POWER_SUPPLY_PROP_TEMP_MIN: val->intval = chip->pdata->temp_min; break; case POWER_SUPPLY_PROP_TEMP_MAX: val->intval = chip->pdata->temp_max; break; case POWER_SUPPLY_PROP_HEALTH: ret = max17042_get_battery_health(chip, &val->intval); if (ret < 0) return ret; break; case POWER_SUPPLY_PROP_SCOPE: val->intval = POWER_SUPPLY_SCOPE_SYSTEM; break; case POWER_SUPPLY_PROP_CURRENT_NOW: if (chip->pdata->enable_current_sense) { ret = regmap_read(map, MAX17042_Current, &data); if (ret < 0) return ret; data64 = sign_extend64(data, 15) * 1562500ll; val->intval = div_s64(data64, chip->pdata->r_sns); } else { return -EINVAL; } break; case POWER_SUPPLY_PROP_CURRENT_AVG: if (chip->pdata->enable_current_sense) { ret = regmap_read(map, MAX17042_AvgCurrent, &data); if (ret < 0) return ret; data64 = sign_extend64(data, 15) * 1562500ll; val->intval = div_s64(data64, chip->pdata->r_sns); } else { return -EINVAL; } break; case POWER_SUPPLY_PROP_CHARGE_TERM_CURRENT: ret = regmap_read(map, MAX17042_ICHGTerm, &data); if (ret < 0) return ret; data64 = data * 1562500ll; val->intval = div_s64(data64, chip->pdata->r_sns); break; case POWER_SUPPLY_PROP_TIME_TO_EMPTY_NOW: ret = regmap_read(map, MAX17042_TTE, &data); if (ret < 0) return ret; val->intval = data * 5625 / 1000; break; default: return -EINVAL; } return 0; } static int max17042_set_property(struct power_supply *psy, enum power_supply_property psp, const union power_supply_propval *val) { struct max17042_chip *chip = power_supply_get_drvdata(psy); struct regmap *map = chip->regmap; int ret = 0; u32 data; int8_t temp; switch (psp) { case POWER_SUPPLY_PROP_TEMP_ALERT_MIN: ret = regmap_read(map, MAX17042_TALRT_Th, &data); if (ret < 0) return ret; /* Input in deci-centigrade, convert to centigrade */ temp = val->intval / 10; /* force min < max */ if (temp >= (int8_t)(data >> 8)) temp = (int8_t)(data >> 8) - 1; /* Write both MAX and MIN ALERT */ data = (data & 0xff00) + temp; ret = regmap_write(map, MAX17042_TALRT_Th, data); break; case POWER_SUPPLY_PROP_TEMP_ALERT_MAX: ret = regmap_read(map, MAX17042_TALRT_Th, &data); if (ret < 0) return ret; /* Input in Deci-Centigrade, convert to centigrade */ temp = val->intval / 10; /* force max > min */ if (temp <= (int8_t)(data & 0xff)) temp = (int8_t)(data & 0xff) + 1; /* Write both MAX and MIN ALERT */ data = (data & 0xff) + (temp << 8); ret = regmap_write(map, MAX17042_TALRT_Th, data); break; default: ret = -EINVAL; } return ret; } static int max17042_property_is_writeable(struct power_supply *psy, enum power_supply_property psp) { int ret; switch (psp) { case POWER_SUPPLY_PROP_TEMP_ALERT_MIN: case POWER_SUPPLY_PROP_TEMP_ALERT_MAX: ret = 1; break; default: ret = 0; } return ret; } static int max17042_write_verify_reg(struct regmap *map, u8 reg, u32 value) { int retries = 8; int ret; u32 read_value; do { ret = regmap_write(map, reg, value); regmap_read(map, reg, &read_value); if (read_value != value) { ret = -EIO; retries--; } } while (retries && read_value != value); if (ret < 0) pr_err("%s: err %d\n", __func__, ret); return ret; } static inline void max17042_override_por(struct regmap *map, u8 reg, u16 value) { if (value) regmap_write(map, reg, value); } static inline void max17042_unlock_model(struct max17042_chip *chip) { struct regmap *map = chip->regmap; regmap_write(map, MAX17042_MLOCKReg1, MODEL_UNLOCK1); regmap_write(map, MAX17042_MLOCKReg2, MODEL_UNLOCK2); } static inline void max17042_lock_model(struct max17042_chip *chip) { struct regmap *map = chip->regmap; regmap_write(map, MAX17042_MLOCKReg1, MODEL_LOCK1); regmap_write(map, MAX17042_MLOCKReg2, MODEL_LOCK2); } static inline void max17042_write_model_data(struct max17042_chip *chip, u8 addr, int size) { struct regmap *map = chip->regmap; int i; for (i = 0; i < size; i++) regmap_write(map, addr + i, chip->pdata->config_data->cell_char_tbl[i]); } static inline void max17042_read_model_data(struct max17042_chip *chip, u8 addr, u16 *data, int size) { struct regmap *map = chip->regmap; int i; u32 tmp; for (i = 0; i < size; i++) { regmap_read(map, addr + i, &tmp); data[i] = (u16)tmp; } } static inline int max17042_model_data_compare(struct max17042_chip *chip, u16 *data1, u16 *data2, int size) { int i; if (memcmp(data1, data2, size)) { dev_err(&chip->client->dev, "%s compare failed\n", __func__); for (i = 0; i < size; i++) dev_info(&chip->client->dev, "0x%x, 0x%x", data1[i], data2[i]); dev_info(&chip->client->dev, "\n"); return -EINVAL; } return 0; } static int max17042_init_model(struct max17042_chip *chip) { int ret; int table_size = ARRAY_SIZE(chip->pdata->config_data->cell_char_tbl); u16 *temp_data; temp_data = kcalloc(table_size, sizeof(*temp_data), GFP_KERNEL); if (!temp_data) return -ENOMEM; max17042_unlock_model(chip); max17042_write_model_data(chip, MAX17042_MODELChrTbl, table_size); max17042_read_model_data(chip, MAX17042_MODELChrTbl, temp_data, table_size); ret = max17042_model_data_compare( chip, chip->pdata->config_data->cell_char_tbl, temp_data, table_size); max17042_lock_model(chip); kfree(temp_data); return ret; } static int max17042_verify_model_lock(struct max17042_chip *chip) { int i; int table_size = ARRAY_SIZE(chip->pdata->config_data->cell_char_tbl); u16 *temp_data; int ret = 0; temp_data = kcalloc(table_size, sizeof(*temp_data), GFP_KERNEL); if (!temp_data) return -ENOMEM; max17042_read_model_data(chip, MAX17042_MODELChrTbl, temp_data, table_size); for (i = 0; i < table_size; i++) if (temp_data[i]) ret = -EINVAL; kfree(temp_data); return ret; } static void max17042_write_config_regs(struct max17042_chip *chip) { struct max17042_config_data *config = chip->pdata->config_data; struct regmap *map = chip->regmap; regmap_write(map, MAX17042_CONFIG, config->config); regmap_write(map, MAX17042_LearnCFG, config->learn_cfg); regmap_write(map, MAX17042_FilterCFG, config->filter_cfg); regmap_write(map, MAX17042_RelaxCFG, config->relax_cfg); if (chip->chip_type == MAXIM_DEVICE_TYPE_MAX17047 || chip->chip_type == MAXIM_DEVICE_TYPE_MAX17050 || chip->chip_type == MAXIM_DEVICE_TYPE_MAX17055) regmap_write(map, MAX17047_FullSOCThr, config->full_soc_thresh); } static void max17042_write_custom_regs(struct max17042_chip *chip) { struct max17042_config_data *config = chip->pdata->config_data; struct regmap *map = chip->regmap; max17042_write_verify_reg(map, MAX17042_RCOMP0, config->rcomp0); max17042_write_verify_reg(map, MAX17042_TempCo, config->tcompc0); max17042_write_verify_reg(map, MAX17042_ICHGTerm, config->ichgt_term); if (chip->chip_type == MAXIM_DEVICE_TYPE_MAX17042) { regmap_write(map, MAX17042_EmptyTempCo, config->empty_tempco); max17042_write_verify_reg(map, MAX17042_K_empty0, config->kempty0); } else { max17042_write_verify_reg(map, MAX17047_QRTbl00, config->qrtbl00); max17042_write_verify_reg(map, MAX17047_QRTbl10, config->qrtbl10); max17042_write_verify_reg(map, MAX17047_QRTbl20, config->qrtbl20); max17042_write_verify_reg(map, MAX17047_QRTbl30, config->qrtbl30); } } static void max17042_update_capacity_regs(struct max17042_chip *chip) { struct max17042_config_data *config = chip->pdata->config_data; struct regmap *map = chip->regmap; max17042_write_verify_reg(map, MAX17042_FullCAP, config->fullcap); regmap_write(map, MAX17042_DesignCap, config->design_cap); max17042_write_verify_reg(map, MAX17042_FullCAPNom, config->fullcapnom); } static void max17042_reset_vfsoc0_reg(struct max17042_chip *chip) { unsigned int vfSoc; struct regmap *map = chip->regmap; regmap_read(map, MAX17042_VFSOC, &vfSoc); regmap_write(map, MAX17042_VFSOC0Enable, VFSOC0_UNLOCK); max17042_write_verify_reg(map, MAX17042_VFSOC0, vfSoc); regmap_write(map, MAX17042_VFSOC0Enable, VFSOC0_LOCK); } static void max17042_load_new_capacity_params(struct max17042_chip *chip) { u32 full_cap0, rep_cap, dq_acc, vfSoc; u32 rem_cap; struct max17042_config_data *config = chip->pdata->config_data; struct regmap *map = chip->regmap; regmap_read(map, MAX17042_FullCAP0, &full_cap0); regmap_read(map, MAX17042_VFSOC, &vfSoc); /* fg_vfSoc needs to shifted by 8 bits to get the * perc in 1% accuracy, to get the right rem_cap multiply * full_cap0, fg_vfSoc and devide by 100 */ rem_cap = ((vfSoc >> 8) * full_cap0) / 100; max17042_write_verify_reg(map, MAX17042_RemCap, rem_cap); rep_cap = rem_cap; max17042_write_verify_reg(map, MAX17042_RepCap, rep_cap); /* Write dQ_acc to 200% of Capacity and dP_acc to 200% */ dq_acc = config->fullcap / dQ_ACC_DIV; max17042_write_verify_reg(map, MAX17042_dQacc, dq_acc); max17042_write_verify_reg(map, MAX17042_dPacc, dP_ACC_200); max17042_write_verify_reg(map, MAX17042_FullCAP, config->fullcap); regmap_write(map, MAX17042_DesignCap, config->design_cap); max17042_write_verify_reg(map, MAX17042_FullCAPNom, config->fullcapnom); /* Update SOC register with new SOC */ regmap_write(map, MAX17042_RepSOC, vfSoc); } /* * Block write all the override values coming from platform data. * This function MUST be called before the POR initialization procedure * specified by maxim. */ static inline void max17042_override_por_values(struct max17042_chip *chip) { struct regmap *map = chip->regmap; struct max17042_config_data *config = chip->pdata->config_data; max17042_override_por(map, MAX17042_TGAIN, config->tgain); max17042_override_por(map, MAX17042_TOFF, config->toff); max17042_override_por(map, MAX17042_CGAIN, config->cgain); max17042_override_por(map, MAX17042_COFF, config->coff); max17042_override_por(map, MAX17042_VALRT_Th, config->valrt_thresh); max17042_override_por(map, MAX17042_TALRT_Th, config->talrt_thresh); max17042_override_por(map, MAX17042_SALRT_Th, config->soc_alrt_thresh); max17042_override_por(map, MAX17042_CONFIG, config->config); max17042_override_por(map, MAX17042_SHDNTIMER, config->shdntimer); max17042_override_por(map, MAX17042_DesignCap, config->design_cap); max17042_override_por(map, MAX17042_ICHGTerm, config->ichgt_term); max17042_override_por(map, MAX17042_AtRate, config->at_rate); max17042_override_por(map, MAX17042_LearnCFG, config->learn_cfg); max17042_override_por(map, MAX17042_FilterCFG, config->filter_cfg); max17042_override_por(map, MAX17042_RelaxCFG, config->relax_cfg); max17042_override_por(map, MAX17042_MiscCFG, config->misc_cfg); max17042_override_por(map, MAX17042_FullCAP, config->fullcap); max17042_override_por(map, MAX17042_FullCAPNom, config->fullcapnom); max17042_override_por(map, MAX17042_dQacc, config->dqacc); max17042_override_por(map, MAX17042_dPacc, config->dpacc); max17042_override_por(map, MAX17042_RCOMP0, config->rcomp0); max17042_override_por(map, MAX17042_TempCo, config->tcompc0); if (chip->chip_type == MAXIM_DEVICE_TYPE_MAX17042) { max17042_override_por(map, MAX17042_MaskSOC, config->masksoc); max17042_override_por(map, MAX17042_SOC_empty, config->socempty); max17042_override_por(map, MAX17042_V_empty, config->vempty); max17042_override_por(map, MAX17042_EmptyTempCo, config->empty_tempco); max17042_override_por(map, MAX17042_K_empty0, config->kempty0); } if ((chip->chip_type == MAXIM_DEVICE_TYPE_MAX17042) || (chip->chip_type == MAXIM_DEVICE_TYPE_MAX17047) || (chip->chip_type == MAXIM_DEVICE_TYPE_MAX17050)) { max17042_override_por(map, MAX17042_IAvg_empty, config->iavg_empty); max17042_override_por(map, MAX17042_TempNom, config->temp_nom); max17042_override_por(map, MAX17042_TempLim, config->temp_lim); max17042_override_por(map, MAX17042_FCTC, config->fctc); } if ((chip->chip_type == MAXIM_DEVICE_TYPE_MAX17047) || (chip->chip_type == MAXIM_DEVICE_TYPE_MAX17050) || (chip->chip_type == MAXIM_DEVICE_TYPE_MAX17055)) { max17042_override_por(map, MAX17047_V_empty, config->vempty); } } static int max17042_init_chip(struct max17042_chip *chip) { struct regmap *map = chip->regmap; int ret; max17042_override_por_values(chip); /* After Power up, the MAX17042 requires 500mS in order * to perform signal debouncing and initial SOC reporting */ msleep(500); /* Initialize configuration */ max17042_write_config_regs(chip); /* write cell characterization data */ ret = max17042_init_model(chip); if (ret) { dev_err(&chip->client->dev, "%s init failed\n", __func__); return -EIO; } ret = max17042_verify_model_lock(chip); if (ret) { dev_err(&chip->client->dev, "%s lock verify failed\n", __func__); return -EIO; } /* write custom parameters */ max17042_write_custom_regs(chip); /* update capacity params */ max17042_update_capacity_regs(chip); /* delay must be atleast 350mS to allow VFSOC * to be calculated from the new configuration */ msleep(350); /* reset vfsoc0 reg */ max17042_reset_vfsoc0_reg(chip); /* load new capacity params */ max17042_load_new_capacity_params(chip); /* Init complete, Clear the POR bit */ regmap_update_bits(map, MAX17042_STATUS, STATUS_POR_BIT, 0x0); return 0; } static void max17042_set_soc_threshold(struct max17042_chip *chip, u16 off) { struct regmap *map = chip->regmap; u32 soc, soc_tr; /* program interrupt thresholds such that we should * get interrupt for every 'off' perc change in the soc */ regmap_read(map, MAX17042_RepSOC, &soc); soc >>= 8; soc_tr = (soc + off) << 8; if (off < soc) soc_tr |= soc - off; regmap_write(map, MAX17042_SALRT_Th, soc_tr); } static irqreturn_t max17042_thread_handler(int id, void *dev) { struct max17042_chip *chip = dev; u32 val; int ret; ret = regmap_read(chip->regmap, MAX17042_STATUS, &val); if (ret) return IRQ_HANDLED; if ((val & STATUS_SMN_BIT) || (val & STATUS_SMX_BIT)) { dev_dbg(&chip->client->dev, "SOC threshold INTR\n"); max17042_set_soc_threshold(chip, 1); } /* we implicitly handle all alerts via power_supply_changed */ regmap_clear_bits(chip->regmap, MAX17042_STATUS, 0xFFFF & ~(STATUS_POR_BIT | STATUS_BST_BIT)); power_supply_changed(chip->battery); return IRQ_HANDLED; } static void max17042_init_worker(struct work_struct *work) { struct max17042_chip *chip = container_of(work, struct max17042_chip, work); int ret; /* Initialize registers according to values from the platform data */ if (chip->pdata->enable_por_init && chip->pdata->config_data) { ret = max17042_init_chip(chip); if (ret) return; } chip->init_complete = 1; } #ifdef CONFIG_OF static struct max17042_platform_data * max17042_get_of_pdata(struct max17042_chip *chip) { struct device *dev = &chip->client->dev; struct device_node *np = dev->of_node; u32 prop; struct max17042_platform_data *pdata; pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL); if (!pdata) return NULL; /* * Require current sense resistor value to be specified for * current-sense functionality to be enabled at all. */ if (of_property_read_u32(np, "maxim,rsns-microohm", &prop) == 0) { pdata->r_sns = prop; pdata->enable_current_sense = true; } if (of_property_read_s32(np, "maxim,cold-temp", &pdata->temp_min)) pdata->temp_min = INT_MIN; if (of_property_read_s32(np, "maxim,over-heat-temp", &pdata->temp_max)) pdata->temp_max = INT_MAX; if (of_property_read_s32(np, "maxim,dead-volt", &pdata->vmin)) pdata->vmin = INT_MIN; if (of_property_read_s32(np, "maxim,over-volt", &pdata->vmax)) pdata->vmax = INT_MAX; return pdata; } #endif static struct max17042_reg_data max17047_default_pdata_init_regs[] = { /* * Some firmwares do not set FullSOCThr, Enable End-of-Charge Detection * when the voltage FG reports 95%, as recommended in the datasheet. */ { MAX17047_FullSOCThr, MAX17042_BATTERY_FULL << 8 }, }; static struct max17042_platform_data * max17042_get_default_pdata(struct max17042_chip *chip) { struct device *dev = &chip->client->dev; struct max17042_platform_data *pdata; int ret, misc_cfg; /* * The MAX17047 gets used on x86 where we might not have pdata, assume * the firmware will already have initialized the fuel-gauge and provide * default values for the non init bits to make things work. */ pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL); if (!pdata) return pdata; if ((chip->chip_type == MAXIM_DEVICE_TYPE_MAX17047) || (chip->chip_type == MAXIM_DEVICE_TYPE_MAX17050)) { pdata->init_data = max17047_default_pdata_init_regs; pdata->num_init_data = ARRAY_SIZE(max17047_default_pdata_init_regs); } ret = regmap_read(chip->regmap, MAX17042_MiscCFG, &misc_cfg); if (ret < 0) return NULL; /* If bits 0-1 are set to 3 then only Voltage readings are used */ if ((misc_cfg & 0x3) == 0x3) pdata->enable_current_sense = false; else pdata->enable_current_sense = true; pdata->vmin = MAX17042_DEFAULT_VMIN; pdata->vmax = MAX17042_DEFAULT_VMAX; pdata->temp_min = MAX17042_DEFAULT_TEMP_MIN; pdata->temp_max = MAX17042_DEFAULT_TEMP_MAX; return pdata; } static struct max17042_platform_data * max17042_get_pdata(struct max17042_chip *chip) { struct device *dev = &chip->client->dev; #ifdef CONFIG_OF if (dev->of_node) return max17042_get_of_pdata(chip); #endif if (dev->platform_data) return dev->platform_data; return max17042_get_default_pdata(chip); } static const struct regmap_config max17042_regmap_config = { .reg_bits = 8, .val_bits = 16, .val_format_endian = REGMAP_ENDIAN_NATIVE, }; static const struct power_supply_desc max17042_psy_desc = { .name = "max170xx_battery", .type = POWER_SUPPLY_TYPE_BATTERY, .get_property = max17042_get_property, .set_property = max17042_set_property, .property_is_writeable = max17042_property_is_writeable, .external_power_changed = power_supply_changed, .properties = max17042_battery_props, .num_properties = ARRAY_SIZE(max17042_battery_props), }; static const struct power_supply_desc max17042_no_current_sense_psy_desc = { .name = "max170xx_battery", .type = POWER_SUPPLY_TYPE_BATTERY, .get_property = max17042_get_property, .set_property = max17042_set_property, .property_is_writeable = max17042_property_is_writeable, .properties = max17042_battery_props, .num_properties = ARRAY_SIZE(max17042_battery_props) - 2, }; static int max17042_probe(struct i2c_client *client) { const struct i2c_device_id *id = i2c_client_get_device_id(client); struct i2c_adapter *adapter = client->adapter; const struct power_supply_desc *max17042_desc = &max17042_psy_desc; struct power_supply_config psy_cfg = {}; const struct acpi_device_id *acpi_id = NULL; struct device *dev = &client->dev; struct max17042_chip *chip; int ret; int i; u32 val; if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_WORD_DATA)) return -EIO; chip = devm_kzalloc(&client->dev, sizeof(*chip), GFP_KERNEL); if (!chip) return -ENOMEM; chip->client = client; if (id) { chip->chip_type = id->driver_data; } else { acpi_id = acpi_match_device(dev->driver->acpi_match_table, dev); if (!acpi_id) return -ENODEV; chip->chip_type = acpi_id->driver_data; } chip->regmap = devm_regmap_init_i2c(client, &max17042_regmap_config); if (IS_ERR(chip->regmap)) { dev_err(&client->dev, "Failed to initialize regmap\n"); return -EINVAL; } chip->pdata = max17042_get_pdata(chip); if (!chip->pdata) { dev_err(&client->dev, "no platform data provided\n"); return -EINVAL; } i2c_set_clientdata(client, chip); psy_cfg.drv_data = chip; psy_cfg.of_node = dev->of_node; /* When current is not measured, * CURRENT_NOW and CURRENT_AVG properties should be invisible. */ if (!chip->pdata->enable_current_sense) max17042_desc = &max17042_no_current_sense_psy_desc; if (chip->pdata->r_sns == 0) chip->pdata->r_sns = MAX17042_DEFAULT_SNS_RESISTOR; if (chip->pdata->init_data) for (i = 0; i < chip->pdata->num_init_data; i++) regmap_write(chip->regmap, chip->pdata->init_data[i].addr, chip->pdata->init_data[i].data); if (!chip->pdata->enable_current_sense) { regmap_write(chip->regmap, MAX17042_CGAIN, 0x0000); regmap_write(chip->regmap, MAX17042_MiscCFG, 0x0003); regmap_write(chip->regmap, MAX17042_LearnCFG, 0x0007); } chip->battery = devm_power_supply_register(&client->dev, max17042_desc, &psy_cfg); if (IS_ERR(chip->battery)) { dev_err(&client->dev, "failed: power supply register\n"); return PTR_ERR(chip->battery); } if (client->irq) { unsigned int flags = IRQF_ONESHOT; /* * On ACPI systems the IRQ may be handled by ACPI-event code, * so we need to share (if the ACPI code is willing to share). */ if (acpi_id) flags |= IRQF_SHARED | IRQF_PROBE_SHARED; ret = devm_request_threaded_irq(&client->dev, client->irq, NULL, max17042_thread_handler, flags, chip->battery->desc->name, chip); if (!ret) { regmap_update_bits(chip->regmap, MAX17042_CONFIG, CONFIG_ALRT_BIT_ENBL, CONFIG_ALRT_BIT_ENBL); max17042_set_soc_threshold(chip, 1); } else { client->irq = 0; if (ret != -EBUSY) dev_err(&client->dev, "Failed to get IRQ\n"); } } /* Not able to update the charge threshold when exceeded? -> disable */ if (!client->irq) regmap_write(chip->regmap, MAX17042_SALRT_Th, 0xff00); regmap_read(chip->regmap, MAX17042_STATUS, &val); if (val & STATUS_POR_BIT) { ret = devm_work_autocancel(&client->dev, &chip->work, max17042_init_worker); if (ret) return ret; schedule_work(&chip->work); } else { chip->init_complete = 1; } return 0; } #ifdef CONFIG_PM_SLEEP static int max17042_suspend(struct device *dev) { struct max17042_chip *chip = dev_get_drvdata(dev); /* * disable the irq and enable irq_wake * capability to the interrupt line. */ if (chip->client->irq) { disable_irq(chip->client->irq); enable_irq_wake(chip->client->irq); } return 0; } static int max17042_resume(struct device *dev) { struct max17042_chip *chip = dev_get_drvdata(dev); if (chip->client->irq) { disable_irq_wake(chip->client->irq); enable_irq(chip->client->irq); /* re-program the SOC thresholds to 1% change */ max17042_set_soc_threshold(chip, 1); } return 0; } #endif static SIMPLE_DEV_PM_OPS(max17042_pm_ops, max17042_suspend, max17042_resume); #ifdef CONFIG_ACPI static const struct acpi_device_id max17042_acpi_match[] = { { "MAX17047", MAXIM_DEVICE_TYPE_MAX17047 }, { } }; MODULE_DEVICE_TABLE(acpi, max17042_acpi_match); #endif #ifdef CONFIG_OF static const struct of_device_id max17042_dt_match[] = { { .compatible = "maxim,max17042" }, { .compatible = "maxim,max17047" }, { .compatible = "maxim,max17050" }, { .compatible = "maxim,max17055" }, { .compatible = "maxim,max77849-battery" }, { }, }; MODULE_DEVICE_TABLE(of, max17042_dt_match); #endif static const struct i2c_device_id max17042_id[] = { { "max17042", MAXIM_DEVICE_TYPE_MAX17042 }, { "max17047", MAXIM_DEVICE_TYPE_MAX17047 }, { "max17050", MAXIM_DEVICE_TYPE_MAX17050 }, { "max17055", MAXIM_DEVICE_TYPE_MAX17055 }, { "max77849-battery", MAXIM_DEVICE_TYPE_MAX17047 }, { } }; MODULE_DEVICE_TABLE(i2c, max17042_id); static struct i2c_driver max17042_i2c_driver = { .driver = { .name = "max17042", .acpi_match_table = ACPI_PTR(max17042_acpi_match), .of_match_table = of_match_ptr(max17042_dt_match), .pm = &max17042_pm_ops, }, .probe = max17042_probe, .id_table = max17042_id, }; module_i2c_driver(max17042_i2c_driver); MODULE_AUTHOR("MyungJoo Ham <[email protected]>"); MODULE_DESCRIPTION("MAX17042 Fuel Gauge"); MODULE_LICENSE("GPL");
linux-master
drivers/power/supply/max17042_battery.c
// SPDX-License-Identifier: GPL-2.0-only /* * Backup battery driver for Wolfson Microelectronics wm831x PMICs * * Copyright 2009 Wolfson Microelectronics PLC. */ #include <linux/module.h> #include <linux/err.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/slab.h> #include <linux/mfd/wm831x/core.h> #include <linux/mfd/wm831x/auxadc.h> #include <linux/mfd/wm831x/pmu.h> #include <linux/mfd/wm831x/pdata.h> struct wm831x_backup { struct wm831x *wm831x; struct power_supply *backup; struct power_supply_desc backup_desc; char name[20]; }; static int wm831x_backup_read_voltage(struct wm831x *wm831x, enum wm831x_auxadc src, union power_supply_propval *val) { int ret; ret = wm831x_auxadc_read_uv(wm831x, src); if (ret >= 0) val->intval = ret; return ret; } /********************************************************************* * Backup supply properties *********************************************************************/ static void wm831x_config_backup(struct wm831x *wm831x) { struct wm831x_pdata *wm831x_pdata = wm831x->dev->platform_data; struct wm831x_backup_pdata *pdata; int ret, reg; if (!wm831x_pdata || !wm831x_pdata->backup) { dev_warn(wm831x->dev, "No backup battery charger configuration\n"); return; } pdata = wm831x_pdata->backup; reg = 0; if (pdata->charger_enable) reg |= WM831X_BKUP_CHG_ENA | WM831X_BKUP_BATT_DET_ENA; if (pdata->no_constant_voltage) reg |= WM831X_BKUP_CHG_MODE; switch (pdata->vlim) { case 2500: break; case 3100: reg |= WM831X_BKUP_CHG_VLIM; break; default: dev_err(wm831x->dev, "Invalid backup voltage limit %dmV\n", pdata->vlim); } switch (pdata->ilim) { case 100: break; case 200: reg |= 1; break; case 300: reg |= 2; break; case 400: reg |= 3; break; default: dev_err(wm831x->dev, "Invalid backup current limit %duA\n", pdata->ilim); } ret = wm831x_reg_unlock(wm831x); if (ret != 0) { dev_err(wm831x->dev, "Failed to unlock registers: %d\n", ret); return; } ret = wm831x_set_bits(wm831x, WM831X_BACKUP_CHARGER_CONTROL, WM831X_BKUP_CHG_ENA_MASK | WM831X_BKUP_CHG_MODE_MASK | WM831X_BKUP_BATT_DET_ENA_MASK | WM831X_BKUP_CHG_VLIM_MASK | WM831X_BKUP_CHG_ILIM_MASK, reg); if (ret != 0) dev_err(wm831x->dev, "Failed to set backup charger config: %d\n", ret); wm831x_reg_lock(wm831x); } static int wm831x_backup_get_prop(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct wm831x_backup *devdata = dev_get_drvdata(psy->dev.parent); struct wm831x *wm831x = devdata->wm831x; int ret = 0; ret = wm831x_reg_read(wm831x, WM831X_BACKUP_CHARGER_CONTROL); if (ret < 0) return ret; switch (psp) { case POWER_SUPPLY_PROP_STATUS: if (ret & WM831X_BKUP_CHG_STS) val->intval = POWER_SUPPLY_STATUS_CHARGING; else val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING; break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: ret = wm831x_backup_read_voltage(wm831x, WM831X_AUX_BKUP_BATT, val); break; case POWER_SUPPLY_PROP_PRESENT: if (ret & WM831X_BKUP_CHG_STS) val->intval = 1; else val->intval = 0; break; default: ret = -EINVAL; break; } return ret; } static enum power_supply_property wm831x_backup_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_PRESENT, }; /********************************************************************* * Initialisation *********************************************************************/ static int wm831x_backup_probe(struct platform_device *pdev) { struct wm831x *wm831x = dev_get_drvdata(pdev->dev.parent); struct wm831x_pdata *wm831x_pdata = wm831x->dev->platform_data; struct wm831x_backup *devdata; devdata = devm_kzalloc(&pdev->dev, sizeof(struct wm831x_backup), GFP_KERNEL); if (devdata == NULL) return -ENOMEM; devdata->wm831x = wm831x; platform_set_drvdata(pdev, devdata); /* We ignore configuration failures since we can still read * back the status without enabling the charger (which may * already be enabled anyway). */ wm831x_config_backup(wm831x); if (wm831x_pdata && wm831x_pdata->wm831x_num) snprintf(devdata->name, sizeof(devdata->name), "wm831x-backup.%d", wm831x_pdata->wm831x_num); else snprintf(devdata->name, sizeof(devdata->name), "wm831x-backup"); devdata->backup_desc.name = devdata->name; devdata->backup_desc.type = POWER_SUPPLY_TYPE_BATTERY; devdata->backup_desc.properties = wm831x_backup_props; devdata->backup_desc.num_properties = ARRAY_SIZE(wm831x_backup_props); devdata->backup_desc.get_property = wm831x_backup_get_prop; devdata->backup = power_supply_register(&pdev->dev, &devdata->backup_desc, NULL); return PTR_ERR_OR_ZERO(devdata->backup); } static int wm831x_backup_remove(struct platform_device *pdev) { struct wm831x_backup *devdata = platform_get_drvdata(pdev); power_supply_unregister(devdata->backup); return 0; } static struct platform_driver wm831x_backup_driver = { .probe = wm831x_backup_probe, .remove = wm831x_backup_remove, .driver = { .name = "wm831x-backup", }, }; module_platform_driver(wm831x_backup_driver); MODULE_DESCRIPTION("Backup battery charger driver for WM831x PMICs"); MODULE_AUTHOR("Mark Brown <[email protected]>"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:wm831x-backup");
linux-master
drivers/power/supply/wm831x_backup.c
// SPDX-License-Identifier: GPL-2.0 // BQ2515X Battery Charger Driver // Copyright (C) 2020 Texas Instruments Incorporated - https://www.ti.com/ #include <linux/err.h> #include <linux/i2c.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/gpio/consumer.h> #include <linux/power_supply.h> #include <linux/regmap.h> #include <linux/types.h> #define BQ2515X_MANUFACTURER "Texas Instruments" #define BQ2515X_STAT0 0x00 #define BQ2515X_STAT1 0x01 #define BQ2515X_STAT2 0x02 #define BQ2515X_FLAG0 0x03 #define BQ2515X_FLAG1 0x04 #define BQ2515X_FLAG2 0x05 #define BQ2515X_FLAG3 0x06 #define BQ2515X_MASK0 0x07 #define BQ2515X_MASK1 0x08 #define BQ2515X_MASK2 0x09 #define BQ2515X_MASK3 0x0a #define BQ2515X_VBAT_CTRL 0x12 #define BQ2515X_ICHG_CTRL 0x13 #define BQ2515X_PCHRGCTRL 0x14 #define BQ2515X_TERMCTRL 0x15 #define BQ2515X_BUVLO 0x16 #define BQ2515X_CHARGERCTRL0 0x17 #define BQ2515X_CHARGERCTRL1 0x18 #define BQ2515X_ILIMCTRL 0x19 #define BQ2515X_LDOCTRL 0x1d #define BQ2515X_MRCTRL 0x30 #define BQ2515X_ICCTRL0 0x35 #define BQ2515X_ICCTRL1 0x36 #define BQ2515X_ICCTRL2 0x37 #define BQ2515X_ADCCTRL0 0x40 #define BQ2515X_ADCCTRL1 0x41 #define BQ2515X_ADC_VBAT_M 0x42 #define BQ2515X_ADC_VBAT_L 0x43 #define BQ2515X_ADC_TS_M 0x44 #define BQ2515X_ADC_TS_L 0x45 #define BQ2515X_ADC_ICHG_M 0x46 #define BQ2515X_ADC_ICHG_L 0x47 #define BQ2515X_ADC_ADCIN_M 0x48 #define BQ2515X_ADC_ADCIN_L 0x49 #define BQ2515X_ADC_VIN_M 0x4a #define BQ2515X_ADC_VIN_L 0x4b #define BQ2515X_ADC_PMID_M 0x4c #define BQ2515X_ADC_PMID_L 0x4d #define BQ2515X_ADC_IIN_M 0x4e #define BQ2515X_ADC_IIN_L 0x4f #define BQ2515X_ADC_COMP1_M 0x52 #define BQ2515X_ADC_COMP1_L 0X53 #define BQ2515X_ADC_COMP2_M 0X54 #define BQ2515X_ADC_COMP2_L 0x55 #define BQ2515X_ADC_COMP3_M 0x56 #define BQ2515X_ADC_COMP3_L 0x57 #define BQ2515X_ADC_READ_EN 0x58 #define BQ2515X_TS_FASTCHGCTRL 0x61 #define BQ2515X_TS_COLD 0x62 #define BQ2515X_TS_COOL 0x63 #define BQ2515X_TS_WARM 0x64 #define BQ2515X_TS_HOT 0x65 #define BQ2515X_DEVICE_ID 0x6f #define BQ2515X_DEFAULT_ICHG_UA 10000 #define BQ25150_DEFAULT_ILIM_UA 100000 #define BQ25155_DEFAULT_ILIM_UA 500000 #define BQ2515X_DEFAULT_VBAT_REG_UV 4200000 #define BQ2515X_DEFAULT_IPRECHARGE_UA 2500 #define BQ2515X_DIVISOR 65536 #define BQ2515X_VBAT_BASE_VOLT 3600000 #define BQ2515X_VBAT_REG_MAX 4600000 #define BQ2515X_VBAT_REG_MIN 3600000 #define BQ2515X_VBAT_STEP_UV 10000 #define BQ2515X_UV_FACTOR 1000000 #define BQ2515X_VBAT_MULTIPLIER 6 #define BQ2515X_ICHG_DIVISOR 52429 #define BQ2515X_ICHG_CURR_STEP_THRESH_UA 318750 #define BQ2515X_ICHG_MIN_UA 0 #define BQ2515X_ICHG_MAX_UA 500000 #define BQ2515X_ICHG_RNG_1B0_UA 1250 #define BQ2515X_ICHG_RNG_1B1_UA 2500 #define BQ2515X_VLOWV_SEL_1B0_UV 3000000 #define BQ2515X_VLOWV_SEL_1B1_UV 2800000 #define BQ2515X_PRECHRG_ICHRG_RNGE_1875_UA 18750 #define BQ2515X_PRECHRG_ICHRG_RNGE_3750_UA 37500 #define BQ2515X_TWAKE2_MIN_US 1700000 #define BQ2515X_TWAKE2_MAX_US 2300000 #define BQ2515X_ILIM_150MA 0x2 #define BQ2515X_ILIM_MASK 0x7 #define BQ2515X_ILIM_MIN 50000 #define BQ2515X_ILIM_MAX 600000 #define BQ2515X_HEALTH_MASK 0xf #define BQ2515X_ICHGRNG_MASK 0x80 #define BQ2515X_STAT0_MASK 0x0f #define BQ2515X_STAT1_MASK 0x1f #define BQ2515X_PRECHARGE_MASK 0x1f #define BQ2515X_TS_HOT_STAT BIT(0) #define BQ2515X_TS_WARM_STAT BIT(1) #define BQ2515X_TS_COOL_STAT BIT(2) #define BQ2515X_TS_COLD_STAT BIT(3) #define BQ2515X_SAFETY_TIMER_EXP BIT(5) #define BQ2515X_EN_VBAT_READ BIT(3) #define BQ2515X_EN_ICHG_READ BIT(5) #define BQ2515X_VIN_GOOD BIT(0) #define BQ2515X_CHRG_DONE BIT(5) #define BQ2515X_CV_CHRG_MODE BIT(6) #define BQ2515X_VIN_OVP_FAULT_STAT BIT(7) #define BQ2515X_WATCHDOG_DISABLE BIT(4) #define BQ2515X_ICHARGE_RANGE BIT(7) #define BQ2515X_VLOWV_SEL BIT(5) #define BQ2515X_CHARGER_DISABLE BIT(0) #define BQ2515X_HWRESET_14S_WD BIT(1) static const int bq2515x_ilim_lvl_values[] = { 50000, 100000, 150000, 200000, 300000, 400000, 500000, 600000 }; /** * struct bq2515x_init_data - * @ilim: input current limit * @ichg: fast charge current * @vbatreg: battery regulation voltage * @iprechg: precharge current */ struct bq2515x_init_data { int ilim; int ichg; int vbatreg; int iprechg; }; enum bq2515x_id { BQ25150, BQ25155, }; /** * struct bq2515x_device - * @mains: mains properties * @battery: battery properties * @regmap: register map structure * @dev: device structure * * @reset_gpio: manual reset (MR) pin * @powerdown_gpio: low power mode pin * @ac_detect_gpio: power good (PG) pin * @ce_gpio: charge enable (CE) pin * * @model_name: string value describing device model * @device_id: value of device_id * @mains_online: boolean value indicating power supply online * * @init_data: charger initialization data structure */ struct bq2515x_device { struct power_supply *mains; struct power_supply *battery; struct regmap *regmap; struct device *dev; struct gpio_desc *reset_gpio; struct gpio_desc *powerdown_gpio; struct gpio_desc *ac_detect_gpio; struct gpio_desc *ce_gpio; char model_name[I2C_NAME_SIZE]; int device_id; bool mains_online; struct bq2515x_init_data init_data; }; static const struct reg_default bq25150_reg_defaults[] = { {BQ2515X_FLAG0, 0x0}, {BQ2515X_FLAG1, 0x0}, {BQ2515X_FLAG2, 0x0}, {BQ2515X_FLAG3, 0x0}, {BQ2515X_MASK0, 0x0}, {BQ2515X_MASK1, 0x0}, {BQ2515X_MASK2, 0x71}, {BQ2515X_MASK3, 0x0}, {BQ2515X_VBAT_CTRL, 0x3C}, {BQ2515X_ICHG_CTRL, 0x8}, {BQ2515X_PCHRGCTRL, 0x2}, {BQ2515X_TERMCTRL, 0x14}, {BQ2515X_BUVLO, 0x0}, {BQ2515X_CHARGERCTRL0, 0x82}, {BQ2515X_CHARGERCTRL1, 0x42}, {BQ2515X_ILIMCTRL, 0x1}, {BQ2515X_LDOCTRL, 0xB0}, {BQ2515X_MRCTRL, 0x2A}, {BQ2515X_ICCTRL0, 0x10}, {BQ2515X_ICCTRL1, 0x0}, {BQ2515X_ICCTRL2, 0x0}, {BQ2515X_ADCCTRL0, 0x2}, {BQ2515X_ADCCTRL1, 0x40}, {BQ2515X_ADC_COMP1_M, 0x23}, {BQ2515X_ADC_COMP1_L, 0x20}, {BQ2515X_ADC_COMP2_M, 0x38}, {BQ2515X_ADC_COMP2_L, 0x90}, {BQ2515X_ADC_COMP3_M, 0x0}, {BQ2515X_ADC_COMP3_L, 0x0}, {BQ2515X_ADC_READ_EN, 0x0}, {BQ2515X_TS_FASTCHGCTRL, 0x34}, {BQ2515X_TS_COLD, 0x7C}, {BQ2515X_TS_COOL, 0x6D}, {BQ2515X_TS_WARM, 0x38}, {BQ2515X_TS_HOT, 0x27}, {BQ2515X_DEVICE_ID, 0x20}, }; static const struct reg_default bq25155_reg_defaults[] = { {BQ2515X_FLAG0, 0x0}, {BQ2515X_FLAG1, 0x0}, {BQ2515X_FLAG2, 0x0}, {BQ2515X_FLAG3, 0x0}, {BQ2515X_MASK0, 0x0}, {BQ2515X_MASK1, 0x0}, {BQ2515X_MASK2, 0x71}, {BQ2515X_MASK3, 0x0}, {BQ2515X_VBAT_CTRL, 0x3C}, {BQ2515X_ICHG_CTRL, 0x8}, {BQ2515X_PCHRGCTRL, 0x2}, {BQ2515X_TERMCTRL, 0x14}, {BQ2515X_BUVLO, 0x0}, {BQ2515X_CHARGERCTRL0, 0x82}, {BQ2515X_CHARGERCTRL1, 0xC2}, {BQ2515X_ILIMCTRL, 0x6}, {BQ2515X_LDOCTRL, 0xB0}, {BQ2515X_MRCTRL, 0x2A}, {BQ2515X_ICCTRL0, 0x10}, {BQ2515X_ICCTRL1, 0x0}, {BQ2515X_ICCTRL2, 0x40}, {BQ2515X_ADCCTRL0, 0x2}, {BQ2515X_ADCCTRL1, 0x40}, {BQ2515X_ADC_COMP1_M, 0x23}, {BQ2515X_ADC_COMP1_L, 0x20}, {BQ2515X_ADC_COMP2_M, 0x38}, {BQ2515X_ADC_COMP2_L, 0x90}, {BQ2515X_ADC_COMP3_M, 0x0}, {BQ2515X_ADC_COMP3_L, 0x0}, {BQ2515X_ADC_READ_EN, 0x0}, {BQ2515X_TS_FASTCHGCTRL, 0x34}, {BQ2515X_TS_COLD, 0x7C}, {BQ2515X_TS_COOL, 0x6D}, {BQ2515X_TS_WARM, 0x38}, {BQ2515X_TS_HOT, 0x27}, {BQ2515X_DEVICE_ID, 0x35}, }; static int bq2515x_wake_up(struct bq2515x_device *bq2515x) { int ret; int val; /* Read the STAT register if we can read it then the device is out * of ship mode. If the register cannot be read then attempt to wake * it up and enable the ADC. */ ret = regmap_read(bq2515x->regmap, BQ2515X_STAT0, &val); if (ret) return ret; /* Need to toggle LP and bring device out of ship mode. The device * will exit the ship mode when the MR pin is held low for at least * t_WAKE2 as shown in section 8.3.7.1 of the datasheet. */ gpiod_set_value_cansleep(bq2515x->powerdown_gpio, 0); gpiod_set_value_cansleep(bq2515x->reset_gpio, 0); usleep_range(BQ2515X_TWAKE2_MIN_US, BQ2515X_TWAKE2_MAX_US); gpiod_set_value_cansleep(bq2515x->reset_gpio, 1); return regmap_write(bq2515x->regmap, BQ2515X_ADC_READ_EN, (BQ2515X_EN_VBAT_READ | BQ2515X_EN_ICHG_READ)); } static int bq2515x_update_ps_status(struct bq2515x_device *bq2515x) { bool dc = false; unsigned int val; int ret; if (bq2515x->ac_detect_gpio) val = gpiod_get_value_cansleep(bq2515x->ac_detect_gpio); else { ret = regmap_read(bq2515x->regmap, BQ2515X_STAT0, &val); if (ret) return ret; } dc = val & BQ2515X_VIN_GOOD; ret = bq2515x->mains_online != dc; bq2515x->mains_online = dc; return ret; } static int bq2515x_disable_watchdog_timers(struct bq2515x_device *bq2515x) { int ret; ret = regmap_update_bits(bq2515x->regmap, BQ2515X_CHARGERCTRL0, BQ2515X_WATCHDOG_DISABLE, BQ2515X_WATCHDOG_DISABLE); if (ret) return ret; return regmap_update_bits(bq2515x->regmap, BQ2515X_ICCTRL2, BQ2515X_HWRESET_14S_WD, 0); } static int bq2515x_get_battery_voltage_now(struct bq2515x_device *bq2515x) { int ret; int vbat_msb; int vbat_lsb; uint32_t vbat_measurement; if (!bq2515x->mains_online) bq2515x_wake_up(bq2515x); ret = regmap_read(bq2515x->regmap, BQ2515X_ADC_VBAT_M, &vbat_msb); if (ret) return ret; ret = regmap_read(bq2515x->regmap, BQ2515X_ADC_VBAT_L, &vbat_lsb); if (ret) return ret; vbat_measurement = (vbat_msb << 8) | vbat_lsb; return vbat_measurement * (BQ2515X_UV_FACTOR / BQ2515X_DIVISOR) * BQ2515X_VBAT_MULTIPLIER; } static int bq2515x_get_battery_current_now(struct bq2515x_device *bq2515x) { int ret; int ichg_msb; int ichg_lsb; uint32_t ichg_measurement; u16 ichg_multiplier = BQ2515X_ICHG_RNG_1B0_UA; unsigned int ichg_reg_code, reg_code; unsigned int icharge_range = 0, pchrgctrl; unsigned int buvlo, vlowv_sel, vlowv = BQ2515X_VLOWV_SEL_1B0_UV; if (!bq2515x->mains_online) return -ENODATA; ret = regmap_read(bq2515x->regmap, BQ2515X_ADC_ICHG_M, &ichg_msb); if (ret) return ret; ret = regmap_read(bq2515x->regmap, BQ2515X_ADC_ICHG_L, &ichg_lsb); if (ret) return ret; ichg_measurement = (ichg_msb << 8) | ichg_lsb; ret = regmap_read(bq2515x->regmap, BQ2515X_BUVLO, &buvlo); if (ret) return ret; vlowv_sel = buvlo & BQ2515X_VLOWV_SEL; if (vlowv_sel) vlowv = BQ2515X_VLOWV_SEL_1B1_UV; if (bq2515x_get_battery_voltage_now(bq2515x) < vlowv) { ret = regmap_read(bq2515x->regmap, BQ2515X_PCHRGCTRL, &pchrgctrl); if (ret) return ret; reg_code = pchrgctrl & BQ2515X_PRECHARGE_MASK; } else { ret = regmap_read(bq2515x->regmap, BQ2515X_ICHG_CTRL, &ichg_reg_code); if (ret) return ret; reg_code = ichg_reg_code; } ret = regmap_read(bq2515x->regmap, BQ2515X_PCHRGCTRL, &pchrgctrl); if (ret) return ret; icharge_range = pchrgctrl & BQ2515X_ICHARGE_RANGE; if (icharge_range) ichg_multiplier = BQ2515X_ICHG_RNG_1B1_UA; return reg_code * (ichg_multiplier * ichg_measurement / BQ2515X_ICHG_DIVISOR); } static bool bq2515x_get_charge_disable(struct bq2515x_device *bq2515x) { int ret; int ce_pin; int icctrl2; int charger_disable; ce_pin = gpiod_get_value_cansleep(bq2515x->ce_gpio); ret = regmap_read(bq2515x->regmap, BQ2515X_ICCTRL2, &icctrl2); if (ret) return ret; charger_disable = icctrl2 & BQ2515X_CHARGER_DISABLE; if (charger_disable || ce_pin) return true; return false; } static int bq2515x_set_charge_disable(struct bq2515x_device *bq2515x, int val) { gpiod_set_value_cansleep(bq2515x->ce_gpio, val); return regmap_update_bits(bq2515x->regmap, BQ2515X_ICCTRL2, BQ2515X_CHARGER_DISABLE, val); } static int bq2515x_get_const_charge_current(struct bq2515x_device *bq2515x) { int ret; u16 ichg_multiplier = BQ2515X_ICHG_RNG_1B0_UA; unsigned int ichg_reg_code; unsigned int pchrgctrl; unsigned int icharge_range; ret = regmap_read(bq2515x->regmap, BQ2515X_ICHG_CTRL, &ichg_reg_code); if (ret) return ret; ret = regmap_read(bq2515x->regmap, BQ2515X_PCHRGCTRL, &pchrgctrl); if (ret) return ret; icharge_range = pchrgctrl & BQ2515X_ICHARGE_RANGE; if (icharge_range) ichg_multiplier = BQ2515X_ICHG_RNG_1B1_UA; return ichg_reg_code * ichg_multiplier; } static int bq2515x_set_const_charge_current(struct bq2515x_device *bq2515x, int val) { int ret; unsigned int ichg_reg_code; u16 ichg_multiplier = BQ2515X_ICHG_RNG_1B0_UA; unsigned int icharge_range = 0; if (val > BQ2515X_ICHG_MAX_UA || val < BQ2515X_ICHG_MIN_UA) return -EINVAL; if (val > BQ2515X_ICHG_CURR_STEP_THRESH_UA) { ichg_multiplier = BQ2515X_ICHG_RNG_1B1_UA; icharge_range = BQ2515X_ICHARGE_RANGE; } bq2515x_set_charge_disable(bq2515x, 1); ret = regmap_update_bits(bq2515x->regmap, BQ2515X_PCHRGCTRL, BQ2515X_ICHARGE_RANGE, icharge_range); if (ret) return ret; ichg_reg_code = val / ichg_multiplier; ret = regmap_write(bq2515x->regmap, BQ2515X_ICHG_CTRL, ichg_reg_code); if (ret) return ret; return bq2515x_set_charge_disable(bq2515x, 0); } static int bq2515x_get_precharge_current(struct bq2515x_device *bq2515x) { int ret; unsigned int pchrgctrl; unsigned int icharge_range; u16 precharge_multiplier = BQ2515X_ICHG_RNG_1B0_UA; unsigned int precharge_reg_code; ret = regmap_read(bq2515x->regmap, BQ2515X_PCHRGCTRL, &pchrgctrl); if (ret) return ret; icharge_range = pchrgctrl & BQ2515X_ICHARGE_RANGE; if (icharge_range) precharge_multiplier = BQ2515X_ICHG_RNG_1B1_UA; precharge_reg_code = pchrgctrl & BQ2515X_PRECHARGE_MASK; return precharge_reg_code * precharge_multiplier; } static int bq2515x_set_precharge_current(struct bq2515x_device *bq2515x, int val) { int ret; unsigned int pchrgctrl; unsigned int icharge_range; unsigned int precharge_reg_code; unsigned int precharge_multiplier = BQ2515X_ICHG_RNG_1B0_UA; unsigned int precharge_max_ua = BQ2515X_PRECHRG_ICHRG_RNGE_1875_UA; ret = regmap_read(bq2515x->regmap, BQ2515X_PCHRGCTRL, &pchrgctrl); if (ret) return ret; icharge_range = pchrgctrl & BQ2515X_ICHARGE_RANGE; if (icharge_range) { precharge_max_ua = BQ2515X_PRECHRG_ICHRG_RNGE_3750_UA; precharge_multiplier = BQ2515X_ICHG_RNG_1B1_UA; } else { precharge_max_ua = BQ2515X_PRECHRG_ICHRG_RNGE_1875_UA; precharge_multiplier = BQ2515X_ICHG_RNG_1B0_UA; } if (val > precharge_max_ua || val < BQ2515X_ICHG_MIN_UA) return -EINVAL; precharge_reg_code = val / precharge_multiplier; ret = bq2515x_set_charge_disable(bq2515x, 1); if (ret) return ret; ret = regmap_update_bits(bq2515x->regmap, BQ2515X_PCHRGCTRL, BQ2515X_PRECHARGE_MASK, precharge_reg_code); if (ret) return ret; return bq2515x_set_charge_disable(bq2515x, 0); } static int bq2515x_charging_status(struct bq2515x_device *bq2515x, union power_supply_propval *val) { bool status0_no_fault; bool status1_no_fault; bool ce_status; bool charge_done; unsigned int status; int ret; if (!bq2515x->mains_online) { val->intval = POWER_SUPPLY_STATUS_DISCHARGING; return 0; } ret = regmap_read(bq2515x->regmap, BQ2515X_STAT0, &status); if (ret) return ret; /* * The code block below is used to determine if any faults from the * STAT0 register are disbaling charging or if the charge has completed * according to the CHARGE_DONE_STAT bit. */ if (((status & BQ2515X_STAT0_MASK) == true) & ((status & BQ2515X_CHRG_DONE) == false)) { status0_no_fault = true; charge_done = false; } else if (status & BQ2515X_CHRG_DONE) { charge_done = true; status0_no_fault = false; } else { status0_no_fault = false; charge_done = false; } ret = regmap_read(bq2515x->regmap, BQ2515X_STAT1, &status); if (ret) return ret; /* * The code block below is used to determine if any faults from the * STAT1 register are disbaling charging */ if ((status & BQ2515X_STAT1_MASK) == false) status1_no_fault = true; else status1_no_fault = false; ce_status = (!bq2515x_get_charge_disable(bq2515x)); /* * If there are no faults and charging is enabled, then status is * charging. Otherwise, if charging is complete, then status is full. * Otherwise, if a fault exists or charging is disabled, then status is * not charging */ if (status0_no_fault & status1_no_fault & ce_status) val->intval = POWER_SUPPLY_STATUS_CHARGING; else if (charge_done) val->intval = POWER_SUPPLY_STATUS_FULL; else if (!(status0_no_fault & status1_no_fault & ce_status)) val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING; return 0; } static int bq2515x_get_batt_reg(struct bq2515x_device *bq2515x) { int vbat_reg_code; int ret; ret = regmap_read(bq2515x->regmap, BQ2515X_VBAT_CTRL, &vbat_reg_code); if (ret) return ret; return BQ2515X_VBAT_BASE_VOLT + vbat_reg_code * BQ2515X_VBAT_STEP_UV; } static int bq2515x_set_batt_reg(struct bq2515x_device *bq2515x, int val) { int vbat_reg_code; if (val > BQ2515X_VBAT_REG_MAX || val < BQ2515X_VBAT_REG_MIN) return -EINVAL; vbat_reg_code = (val - BQ2515X_VBAT_BASE_VOLT) / BQ2515X_VBAT_STEP_UV; return regmap_write(bq2515x->regmap, BQ2515X_VBAT_CTRL, vbat_reg_code); } static int bq2515x_get_ilim_lvl(struct bq2515x_device *bq2515x) { int ret; int ilimctrl; ret = regmap_read(bq2515x->regmap, BQ2515X_ILIMCTRL, &ilimctrl); if (ret) return ret; return bq2515x_ilim_lvl_values[ilimctrl & BQ2515X_ILIM_MASK]; } static int bq2515x_set_ilim_lvl(struct bq2515x_device *bq2515x, int val) { int i = 0; unsigned int array_size = ARRAY_SIZE(bq2515x_ilim_lvl_values); for (i = array_size - 1; i > 0; i--) { if (val >= bq2515x_ilim_lvl_values[i]) break; } return regmap_write(bq2515x->regmap, BQ2515X_ILIMCTRL, i); } static int bq2515x_power_supply_property_is_writeable(struct power_supply *psy, enum power_supply_property prop) { switch (prop) { case POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT: case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE: case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT: case POWER_SUPPLY_PROP_PRECHARGE_CURRENT: return true; default: return false; } } static int bq2515x_charger_get_health(struct bq2515x_device *bq2515x, union power_supply_propval *val) { int health = POWER_SUPPLY_HEALTH_GOOD; int ret; unsigned int stat1; unsigned int flag3; if (!bq2515x->mains_online) bq2515x_wake_up(bq2515x); ret = regmap_read(bq2515x->regmap, BQ2515X_FLAG3, &flag3); if (ret) return ret; ret = regmap_read(bq2515x->regmap, BQ2515X_STAT1, &stat1); if (ret) return ret; if (stat1 & BQ2515X_HEALTH_MASK) { switch (stat1 & BQ2515X_HEALTH_MASK) { case BQ2515X_TS_HOT_STAT: health = POWER_SUPPLY_HEALTH_HOT; break; case BQ2515X_TS_WARM_STAT: health = POWER_SUPPLY_HEALTH_WARM; break; case BQ2515X_TS_COOL_STAT: health = POWER_SUPPLY_HEALTH_COOL; break; case BQ2515X_TS_COLD_STAT: health = POWER_SUPPLY_HEALTH_COLD; break; default: health = POWER_SUPPLY_HEALTH_UNKNOWN; break; } } if (stat1 & BQ2515X_VIN_OVP_FAULT_STAT) health = POWER_SUPPLY_HEALTH_OVERVOLTAGE; if (flag3 & BQ2515X_SAFETY_TIMER_EXP) health = POWER_SUPPLY_HEALTH_SAFETY_TIMER_EXPIRE; val->intval = health; return 0; } static int bq2515x_mains_set_property(struct power_supply *psy, enum power_supply_property prop, const union power_supply_propval *val) { struct bq2515x_device *bq2515x = power_supply_get_drvdata(psy); int ret; switch (prop) { case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE: ret = bq2515x_set_batt_reg(bq2515x, val->intval); break; case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT: ret = bq2515x_set_const_charge_current(bq2515x, val->intval); break; case POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT: ret = bq2515x_set_ilim_lvl(bq2515x, val->intval); break; case POWER_SUPPLY_PROP_PRECHARGE_CURRENT: ret = bq2515x_set_precharge_current(bq2515x, val->intval); break; default: return -EINVAL; } return ret; } static int bq2515x_mains_get_property(struct power_supply *psy, enum power_supply_property prop, union power_supply_propval *val) { struct bq2515x_device *bq2515x = power_supply_get_drvdata(psy); int ret = 0; switch (prop) { case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT: ret = bq2515x_get_const_charge_current(bq2515x); if (ret < 0) return ret; val->intval = ret; break; case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE: ret = bq2515x_get_batt_reg(bq2515x); if (ret < 0) return ret; val->intval = ret; break; case POWER_SUPPLY_PROP_PRECHARGE_CURRENT: ret = bq2515x_get_precharge_current(bq2515x); if (ret < 0) return ret; val->intval = ret; break; case POWER_SUPPLY_PROP_ONLINE: val->intval = bq2515x->mains_online; break; case POWER_SUPPLY_PROP_HEALTH: ret = bq2515x_charger_get_health(bq2515x, val); if (ret) val->intval = POWER_SUPPLY_HEALTH_UNKNOWN; break; case POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT: ret = bq2515x_get_ilim_lvl(bq2515x); if (ret < 0) return ret; val->intval = ret; break; case POWER_SUPPLY_PROP_MODEL_NAME: val->strval = bq2515x->model_name; break; case POWER_SUPPLY_PROP_MANUFACTURER: val->strval = BQ2515X_MANUFACTURER; break; case POWER_SUPPLY_PROP_STATUS: ret = bq2515x_charging_status(bq2515x, val); if (ret) return ret; break; default: return -EINVAL; } return ret; } static int bq2515x_battery_get_property(struct power_supply *psy, enum power_supply_property prop, union power_supply_propval *val) { struct bq2515x_device *bq2515x = power_supply_get_drvdata(psy); int ret; ret = bq2515x_update_ps_status(bq2515x); if (ret) return ret; switch (prop) { case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE_MAX: ret = bq2515x->init_data.vbatreg; if (ret < 0) return ret; val->intval = ret; break; case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX: ret = bq2515x->init_data.ichg; if (ret < 0) return ret; val->intval = ret; break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: ret = bq2515x_get_battery_voltage_now(bq2515x); if (ret < 0) return ret; val->intval = ret; break; case POWER_SUPPLY_PROP_CURRENT_NOW: ret = bq2515x_get_battery_current_now(bq2515x); if (ret < 0) return ret; val->intval = ret; break; default: return -EINVAL; } return 0; } static const enum power_supply_property bq2515x_battery_properties[] = { POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_CURRENT_NOW, POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX, POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE_MAX, }; static const enum power_supply_property bq2515x_mains_properties[] = { POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_HEALTH, POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT, POWER_SUPPLY_PROP_MODEL_NAME, POWER_SUPPLY_PROP_MANUFACTURER, POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE, POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT, POWER_SUPPLY_PROP_PRECHARGE_CURRENT, }; static const struct power_supply_desc bq2515x_mains_desc = { .name = "bq2515x-mains", .type = POWER_SUPPLY_TYPE_MAINS, .get_property = bq2515x_mains_get_property, .set_property = bq2515x_mains_set_property, .properties = bq2515x_mains_properties, .num_properties = ARRAY_SIZE(bq2515x_mains_properties), .property_is_writeable = bq2515x_power_supply_property_is_writeable, }; static const struct power_supply_desc bq2515x_battery_desc = { .name = "bq2515x-battery", .type = POWER_SUPPLY_TYPE_BATTERY, .get_property = bq2515x_battery_get_property, .properties = bq2515x_battery_properties, .num_properties = ARRAY_SIZE(bq2515x_battery_properties), .property_is_writeable = bq2515x_power_supply_property_is_writeable, }; static int bq2515x_power_supply_register(struct bq2515x_device *bq2515x, struct device *dev, struct power_supply_config psy_cfg) { bq2515x->mains = devm_power_supply_register(bq2515x->dev, &bq2515x_mains_desc, &psy_cfg); if (IS_ERR(bq2515x->mains)) return -EINVAL; bq2515x->battery = devm_power_supply_register(bq2515x->dev, &bq2515x_battery_desc, &psy_cfg); if (IS_ERR(bq2515x->battery)) return -EINVAL; return 0; } static int bq2515x_hw_init(struct bq2515x_device *bq2515x) { int ret; struct power_supply_battery_info *bat_info; ret = bq2515x_disable_watchdog_timers(bq2515x); if (ret) return ret; if (bq2515x->init_data.ilim) { ret = bq2515x_set_ilim_lvl(bq2515x, bq2515x->init_data.ilim); if (ret) return ret; } ret = power_supply_get_battery_info(bq2515x->mains, &bat_info); if (ret) { dev_warn(bq2515x->dev, "battery info missing, default values will be applied\n"); bq2515x->init_data.ichg = BQ2515X_DEFAULT_ICHG_UA; bq2515x->init_data.vbatreg = BQ2515X_DEFAULT_VBAT_REG_UV; bq2515x->init_data.iprechg = BQ2515X_DEFAULT_IPRECHARGE_UA; } else { bq2515x->init_data.ichg = bat_info->constant_charge_current_max_ua; bq2515x->init_data.vbatreg = bat_info->constant_charge_voltage_max_uv; bq2515x->init_data.iprechg = bat_info->precharge_current_ua; } ret = bq2515x_set_const_charge_current(bq2515x, bq2515x->init_data.ichg); if (ret) return ret; ret = bq2515x_set_batt_reg(bq2515x, bq2515x->init_data.vbatreg); if (ret) return ret; return bq2515x_set_precharge_current(bq2515x, bq2515x->init_data.iprechg); } static int bq2515x_read_properties(struct bq2515x_device *bq2515x) { int ret; ret = device_property_read_u32(bq2515x->dev, "input-current-limit-microamp", &bq2515x->init_data.ilim); if (ret) { switch (bq2515x->device_id) { case BQ25150: bq2515x->init_data.ilim = BQ25150_DEFAULT_ILIM_UA; break; case BQ25155: bq2515x->init_data.ilim = BQ25155_DEFAULT_ILIM_UA; break; } } bq2515x->ac_detect_gpio = devm_gpiod_get_optional(bq2515x->dev, "ac-detect", GPIOD_IN); if (IS_ERR(bq2515x->ac_detect_gpio)) { ret = PTR_ERR(bq2515x->ac_detect_gpio); dev_err(bq2515x->dev, "Failed to get ac detect"); return ret; } bq2515x->reset_gpio = devm_gpiod_get_optional(bq2515x->dev, "reset", GPIOD_OUT_LOW); if (IS_ERR(bq2515x->reset_gpio)) { ret = PTR_ERR(bq2515x->reset_gpio); dev_err(bq2515x->dev, "Failed to get reset"); return ret; } bq2515x->powerdown_gpio = devm_gpiod_get_optional(bq2515x->dev, "powerdown", GPIOD_OUT_LOW); if (IS_ERR(bq2515x->powerdown_gpio)) { ret = PTR_ERR(bq2515x->powerdown_gpio); dev_err(bq2515x->dev, "Failed to get powerdown"); return ret; } bq2515x->ce_gpio = devm_gpiod_get_optional(bq2515x->dev, "charge-enable", GPIOD_OUT_LOW); if (IS_ERR(bq2515x->ce_gpio)) { ret = PTR_ERR(bq2515x->ce_gpio); dev_err(bq2515x->dev, "Failed to get ce"); return ret; } return 0; } static bool bq2515x_volatile_register(struct device *dev, unsigned int reg) { switch (reg) { case BQ2515X_STAT0 ... BQ2515X_FLAG3: case BQ2515X_ADC_VBAT_M ... BQ2515X_ADC_IIN_L: return true; default: return false; } } static const struct regmap_config bq25150_regmap_config = { .reg_bits = 8, .val_bits = 8, .max_register = BQ2515X_DEVICE_ID, .reg_defaults = bq25150_reg_defaults, .num_reg_defaults = ARRAY_SIZE(bq25150_reg_defaults), .cache_type = REGCACHE_RBTREE, .volatile_reg = bq2515x_volatile_register, }; static const struct regmap_config bq25155_regmap_config = { .reg_bits = 8, .val_bits = 8, .max_register = BQ2515X_DEVICE_ID, .reg_defaults = bq25155_reg_defaults, .num_reg_defaults = ARRAY_SIZE(bq25155_reg_defaults), .cache_type = REGCACHE_RBTREE, .volatile_reg = bq2515x_volatile_register, }; static int bq2515x_probe(struct i2c_client *client) { const struct i2c_device_id *id = i2c_client_get_device_id(client); struct device *dev = &client->dev; struct bq2515x_device *bq2515x; struct power_supply_config charger_cfg = {}; int ret; bq2515x = devm_kzalloc(dev, sizeof(*bq2515x), GFP_KERNEL); if (!bq2515x) return -ENOMEM; bq2515x->dev = dev; strncpy(bq2515x->model_name, id->name, I2C_NAME_SIZE); bq2515x->device_id = id->driver_data; switch (bq2515x->device_id) { case BQ25150: bq2515x->regmap = devm_regmap_init_i2c(client, &bq25150_regmap_config); break; case BQ25155: bq2515x->regmap = devm_regmap_init_i2c(client, &bq25155_regmap_config); break; } if (IS_ERR(bq2515x->regmap)) { dev_err(dev, "failed to allocate register map\n"); return PTR_ERR(bq2515x->regmap); } i2c_set_clientdata(client, bq2515x); charger_cfg.drv_data = bq2515x; charger_cfg.of_node = dev->of_node; ret = bq2515x_read_properties(bq2515x); if (ret) { dev_err(dev, "Failed to read device tree properties %d\n", ret); return ret; } ret = bq2515x_power_supply_register(bq2515x, dev, charger_cfg); if (ret) { dev_err(dev, "failed to register power supply\n"); return ret; } ret = bq2515x_hw_init(bq2515x); if (ret) { dev_err(dev, "Cannot initialize the chip\n"); return ret; } return 0; } static const struct i2c_device_id bq2515x_i2c_ids[] = { { "bq25150", BQ25150, }, { "bq25155", BQ25155, }, {}, }; MODULE_DEVICE_TABLE(i2c, bq2515x_i2c_ids); static const struct of_device_id bq2515x_of_match[] = { { .compatible = "ti,bq25150", }, { .compatible = "ti,bq25155", }, { }, }; MODULE_DEVICE_TABLE(of, bq2515x_of_match); static struct i2c_driver bq2515x_driver = { .driver = { .name = "bq2515x-charger", .of_match_table = bq2515x_of_match, }, .probe = bq2515x_probe, .id_table = bq2515x_i2c_ids, }; module_i2c_driver(bq2515x_driver); MODULE_AUTHOR("Dan Murphy <[email protected]>"); MODULE_AUTHOR("Ricardo Rivera-Matos <[email protected]>"); MODULE_DESCRIPTION("BQ2515X charger driver"); MODULE_LICENSE("GPL v2");
linux-master
drivers/power/supply/bq2515x_charger.c
// SPDX-License-Identifier: GPL-2.0+ /* * Driver for Analog Devices (Linear Technology) LT3651 charger IC. * Copyright (C) 2017, Topic Embedded Products */ #include <linux/device.h> #include <linux/gpio/consumer.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/slab.h> #include <linux/of.h> struct lt3651_charger { struct power_supply *charger; struct power_supply_desc charger_desc; struct gpio_desc *acpr_gpio; struct gpio_desc *fault_gpio; struct gpio_desc *chrg_gpio; }; static irqreturn_t lt3651_charger_irq(int irq, void *devid) { struct power_supply *charger = devid; power_supply_changed(charger); return IRQ_HANDLED; } static inline struct lt3651_charger *psy_to_lt3651_charger( struct power_supply *psy) { return power_supply_get_drvdata(psy); } static int lt3651_charger_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct lt3651_charger *lt3651_charger = psy_to_lt3651_charger(psy); switch (psp) { case POWER_SUPPLY_PROP_STATUS: if (!lt3651_charger->chrg_gpio) { val->intval = POWER_SUPPLY_STATUS_UNKNOWN; break; } if (gpiod_get_value(lt3651_charger->chrg_gpio)) val->intval = POWER_SUPPLY_STATUS_CHARGING; else val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING; break; case POWER_SUPPLY_PROP_ONLINE: val->intval = gpiod_get_value(lt3651_charger->acpr_gpio); break; case POWER_SUPPLY_PROP_HEALTH: if (!lt3651_charger->fault_gpio) { val->intval = POWER_SUPPLY_HEALTH_UNKNOWN; break; } if (!gpiod_get_value(lt3651_charger->fault_gpio)) { val->intval = POWER_SUPPLY_HEALTH_GOOD; break; } /* * If the fault pin is active, the chrg pin explains the type * of failure. */ if (!lt3651_charger->chrg_gpio) { val->intval = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE; break; } val->intval = gpiod_get_value(lt3651_charger->chrg_gpio) ? POWER_SUPPLY_HEALTH_OVERHEAT : POWER_SUPPLY_HEALTH_DEAD; break; default: return -EINVAL; } return 0; } static enum power_supply_property lt3651_charger_properties[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_HEALTH, }; static int lt3651_charger_probe(struct platform_device *pdev) { struct power_supply_config psy_cfg = {}; struct lt3651_charger *lt3651_charger; struct power_supply_desc *charger_desc; int ret; lt3651_charger = devm_kzalloc(&pdev->dev, sizeof(*lt3651_charger), GFP_KERNEL); if (!lt3651_charger) return -ENOMEM; lt3651_charger->acpr_gpio = devm_gpiod_get(&pdev->dev, "lltc,acpr", GPIOD_IN); if (IS_ERR(lt3651_charger->acpr_gpio)) { ret = PTR_ERR(lt3651_charger->acpr_gpio); dev_err(&pdev->dev, "Failed to acquire acpr GPIO: %d\n", ret); return ret; } lt3651_charger->fault_gpio = devm_gpiod_get_optional(&pdev->dev, "lltc,fault", GPIOD_IN); if (IS_ERR(lt3651_charger->fault_gpio)) { ret = PTR_ERR(lt3651_charger->fault_gpio); dev_err(&pdev->dev, "Failed to acquire fault GPIO: %d\n", ret); return ret; } lt3651_charger->chrg_gpio = devm_gpiod_get_optional(&pdev->dev, "lltc,chrg", GPIOD_IN); if (IS_ERR(lt3651_charger->chrg_gpio)) { ret = PTR_ERR(lt3651_charger->chrg_gpio); dev_err(&pdev->dev, "Failed to acquire chrg GPIO: %d\n", ret); return ret; } charger_desc = &lt3651_charger->charger_desc; charger_desc->name = pdev->dev.of_node->name; charger_desc->type = POWER_SUPPLY_TYPE_MAINS; charger_desc->properties = lt3651_charger_properties; charger_desc->num_properties = ARRAY_SIZE(lt3651_charger_properties); charger_desc->get_property = lt3651_charger_get_property; psy_cfg.of_node = pdev->dev.of_node; psy_cfg.drv_data = lt3651_charger; lt3651_charger->charger = devm_power_supply_register(&pdev->dev, charger_desc, &psy_cfg); if (IS_ERR(lt3651_charger->charger)) { ret = PTR_ERR(lt3651_charger->charger); dev_err(&pdev->dev, "Failed to register power supply: %d\n", ret); return ret; } /* * Acquire IRQs for the GPIO pins if possible. If the system does not * support IRQs on these pins, userspace will have to poll the sysfs * files manually. */ if (lt3651_charger->acpr_gpio) { ret = gpiod_to_irq(lt3651_charger->acpr_gpio); if (ret >= 0) ret = devm_request_any_context_irq(&pdev->dev, ret, lt3651_charger_irq, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, dev_name(&pdev->dev), lt3651_charger->charger); if (ret < 0) dev_warn(&pdev->dev, "Failed to request acpr irq\n"); } if (lt3651_charger->fault_gpio) { ret = gpiod_to_irq(lt3651_charger->fault_gpio); if (ret >= 0) ret = devm_request_any_context_irq(&pdev->dev, ret, lt3651_charger_irq, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, dev_name(&pdev->dev), lt3651_charger->charger); if (ret < 0) dev_warn(&pdev->dev, "Failed to request fault irq\n"); } if (lt3651_charger->chrg_gpio) { ret = gpiod_to_irq(lt3651_charger->chrg_gpio); if (ret >= 0) ret = devm_request_any_context_irq(&pdev->dev, ret, lt3651_charger_irq, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, dev_name(&pdev->dev), lt3651_charger->charger); if (ret < 0) dev_warn(&pdev->dev, "Failed to request chrg irq\n"); } platform_set_drvdata(pdev, lt3651_charger); return 0; } static const struct of_device_id lt3651_charger_match[] = { { .compatible = "lltc,ltc3651-charger" }, /* DEPRECATED */ { .compatible = "lltc,lt3651-charger" }, { } }; MODULE_DEVICE_TABLE(of, lt3651_charger_match); static struct platform_driver lt3651_charger_driver = { .probe = lt3651_charger_probe, .driver = { .name = "lt3651-charger", .of_match_table = lt3651_charger_match, }, }; module_platform_driver(lt3651_charger_driver); MODULE_AUTHOR("Mike Looijmans <[email protected]>"); MODULE_DESCRIPTION("Driver for LT3651 charger"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:lt3651-charger");
linux-master
drivers/power/supply/lt3651-charger.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * AXP20x PMIC USB power supply status driver * * Copyright (C) 2015 Hans de Goede <[email protected]> * Copyright (C) 2014 Bruno Prémont <[email protected]> */ #include <linux/bitops.h> #include <linux/device.h> #include <linux/devm-helpers.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/kernel.h> #include <linux/mfd/axp20x.h> #include <linux/module.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/pm.h> #include <linux/power_supply.h> #include <linux/regmap.h> #include <linux/slab.h> #include <linux/iio/consumer.h> #include <linux/workqueue.h> #define DRVNAME "axp20x-usb-power-supply" #define AXP192_USB_OTG_STATUS 0x04 #define AXP20X_PWR_STATUS_VBUS_PRESENT BIT(5) #define AXP20X_PWR_STATUS_VBUS_USED BIT(4) #define AXP20X_USB_STATUS_VBUS_VALID BIT(2) #define AXP20X_VBUS_VHOLD_uV(b) (4000000 + (((b) >> 3) & 7) * 100000) #define AXP20X_VBUS_VHOLD_MASK GENMASK(5, 3) #define AXP20X_VBUS_VHOLD_OFFSET 3 #define AXP20X_ADC_EN1_VBUS_CURR BIT(2) #define AXP20X_ADC_EN1_VBUS_VOLT BIT(3) /* * Note do not raise the debounce time, we must report Vusb high within * 100ms otherwise we get Vbus errors in musb. */ #define DEBOUNCE_TIME msecs_to_jiffies(50) struct axp_data { const struct power_supply_desc *power_desc; const char * const *irq_names; unsigned int num_irq_names; const int *curr_lim_table; struct reg_field curr_lim_fld; struct reg_field vbus_valid_bit; struct reg_field vbus_mon_bit; struct reg_field usb_bc_en_bit; struct reg_field vbus_disable_bit; bool vbus_needs_polling: 1; }; struct axp20x_usb_power { struct regmap *regmap; struct regmap_field *curr_lim_fld; struct regmap_field *vbus_valid_bit; struct regmap_field *vbus_mon_bit; struct regmap_field *usb_bc_en_bit; struct regmap_field *vbus_disable_bit; struct power_supply *supply; const struct axp_data *axp_data; struct iio_channel *vbus_v; struct iio_channel *vbus_i; struct delayed_work vbus_detect; unsigned int old_status; unsigned int online; unsigned int num_irqs; unsigned int irqs[]; }; static bool axp20x_usb_vbus_needs_polling(struct axp20x_usb_power *power) { /* * Polling is only necessary while VBUS is offline. While online, a * present->absent transition implies an online->offline transition * and will trigger the VBUS_REMOVAL IRQ. */ if (power->axp_data->vbus_needs_polling && !power->online) return true; return false; } static irqreturn_t axp20x_usb_power_irq(int irq, void *devid) { struct axp20x_usb_power *power = devid; power_supply_changed(power->supply); mod_delayed_work(system_power_efficient_wq, &power->vbus_detect, DEBOUNCE_TIME); return IRQ_HANDLED; } static void axp20x_usb_power_poll_vbus(struct work_struct *work) { struct axp20x_usb_power *power = container_of(work, struct axp20x_usb_power, vbus_detect.work); unsigned int val; int ret; ret = regmap_read(power->regmap, AXP20X_PWR_INPUT_STATUS, &val); if (ret) goto out; val &= (AXP20X_PWR_STATUS_VBUS_PRESENT | AXP20X_PWR_STATUS_VBUS_USED); if (val != power->old_status) power_supply_changed(power->supply); power->old_status = val; power->online = val & AXP20X_PWR_STATUS_VBUS_USED; out: if (axp20x_usb_vbus_needs_polling(power)) mod_delayed_work(system_power_efficient_wq, &power->vbus_detect, DEBOUNCE_TIME); } static int axp20x_usb_power_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct axp20x_usb_power *power = power_supply_get_drvdata(psy); unsigned int input, v; int ret; switch (psp) { case POWER_SUPPLY_PROP_VOLTAGE_MIN: ret = regmap_read(power->regmap, AXP20X_VBUS_IPSOUT_MGMT, &v); if (ret) return ret; val->intval = AXP20X_VBUS_VHOLD_uV(v); return 0; case POWER_SUPPLY_PROP_VOLTAGE_NOW: if (IS_ENABLED(CONFIG_AXP20X_ADC)) { ret = iio_read_channel_processed(power->vbus_v, &val->intval); if (ret) return ret; /* * IIO framework gives mV but Power Supply framework * gives uV. */ val->intval *= 1000; return 0; } ret = axp20x_read_variable_width(power->regmap, AXP20X_VBUS_V_ADC_H, 12); if (ret < 0) return ret; val->intval = ret * 1700; /* 1 step = 1.7 mV */ return 0; case POWER_SUPPLY_PROP_CURRENT_MAX: ret = regmap_field_read(power->curr_lim_fld, &v); if (ret) return ret; val->intval = power->axp_data->curr_lim_table[v]; return 0; case POWER_SUPPLY_PROP_CURRENT_NOW: if (IS_ENABLED(CONFIG_AXP20X_ADC)) { ret = iio_read_channel_processed(power->vbus_i, &val->intval); if (ret) return ret; /* * IIO framework gives mA but Power Supply framework * gives uA. */ val->intval *= 1000; return 0; } ret = axp20x_read_variable_width(power->regmap, AXP20X_VBUS_I_ADC_H, 12); if (ret < 0) return ret; val->intval = ret * 375; /* 1 step = 0.375 mA */ return 0; default: break; } /* All the properties below need the input-status reg value */ ret = regmap_read(power->regmap, AXP20X_PWR_INPUT_STATUS, &input); if (ret) return ret; switch (psp) { case POWER_SUPPLY_PROP_HEALTH: if (!(input & AXP20X_PWR_STATUS_VBUS_PRESENT)) { val->intval = POWER_SUPPLY_HEALTH_UNKNOWN; break; } val->intval = POWER_SUPPLY_HEALTH_GOOD; if (power->vbus_valid_bit) { ret = regmap_field_read(power->vbus_valid_bit, &v); if (ret) return ret; if (v == 0) val->intval = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE; } break; case POWER_SUPPLY_PROP_PRESENT: val->intval = !!(input & AXP20X_PWR_STATUS_VBUS_PRESENT); break; case POWER_SUPPLY_PROP_ONLINE: val->intval = !!(input & AXP20X_PWR_STATUS_VBUS_USED); break; default: return -EINVAL; } return 0; } static int axp20x_usb_power_set_voltage_min(struct axp20x_usb_power *power, int intval) { int val; switch (intval) { case 4000000: case 4100000: case 4200000: case 4300000: case 4400000: case 4500000: case 4600000: case 4700000: val = (intval - 4000000) / 100000; return regmap_update_bits(power->regmap, AXP20X_VBUS_IPSOUT_MGMT, AXP20X_VBUS_VHOLD_MASK, val << AXP20X_VBUS_VHOLD_OFFSET); default: return -EINVAL; } return -EINVAL; } static int axp20x_usb_power_set_current_max(struct axp20x_usb_power *power, int intval) { const unsigned int max = GENMASK(power->axp_data->curr_lim_fld.msb, power->axp_data->curr_lim_fld.lsb); if (intval == -1) return -EINVAL; for (unsigned int i = 0; i <= max; ++i) if (power->axp_data->curr_lim_table[i] == intval) return regmap_field_write(power->curr_lim_fld, i); return -EINVAL; } static int axp20x_usb_power_set_property(struct power_supply *psy, enum power_supply_property psp, const union power_supply_propval *val) { struct axp20x_usb_power *power = power_supply_get_drvdata(psy); switch (psp) { case POWER_SUPPLY_PROP_ONLINE: if (!power->vbus_disable_bit) return -EINVAL; return regmap_field_write(power->vbus_disable_bit, !val->intval); case POWER_SUPPLY_PROP_VOLTAGE_MIN: return axp20x_usb_power_set_voltage_min(power, val->intval); case POWER_SUPPLY_PROP_CURRENT_MAX: return axp20x_usb_power_set_current_max(power, val->intval); default: return -EINVAL; } return -EINVAL; } static int axp20x_usb_power_prop_writeable(struct power_supply *psy, enum power_supply_property psp) { struct axp20x_usb_power *power = power_supply_get_drvdata(psy); /* * The VBUS path select flag works differently on AXP288 and newer: * - On AXP20x and AXP22x, the flag enables VBUS (ignoring N_VBUSEN). * - On AXP288 and AXP8xx, the flag disables VBUS (ignoring N_VBUSEN). * We only expose the control on variants where it can be used to force * the VBUS input offline. */ if (psp == POWER_SUPPLY_PROP_ONLINE) return power->vbus_disable_bit != NULL; return psp == POWER_SUPPLY_PROP_VOLTAGE_MIN || psp == POWER_SUPPLY_PROP_CURRENT_MAX; } static enum power_supply_property axp20x_usb_power_properties[] = { POWER_SUPPLY_PROP_HEALTH, POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_VOLTAGE_MIN, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_CURRENT_MAX, POWER_SUPPLY_PROP_CURRENT_NOW, }; static enum power_supply_property axp22x_usb_power_properties[] = { POWER_SUPPLY_PROP_HEALTH, POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_VOLTAGE_MIN, POWER_SUPPLY_PROP_CURRENT_MAX, }; static const struct power_supply_desc axp20x_usb_power_desc = { .name = "axp20x-usb", .type = POWER_SUPPLY_TYPE_USB, .properties = axp20x_usb_power_properties, .num_properties = ARRAY_SIZE(axp20x_usb_power_properties), .property_is_writeable = axp20x_usb_power_prop_writeable, .get_property = axp20x_usb_power_get_property, .set_property = axp20x_usb_power_set_property, }; static const struct power_supply_desc axp22x_usb_power_desc = { .name = "axp20x-usb", .type = POWER_SUPPLY_TYPE_USB, .properties = axp22x_usb_power_properties, .num_properties = ARRAY_SIZE(axp22x_usb_power_properties), .property_is_writeable = axp20x_usb_power_prop_writeable, .get_property = axp20x_usb_power_get_property, .set_property = axp20x_usb_power_set_property, }; static const char * const axp20x_irq_names[] = { "VBUS_PLUGIN", "VBUS_REMOVAL", "VBUS_VALID", "VBUS_NOT_VALID", }; static const char * const axp22x_irq_names[] = { "VBUS_PLUGIN", "VBUS_REMOVAL", }; static int axp192_usb_curr_lim_table[] = { -1, -1, 500000, 100000, }; static int axp20x_usb_curr_lim_table[] = { 900000, 500000, 100000, -1, }; static int axp221_usb_curr_lim_table[] = { 900000, 500000, -1, -1, }; static int axp813_usb_curr_lim_table[] = { 900000, 1500000, 2000000, 2500000, }; static const struct axp_data axp192_data = { .power_desc = &axp20x_usb_power_desc, .irq_names = axp20x_irq_names, .num_irq_names = ARRAY_SIZE(axp20x_irq_names), .curr_lim_table = axp192_usb_curr_lim_table, .curr_lim_fld = REG_FIELD(AXP20X_VBUS_IPSOUT_MGMT, 0, 1), .vbus_valid_bit = REG_FIELD(AXP192_USB_OTG_STATUS, 2, 2), .vbus_mon_bit = REG_FIELD(AXP20X_VBUS_MON, 3, 3), }; static const struct axp_data axp202_data = { .power_desc = &axp20x_usb_power_desc, .irq_names = axp20x_irq_names, .num_irq_names = ARRAY_SIZE(axp20x_irq_names), .curr_lim_table = axp20x_usb_curr_lim_table, .curr_lim_fld = REG_FIELD(AXP20X_VBUS_IPSOUT_MGMT, 0, 1), .vbus_valid_bit = REG_FIELD(AXP20X_USB_OTG_STATUS, 2, 2), .vbus_mon_bit = REG_FIELD(AXP20X_VBUS_MON, 3, 3), }; static const struct axp_data axp221_data = { .power_desc = &axp22x_usb_power_desc, .irq_names = axp22x_irq_names, .num_irq_names = ARRAY_SIZE(axp22x_irq_names), .curr_lim_table = axp221_usb_curr_lim_table, .curr_lim_fld = REG_FIELD(AXP20X_VBUS_IPSOUT_MGMT, 0, 1), .vbus_needs_polling = true, }; static const struct axp_data axp223_data = { .power_desc = &axp22x_usb_power_desc, .irq_names = axp22x_irq_names, .num_irq_names = ARRAY_SIZE(axp22x_irq_names), .curr_lim_table = axp20x_usb_curr_lim_table, .curr_lim_fld = REG_FIELD(AXP20X_VBUS_IPSOUT_MGMT, 0, 1), .vbus_needs_polling = true, }; static const struct axp_data axp813_data = { .power_desc = &axp22x_usb_power_desc, .irq_names = axp22x_irq_names, .num_irq_names = ARRAY_SIZE(axp22x_irq_names), .curr_lim_table = axp813_usb_curr_lim_table, .curr_lim_fld = REG_FIELD(AXP20X_VBUS_IPSOUT_MGMT, 0, 1), .usb_bc_en_bit = REG_FIELD(AXP288_BC_GLOBAL, 0, 0), .vbus_disable_bit = REG_FIELD(AXP20X_VBUS_IPSOUT_MGMT, 7, 7), .vbus_needs_polling = true, }; #ifdef CONFIG_PM_SLEEP static int axp20x_usb_power_suspend(struct device *dev) { struct axp20x_usb_power *power = dev_get_drvdata(dev); int i = 0; /* * Allow wake via VBUS_PLUGIN only. * * As nested threaded IRQs are not automatically disabled during * suspend, we must explicitly disable the remainder of the IRQs. */ if (device_may_wakeup(&power->supply->dev)) enable_irq_wake(power->irqs[i++]); while (i < power->num_irqs) disable_irq(power->irqs[i++]); return 0; } static int axp20x_usb_power_resume(struct device *dev) { struct axp20x_usb_power *power = dev_get_drvdata(dev); int i = 0; if (device_may_wakeup(&power->supply->dev)) disable_irq_wake(power->irqs[i++]); while (i < power->num_irqs) enable_irq(power->irqs[i++]); mod_delayed_work(system_power_efficient_wq, &power->vbus_detect, DEBOUNCE_TIME); return 0; } #endif static SIMPLE_DEV_PM_OPS(axp20x_usb_power_pm_ops, axp20x_usb_power_suspend, axp20x_usb_power_resume); static int configure_iio_channels(struct platform_device *pdev, struct axp20x_usb_power *power) { power->vbus_v = devm_iio_channel_get(&pdev->dev, "vbus_v"); if (IS_ERR(power->vbus_v)) { if (PTR_ERR(power->vbus_v) == -ENODEV) return -EPROBE_DEFER; return PTR_ERR(power->vbus_v); } power->vbus_i = devm_iio_channel_get(&pdev->dev, "vbus_i"); if (IS_ERR(power->vbus_i)) { if (PTR_ERR(power->vbus_i) == -ENODEV) return -EPROBE_DEFER; return PTR_ERR(power->vbus_i); } return 0; } static int configure_adc_registers(struct axp20x_usb_power *power) { /* Enable vbus voltage and current measurement */ return regmap_update_bits(power->regmap, AXP20X_ADC_EN1, AXP20X_ADC_EN1_VBUS_CURR | AXP20X_ADC_EN1_VBUS_VOLT, AXP20X_ADC_EN1_VBUS_CURR | AXP20X_ADC_EN1_VBUS_VOLT); } static int axp20x_regmap_field_alloc_optional(struct device *dev, struct regmap *regmap, struct reg_field fdesc, struct regmap_field **fieldp) { struct regmap_field *field; if (fdesc.reg == 0) { *fieldp = NULL; return 0; } field = devm_regmap_field_alloc(dev, regmap, fdesc); if (IS_ERR(field)) return PTR_ERR(field); *fieldp = field; return 0; } static int axp20x_usb_power_probe(struct platform_device *pdev) { struct axp20x_dev *axp20x = dev_get_drvdata(pdev->dev.parent); struct power_supply_config psy_cfg = {}; struct axp20x_usb_power *power; const struct axp_data *axp_data; int i, irq, ret; if (!of_device_is_available(pdev->dev.of_node)) return -ENODEV; if (!axp20x) { dev_err(&pdev->dev, "Parent drvdata not set\n"); return -EINVAL; } axp_data = of_device_get_match_data(&pdev->dev); power = devm_kzalloc(&pdev->dev, struct_size(power, irqs, axp_data->num_irq_names), GFP_KERNEL); if (!power) return -ENOMEM; platform_set_drvdata(pdev, power); power->axp_data = axp_data; power->regmap = axp20x->regmap; power->num_irqs = axp_data->num_irq_names; power->curr_lim_fld = devm_regmap_field_alloc(&pdev->dev, power->regmap, axp_data->curr_lim_fld); if (IS_ERR(power->curr_lim_fld)) return PTR_ERR(power->curr_lim_fld); ret = axp20x_regmap_field_alloc_optional(&pdev->dev, power->regmap, axp_data->vbus_valid_bit, &power->vbus_valid_bit); if (ret) return ret; ret = axp20x_regmap_field_alloc_optional(&pdev->dev, power->regmap, axp_data->vbus_mon_bit, &power->vbus_mon_bit); if (ret) return ret; ret = axp20x_regmap_field_alloc_optional(&pdev->dev, power->regmap, axp_data->usb_bc_en_bit, &power->usb_bc_en_bit); if (ret) return ret; ret = axp20x_regmap_field_alloc_optional(&pdev->dev, power->regmap, axp_data->vbus_disable_bit, &power->vbus_disable_bit); if (ret) return ret; ret = devm_delayed_work_autocancel(&pdev->dev, &power->vbus_detect, axp20x_usb_power_poll_vbus); if (ret) return ret; if (power->vbus_mon_bit) { /* Enable vbus valid checking */ ret = regmap_field_write(power->vbus_mon_bit, 1); if (ret) return ret; if (IS_ENABLED(CONFIG_AXP20X_ADC)) ret = configure_iio_channels(pdev, power); else ret = configure_adc_registers(power); if (ret) return ret; } if (power->usb_bc_en_bit) { /* Enable USB Battery Charging specification detection */ ret = regmap_field_write(power->usb_bc_en_bit, 1); if (ret) return ret; } psy_cfg.of_node = pdev->dev.of_node; psy_cfg.drv_data = power; power->supply = devm_power_supply_register(&pdev->dev, axp_data->power_desc, &psy_cfg); if (IS_ERR(power->supply)) return PTR_ERR(power->supply); /* Request irqs after registering, as irqs may trigger immediately */ for (i = 0; i < axp_data->num_irq_names; i++) { irq = platform_get_irq_byname(pdev, axp_data->irq_names[i]); if (irq < 0) return irq; power->irqs[i] = regmap_irq_get_virq(axp20x->regmap_irqc, irq); ret = devm_request_any_context_irq(&pdev->dev, power->irqs[i], axp20x_usb_power_irq, 0, DRVNAME, power); if (ret < 0) { dev_err(&pdev->dev, "Error requesting %s IRQ: %d\n", axp_data->irq_names[i], ret); return ret; } } if (axp20x_usb_vbus_needs_polling(power)) queue_delayed_work(system_power_efficient_wq, &power->vbus_detect, 0); return 0; } static const struct of_device_id axp20x_usb_power_match[] = { { .compatible = "x-powers,axp192-usb-power-supply", .data = &axp192_data, }, { .compatible = "x-powers,axp202-usb-power-supply", .data = &axp202_data, }, { .compatible = "x-powers,axp221-usb-power-supply", .data = &axp221_data, }, { .compatible = "x-powers,axp223-usb-power-supply", .data = &axp223_data, }, { .compatible = "x-powers,axp813-usb-power-supply", .data = &axp813_data, }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, axp20x_usb_power_match); static struct platform_driver axp20x_usb_power_driver = { .probe = axp20x_usb_power_probe, .driver = { .name = DRVNAME, .of_match_table = axp20x_usb_power_match, .pm = &axp20x_usb_power_pm_ops, }, }; module_platform_driver(axp20x_usb_power_driver); MODULE_AUTHOR("Hans de Goede <[email protected]>"); MODULE_DESCRIPTION("AXP20x PMIC USB power supply status driver"); MODULE_LICENSE("GPL");
linux-master
drivers/power/supply/axp20x_usb_power.c
// SPDX-License-Identifier: GPL-2.0 /* * power_supply_hwmon.c - power supply hwmon support. */ #include <linux/err.h> #include <linux/hwmon.h> #include <linux/power_supply.h> #include <linux/slab.h> struct power_supply_hwmon { struct power_supply *psy; unsigned long *props; }; static const char *const ps_temp_label[] = { "temp", "ambient temp", }; static int power_supply_hwmon_in_to_property(u32 attr) { switch (attr) { case hwmon_in_average: return POWER_SUPPLY_PROP_VOLTAGE_AVG; case hwmon_in_min: return POWER_SUPPLY_PROP_VOLTAGE_MIN; case hwmon_in_max: return POWER_SUPPLY_PROP_VOLTAGE_MAX; case hwmon_in_input: return POWER_SUPPLY_PROP_VOLTAGE_NOW; default: return -EINVAL; } } static int power_supply_hwmon_curr_to_property(u32 attr) { switch (attr) { case hwmon_curr_average: return POWER_SUPPLY_PROP_CURRENT_AVG; case hwmon_curr_max: return POWER_SUPPLY_PROP_CURRENT_MAX; case hwmon_curr_input: return POWER_SUPPLY_PROP_CURRENT_NOW; default: return -EINVAL; } } static int power_supply_hwmon_temp_to_property(u32 attr, int channel) { if (channel) { switch (attr) { case hwmon_temp_input: return POWER_SUPPLY_PROP_TEMP_AMBIENT; case hwmon_temp_min_alarm: return POWER_SUPPLY_PROP_TEMP_AMBIENT_ALERT_MIN; case hwmon_temp_max_alarm: return POWER_SUPPLY_PROP_TEMP_AMBIENT_ALERT_MAX; default: break; } } else { switch (attr) { case hwmon_temp_input: return POWER_SUPPLY_PROP_TEMP; case hwmon_temp_max: return POWER_SUPPLY_PROP_TEMP_MAX; case hwmon_temp_min: return POWER_SUPPLY_PROP_TEMP_MIN; case hwmon_temp_min_alarm: return POWER_SUPPLY_PROP_TEMP_ALERT_MIN; case hwmon_temp_max_alarm: return POWER_SUPPLY_PROP_TEMP_ALERT_MAX; default: break; } } return -EINVAL; } static int power_supply_hwmon_to_property(enum hwmon_sensor_types type, u32 attr, int channel) { switch (type) { case hwmon_in: return power_supply_hwmon_in_to_property(attr); case hwmon_curr: return power_supply_hwmon_curr_to_property(attr); case hwmon_temp: return power_supply_hwmon_temp_to_property(attr, channel); default: return -EINVAL; } } static bool power_supply_hwmon_is_a_label(enum hwmon_sensor_types type, u32 attr) { return type == hwmon_temp && attr == hwmon_temp_label; } struct hwmon_type_attr_list { const u32 *attrs; size_t n_attrs; }; static const u32 ps_temp_attrs[] = { hwmon_temp_input, hwmon_temp_min, hwmon_temp_max, hwmon_temp_min_alarm, hwmon_temp_max_alarm, }; static const struct hwmon_type_attr_list ps_type_attrs[hwmon_max] = { [hwmon_temp] = { ps_temp_attrs, ARRAY_SIZE(ps_temp_attrs) }, }; static bool power_supply_hwmon_has_input( const struct power_supply_hwmon *psyhw, enum hwmon_sensor_types type, int channel) { const struct hwmon_type_attr_list *attr_list = &ps_type_attrs[type]; size_t i; for (i = 0; i < attr_list->n_attrs; ++i) { int prop = power_supply_hwmon_to_property(type, attr_list->attrs[i], channel); if (prop >= 0 && test_bit(prop, psyhw->props)) return true; } return false; } static bool power_supply_hwmon_is_writable(enum hwmon_sensor_types type, u32 attr) { switch (type) { case hwmon_in: return attr == hwmon_in_min || attr == hwmon_in_max; case hwmon_curr: return attr == hwmon_curr_max; case hwmon_temp: return attr == hwmon_temp_max || attr == hwmon_temp_min || attr == hwmon_temp_min_alarm || attr == hwmon_temp_max_alarm; default: return false; } } static umode_t power_supply_hwmon_is_visible(const void *data, enum hwmon_sensor_types type, u32 attr, int channel) { const struct power_supply_hwmon *psyhw = data; int prop; if (power_supply_hwmon_is_a_label(type, attr)) { if (power_supply_hwmon_has_input(psyhw, type, channel)) return 0444; else return 0; } prop = power_supply_hwmon_to_property(type, attr, channel); if (prop < 0 || !test_bit(prop, psyhw->props)) return 0; if (power_supply_property_is_writeable(psyhw->psy, prop) > 0 && power_supply_hwmon_is_writable(type, attr)) return 0644; return 0444; } static int power_supply_hwmon_read_string(struct device *dev, enum hwmon_sensor_types type, u32 attr, int channel, const char **str) { switch (type) { case hwmon_temp: *str = ps_temp_label[channel]; break; default: /* unreachable, but see: * gcc bug #51513 [1] and clang bug #978 [2] * * [1] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51513 * [2] https://github.com/ClangBuiltLinux/linux/issues/978 */ break; } return 0; } static int power_supply_hwmon_read(struct device *dev, enum hwmon_sensor_types type, u32 attr, int channel, long *val) { struct power_supply_hwmon *psyhw = dev_get_drvdata(dev); struct power_supply *psy = psyhw->psy; union power_supply_propval pspval; int ret, prop; prop = power_supply_hwmon_to_property(type, attr, channel); if (prop < 0) return prop; ret = power_supply_get_property(psy, prop, &pspval); if (ret) return ret; switch (type) { /* * Both voltage and current is reported in units of * microvolts/microamps, so we need to adjust it to * milliamps(volts) */ case hwmon_curr: case hwmon_in: pspval.intval = DIV_ROUND_CLOSEST(pspval.intval, 1000); break; /* * Temp needs to be converted from 1/10 C to milli-C */ case hwmon_temp: if (check_mul_overflow(pspval.intval, 100, &pspval.intval)) return -EOVERFLOW; break; default: return -EINVAL; } *val = pspval.intval; return 0; } static int power_supply_hwmon_write(struct device *dev, enum hwmon_sensor_types type, u32 attr, int channel, long val) { struct power_supply_hwmon *psyhw = dev_get_drvdata(dev); struct power_supply *psy = psyhw->psy; union power_supply_propval pspval; int prop; prop = power_supply_hwmon_to_property(type, attr, channel); if (prop < 0) return prop; pspval.intval = val; switch (type) { /* * Both voltage and current is reported in units of * microvolts/microamps, so we need to adjust it to * milliamps(volts) */ case hwmon_curr: case hwmon_in: if (check_mul_overflow(pspval.intval, 1000, &pspval.intval)) return -EOVERFLOW; break; /* * Temp needs to be converted from 1/10 C to milli-C */ case hwmon_temp: pspval.intval = DIV_ROUND_CLOSEST(pspval.intval, 100); break; default: return -EINVAL; } return power_supply_set_property(psy, prop, &pspval); } static const struct hwmon_ops power_supply_hwmon_ops = { .is_visible = power_supply_hwmon_is_visible, .read = power_supply_hwmon_read, .write = power_supply_hwmon_write, .read_string = power_supply_hwmon_read_string, }; static const struct hwmon_channel_info * const power_supply_hwmon_info[] = { HWMON_CHANNEL_INFO(temp, HWMON_T_LABEL | HWMON_T_INPUT | HWMON_T_MAX | HWMON_T_MIN | HWMON_T_MIN_ALARM, HWMON_T_LABEL | HWMON_T_INPUT | HWMON_T_MIN_ALARM | HWMON_T_MAX_ALARM), HWMON_CHANNEL_INFO(curr, HWMON_C_AVERAGE | HWMON_C_MAX | HWMON_C_INPUT), HWMON_CHANNEL_INFO(in, HWMON_I_AVERAGE | HWMON_I_MIN | HWMON_I_MAX | HWMON_I_INPUT), NULL }; static const struct hwmon_chip_info power_supply_hwmon_chip_info = { .ops = &power_supply_hwmon_ops, .info = power_supply_hwmon_info, }; int power_supply_add_hwmon_sysfs(struct power_supply *psy) { const struct power_supply_desc *desc = psy->desc; struct power_supply_hwmon *psyhw; struct device *dev = &psy->dev; struct device *hwmon; int ret, i; const char *name; if (!devres_open_group(dev, power_supply_add_hwmon_sysfs, GFP_KERNEL)) return -ENOMEM; psyhw = devm_kzalloc(dev, sizeof(*psyhw), GFP_KERNEL); if (!psyhw) { ret = -ENOMEM; goto error; } psyhw->psy = psy; psyhw->props = devm_bitmap_zalloc(dev, POWER_SUPPLY_PROP_TIME_TO_FULL_AVG + 1, GFP_KERNEL); if (!psyhw->props) { ret = -ENOMEM; goto error; } for (i = 0; i < desc->num_properties; i++) { const enum power_supply_property prop = desc->properties[i]; switch (prop) { case POWER_SUPPLY_PROP_CURRENT_AVG: case POWER_SUPPLY_PROP_CURRENT_MAX: case POWER_SUPPLY_PROP_CURRENT_NOW: case POWER_SUPPLY_PROP_TEMP: case POWER_SUPPLY_PROP_TEMP_MAX: case POWER_SUPPLY_PROP_TEMP_MIN: case POWER_SUPPLY_PROP_TEMP_ALERT_MIN: case POWER_SUPPLY_PROP_TEMP_ALERT_MAX: case POWER_SUPPLY_PROP_TEMP_AMBIENT: case POWER_SUPPLY_PROP_TEMP_AMBIENT_ALERT_MIN: case POWER_SUPPLY_PROP_TEMP_AMBIENT_ALERT_MAX: case POWER_SUPPLY_PROP_VOLTAGE_AVG: case POWER_SUPPLY_PROP_VOLTAGE_MIN: case POWER_SUPPLY_PROP_VOLTAGE_MAX: case POWER_SUPPLY_PROP_VOLTAGE_NOW: set_bit(prop, psyhw->props); break; default: break; } } name = psy->desc->name; if (strchr(name, '-')) { char *new_name; new_name = devm_kstrdup(dev, name, GFP_KERNEL); if (!new_name) { ret = -ENOMEM; goto error; } strreplace(new_name, '-', '_'); name = new_name; } hwmon = devm_hwmon_device_register_with_info(dev, name, psyhw, &power_supply_hwmon_chip_info, NULL); ret = PTR_ERR_OR_ZERO(hwmon); if (ret) goto error; devres_close_group(dev, power_supply_add_hwmon_sysfs); return 0; error: devres_release_group(dev, NULL); return ret; } void power_supply_remove_hwmon_sysfs(struct power_supply *psy) { devres_release_group(&psy->dev, power_supply_add_hwmon_sysfs); }
linux-master
drivers/power/supply/power_supply_hwmon.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (C) ST-Ericsson SA 2012 * Copyright (c) 2012 Sony Mobile Communications AB * * Charging algorithm driver for AB8500 * * Authors: * Johan Palsson <[email protected]> * Karl Komierowski <[email protected]> * Arun R Murthy <[email protected]> * Author: Imre Sunyi <[email protected]> */ #include <linux/init.h> #include <linux/module.h> #include <linux/device.h> #include <linux/component.h> #include <linux/hrtimer.h> #include <linux/interrupt.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/completion.h> #include <linux/workqueue.h> #include <linux/kobject.h> #include <linux/of.h> #include <linux/mfd/core.h> #include <linux/mfd/abx500.h> #include <linux/mfd/abx500/ab8500.h> #include <linux/notifier.h> #include "ab8500-bm.h" #include "ab8500-chargalg.h" /* Watchdog kick interval */ #define CHG_WD_INTERVAL (6 * HZ) /* End-of-charge criteria counter */ #define EOC_COND_CNT 10 /* One hour expressed in seconds */ #define ONE_HOUR_IN_SECONDS 3600 /* Five minutes expressed in seconds */ #define FIVE_MINUTES_IN_SECONDS 300 /* * This is the battery capacity limit that will trigger a new * full charging cycle in the case where maintenance charging * has been disabled */ #define AB8500_RECHARGE_CAP 95 enum ab8500_chargers { NO_CHG, AC_CHG, USB_CHG, }; struct ab8500_chargalg_charger_info { enum ab8500_chargers conn_chg; enum ab8500_chargers prev_conn_chg; enum ab8500_chargers online_chg; enum ab8500_chargers prev_online_chg; enum ab8500_chargers charger_type; bool usb_chg_ok; bool ac_chg_ok; int usb_volt_uv; int usb_curr_ua; int ac_volt_uv; int ac_curr_ua; int usb_vset_uv; int usb_iset_ua; int ac_vset_uv; int ac_iset_ua; }; struct ab8500_chargalg_battery_data { int temp; int volt_uv; int avg_curr_ua; int inst_curr_ua; int percent; }; enum ab8500_chargalg_states { STATE_HANDHELD_INIT, STATE_HANDHELD, STATE_CHG_NOT_OK_INIT, STATE_CHG_NOT_OK, STATE_HW_TEMP_PROTECT_INIT, STATE_HW_TEMP_PROTECT, STATE_NORMAL_INIT, STATE_NORMAL, STATE_WAIT_FOR_RECHARGE_INIT, STATE_WAIT_FOR_RECHARGE, STATE_MAINTENANCE_A_INIT, STATE_MAINTENANCE_A, STATE_MAINTENANCE_B_INIT, STATE_MAINTENANCE_B, STATE_TEMP_UNDEROVER_INIT, STATE_TEMP_UNDEROVER, STATE_TEMP_LOWHIGH_INIT, STATE_TEMP_LOWHIGH, STATE_OVV_PROTECT_INIT, STATE_OVV_PROTECT, STATE_SAFETY_TIMER_EXPIRED_INIT, STATE_SAFETY_TIMER_EXPIRED, STATE_BATT_REMOVED_INIT, STATE_BATT_REMOVED, STATE_WD_EXPIRED_INIT, STATE_WD_EXPIRED, }; static const char * const states[] = { "HANDHELD_INIT", "HANDHELD", "CHG_NOT_OK_INIT", "CHG_NOT_OK", "HW_TEMP_PROTECT_INIT", "HW_TEMP_PROTECT", "NORMAL_INIT", "NORMAL", "WAIT_FOR_RECHARGE_INIT", "WAIT_FOR_RECHARGE", "MAINTENANCE_A_INIT", "MAINTENANCE_A", "MAINTENANCE_B_INIT", "MAINTENANCE_B", "TEMP_UNDEROVER_INIT", "TEMP_UNDEROVER", "TEMP_LOWHIGH_INIT", "TEMP_LOWHIGH", "OVV_PROTECT_INIT", "OVV_PROTECT", "SAFETY_TIMER_EXPIRED_INIT", "SAFETY_TIMER_EXPIRED", "BATT_REMOVED_INIT", "BATT_REMOVED", "WD_EXPIRED_INIT", "WD_EXPIRED", }; struct ab8500_chargalg_events { bool batt_unknown; bool mainextchnotok; bool batt_ovv; bool batt_rem; bool btemp_underover; bool btemp_low; bool btemp_high; bool main_thermal_prot; bool usb_thermal_prot; bool main_ovv; bool vbus_ovv; bool usbchargernotok; bool safety_timer_expired; bool maintenance_timer_expired; bool ac_wd_expired; bool usb_wd_expired; bool ac_cv_active; bool usb_cv_active; bool vbus_collapsed; }; /** * struct ab8500_charge_curr_maximization - Charger maximization parameters * @original_iset_ua: the non optimized/maximised charger current * @current_iset_ua: the charging current used at this moment * @condition_cnt: number of iterations needed before a new charger current is set * @max_current_ua: maximum charger current * @wait_cnt: to avoid too fast current step down in case of charger * voltage collapse, we insert this delay between step * down * @level: tells in how many steps the charging current has been increased */ struct ab8500_charge_curr_maximization { int original_iset_ua; int current_iset_ua; int condition_cnt; int max_current_ua; int wait_cnt; u8 level; }; enum maxim_ret { MAXIM_RET_NOACTION, MAXIM_RET_CHANGE, MAXIM_RET_IBAT_TOO_HIGH, }; /** * struct ab8500_chargalg - ab8500 Charging algorithm device information * @dev: pointer to the structure device * @charge_status: battery operating status * @eoc_cnt: counter used to determine end-of_charge * @maintenance_chg: indicate if maintenance charge is active * @t_hyst_norm temperature hysteresis when the temperature has been * over or under normal limits * @t_hyst_lowhigh temperature hysteresis when the temperature has been * over or under the high or low limits * @charge_state: current state of the charging algorithm * @ccm charging current maximization parameters * @chg_info: information about connected charger types * @batt_data: data of the battery * @bm: Platform specific battery management information * @parent: pointer to the struct ab8500 * @chargalg_psy: structure that holds the battery properties exposed by * the charging algorithm * @events: structure for information about events triggered * @chargalg_wq: work queue for running the charging algorithm * @chargalg_periodic_work: work to run the charging algorithm periodically * @chargalg_wd_work: work to kick the charger watchdog periodically * @chargalg_work: work to run the charging algorithm instantly * @safety_timer: charging safety timer * @maintenance_timer: maintenance charging timer * @chargalg_kobject: structure of type kobject */ struct ab8500_chargalg { struct device *dev; int charge_status; int eoc_cnt; bool maintenance_chg; int t_hyst_norm; int t_hyst_lowhigh; enum ab8500_chargalg_states charge_state; struct ab8500_charge_curr_maximization ccm; struct ab8500_chargalg_charger_info chg_info; struct ab8500_chargalg_battery_data batt_data; struct ab8500 *parent; struct ab8500_bm_data *bm; struct power_supply *chargalg_psy; struct ux500_charger *ac_chg; struct ux500_charger *usb_chg; struct ab8500_chargalg_events events; struct workqueue_struct *chargalg_wq; struct delayed_work chargalg_periodic_work; struct delayed_work chargalg_wd_work; struct work_struct chargalg_work; struct hrtimer safety_timer; struct hrtimer maintenance_timer; struct kobject chargalg_kobject; }; /* Main battery properties */ static enum power_supply_property ab8500_chargalg_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_HEALTH, }; /** * ab8500_chargalg_safety_timer_expired() - Expiration of the safety timer * @timer: pointer to the hrtimer structure * * This function gets called when the safety timer for the charger * expires */ static enum hrtimer_restart ab8500_chargalg_safety_timer_expired(struct hrtimer *timer) { struct ab8500_chargalg *di = container_of(timer, struct ab8500_chargalg, safety_timer); dev_err(di->dev, "Safety timer expired\n"); di->events.safety_timer_expired = true; /* Trigger execution of the algorithm instantly */ queue_work(di->chargalg_wq, &di->chargalg_work); return HRTIMER_NORESTART; } /** * ab8500_chargalg_maintenance_timer_expired() - Expiration of * the maintenance timer * @timer: pointer to the timer structure * * This function gets called when the maintenance timer * expires */ static enum hrtimer_restart ab8500_chargalg_maintenance_timer_expired(struct hrtimer *timer) { struct ab8500_chargalg *di = container_of(timer, struct ab8500_chargalg, maintenance_timer); dev_dbg(di->dev, "Maintenance timer expired\n"); di->events.maintenance_timer_expired = true; /* Trigger execution of the algorithm instantly */ queue_work(di->chargalg_wq, &di->chargalg_work); return HRTIMER_NORESTART; } /** * ab8500_chargalg_state_to() - Change charge state * @di: pointer to the ab8500_chargalg structure * * This function gets called when a charge state change should occur */ static void ab8500_chargalg_state_to(struct ab8500_chargalg *di, enum ab8500_chargalg_states state) { dev_dbg(di->dev, "State changed: %s (From state: [%d] %s =to=> [%d] %s )\n", di->charge_state == state ? "NO" : "YES", di->charge_state, states[di->charge_state], state, states[state]); di->charge_state = state; } static int ab8500_chargalg_check_charger_enable(struct ab8500_chargalg *di) { struct power_supply_battery_info *bi = di->bm->bi; switch (di->charge_state) { case STATE_NORMAL: case STATE_MAINTENANCE_A: case STATE_MAINTENANCE_B: break; default: return 0; } if (di->chg_info.charger_type & USB_CHG) { return di->usb_chg->ops.check_enable(di->usb_chg, bi->constant_charge_voltage_max_uv, bi->constant_charge_current_max_ua); } else if (di->chg_info.charger_type & AC_CHG) { return di->ac_chg->ops.check_enable(di->ac_chg, bi->constant_charge_voltage_max_uv, bi->constant_charge_current_max_ua); } return 0; } /** * ab8500_chargalg_check_charger_connection() - Check charger connection change * @di: pointer to the ab8500_chargalg structure * * This function will check if there is a change in the charger connection * and change charge state accordingly. AC has precedence over USB. */ static int ab8500_chargalg_check_charger_connection(struct ab8500_chargalg *di) { if (di->chg_info.conn_chg != di->chg_info.prev_conn_chg) { /* Charger state changed since last update */ if (di->chg_info.conn_chg & AC_CHG) { dev_info(di->dev, "Charging source is AC\n"); if (di->chg_info.charger_type != AC_CHG) { di->chg_info.charger_type = AC_CHG; ab8500_chargalg_state_to(di, STATE_NORMAL_INIT); } } else if (di->chg_info.conn_chg & USB_CHG) { dev_info(di->dev, "Charging source is USB\n"); di->chg_info.charger_type = USB_CHG; ab8500_chargalg_state_to(di, STATE_NORMAL_INIT); } else { dev_dbg(di->dev, "Charging source is OFF\n"); di->chg_info.charger_type = NO_CHG; ab8500_chargalg_state_to(di, STATE_HANDHELD_INIT); } di->chg_info.prev_conn_chg = di->chg_info.conn_chg; } return di->chg_info.conn_chg; } /** * ab8500_chargalg_start_safety_timer() - Start charging safety timer * @di: pointer to the ab8500_chargalg structure * * The safety timer is used to avoid overcharging of old or bad batteries. * There are different timers for AC and USB */ static void ab8500_chargalg_start_safety_timer(struct ab8500_chargalg *di) { /* Charger-dependent expiration time in hours*/ int timer_expiration = 0; switch (di->chg_info.charger_type) { case AC_CHG: timer_expiration = di->bm->main_safety_tmr_h; break; case USB_CHG: timer_expiration = di->bm->usb_safety_tmr_h; break; default: dev_err(di->dev, "Unknown charger to charge from\n"); break; } di->events.safety_timer_expired = false; hrtimer_set_expires_range(&di->safety_timer, ktime_set(timer_expiration * ONE_HOUR_IN_SECONDS, 0), ktime_set(FIVE_MINUTES_IN_SECONDS, 0)); hrtimer_start_expires(&di->safety_timer, HRTIMER_MODE_REL); } /** * ab8500_chargalg_stop_safety_timer() - Stop charging safety timer * @di: pointer to the ab8500_chargalg structure * * The safety timer is stopped whenever the NORMAL state is exited */ static void ab8500_chargalg_stop_safety_timer(struct ab8500_chargalg *di) { if (hrtimer_try_to_cancel(&di->safety_timer) >= 0) di->events.safety_timer_expired = false; } /** * ab8500_chargalg_start_maintenance_timer() - Start charging maintenance timer * @di: pointer to the ab8500_chargalg structure * @duration: duration of the maintenance timer in minutes * * The maintenance timer is used to maintain the charge in the battery once * the battery is considered full. These timers are chosen to match the * discharge curve of the battery */ static void ab8500_chargalg_start_maintenance_timer(struct ab8500_chargalg *di, int duration) { /* Set a timer in minutes with a 30 second range */ hrtimer_set_expires_range(&di->maintenance_timer, ktime_set(duration * 60, 0), ktime_set(30, 0)); di->events.maintenance_timer_expired = false; hrtimer_start_expires(&di->maintenance_timer, HRTIMER_MODE_REL); } /** * ab8500_chargalg_stop_maintenance_timer() - Stop maintenance timer * @di: pointer to the ab8500_chargalg structure * * The maintenance timer is stopped whenever maintenance ends or when another * state is entered */ static void ab8500_chargalg_stop_maintenance_timer(struct ab8500_chargalg *di) { if (hrtimer_try_to_cancel(&di->maintenance_timer) >= 0) di->events.maintenance_timer_expired = false; } /** * ab8500_chargalg_kick_watchdog() - Kick charger watchdog * @di: pointer to the ab8500_chargalg structure * * The charger watchdog have to be kicked periodically whenever the charger is * on, else the ABB will reset the system */ static int ab8500_chargalg_kick_watchdog(struct ab8500_chargalg *di) { /* Check if charger exists and kick watchdog if charging */ if (di->ac_chg && di->ac_chg->ops.kick_wd && di->chg_info.online_chg & AC_CHG) { return di->ac_chg->ops.kick_wd(di->ac_chg); } else if (di->usb_chg && di->usb_chg->ops.kick_wd && di->chg_info.online_chg & USB_CHG) return di->usb_chg->ops.kick_wd(di->usb_chg); return -ENXIO; } /** * ab8500_chargalg_ac_en() - Turn on/off the AC charger * @di: pointer to the ab8500_chargalg structure * @enable: charger on/off * @vset_uv: requested charger output voltage in microvolt * @iset_ua: requested charger output current in microampere * * The AC charger will be turned on/off with the requested charge voltage and * current */ static int ab8500_chargalg_ac_en(struct ab8500_chargalg *di, int enable, int vset_uv, int iset_ua) { if (!di->ac_chg || !di->ac_chg->ops.enable) return -ENXIO; /* Select maximum of what both the charger and the battery supports */ if (di->ac_chg->max_out_volt_uv) vset_uv = min(vset_uv, di->ac_chg->max_out_volt_uv); if (di->ac_chg->max_out_curr_ua) iset_ua = min(iset_ua, di->ac_chg->max_out_curr_ua); di->chg_info.ac_iset_ua = iset_ua; di->chg_info.ac_vset_uv = vset_uv; return di->ac_chg->ops.enable(di->ac_chg, enable, vset_uv, iset_ua); } /** * ab8500_chargalg_usb_en() - Turn on/off the USB charger * @di: pointer to the ab8500_chargalg structure * @enable: charger on/off * @vset_uv: requested charger output voltage in microvolt * @iset_ua: requested charger output current in microampere * * The USB charger will be turned on/off with the requested charge voltage and * current */ static int ab8500_chargalg_usb_en(struct ab8500_chargalg *di, int enable, int vset_uv, int iset_ua) { if (!di->usb_chg || !di->usb_chg->ops.enable) return -ENXIO; /* Select maximum of what both the charger and the battery supports */ if (di->usb_chg->max_out_volt_uv) vset_uv = min(vset_uv, di->usb_chg->max_out_volt_uv); if (di->usb_chg->max_out_curr_ua) iset_ua = min(iset_ua, di->usb_chg->max_out_curr_ua); di->chg_info.usb_iset_ua = iset_ua; di->chg_info.usb_vset_uv = vset_uv; return di->usb_chg->ops.enable(di->usb_chg, enable, vset_uv, iset_ua); } /** * ab8500_chargalg_update_chg_curr() - Update charger current * @di: pointer to the ab8500_chargalg structure * @iset_ua: requested charger output current in microampere * * The charger output current will be updated for the charger * that is currently in use */ static int ab8500_chargalg_update_chg_curr(struct ab8500_chargalg *di, int iset_ua) { /* Check if charger exists and update current if charging */ if (di->ac_chg && di->ac_chg->ops.update_curr && di->chg_info.charger_type & AC_CHG) { /* * Select maximum of what both the charger * and the battery supports */ if (di->ac_chg->max_out_curr_ua) iset_ua = min(iset_ua, di->ac_chg->max_out_curr_ua); di->chg_info.ac_iset_ua = iset_ua; return di->ac_chg->ops.update_curr(di->ac_chg, iset_ua); } else if (di->usb_chg && di->usb_chg->ops.update_curr && di->chg_info.charger_type & USB_CHG) { /* * Select maximum of what both the charger * and the battery supports */ if (di->usb_chg->max_out_curr_ua) iset_ua = min(iset_ua, di->usb_chg->max_out_curr_ua); di->chg_info.usb_iset_ua = iset_ua; return di->usb_chg->ops.update_curr(di->usb_chg, iset_ua); } return -ENXIO; } /** * ab8500_chargalg_stop_charging() - Stop charging * @di: pointer to the ab8500_chargalg structure * * This function is called from any state where charging should be stopped. * All charging is disabled and all status parameters and timers are changed * accordingly */ static void ab8500_chargalg_stop_charging(struct ab8500_chargalg *di) { ab8500_chargalg_ac_en(di, false, 0, 0); ab8500_chargalg_usb_en(di, false, 0, 0); ab8500_chargalg_stop_safety_timer(di); ab8500_chargalg_stop_maintenance_timer(di); di->charge_status = POWER_SUPPLY_STATUS_NOT_CHARGING; di->maintenance_chg = false; cancel_delayed_work(&di->chargalg_wd_work); power_supply_changed(di->chargalg_psy); } /** * ab8500_chargalg_hold_charging() - Pauses charging * @di: pointer to the ab8500_chargalg structure * * This function is called in the case where maintenance charging has been * disabled and instead a battery voltage mode is entered to check when the * battery voltage has reached a certain recharge voltage */ static void ab8500_chargalg_hold_charging(struct ab8500_chargalg *di) { ab8500_chargalg_ac_en(di, false, 0, 0); ab8500_chargalg_usb_en(di, false, 0, 0); ab8500_chargalg_stop_safety_timer(di); ab8500_chargalg_stop_maintenance_timer(di); di->charge_status = POWER_SUPPLY_STATUS_CHARGING; di->maintenance_chg = false; cancel_delayed_work(&di->chargalg_wd_work); power_supply_changed(di->chargalg_psy); } /** * ab8500_chargalg_start_charging() - Start the charger * @di: pointer to the ab8500_chargalg structure * @vset_uv: requested charger output voltage in microvolt * @iset_ua: requested charger output current in microampere * * A charger will be enabled depending on the requested charger type that was * detected previously. */ static void ab8500_chargalg_start_charging(struct ab8500_chargalg *di, int vset_uv, int iset_ua) { switch (di->chg_info.charger_type) { case AC_CHG: dev_dbg(di->dev, "AC parameters: Vset %d, Ich %d\n", vset_uv, iset_ua); ab8500_chargalg_usb_en(di, false, 0, 0); ab8500_chargalg_ac_en(di, true, vset_uv, iset_ua); break; case USB_CHG: dev_dbg(di->dev, "USB parameters: Vset %d, Ich %d\n", vset_uv, iset_ua); ab8500_chargalg_ac_en(di, false, 0, 0); ab8500_chargalg_usb_en(di, true, vset_uv, iset_ua); break; default: dev_err(di->dev, "Unknown charger to charge from\n"); break; } } /** * ab8500_chargalg_check_temp() - Check battery temperature ranges * @di: pointer to the ab8500_chargalg structure * * The battery temperature is checked against the predefined limits and the * charge state is changed accordingly */ static void ab8500_chargalg_check_temp(struct ab8500_chargalg *di) { struct power_supply_battery_info *bi = di->bm->bi; if (di->batt_data.temp > (bi->temp_alert_min + di->t_hyst_norm) && di->batt_data.temp < (bi->temp_alert_max - di->t_hyst_norm)) { /* Temp OK! */ di->events.btemp_underover = false; di->events.btemp_low = false; di->events.btemp_high = false; di->t_hyst_norm = 0; di->t_hyst_lowhigh = 0; } else { if ((di->batt_data.temp >= bi->temp_alert_max) && (di->batt_data.temp < (bi->temp_max - di->t_hyst_lowhigh))) { /* Alert zone for high temperature */ di->events.btemp_underover = false; di->events.btemp_high = true; di->t_hyst_norm = di->bm->temp_hysteresis; di->t_hyst_lowhigh = 0; } else if ((di->batt_data.temp > (bi->temp_min + di->t_hyst_lowhigh)) && (di->batt_data.temp <= bi->temp_alert_min)) { /* Alert zone for low temperature */ di->events.btemp_underover = false; di->events.btemp_low = true; di->t_hyst_norm = di->bm->temp_hysteresis; di->t_hyst_lowhigh = 0; } else if (di->batt_data.temp <= bi->temp_min || di->batt_data.temp >= bi->temp_max) { /* TEMP major!!!!! */ di->events.btemp_underover = true; di->events.btemp_low = false; di->events.btemp_high = false; di->t_hyst_norm = 0; di->t_hyst_lowhigh = di->bm->temp_hysteresis; } else { /* Within hysteresis */ dev_dbg(di->dev, "Within hysteresis limit temp: %d " "hyst_lowhigh %d, hyst normal %d\n", di->batt_data.temp, di->t_hyst_lowhigh, di->t_hyst_norm); } } } /** * ab8500_chargalg_check_charger_voltage() - Check charger voltage * @di: pointer to the ab8500_chargalg structure * * Charger voltage is checked against maximum limit */ static void ab8500_chargalg_check_charger_voltage(struct ab8500_chargalg *di) { if (di->chg_info.usb_volt_uv > di->bm->chg_params->usb_volt_max_uv) di->chg_info.usb_chg_ok = false; else di->chg_info.usb_chg_ok = true; if (di->chg_info.ac_volt_uv > di->bm->chg_params->ac_volt_max_uv) di->chg_info.ac_chg_ok = false; else di->chg_info.ac_chg_ok = true; } /** * ab8500_chargalg_end_of_charge() - Check if end-of-charge criteria is fulfilled * @di: pointer to the ab8500_chargalg structure * * End-of-charge criteria is fulfilled when the battery voltage is above a * certain limit and the battery current is below a certain limit for a * predefined number of consecutive seconds. If true, the battery is full */ static void ab8500_chargalg_end_of_charge(struct ab8500_chargalg *di) { if (di->charge_status == POWER_SUPPLY_STATUS_CHARGING && di->charge_state == STATE_NORMAL && !di->maintenance_chg && (di->batt_data.volt_uv >= di->bm->bi->voltage_max_design_uv || di->events.usb_cv_active || di->events.ac_cv_active) && di->batt_data.avg_curr_ua < di->bm->bi->charge_term_current_ua && di->batt_data.avg_curr_ua > 0) { if (++di->eoc_cnt >= EOC_COND_CNT) { di->eoc_cnt = 0; di->charge_status = POWER_SUPPLY_STATUS_FULL; di->maintenance_chg = true; dev_dbg(di->dev, "EOC reached!\n"); power_supply_changed(di->chargalg_psy); } else { dev_dbg(di->dev, " EOC limit reached for the %d" " time, out of %d before EOC\n", di->eoc_cnt, EOC_COND_CNT); } } else { di->eoc_cnt = 0; } } static void init_maxim_chg_curr(struct ab8500_chargalg *di) { struct power_supply_battery_info *bi = di->bm->bi; di->ccm.original_iset_ua = bi->constant_charge_current_max_ua; di->ccm.current_iset_ua = bi->constant_charge_current_max_ua; di->ccm.max_current_ua = di->bm->maxi->chg_curr_ua; di->ccm.condition_cnt = di->bm->maxi->wait_cycles; di->ccm.level = 0; } /** * ab8500_chargalg_chg_curr_maxim - increases the charger current to * compensate for the system load * @di pointer to the ab8500_chargalg structure * * This maximization function is used to raise the charger current to get the * battery current as close to the optimal value as possible. The battery * current during charging is affected by the system load */ static enum maxim_ret ab8500_chargalg_chg_curr_maxim(struct ab8500_chargalg *di) { if (!di->bm->maxi->ena_maxi) return MAXIM_RET_NOACTION; if (di->events.vbus_collapsed) { dev_dbg(di->dev, "Charger voltage has collapsed %d\n", di->ccm.wait_cnt); if (di->ccm.wait_cnt == 0) { dev_dbg(di->dev, "lowering current\n"); di->ccm.wait_cnt++; di->ccm.condition_cnt = di->bm->maxi->wait_cycles; di->ccm.max_current_ua = di->ccm.current_iset_ua; di->ccm.current_iset_ua = di->ccm.max_current_ua; di->ccm.level--; return MAXIM_RET_CHANGE; } else { dev_dbg(di->dev, "waiting\n"); /* Let's go in here twice before lowering curr again */ di->ccm.wait_cnt = (di->ccm.wait_cnt + 1) % 3; return MAXIM_RET_NOACTION; } } di->ccm.wait_cnt = 0; if (di->batt_data.inst_curr_ua > di->ccm.original_iset_ua) { dev_dbg(di->dev, " Maximization Ibat (%duA) too high" " (limit %duA) (current iset: %duA)!\n", di->batt_data.inst_curr_ua, di->ccm.original_iset_ua, di->ccm.current_iset_ua); if (di->ccm.current_iset_ua == di->ccm.original_iset_ua) return MAXIM_RET_NOACTION; di->ccm.condition_cnt = di->bm->maxi->wait_cycles; di->ccm.current_iset_ua = di->ccm.original_iset_ua; di->ccm.level = 0; return MAXIM_RET_IBAT_TOO_HIGH; } di->ccm.condition_cnt = di->bm->maxi->wait_cycles; return MAXIM_RET_NOACTION; } static void handle_maxim_chg_curr(struct ab8500_chargalg *di) { struct power_supply_battery_info *bi = di->bm->bi; enum maxim_ret ret; int result; ret = ab8500_chargalg_chg_curr_maxim(di); switch (ret) { case MAXIM_RET_CHANGE: result = ab8500_chargalg_update_chg_curr(di, di->ccm.current_iset_ua); if (result) dev_err(di->dev, "failed to set chg curr\n"); break; case MAXIM_RET_IBAT_TOO_HIGH: result = ab8500_chargalg_update_chg_curr(di, bi->constant_charge_current_max_ua); if (result) dev_err(di->dev, "failed to set chg curr\n"); break; case MAXIM_RET_NOACTION: default: /* Do nothing..*/ break; } } static int ab8500_chargalg_get_ext_psy_data(struct device *dev, void *data) { struct power_supply *psy; struct power_supply *ext = dev_get_drvdata(dev); const char **supplicants = (const char **)ext->supplied_to; struct ab8500_chargalg *di; union power_supply_propval ret; int j; bool capacity_updated = false; psy = (struct power_supply *)data; di = power_supply_get_drvdata(psy); /* For all psy where the driver name appears in any supplied_to */ j = match_string(supplicants, ext->num_supplicants, psy->desc->name); if (j < 0) return 0; /* * If external is not registering 'POWER_SUPPLY_PROP_CAPACITY' to its * property because of handling that sysfs entry on its own, this is * the place to get the battery capacity. */ if (!power_supply_get_property(ext, POWER_SUPPLY_PROP_CAPACITY, &ret)) { di->batt_data.percent = ret.intval; capacity_updated = true; } /* Go through all properties for the psy */ for (j = 0; j < ext->desc->num_properties; j++) { enum power_supply_property prop; prop = ext->desc->properties[j]; /* * Initialize chargers if not already done. * The ab8500_charger*/ if (!di->ac_chg && ext->desc->type == POWER_SUPPLY_TYPE_MAINS) di->ac_chg = psy_to_ux500_charger(ext); else if (!di->usb_chg && ext->desc->type == POWER_SUPPLY_TYPE_USB) di->usb_chg = psy_to_ux500_charger(ext); if (power_supply_get_property(ext, prop, &ret)) continue; switch (prop) { case POWER_SUPPLY_PROP_PRESENT: switch (ext->desc->type) { case POWER_SUPPLY_TYPE_BATTERY: /* Battery present */ if (ret.intval) di->events.batt_rem = false; /* Battery removed */ else di->events.batt_rem = true; break; case POWER_SUPPLY_TYPE_MAINS: /* AC disconnected */ if (!ret.intval && (di->chg_info.conn_chg & AC_CHG)) { di->chg_info.prev_conn_chg = di->chg_info.conn_chg; di->chg_info.conn_chg &= ~AC_CHG; } /* AC connected */ else if (ret.intval && !(di->chg_info.conn_chg & AC_CHG)) { di->chg_info.prev_conn_chg = di->chg_info.conn_chg; di->chg_info.conn_chg |= AC_CHG; } break; case POWER_SUPPLY_TYPE_USB: /* USB disconnected */ if (!ret.intval && (di->chg_info.conn_chg & USB_CHG)) { di->chg_info.prev_conn_chg = di->chg_info.conn_chg; di->chg_info.conn_chg &= ~USB_CHG; } /* USB connected */ else if (ret.intval && !(di->chg_info.conn_chg & USB_CHG)) { di->chg_info.prev_conn_chg = di->chg_info.conn_chg; di->chg_info.conn_chg |= USB_CHG; } break; default: break; } break; case POWER_SUPPLY_PROP_ONLINE: switch (ext->desc->type) { case POWER_SUPPLY_TYPE_BATTERY: break; case POWER_SUPPLY_TYPE_MAINS: /* AC offline */ if (!ret.intval && (di->chg_info.online_chg & AC_CHG)) { di->chg_info.prev_online_chg = di->chg_info.online_chg; di->chg_info.online_chg &= ~AC_CHG; } /* AC online */ else if (ret.intval && !(di->chg_info.online_chg & AC_CHG)) { di->chg_info.prev_online_chg = di->chg_info.online_chg; di->chg_info.online_chg |= AC_CHG; queue_delayed_work(di->chargalg_wq, &di->chargalg_wd_work, 0); } break; case POWER_SUPPLY_TYPE_USB: /* USB offline */ if (!ret.intval && (di->chg_info.online_chg & USB_CHG)) { di->chg_info.prev_online_chg = di->chg_info.online_chg; di->chg_info.online_chg &= ~USB_CHG; } /* USB online */ else if (ret.intval && !(di->chg_info.online_chg & USB_CHG)) { di->chg_info.prev_online_chg = di->chg_info.online_chg; di->chg_info.online_chg |= USB_CHG; queue_delayed_work(di->chargalg_wq, &di->chargalg_wd_work, 0); } break; default: break; } break; case POWER_SUPPLY_PROP_HEALTH: switch (ext->desc->type) { case POWER_SUPPLY_TYPE_BATTERY: break; case POWER_SUPPLY_TYPE_MAINS: switch (ret.intval) { case POWER_SUPPLY_HEALTH_UNSPEC_FAILURE: di->events.mainextchnotok = true; di->events.main_thermal_prot = false; di->events.main_ovv = false; di->events.ac_wd_expired = false; break; case POWER_SUPPLY_HEALTH_DEAD: di->events.ac_wd_expired = true; di->events.mainextchnotok = false; di->events.main_ovv = false; di->events.main_thermal_prot = false; break; case POWER_SUPPLY_HEALTH_COLD: case POWER_SUPPLY_HEALTH_OVERHEAT: di->events.main_thermal_prot = true; di->events.mainextchnotok = false; di->events.main_ovv = false; di->events.ac_wd_expired = false; break; case POWER_SUPPLY_HEALTH_OVERVOLTAGE: di->events.main_ovv = true; di->events.mainextchnotok = false; di->events.main_thermal_prot = false; di->events.ac_wd_expired = false; break; case POWER_SUPPLY_HEALTH_GOOD: di->events.main_thermal_prot = false; di->events.mainextchnotok = false; di->events.main_ovv = false; di->events.ac_wd_expired = false; break; default: break; } break; case POWER_SUPPLY_TYPE_USB: switch (ret.intval) { case POWER_SUPPLY_HEALTH_UNSPEC_FAILURE: di->events.usbchargernotok = true; di->events.usb_thermal_prot = false; di->events.vbus_ovv = false; di->events.usb_wd_expired = false; break; case POWER_SUPPLY_HEALTH_DEAD: di->events.usb_wd_expired = true; di->events.usbchargernotok = false; di->events.usb_thermal_prot = false; di->events.vbus_ovv = false; break; case POWER_SUPPLY_HEALTH_COLD: case POWER_SUPPLY_HEALTH_OVERHEAT: di->events.usb_thermal_prot = true; di->events.usbchargernotok = false; di->events.vbus_ovv = false; di->events.usb_wd_expired = false; break; case POWER_SUPPLY_HEALTH_OVERVOLTAGE: di->events.vbus_ovv = true; di->events.usbchargernotok = false; di->events.usb_thermal_prot = false; di->events.usb_wd_expired = false; break; case POWER_SUPPLY_HEALTH_GOOD: di->events.usbchargernotok = false; di->events.usb_thermal_prot = false; di->events.vbus_ovv = false; di->events.usb_wd_expired = false; break; default: break; } break; default: break; } break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: switch (ext->desc->type) { case POWER_SUPPLY_TYPE_BATTERY: di->batt_data.volt_uv = ret.intval; break; case POWER_SUPPLY_TYPE_MAINS: di->chg_info.ac_volt_uv = ret.intval; break; case POWER_SUPPLY_TYPE_USB: di->chg_info.usb_volt_uv = ret.intval; break; default: break; } break; case POWER_SUPPLY_PROP_VOLTAGE_AVG: switch (ext->desc->type) { case POWER_SUPPLY_TYPE_MAINS: /* AVG is used to indicate when we are * in CV mode */ if (ret.intval) di->events.ac_cv_active = true; else di->events.ac_cv_active = false; break; case POWER_SUPPLY_TYPE_USB: /* AVG is used to indicate when we are * in CV mode */ if (ret.intval) di->events.usb_cv_active = true; else di->events.usb_cv_active = false; break; default: break; } break; case POWER_SUPPLY_PROP_TECHNOLOGY: switch (ext->desc->type) { case POWER_SUPPLY_TYPE_BATTERY: if (ret.intval) di->events.batt_unknown = false; else di->events.batt_unknown = true; break; default: break; } break; case POWER_SUPPLY_PROP_TEMP: di->batt_data.temp = ret.intval / 10; break; case POWER_SUPPLY_PROP_CURRENT_NOW: switch (ext->desc->type) { case POWER_SUPPLY_TYPE_MAINS: di->chg_info.ac_curr_ua = ret.intval; break; case POWER_SUPPLY_TYPE_USB: di->chg_info.usb_curr_ua = ret.intval; break; case POWER_SUPPLY_TYPE_BATTERY: di->batt_data.inst_curr_ua = ret.intval; break; default: break; } break; case POWER_SUPPLY_PROP_CURRENT_AVG: switch (ext->desc->type) { case POWER_SUPPLY_TYPE_BATTERY: di->batt_data.avg_curr_ua = ret.intval; break; case POWER_SUPPLY_TYPE_USB: if (ret.intval) di->events.vbus_collapsed = true; else di->events.vbus_collapsed = false; break; default: break; } break; case POWER_SUPPLY_PROP_CAPACITY: if (!capacity_updated) di->batt_data.percent = ret.intval; break; default: break; } } return 0; } /** * ab8500_chargalg_external_power_changed() - callback for power supply changes * @psy: pointer to the structure power_supply * * This function is the entry point of the pointer external_power_changed * of the structure power_supply. * This function gets executed when there is a change in any external power * supply that this driver needs to be notified of. */ static void ab8500_chargalg_external_power_changed(struct power_supply *psy) { struct ab8500_chargalg *di = power_supply_get_drvdata(psy); /* * Trigger execution of the algorithm instantly and read * all power_supply properties there instead */ if (di->chargalg_wq) queue_work(di->chargalg_wq, &di->chargalg_work); } /** * ab8500_chargalg_time_to_restart() - time to restart CC/CV charging? * @di: charging algorithm state * * This checks if the voltage or capacity of the battery has fallen so * low that we need to restart the CC/CV charge cycle. */ static bool ab8500_chargalg_time_to_restart(struct ab8500_chargalg *di) { struct power_supply_battery_info *bi = di->bm->bi; /* Sanity check - these need to have some reasonable values */ if (!di->batt_data.volt_uv || !di->batt_data.percent) return false; /* Some batteries tell us at which voltage we should restart charging */ if (bi->charge_restart_voltage_uv > 0) { if (di->batt_data.volt_uv <= bi->charge_restart_voltage_uv) return true; /* Else we restart as we reach a certain capacity */ } else { if (di->batt_data.percent <= AB8500_RECHARGE_CAP) return true; } return false; } /** * ab8500_chargalg_algorithm() - Main function for the algorithm * @di: pointer to the ab8500_chargalg structure * * This is the main control function for the charging algorithm. * It is called periodically or when something happens that will * trigger a state change */ static void ab8500_chargalg_algorithm(struct ab8500_chargalg *di) { struct power_supply_battery_info *bi = di->bm->bi; struct power_supply_maintenance_charge_table *mt; int charger_status; int ret; /* Collect data from all power_supply class devices */ class_for_each_device(power_supply_class, NULL, di->chargalg_psy, ab8500_chargalg_get_ext_psy_data); ab8500_chargalg_end_of_charge(di); ab8500_chargalg_check_temp(di); ab8500_chargalg_check_charger_voltage(di); charger_status = ab8500_chargalg_check_charger_connection(di); if (is_ab8500(di->parent)) { ret = ab8500_chargalg_check_charger_enable(di); if (ret < 0) dev_err(di->dev, "Checking charger is enabled error" ": Returned Value %d\n", ret); } /* * First check if we have a charger connected. * Also we don't allow charging of unknown batteries if configured * this way */ if (!charger_status || (di->events.batt_unknown && !di->bm->chg_unknown_bat)) { if (di->charge_state != STATE_HANDHELD) { di->events.safety_timer_expired = false; ab8500_chargalg_state_to(di, STATE_HANDHELD_INIT); } } /* Safety timer expiration */ else if (di->events.safety_timer_expired) { if (di->charge_state != STATE_SAFETY_TIMER_EXPIRED) ab8500_chargalg_state_to(di, STATE_SAFETY_TIMER_EXPIRED_INIT); } /* * Check if any interrupts has occurred * that will prevent us from charging */ /* Battery removed */ else if (di->events.batt_rem) { if (di->charge_state != STATE_BATT_REMOVED) ab8500_chargalg_state_to(di, STATE_BATT_REMOVED_INIT); } /* Main or USB charger not ok. */ else if (di->events.mainextchnotok || di->events.usbchargernotok) { /* * If vbus_collapsed is set, we have to lower the charger * current, which is done in the normal state below */ if (di->charge_state != STATE_CHG_NOT_OK && !di->events.vbus_collapsed) ab8500_chargalg_state_to(di, STATE_CHG_NOT_OK_INIT); } /* VBUS, Main or VBAT OVV. */ else if (di->events.vbus_ovv || di->events.main_ovv || di->events.batt_ovv || !di->chg_info.usb_chg_ok || !di->chg_info.ac_chg_ok) { if (di->charge_state != STATE_OVV_PROTECT) ab8500_chargalg_state_to(di, STATE_OVV_PROTECT_INIT); } /* USB Thermal, stop charging */ else if (di->events.main_thermal_prot || di->events.usb_thermal_prot) { if (di->charge_state != STATE_HW_TEMP_PROTECT) ab8500_chargalg_state_to(di, STATE_HW_TEMP_PROTECT_INIT); } /* Battery temp over/under */ else if (di->events.btemp_underover) { if (di->charge_state != STATE_TEMP_UNDEROVER) ab8500_chargalg_state_to(di, STATE_TEMP_UNDEROVER_INIT); } /* Watchdog expired */ else if (di->events.ac_wd_expired || di->events.usb_wd_expired) { if (di->charge_state != STATE_WD_EXPIRED) ab8500_chargalg_state_to(di, STATE_WD_EXPIRED_INIT); } /* Battery temp high/low */ else if (di->events.btemp_low || di->events.btemp_high) { if (di->charge_state != STATE_TEMP_LOWHIGH) ab8500_chargalg_state_to(di, STATE_TEMP_LOWHIGH_INIT); } dev_dbg(di->dev, "[CHARGALG] Vb %d Ib_avg %d Ib_inst %d Tb %d Cap %d Maint %d " "State %s Active_chg %d Chg_status %d AC %d USB %d " "AC_online %d USB_online %d AC_CV %d USB_CV %d AC_I %d " "USB_I %d AC_Vset %d AC_Iset %d USB_Vset %d USB_Iset %d\n", di->batt_data.volt_uv, di->batt_data.avg_curr_ua, di->batt_data.inst_curr_ua, di->batt_data.temp, di->batt_data.percent, di->maintenance_chg, states[di->charge_state], di->chg_info.charger_type, di->charge_status, di->chg_info.conn_chg & AC_CHG, di->chg_info.conn_chg & USB_CHG, di->chg_info.online_chg & AC_CHG, di->chg_info.online_chg & USB_CHG, di->events.ac_cv_active, di->events.usb_cv_active, di->chg_info.ac_curr_ua, di->chg_info.usb_curr_ua, di->chg_info.ac_vset_uv, di->chg_info.ac_iset_ua, di->chg_info.usb_vset_uv, di->chg_info.usb_iset_ua); switch (di->charge_state) { case STATE_HANDHELD_INIT: ab8500_chargalg_stop_charging(di); di->charge_status = POWER_SUPPLY_STATUS_DISCHARGING; ab8500_chargalg_state_to(di, STATE_HANDHELD); fallthrough; case STATE_HANDHELD: break; case STATE_BATT_REMOVED_INIT: ab8500_chargalg_stop_charging(di); ab8500_chargalg_state_to(di, STATE_BATT_REMOVED); fallthrough; case STATE_BATT_REMOVED: if (!di->events.batt_rem) ab8500_chargalg_state_to(di, STATE_NORMAL_INIT); break; case STATE_HW_TEMP_PROTECT_INIT: ab8500_chargalg_stop_charging(di); ab8500_chargalg_state_to(di, STATE_HW_TEMP_PROTECT); fallthrough; case STATE_HW_TEMP_PROTECT: if (!di->events.main_thermal_prot && !di->events.usb_thermal_prot) ab8500_chargalg_state_to(di, STATE_NORMAL_INIT); break; case STATE_OVV_PROTECT_INIT: ab8500_chargalg_stop_charging(di); ab8500_chargalg_state_to(di, STATE_OVV_PROTECT); fallthrough; case STATE_OVV_PROTECT: if (!di->events.vbus_ovv && !di->events.main_ovv && !di->events.batt_ovv && di->chg_info.usb_chg_ok && di->chg_info.ac_chg_ok) ab8500_chargalg_state_to(di, STATE_NORMAL_INIT); break; case STATE_CHG_NOT_OK_INIT: ab8500_chargalg_stop_charging(di); ab8500_chargalg_state_to(di, STATE_CHG_NOT_OK); fallthrough; case STATE_CHG_NOT_OK: if (!di->events.mainextchnotok && !di->events.usbchargernotok) ab8500_chargalg_state_to(di, STATE_NORMAL_INIT); break; case STATE_SAFETY_TIMER_EXPIRED_INIT: ab8500_chargalg_stop_charging(di); ab8500_chargalg_state_to(di, STATE_SAFETY_TIMER_EXPIRED); fallthrough; case STATE_SAFETY_TIMER_EXPIRED: /* We exit this state when charger is removed */ break; case STATE_NORMAL_INIT: if (bi->constant_charge_current_max_ua == 0) /* "charging" with 0 uA */ ab8500_chargalg_stop_charging(di); else { ab8500_chargalg_start_charging(di, bi->constant_charge_voltage_max_uv, bi->constant_charge_current_max_ua); } ab8500_chargalg_state_to(di, STATE_NORMAL); ab8500_chargalg_start_safety_timer(di); ab8500_chargalg_stop_maintenance_timer(di); init_maxim_chg_curr(di); di->charge_status = POWER_SUPPLY_STATUS_CHARGING; di->eoc_cnt = 0; di->maintenance_chg = false; power_supply_changed(di->chargalg_psy); break; case STATE_NORMAL: handle_maxim_chg_curr(di); if (di->charge_status == POWER_SUPPLY_STATUS_FULL && di->maintenance_chg) { /* * The battery is fully charged, check if we support * maintenance charging else go back to waiting for * the recharge voltage limit. */ if (!power_supply_supports_maintenance_charging(bi)) ab8500_chargalg_state_to(di, STATE_WAIT_FOR_RECHARGE_INIT); else ab8500_chargalg_state_to(di, STATE_MAINTENANCE_A_INIT); } break; /* This state will be used when the maintenance state is disabled */ case STATE_WAIT_FOR_RECHARGE_INIT: ab8500_chargalg_hold_charging(di); ab8500_chargalg_state_to(di, STATE_WAIT_FOR_RECHARGE); fallthrough; case STATE_WAIT_FOR_RECHARGE: if (ab8500_chargalg_time_to_restart(di)) ab8500_chargalg_state_to(di, STATE_NORMAL_INIT); break; case STATE_MAINTENANCE_A_INIT: mt = power_supply_get_maintenance_charging_setting(bi, 0); if (!mt) { /* No maintenance A state, go back to normal */ ab8500_chargalg_state_to(di, STATE_NORMAL_INIT); power_supply_changed(di->chargalg_psy); break; } ab8500_chargalg_stop_safety_timer(di); ab8500_chargalg_start_maintenance_timer(di, mt->charge_safety_timer_minutes); ab8500_chargalg_start_charging(di, mt->charge_voltage_max_uv, mt->charge_current_max_ua); ab8500_chargalg_state_to(di, STATE_MAINTENANCE_A); power_supply_changed(di->chargalg_psy); fallthrough; case STATE_MAINTENANCE_A: if (di->events.maintenance_timer_expired) { ab8500_chargalg_stop_maintenance_timer(di); ab8500_chargalg_state_to(di, STATE_MAINTENANCE_B_INIT); } /* * This happens if the voltage drops too quickly during * maintenance charging, especially in older batteries. */ if (ab8500_chargalg_time_to_restart(di)) { ab8500_chargalg_state_to(di, STATE_NORMAL_INIT); dev_info(di->dev, "restarted charging from maintenance state A - battery getting old?\n"); } break; case STATE_MAINTENANCE_B_INIT: mt = power_supply_get_maintenance_charging_setting(bi, 1); if (!mt) { /* No maintenance B state, go back to normal */ ab8500_chargalg_state_to(di, STATE_NORMAL_INIT); power_supply_changed(di->chargalg_psy); break; } ab8500_chargalg_start_maintenance_timer(di, mt->charge_safety_timer_minutes); ab8500_chargalg_start_charging(di, mt->charge_voltage_max_uv, mt->charge_current_max_ua); ab8500_chargalg_state_to(di, STATE_MAINTENANCE_B); power_supply_changed(di->chargalg_psy); fallthrough; case STATE_MAINTENANCE_B: if (di->events.maintenance_timer_expired) { ab8500_chargalg_stop_maintenance_timer(di); ab8500_chargalg_state_to(di, STATE_NORMAL_INIT); } /* * This happens if the voltage drops too quickly during * maintenance charging, especially in older batteries. */ if (ab8500_chargalg_time_to_restart(di)) { ab8500_chargalg_state_to(di, STATE_NORMAL_INIT); dev_info(di->dev, "restarted charging from maintenance state B - battery getting old?\n"); } break; case STATE_TEMP_LOWHIGH_INIT: if (di->events.btemp_low) { ab8500_chargalg_start_charging(di, bi->alert_low_temp_charge_voltage_uv, bi->alert_low_temp_charge_current_ua); } else if (di->events.btemp_high) { ab8500_chargalg_start_charging(di, bi->alert_high_temp_charge_voltage_uv, bi->alert_high_temp_charge_current_ua); } else { dev_err(di->dev, "neither low or high temp event occurred\n"); ab8500_chargalg_state_to(di, STATE_NORMAL_INIT); break; } ab8500_chargalg_stop_maintenance_timer(di); di->charge_status = POWER_SUPPLY_STATUS_CHARGING; ab8500_chargalg_state_to(di, STATE_TEMP_LOWHIGH); power_supply_changed(di->chargalg_psy); fallthrough; case STATE_TEMP_LOWHIGH: if (!di->events.btemp_low && !di->events.btemp_high) ab8500_chargalg_state_to(di, STATE_NORMAL_INIT); break; case STATE_WD_EXPIRED_INIT: ab8500_chargalg_stop_charging(di); ab8500_chargalg_state_to(di, STATE_WD_EXPIRED); fallthrough; case STATE_WD_EXPIRED: if (!di->events.ac_wd_expired && !di->events.usb_wd_expired) ab8500_chargalg_state_to(di, STATE_NORMAL_INIT); break; case STATE_TEMP_UNDEROVER_INIT: ab8500_chargalg_stop_charging(di); ab8500_chargalg_state_to(di, STATE_TEMP_UNDEROVER); fallthrough; case STATE_TEMP_UNDEROVER: if (!di->events.btemp_underover) ab8500_chargalg_state_to(di, STATE_NORMAL_INIT); break; } /* Start charging directly if the new state is a charge state */ if (di->charge_state == STATE_NORMAL_INIT || di->charge_state == STATE_MAINTENANCE_A_INIT || di->charge_state == STATE_MAINTENANCE_B_INIT) queue_work(di->chargalg_wq, &di->chargalg_work); } /** * ab8500_chargalg_periodic_work() - Periodic work for the algorithm * @work: pointer to the work_struct structure * * Work queue function for the charging algorithm */ static void ab8500_chargalg_periodic_work(struct work_struct *work) { struct ab8500_chargalg *di = container_of(work, struct ab8500_chargalg, chargalg_periodic_work.work); ab8500_chargalg_algorithm(di); /* * If a charger is connected then the battery has to be monitored * frequently, else the work can be delayed. */ if (di->chg_info.conn_chg) queue_delayed_work(di->chargalg_wq, &di->chargalg_periodic_work, di->bm->interval_charging * HZ); else queue_delayed_work(di->chargalg_wq, &di->chargalg_periodic_work, di->bm->interval_not_charging * HZ); } /** * ab8500_chargalg_wd_work() - periodic work to kick the charger watchdog * @work: pointer to the work_struct structure * * Work queue function for kicking the charger watchdog */ static void ab8500_chargalg_wd_work(struct work_struct *work) { int ret; struct ab8500_chargalg *di = container_of(work, struct ab8500_chargalg, chargalg_wd_work.work); ret = ab8500_chargalg_kick_watchdog(di); if (ret < 0) dev_err(di->dev, "failed to kick watchdog\n"); queue_delayed_work(di->chargalg_wq, &di->chargalg_wd_work, CHG_WD_INTERVAL); } /** * ab8500_chargalg_work() - Work to run the charging algorithm instantly * @work: pointer to the work_struct structure * * Work queue function for calling the charging algorithm */ static void ab8500_chargalg_work(struct work_struct *work) { struct ab8500_chargalg *di = container_of(work, struct ab8500_chargalg, chargalg_work); ab8500_chargalg_algorithm(di); } /** * ab8500_chargalg_get_property() - get the chargalg properties * @psy: pointer to the power_supply structure * @psp: pointer to the power_supply_property structure * @val: pointer to the power_supply_propval union * * This function gets called when an application tries to get the * chargalg properties by reading the sysfs files. * status: charging/discharging/full/unknown * health: health of the battery * Returns error code in case of failure else 0 on success */ static int ab8500_chargalg_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct ab8500_chargalg *di = power_supply_get_drvdata(psy); switch (psp) { case POWER_SUPPLY_PROP_STATUS: val->intval = di->charge_status; break; case POWER_SUPPLY_PROP_HEALTH: if (di->events.batt_ovv) { val->intval = POWER_SUPPLY_HEALTH_OVERVOLTAGE; } else if (di->events.btemp_underover) { if (di->batt_data.temp <= di->bm->bi->temp_min) val->intval = POWER_SUPPLY_HEALTH_COLD; else val->intval = POWER_SUPPLY_HEALTH_OVERHEAT; } else if (di->charge_state == STATE_SAFETY_TIMER_EXPIRED || di->charge_state == STATE_SAFETY_TIMER_EXPIRED_INIT) { val->intval = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE; } else { val->intval = POWER_SUPPLY_HEALTH_GOOD; } break; default: return -EINVAL; } return 0; } static int __maybe_unused ab8500_chargalg_resume(struct device *dev) { struct ab8500_chargalg *di = dev_get_drvdata(dev); /* Kick charger watchdog if charging (any charger online) */ if (di->chg_info.online_chg) queue_delayed_work(di->chargalg_wq, &di->chargalg_wd_work, 0); /* * Run the charging algorithm directly to be sure we don't * do it too seldom */ queue_delayed_work(di->chargalg_wq, &di->chargalg_periodic_work, 0); return 0; } static int __maybe_unused ab8500_chargalg_suspend(struct device *dev) { struct ab8500_chargalg *di = dev_get_drvdata(dev); if (di->chg_info.online_chg) cancel_delayed_work_sync(&di->chargalg_wd_work); cancel_delayed_work_sync(&di->chargalg_periodic_work); return 0; } static char *supply_interface[] = { "ab8500_fg", }; static const struct power_supply_desc ab8500_chargalg_desc = { .name = "ab8500_chargalg", .type = POWER_SUPPLY_TYPE_BATTERY, .properties = ab8500_chargalg_props, .num_properties = ARRAY_SIZE(ab8500_chargalg_props), .get_property = ab8500_chargalg_get_property, .external_power_changed = ab8500_chargalg_external_power_changed, }; static int ab8500_chargalg_bind(struct device *dev, struct device *master, void *data) { struct ab8500_chargalg *di = dev_get_drvdata(dev); /* Create a work queue for the chargalg */ di->chargalg_wq = alloc_ordered_workqueue("ab8500_chargalg_wq", WQ_MEM_RECLAIM); if (di->chargalg_wq == NULL) { dev_err(di->dev, "failed to create work queue\n"); return -ENOMEM; } /* Run the charging algorithm */ queue_delayed_work(di->chargalg_wq, &di->chargalg_periodic_work, 0); return 0; } static void ab8500_chargalg_unbind(struct device *dev, struct device *master, void *data) { struct ab8500_chargalg *di = dev_get_drvdata(dev); /* Stop all timers and work */ hrtimer_cancel(&di->safety_timer); hrtimer_cancel(&di->maintenance_timer); cancel_delayed_work_sync(&di->chargalg_periodic_work); cancel_delayed_work_sync(&di->chargalg_wd_work); cancel_work_sync(&di->chargalg_work); /* Delete the work queue */ destroy_workqueue(di->chargalg_wq); } static const struct component_ops ab8500_chargalg_component_ops = { .bind = ab8500_chargalg_bind, .unbind = ab8500_chargalg_unbind, }; static int ab8500_chargalg_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct power_supply_config psy_cfg = {}; struct ab8500_chargalg *di; di = devm_kzalloc(dev, sizeof(*di), GFP_KERNEL); if (!di) return -ENOMEM; di->bm = &ab8500_bm_data; /* get device struct and parent */ di->dev = dev; di->parent = dev_get_drvdata(pdev->dev.parent); psy_cfg.supplied_to = supply_interface; psy_cfg.num_supplicants = ARRAY_SIZE(supply_interface); psy_cfg.drv_data = di; /* Initilialize safety timer */ hrtimer_init(&di->safety_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); di->safety_timer.function = ab8500_chargalg_safety_timer_expired; /* Initilialize maintenance timer */ hrtimer_init(&di->maintenance_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); di->maintenance_timer.function = ab8500_chargalg_maintenance_timer_expired; /* Init work for chargalg */ INIT_DEFERRABLE_WORK(&di->chargalg_periodic_work, ab8500_chargalg_periodic_work); INIT_DEFERRABLE_WORK(&di->chargalg_wd_work, ab8500_chargalg_wd_work); /* Init work for chargalg */ INIT_WORK(&di->chargalg_work, ab8500_chargalg_work); /* To detect charger at startup */ di->chg_info.prev_conn_chg = -1; /* Register chargalg power supply class */ di->chargalg_psy = devm_power_supply_register(di->dev, &ab8500_chargalg_desc, &psy_cfg); if (IS_ERR(di->chargalg_psy)) { dev_err(di->dev, "failed to register chargalg psy\n"); return PTR_ERR(di->chargalg_psy); } platform_set_drvdata(pdev, di); dev_info(di->dev, "probe success\n"); return component_add(dev, &ab8500_chargalg_component_ops); } static int ab8500_chargalg_remove(struct platform_device *pdev) { component_del(&pdev->dev, &ab8500_chargalg_component_ops); return 0; } static SIMPLE_DEV_PM_OPS(ab8500_chargalg_pm_ops, ab8500_chargalg_suspend, ab8500_chargalg_resume); static const struct of_device_id ab8500_chargalg_match[] = { { .compatible = "stericsson,ab8500-chargalg", }, { }, }; struct platform_driver ab8500_chargalg_driver = { .probe = ab8500_chargalg_probe, .remove = ab8500_chargalg_remove, .driver = { .name = "ab8500_chargalg", .of_match_table = ab8500_chargalg_match, .pm = &ab8500_chargalg_pm_ops, }, }; MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Johan Palsson, Karl Komierowski"); MODULE_ALIAS("platform:ab8500-chargalg"); MODULE_DESCRIPTION("ab8500 battery charging algorithm");
linux-master
drivers/power/supply/ab8500_chargalg.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * TI BQ24257 charger driver * * Copyright (C) 2015 Intel Corporation * * Datasheets: * https://www.ti.com/product/bq24250 * https://www.ti.com/product/bq24251 * https://www.ti.com/product/bq24257 */ #include <linux/module.h> #include <linux/i2c.h> #include <linux/power_supply.h> #include <linux/regmap.h> #include <linux/types.h> #include <linux/gpio/consumer.h> #include <linux/interrupt.h> #include <linux/delay.h> #include <linux/acpi.h> #include <linux/of.h> #define BQ24257_REG_1 0x00 #define BQ24257_REG_2 0x01 #define BQ24257_REG_3 0x02 #define BQ24257_REG_4 0x03 #define BQ24257_REG_5 0x04 #define BQ24257_REG_6 0x05 #define BQ24257_REG_7 0x06 #define BQ24257_MANUFACTURER "Texas Instruments" #define BQ24257_PG_GPIO "pg" #define BQ24257_ILIM_SET_DELAY 1000 /* msec */ /* * When adding support for new devices make sure that enum bq2425x_chip and * bq2425x_chip_name[] always stay in sync! */ enum bq2425x_chip { BQ24250, BQ24251, BQ24257, }; static const char *const bq2425x_chip_name[] = { "bq24250", "bq24251", "bq24257", }; enum bq24257_fields { F_WD_FAULT, F_WD_EN, F_STAT, F_FAULT, /* REG 1 */ F_RESET, F_IILIMIT, F_EN_STAT, F_EN_TERM, F_CE, F_HZ_MODE, /* REG 2 */ F_VBAT, F_USB_DET, /* REG 3 */ F_ICHG, F_ITERM, /* REG 4 */ F_LOOP_STATUS, F_LOW_CHG, F_DPDM_EN, F_CE_STATUS, F_VINDPM, /* REG 5 */ F_X2_TMR_EN, F_TMR, F_SYSOFF, F_TS_EN, F_TS_STAT, /* REG 6 */ F_VOVP, F_CLR_VDP, F_FORCE_BATDET, F_FORCE_PTM, /* REG 7 */ F_MAX_FIELDS }; /* initial field values, converted from uV/uA */ struct bq24257_init_data { u8 ichg; /* charge current */ u8 vbat; /* regulation voltage */ u8 iterm; /* termination current */ u8 iilimit; /* input current limit */ u8 vovp; /* over voltage protection voltage */ u8 vindpm; /* VDMP input threshold voltage */ }; struct bq24257_state { u8 status; u8 fault; bool power_good; }; struct bq24257_device { struct i2c_client *client; struct device *dev; struct power_supply *charger; enum bq2425x_chip chip; struct regmap *rmap; struct regmap_field *rmap_fields[F_MAX_FIELDS]; struct gpio_desc *pg; struct delayed_work iilimit_setup_work; struct bq24257_init_data init_data; struct bq24257_state state; struct mutex lock; /* protect state data */ bool iilimit_autoset_enable; }; static bool bq24257_is_volatile_reg(struct device *dev, unsigned int reg) { switch (reg) { case BQ24257_REG_2: case BQ24257_REG_4: return false; default: return true; } } static const struct regmap_config bq24257_regmap_config = { .reg_bits = 8, .val_bits = 8, .max_register = BQ24257_REG_7, .cache_type = REGCACHE_RBTREE, .volatile_reg = bq24257_is_volatile_reg, }; static const struct reg_field bq24257_reg_fields[] = { /* REG 1 */ [F_WD_FAULT] = REG_FIELD(BQ24257_REG_1, 7, 7), [F_WD_EN] = REG_FIELD(BQ24257_REG_1, 6, 6), [F_STAT] = REG_FIELD(BQ24257_REG_1, 4, 5), [F_FAULT] = REG_FIELD(BQ24257_REG_1, 0, 3), /* REG 2 */ [F_RESET] = REG_FIELD(BQ24257_REG_2, 7, 7), [F_IILIMIT] = REG_FIELD(BQ24257_REG_2, 4, 6), [F_EN_STAT] = REG_FIELD(BQ24257_REG_2, 3, 3), [F_EN_TERM] = REG_FIELD(BQ24257_REG_2, 2, 2), [F_CE] = REG_FIELD(BQ24257_REG_2, 1, 1), [F_HZ_MODE] = REG_FIELD(BQ24257_REG_2, 0, 0), /* REG 3 */ [F_VBAT] = REG_FIELD(BQ24257_REG_3, 2, 7), [F_USB_DET] = REG_FIELD(BQ24257_REG_3, 0, 1), /* REG 4 */ [F_ICHG] = REG_FIELD(BQ24257_REG_4, 3, 7), [F_ITERM] = REG_FIELD(BQ24257_REG_4, 0, 2), /* REG 5 */ [F_LOOP_STATUS] = REG_FIELD(BQ24257_REG_5, 6, 7), [F_LOW_CHG] = REG_FIELD(BQ24257_REG_5, 5, 5), [F_DPDM_EN] = REG_FIELD(BQ24257_REG_5, 4, 4), [F_CE_STATUS] = REG_FIELD(BQ24257_REG_5, 3, 3), [F_VINDPM] = REG_FIELD(BQ24257_REG_5, 0, 2), /* REG 6 */ [F_X2_TMR_EN] = REG_FIELD(BQ24257_REG_6, 7, 7), [F_TMR] = REG_FIELD(BQ24257_REG_6, 5, 6), [F_SYSOFF] = REG_FIELD(BQ24257_REG_6, 4, 4), [F_TS_EN] = REG_FIELD(BQ24257_REG_6, 3, 3), [F_TS_STAT] = REG_FIELD(BQ24257_REG_6, 0, 2), /* REG 7 */ [F_VOVP] = REG_FIELD(BQ24257_REG_7, 5, 7), [F_CLR_VDP] = REG_FIELD(BQ24257_REG_7, 4, 4), [F_FORCE_BATDET] = REG_FIELD(BQ24257_REG_7, 3, 3), [F_FORCE_PTM] = REG_FIELD(BQ24257_REG_7, 2, 2) }; static const u32 bq24257_vbat_map[] = { 3500000, 3520000, 3540000, 3560000, 3580000, 3600000, 3620000, 3640000, 3660000, 3680000, 3700000, 3720000, 3740000, 3760000, 3780000, 3800000, 3820000, 3840000, 3860000, 3880000, 3900000, 3920000, 3940000, 3960000, 3980000, 4000000, 4020000, 4040000, 4060000, 4080000, 4100000, 4120000, 4140000, 4160000, 4180000, 4200000, 4220000, 4240000, 4260000, 4280000, 4300000, 4320000, 4340000, 4360000, 4380000, 4400000, 4420000, 4440000 }; #define BQ24257_VBAT_MAP_SIZE ARRAY_SIZE(bq24257_vbat_map) static const u32 bq24257_ichg_map[] = { 500000, 550000, 600000, 650000, 700000, 750000, 800000, 850000, 900000, 950000, 1000000, 1050000, 1100000, 1150000, 1200000, 1250000, 1300000, 1350000, 1400000, 1450000, 1500000, 1550000, 1600000, 1650000, 1700000, 1750000, 1800000, 1850000, 1900000, 1950000, 2000000 }; #define BQ24257_ICHG_MAP_SIZE ARRAY_SIZE(bq24257_ichg_map) static const u32 bq24257_iterm_map[] = { 50000, 75000, 100000, 125000, 150000, 175000, 200000, 225000 }; #define BQ24257_ITERM_MAP_SIZE ARRAY_SIZE(bq24257_iterm_map) static const u32 bq24257_iilimit_map[] = { 100000, 150000, 500000, 900000, 1500000, 2000000 }; #define BQ24257_IILIMIT_MAP_SIZE ARRAY_SIZE(bq24257_iilimit_map) static const u32 bq24257_vovp_map[] = { 6000000, 6500000, 7000000, 8000000, 9000000, 9500000, 10000000, 10500000 }; #define BQ24257_VOVP_MAP_SIZE ARRAY_SIZE(bq24257_vovp_map) static const u32 bq24257_vindpm_map[] = { 4200000, 4280000, 4360000, 4440000, 4520000, 4600000, 4680000, 4760000 }; #define BQ24257_VINDPM_MAP_SIZE ARRAY_SIZE(bq24257_vindpm_map) static int bq24257_field_read(struct bq24257_device *bq, enum bq24257_fields field_id) { int ret; int val; ret = regmap_field_read(bq->rmap_fields[field_id], &val); if (ret < 0) return ret; return val; } static int bq24257_field_write(struct bq24257_device *bq, enum bq24257_fields field_id, u8 val) { return regmap_field_write(bq->rmap_fields[field_id], val); } static u8 bq24257_find_idx(u32 value, const u32 *map, u8 map_size) { u8 idx; for (idx = 1; idx < map_size; idx++) if (value < map[idx]) break; return idx - 1; } enum bq24257_status { STATUS_READY, STATUS_CHARGE_IN_PROGRESS, STATUS_CHARGE_DONE, STATUS_FAULT, }; enum bq24257_fault { FAULT_NORMAL, FAULT_INPUT_OVP, FAULT_INPUT_UVLO, FAULT_SLEEP, FAULT_BAT_TS, FAULT_BAT_OVP, FAULT_TS, FAULT_TIMER, FAULT_NO_BAT, FAULT_ISET, FAULT_INPUT_LDO_LOW, }; static int bq24257_get_input_current_limit(struct bq24257_device *bq, union power_supply_propval *val) { int ret; ret = bq24257_field_read(bq, F_IILIMIT); if (ret < 0) return ret; /* * The "External ILIM" and "Production & Test" modes are not exposed * through this driver and not being covered by the lookup table. * Should such a mode have become active let's return an error rather * than exceeding the bounds of the lookup table and returning * garbage. */ if (ret >= BQ24257_IILIMIT_MAP_SIZE) return -ENODATA; val->intval = bq24257_iilimit_map[ret]; return 0; } static int bq24257_set_input_current_limit(struct bq24257_device *bq, const union power_supply_propval *val) { /* * Address the case where the user manually sets an input current limit * while the charger auto-detection mechanism is active. In this * case we want to abort and go straight to the user-specified value. */ if (bq->iilimit_autoset_enable) cancel_delayed_work_sync(&bq->iilimit_setup_work); return bq24257_field_write(bq, F_IILIMIT, bq24257_find_idx(val->intval, bq24257_iilimit_map, BQ24257_IILIMIT_MAP_SIZE)); } static int bq24257_power_supply_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { struct bq24257_device *bq = power_supply_get_drvdata(psy); struct bq24257_state state; mutex_lock(&bq->lock); state = bq->state; mutex_unlock(&bq->lock); switch (psp) { case POWER_SUPPLY_PROP_STATUS: if (!state.power_good) val->intval = POWER_SUPPLY_STATUS_DISCHARGING; else if (state.status == STATUS_READY) val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING; else if (state.status == STATUS_CHARGE_IN_PROGRESS) val->intval = POWER_SUPPLY_STATUS_CHARGING; else if (state.status == STATUS_CHARGE_DONE) val->intval = POWER_SUPPLY_STATUS_FULL; else val->intval = POWER_SUPPLY_STATUS_UNKNOWN; break; case POWER_SUPPLY_PROP_MANUFACTURER: val->strval = BQ24257_MANUFACTURER; break; case POWER_SUPPLY_PROP_MODEL_NAME: val->strval = bq2425x_chip_name[bq->chip]; break; case POWER_SUPPLY_PROP_ONLINE: val->intval = state.power_good; break; case POWER_SUPPLY_PROP_HEALTH: switch (state.fault) { case FAULT_NORMAL: val->intval = POWER_SUPPLY_HEALTH_GOOD; break; case FAULT_INPUT_OVP: case FAULT_BAT_OVP: val->intval = POWER_SUPPLY_HEALTH_OVERVOLTAGE; break; case FAULT_TS: case FAULT_BAT_TS: val->intval = POWER_SUPPLY_HEALTH_OVERHEAT; break; case FAULT_TIMER: val->intval = POWER_SUPPLY_HEALTH_SAFETY_TIMER_EXPIRE; break; default: val->intval = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE; break; } break; case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT: val->intval = bq24257_ichg_map[bq->init_data.ichg]; break; case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX: val->intval = bq24257_ichg_map[BQ24257_ICHG_MAP_SIZE - 1]; break; case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE: val->intval = bq24257_vbat_map[bq->init_data.vbat]; break; case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE_MAX: val->intval = bq24257_vbat_map[BQ24257_VBAT_MAP_SIZE - 1]; break; case POWER_SUPPLY_PROP_CHARGE_TERM_CURRENT: val->intval = bq24257_iterm_map[bq->init_data.iterm]; break; case POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT: return bq24257_get_input_current_limit(bq, val); default: return -EINVAL; } return 0; } static int bq24257_power_supply_set_property(struct power_supply *psy, enum power_supply_property prop, const union power_supply_propval *val) { struct bq24257_device *bq = power_supply_get_drvdata(psy); switch (prop) { case POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT: return bq24257_set_input_current_limit(bq, val); default: return -EINVAL; } } static int bq24257_power_supply_property_is_writeable(struct power_supply *psy, enum power_supply_property psp) { switch (psp) { case POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT: return true; default: return false; } } static int bq24257_get_chip_state(struct bq24257_device *bq, struct bq24257_state *state) { int ret; ret = bq24257_field_read(bq, F_STAT); if (ret < 0) return ret; state->status = ret; ret = bq24257_field_read(bq, F_FAULT); if (ret < 0) return ret; state->fault = ret; if (bq->pg) state->power_good = !gpiod_get_value_cansleep(bq->pg); else /* * If we have a chip without a dedicated power-good GPIO or * some other explicit bit that would provide this information * assume the power is good if there is no supply related * fault - and not good otherwise. There is a possibility for * other errors to mask that power in fact is not good but this * is probably the best we can do here. */ switch (state->fault) { case FAULT_INPUT_OVP: case FAULT_INPUT_UVLO: case FAULT_INPUT_LDO_LOW: state->power_good = false; break; default: state->power_good = true; } return 0; } static bool bq24257_state_changed(struct bq24257_device *bq, struct bq24257_state *new_state) { int ret; mutex_lock(&bq->lock); ret = (bq->state.status != new_state->status || bq->state.fault != new_state->fault || bq->state.power_good != new_state->power_good); mutex_unlock(&bq->lock); return ret; } enum bq24257_loop_status { LOOP_STATUS_NONE, LOOP_STATUS_IN_DPM, LOOP_STATUS_IN_CURRENT_LIMIT, LOOP_STATUS_THERMAL, }; enum bq24257_in_ilimit { IILIMIT_100, IILIMIT_150, IILIMIT_500, IILIMIT_900, IILIMIT_1500, IILIMIT_2000, IILIMIT_EXT, IILIMIT_NONE, }; enum bq24257_vovp { VOVP_6000, VOVP_6500, VOVP_7000, VOVP_8000, VOVP_9000, VOVP_9500, VOVP_10000, VOVP_10500 }; enum bq24257_vindpm { VINDPM_4200, VINDPM_4280, VINDPM_4360, VINDPM_4440, VINDPM_4520, VINDPM_4600, VINDPM_4680, VINDPM_4760 }; enum bq24257_port_type { PORT_TYPE_DCP, /* Dedicated Charging Port */ PORT_TYPE_CDP, /* Charging Downstream Port */ PORT_TYPE_SDP, /* Standard Downstream Port */ PORT_TYPE_NON_STANDARD, }; enum bq24257_safety_timer { SAFETY_TIMER_45, SAFETY_TIMER_360, SAFETY_TIMER_540, SAFETY_TIMER_NONE, }; static int bq24257_iilimit_autoset(struct bq24257_device *bq) { int loop_status; int iilimit; int port_type; int ret; const u8 new_iilimit[] = { [PORT_TYPE_DCP] = IILIMIT_2000, [PORT_TYPE_CDP] = IILIMIT_2000, [PORT_TYPE_SDP] = IILIMIT_500, [PORT_TYPE_NON_STANDARD] = IILIMIT_500 }; ret = bq24257_field_read(bq, F_LOOP_STATUS); if (ret < 0) goto error; loop_status = ret; ret = bq24257_field_read(bq, F_IILIMIT); if (ret < 0) goto error; iilimit = ret; /* * All USB ports should be able to handle 500mA. If not, DPM will lower * the charging current to accommodate the power source. No need to set * a lower IILIMIT value. */ if (loop_status == LOOP_STATUS_IN_DPM && iilimit == IILIMIT_500) return 0; ret = bq24257_field_read(bq, F_USB_DET); if (ret < 0) goto error; port_type = ret; ret = bq24257_field_write(bq, F_IILIMIT, new_iilimit[port_type]); if (ret < 0) goto error; ret = bq24257_field_write(bq, F_TMR, SAFETY_TIMER_360); if (ret < 0) goto error; ret = bq24257_field_write(bq, F_CLR_VDP, 1); if (ret < 0) goto error; dev_dbg(bq->dev, "port/loop = %d/%d -> iilimit = %d\n", port_type, loop_status, new_iilimit[port_type]); return 0; error: dev_err(bq->dev, "%s: Error communicating with the chip.\n", __func__); return ret; } static void bq24257_iilimit_setup_work(struct work_struct *work) { struct bq24257_device *bq = container_of(work, struct bq24257_device, iilimit_setup_work.work); bq24257_iilimit_autoset(bq); } static void bq24257_handle_state_change(struct bq24257_device *bq, struct bq24257_state *new_state) { int ret; struct bq24257_state old_state; mutex_lock(&bq->lock); old_state = bq->state; mutex_unlock(&bq->lock); /* * Handle BQ2425x state changes observing whether the D+/D- based input * current limit autoset functionality is enabled. */ if (!new_state->power_good) { dev_dbg(bq->dev, "Power removed\n"); if (bq->iilimit_autoset_enable) { cancel_delayed_work_sync(&bq->iilimit_setup_work); /* activate D+/D- port detection algorithm */ ret = bq24257_field_write(bq, F_DPDM_EN, 1); if (ret < 0) goto error; } /* * When power is removed always return to the default input * current limit as configured during probe. */ ret = bq24257_field_write(bq, F_IILIMIT, bq->init_data.iilimit); if (ret < 0) goto error; } else if (!old_state.power_good) { dev_dbg(bq->dev, "Power inserted\n"); if (bq->iilimit_autoset_enable) /* configure input current limit */ schedule_delayed_work(&bq->iilimit_setup_work, msecs_to_jiffies(BQ24257_ILIM_SET_DELAY)); } else if (new_state->fault == FAULT_NO_BAT) { dev_warn(bq->dev, "Battery removed\n"); } else if (new_state->fault == FAULT_TIMER) { dev_err(bq->dev, "Safety timer expired! Battery dead?\n"); } return; error: dev_err(bq->dev, "%s: Error communicating with the chip.\n", __func__); } static irqreturn_t bq24257_irq_handler_thread(int irq, void *private) { int ret; struct bq24257_device *bq = private; struct bq24257_state state; ret = bq24257_get_chip_state(bq, &state); if (ret < 0) return IRQ_HANDLED; if (!bq24257_state_changed(bq, &state)) return IRQ_HANDLED; dev_dbg(bq->dev, "irq(state changed): status/fault/pg = %d/%d/%d\n", state.status, state.fault, state.power_good); bq24257_handle_state_change(bq, &state); mutex_lock(&bq->lock); bq->state = state; mutex_unlock(&bq->lock); power_supply_changed(bq->charger); return IRQ_HANDLED; } static int bq24257_hw_init(struct bq24257_device *bq) { int ret; int i; struct bq24257_state state; const struct { int field; u32 value; } init_data[] = { {F_ICHG, bq->init_data.ichg}, {F_VBAT, bq->init_data.vbat}, {F_ITERM, bq->init_data.iterm}, {F_VOVP, bq->init_data.vovp}, {F_VINDPM, bq->init_data.vindpm}, }; /* * Disable the watchdog timer to prevent the IC from going back to * default settings after 50 seconds of I2C inactivity. */ ret = bq24257_field_write(bq, F_WD_EN, 0); if (ret < 0) return ret; /* configure the charge currents and voltages */ for (i = 0; i < ARRAY_SIZE(init_data); i++) { ret = bq24257_field_write(bq, init_data[i].field, init_data[i].value); if (ret < 0) return ret; } ret = bq24257_get_chip_state(bq, &state); if (ret < 0) return ret; mutex_lock(&bq->lock); bq->state = state; mutex_unlock(&bq->lock); if (!bq->iilimit_autoset_enable) { dev_dbg(bq->dev, "manually setting iilimit = %u\n", bq->init_data.iilimit); /* program fixed input current limit */ ret = bq24257_field_write(bq, F_IILIMIT, bq->init_data.iilimit); if (ret < 0) return ret; } else if (!state.power_good) /* activate D+/D- detection algorithm */ ret = bq24257_field_write(bq, F_DPDM_EN, 1); else if (state.fault != FAULT_NO_BAT) ret = bq24257_iilimit_autoset(bq); return ret; } static enum power_supply_property bq24257_power_supply_props[] = { POWER_SUPPLY_PROP_MANUFACTURER, POWER_SUPPLY_PROP_MODEL_NAME, POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_ONLINE, POWER_SUPPLY_PROP_HEALTH, POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT, POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX, POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE, POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE_MAX, POWER_SUPPLY_PROP_CHARGE_TERM_CURRENT, POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT, }; static char *bq24257_charger_supplied_to[] = { "main-battery", }; static const struct power_supply_desc bq24257_power_supply_desc = { .name = "bq24257-charger", .type = POWER_SUPPLY_TYPE_USB, .properties = bq24257_power_supply_props, .num_properties = ARRAY_SIZE(bq24257_power_supply_props), .get_property = bq24257_power_supply_get_property, .set_property = bq24257_power_supply_set_property, .property_is_writeable = bq24257_power_supply_property_is_writeable, }; static ssize_t bq24257_show_ovp_voltage(struct device *dev, struct device_attribute *attr, char *buf) { struct power_supply *psy = dev_get_drvdata(dev); struct bq24257_device *bq = power_supply_get_drvdata(psy); return sysfs_emit(buf, "%u\n", bq24257_vovp_map[bq->init_data.vovp]); } static ssize_t bq24257_show_in_dpm_voltage(struct device *dev, struct device_attribute *attr, char *buf) { struct power_supply *psy = dev_get_drvdata(dev); struct bq24257_device *bq = power_supply_get_drvdata(psy); return sysfs_emit(buf, "%u\n", bq24257_vindpm_map[bq->init_data.vindpm]); } static ssize_t bq24257_sysfs_show_enable(struct device *dev, struct device_attribute *attr, char *buf) { struct power_supply *psy = dev_get_drvdata(dev); struct bq24257_device *bq = power_supply_get_drvdata(psy); int ret; if (strcmp(attr->attr.name, "high_impedance_enable") == 0) ret = bq24257_field_read(bq, F_HZ_MODE); else if (strcmp(attr->attr.name, "sysoff_enable") == 0) ret = bq24257_field_read(bq, F_SYSOFF); else return -EINVAL; if (ret < 0) return ret; return sysfs_emit(buf, "%d\n", ret); } static ssize_t bq24257_sysfs_set_enable(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct power_supply *psy = dev_get_drvdata(dev); struct bq24257_device *bq = power_supply_get_drvdata(psy); long val; int ret; if (kstrtol(buf, 10, &val) < 0) return -EINVAL; if (strcmp(attr->attr.name, "high_impedance_enable") == 0) ret = bq24257_field_write(bq, F_HZ_MODE, (bool)val); else if (strcmp(attr->attr.name, "sysoff_enable") == 0) ret = bq24257_field_write(bq, F_SYSOFF, (bool)val); else return -EINVAL; if (ret < 0) return ret; return count; } static DEVICE_ATTR(ovp_voltage, S_IRUGO, bq24257_show_ovp_voltage, NULL); static DEVICE_ATTR(in_dpm_voltage, S_IRUGO, bq24257_show_in_dpm_voltage, NULL); static DEVICE_ATTR(high_impedance_enable, S_IWUSR | S_IRUGO, bq24257_sysfs_show_enable, bq24257_sysfs_set_enable); static DEVICE_ATTR(sysoff_enable, S_IWUSR | S_IRUGO, bq24257_sysfs_show_enable, bq24257_sysfs_set_enable); static struct attribute *bq24257_charger_sysfs_attrs[] = { &dev_attr_ovp_voltage.attr, &dev_attr_in_dpm_voltage.attr, &dev_attr_high_impedance_enable.attr, &dev_attr_sysoff_enable.attr, NULL, }; ATTRIBUTE_GROUPS(bq24257_charger_sysfs); static int bq24257_power_supply_init(struct bq24257_device *bq) { struct power_supply_config psy_cfg = { .drv_data = bq, }; psy_cfg.attr_grp = bq24257_charger_sysfs_groups; psy_cfg.supplied_to = bq24257_charger_supplied_to; psy_cfg.num_supplicants = ARRAY_SIZE(bq24257_charger_supplied_to); bq->charger = devm_power_supply_register(bq->dev, &bq24257_power_supply_desc, &psy_cfg); return PTR_ERR_OR_ZERO(bq->charger); } static void bq24257_pg_gpio_probe(struct bq24257_device *bq) { bq->pg = devm_gpiod_get_optional(bq->dev, BQ24257_PG_GPIO, GPIOD_IN); if (PTR_ERR(bq->pg) == -EPROBE_DEFER) { dev_info(bq->dev, "probe retry requested for PG pin\n"); return; } else if (IS_ERR(bq->pg)) { dev_err(bq->dev, "error probing PG pin\n"); bq->pg = NULL; return; } if (bq->pg) dev_dbg(bq->dev, "probed PG pin = %d\n", desc_to_gpio(bq->pg)); } static int bq24257_fw_probe(struct bq24257_device *bq) { int ret; u32 property; /* Required properties */ ret = device_property_read_u32(bq->dev, "ti,charge-current", &property); if (ret < 0) return ret; bq->init_data.ichg = bq24257_find_idx(property, bq24257_ichg_map, BQ24257_ICHG_MAP_SIZE); ret = device_property_read_u32(bq->dev, "ti,battery-regulation-voltage", &property); if (ret < 0) return ret; bq->init_data.vbat = bq24257_find_idx(property, bq24257_vbat_map, BQ24257_VBAT_MAP_SIZE); ret = device_property_read_u32(bq->dev, "ti,termination-current", &property); if (ret < 0) return ret; bq->init_data.iterm = bq24257_find_idx(property, bq24257_iterm_map, BQ24257_ITERM_MAP_SIZE); /* Optional properties. If not provided use reasonable default. */ ret = device_property_read_u32(bq->dev, "ti,current-limit", &property); if (ret < 0) { bq->iilimit_autoset_enable = true; /* * Explicitly set a default value which will be needed for * devices that don't support the automatic setting of the input * current limit through the charger type detection mechanism. */ bq->init_data.iilimit = IILIMIT_500; } else bq->init_data.iilimit = bq24257_find_idx(property, bq24257_iilimit_map, BQ24257_IILIMIT_MAP_SIZE); ret = device_property_read_u32(bq->dev, "ti,ovp-voltage", &property); if (ret < 0) bq->init_data.vovp = VOVP_6500; else bq->init_data.vovp = bq24257_find_idx(property, bq24257_vovp_map, BQ24257_VOVP_MAP_SIZE); ret = device_property_read_u32(bq->dev, "ti,in-dpm-voltage", &property); if (ret < 0) bq->init_data.vindpm = VINDPM_4360; else bq->init_data.vindpm = bq24257_find_idx(property, bq24257_vindpm_map, BQ24257_VINDPM_MAP_SIZE); return 0; } static int bq24257_probe(struct i2c_client *client) { const struct i2c_device_id *id = i2c_client_get_device_id(client); struct i2c_adapter *adapter = client->adapter; struct device *dev = &client->dev; const struct acpi_device_id *acpi_id; struct bq24257_device *bq; int ret; int i; if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA)) { dev_err(dev, "No support for SMBUS_BYTE_DATA\n"); return -ENODEV; } bq = devm_kzalloc(dev, sizeof(*bq), GFP_KERNEL); if (!bq) return -ENOMEM; bq->client = client; bq->dev = dev; if (ACPI_HANDLE(dev)) { acpi_id = acpi_match_device(dev->driver->acpi_match_table, &client->dev); if (!acpi_id) { dev_err(dev, "Failed to match ACPI device\n"); return -ENODEV; } bq->chip = (enum bq2425x_chip)acpi_id->driver_data; } else { bq->chip = (enum bq2425x_chip)id->driver_data; } mutex_init(&bq->lock); bq->rmap = devm_regmap_init_i2c(client, &bq24257_regmap_config); if (IS_ERR(bq->rmap)) { dev_err(dev, "failed to allocate register map\n"); return PTR_ERR(bq->rmap); } for (i = 0; i < ARRAY_SIZE(bq24257_reg_fields); i++) { const struct reg_field *reg_fields = bq24257_reg_fields; bq->rmap_fields[i] = devm_regmap_field_alloc(dev, bq->rmap, reg_fields[i]); if (IS_ERR(bq->rmap_fields[i])) { dev_err(dev, "cannot allocate regmap field\n"); return PTR_ERR(bq->rmap_fields[i]); } } i2c_set_clientdata(client, bq); if (!dev->platform_data) { ret = bq24257_fw_probe(bq); if (ret < 0) { dev_err(dev, "Cannot read device properties.\n"); return ret; } } else { return -ENODEV; } /* * The BQ24250 doesn't support the D+/D- based charger type detection * used for the automatic setting of the input current limit setting so * explicitly disable that feature. */ if (bq->chip == BQ24250) bq->iilimit_autoset_enable = false; if (bq->iilimit_autoset_enable) INIT_DELAYED_WORK(&bq->iilimit_setup_work, bq24257_iilimit_setup_work); /* * The BQ24250 doesn't have a dedicated Power Good (PG) pin so let's * not probe for it and instead use a SW-based approach to determine * the PG state. We also use a SW-based approach for all other devices * if the PG pin is either not defined or can't be probed. */ if (bq->chip != BQ24250) bq24257_pg_gpio_probe(bq); if (PTR_ERR(bq->pg) == -EPROBE_DEFER) return PTR_ERR(bq->pg); else if (!bq->pg) dev_info(bq->dev, "using SW-based power-good detection\n"); /* reset all registers to defaults */ ret = bq24257_field_write(bq, F_RESET, 1); if (ret < 0) return ret; /* * Put the RESET bit back to 0, in cache. For some reason the HW always * returns 1 on this bit, so this is the only way to avoid resetting the * chip every time we update another field in this register. */ ret = bq24257_field_write(bq, F_RESET, 0); if (ret < 0) return ret; ret = bq24257_hw_init(bq); if (ret < 0) { dev_err(dev, "Cannot initialize the chip.\n"); return ret; } ret = bq24257_power_supply_init(bq); if (ret < 0) { dev_err(dev, "Failed to register power supply\n"); return ret; } ret = devm_request_threaded_irq(dev, client->irq, NULL, bq24257_irq_handler_thread, IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING | IRQF_ONESHOT, bq2425x_chip_name[bq->chip], bq); if (ret) { dev_err(dev, "Failed to request IRQ #%d\n", client->irq); return ret; } return 0; } static void bq24257_remove(struct i2c_client *client) { struct bq24257_device *bq = i2c_get_clientdata(client); if (bq->iilimit_autoset_enable) cancel_delayed_work_sync(&bq->iilimit_setup_work); bq24257_field_write(bq, F_RESET, 1); /* reset to defaults */ } #ifdef CONFIG_PM_SLEEP static int bq24257_suspend(struct device *dev) { struct bq24257_device *bq = dev_get_drvdata(dev); int ret = 0; if (bq->iilimit_autoset_enable) cancel_delayed_work_sync(&bq->iilimit_setup_work); /* reset all registers to default (and activate standalone mode) */ ret = bq24257_field_write(bq, F_RESET, 1); if (ret < 0) dev_err(bq->dev, "Cannot reset chip to standalone mode.\n"); return ret; } static int bq24257_resume(struct device *dev) { int ret; struct bq24257_device *bq = dev_get_drvdata(dev); ret = regcache_drop_region(bq->rmap, BQ24257_REG_1, BQ24257_REG_7); if (ret < 0) return ret; ret = bq24257_field_write(bq, F_RESET, 0); if (ret < 0) return ret; ret = bq24257_hw_init(bq); if (ret < 0) { dev_err(bq->dev, "Cannot init chip after resume.\n"); return ret; } /* signal userspace, maybe state changed while suspended */ power_supply_changed(bq->charger); return 0; } #endif static const struct dev_pm_ops bq24257_pm = { SET_SYSTEM_SLEEP_PM_OPS(bq24257_suspend, bq24257_resume) }; static const struct i2c_device_id bq24257_i2c_ids[] = { { "bq24250", BQ24250 }, { "bq24251", BQ24251 }, { "bq24257", BQ24257 }, {}, }; MODULE_DEVICE_TABLE(i2c, bq24257_i2c_ids); static const struct of_device_id bq24257_of_match[] __maybe_unused = { { .compatible = "ti,bq24250", }, { .compatible = "ti,bq24251", }, { .compatible = "ti,bq24257", }, { }, }; MODULE_DEVICE_TABLE(of, bq24257_of_match); #ifdef CONFIG_ACPI static const struct acpi_device_id bq24257_acpi_match[] = { { "BQ242500", BQ24250 }, { "BQ242510", BQ24251 }, { "BQ242570", BQ24257 }, {}, }; MODULE_DEVICE_TABLE(acpi, bq24257_acpi_match); #endif static struct i2c_driver bq24257_driver = { .driver = { .name = "bq24257-charger", .of_match_table = of_match_ptr(bq24257_of_match), .acpi_match_table = ACPI_PTR(bq24257_acpi_match), .pm = &bq24257_pm, }, .probe = bq24257_probe, .remove = bq24257_remove, .id_table = bq24257_i2c_ids, }; module_i2c_driver(bq24257_driver); MODULE_AUTHOR("Laurentiu Palcu <[email protected]>"); MODULE_DESCRIPTION("bq24257 charger driver"); MODULE_LICENSE("GPL");
linux-master
drivers/power/supply/bq24257_charger.c