android_kernel_motorola_sm6225/kernel/power/energy_model.c
Michael Bestas d911a7f189
Merge tag 'ASB-2023-03-05_4.19-stable' of https://android.googlesource.com/kernel/common into android13-4.19-kona
https://source.android.com/docs/security/bulletin/2023-03-01
CVE-2021-33655

* tag 'ASB-2023-03-05_4.19-stable' of https://android.googlesource.com/kernel/common:
  Linux 4.19.275
  USB: core: Don't hold device lock while reading the "descriptors" sysfs file
  USB: serial: option: add support for VW/Skoda "Carstick LTE"
  dmaengine: sh: rcar-dmac: Check for error num after dma_set_max_seg_size
  vc_screen: don't clobber return value in vcs_read
  net: Remove WARN_ON_ONCE(sk->sk_forward_alloc) from sk_stream_kill_queues().
  IB/hfi1: Assign npages earlier
  btrfs: send: limit number of clones and allocated memory size
  ACPI: NFIT: fix a potential deadlock during NFIT teardown
  ARM: dts: rockchip: add power-domains property to dp node on rk3288
  UPSTREAM: selinux: check return value of sel_make_avc_files
  UPSTREAM: lib/test_meminit: destroy cache in kmem_cache_alloc_bulk() test
  UPSTREAM: wireguard: ratelimiter: use kvcalloc() instead of kvzalloc()
  UPSTREAM: wireguard: receive: drop handshakes if queue lock is contended
  UPSTREAM: wireguard: receive: use ring buffer for incoming handshakes
  UPSTREAM: wireguard: device: reset peer src endpoint when netns exits
  UPSTREAM: wireguard: selftests: actually test for routing loops
  UPSTREAM: kasan: fix tag for large allocations when using CONFIG_SLAB
  UPSTREAM: usb: musb: select GENERIC_PHY instead of depending on it
  UPSTREAM: driver core: Reject pointless SYNC_STATE_ONLY device links
  BACKPORT: PM: EM: Fix inefficient states detection
  UPSTREAM: cfg80211: scan: fix RCU in cfg80211_add_nontrans_list()
  UPSTREAM: thermal/core: Fix thermal_cooling_device_register() prototype
  UPSTREAM: PM: EM: Increase energy calculation precision
  UPSTREAM: lib/test_stackinit: Fix static initializer test
  BACKPORT: userfaultfd: do not untag user pointers
  UPSTREAM: net/xfrm/compat: Copy xfrm_spdattr_type_t atributes
  UPSTREAM: sched/uclamp: Ignore max aggregation if rq is idle
  UPSTREAM: net: xfrm: fix memory leak in xfrm_user_rcv_msg
  UPSTREAM: f2fs: Advertise encrypted casefolding in sysfs
  UPSTREAM: fuse: ignore PG_workingset after stealing
  BACKPORT: loop: Fix missing discard support when using LOOP_CONFIGURE
  BACKPORT: nvmem: core: add a missing of_node_put
  UPSTREAM: usb: typec: mux: Fix copy-paste mistake in typec_mux_match
  Linux 4.19.274
  bpf: add missing header file include
  ext4: Fix function prototype mismatch for ext4_feat_ktype
  wifi: mwifiex: Add missing compatible string for SD8787
  uaccess: Add speculation barrier to copy_from_user()
  mac80211: mesh: embedd mesh_paths and mpp_paths into ieee80211_if_mesh
  drm/i915/gvt: fix double free bug in split_2MB_gtt_entry
  alarmtimer: Prevent starvation by small intervals and SIG_IGN
  powerpc: dts: t208x: Disable 10G on MAC1 and MAC2
  can: kvaser_usb: hydra: help gcc-13 to figure out cmd_len
  random: always mix cycle counter in add_latent_entropy()
  powerpc: dts: t208x: Mark MAC1 and MAC2 as 10G
  wifi: rtl8xxxu: gen2: Turn on the rate control
  BACKPORT: fscrypt: fix derivation of SipHash keys on big endian CPUs
  UPSTREAM: wireguard: allowedips: free empty intermediate nodes when removing single node
  BACKPORT: wireguard: allowedips: allocate nodes in kmem_cache
  Linux 4.19.273
  net: phy: meson-gxl: Add generic dummy stubs for MMD register access
  nilfs2: fix underflow in second superblock position calculations
  kvm: initialize all of the kvm_debugregs structure before sending it to userspace
  i40e: Add checking for null for nlmsg_find_attr()
  ipv6: Fix tcp socket connection with DSCP.
  ipv6: Fix datagram socket connection with DSCP.
  net: mpls: fix stale pointer if allocation fails during device rename
  net: stmmac: Restrict warning on disabling DMA store and fwd mode
  bnxt_en: Fix mqprio and XDP ring checking logic
  net: stmmac: fix order of dwmac5 FlexPPS parametrization sequence
  net/usb: kalmia: Don't pass act_len in usb_bulk_msg error path
  dccp/tcp: Avoid negative sk_forward_alloc by ipv6_pinfo.pktoptions.
  net: bgmac: fix BCM5358 support by setting correct flags
  i40e: add double of VLAN header when computing the max MTU
  revert "squashfs: harden sanity check in squashfs_read_xattr_id_table"
  hugetlb: check for undefined shift on 32 bit architectures
  ALSA: hda/realtek - fixed wrong gpio assigned
  ALSA: hda/conexant: add a new hda codec SN6180
  mmc: sdio: fix possible resource leaks in some error paths
  Revert "x86/fpu: Use _Alignof to avoid undefined behavior in TYPE_ALIGN"
  netfilter: nft_tproxy: restrict to prerouting hook
  aio: fix mremap after fork null-deref
  nvme-fc: fix a missing queue put in nvmet_fc_ls_create_association
  net/rose: Fix to not accept on connected socket
  tools/virtio: fix the vringh test for virtio ring changes
  ASoC: cs42l56: fix DT probe
  migrate: hugetlb: check for hugetlb shared PMD in node migration
  bpf: Always return target ifindex in bpf_fib_lookup
  arm64: dts: meson-axg: Make mmc host controller interrupts level-sensitive
  arm64: dts: meson-gx: Make mmc host controller interrupts level-sensitive
  riscv: Fixup race condition on PG_dcache_clean in flush_icache_pte
  usb: typec: altmodes/displayport: Fix probe pin assign check
  usb: core: add quirk for Alcor Link AK9563 smartcard reader
  net: USB: Fix wrong-direction WARNING in plusb.c
  pinctrl: intel: Restore the pins that used to be in Direct IRQ mode
  pinctrl: intel: Convert unsigned to unsigned int
  pinctrl: single: fix potential NULL dereference
  pinctrl: aspeed: Fix confusing types in return value
  ALSA: pci: lx6464es: fix a debug loop
  selftests: forwarding: lib: quote the sysctl values
  rds: rds_rm_zerocopy_callback() use list_first_entry()
  net: phy: meson-gxl: use MMD access dummy stubs for GXL, internal PHY
  net: phy: meson-gxl: add g12a support
  net: phy: add macros for PHYID matching
  IB/hfi1: Restore allocated resources on failed copyout
  ALSA: emux: Avoid potential array out-of-bound in snd_emux_xg_control()
  btrfs: limit device extents to the device size
  iio:adc:twl6030: Enable measurement of VAC
  thermal: intel: int340x: Add locking to int340x_thermal_get_trip_type()
  serial: 8250_dma: Fix DMA Rx rearm race
  serial: 8250_dma: Fix DMA Rx completion race
  Squashfs: fix handling and sanity checking of xattr_ids count
  mm/swapfile: add cond_resched() in get_swap_pages()
  mm: hugetlb: proc: check for hugetlb shared PMD in /proc/PID/smaps
  riscv: disable generation of unwind tables
  parisc: Wire up PTRACE_GETREGS/PTRACE_SETREGS for compat case
  parisc: Fix return code of pdc_iodc_print()
  iio:adc:twl6030: Enable measurements of VUSB, VBAT and others
  iio: adc: berlin2-adc: Add missing of_node_put() in error path
  iio: hid: fix the retval in accel_3d_capture_sample
  efi: Accept version 2 of memory attributes table
  watchdog: diag288_wdt: fix __diag288() inline assembly
  watchdog: diag288_wdt: do not use stack buffers for hardware data
  fbcon: Check font dimension limits
  thermal: intel: int340x: Protect trip temperature from concurrent updates
  KVM: x86/vmx: Do not skip segment attributes if unusable bit is set
  KVM: VMX: Move caching of MSR_IA32_XSS to hardware_setup()
  KVM: VMX: Move VMX specific files to a "vmx" subdirectory
  nVMX x86: Check VMX-preemption timer controls on vmentry of L2 guests
  Input: i8042 - add Clevo PCX0DX to i8042 quirk table
  Input: i8042 - add TUXEDO devices to i8042 quirk tables
  Input: i8042 - merge quirk tables
  Input: i8042 - move __initconst to fix code styling warning
  vc_screen: move load of struct vc_data pointer in vcs_read() to avoid UAF
  usb: gadget: f_fs: Fix unbalanced spinlock in __ffs_ep0_queue_wait
  usb: dwc3: qcom: enable vbus override when in OTG dr-mode
  usb: dwc3: dwc3-qcom: Fix typo in the dwc3 vbus override API
  iio: adc: stm32-dfsdm: fill module aliases
  net/x25: Fix to not accept on connected socket
  i2c: rk3x: fix a bunch of kernel-doc warnings
  scsi: iscsi_tcp: Fix UAF during login when accessing the shost ipaddress
  scsi: target: core: Fix warning on RT kernels
  net: openvswitch: fix flow memory leak in ovs_flow_cmd_new
  ata: libata: Fix sata_down_spd_limit() when no link speed is reported
  squashfs: harden sanity check in squashfs_read_xattr_id_table
  netrom: Fix use-after-free caused by accept on already connected socket
  ALSA: hda/via: Avoid potential array out-of-bound in add_secret_dac_path()
  bus: sunxi-rsb: Fix error handling in sunxi_rsb_init()
  firewire: fix memory leak for payload of request subaction to IEC 61883-1 FCP region
  UPSTREAM: wireguard: allowedips: remove nodes in O(1)
  UPSTREAM: wireguard: allowedips: initialize list head in selftest
  UPSTREAM: wireguard: use synchronize_net rather than synchronize_rcu
  UPSTREAM: wireguard: do not use -O3
  UPSTREAM: wireguard: selftests: make sure rp_filter is disabled on vethc
  BACKPORT: wireguard: selftests: remove old conntrack kconfig value
  BACKPORT: usb: typec: mux: Fix matching with typec_altmode_desc
  UPSTREAM: sched/uclamp: Fix locking around cpu_util_update_eff()
  UPSTREAM: sched/uclamp: Fix wrong implementation of cpu.uclamp.min
  UPSTREAM: usb: musb: Fix an error message
  UPSTREAM: arm64: doc: Add brk/mmap/mremap() to the Tagged Address ABI Exceptions
  BACKPORT: selinux: add proper NULL termination to the secclass_map permissions
  UPSTREAM: crypto: arm/curve25519 - Move '.fpu' after '.arch'
  UPSTREAM: libnvdimm/region: Fix nvdimm_has_flush() to handle ND_REGION_ASYNC
  UPSTREAM: of: property: fw_devlink: do not link ".*,nr-gpios"
  UPSTREAM: xfrm/compat: Cleanup WARN()s that can be user-triggered
  UPSTREAM: wireguard: selftests: test multiple parallel streams
  UPSTREAM: crypto: mips: add poly1305-core.S to .gitignore
  BACKPORT: arm64: kasan: fix page_alloc tagging with DEBUG_VIRTUAL
  UPSTREAM: crypto: mips/poly1305 - enable for all MIPS processors
  UPSTREAM: kbuild: do not include include/config/auto.conf from adjust_autoksyms.sh
  UPSTREAM: wireguard: kconfig: use arm chacha even with no neon
  UPSTREAM: wireguard: queueing: get rid of per-peer ring buffers
  UPSTREAM: wireguard: device: do not generate ICMP for non-IP packets
  BACKPORT: mac80211_hwsim: notify wmediumd of used MAC addresses
  BACKPORT: mac80211_hwsim: add concurrent channels scanning support over virtio
  BACKPORT: perf_event_open: switch to copy_struct_from_user()
  BACKPORT: sched_setattr: switch to copy_struct_from_user()

 Conflicts:
	kernel/power/energy_model.c
	net/wireless/scan.c

