Files
android_kernel_fxtec_sm6115/kernel/taskstats.c
Thomas Turner b49f61e801 Merge tag 'v4.19.325-cip134' of https://git.kernel.org/pub/scm/linux/kernel/git/cip/linux-cip into android13-4.19-kona
version 4.19.325-cip134

* tag 'v4.19.325-cip134' of https://git.kernel.org/pub/scm/linux/kernel/git/cip/linux-cip:
  CIP: Bump version suffix to -cip134 after merge from cip/linux-4.19.y-st tree
  Update localversion-st, tree is up-to-date with 5.10.258.
  tipc: fix double-free in tipc_buf_append()
  slip: reject VJ receive packets on instances with no rstate array
  netfilter: nfnetlink_osf: fix potential NULL dereference in ttl check
  wifi: brcmfmac: Fix error pointer dereference
  bpf: fix end-of-list detection in cgroup_storage_get_next_key()
  crypto: ccp - copy IV using skcipher ivsize
  netfilter: ipset: stop hash:* range iteration at end
  net/sched: netem: fix queue limit check to include reordered packets
  cdrom, scsi: sr: propagate read-only status to block layer via set_disk_ro()
  btrfs: fix double-decrement of bytes_may_use in submit_one_async_extent()
  crypto: authencesn - reject short ahash digests during instance creation
  crypto: ccp: Don't attempt to copy PDH cert to userspace if PSP command failed
  crypto: ccp: Don't attempt to copy CSR to userspace if PSP command failed
  x86/uprobes: Fix XOL allocation failure for 32-bit tasks
  blk-mq: use quiesced elevator switch when reinitializing queues
  scsi: ufs: core: Improve SCSI abort handling
  bcache: fix cached_dev.sb_bio use-after-free and crash
  rxrpc: proc: size address buffers for %pISpc output
  can: raw: fix ro->uniq use-after-free in raw_rcv()
  can: af_can: export can_sock_destruct()
  batman-adv: hold claim backbone gateways by reference
  l2tp: Drop large packets with UDP encap
  xsk: tighten UMEM headroom validation to account for tailroom and min frame
  can: mcp251x: add error handling for power enable in open and resume
  net: skbuff: propagate shared-frag marker through frag-transfer helpers
  Revert "i2c: fsi: Fix a potential leak in fsi_i2c_probe()"
  net: usb: lan78xx: Fix double free issue with interrupt buffer allocation
  string: add mem_is_zero() helper to check if memory area is all zeros
  tracing: Avoid NULL return from hist_field_name() on truncation
  platform/x86: intel-hid: Check ACPI_HANDLE() against NULL
  HID: quirks: really enable the intended work around for appledisplay
  net: ethernet: cs89x0: remove stale CONFIG_MACH_MX31ADS reference
  net: ethernet: cortina: Carry over frag counter
  net: ethernet: cortina: Drop half-assembled SKB
  net: ethernet: cortina: Make RX SKB per-port
  irqchip/ath79-cpu: Remove unused function
  ARM: integrator: Fix early initialization
  batman-adv: tt: fix negative tt_buff_len
  batman-adv: tt: fix negative last_changeset_len
  batman-adv: tp_meter: avoid use of uninit sender vars
  batman-adv: bla: fix report_work leak on backbone_gw purge
  batman-adv: frag: disallow unicast fragment in fragment
  batman-adv: fix tp_meter counter underflow during shutdown
  batman-adv: fix fragment reassembly length accounting
  batman-adv: dat: handle forward allocation error
  batman-adv: clear current gateway during teardown
  batman-adv: mcast: fix use-after-free in orig_node RCU release
  drm/amd/display: Fix integer overflow in bios_get_image()
  spi: ti-qspi: fix use-after-free after DMA setup failure
  scsi: isci: Fix use-after-free in device removal path
  tracing: Do not call map->ops->elt_free() if elt_alloc() fails
  ixgbevf: fix use-after-free in VEPA multicast source pruning
  ipv4: raw: reject IP_HDRINCL packets with ihl < 5
  vsock/vmci: fix UAF when peer resets connection during handshake
  netfilter: ip6t_hbh: reject oversized option lists
  net: bcmgenet: keep RBUF EEE/PM disabled
  phonet/pep: disable BH around forwarded sk_receive_skb()
  Bluetooth: hci_uart: fix UAFs and race conditions in close and init paths
  Bluetooth: bnep: Fix UAF read of dev->name
  ALSA: asihpi: Fix potential OOB array access at reading cache
  ALSA: ua101: Reject too-short USB descriptors
  sysfs: don't remove existing directory on update failure
  smb: client: reject userspace cifs.spnego descriptions
  Revert "s390/cio: Fix device lifecycle handling in css_alloc_subchannel()"
  selftests: lib.mk: Also install "config" and "settings"
  s390/debug: Reject zero-length input before trimming a newline
  net/rds: reset op_nents when zerocopy page pin fails
  drm/gma500/oaktrail_hdmi: fix i2c adapter leak on setup
  libceph: Fix potential out-of-bounds access in crush_decode()
  libceph: Fix potential null-ptr-deref in decode_choose_args()
  powerpc/warp: Fix error handling in pika_dtm_thread
  ceph: fix a buffer leak in __ceph_setxattr()
  ALSA: usb-audio: Bound MIDI endpoint descriptor scans
  audit: enforce AUDIT_LOCKED for AUDIT_TRIM and AUDIT_MAKE_EQUIV
  audit: fix incorrect inheritable capability in CAPSET records
  crypto: af_alg - Cap AEAD AD length to 0x80000000
  btrfs: tracepoints: fix sleep while in atomic context in btrfs_sync_file()
  drm/amd/display: Read EDID from VBIOS embedded panel info
  drm/amd/display: Allow DCE link encoder without AUX registers
  net/sched: sch_cake: annotate data-races in cake_dump_stats() (V)
  sctp: discard stale INIT after handshake completion
  ASoC: codecs: ab8500: Fix casting of private data
  NFC: trf7970a: Ignore antenna noise when checking for RF field
  net: usb: rtl8150: free skb on usb_submit_urb() failure in xmit
  net: usb: rtl8150: fix use-after-free in rtl8150_start_xmit()
  vrf: Fix a potential NPD when removing a port from a VRF
  net/sched: sch_choke: annotate data-races in choke_dump_stats()
  net: sched: choke: remove unused variables in struct choke_sched_data
  net/sched: netem: validate slot configuration
  net/sched: netem: fix probability gaps in 4-state loss model
  net: sched: sch_netem: Refactor code in 4-state loss generator
  scsi: sr: Add memory allocation failure handling for get_capabilities()
  netfilter: nf_conntrack_sip: don't use simple_strtoul
  netfilter: xt_policy: fix strict mode inbound policy matching
  drm/amdgpu/gfx6: Support harvested SI chips with disabled TCCs (v2)
  netfilter: arp_tables: fix IEEE1394 ARP payload parsing
  tracing: branch: Fix inverted check on stat tracer registration
  mailbox: mailbox-test: initialize struct earlier
  mailbox: mailbox-test: don't free the reused channel
  mailbox: add sanity check for channel array
  cgroup/rdma: fix integer overflow in rdmacg_try_charge()
  mailbox: mailbox-test: free channels on probe error
  fbdev: offb: fix PCI device reference leak on probe failure
  net/sched: sch_sfb: annotate data-races in sfb_dump_stats()
  net/sched: sch_fq_codel: remove data-races from fq_codel_dump_stats()
  net_sched: sch_hhf: annotate data-races in hhf_dump_stats()
  net/rds: zero per-item info buffer before handing it to visitors
  slip: bound decode() reads against the compressed packet length
  netfilter: nfnetlink_osf: fix out-of-bounds read on option matching
  ipvs: fix MTU check for GSO packets in tunnel mode
  netfilter: xtables: restrict several matches to inet family
  netfilter: conntrack: remove sprintf usage
  netfilter: nfnetlink_osf: fix divide-by-zero in OSF_WSS_MODULO
  netfilter: nft_osf: restrict it to ipv4
  openvswitch: cap upcall PID array size and pre-size vport replies
  dissector: do not set invalid PPP protocol
  sctp: fix OOB write to userspace in sctp_getsockopt_peer_auth_chunks
  ipv6: fix possible UAF in icmpv6_rcv()
  e1000e: Unroll PTP in probe error handling
  i40e: don't advertise IFF_SUPP_NOFCS
  PCMCIA: Fix garbled log messages for KERN_CONT
  clk: xgene: Fix mapping leak in xgene_pllclk_init()
  clk: qoriq: avoid format string warning
  clk: imx: imx6q: Fix device node reference leak in of_assigned_ldb_sels()
  scsi: target: core: Fix integer overflow in UNMAP bounds check
  scsi: sg: Resolve soft lockup issue when opening /dev/sgX
  RDMA/core: Prefer NLA_NUL_STRING
  nfs/blocklayout: Fix compilation error (`make W=1`) in bl_write_pagelist()
  mfd: mc13xxx-core: Fix memory leak in mc13xxx_add_subdevice_pdata()
  tty: hvc_iucv: fix off-by-one in number of supported devices
  tty: hvc: remove HVC_IUCV_MAGIC
  platform/surface: surfacepro3_button: Drop wakeup source on remove
  driver core: device.h: remove extern from function prototypes
  perf util: Kill die() prototype, dead for a long time
  pinctrl: abx500: Fix type of 'argument' variable
  pinctrl: pinctrl-pic32: Fix resource leak
  bpf: Fix precedence bug in convert_bpf_ld_abs alignment check
  HID: usbhid: fix deadlock in hid_post_reset()
  mtd: rawnand: sunxi: fix sunxi_nfc_hw_ecc_read_extra_oob
  HID: asus: do not abort probe when not necessary
  HID: asus: make asus_resume adhere to linux kernel coding standards
  ima: check return value of crypto_shash_final() in boot aggregate
  tracing: Rebuild full_name on each hist_field_name() call
  ocfs2: validate group add input before caching
  ocfs2: validate bg_bits during freefrag scan
  ocfs2: fix listxattr handling when the buffer is full
  ocfs2/dlm: fix off-by-one in dlm_match_regions() region comparison
  ocfs2/dlm: validate qr_numregions in dlm_match_regions()
  memory: tegra124-emc: Fix dll_change check
  ARM: dts: mediatek: mt7623: fix efuse fallback compatible
  efi/capsule-loader: fix incorrect sizeof in phys array reallocation
  quota: Fix race of dquot_scan_active() with quota deactivation
  ktest: Honor empty per-test option overrides
  ktest: Avoid undef warning when WARNINGS_FILE is unset
  selftest: memcg: skip memcg_sock test if address family not supported
  Documentation: fix a hugetlbfs reservation statement
  ALSA: hda/realtek: fix code style (ERROR: else should follow close brace '}')
  ALSA: hda/realtek: Whitespace fix
  drm/amd/pm/ci: Clear EnabledForActivity field for memory levels
  drm/amd/pm/ci: Fix powertune defaults for Hawaii 0x67B0
  drm/amd/pm/ci: Use highest MCLK on CI when MCLK DPM is disabled
  ALSA: core: Validate compress device numbers without dynamic minors
  ALSA: compress: Drop unused functions
  fbdev: matroxfb: Mark variable with __maybe_unused to avoid W=1 build break
  drm/sun4i: Fix resource leaks
  dm log: fix out-of-bounds write due to region_count overflow
  dm cache metadata: fix memory leak on metadata abort retry
  dm cache: fix concurrent write failure in passthrough mode
  dm cache policy smq: fix missing locks in invalidating cache blocks
  dm cache: fix write path cache coherency in passthrough mode
  dm cache: fix null-deref with concurrent writes in passthrough mode
  ASoC: sti: use managed regmap_field allocations
  ASoC: sti: Return errors from regmap_field_alloc()
  Bluetooth: hci_ldisc: Clear HCI_UART_PROTO_INIT on error
  Bluetooth: L2CAP: Fix printing wrong information if SDU length exceeds MTU
  ppp: require CAP_NET_ADMIN in target netns for unattached ioctls
  net/rds: Optimize rds_ib_laddr_check
  net: hamradio: 6pack: fix uninit-value in sixpack_receive_buf
  6pack: propagage new tty types
  netfilter: nft_fwd_netdev: check ttl/hl before forwarding
  net: bcmgenet: fix off-by-one in bcmgenet_put_txcb
  wifi: rtlwifi: pci: fix possible use-after-free caused by unfinished irq_prepare_bcn_tasklet
  firmware: dmi: Correct an indexing error in dmi.h
  locking: Fix rwlock support in <linux/spinlock_up.h>
  irqchip/irq-pic32-evic: Address warning related to wrong printf() formatter
  thermal/drivers/spear: Fix error condition for reading st,thermal-flags
  pstore/ram: fix resource leak when ioremap() fails
  nilfs2: reject zero bd_oblocknr in nilfs_ioctl_mark_blocks_dirty()
  drbd: Balance RCU calls in drbd_adm_dump_devices()
  fs/omfs: reject s_sys_blocksize smaller than OMFS_DIR_START
  Bluetooth: L2CAP: Fix null-ptr-deref in l2cap_sock_get_sndtimeo_cb()
  batman-adv: bla: put backbone reference on failed claim hash insert
  batman-adv: bla: only purge non-released claims
  batman-adv: bla: prevent use-after-free when deleting claims
  batman-adv: reject new tp_meter sessions during teardown
  batman-adv: fix integer overflow on buff_pos
  sctp: revalidate list cursor after sctp_sendmsg_to_asoc() in SCTP_SENDALL
  drm/amdgpu/pm: align Hawaii mclk workaround with radeon
  drm/amdgpu/pm: add missing revision check for CI
  drm/amdgpu/sdma4: replace BUG_ON with WARN_ON in fence emission
  drm/amdgpu/gfx9: drop unnecessary 64-bit fence flag check in KIQ
  drm/radeon: add missing revision check for CI
  spi: mpc52xx: fix use-after-free on unbind
  media: dib8000: avoid division by 0 in dib8000_set_dds()
  media: rc: streamzap: Error handling in probe
  media: uvcvideo: Enable VB2_DMABUF for metadata stream
  RDMA/rxe: Reject unknown opcodes before ICRC processing
  RDMA/ocrdma: Don't NULL deref uctx on errors in ocrdma_copy_pd_uresp()
  power: supply: max17042: avoid overflow when determining health
  PCI/AER: Stop ruling out unbound devices as error source
  s390/debug: Reject zero-length input in debug_input_flush_fn()
  nvmet: avoid recursive nvmet-wq flush in nvmet_ctrl_free
  md/raid10: fix divide-by-zero in setup_geo() with zero far_copies
  isofs: validate block number from NFS file handle in isofs_export_iget
  isofs: validate Rock Ridge CE continuation extent against volume size
  dm-verity-fec: correctly reject too-small hash devices
  dm-verity-fec: correctly reject too-small FEC devices
  dm: fix a buffer overflow in ioctl processing
  dm: don't report warning when doing deferred remove
  cpuidle: powerpc: avoid double clear when breaking snooze
  spi: topcliff-pch: fix use-after-free on unbind
  udf: reject descriptors with oversized CRC length
  ibmveth: Disable GSO for packets with small MSS
  parisc: Fix IRQ leak in LASI driver
  net/rds: handle zerocopy send cleanup before the message is queued
  ip6_gre: Use cached t->net in ip6erspan_changelink().
  sound: ua101: fix division by zero at probe
  Bluetooth: L2CAP: Fix null-ptr-deref in l2cap_sock_state_change_cb()
  Bluetooth: L2CAP: Fix null-ptr-deref in l2cap_sock_new_connection_cb()
  usb: ulpi: fix memory leak on ulpi_register() error paths
  USB: serial: option: add Telit Cinterion LE910Cx compositions
  USB: omap_udc: DMA: Don't enable burst 4 mode
  ALSA: usb-audio: Fix UAC3 cluster descriptor size check
  ALSA: usb-audio: Avoid potential endless loop in convert_chmap_v3()
  usb: usblp: fix uninitialized heap leak via LPGETSTATUS ioctl
  usb: usblp: fix heap leak in IEEE 1284 device ID via short response
  wifi: b43: enforce bounds check on firmware key index in b43_rx()
  wifi: ath5k: do not access array OOB
  wifi: rsi: fix kthread lifetime race between self-exit and external-stop
  wifi: b43legacy: enforce bounds check on firmware key index in RX path
  ipmi:ssif: NULL thread on error
  ipmi:ssif: Remove unnecessary indention
  ipmi:ssif: Clean up kthread on errors
  ipmi:ssif: Fix a shutdown race
  net/sched: sch_red: Replace direct dequeue call with peek and qdisc_dequeue_peeked
  fbdev: udlfb: add vm_ops to dlfb_ops_mmap to prevent use-after-free
  ipmi:si: Return state to normal if message allocation fails
  ipmi: Check event message buffer response for bad data
  ipmi: Add limits to event and receive message requests
  scsi: target: configfs: Bound snprintf() return in tg_pt_gp_members_show()
  ALSA: caiaq: fix usb_dev refcount leak on probe failure
  ALSA: caiaq: Don't abort when no input device is available
  ALSA: caiaq: Fix potentially leftover ep1_in_urb at error path
  dm mirror: fix integer overflow in create_dirty_log()
  crypto: atmel-tdes - fix DMA sync direction
  crypto: ccree - fix a memory leak in cc_mac_digest()
  crypto: hisilicon - Fix dma_unmap_single() direction
  crypto: atmel-ecc - Release client on allocation failure
  crypto: atmel-aes - Fix 3-page memory leak in atmel_aes_buff_cleanup
  taskstats: set version in TGID exit notifications
  inotify: fix watch count leak when fsnotify_add_inode_mark_locked() fails
  md/raid5: validate payload size before accessing journal metadata
  md/raid5: fix soft lockup in retry_aligned_read()
  ext4: fix missing brelse() in ext4_xattr_inode_dec_ref_all()
  userfaultfd: allow registration of ranges below mmap_min_addr
  tpm: tpm_tis: add error logging for data transfer
  mmc: block: use single block write in retry
  RDMA/rxe: Validate pad and ICRC before payload_size() in rxe_rcv
  ALSA: 6fire: Fix input volume change detection
  ALSA: caiaq: Handle probe errors properly
  ALSA: caiaq: Fix control_put() result and cache rollback
  ALSA: seq_oss: return full count for successful SEQ_FULLSIZE writes
  ALSA: ctxfi: Add fallback to default RSR for S/PDIF
  lib/ts_kmp: fix integer overflow in pattern length calculation
  Revert "ALSA: usb: Increase volume range that triggers a warning"
  net: strparser: fix skb_head leak in strp_abort_strp()
  net: caif: clear client service pointer on teardown
  ALSA: control: Validate buf_len before strnlen() in snd_ctl_elem_init_enum_names()
  crypto: pcrypt - Fix handling of MAY_BACKLOG requests
  um: drivers: call kernel_strrchr() explicitly in cow_user.c
  firmware: google: framebuffer: Do not mark framebuffer as busy
  ibmasm: fix heap over-read in ibmasm_send_i2o_message()
  ibmasm: fix OOB reads in command_file_write due to missing size checks
  misc: ibmasm: fix OOB MMIO read in ibmasm_handle_mouse_interrupt()
  ALSA: usb-audio: Fix Audio Advantage Micro II SPDIF switch
  ALSA: usb-audio: Avoid false E-MU sample-rate notifications
  ALSA: usb-audio: stop parsing UAC2 rates at MAX_NR_RATES
  rxrpc: Fix missing validation of ticket length in non-XDR key preparsing
  ALSA: caiaq: take a reference on the USB device in create_card()
  ALSA: usb-audio: apply quirk for MOONDROP JU Jiu
  rxrpc: Fix anonymous key handling
  scripts/dtc: Remove unused dts_version in dtc-lexer.l
  gfs2: Validate i_depth for exhash directories
  mm: blk-cgroup: fix use-after-free in cgwb_release_workfn()
  ocfs2: fix possible deadlock between unlink and dio_end_io_write
  fs/ocfs2: fix comments mentioning i_mutex
  rxrpc: reject undecryptable rxkad response tickets
  ocfs2: fix out-of-bounds write in ocfs2_write_end_inline
  ocfs2: validate inline data i_size during inode read
  ocfs2: add inline inode consistency check to ocfs2_validate_inode_block()
  xfrm: clear trailing padding in build_polexpire()
  rxrpc: fix reference count leak in rxrpc_server_keyring()
  mailbox: Prevent out-of-bounds access in of_mbox_index_xlate()
  wifi: mac80211: always free skb on ieee80211_tx_prepare_skb() failure
  ipv6: add NULL checks for idev in SRv6 paths
  net: tap: NULL pointer derefence in dev_parse_header_protocol when skb->dev is null
  media: hackrf: fix to not free memory after the device is registered in hackrf_probe()
  nilfs2: fix NULL i_assoc_inode dereference in nilfs_mdt_save_to_shadow_map
  media: as102: fix to not free memory after the device is registered in as102_usb_probe()
  ALSA: 6fire: fix use-after-free on disconnect
  media: em28xx: fix use-after-free in em28xx_v4l2_open()
  mm/kasan: fix double free for kasan pXds
  KVM: x86: Use scratch field in MMIO fragment to hold small write values
  media: uvcvideo: Allow extra entities
  Revert "wifi: cfg80211: stop NAN and P2P in cfg80211_leave"
  rxrpc: Fix call removal to use RCU safe deletion
  ACPI: property: Constify stubs for CONFIG_ACPI=n case
  ocfs2: handle invalid dinode in ocfs2_group_extend
  ocfs2: fix use-after-free in ocfs2_fault() when VM_FAULT_RETRY
  ALSA: ctxfi: Limit PTP to a single page
  USB: serial: option: add Telit Cinterion FN990A MBIM composition
  fbdev: udlfb: avoid divide-by-zero on FBIOPUT_VSCREENINFO
  usb: storage: Expand range of matched versions for VL817 quirks entry
  usbip: validate number_of_packets in usbip_pack_ret_submit()
  usb: gadget: renesas_usb3: validate endpoint index in standard request handlers
  usb: gadget: f_phonet: fix skb frags[] overflow in pn_rx_complete()
  usb: gadget: f_ncm: validate minimum block_len in ncm_unwrap_ntb()
  fbdev: tdfxfb: avoid divide-by-zero on FBIOPUT_VSCREENINFO
  ALSA: fireworks: bound device-supplied status before string array lookup
  NFC: digital: Bounds check NFC-A cascade depth in SDD response handler
  net: usb: cdc-phonet: fix skb frags[] overflow in rx_complete()
  HID: core: clamp report_size in s32ton() to avoid undefined shift
  HID: alps: fix NULL pointer dereference in alps_raw_event()
  staging: rtl8723bs: initialize le_tmp64 in rtw_BIP_verify()
  i2c: s3c24xx: check the size of the SMBUS message before using it
  nfc: llcp: add missing return after LLCP_CLOSED checks
  MIPS: mm: Suppress TLB uniquification on EHINV hardware
  af_unix: read UNIX_DIAG_VFS data under unix_state_lock
  netfilter: ip6t_eui64: reject invalid MAC header for all packets
  netfilter: xt_multiport: validate range encoding in checkentry
  netfilter: nfnetlink_log: initialize nfgenmsg in NLMSG_DONE terminator
  xfrm_user: fix info leak in build_mapping()
  e1000: check return value of e1000_read_eeprom
  net: lapbether: replace comparison to NULL with "lapbeth_get_x25_dev"
  net: lapbether: Close the LAPB device before its underlying Ethernet device closes
  net: sched: act_csum: validate nested VLAN headers
  drm/vc4: Protect madv read in vc4_gem_object_mmap() with madv_lock
  drm/vc4: Fix a memory leak in hang state error path
  drm/vc4: Fix memory leak of BO array in hang state
  ASoC: stm32_sai: fix incorrect BCLK polarity for DSP_A/B, LEFT_J
  wifi: brcmfmac: validate bsscfg indices in IF events
  ata: ahci: force 32-bit DMA for JMicron JMB582/JMB585
  HID: roccat: fix use-after-free in roccat_report_event
  HID: quirks: add HID_QUIRK_ALWAYS_POLL for 8BitDo Pro 3
  wifi: wl1251: validate packet IDs before indexing tx_frames
  btrfs: tracepoints: get correct superblock from dentry in event btrfs_sync_file()
  ALSA: asihpi: avoid write overflow check warning
  net: skbuff: preserve shared-frag marker during coalescing