Change-Id: I55c29a161fd214642259ddfb19fb749a416babb2
2023-03-07 19:31:08 +02:00

258 lines
6.5 KiB
C

// SPDX-License-Identifier: GPL-2.0
/*
* Energy Model of CPUs
*
* Copyright (c) 2018, Arm ltd.
* Written by: Quentin Perret, Arm ltd.
*/
#define pr_fmt(fmt) "energy_model: " fmt
#include <linux/cpu.h>
#include <linux/cpumask.h>
#include <linux/debugfs.h>
#include <linux/energy_model.h>
#include <linux/sched/topology.h>
#include <linux/slab.h>
/* Mapping of each CPU to the performance domain to which it belongs. */
static DEFINE_PER_CPU(struct em_perf_domain *, em_data);
/*
* Mutex serializing the registrations of performance domains and letting
* callbacks defined by drivers sleep.
*/
static DEFINE_MUTEX(em_pd_mutex);
#ifdef CONFIG_DEBUG_FS
static struct dentry *rootdir;
static void em_debug_create_cs(struct em_cap_state *cs, struct dentry *pd)
{
struct dentry *d;
char name[24];
snprintf(name, sizeof(name), "cs:%lu", cs->frequency);
/* Create per-cs directory */
d = debugfs_create_dir(name, pd);
debugfs_create_ulong("frequency", 0444, d, &cs->frequency);
debugfs_create_ulong("power", 0444, d, &cs->power);
debugfs_create_ulong("cost", 0444, d, &cs->cost);
}
static int em_debug_cpus_show(struct seq_file *s, void *unused)
{
seq_printf(s, "%*pbl\n", cpumask_pr_args(to_cpumask(s->private)));
return 0;
}
DEFINE_SHOW_ATTRIBUTE(em_debug_cpus);
static void em_debug_create_pd(struct em_perf_domain *pd, int cpu)
{
struct dentry *d;
char name[8];
int i;
snprintf(name, sizeof(name), "pd%d", cpu);
/* Create the directory of the performance domain */
d = debugfs_create_dir(name, rootdir);
debugfs_create_file("cpus", 0444, d, pd->cpus, &em_debug_cpus_fops);
/* Create a sub-directory for each capacity state */
for (i = 0; i < pd->nr_cap_states; i++)
em_debug_create_cs(&pd->table[i], d);
}
static int __init em_debug_init(void)
{
/* Create /sys/kernel/debug/energy_model directory */
rootdir = debugfs_create_dir("energy_model", NULL);
return 0;
}
core_initcall(em_debug_init);
#else /* CONFIG_DEBUG_FS */
static void em_debug_create_pd(struct em_perf_domain *pd, int cpu) {}
#endif
static struct em_perf_domain *em_create_pd(cpumask_t *span, int nr_states,
struct em_data_callback *cb)
{
unsigned long power, freq, prev_freq = 0, prev_cost = ULONG_MAX;
int i, ret, cpu = cpumask_first(span);
struct em_cap_state *table;
struct em_perf_domain *pd;
u64 fmax;
if (!cb->active_power)
return NULL;
pd = kzalloc(sizeof(*pd) + cpumask_size(), GFP_KERNEL);
if (!pd)
return NULL;
table = kcalloc(nr_states, sizeof(*table), GFP_KERNEL);
if (!table)
goto free_pd;
/* Build the list of capacity states for this performance domain */
for (i = 0, freq = 0; i < nr_states; i++, freq++) {
/*
* active_power() is a driver callback which ceils 'freq' to
* lowest capacity state of 'cpu' above 'freq' and updates
* 'power' and 'freq' accordingly.
*/
ret = cb->active_power(&power, &freq, cpu);
if (ret) {
pr_err("pd%d: invalid cap. state: %d\n", cpu, ret);
goto free_cs_table;
}
/*
* We expect the driver callback to increase the frequency for
* higher capacity states.
*/
if (freq <= prev_freq) {
pr_err("pd%d: non-increasing freq: %lu\n", cpu, freq);
goto free_cs_table;
}
/*
* The power returned by active_state() is expected to be
* positive, in milli-watts and to fit into 16 bits.
*/
if (!power || power > EM_CPU_MAX_POWER) {
pr_err("pd%d: invalid power: %lu\n", cpu, power);
goto free_cs_table;
}
table[i].power = power;
table[i].frequency = prev_freq = freq;
}
/* Compute the cost of each capacity_state. */
fmax = (u64) table[nr_states - 1].frequency;
for (i = nr_states - 1; i >= 0; i--) {
unsigned long power_res = em_scale_power(table[i].power);
table[i].cost = div64_u64(fmax * power_res,
table[i].frequency);
if (i > 0 && (table[i].cost < table[i - 1].cost) &&
(table[i].power > table[i - 1].power)) {
table[i].cost = table[i - 1].cost;
}
if (table[i].cost >= prev_cost) {
pr_debug("pd%d: EM: OPP:%lu is inefficient\n",
cpu, table[i].frequency);
} else {
prev_cost = table[i].cost;
}
}
pd->table = table;
pd->nr_cap_states = nr_states;
cpumask_copy(to_cpumask(pd->cpus), span);
em_debug_create_pd(pd, cpu);
return pd;
free_cs_table:
kfree(table);
free_pd:
kfree(pd);
return NULL;
}
/**
* em_cpu_get() - Return the performance domain for a CPU
* @cpu : CPU to find the performance domain for
*
* Return: the performance domain to which 'cpu' belongs, or NULL if it doesn't
* exist.
*/
struct em_perf_domain *em_cpu_get(int cpu)
{
return READ_ONCE(per_cpu(em_data, cpu));
}
EXPORT_SYMBOL_GPL(em_cpu_get);
/**
* em_register_perf_domain() - Register the Energy Model of a performance domain
* @span : Mask of CPUs in the performance domain
* @nr_states : Number of capacity states to register
* @cb : Callback functions providing the data of the Energy Model
*
* Create Energy Model tables for a performance domain using the callbacks
* defined in cb.
*
* If multiple clients register the same performance domain, all but the first
* registration will be ignored.
*
* Return 0 on success
*/
int em_register_perf_domain(cpumask_t *span, unsigned int nr_states,
struct em_data_callback *cb)
{
unsigned long cap, prev_cap = 0;
struct em_perf_domain *pd;
int cpu, ret = 0;
if (!span || !nr_states || !cb)
return -EINVAL;
/*
* Use a mutex to serialize the registration of performance domains and
* let the driver-defined callback functions sleep.
*/
mutex_lock(&em_pd_mutex);
for_each_cpu(cpu, span) {
/* Make sure we don't register again an existing domain. */
if (READ_ONCE(per_cpu(em_data, cpu))) {
ret = -EEXIST;
goto unlock;
}
/*
* All CPUs of a domain must have the same micro-architecture
* since they all share the same table.
*/
cap = arch_scale_cpu_capacity(NULL, cpu);
if (prev_cap && prev_cap != cap) {
pr_err("CPUs of %*pbl must have the same capacity\n",
cpumask_pr_args(span));
ret = -EINVAL;
goto unlock;
}
prev_cap = cap;
}
/* Create the performance domain and add it to the Energy Model. */
pd = em_create_pd(span, nr_states, cb);
if (!pd) {
ret = -EINVAL;
goto unlock;
}
for_each_cpu(cpu, span) {
/*
* The per-cpu array can be read concurrently from em_cpu_get().
* The barrier enforces the ordering needed to make sure readers
* can only access well formed em_perf_domain structs.
*/
smp_store_release(per_cpu_ptr(&em_data, cpu), pd);
}
pr_debug("Created perf domain %*pbl\n", cpumask_pr_args(span));
unlock:
mutex_unlock(&em_pd_mutex);
return ret;
}
EXPORT_SYMBOL_GPL(em_register_perf_domain);