Change-Id: I535ecdb1a77312a12564125fedb9f99b3a5533d1
2026-07-09 22:06:07 +01:00

1079 lines
25 KiB
C

/*
* taskstats.c - Export per-task statistics to userland
*
* Copyright (C) Shailabh Nagar, IBM Corp. 2006
* (C) Balbir Singh, IBM Corp. 2006
*
* 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; either version 2 of the License, or
* (at your option) any later version.
*
* 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.
*
*/
#include <linux/kernel.h>
#include <linux/taskstats_kern.h>
#include <linux/tsacct_kern.h>
#include <linux/delayacct.h>
#include <linux/cpumask.h>
#include <linux/percpu.h>
#include <linux/slab.h>
#include <linux/swap.h>
#include <linux/vmalloc.h>
#include <linux/cgroupstats.h>
#include <linux/sysstats.h>
#include <linux/cgroup.h>
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/pid_namespace.h>
#include <net/genetlink.h>
#include <linux/atomic.h>
#include <linux/sched/cputime.h>
#include <linux/oom.h>
/*
* Maximum length of a cpumask that can be specified in
* the TASKSTATS_CMD_ATTR_REGISTER/DEREGISTER_CPUMASK attribute
*/
#define TASKSTATS_CPUMASK_MAXLEN (100+6*NR_CPUS)
static DEFINE_PER_CPU(__u32, taskstats_seqnum);
static int family_registered;
struct kmem_cache *taskstats_cache;
static struct genl_family family;
static const struct nla_policy taskstats_cmd_get_policy[TASKSTATS_CMD_ATTR_MAX+1] = {
[TASKSTATS_CMD_ATTR_PID] = { .type = NLA_U32 },
[TASKSTATS_CMD_ATTR_TGID] = { .type = NLA_U32 },
[TASKSTATS_CMD_ATTR_REGISTER_CPUMASK] = { .type = NLA_STRING },
[TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK] = { .type = NLA_STRING },
[TASKSTATS_CMD_ATTR_FOREACH] = { .type = NLA_U32 },};
/*
* We have to use TASKSTATS_CMD_ATTR_MAX here, it is the maxattr in the family.
* Make sure they are always aligned.
*/
static const struct nla_policy cgroupstats_cmd_get_policy[TASKSTATS_CMD_ATTR_MAX+1] = {
[CGROUPSTATS_CMD_ATTR_FD] = { .type = NLA_U32 },
};
static const struct nla_policy
sysstats_cmd_get_policy[TASKSTATS_CMD_ATTR_MAX+1] = {
[SYSSTATS_CMD_ATTR_SYSMEM_STATS] = { .type = NLA_U32 },
};
struct listener {
struct list_head list;
pid_t pid;
char valid;
};
struct listener_list {
struct rw_semaphore sem;
struct list_head list;
};
static DEFINE_PER_CPU(struct listener_list, listener_array);
struct tgid_iter {
unsigned int tgid;
struct task_struct *task;
};
enum actions {
REGISTER,
DEREGISTER,
CPU_DONT_CARE
};
static int prepare_reply(struct genl_info *info, u8 cmd, struct sk_buff **skbp,
size_t size)
{
struct sk_buff *skb;
void *reply;
/*
* If new attributes are added, please revisit this allocation
*/
skb = genlmsg_new(size, GFP_KERNEL);
if (!skb)
return -ENOMEM;
if (!info) {
int seq = this_cpu_inc_return(taskstats_seqnum) - 1;
reply = genlmsg_put(skb, 0, seq, &family, 0, cmd);
} else
reply = genlmsg_put_reply(skb, info, &family, 0, cmd);
if (reply == NULL) {
nlmsg_free(skb);
return -EINVAL;
}
*skbp = skb;
return 0;
}
/*
* Send taskstats data in @skb to listener with nl_pid @pid
*/
static int send_reply(struct sk_buff *skb, struct genl_info *info)
{
struct genlmsghdr *genlhdr = nlmsg_data(nlmsg_hdr(skb));
void *reply = genlmsg_data(genlhdr);
genlmsg_end(skb, reply);
return genlmsg_reply(skb, info);
}
/*
* Send taskstats data in @skb to listeners registered for @cpu's exit data
*/
static void send_cpu_listeners(struct sk_buff *skb,
struct listener_list *listeners)
{
struct genlmsghdr *genlhdr = nlmsg_data(nlmsg_hdr(skb));
struct listener *s, *tmp;
struct sk_buff *skb_next, *skb_cur = skb;
void *reply = genlmsg_data(genlhdr);
int rc, delcount = 0;
genlmsg_end(skb, reply);
rc = 0;
down_read(&listeners->sem);
list_for_each_entry(s, &listeners->list, list) {
skb_next = NULL;
if (!list_is_last(&s->list, &listeners->list)) {
skb_next = skb_clone(skb_cur, GFP_KERNEL);
if (!skb_next)
break;
}
rc = genlmsg_unicast(&init_net, skb_cur, s->pid);
if (rc == -ECONNREFUSED) {
s->valid = 0;
delcount++;
}
skb_cur = skb_next;
}
up_read(&listeners->sem);
if (skb_cur)
nlmsg_free(skb_cur);
if (!delcount)
return;
/* Delete invalidated entries */
down_write(&listeners->sem);
list_for_each_entry_safe(s, tmp, &listeners->list, list) {
if (!s->valid) {
list_del(&s->list);
kfree(s);
}
}
up_write(&listeners->sem);
}
static void fill_stats(struct user_namespace *user_ns,
struct pid_namespace *pid_ns,
struct task_struct *tsk, struct taskstats *stats)
{
memset(stats, 0, sizeof(*stats));
/*
* Each accounting subsystem adds calls to its functions to
* fill in relevant parts of struct taskstsats as follows
*
* per-task-foo(stats, tsk);
*/
delayacct_add_tsk(stats, tsk);
/* fill in basic acct fields */
stats->version = TASKSTATS_VERSION;
stats->nvcsw = tsk->nvcsw;
stats->nivcsw = tsk->nivcsw;
bacct_add_tsk(user_ns, pid_ns, stats, tsk);
/* fill in extended acct fields */
xacct_add_tsk(stats, tsk);
}
static int fill_stats_for_pid(pid_t pid, struct taskstats *stats)
{
struct task_struct *tsk;
tsk = find_get_task_by_vpid(pid);
if (!tsk)
return -ESRCH;
fill_stats(current_user_ns(), task_active_pid_ns(current), tsk, stats);
put_task_struct(tsk);
return 0;
}
static int fill_stats_for_tgid(pid_t tgid, struct taskstats *stats)
{
struct task_struct *tsk, *first;
unsigned long flags;
int rc = -ESRCH;
u64 delta, utime, stime;
u64 start_time;
/*
* Add additional stats from live tasks except zombie thread group
* leaders who are already counted with the dead tasks
*/
rcu_read_lock();
first = find_task_by_vpid(tgid);
if (!first || !lock_task_sighand(first, &flags))
goto out;
if (first->signal->stats)
memcpy(stats, first->signal->stats, sizeof(*stats));
else
memset(stats, 0, sizeof(*stats));
tsk = first;
start_time = ktime_get_ns();
do {
if (tsk->exit_state)
continue;
/*
* Accounting subsystem can call its functions here to
* fill in relevant parts of struct taskstsats as follows
*
* per-task-foo(stats, tsk);
*/
delayacct_add_tsk(stats, tsk);
/* calculate task elapsed time in nsec */
delta = start_time - tsk->start_time;
/* Convert to micro seconds */
do_div(delta, NSEC_PER_USEC);
stats->ac_etime += delta;
task_cputime(tsk, &utime, &stime);
stats->ac_utime += div_u64(utime, NSEC_PER_USEC);
stats->ac_stime += div_u64(stime, NSEC_PER_USEC);
stats->nvcsw += tsk->nvcsw;
stats->nivcsw += tsk->nivcsw;
} while_each_thread(first, tsk);
unlock_task_sighand(first, &flags);
rc = 0;
out:
rcu_read_unlock();
stats->version = TASKSTATS_VERSION;
/*
* Accounting subsystems can also add calls here to modify
* fields of taskstats.
*/
return rc;
}
static void fill_tgid_exit(struct task_struct *tsk)
{
unsigned long flags;
spin_lock_irqsave(&tsk->sighand->siglock, flags);
if (!tsk->signal->stats)
goto ret;
/*
* Each accounting subsystem calls its functions here to
* accumalate its per-task stats for tsk, into the per-tgid structure
*
* per-task-foo(tsk->signal->stats, tsk);
*/
delayacct_add_tsk(tsk->signal->stats, tsk);
ret:
spin_unlock_irqrestore(&tsk->sighand->siglock, flags);
return;
}
static int add_del_listener(pid_t pid, const struct cpumask *mask, int isadd)
{
struct listener_list *listeners;
struct listener *s, *tmp, *s2;
unsigned int cpu;
int ret = 0;
if (!cpumask_subset(mask, cpu_possible_mask))
return -EINVAL;
if (current_user_ns() != &init_user_ns)
return -EINVAL;
if (task_active_pid_ns(current) != &init_pid_ns)
return -EINVAL;
if (isadd == REGISTER) {
for_each_cpu(cpu, mask) {
s = kmalloc_node(sizeof(struct listener),
GFP_KERNEL, cpu_to_node(cpu));
if (!s) {
ret = -ENOMEM;
goto cleanup;
}
s->pid = pid;
s->valid = 1;
listeners = &per_cpu(listener_array, cpu);
down_write(&listeners->sem);
list_for_each_entry(s2, &listeners->list, list) {
if (s2->pid == pid && s2->valid)
goto exists;
}
list_add(&s->list, &listeners->list);
s = NULL;
exists:
up_write(&listeners->sem);
kfree(s); /* nop if NULL */
}
return 0;
}
/* Deregister or cleanup */
cleanup:
for_each_cpu(cpu, mask) {
listeners = &per_cpu(listener_array, cpu);
down_write(&listeners->sem);
list_for_each_entry_safe(s, tmp, &listeners->list, list) {
if (s->pid == pid) {
list_del(&s->list);
kfree(s);
break;
}
}
up_write(&listeners->sem);
}
return ret;
}
static int parse(struct nlattr *na, struct cpumask *mask)
{
char *data;
int len;
int ret;
if (na == NULL)
return 1;
len = nla_len(na);
if (len > TASKSTATS_CPUMASK_MAXLEN)
return -E2BIG;
if (len < 1)
return -EINVAL;
data = kmalloc(len, GFP_KERNEL);
if (!data)
return -ENOMEM;
nla_strlcpy(data, na, len);
ret = cpulist_parse(data, mask);
kfree(data);
return ret;
}
static struct taskstats *mk_reply(struct sk_buff *skb, int type, u32 pid)
{
struct nlattr *na, *ret;
int aggr;
aggr = (type == TASKSTATS_TYPE_PID)
? TASKSTATS_TYPE_AGGR_PID
: TASKSTATS_TYPE_AGGR_TGID;
na = nla_nest_start_noflag(skb, aggr);
if (!na)
goto err;
if (nla_put(skb, type, sizeof(pid), &pid) < 0) {
nla_nest_cancel(skb, na);
goto err;
}
ret = nla_reserve_64bit(skb, TASKSTATS_TYPE_STATS,
sizeof(struct taskstats), TASKSTATS_TYPE_NULL);
if (!ret) {
nla_nest_cancel(skb, na);
goto err;
}
nla_nest_end(skb, na);
return nla_data(ret);
err:
return NULL;
}
#define K(x) ((x) << (PAGE_SHIFT - 10))
#ifndef CONFIG_NUMA
static void sysstats_fill_zoneinfo(struct sys_memstats *stats)
{
pg_data_t *pgdat;
struct zone *zone;
struct zone *node_zones;
unsigned long zspages = 0;
pgdat = NODE_DATA(0);
node_zones = pgdat->node_zones;
for (zone = node_zones; zone - node_zones < MAX_NR_ZONES; ++zone) {
if (!populated_zone(zone))
continue;
zspages += zone_page_state(zone, NR_ZSPAGES);
if (!strcmp(zone->name, "DMA")) {
stats->dma_nr_free_pages =
K(zone_page_state(zone, NR_FREE_PAGES));
stats->dma_nr_active_anon =
K(zone_page_state(zone, NR_ZONE_ACTIVE_ANON));
stats->dma_nr_inactive_anon =
K(zone_page_state(zone, NR_ZONE_INACTIVE_ANON));
stats->dma_nr_active_file =
K(zone_page_state(zone, NR_ZONE_ACTIVE_FILE));
stats->dma_nr_inactive_file =
K(zone_page_state(zone, NR_ZONE_INACTIVE_FILE));
} else if (!strcmp(zone->name, "Normal")) {
stats->normal_nr_free_pages =
K(zone_page_state(zone, NR_FREE_PAGES));
stats->normal_nr_active_anon =
K(zone_page_state(zone, NR_ZONE_ACTIVE_ANON));
stats->normal_nr_inactive_anon =
K(zone_page_state(zone, NR_ZONE_INACTIVE_ANON));
stats->normal_nr_active_file =
K(zone_page_state(zone, NR_ZONE_ACTIVE_FILE));
stats->normal_nr_inactive_file =
K(zone_page_state(zone, NR_ZONE_INACTIVE_FILE));
} else if (!strcmp(zone->name, "HighMem")) {
stats->highmem_nr_free_pages =
K(zone_page_state(zone, NR_FREE_PAGES));
stats->highmem_nr_active_anon =
K(zone_page_state(zone, NR_ZONE_ACTIVE_ANON));
stats->highmem_nr_inactive_anon =
K(zone_page_state(zone, NR_ZONE_INACTIVE_ANON));
stats->highmem_nr_active_file =
K(zone_page_state(zone, NR_ZONE_ACTIVE_FILE));
stats->highmem_nr_inactive_file =
K(zone_page_state(zone, NR_ZONE_INACTIVE_FILE));
} else if (!strcmp(zone->name, "Movable")) {
stats->movable_nr_free_pages =
K(zone_page_state(zone, NR_FREE_PAGES));
stats->movable_nr_active_anon =
K(zone_page_state(zone, NR_ZONE_ACTIVE_ANON));
stats->movable_nr_inactive_anon =
K(zone_page_state(zone, NR_ZONE_INACTIVE_ANON));
stats->movable_nr_active_file =
K(zone_page_state(zone, NR_ZONE_ACTIVE_FILE));
stats->movable_nr_inactive_file =
K(zone_page_state(zone, NR_ZONE_INACTIVE_FILE));
}
}
stats->zram_compressed = K(zspages);
}
#elif
static void sysstats_fill_zoneinfo(struct sys_memstats *stats)
{
}
#endif
static void sysstats_build(struct sys_memstats *stats)
{
struct sysinfo i;
si_meminfo(&i);
si_swapinfo(&i);
stats->version = SYSSTATS_VERSION;
stats->memtotal = K(i.totalram);
stats->reclaimable =
K(global_node_page_state(NR_KERNEL_MISC_RECLAIMABLE));
stats->swap_used = K(i.totalswap - i.freeswap);
stats->swap_total = K(i.totalswap);
stats->vmalloc_total = K(vmalloc_nr_pages());
stats->unreclaimable =
K(global_node_page_state(NR_UNRECLAIMABLE_PAGES));
stats->buffer = K(i.bufferram);
stats->swapcache = K(total_swapcache_pages());
stats->slab_reclaimable =
K(global_node_page_state(NR_SLAB_RECLAIMABLE));
stats->slab_unreclaimable =
K(global_node_page_state(NR_SLAB_UNRECLAIMABLE));
stats->free_cma = K(global_zone_page_state(NR_FREE_CMA_PAGES));
stats->file_mapped = K(global_node_page_state(NR_FILE_MAPPED));
stats->kernelstack = global_zone_page_state(NR_KERNEL_STACK_KB);
stats->pagetable = K(global_zone_page_state(NR_PAGETABLE));
stats->shmem = K(i.sharedram);
sysstats_fill_zoneinfo(stats);
}
#undef K
static int sysstats_user_cmd(struct sk_buff *skb, struct genl_info *info)
{
int rc = 0;
struct sk_buff *rep_skb;
struct sys_memstats *stats;
struct nlattr *na;
size_t size;
size = nla_total_size(sizeof(struct sys_memstats));
rc = prepare_reply(info, SYSSTATS_CMD_NEW, &rep_skb,
size);
if (rc < 0)
goto err;
na = nla_reserve(rep_skb, SYSSTATS_TYPE_SYSMEM_STATS,
sizeof(struct sys_memstats));
if (na == NULL) {
nlmsg_free(rep_skb);
rc = -EMSGSIZE;
goto err;
}
stats = nla_data(na);
memset(stats, 0, sizeof(*stats));
sysstats_build(stats);
rc = send_reply(rep_skb, info);
err:
return rc;
}
static int cgroupstats_user_cmd(struct sk_buff *skb, struct genl_info *info)
{
int rc = 0;
struct sk_buff *rep_skb;
struct cgroupstats *stats;
struct nlattr *na;
size_t size;
u32 fd;
struct fd f;
na = info->attrs[CGROUPSTATS_CMD_ATTR_FD];
if (!na)
return -EINVAL;
fd = nla_get_u32(info->attrs[CGROUPSTATS_CMD_ATTR_FD]);
f = fdget(fd);
if (!f.file)
return 0;
size = nla_total_size(sizeof(struct cgroupstats));
rc = prepare_reply(info, CGROUPSTATS_CMD_NEW, &rep_skb,
size);
if (rc < 0)
goto err;
na = nla_reserve(rep_skb, CGROUPSTATS_TYPE_CGROUP_STATS,
sizeof(struct cgroupstats));
if (na == NULL) {
nlmsg_free(rep_skb);
rc = -EMSGSIZE;
goto err;
}
stats = nla_data(na);
memset(stats, 0, sizeof(*stats));
rc = cgroupstats_build(stats, f.file->f_path.dentry);
if (rc < 0) {
nlmsg_free(rep_skb);
goto err;
}
rc = send_reply(rep_skb, info);
err:
fdput(f);
return rc;
}
static int cmd_attr_register_cpumask(struct genl_info *info)
{
cpumask_var_t mask;
int rc;
if (!alloc_cpumask_var(&mask, GFP_KERNEL))
return -ENOMEM;
rc = parse(info->attrs[TASKSTATS_CMD_ATTR_REGISTER_CPUMASK], mask);
if (rc < 0)
goto out;
rc = add_del_listener(info->snd_portid, mask, REGISTER);
out:
free_cpumask_var(mask);
return rc;
}
static int cmd_attr_deregister_cpumask(struct genl_info *info)
{
cpumask_var_t mask;
int rc;
if (!alloc_cpumask_var(&mask, GFP_KERNEL))
return -ENOMEM;
rc = parse(info->attrs[TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK], mask);
if (rc < 0)
goto out;
rc = add_del_listener(info->snd_portid, mask, DEREGISTER);
out:
free_cpumask_var(mask);
return rc;
}
static size_t taskstats_packet_size(void)
{
size_t size;
size = nla_total_size(sizeof(u32)) +
nla_total_size_64bit(sizeof(struct taskstats)) +
nla_total_size(0);
return size;
}
static int taskstats2_cmd_attr_pid(struct genl_info *info)
{
struct taskstats2 *stats;
struct sk_buff *rep_skb;
struct nlattr *ret;
struct task_struct *tsk;
struct task_struct *p;
size_t size;
u32 pid;
int rc;
u64 utime, stime;
const struct cred *tcred;
struct cgroup_subsys_state *css;
unsigned long flags;
struct signal_struct *sig;
size = nla_total_size_64bit(sizeof(struct taskstats2));
rc = prepare_reply(info, TASKSTATS_CMD_NEW, &rep_skb, size);
if (rc < 0)
return rc;
rc = -EINVAL;
pid = nla_get_u32(info->attrs[TASKSTATS_CMD_ATTR_PID]);
ret = nla_reserve_64bit(rep_skb, TASKSTATS_TYPE_STATS,
sizeof(struct taskstats2), TASKSTATS_TYPE_NULL);
if (!ret)
goto err;
stats = nla_data(ret);
rcu_read_lock();
tsk = find_task_by_vpid(pid);
if (tsk)
get_task_struct(tsk);
rcu_read_unlock();
if (!tsk) {
rc = -ESRCH;
goto err;
}
memset(stats, 0, sizeof(*stats));
stats->version = TASKSTATS2_VERSION;
stats->pid = task_pid_nr_ns(tsk, task_active_pid_ns(current));
p = find_lock_task_mm(tsk);
if (p) {
#define K(x) ((x) << (PAGE_SHIFT - 10))
stats->anon_rss = K(get_mm_counter(p->mm, MM_ANONPAGES));
stats->file_rss = K(get_mm_counter(p->mm, MM_FILEPAGES));
stats->shmem_rss = K(get_mm_counter(p->mm, MM_SHMEMPAGES));
stats->swap_rss = K(get_mm_counter(p->mm, MM_SWAPENTS));
stats->unreclaimable =
K(get_mm_counter(p->mm, MM_UNRECLAIMABLE));
#undef K
task_unlock(p);
}
/* version 2 fields begin here */
task_cputime(tsk, &utime, &stime);
stats->utime = div_u64(utime, NSEC_PER_USEC);
stats->stime = div_u64(stime, NSEC_PER_USEC);
if (lock_task_sighand(tsk, &flags)) {
sig = tsk->signal;
stats->cutime = sig->cutime;
stats->cstime = sig->cstime;
unlock_task_sighand(tsk, &flags);
}
rcu_read_lock();
tcred = __task_cred(tsk);
stats->uid = from_kuid_munged(current_user_ns(), tcred->uid);
stats->ppid = pid_alive(tsk) ?
task_tgid_nr_ns(rcu_dereference(tsk->real_parent),
task_active_pid_ns(current)) : 0;
rcu_read_unlock();
strlcpy(stats->name, tsk->comm, sizeof(stats->name));
css = task_get_css(tsk, cpuset_cgrp_id);
cgroup_path_ns(css->cgroup, stats->state, sizeof(stats->state),
current->nsproxy->cgroup_ns);
css_put(css);
/* version 2 fields end here */
put_task_struct(tsk);
return send_reply(rep_skb, info);
err:
nlmsg_free(rep_skb);
return rc;
}
static int cmd_attr_pid(struct genl_info *info)
{
struct taskstats *stats;
struct sk_buff *rep_skb;
size_t size;
u32 pid;
int rc;
size = taskstats_packet_size();
rc = prepare_reply(info, TASKSTATS_CMD_NEW, &rep_skb, size);
if (rc < 0)
return rc;
rc = -EINVAL;
pid = nla_get_u32(info->attrs[TASKSTATS_CMD_ATTR_PID]);
stats = mk_reply(rep_skb, TASKSTATS_TYPE_PID, pid);
if (!stats)
goto err;
rc = fill_stats_for_pid(pid, stats);
if (rc < 0)
goto err;
return send_reply(rep_skb, info);
err:
nlmsg_free(rep_skb);
return rc;
}
static int cmd_attr_tgid(struct genl_info *info)
{
struct taskstats *stats;
struct sk_buff *rep_skb;
size_t size;
u32 tgid;
int rc;
size = taskstats_packet_size();
rc = prepare_reply(info, TASKSTATS_CMD_NEW, &rep_skb, size);
if (rc < 0)
return rc;
rc = -EINVAL;
tgid = nla_get_u32(info->attrs[TASKSTATS_CMD_ATTR_TGID]);
stats = mk_reply(rep_skb, TASKSTATS_TYPE_TGID, tgid);
if (!stats)
goto err;
rc = fill_stats_for_tgid(tgid, stats);
if (rc < 0)
goto err;
return send_reply(rep_skb, info);
err:
nlmsg_free(rep_skb);
return rc;
}
static struct tgid_iter next_tgid(struct pid_namespace *ns,
struct tgid_iter iter)
{
struct pid *pid;
if (iter.task)
put_task_struct(iter.task);
rcu_read_lock();
retry:
iter.task = NULL;
pid = find_ge_pid(iter.tgid, ns);
if (pid) {
iter.tgid = pid_nr_ns(pid, ns);
iter.task = pid_task(pid, PIDTYPE_PID);
if (!iter.task || !has_group_leader_pid(iter.task)) {
iter.tgid += 1;
goto retry;
}
get_task_struct(iter.task);
}
rcu_read_unlock();
return iter;
}
static int taskstats2_foreach(struct sk_buff *skb, struct netlink_callback *cb)
{
struct pid_namespace *ns = task_active_pid_ns(current);
struct tgid_iter iter;
void *reply;
struct nlattr *attr;
struct nlattr *nla;
struct taskstats2 *stats;
struct task_struct *p;
short oom_score;
short oom_score_min;
short oom_score_max;
u32 buf;
nla = nla_find(nlmsg_attrdata(cb->nlh, GENL_HDRLEN),
nlmsg_attrlen(cb->nlh, GENL_HDRLEN),
TASKSTATS_TYPE_FOREACH);
if (!nla)
goto out;
buf = nla_get_u32(nla);
oom_score_min = (short) (buf & 0xFFFF);
oom_score_max = (short) ((buf >> 16) & 0xFFFF);
iter.tgid = cb->args[0];
iter.task = NULL;
for (iter = next_tgid(ns, iter); iter.task;
iter.tgid += 1, iter = next_tgid(ns, iter)) {
if (iter.task->flags & PF_KTHREAD)
continue;
oom_score = iter.task->signal->oom_score_adj;
if ((oom_score < oom_score_min)
|| (oom_score > oom_score_max))
continue;
reply = genlmsg_put(skb, NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, &family, 0, TASKSTATS2_CMD_GET);
if (reply == NULL) {
put_task_struct(iter.task);
break;
}
attr = nla_reserve(skb, TASKSTATS_TYPE_FOREACH,
sizeof(struct taskstats2));
if (!attr) {
put_task_struct(iter.task);
genlmsg_cancel(skb, reply);
break;
}
stats = nla_data(attr);
memset(stats, 0, sizeof(struct taskstats2));
stats->version = TASKSTATS2_VERSION;
rcu_read_lock();
stats->pid = task_pid_nr_ns(iter.task,
task_active_pid_ns(current));
stats->oom_score = iter.task->signal->oom_score_adj;
rcu_read_unlock();
p = find_lock_task_mm(iter.task);
if (p) {
#define K(x) ((x) << (PAGE_SHIFT - 10))
stats->anon_rss =
K(get_mm_counter(p->mm, MM_ANONPAGES));
stats->file_rss =
K(get_mm_counter(p->mm, MM_FILEPAGES));
stats->shmem_rss =
K(get_mm_counter(p->mm, MM_SHMEMPAGES));
stats->swap_rss =
K(get_mm_counter(p->mm, MM_SWAPENTS));
task_unlock(p);
#undef K
}
genlmsg_end(skb, reply);
}
cb->args[0] = iter.tgid;
out:
return skb->len;
}
static int taskstats2_user_cmd(struct sk_buff *skb, struct genl_info *info)
{
if (info->attrs[TASKSTATS_CMD_ATTR_PID])
return taskstats2_cmd_attr_pid(info);
else
return -EINVAL;
}
static int taskstats_user_cmd(struct sk_buff *skb, struct genl_info *info)
{
if (info->attrs[TASKSTATS_CMD_ATTR_REGISTER_CPUMASK])
return cmd_attr_register_cpumask(info);
else if (info->attrs[TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK])
return cmd_attr_deregister_cpumask(info);
else if (info->attrs[TASKSTATS_CMD_ATTR_PID])
return cmd_attr_pid(info);
else if (info->attrs[TASKSTATS_CMD_ATTR_TGID])
return cmd_attr_tgid(info);
else
return -EINVAL;
}
static struct taskstats *taskstats_tgid_alloc(struct task_struct *tsk)
{
struct signal_struct *sig = tsk->signal;
struct taskstats *stats_new, *stats;
/* Pairs with smp_store_release() below. */
stats = smp_load_acquire(&sig->stats);
if (stats || thread_group_empty(tsk))
return stats;
/* No problem if kmem_cache_zalloc() fails */
stats_new = kmem_cache_zalloc(taskstats_cache, GFP_KERNEL);
spin_lock_irq(&tsk->sighand->siglock);
stats = sig->stats;
if (!stats) {
/*
* Pairs with smp_store_release() above and order the
* kmem_cache_zalloc().
*/
smp_store_release(&sig->stats, stats_new);
stats = stats_new;
stats_new = NULL;
}
spin_unlock_irq(&tsk->sighand->siglock);
if (stats_new)
kmem_cache_free(taskstats_cache, stats_new);
return stats;
}
/* Send pid data out on exit */
void taskstats_exit(struct task_struct *tsk, int group_dead)
{
int rc;
struct listener_list *listeners;
struct taskstats *stats;
struct sk_buff *rep_skb;
size_t size;
int is_thread_group;
if (!family_registered)
return;
/*
* Size includes space for nested attributes
*/
size = taskstats_packet_size();
is_thread_group = !!taskstats_tgid_alloc(tsk);
if (is_thread_group) {
/* PID + STATS + TGID + STATS */
size = 2 * size;
/* fill the tsk->signal->stats structure */
fill_tgid_exit(tsk);
}
listeners = raw_cpu_ptr(&listener_array);
if (list_empty(&listeners->list))
return;
rc = prepare_reply(NULL, TASKSTATS_CMD_NEW, &rep_skb, size);
if (rc < 0)
return;
stats = mk_reply(rep_skb, TASKSTATS_TYPE_PID,
task_pid_nr_ns(tsk, &init_pid_ns));
if (!stats)
goto err;
fill_stats(&init_user_ns, &init_pid_ns, tsk, stats);
/*
* Doesn't matter if tsk is the leader or the last group member leaving
*/
if (!is_thread_group || !group_dead)
goto send;
stats = mk_reply(rep_skb, TASKSTATS_TYPE_TGID,
task_tgid_nr_ns(tsk, &init_pid_ns));
if (!stats)
goto err;
memcpy(stats, tsk->signal->stats, sizeof(*stats));
stats->version = TASKSTATS_VERSION;
send:
send_cpu_listeners(rep_skb, listeners);
return;
err:
nlmsg_free(rep_skb);
}
static const struct genl_ops taskstats_ops[] = {
{
.cmd = TASKSTATS_CMD_GET,
.doit = taskstats_user_cmd,
.policy = taskstats_cmd_get_policy,
.flags = GENL_ADMIN_PERM,
},
{
.cmd = TASKSTATS2_CMD_GET,
.doit = taskstats2_user_cmd,
.dumpit = taskstats2_foreach,
.policy = taskstats_cmd_get_policy,
},
{
.cmd = CGROUPSTATS_CMD_GET,
.doit = cgroupstats_user_cmd,
.policy = cgroupstats_cmd_get_policy,
},
{
.cmd = SYSSTATS_CMD_GET,
.doit = sysstats_user_cmd,
.policy = sysstats_cmd_get_policy,
},
};
static struct genl_family family __ro_after_init = {
.name = TASKSTATS_GENL_NAME,
.version = TASKSTATS_GENL_VERSION,
.maxattr = TASKSTATS_CMD_ATTR_MAX,
.module = THIS_MODULE,
.ops = taskstats_ops,
.n_ops = ARRAY_SIZE(taskstats_ops),
};
/* Needed early in initialization */
void __init taskstats_init_early(void)
{
unsigned int i;
taskstats_cache = KMEM_CACHE(taskstats, SLAB_PANIC);
for_each_possible_cpu(i) {
INIT_LIST_HEAD(&(per_cpu(listener_array, i).list));
init_rwsem(&(per_cpu(listener_array, i).sem));
}
}
static int __init taskstats_init(void)
{
int rc;
rc = genl_register_family(&family);
if (rc)
return rc;
family_registered = 1;
pr_info("registered taskstats version %d\n", TASKSTATS_GENL_VERSION);
return 0;
}
/*
* late initcall ensures initialization of statistics collection
* mechanisms precedes initialization of the taskstats interface
*/
late_initcall(taskstats_init);