android_kernel_xiaomi_sm8350/fs/userfaultfd.c
Michael Bestas c066ac93be
Merge tag 'ASB-2023-02-05_11-5.4' of https://android.googlesource.com/kernel/common into android13-5.4-lahaina
https://source.android.com/docs/security/bulletin/2023-02-01
CVE-2022-39189
CVE-2022-39842
CVE-2022-41222
CVE-2023-20937
CVE-2023-20938
CVE-2022-0850

* tag 'ASB-2023-02-05_11-5.4' of https://android.googlesource.com/kernel/common:
  ANDROID: ABI: Cuttlefish Symbol update
  UPSTREAM: media: dvb-core: Fix UAF due to refcount races at releasing
  ANDROID: abi_gki_aarch64_qcom: Add hrtimer_sleeper_start_expires
  UPSTREAM: ALSA: pcm: Move rwsem lock inside snd_ctl_elem_read to prevent UAF
  ANDROID: Revert "tracing/ring-buffer: Have polling block on watermark"
  UPSTREAM: usb: gadget: f_hid: fix f_hidg lifetime vs cdev
  UPSTREAM: usb: gadget: f_hid: optional SETUP/SET_REPORT mode
  ANDROID: add TEST_MAPPING for net/, include/net
  UPSTREAM: nfp: fix use-after-free in area_cache_get()
  UPSTREAM: proc: avoid integer type confusion in get_proc_long
  UPSTREAM: proc: proc_skip_spaces() shouldn't think it is working on C strings
  ANDROID: usb: f_accessory: Check buffer size when initialised via composite
  BACKPORT: mm: don't be stuck to rmap lock on reclaim path
  ANDROID: Add more hvc devices for virtio-console.
  Revert "mmc: sdhci: Fix voltage switch delay"
  ANDROID: gki_defconfig: add CONFIG_FUNCTION_ERROR_INJECTION
  Linux 5.4.226
  ipc/sem: Fix dangling sem_array access in semtimedop race
  v4l2: don't fall back to follow_pfn() if pin_user_pages_fast() fails
  proc: proc_skip_spaces() shouldn't think it is working on C strings
  proc: avoid integer type confusion in get_proc_long
  mmc: sdhci: Fix voltage switch delay
  mmc: sdhci: use FIELD_GET for preset value bit masks
  char: tpm: Protect tpm_pm_suspend with locks
  Revert "clocksource/drivers/riscv: Events are stopped during CPU suspend"
  x86/ioremap: Fix page aligned size calculation in __ioremap_caller()
  Bluetooth: L2CAP: Fix accepting connection request for invalid SPSM
  x86/pm: Add enumeration check before spec MSRs save/restore setup
  x86/tsx: Add a feature bit for TSX control MSR support
  nvme: ensure subsystem reset is single threaded
  nvme: restrict management ioctls to admin
  epoll: check for events when removing a timed out thread from the wait queue
  epoll: call final ep_events_available() check under the lock
  tracing/ring-buffer: Have polling block on watermark
  ipv4: Fix route deletion when nexthop info is not specified
  ipv4: Handle attempt to delete multipath route when fib_info contains an nh reference
  selftests: net: fix nexthop warning cleanup double ip typo
  selftests: net: add delete nexthop route warning test
  Kconfig.debug: provide a little extra FRAME_WARN leeway when KASAN is enabled
  parisc: Increase FRAME_WARN to 2048 bytes on parisc
  xtensa: increase size of gcc stack frame check
  parisc: Increase size of gcc stack frame check
  iommu/vt-d: Fix PCI device refcount leak in dmar_dev_scope_init()
  pinctrl: single: Fix potential division by zero
  ASoC: ops: Fix bounds check for _sx controls
  mm: Fix '.data.once' orphan section warning
  arm64: errata: Fix KVM Spectre-v2 mitigation selection for Cortex-A57/A72
  arm64: Fix panic() when Spectre-v2 causes Spectre-BHB to re-allocate KVM vectors
  tracing: Free buffers when a used dynamic event is removed
  mmc: sdhci-sprd: Fix no reset data and command after voltage switch
  mmc: sdhci-esdhc-imx: correct CQHCI exit halt state check
  mmc: core: Fix ambiguous TRIM and DISCARD arg
  mmc: mmc_test: Fix removal of debugfs file
  pinctrl: intel: Save and restore pins in "direct IRQ" mode
  x86/bugs: Make sure MSR_SPEC_CTRL is updated properly upon resume from S3
  nilfs2: fix NULL pointer dereference in nilfs_palloc_commit_free_entry()
  tools/vm/slabinfo-gnuplot: use "grep -E" instead of "egrep"
  error-injection: Add prompt for function error injection
  net/mlx5: DR, Fix uninitialized var warning
  hwmon: (coretemp) fix pci device refcount leak in nv1a_ram_new()
  hwmon: (coretemp) Check for null before removing sysfs attrs
  net: ethernet: renesas: ravb: Fix promiscuous mode after system resumed
  sctp: fix memory leak in sctp_stream_outq_migrate()
  packet: do not set TP_STATUS_CSUM_VALID on CHECKSUM_COMPLETE
  net: tun: Fix use-after-free in tun_detach()
  afs: Fix fileserver probe RTT handling
  net: hsr: Fix potential use-after-free
  dsa: lan9303: Correct stat name
  net: ethernet: nixge: fix NULL dereference
  net/9p: Fix a potential socket leak in p9_socket_open
  net: net_netdev: Fix error handling in ntb_netdev_init_module()
  net: phy: fix null-ptr-deref while probe() failed
  wifi: cfg80211: fix buffer overflow in elem comparison
  qlcnic: fix sleep-in-atomic-context bugs caused by msleep
  can: cc770: cc770_isa_probe(): add missing free_cc770dev()
  can: sja1000_isa: sja1000_isa_probe(): add missing free_sja1000dev()
  net/mlx5e: Fix use-after-free when reverting termination table
  net/mlx5: Fix uninitialized variable bug in outlen_write()
  of: property: decrement node refcount in of_fwnode_get_reference_args()
  hwmon: (ibmpex) Fix possible UAF when ibmpex_register_bmc() fails
  hwmon: (i5500_temp) fix missing pci_disable_device()
  scripts/faddr2line: Fix regression in name resolution on ppc64le
  iio: light: rpr0521: add missing Kconfig dependencies
  iio: health: afe4404: Fix oob read in afe4404_[read|write]_raw
  iio: health: afe4403: Fix oob read in afe4403_read_raw
  btrfs: qgroup: fix sleep from invalid context bug in btrfs_qgroup_inherit()
  drm/amdgpu: Partially revert "drm/amdgpu: update drm_display_info correctly when the edid is read"
  drm/amdgpu: update drm_display_info correctly when the edid is read
  btrfs: move QUOTA_ENABLED check to rescan_should_stop from btrfs_qgroup_rescan_worker
  spi: spi-imx: Fix spi_bus_clk if requested clock is higher than input clock
  btrfs: free btrfs_path before copying inodes to userspace
  fuse: lock inode unconditionally in fuse_fallocate()
  drm/i915: fix TLB invalidation for Gen12 video and compute engines
  drm/amdgpu: always register an MMU notifier for userptr
  drm/amd/dc/dce120: Fix audio register mapping, stop triggering KASAN
  btrfs: sysfs: normalize the error handling branch in btrfs_init_sysfs()
  btrfs: free btrfs_path before copying subvol info to userspace
  btrfs: free btrfs_path before copying fspath to userspace
  btrfs: free btrfs_path before copying root refs to userspace
  binder: Gracefully handle BINDER_TYPE_FDA objects with num_fds=0
  binder: Address corner cases in deferred copy and fixup
  binder: fix pointer cast warning
  binder: defer copies of pre-patched txn data
  binder: read pre-translated fds from sender buffer
  binder: avoid potential data leakage when copying txn
  dm integrity: flush the journal on suspend
  net: usb: qmi_wwan: add Telit 0x103a composition
  tcp: configurable source port perturb table size
  platform/x86: hp-wmi: Ignore Smart Experience App event
  platform/x86: acer-wmi: Enable SW_TABLET_MODE on Switch V 10 (SW5-017)
  platform/x86: asus-wmi: add missing pci_dev_put() in asus_wmi_set_xusb2pr()
  xen/platform-pci: add missing free_irq() in error path
  serial: 8250: 8250_omap: Avoid RS485 RTS glitch on ->set_termios()
  ASoC: Intel: bytcht_es8316: Add quirk for the Nanote UMPC-01
  Input: synaptics - switch touchpad on HP Laptop 15-da3001TU to RMI mode
  gcov: clang: fix the buffer overflow issue
  nilfs2: fix nilfs_sufile_mark_dirty() not set segment usage as dirty
  firmware: coreboot: Register bus in module init
  firmware: google: Release devices before unregistering the bus
  ceph: avoid putting the realm twice when decoding snaps fails
  ceph: do not update snapshot context when there is no new snapshot
  iio: pressure: ms5611: fixed value compensation bug
  iio: ms5611: Simplify IO callback parameters
  nios2: add FORCE for vmlinuz.gz
  init/Kconfig: fix CC_HAS_ASM_GOTO_TIED_OUTPUT test with dash
  iio: core: Fix entry not deleted when iio_register_sw_trigger_type() fails
  iio: light: apds9960: fix wrong register for gesture gain
  arm64: dts: rockchip: lower rk3399-puma-haikou SD controller clock frequency
  usb: dwc3: exynos: Fix remove() function
  lib/vdso: use "grep -E" instead of "egrep"
  s390/crashdump: fix TOD programmable field size
  net: thunderx: Fix the ACPI memory leak
  nfc: st-nci: fix memory leaks in EVT_TRANSACTION
  nfc: st-nci: fix incorrect validating logic in EVT_TRANSACTION
  s390/dasd: fix no record found for raw_track_access
  dccp/tcp: Reset saddr on failure after inet6?_hash_connect().
  bnx2x: fix pci device refcount leak in bnx2x_vf_is_pcie_pending()
  regulator: twl6030: re-add TWL6032_SUBCLASS
  NFC: nci: fix memory leak in nci_rx_data_packet()
  xfrm: Fix ignored return value in xfrm6_init()
  tipc: check skb_linearize() return value in tipc_disc_rcv()
  tipc: add an extra conn_get in tipc_conn_alloc
  tipc: set con sock in tipc_conn_alloc
  net/mlx5: Fix FW tracer timestamp calculation
  Drivers: hv: vmbus: fix possible memory leak in vmbus_device_register()
  Drivers: hv: vmbus: fix double free in the error path of vmbus_add_channel_work()
  nfp: add port from netdev validation for EEPROM access
  net: pch_gbe: fix pci device refcount leak while module exiting
  net/qla3xxx: fix potential memleak in ql3xxx_send()
  net/mlx4: Check retval of mlx4_bitmap_init
  ARM: mxs: fix memory leak in mxs_machine_init()
  9p/fd: fix issue of list_del corruption in p9_fd_cancel()
  net: pch_gbe: fix potential memleak in pch_gbe_tx_queue()
  nfc/nci: fix race with opening and closing
  net: liquidio: simplify if expression
  ARM: dts: at91: sam9g20ek: enable udc vbus gpio pinctrl
  tee: optee: fix possible memory leak in optee_register_device()
  bus: sunxi-rsb: Support atomic transfers
  regulator: core: fix UAF in destroy_regulator()
  regulator: core: fix kobject release warning and memory leak in regulator_register()
  ASoC: sgtl5000: Reset the CHIP_CLK_CTRL reg on remove
  ARM: dts: am335x-pcm-953: Define fixed regulators in root node
  af_key: Fix send_acquire race with pfkey_register
  MIPS: pic32: treat port as signed integer
  RISC-V: vdso: Do not add missing symbols to version section in linker script
  arm64/syscall: Include asm/ptrace.h in syscall_wrapper header.
  block, bfq: fix null pointer dereference in bfq_bio_bfqg()
  drm: panel-orientation-quirks: Add quirk for Acer Switch V 10 (SW5-017)
  spi: stm32: fix stm32_spi_prepare_mbr() that halves spi clk for every run
  wifi: mac80211: Fix ack frame idr leak when mesh has no route
  audit: fix undefined behavior in bit shift for AUDIT_BIT
  wifi: mac80211_hwsim: fix debugfs attribute ps with rc table support
  wifi: mac80211: fix memory free error when registering wiphy fail
  Revert "can: af_can: fix NULL pointer dereference in can_rx_register()"
  Linux 5.4.225
  ntfs: check overflow when iterating ATTR_RECORDs
  ntfs: fix out-of-bounds read in ntfs_attr_find()
  ntfs: fix use-after-free in ntfs_attr_find()
  mm: fs: initialize fsdata passed to write_begin/write_end interface
  9p/trans_fd: always use O_NONBLOCK read/write
  gfs2: Switch from strlcpy to strscpy
  gfs2: Check sb_bsize_shift after reading superblock
  9p: trans_fd/p9_conn_cancel: drop client lock earlier
  kcm: close race conditions on sk_receive_queue
  bpf, test_run: Fix alignment problem in bpf_prog_test_run_skb()
  kcm: avoid potential race in kcm_tx_work
  tcp: cdg: allow tcp_cdg_release() to be called multiple times
  macvlan: enforce a consistent minimal mtu
  Input: i8042 - fix leaking of platform device on module removal
  kprobes: Skip clearing aggrprobe's post_handler in kprobe-on-ftrace case
  scsi: target: tcm_loop: Fix possible name leak in tcm_loop_setup_hba_bus()
  ring-buffer: Include dropped pages in counting dirty patches
  serial: 8250: Flush DMA Rx on RLSI
  misc/vmw_vmci: fix an infoleak in vmci_host_do_receive_datagram()
  docs: update mediator contact information in CoC doc
  mmc: sdhci-pci: Fix possible memory leak caused by missing pci_dev_put()
  mmc: sdhci-pci-o2micro: fix card detect fail issue caused by CD# debounce timeout
  mmc: core: properly select voltage range without power cycle
  scsi: zfcp: Fix double free of FSF request when qdio send fails
  Input: iforce - invert valid length check when fetching device IDs
  serial: 8250_lpss: Configure DMA also w/o DMA filter
  serial: 8250: Fall back to non-DMA Rx if IIR_RDI occurs
  dm ioctl: fix misbehavior if list_versions races with module loading
  iio: pressure: ms5611: changed hardcoded SPI speed to value limited
  iio: trigger: sysfs: fix possible memory leak in iio_sysfs_trig_init()
  iio: adc: at91_adc: fix possible memory leak in at91_adc_allocate_trigger()
  usb: chipidea: fix deadlock in ci_otg_del_timer
  usb: add NO_LPM quirk for Realforce 87U Keyboard
  USB: serial: option: add Fibocom FM160 0x0111 composition
  USB: serial: option: add u-blox LARA-L6 modem
  USB: serial: option: add u-blox LARA-R6 00B modem
  USB: serial: option: remove old LARA-R6 PID
  USB: serial: option: add Sierra Wireless EM9191
  speakup: fix a segfault caused by switching consoles
  slimbus: stream: correct presence rate frequencies
  Revert "usb: dwc3: disable USB core PHY management"
  ALSA: usb-audio: Drop snd_BUG_ON() from snd_usbmidi_output_open()
  ring_buffer: Do not deactivate non-existant pages
  ftrace: Fix null pointer dereference in ftrace_add_mod()
  ftrace: Optimize the allocation for mcount entries
  ftrace: Fix the possible incorrect kernel message
  cifs: add check for returning value of SMB2_set_info_init
  net: thunderbolt: Fix error handling in tbnet_init()
  cifs: Fix wrong return value checking when GETFLAGS
  net/x25: Fix skb leak in x25_lapb_receive_frame()
  platform/x86/intel: pmc: Don't unconditionally attach Intel PMC when virtualized
  drbd: use after free in drbd_create_device()
  xen/pcpu: fix possible memory leak in register_pcpu()
  bnxt_en: Remove debugfs when pci_register_driver failed
  net: caif: fix double disconnect client in chnl_net_open()
  net: macvlan: Use built-in RCU list checking
  mISDN: fix misuse of put_device() in mISDN_register_device()
  net: liquidio: release resources when liquidio driver open failed
  mISDN: fix possible memory leak in mISDN_dsp_element_register()
  net: bgmac: Drop free_netdev() from bgmac_enet_remove()
  ata: libata-transport: fix double ata_host_put() in ata_tport_add()
  arm64: dts: imx8mn: Fix NAND controller size-cells
  arm64: dts: imx8mm: Fix NAND controller size-cells
  pinctrl: devicetree: fix null pointer dereferencing in pinctrl_dt_to_map
  parport_pc: Avoid FIFO port location truncation
  siox: fix possible memory leak in siox_device_add()
  block: sed-opal: kmalloc the cmd/resp buffers
  ASoC: soc-utils: Remove __exit for snd_soc_util_exit()
  tty: n_gsm: fix sleep-in-atomic-context bug in gsm_control_send
  serial: imx: Add missing .thaw_noirq hook
  serial: 8250: omap: Flush PM QOS work on remove
  serial: 8250: omap: Fix unpaired pm_runtime_put_sync() in omap8250_remove()
  serial: 8250_omap: remove wait loop from Errata i202 workaround
  ASoC: core: Fix use-after-free in snd_soc_exit()
  spi: stm32: Print summary 'callbacks suppressed' message
  ASoC: codecs: jz4725b: Fix spelling mistake "Sourc" -> "Source", "Routee" -> "Route"
  Bluetooth: L2CAP: Fix l2cap_global_chan_by_psm
  btrfs: remove pointless and double ulist frees in error paths of qgroup tests
  drm/imx: imx-tve: Fix return type of imx_tve_connector_mode_valid
  i2c: i801: add lis3lv02d's I2C address for Vostro 5568
  NFSv4: Retry LOCK on OLD_STATEID during delegation return
  selftests/intel_pstate: fix build for ARCH=x86_64
  selftests/futex: fix build for clang
  ASoC: codecs: jz4725b: fix capture selector naming
  ASoC: codecs: jz4725b: use right control for Capture Volume
  ASoC: codecs: jz4725b: fix reported volume for Master ctl
  ASoC: codecs: jz4725b: add missed Line In power control bit
  spi: intel: Fix the offset to get the 64K erase opcode
  ASoC: wm8962: Add an event handler for TEMP_HP and TEMP_SPK
  ASoC: wm8997: Revert "ASoC: wm8997: Fix PM disable depth imbalance in wm8997_probe"
  ASoC: wm5110: Revert "ASoC: wm5110: Fix PM disable depth imbalance in wm5110_probe"
  ASoC: wm5102: Revert "ASoC: wm5102: Fix PM disable depth imbalance in wm5102_probe"
  x86/cpu: Restore AMD's DE_CFG MSR after resume
  net: tun: call napi_schedule_prep() to ensure we own a napi
  dmaengine: at_hdmac: Check return code of dma_async_device_register
  dmaengine: at_hdmac: Fix impossible condition
  dmaengine: at_hdmac: Don't allow CPU to reorder channel enable
  dmaengine: at_hdmac: Fix completion of unissued descriptor in case of errors
  dmaengine: at_hdmac: Don't start transactions at tx_submit level
  dmaengine: at_hdmac: Fix at_lli struct definition
  cert host tools: Stop complaining about deprecated OpenSSL functions
  can: j1939: j1939_send_one(): fix missing CAN header initialization
  udf: Fix a slab-out-of-bounds write bug in udf_find_entry()
  btrfs: selftests: fix wrong error check in btrfs_free_dummy_root()
  platform/x86: hp_wmi: Fix rfkill causing soft blocked wifi
  drm/i915/dmabuf: fix sg_table handling in map_dma_buf
  nilfs2: fix use-after-free bug of ns_writer on remount
  nilfs2: fix deadlock in nilfs_count_free_blocks()
  vmlinux.lds.h: Fix placement of '.data..decrypted' section
  ALSA: usb-audio: Add DSD support for Accuphase DAC-60
  ALSA: usb-audio: Add quirk entry for M-Audio Micro
  ALSA: hda: fix potential memleak in 'add_widget_node'
  ALSA: hda/ca0132: add quirk for EVGA Z390 DARK
  mmc: sdhci-tegra: Fix SDHCI_RESET_ALL for CQHCI
  mmc: sdhci-of-arasan: Fix SDHCI_RESET_ALL for CQHCI
  mmc: cqhci: Provide helper for resetting both SDHCI and CQHCI
  MIPS: jump_label: Fix compat branch range check
  arm64: efi: Fix handling of misaligned runtime regions and drop warning
  riscv: process: fix kernel info leakage
  net: macvlan: fix memory leaks of macvlan_common_newlink
  ethernet: tundra: free irq when alloc ring failed in tsi108_open()
  net: mv643xx_eth: disable napi when init rxq or txq failed in mv643xx_eth_open()
  ethernet: s2io: disable napi when start nic failed in s2io_card_up()
  cxgb4vf: shut down the adapter when t4vf_update_port_info() failed in cxgb4vf_open()
  net: cxgb3_main: disable napi when bind qsets failed in cxgb_up()
  net: cpsw: disable napi in cpsw_ndo_open()
  net/mlx5: Allow async trigger completion execution on single CPU systems
  net: nixge: disable napi when enable interrupts failed in nixge_open()
  perf stat: Fix printing os->prefix in CSV metrics output
  drivers: net: xgene: disable napi when register irq failed in xgene_enet_open()
  dmaengine: mv_xor_v2: Fix a resource leak in mv_xor_v2_remove()
  dmaengine: pxa_dma: use platform_get_irq_optional
  tipc: fix the msg->req tlv len check in tipc_nl_compat_name_table_dump_header
  can: af_can: fix NULL pointer dereference in can_rx_register()
  ipv6: addrlabel: fix infoleak when sending struct ifaddrlblmsg to network
  drm/vc4: Fix missing platform_unregister_drivers() call in vc4_drm_register()
  hamradio: fix issue of dev reference count leakage in bpq_device_event()
  net: lapbether: fix issue of dev reference count leakage in lapbeth_device_event()
  capabilities: fix undefined behavior in bit shift for CAP_TO_MASK
  net: fman: Unregister ethernet device on removal
  bnxt_en: fix potentially incorrect return value for ndo_rx_flow_steer
  bnxt_en: Fix possible crash in bnxt_hwrm_set_coal()
  net: tun: Fix memory leaks of napi_get_frags
  net: gso: fix panic on frag_list with mixed head alloc types
  HID: hyperv: fix possible memory leak in mousevsc_probe()
  bpf, sockmap: Fix the sk->sk_forward_alloc warning of sk_stream_kill_queues
  wifi: cfg80211: fix memory leak in query_regdb_file()
  wifi: cfg80211: silence a sparse RCU warning
  phy: stm32: fix an error code in probe
  xfs: drain the buf delwri queue before xfsaild idles
  xfs: preserve inode versioning across remounts
  xfs: use MMAPLOCK around filemap_map_pages()
  xfs: redesign the reflink remap loop to fix blkres depletion crash
  xfs: rename xfs_bmap_is_real_extent to is_written_extent
  xfs: preserve rmapbt swapext block reservation from freed blocks
  ANDROID: properly copy the scm_io_uring field in struct sk_buff
  Linux 5.4.224
  ipc: remove memcg accounting for sops objects in do_semtimedop()
  wifi: brcmfmac: Fix potential buffer overflow in brcmf_fweh_event_worker()
  drm/i915/sdvo: Setup DDC fully before output init
  drm/i915/sdvo: Filter out invalid outputs more sensibly
  drm/rockchip: dsi: Force synchronous probe
  mtd: rawnand: gpmi: Set WAIT_FOR_READY timeout based on program/erase times
  KVM: x86: emulator: update the emulation mode after CR0 write
  KVM: x86: emulator: introduce emulator_recalc_and_set_mode
  KVM: x86: emulator: em_sysexit should update ctxt->mode
  KVM: x86: Mask off reserved bits in CPUID.80000008H
  KVM: x86: Mask off reserved bits in CPUID.8000001AH
  ext4: fix BUG_ON() when directory entry has invalid rec_len
  ext4: fix warning in 'ext4_da_release_space'
  parisc: Avoid printing the hardware path twice
  parisc: Export iosapic_serial_irq() symbol for serial port driver
  parisc: Make 8250_gsc driver dependend on CONFIG_PARISC
  ALSA: usb-audio: Add quirks for MacroSilicon MS2100/MS2106 devices
  perf/x86/intel: Add Cooper Lake stepping to isolation_ucodes[]
  perf/x86/intel: Fix pebs event constraints for ICL
  efi: random: reduce seed size to 32 bytes
  fuse: add file_modified() to fallocate
  capabilities: fix potential memleak on error path from vfs_getxattr_alloc()
  tracing/histogram: Update document for KEYS_MAX size
  tools/nolibc/string: Fix memcmp() implementation
  kprobe: reverse kp->flags when arm_kprobe failed
  tcp/udp: Make early_demux back namespacified.
  btrfs: fix type of parameter generation in btrfs_get_dentry
  binder: fix UAF of alloc->vma in race with munmap()
  memcg: enable accounting of ipc resources
  tcp/udp: Fix memory leak in ipv6_renew_options().
  block, bfq: protect 'bfqd->queued' by 'bfqd->lock'
  Bluetooth: L2CAP: Fix attempting to access uninitialized memory
  xfs: Add the missed xfs_perag_put() for xfs_ifree_cluster()
  xfs: don't fail unwritten extent conversion on writeback due to edquot
  xfs: group quota should return EDQUOT when prj quota enabled
  xfs: gut error handling in xfs_trans_unreserve_and_mod_sb()
  xfs: use ordered buffers to initialize dquot buffers during quotacheck
  xfs: don't fail verifier on empty attr3 leaf block
  i2c: xiic: Add platform module alias
  HID: saitek: add madcatz variant of MMO7 mouse device ID
  scsi: core: Restrict legal sdev_state transitions via sysfs
  media: meson: vdec: fix possible refcount leak in vdec_probe()
  media: dvb-frontends/drxk: initialize err to 0
  media: cros-ec-cec: limit msg.len to CEC_MAX_MSG_SIZE
  media: s5p_cec: limit msg.len to CEC_MAX_MSG_SIZE
  ipv6: fix WARNING in ip6_route_net_exit_late()
  net, neigh: Fix null-ptr-deref in neigh_table_clear()
  net: mdio: fix undefined behavior in bit shift for __mdiobus_register
  Bluetooth: L2CAP: fix use-after-free in l2cap_conn_del()
  Bluetooth: L2CAP: Fix use-after-free caused by l2cap_reassemble_sdu
  btrfs: fix ulist leaks in error paths of qgroup self tests
  btrfs: fix inode list leak during backref walking at find_parent_nodes()
  btrfs: fix inode list leak during backref walking at resolve_indirect_refs()
  isdn: mISDN: netjet: fix wrong check of device registration
  mISDN: fix possible memory leak in mISDN_register_device()
  rose: Fix NULL pointer dereference in rose_send_frame()
  ipvs: fix WARNING in ip_vs_app_net_cleanup()
  ipvs: fix WARNING in __ip_vs_cleanup_batch()
  ipvs: use explicitly signed chars
  netfilter: nf_tables: release flow rule object from commit path
  net: tun: fix bugs for oversize packet when napi frags enabled
  net: sched: Fix use after free in red_enqueue()
  ata: pata_legacy: fix pdc20230_set_piomode()
  net: fec: fix improper use of NETDEV_TX_BUSY
  nfc: nfcmrvl: Fix potential memory leak in nfcmrvl_i2c_nci_send()
  nfc: s3fwrn5: Fix potential memory leak in s3fwrn5_nci_send()
  RDMA/qedr: clean up work queue on failure in qedr_alloc_resources()
  RDMA/core: Fix null-ptr-deref in ib_core_cleanup()
  net: dsa: Fix possible memory leaks in dsa_loop_init()
  nfs4: Fix kmemleak when allocate slot failed
  NFSv4.1: We must always send RECLAIM_COMPLETE after a reboot
  NFSv4.1: Handle RECLAIM_COMPLETE trunking errors
  IB/hfi1: Correctly move list in sc_disable()
  RDMA/cma: Use output interface for net_dev check
  Linux 5.4.223
  can: rcar_canfd: rcar_canfd_handle_global_receive(): fix IRQ storm on global FIFO receive
  net: enetc: survive memory pressure without crashing
  net/mlx5: Fix possible use-after-free in async command interface
  net/mlx5e: Do not increment ESN when updating IPsec ESN state
  nh: fix scope used to find saddr when adding non gw nh
  net: ehea: fix possible memory leak in ehea_register_port()
  openvswitch: switch from WARN to pr_warn
  ALSA: aoa: Fix I2S device accounting
  ALSA: aoa: i2sbus: fix possible memory leak in i2sbus_add_dev()
  PM: domains: Fix handling of unavailable/disabled idle states
  net: ksz884x: fix missing pci_disable_device() on error in pcidev_init()
  i40e: Fix flow-type by setting GL_HASH_INSET registers
  i40e: Fix VF hang when reset is triggered on another VF
  i40e: Fix ethtool rx-flow-hash setting for X722
  media: videodev2.h: V4L2_DV_BT_BLANKING_HEIGHT should check 'interlaced'
  media: v4l2-dv-timings: add sanity checks for blanking values
  media: vivid: dev->bitmap_cap wasn't freed in all cases
  media: vivid: s_fbuf: add more sanity checks
  PM: hibernate: Allow hybrid sleep to work with s2idle
  can: mscan: mpc5xxx: mpc5xxx_can_probe(): add missing put_clock() in error path
  tcp: fix indefinite deferral of RTO with SACK reneging
  net: lantiq_etop: don't free skb when returning NETDEV_TX_BUSY
  net: fix UAF issue in nfqnl_nf_hook_drop() when ops_init() failed
  kcm: annotate data-races around kcm->rx_wait
  kcm: annotate data-races around kcm->rx_psock
  amd-xgbe: add the bit rate quirk for Molex cables
  amd-xgbe: fix the SFP compliance codes check for DAC cables
  x86/unwind/orc: Fix unreliable stack dump with gcov
  net: netsec: fix error handling in netsec_register_mdio()
  tipc: fix a null-ptr-deref in tipc_topsrv_accept
  ALSA: ac97: fix possible memory leak in snd_ac97_dev_register()
  arc: iounmap() arg is volatile
  drm/msm: Fix return type of mdp4_lvds_connector_mode_valid
  media: v4l2: Fix v4l2_i2c_subdev_set_name function documentation
  net: ieee802154: fix error return code in dgram_bind()
  mm,hugetlb: take hugetlb_lock before decrementing h->resv_huge_pages
  cgroup-v1: add disabled controller check in cgroup1_parse_param()
  xen/gntdev: Prevent leaking grants
  Xen/gntdev: don't ignore kernel unmapping error
  xfs: force the log after remapping a synchronous-writes file
  xfs: clear XFS_DQ_FREEING if we can't lock the dquot buffer to flush
  xfs: finish dfops on every insert range shift iteration
  s390/pci: add missing EX_TABLE entries to __pcistg_mio_inuser()/__pcilg_mio_inuser()
  s390/futex: add missing EX_TABLE entry to __futex_atomic_op()
  perf auxtrace: Fix address filter symbol name match for modules
  kernfs: fix use-after-free in __kernfs_remove
  mmc: core: Fix kernel panic when remove non-standard SDIO card
  drm/msm/hdmi: fix memory corruption with too many bridges
  drm/msm/dsi: fix memory corruption with too many bridges
  mac802154: Fix LQI recording
  fbdev: smscufx: Fix several use-after-free bugs
  iio: light: tsl2583: Fix module unloading
  tools: iio: iio_utils: fix digit calculation
  xhci: Remove device endpoints from bandwidth list when freeing the device
  mtd: rawnand: marvell: Use correct logic for nand-keep-config
  usb: xhci: add XHCI_SPURIOUS_SUCCESS to ASM1042 despite being a V0.96 controller
  usb: bdc: change state when port disconnected
  usb: dwc3: gadget: Don't set IMI for no_interrupt
  usb: dwc3: gadget: Stop processing more requests on IMI
  USB: add RESET_RESUME quirk for NVIDIA Jetson devices in RCM
  ALSA: au88x0: use explicitly signed char
  ALSA: Use del_timer_sync() before freeing timer
  can: kvaser_usb: Fix possible completions during init_completion
  can: j1939: transport: j1939_session_skb_drop_old(): spin_unlock_irqrestore() before kfree_skb()
  UPSTREAM: once: fix section mismatch on clang builds
  ANDROID: fix up struct sk_buf ABI breakage
  ANDROID: fix up CRC issue with struct tcp_sock
  Linux 5.4.222
  once: fix section mismatch on clang builds
  ANDROID: fix up 131287ff83 ("once: add DO_ONCE_SLOW() for sleepable contexts")
  Revert "serial: 8250: Fix restoring termios speed after suspend"
  Linux 5.4.221
  mm: /proc/pid/smaps_rollup: fix no vma's null-deref
  hv_netvsc: Fix race between VF offering and VF association message from host
  Makefile.debug: re-enable debug info for .S files
  ACPI: video: Force backlight native for more TongFang devices
  riscv: topology: fix default topology reporting
  arm64: topology: move store_cpu_topology() to shared code
  iommu/vt-d: Clean up si_domain in the init_dmars() error path
  net: hns: fix possible memory leak in hnae_ae_register()
  net: sched: cake: fix null pointer access issue when cake_init() fails
  net: phy: dp83867: Extend RX strap quirk for SGMII mode
  net/atm: fix proc_mpc_write incorrect return value
  HID: magicmouse: Do not set BTN_MOUSE on double report
  tipc: fix an information leak in tipc_topsrv_kern_subscr
  tipc: Fix recognition of trial period
  ACPI: extlog: Handle multiple records
  btrfs: fix processing of delayed tree block refs during backref walking
  btrfs: fix processing of delayed data refs during backref walking
  r8152: add PID for the Lenovo OneLink+ Dock
  arm64: errata: Remove AES hwcap for COMPAT tasks
  media: venus: dec: Handle the case where find_format fails
  KVM: arm64: vgic: Fix exit condition in scan_its_table()
  ata: ahci: Match EM_MAX_SLOTS with SATA_PMP_MAX_PORTS
  ata: ahci-imx: Fix MODULE_ALIAS
  hwmon/coretemp: Handle large core ID value
  x86/microcode/AMD: Apply the patch early on every logical thread
  ocfs2: fix BUG when iput after ocfs2_mknod fails
  ocfs2: clear dinode links count in case of error
  xfs: fix use-after-free on CIL context on shutdown
  xfs: move inode flush to the sync workqueue
  xfs: reflink should force the log out if mounted with wsync
  xfs: factor out a new xfs_log_force_inode helper
  xfs: trylock underlying buffer on dquot flush
  xfs: don't write a corrupt unmount record to force summary counter recalc
  xfs: tail updates only need to occur when LSN changes
  xfs: factor common AIL item deletion code
  xfs: Throttle commits on delayed background CIL push
  xfs: Lower CIL flush limit for large logs
  xfs: preserve default grace interval during quotacheck
  xfs: fix unmount hang and memory leak on shutdown during quotaoff
  xfs: factor out quotaoff intent AIL removal and memory free
  xfs: Replace function declaration by actual definition
  xfs: remove the xfs_qoff_logitem_t typedef
  xfs: remove the xfs_dq_logitem_t typedef
  xfs: remove the xfs_disk_dquot_t and xfs_dquot_t
  xfs: Use scnprintf() for avoiding potential buffer overflow
  xfs: check owner of dir3 blocks
  xfs: check owner of dir3 data blocks
  xfs: fix buffer corruption reporting when xfs_dir3_free_header_check fails
  xfs: xfs_buf_corruption_error should take __this_address
  xfs: add a function to deal with corrupt buffers post-verifiers
  xfs: rework collapse range into an atomic operation
  xfs: rework insert range into an atomic operation
  xfs: open code insert range extent split helper
  Linux 5.4.220
  thermal: intel_powerclamp: Use first online CPU as control_cpu
  inet: fully convert sk->sk_rx_dst to RCU rules
  efi: libstub: drop pointless get_memory_map() call
  md: Replace snprintf with scnprintf
  ext4: continue to expand file system when the target size doesn't reach
  net/ieee802154: don't warn zero-sized raw_sendmsg()
  Revert "net/ieee802154: reject zero-sized raw_sendmsg()"
  net: ieee802154: return -EINVAL for unknown addr type
  io_uring/af_unix: defer registered files gc to io_uring release
  perf intel-pt: Fix segfault in intel_pt_print_info() with uClibc
  clk: bcm2835: Make peripheral PLLC critical
  usb: idmouse: fix an uninit-value in idmouse_open
  nvmet-tcp: add bounds check on Transfer Tag
  nvme: copy firmware_rev on each init
  staging: rtl8723bs: fix a potential memory leak in rtw_init_cmd_priv()
  Revert "usb: storage: Add quirk for Samsung Fit flash"
  usb: musb: Fix musb_gadget.c rxstate overflow bug
  usb: host: xhci: Fix potential memory leak in xhci_alloc_stream_info()
  md/raid5: Wait for MD_SB_CHANGE_PENDING in raid5d
  HID: roccat: Fix use-after-free in roccat_read()
  bcache: fix set_at_max_writeback_rate() for multiple attached devices
  ata: libahci_platform: Sanity check the DT child nodes number
  staging: vt6655: fix potential memory leak
  power: supply: adp5061: fix out-of-bounds read in adp5061_get_chg_type()
  nbd: Fix hung when signal interrupts nbd_start_device_ioctl()
  scsi: 3w-9xxx: Avoid disabling device if failing to enable it
  clk: zynqmp: pll: rectify rate rounding in zynqmp_pll_round_rate
  media: cx88: Fix a null-ptr-deref bug in buffer_prepare()
  clk: zynqmp: Fix stack-out-of-bounds in strncpy`
  btrfs: scrub: try to fix super block errors
  ARM: dts: imx6sx: add missing properties for sram
  ARM: dts: imx6sll: add missing properties for sram
  ARM: dts: imx6sl: add missing properties for sram
  ARM: dts: imx6qp: add missing properties for sram
  ARM: dts: imx6dl: add missing properties for sram
  ARM: dts: imx6q: add missing properties for sram
  ARM: dts: imx7d-sdb: config the max pressure for tsc2046
  mmc: sdhci-msm: add compatible string check for sdm670
  drm/amdgpu: fix initial connector audio value
  platform/x86: msi-laptop: Change DMI match / alias strings to fix module autoloading
  drm: panel-orientation-quirks: Add quirk for Anbernic Win600
  drm/vc4: vec: Fix timings for VEC modes
  drm/amd/display: fix overflow on MIN_I64 definition
  drm: Prevent drm_copy_field() to attempt copying a NULL pointer
  drm: Use size_t type for len variable in drm_copy_field()
  drm/nouveau/nouveau_bo: fix potential memory leak in nouveau_bo_alloc()
  r8152: Rate limit overflow messages
  Bluetooth: L2CAP: Fix user-after-free
  net: If sock is dead don't access sock's sk_wq in sk_stream_wait_memory
  wifi: rt2x00: correctly set BBP register 86 for MT7620
  wifi: rt2x00: set SoC wmac clock register
  wifi: rt2x00: set VGC gain for both chains of MT7620
  wifi: rt2x00: set correct TX_SW_CFG1 MAC register for MT7620
  wifi: rt2x00: don't run Rt5592 IQ calibration on MT7620
  can: bcm: check the result of can_send() in bcm_can_tx()
  Bluetooth: hci_sysfs: Fix attempting to call device_add multiple times
  Bluetooth: L2CAP: initialize delayed works at l2cap_chan_create()
  wifi: brcmfmac: fix use-after-free bug in brcmf_netdev_start_xmit()
  xfrm: Update ipcomp_scratches with NULL when freed
  wifi: ath9k: avoid uninit memory read in ath9k_htc_rx_msg()
  tcp: annotate data-race around tcp_md5sig_pool_populated
  openvswitch: Fix overreporting of drops in dropwatch
  openvswitch: Fix double reporting of drops in dropwatch
  bpftool: Clear errno after libcap's checks
  wifi: brcmfmac: fix invalid address access when enabling SCAN log level
  NFSD: Return nfserr_serverfault if splice_ok but buf->pages have data
  thermal: intel_powerclamp: Use get_cpu() instead of smp_processor_id() to avoid crash
  powercap: intel_rapl: fix UBSAN shift-out-of-bounds issue
  MIPS: BCM47XX: Cast memcmp() of function to (void *)
  ACPI: video: Add Toshiba Satellite/Portege Z830 quirk
  f2fs: fix race condition on setting FI_NO_EXTENT flag
  crypto: cavium - prevent integer overflow loading firmware
  kbuild: remove the target in signal traps when interrupted
  iommu/iova: Fix module config properly
  crypto: ccp - Release dma channels before dmaengine unrgister
  crypto: akcipher - default implementation for setting a private key
  iommu/omap: Fix buffer overflow in debugfs
  cgroup/cpuset: Enable update_tasks_cpumask() on top_cpuset
  powerpc: Fix SPE Power ISA properties for e500v1 platforms
  powerpc/64s: Fix GENERIC_CPU build flags for PPC970 / G5
  x86/hyperv: Fix 'struct hv_enlightened_vmcs' definition
  powerpc/powernv: add missing of_node_put() in opal_export_attrs()
  powerpc/pci_dn: Add missing of_node_put()
  powerpc/sysdev/fsl_msi: Add missing of_node_put()
  powerpc/math_emu/efp: Include module.h
  mailbox: bcm-ferxrm-mailbox: Fix error check for dma_map_sg
  clk: ast2600: BCLK comes from EPLL
  clk: ti: dra7-atl: Fix reference leak in of_dra7_atl_clk_probe
  clk: bcm2835: fix bcm2835_clock_rate_from_divisor declaration
  spmi: pmic-arb: correct duplicate APID to PPID mapping logic
  dmaengine: ioat: stop mod_timer from resurrecting deleted timer in __cleanup()
  clk: mediatek: mt8183: mfgcfg: Propagate rate changes to parent
  mfd: sm501: Add check for platform_driver_register()
  mfd: fsl-imx25: Fix check for platform_get_irq() errors
  mfd: lp8788: Fix an error handling path in lp8788_irq_init() and lp8788_irq_init()
  mfd: lp8788: Fix an error handling path in lp8788_probe()
  mfd: fsl-imx25: Fix an error handling path in mx25_tsadc_setup_irq()
  mfd: intel_soc_pmic: Fix an error handling path in intel_soc_pmic_i2c_probe()
  fsi: core: Check error number after calling ida_simple_get
  scsi: libsas: Fix use-after-free bug in smp_execute_task_sg()
  serial: 8250: Fix restoring termios speed after suspend
  firmware: google: Test spinlock on panic path to avoid lockups
  staging: vt6655: fix some erroneous memory clean-up loops
  phy: qualcomm: call clk_disable_unprepare in the error handling
  tty: serial: fsl_lpuart: disable dma rx/tx use flags in lpuart_dma_shutdown
  drivers: serial: jsm: fix some leaks in probe
  usb: gadget: function: fix dangling pnp_string in f_printer.c
  xhci: Don't show warning for reinit on known broken suspend
  md/raid5: Ensure stripe_fill happens on non-read IO with journal
  mtd: rawnand: meson: fix bit map use in meson_nfc_ecc_correct()
  ata: fix ata_id_has_dipm()
  ata: fix ata_id_has_ncq_autosense()
  ata: fix ata_id_has_devslp()
  ata: fix ata_id_sense_reporting_enabled() and ata_id_has_sense_reporting()
  RDMA/siw: Always consume all skbuf data in sk_data_ready() upcall.
  mtd: devices: docg3: check the return value of devm_ioremap() in the probe
  dyndbg: let query-modname override actual module name
  dyndbg: fix module.dyndbg handling
  misc: ocxl: fix possible refcount leak in afu_ioctl()
  RDMA/rxe: Fix the error caused by qp->sk
  RDMA/rxe: Fix "kernel NULL pointer dereference" error
  media: xilinx: vipp: Fix refcount leak in xvip_graph_dma_init
  tty: xilinx_uartps: Fix the ignore_status
  media: exynos4-is: fimc-is: Add of_node_put() when breaking out of loop
  HSI: omap_ssi_port: Fix dma_map_sg error check
  HSI: omap_ssi: Fix refcount leak in ssi_probe
  clk: tegra20: Fix refcount leak in tegra20_clock_init
  clk: tegra: Fix refcount leak in tegra114_clock_init
  clk: tegra: Fix refcount leak in tegra210_clock_init
  clk: berlin: Add of_node_put() for of_get_parent()
  clk: oxnas: Hold reference returned by of_get_parent()
  clk: meson: Hold reference returned by of_get_parent()
  iio: ABI: Fix wrong format of differential capacitance channel ABI.
  iio: inkern: only release the device node when done with it
  iio: adc: at91-sama5d2_adc: lock around oversampling and sample freq
  iio: adc: at91-sama5d2_adc: check return status for pressure and touch
  iio: adc: at91-sama5d2_adc: fix AT91_SAMA5D2_MR_TRACKTIM_MAX
  ARM: dts: exynos: fix polarity of VBUS GPIO of Origen
  ARM: Drop CMDLINE_* dependency on ATAGS
  ARM: dts: exynos: correct s5k6a3 reset polarity on Midas family
  ARM: dts: kirkwood: lsxl: remove first ethernet port
  ARM: dts: kirkwood: lsxl: fix serial line
  ARM: dts: turris-omnia: Fix mpp26 pin name and comment
  soc: qcom: smem_state: Add refcounting for the 'state->of_node'
  soc: qcom: smsm: Fix refcount leak bugs in qcom_smsm_probe()
  memory: of: Fix refcount leak bug in of_get_ddr_timings()
  memory: pl353-smc: Fix refcount leak bug in pl353_smc_probe()
  ALSA: hda/hdmi: Don't skip notification handling during PM operation
  ASoC: wm5102: Fix PM disable depth imbalance in wm5102_probe
  ASoC: wm5110: Fix PM disable depth imbalance in wm5110_probe
  ASoC: wm8997: Fix PM disable depth imbalance in wm8997_probe
  mmc: wmt-sdmmc: Fix an error handling path in wmt_mci_probe()
  ALSA: dmaengine: increment buffer pointer atomically
  drm/msm/dpu: index dpu_kms->hw_vbif using vbif_idx
  ASoC: eureka-tlv320: Hold reference returned from of_find_xxx API
  mmc: au1xmmc: Fix an error handling path in au1xmmc_probe()
  drm/omap: dss: Fix refcount leak bugs
  ALSA: hda: beep: Simplify keep-power-at-enable behavior
  ASoC: rsnd: Add check for rsnd_mod_power_on
  drm/bridge: megachips: Fix a null pointer dereference bug
  drm: fix drm_mipi_dbi build errors
  platform/x86: msi-laptop: Fix resource cleanup
  platform/x86: msi-laptop: Fix old-ec check for backlight registering
  platform/chrome: fix memory corruption in ioctl
  platform/chrome: fix double-free in chromeos_laptop_prepare()
  drm/mipi-dsi: Detach devices when removing the host
  drm: bridge: adv7511: fix CEC power down control register offset
  net: mvpp2: fix mvpp2 debugfs leak
  once: add DO_ONCE_SLOW() for sleepable contexts
  net/ieee802154: reject zero-sized raw_sendmsg()
  bnx2x: fix potential memory leak in bnx2x_tpa_stop()
  net: rds: don't hold sock lock when cancelling work from rds_tcp_reset_callbacks()
  tcp: fix tcp_cwnd_validate() to not forget is_cwnd_limited
  sctp: handle the error returned from sctp_auth_asoc_init_active_key
  mISDN: fix use-after-free bugs in l1oip timer handlers
  vhost/vsock: Use kvmalloc/kvfree for larger packets.
  spi: s3c64xx: Fix large transfers with DMA
  netfilter: nft_fib: Fix for rpath check with VRF devices
  spi/omap100k:Fix PM disable depth imbalance in omap1_spi100k_probe
  x86/microcode/AMD: Track patch allocation size explicitly
  bpf: Ensure correct locking around vulnerable function find_vpid()
  net: fs_enet: Fix wrong check in do_pd_setup
  wifi: rtl8xxxu: gen2: Fix mistake in path B IQ calibration
  bpf: btf: fix truncated last_member_type_id in btf_struct_resolve
  wifi: rtl8xxxu: Fix skb misuse in TX queue selection
  spi: qup: add missing clk_disable_unprepare on error in spi_qup_pm_resume_runtime()
  spi: qup: add missing clk_disable_unprepare on error in spi_qup_resume()
  wifi: rtl8xxxu: tighten bounds checking in rtl8xxxu_read_efuse()
  x86/resctrl: Fix to restore to original value when re-enabling hardware prefetch register
  bpftool: Fix a wrong type cast in btf_dumper_int
  wifi: mac80211: allow bw change during channel switch in mesh
  wifi: ath10k: add peer map clean up for peer delete in ath10k_sta_state()
  nfsd: Fix a memory leak in an error handling path
  ARM: 9247/1: mm: set readonly for MT_MEMORY_RO with ARM_LPAE
  sh: machvec: Use char[] for section boundaries
  userfaultfd: open userfaultfds with O_RDONLY
  tracing: Disable interrupt or preemption before acquiring arch_spinlock_t
  selinux: use "grep -E" instead of "egrep"
  drm/nouveau: fix a use-after-free in nouveau_gem_prime_import_sg_table()
  gcov: support GCC 12.1 and newer compilers
  KVM: VMX: Drop bits 31:16 when shoving exception error code into VMCS
  KVM: nVMX: Unconditionally purge queued/injected events on nested "exit"
  KVM: x86/emulator: Fix handing of POP SS to correctly set interruptibility
  media: cedrus: Set the platform driver data earlier
  ring-buffer: Fix race between reset page and reading page
  ring-buffer: Check pending waiters when doing wake ups as well
  ring-buffer: Have the shortest_full queue be the shortest not longest
  ring-buffer: Allow splice to read previous partially read pages
  ftrace: Properly unset FTRACE_HASH_FL_MOD
  livepatch: fix race between fork and KLP transition
  ext4: place buffer head allocation before handle start
  ext4: make ext4_lazyinit_thread freezable
  ext4: fix null-ptr-deref in ext4_write_info
  ext4: avoid crash when inline data creation follows DIO write
  jbd2: wake up journal waiters in FIFO order, not LIFO
  nilfs2: fix use-after-free bug of struct nilfs_root
  f2fs: fix to do sanity check on summary info
  f2fs: fix to do sanity check on destination blkaddr during recovery
  f2fs: increase the limit for reserve_root
  btrfs: fix race between quota enable and quota rescan ioctl
  fbdev: smscufx: Fix use-after-free in ufx_ops_open()
  powerpc/boot: Explicitly disable usage of SPE instructions
  PCI: Sanitise firmware BAR assignments behind a PCI-PCI bridge
  UM: cpuinfo: Fix a warning for CONFIG_CPUMASK_OFFSTACK
  riscv: Pass -mno-relax only on lld < 15.0.0
  riscv: Allow PROT_WRITE-only mmap()
  parisc: fbdev/stifb: Align graphics memory size to 4MB
  RISC-V: Make port I/O string accessors actually work
  regulator: qcom_rpm: Fix circular deferral regression
  ASoC: wcd9335: fix order of Slimbus unprepare/disable
  quota: Check next/prev free block number after reading from quota file
  HID: multitouch: Add memory barriers
  fs: dlm: handle -EBUSY first in lock arg validation
  fs: dlm: fix race between test_bit() and queue_work()
  mmc: sdhci-sprd: Fix minimum clock limit
  can: kvaser_usb_leaf: Fix CAN state after restart
  can: kvaser_usb_leaf: Fix TX queue out of sync after restart
  can: kvaser_usb_leaf: Fix overread with an invalid command
  can: kvaser_usb: Fix use of uninitialized completion
  usb: add quirks for Lenovo OneLink+ Dock
  iio: pressure: dps310: Reset chip after timeout
  iio: pressure: dps310: Refactor startup procedure
  iio: dac: ad5593r: Fix i2c read protocol requirements
  cifs: Fix the error length of VALIDATE_NEGOTIATE_INFO message
  cifs: destage dirty pages before re-reading them for cache=none
  mtd: rawnand: atmel: Unmap streaming DMA mappings
  ALSA: hda/realtek: Add Intel Reference SSID to support headset keys
  ALSA: hda/realtek: Add quirk for ASUS GV601R laptop
  ALSA: hda/realtek: Correct pin configs for ASUS G533Z
  ALSA: hda/realtek: remove ALC289_FIXUP_DUAL_SPK for Dell 5530
  ALSA: usb-audio: Fix NULL dererence at error path
  ALSA: usb-audio: Fix potential memory leaks
  ALSA: rawmidi: Drop register_mutex in snd_rawmidi_free()
  ALSA: oss: Fix potential deadlock at unregistration

 Conflicts:
	drivers/android/binder.c
	include/linux/rmap.h
	kernel/cgroup/cpuset.c
	mm/rmap.c

Change-Id: I34fe2d5c9b0d5844560de9c983867511b5d57265
2023-02-08 18:28:38 +02:00

2002 lines
52 KiB
C

// SPDX-License-Identifier: GPL-2.0-only
/*
* fs/userfaultfd.c
*
* Copyright (C) 2007 Davide Libenzi <davidel@xmailserver.org>
* Copyright (C) 2008-2009 Red Hat, Inc.
* Copyright (C) 2015 Red Hat, Inc.
*
* Some part derived from fs/eventfd.c (anon inode setup) and
* mm/ksm.c (mm hashing).
*/
#include <linux/list.h>
#include <linux/hashtable.h>
#include <linux/sched/signal.h>
#include <linux/sched/mm.h>
#include <linux/mm.h>
#include <linux/poll.h>
#include <linux/slab.h>
#include <linux/seq_file.h>
#include <linux/file.h>
#include <linux/bug.h>
#include <linux/anon_inodes.h>
#include <linux/syscalls.h>
#include <linux/userfaultfd_k.h>
#include <linux/mempolicy.h>
#include <linux/ioctl.h>
#include <linux/security.h>
#include <linux/hugetlb.h>
int sysctl_unprivileged_userfaultfd __read_mostly = 1;
static struct kmem_cache *userfaultfd_ctx_cachep __read_mostly;
/*
* Start with fault_pending_wqh and fault_wqh so they're more likely
* to be in the same cacheline.
*
* Locking order:
* fd_wqh.lock
* fault_pending_wqh.lock
* fault_wqh.lock
* event_wqh.lock
*
* To avoid deadlocks, IRQs must be disabled when taking any of the above locks,
* since fd_wqh.lock is taken by aio_poll() while it's holding a lock that's
* also taken in IRQ context.
*/
struct userfaultfd_ctx {
/* waitqueue head for the pending (i.e. not read) userfaults */
wait_queue_head_t fault_pending_wqh;
/* waitqueue head for the userfaults */
wait_queue_head_t fault_wqh;
/* waitqueue head for the pseudo fd to wakeup poll/read */
wait_queue_head_t fd_wqh;
/* waitqueue head for events */
wait_queue_head_t event_wqh;
/* a refile sequence protected by fault_pending_wqh lock */
struct seqcount refile_seq;
/* pseudo fd refcounting */
refcount_t refcount;
/* userfaultfd syscall flags */
unsigned int flags;
/* features requested from the userspace */
unsigned int features;
/* released */
bool released;
/* memory mappings are changing because of non-cooperative event */
bool mmap_changing;
/* mm with one ore more vmas attached to this userfaultfd_ctx */
struct mm_struct *mm;
};
struct userfaultfd_fork_ctx {
struct userfaultfd_ctx *orig;
struct userfaultfd_ctx *new;
struct list_head list;
};
struct userfaultfd_unmap_ctx {
struct userfaultfd_ctx *ctx;
unsigned long start;
unsigned long end;
struct list_head list;
};
struct userfaultfd_wait_queue {
struct uffd_msg msg;
wait_queue_entry_t wq;
struct userfaultfd_ctx *ctx;
bool waken;
};
struct userfaultfd_wake_range {
unsigned long start;
unsigned long len;
};
/* internal indication that UFFD_API ioctl was successfully executed */
#define UFFD_FEATURE_INITIALIZED (1u << 31)
static bool userfaultfd_is_initialized(struct userfaultfd_ctx *ctx)
{
return ctx->features & UFFD_FEATURE_INITIALIZED;
}
static int userfaultfd_wake_function(wait_queue_entry_t *wq, unsigned mode,
int wake_flags, void *key)
{
struct userfaultfd_wake_range *range = key;
int ret;
struct userfaultfd_wait_queue *uwq;
unsigned long start, len;
uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
ret = 0;
/* len == 0 means wake all */
start = range->start;
len = range->len;
if (len && (start > uwq->msg.arg.pagefault.address ||
start + len <= uwq->msg.arg.pagefault.address))
goto out;
WRITE_ONCE(uwq->waken, true);
/*
* The Program-Order guarantees provided by the scheduler
* ensure uwq->waken is visible before the task is woken.
*/
ret = wake_up_state(wq->private, mode);
if (ret) {
/*
* Wake only once, autoremove behavior.
*
* After the effect of list_del_init is visible to the other
* CPUs, the waitqueue may disappear from under us, see the
* !list_empty_careful() in handle_userfault().
*
* try_to_wake_up() has an implicit smp_mb(), and the
* wq->private is read before calling the extern function
* "wake_up_state" (which in turns calls try_to_wake_up).
*/
list_del_init(&wq->entry);
}
out:
return ret;
}
/**
* userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
* context.
* @ctx: [in] Pointer to the userfaultfd context.
*/
static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
{
refcount_inc(&ctx->refcount);
}
/**
* userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
* context.
* @ctx: [in] Pointer to userfaultfd context.
*
* The userfaultfd context reference must have been previously acquired either
* with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
*/
static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
{
if (refcount_dec_and_test(&ctx->refcount)) {
VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));
VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));
VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));
VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));
VM_BUG_ON(spin_is_locked(&ctx->event_wqh.lock));
VM_BUG_ON(waitqueue_active(&ctx->event_wqh));
VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));
VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));
mmdrop(ctx->mm);
kmem_cache_free(userfaultfd_ctx_cachep, ctx);
}
}
static inline void msg_init(struct uffd_msg *msg)
{
BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
/*
* Must use memset to zero out the paddings or kernel data is
* leaked to userland.
*/
memset(msg, 0, sizeof(struct uffd_msg));
}
static inline struct uffd_msg userfault_msg(unsigned long address,
unsigned int flags,
unsigned long reason,
unsigned int features)
{
struct uffd_msg msg;
msg_init(&msg);
msg.event = UFFD_EVENT_PAGEFAULT;
msg.arg.pagefault.address = address;
if (flags & FAULT_FLAG_WRITE)
/*
* If UFFD_FEATURE_PAGEFAULT_FLAG_WP was set in the
* uffdio_api.features and UFFD_PAGEFAULT_FLAG_WRITE
* was not set in a UFFD_EVENT_PAGEFAULT, it means it
* was a read fault, otherwise if set it means it's
* a write fault.
*/
msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
if (reason & VM_UFFD_WP)
/*
* If UFFD_FEATURE_PAGEFAULT_FLAG_WP was set in the
* uffdio_api.features and UFFD_PAGEFAULT_FLAG_WP was
* not set in a UFFD_EVENT_PAGEFAULT, it means it was
* a missing fault, otherwise if set it means it's a
* write protect fault.
*/
msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
if (features & UFFD_FEATURE_THREAD_ID)
msg.arg.pagefault.feat.ptid = task_pid_vnr(current);
return msg;
}
#ifdef CONFIG_HUGETLB_PAGE
/*
* Same functionality as userfaultfd_must_wait below with modifications for
* hugepmd ranges.
*/
static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
struct vm_area_struct *vma,
unsigned long address,
unsigned long flags,
unsigned long reason)
{
struct mm_struct *mm = ctx->mm;
pte_t *ptep, pte;
bool ret = true;
VM_BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
ptep = huge_pte_offset(mm, address, vma_mmu_pagesize(vma));
if (!ptep)
goto out;
ret = false;
pte = huge_ptep_get(ptep);
/*
* Lockless access: we're in a wait_event so it's ok if it
* changes under us.
*/
if (huge_pte_none(pte))
ret = true;
if (!huge_pte_write(pte) && (reason & VM_UFFD_WP))
ret = true;
out:
return ret;
}
#else
static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
struct vm_area_struct *vma,
unsigned long address,
unsigned long flags,
unsigned long reason)
{
return false; /* should never get here */
}
#endif /* CONFIG_HUGETLB_PAGE */
/*
* Verify the pagetables are still not ok after having reigstered into
* the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
* userfault that has already been resolved, if userfaultfd_read and
* UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
* threads.
*/
static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
unsigned long address,
unsigned long flags,
unsigned long reason)
{
struct mm_struct *mm = ctx->mm;
pgd_t *pgd;
p4d_t *p4d;
pud_t *pud;
pmd_t *pmd, _pmd;
pte_t *pte;
bool ret = true;
VM_BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
pgd = pgd_offset(mm, address);
if (!pgd_present(*pgd))
goto out;
p4d = p4d_offset(pgd, address);
if (!p4d_present(*p4d))
goto out;
pud = pud_offset(p4d, address);
if (!pud_present(*pud))
goto out;
pmd = pmd_offset(pud, address);
/*
* READ_ONCE must function as a barrier with narrower scope
* and it must be equivalent to:
* _pmd = *pmd; barrier();
*
* This is to deal with the instability (as in
* pmd_trans_unstable) of the pmd.
*/
_pmd = READ_ONCE(*pmd);
if (pmd_none(_pmd))
goto out;
ret = false;
if (!pmd_present(_pmd))
goto out;
if (pmd_trans_huge(_pmd))
goto out;
/*
* the pmd is stable (as in !pmd_trans_unstable) so we can re-read it
* and use the standard pte_offset_map() instead of parsing _pmd.
*/
pte = pte_offset_map(pmd, address);
/*
* Lockless access: we're in a wait_event so it's ok if it
* changes under us.
*/
if (pte_none(*pte))
ret = true;
pte_unmap(pte);
out:
return ret;
}
/*
* The locking rules involved in returning VM_FAULT_RETRY depending on
* FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
* FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
* recommendation in __lock_page_or_retry is not an understatement.
*
* If FAULT_FLAG_ALLOW_RETRY is set, the mmap_sem must be released
* before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
* not set.
*
* If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
* set, VM_FAULT_RETRY can still be returned if and only if there are
* fatal_signal_pending()s, and the mmap_sem must be released before
* returning it.
*/
vm_fault_t handle_userfault(struct vm_fault *vmf, unsigned long reason)
{
struct mm_struct *mm = vmf->vma->vm_mm;
struct userfaultfd_ctx *ctx;
struct userfaultfd_wait_queue uwq;
vm_fault_t ret = VM_FAULT_SIGBUS;
bool must_wait, return_to_userland;
long blocking_state;
/*
* We don't do userfault handling for the final child pid update.
*
* We also don't do userfault handling during
* coredumping. hugetlbfs has the special
* follow_hugetlb_page() to skip missing pages in the
* FOLL_DUMP case, anon memory also checks for FOLL_DUMP with
* the no_page_table() helper in follow_page_mask(), but the
* shmem_vm_ops->fault method is invoked even during
* coredumping without mmap_sem and it ends up here.
*/
if (current->flags & (PF_EXITING|PF_DUMPCORE))
goto out;
/*
* Coredumping runs without mmap_sem so we can only check that
* the mmap_sem is held, if PF_DUMPCORE was not set.
*/
WARN_ON_ONCE(!rwsem_is_locked(&mm->mmap_sem));
ctx = vmf->vma->vm_userfaultfd_ctx.ctx;
if (!ctx)
goto out;
BUG_ON(ctx->mm != mm);
VM_BUG_ON(reason & ~(VM_UFFD_MISSING|VM_UFFD_WP));
VM_BUG_ON(!(reason & VM_UFFD_MISSING) ^ !!(reason & VM_UFFD_WP));
if (ctx->features & UFFD_FEATURE_SIGBUS)
goto out;
/*
* If it's already released don't get it. This avoids to loop
* in __get_user_pages if userfaultfd_release waits on the
* caller of handle_userfault to release the mmap_sem.
*/
if (unlikely(READ_ONCE(ctx->released))) {
/*
* Don't return VM_FAULT_SIGBUS in this case, so a non
* cooperative manager can close the uffd after the
* last UFFDIO_COPY, without risking to trigger an
* involuntary SIGBUS if the process was starting the
* userfaultfd while the userfaultfd was still armed
* (but after the last UFFDIO_COPY). If the uffd
* wasn't already closed when the userfault reached
* this point, that would normally be solved by
* userfaultfd_must_wait returning 'false'.
*
* If we were to return VM_FAULT_SIGBUS here, the non
* cooperative manager would be instead forced to
* always call UFFDIO_UNREGISTER before it can safely
* close the uffd.
*/
ret = VM_FAULT_NOPAGE;
goto out;
}
/*
* Check that we can return VM_FAULT_RETRY.
*
* NOTE: it should become possible to return VM_FAULT_RETRY
* even if FAULT_FLAG_TRIED is set without leading to gup()
* -EBUSY failures, if the userfaultfd is to be extended for
* VM_UFFD_WP tracking and we intend to arm the userfault
* without first stopping userland access to the memory. For
* VM_UFFD_MISSING userfaults this is enough for now.
*/
if (unlikely(!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))) {
/*
* Validate the invariant that nowait must allow retry
* to be sure not to return SIGBUS erroneously on
* nowait invocations.
*/
BUG_ON(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);
#ifdef CONFIG_DEBUG_VM
if (printk_ratelimit()) {
printk(KERN_WARNING
"FAULT_FLAG_ALLOW_RETRY missing %x\n",
vmf->flags);
dump_stack();
}
#endif
goto out;
}
/*
* Handle nowait, not much to do other than tell it to retry
* and wait.
*/
ret = VM_FAULT_RETRY;
if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
goto out;
/* take the reference before dropping the mmap_sem */
userfaultfd_ctx_get(ctx);
init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
uwq.wq.private = current;
uwq.msg = userfault_msg(vmf->address, vmf->flags, reason,
ctx->features);
uwq.ctx = ctx;
uwq.waken = false;
return_to_userland =
(vmf->flags & (FAULT_FLAG_USER|FAULT_FLAG_KILLABLE)) ==
(FAULT_FLAG_USER|FAULT_FLAG_KILLABLE);
blocking_state = return_to_userland ? TASK_INTERRUPTIBLE :
TASK_KILLABLE;
spin_lock_irq(&ctx->fault_pending_wqh.lock);
/*
* After the __add_wait_queue the uwq is visible to userland
* through poll/read().
*/
__add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
/*
* The smp_mb() after __set_current_state prevents the reads
* following the spin_unlock to happen before the list_add in
* __add_wait_queue.
*/
set_current_state(blocking_state);
spin_unlock_irq(&ctx->fault_pending_wqh.lock);
if (!is_vm_hugetlb_page(vmf->vma))
must_wait = userfaultfd_must_wait(ctx, vmf->address, vmf->flags,
reason);
else
must_wait = userfaultfd_huge_must_wait(ctx, vmf->vma,
vmf->address,
vmf->flags, reason);
up_read(&mm->mmap_sem);
if (likely(must_wait && !READ_ONCE(ctx->released) &&
(return_to_userland ? !signal_pending(current) :
!fatal_signal_pending(current)))) {
wake_up_poll(&ctx->fd_wqh, EPOLLIN);
schedule();
ret |= VM_FAULT_MAJOR;
/*
* False wakeups can orginate even from rwsem before
* up_read() however userfaults will wait either for a
* targeted wakeup on the specific uwq waitqueue from
* wake_userfault() or for signals or for uffd
* release.
*/
while (!READ_ONCE(uwq.waken)) {
/*
* This needs the full smp_store_mb()
* guarantee as the state write must be
* visible to other CPUs before reading
* uwq.waken from other CPUs.
*/
set_current_state(blocking_state);
if (READ_ONCE(uwq.waken) ||
READ_ONCE(ctx->released) ||
(return_to_userland ? signal_pending(current) :
fatal_signal_pending(current)))
break;
schedule();
}
}
__set_current_state(TASK_RUNNING);
if (return_to_userland) {
if (signal_pending(current) &&
!fatal_signal_pending(current)) {
/*
* If we got a SIGSTOP or SIGCONT and this is
* a normal userland page fault, just let
* userland return so the signal will be
* handled and gdb debugging works. The page
* fault code immediately after we return from
* this function is going to release the
* mmap_sem and it's not depending on it
* (unlike gup would if we were not to return
* VM_FAULT_RETRY).
*
* If a fatal signal is pending we still take
* the streamlined VM_FAULT_RETRY failure path
* and there's no need to retake the mmap_sem
* in such case.
*/
down_read(&mm->mmap_sem);
ret = VM_FAULT_NOPAGE;
}
}
/*
* Here we race with the list_del; list_add in
* userfaultfd_ctx_read(), however because we don't ever run
* list_del_init() to refile across the two lists, the prev
* and next pointers will never point to self. list_add also
* would never let any of the two pointers to point to
* self. So list_empty_careful won't risk to see both pointers
* pointing to self at any time during the list refile. The
* only case where list_del_init() is called is the full
* removal in the wake function and there we don't re-list_add
* and it's fine not to block on the spinlock. The uwq on this
* kernel stack can be released after the list_del_init.
*/
if (!list_empty_careful(&uwq.wq.entry)) {
spin_lock_irq(&ctx->fault_pending_wqh.lock);
/*
* No need of list_del_init(), the uwq on the stack
* will be freed shortly anyway.
*/
list_del(&uwq.wq.entry);
spin_unlock_irq(&ctx->fault_pending_wqh.lock);
}
/*
* ctx may go away after this if the userfault pseudo fd is
* already released.
*/
userfaultfd_ctx_put(ctx);
out:
return ret;
}
static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
struct userfaultfd_wait_queue *ewq)
{
struct userfaultfd_ctx *release_new_ctx;
if (WARN_ON_ONCE(current->flags & PF_EXITING))
goto out;
ewq->ctx = ctx;
init_waitqueue_entry(&ewq->wq, current);
release_new_ctx = NULL;
spin_lock_irq(&ctx->event_wqh.lock);
/*
* After the __add_wait_queue the uwq is visible to userland
* through poll/read().
*/
__add_wait_queue(&ctx->event_wqh, &ewq->wq);
for (;;) {
set_current_state(TASK_KILLABLE);
if (ewq->msg.event == 0)
break;
if (READ_ONCE(ctx->released) ||
fatal_signal_pending(current)) {
/*
* &ewq->wq may be queued in fork_event, but
* __remove_wait_queue ignores the head
* parameter. It would be a problem if it
* didn't.
*/
__remove_wait_queue(&ctx->event_wqh, &ewq->wq);
if (ewq->msg.event == UFFD_EVENT_FORK) {
struct userfaultfd_ctx *new;
new = (struct userfaultfd_ctx *)
(unsigned long)
ewq->msg.arg.reserved.reserved1;
release_new_ctx = new;
}
break;
}
spin_unlock_irq(&ctx->event_wqh.lock);
wake_up_poll(&ctx->fd_wqh, EPOLLIN);
schedule();
spin_lock_irq(&ctx->event_wqh.lock);
}
__set_current_state(TASK_RUNNING);
spin_unlock_irq(&ctx->event_wqh.lock);
if (release_new_ctx) {
struct vm_area_struct *vma;
struct mm_struct *mm = release_new_ctx->mm;
/* the various vma->vm_userfaultfd_ctx still points to it */
down_write(&mm->mmap_sem);
/* no task can run (and in turn coredump) yet */
VM_WARN_ON(!mmget_still_valid(mm));
for (vma = mm->mmap; vma; vma = vma->vm_next)
if (vma->vm_userfaultfd_ctx.ctx == release_new_ctx) {
vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
vma->vm_flags &= ~(VM_UFFD_WP | VM_UFFD_MISSING);
}
up_write(&mm->mmap_sem);
userfaultfd_ctx_put(release_new_ctx);
}
/*
* ctx may go away after this if the userfault pseudo fd is
* already released.
*/
out:
WRITE_ONCE(ctx->mmap_changing, false);
userfaultfd_ctx_put(ctx);
}
static void userfaultfd_event_complete(struct userfaultfd_ctx *ctx,
struct userfaultfd_wait_queue *ewq)
{
ewq->msg.event = 0;
wake_up_locked(&ctx->event_wqh);
__remove_wait_queue(&ctx->event_wqh, &ewq->wq);
}
int dup_userfaultfd(struct vm_area_struct *vma, struct list_head *fcs)
{
struct userfaultfd_ctx *ctx = NULL, *octx;
struct userfaultfd_fork_ctx *fctx;
octx = vma->vm_userfaultfd_ctx.ctx;
if (!octx || !(octx->features & UFFD_FEATURE_EVENT_FORK)) {
vm_write_begin(vma);
vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
WRITE_ONCE(vma->vm_flags,
vma->vm_flags & ~(VM_UFFD_WP | VM_UFFD_MISSING));
vm_write_end(vma);
return 0;
}
list_for_each_entry(fctx, fcs, list)
if (fctx->orig == octx) {
ctx = fctx->new;
break;
}
if (!ctx) {
fctx = kmalloc(sizeof(*fctx), GFP_KERNEL);
if (!fctx)
return -ENOMEM;
ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
if (!ctx) {
kfree(fctx);
return -ENOMEM;
}
refcount_set(&ctx->refcount, 1);
ctx->flags = octx->flags;
ctx->features = octx->features;
ctx->released = false;
ctx->mmap_changing = false;
ctx->mm = vma->vm_mm;
mmgrab(ctx->mm);
userfaultfd_ctx_get(octx);
WRITE_ONCE(octx->mmap_changing, true);
fctx->orig = octx;
fctx->new = ctx;
list_add_tail(&fctx->list, fcs);
}
vma->vm_userfaultfd_ctx.ctx = ctx;
return 0;
}
static void dup_fctx(struct userfaultfd_fork_ctx *fctx)
{
struct userfaultfd_ctx *ctx = fctx->orig;
struct userfaultfd_wait_queue ewq;
msg_init(&ewq.msg);
ewq.msg.event = UFFD_EVENT_FORK;
ewq.msg.arg.reserved.reserved1 = (unsigned long)fctx->new;
userfaultfd_event_wait_completion(ctx, &ewq);
}
void dup_userfaultfd_complete(struct list_head *fcs)
{
struct userfaultfd_fork_ctx *fctx, *n;
list_for_each_entry_safe(fctx, n, fcs, list) {
dup_fctx(fctx);
list_del(&fctx->list);
kfree(fctx);
}
}
void mremap_userfaultfd_prep(struct vm_area_struct *vma,
struct vm_userfaultfd_ctx *vm_ctx)
{
struct userfaultfd_ctx *ctx;
ctx = vma->vm_userfaultfd_ctx.ctx;
if (!ctx)
return;
if (ctx->features & UFFD_FEATURE_EVENT_REMAP) {
vm_ctx->ctx = ctx;
userfaultfd_ctx_get(ctx);
WRITE_ONCE(ctx->mmap_changing, true);
} else {
/* Drop uffd context if remap feature not enabled */
vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
vma->vm_flags &= ~(VM_UFFD_WP | VM_UFFD_MISSING);
}
}
void mremap_userfaultfd_complete(struct vm_userfaultfd_ctx *vm_ctx,
unsigned long from, unsigned long to,
unsigned long len)
{
struct userfaultfd_ctx *ctx = vm_ctx->ctx;
struct userfaultfd_wait_queue ewq;
if (!ctx)
return;
if (to & ~PAGE_MASK) {
userfaultfd_ctx_put(ctx);
return;
}
msg_init(&ewq.msg);
ewq.msg.event = UFFD_EVENT_REMAP;
ewq.msg.arg.remap.from = from;
ewq.msg.arg.remap.to = to;
ewq.msg.arg.remap.len = len;
userfaultfd_event_wait_completion(ctx, &ewq);
}
bool userfaultfd_remove(struct vm_area_struct *vma,
unsigned long start, unsigned long end)
{
struct mm_struct *mm = vma->vm_mm;
struct userfaultfd_ctx *ctx;
struct userfaultfd_wait_queue ewq;
ctx = vma->vm_userfaultfd_ctx.ctx;
if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_REMOVE))
return true;
userfaultfd_ctx_get(ctx);
WRITE_ONCE(ctx->mmap_changing, true);
up_read(&mm->mmap_sem);
msg_init(&ewq.msg);
ewq.msg.event = UFFD_EVENT_REMOVE;
ewq.msg.arg.remove.start = start;
ewq.msg.arg.remove.end = end;
userfaultfd_event_wait_completion(ctx, &ewq);
return false;
}
static bool has_unmap_ctx(struct userfaultfd_ctx *ctx, struct list_head *unmaps,
unsigned long start, unsigned long end)
{
struct userfaultfd_unmap_ctx *unmap_ctx;
list_for_each_entry(unmap_ctx, unmaps, list)
if (unmap_ctx->ctx == ctx && unmap_ctx->start == start &&
unmap_ctx->end == end)
return true;
return false;
}
int userfaultfd_unmap_prep(struct vm_area_struct *vma,
unsigned long start, unsigned long end,
struct list_head *unmaps)
{
for ( ; vma && vma->vm_start < end; vma = vma->vm_next) {
struct userfaultfd_unmap_ctx *unmap_ctx;
struct userfaultfd_ctx *ctx = vma->vm_userfaultfd_ctx.ctx;
if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_UNMAP) ||
has_unmap_ctx(ctx, unmaps, start, end))
continue;
unmap_ctx = kzalloc(sizeof(*unmap_ctx), GFP_KERNEL);
if (!unmap_ctx)
return -ENOMEM;
userfaultfd_ctx_get(ctx);
WRITE_ONCE(ctx->mmap_changing, true);
unmap_ctx->ctx = ctx;
unmap_ctx->start = start;
unmap_ctx->end = end;
list_add_tail(&unmap_ctx->list, unmaps);
}
return 0;
}
void userfaultfd_unmap_complete(struct mm_struct *mm, struct list_head *uf)
{
struct userfaultfd_unmap_ctx *ctx, *n;
struct userfaultfd_wait_queue ewq;
list_for_each_entry_safe(ctx, n, uf, list) {
msg_init(&ewq.msg);
ewq.msg.event = UFFD_EVENT_UNMAP;
ewq.msg.arg.remove.start = ctx->start;
ewq.msg.arg.remove.end = ctx->end;
userfaultfd_event_wait_completion(ctx->ctx, &ewq);
list_del(&ctx->list);
kfree(ctx);
}
}
static int userfaultfd_release(struct inode *inode, struct file *file)
{
struct userfaultfd_ctx *ctx = file->private_data;
struct mm_struct *mm = ctx->mm;
struct vm_area_struct *vma, *prev;
/* len == 0 means wake all */
struct userfaultfd_wake_range range = { .len = 0, };
unsigned long new_flags;
bool still_valid;
WRITE_ONCE(ctx->released, true);
if (!mmget_not_zero(mm))
goto wakeup;
/*
* Flush page faults out of all CPUs. NOTE: all page faults
* must be retried without returning VM_FAULT_SIGBUS if
* userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
* changes while handle_userfault released the mmap_sem. So
* it's critical that released is set to true (above), before
* taking the mmap_sem for writing.
*/
down_write(&mm->mmap_sem);
still_valid = mmget_still_valid(mm);
prev = NULL;
for (vma = mm->mmap; vma; vma = vma->vm_next) {
cond_resched();
BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
!!(vma->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
if (vma->vm_userfaultfd_ctx.ctx != ctx) {
prev = vma;
continue;
}
new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
if (still_valid) {
prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
new_flags, vma->anon_vma,
vma->vm_file, vma->vm_pgoff,
vma_policy(vma),
NULL_VM_UFFD_CTX,
vma_get_anon_name(vma));
if (prev)
vma = prev;
else
prev = vma;
}
vm_write_begin(vma);
WRITE_ONCE(vma->vm_flags, new_flags);
vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
vm_write_end(vma);
}
up_write(&mm->mmap_sem);
mmput(mm);
wakeup:
/*
* After no new page faults can wait on this fault_*wqh, flush
* the last page faults that may have been already waiting on
* the fault_*wqh.
*/
spin_lock_irq(&ctx->fault_pending_wqh.lock);
__wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
__wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, &range);
spin_unlock_irq(&ctx->fault_pending_wqh.lock);
/* Flush pending events that may still wait on event_wqh */
wake_up_all(&ctx->event_wqh);
wake_up_poll(&ctx->fd_wqh, EPOLLHUP);
userfaultfd_ctx_put(ctx);
return 0;
}
/* fault_pending_wqh.lock must be hold by the caller */
static inline struct userfaultfd_wait_queue *find_userfault_in(
wait_queue_head_t *wqh)
{
wait_queue_entry_t *wq;
struct userfaultfd_wait_queue *uwq;
lockdep_assert_held(&wqh->lock);
uwq = NULL;
if (!waitqueue_active(wqh))
goto out;
/* walk in reverse to provide FIFO behavior to read userfaults */
wq = list_last_entry(&wqh->head, typeof(*wq), entry);
uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
out:
return uwq;
}
static inline struct userfaultfd_wait_queue *find_userfault(
struct userfaultfd_ctx *ctx)
{
return find_userfault_in(&ctx->fault_pending_wqh);
}
static inline struct userfaultfd_wait_queue *find_userfault_evt(
struct userfaultfd_ctx *ctx)
{
return find_userfault_in(&ctx->event_wqh);
}
static __poll_t userfaultfd_poll(struct file *file, poll_table *wait)
{
struct userfaultfd_ctx *ctx = file->private_data;
__poll_t ret;
poll_wait(file, &ctx->fd_wqh, wait);
if (!userfaultfd_is_initialized(ctx))
return EPOLLERR;
/*
* poll() never guarantees that read won't block.
* userfaults can be waken before they're read().
*/
if (unlikely(!(file->f_flags & O_NONBLOCK)))
return EPOLLERR;
/*
* lockless access to see if there are pending faults
* __pollwait last action is the add_wait_queue but
* the spin_unlock would allow the waitqueue_active to
* pass above the actual list_add inside
* add_wait_queue critical section. So use a full
* memory barrier to serialize the list_add write of
* add_wait_queue() with the waitqueue_active read
* below.
*/
ret = 0;
smp_mb();
if (waitqueue_active(&ctx->fault_pending_wqh))
ret = EPOLLIN;
else if (waitqueue_active(&ctx->event_wqh))
ret = EPOLLIN;
return ret;
}
static const struct file_operations userfaultfd_fops;
static int resolve_userfault_fork(struct userfaultfd_ctx *ctx,
struct userfaultfd_ctx *new,
struct uffd_msg *msg)
{
int fd;
fd = anon_inode_getfd("[userfaultfd]", &userfaultfd_fops, new,
O_RDONLY | (new->flags & UFFD_SHARED_FCNTL_FLAGS));
if (fd < 0)
return fd;
msg->arg.reserved.reserved1 = 0;
msg->arg.fork.ufd = fd;
return 0;
}
static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
struct uffd_msg *msg)
{
ssize_t ret;
DECLARE_WAITQUEUE(wait, current);
struct userfaultfd_wait_queue *uwq;
/*
* Handling fork event requires sleeping operations, so
* we drop the event_wqh lock, then do these ops, then
* lock it back and wake up the waiter. While the lock is
* dropped the ewq may go away so we keep track of it
* carefully.
*/
LIST_HEAD(fork_event);
struct userfaultfd_ctx *fork_nctx = NULL;
/* always take the fd_wqh lock before the fault_pending_wqh lock */
spin_lock_irq(&ctx->fd_wqh.lock);
__add_wait_queue(&ctx->fd_wqh, &wait);
for (;;) {
set_current_state(TASK_INTERRUPTIBLE);
spin_lock(&ctx->fault_pending_wqh.lock);
uwq = find_userfault(ctx);
if (uwq) {
/*
* Use a seqcount to repeat the lockless check
* in wake_userfault() to avoid missing
* wakeups because during the refile both
* waitqueue could become empty if this is the
* only userfault.
*/
write_seqcount_begin(&ctx->refile_seq);
/*
* The fault_pending_wqh.lock prevents the uwq
* to disappear from under us.
*
* Refile this userfault from
* fault_pending_wqh to fault_wqh, it's not
* pending anymore after we read it.
*
* Use list_del() by hand (as
* userfaultfd_wake_function also uses
* list_del_init() by hand) to be sure nobody
* changes __remove_wait_queue() to use
* list_del_init() in turn breaking the
* !list_empty_careful() check in
* handle_userfault(). The uwq->wq.head list
* must never be empty at any time during the
* refile, or the waitqueue could disappear
* from under us. The "wait_queue_head_t"
* parameter of __remove_wait_queue() is unused
* anyway.
*/
list_del(&uwq->wq.entry);
add_wait_queue(&ctx->fault_wqh, &uwq->wq);
write_seqcount_end(&ctx->refile_seq);
/* careful to always initialize msg if ret == 0 */
*msg = uwq->msg;
spin_unlock(&ctx->fault_pending_wqh.lock);
ret = 0;
break;
}
spin_unlock(&ctx->fault_pending_wqh.lock);
spin_lock(&ctx->event_wqh.lock);
uwq = find_userfault_evt(ctx);
if (uwq) {
*msg = uwq->msg;
if (uwq->msg.event == UFFD_EVENT_FORK) {
fork_nctx = (struct userfaultfd_ctx *)
(unsigned long)
uwq->msg.arg.reserved.reserved1;
list_move(&uwq->wq.entry, &fork_event);
/*
* fork_nctx can be freed as soon as
* we drop the lock, unless we take a
* reference on it.
*/
userfaultfd_ctx_get(fork_nctx);
spin_unlock(&ctx->event_wqh.lock);
ret = 0;
break;
}
userfaultfd_event_complete(ctx, uwq);
spin_unlock(&ctx->event_wqh.lock);
ret = 0;
break;
}
spin_unlock(&ctx->event_wqh.lock);
if (signal_pending(current)) {
ret = -ERESTARTSYS;
break;
}
if (no_wait) {
ret = -EAGAIN;
break;
}
spin_unlock_irq(&ctx->fd_wqh.lock);
schedule();
spin_lock_irq(&ctx->fd_wqh.lock);
}
__remove_wait_queue(&ctx->fd_wqh, &wait);
__set_current_state(TASK_RUNNING);
spin_unlock_irq(&ctx->fd_wqh.lock);
if (!ret && msg->event == UFFD_EVENT_FORK) {
ret = resolve_userfault_fork(ctx, fork_nctx, msg);
spin_lock_irq(&ctx->event_wqh.lock);
if (!list_empty(&fork_event)) {
/*
* The fork thread didn't abort, so we can
* drop the temporary refcount.
*/
userfaultfd_ctx_put(fork_nctx);
uwq = list_first_entry(&fork_event,
typeof(*uwq),
wq.entry);
/*
* If fork_event list wasn't empty and in turn
* the event wasn't already released by fork
* (the event is allocated on fork kernel
* stack), put the event back to its place in
* the event_wq. fork_event head will be freed
* as soon as we return so the event cannot
* stay queued there no matter the current
* "ret" value.
*/
list_del(&uwq->wq.entry);
__add_wait_queue(&ctx->event_wqh, &uwq->wq);
/*
* Leave the event in the waitqueue and report
* error to userland if we failed to resolve
* the userfault fork.
*/
if (likely(!ret))
userfaultfd_event_complete(ctx, uwq);
} else {
/*
* Here the fork thread aborted and the
* refcount from the fork thread on fork_nctx
* has already been released. We still hold
* the reference we took before releasing the
* lock above. If resolve_userfault_fork
* failed we've to drop it because the
* fork_nctx has to be freed in such case. If
* it succeeded we'll hold it because the new
* uffd references it.
*/
if (ret)
userfaultfd_ctx_put(fork_nctx);
}
spin_unlock_irq(&ctx->event_wqh.lock);
}
return ret;
}
static ssize_t userfaultfd_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct userfaultfd_ctx *ctx = file->private_data;
ssize_t _ret, ret = 0;
struct uffd_msg msg;
int no_wait = file->f_flags & O_NONBLOCK;
if (!userfaultfd_is_initialized(ctx))
return -EINVAL;
for (;;) {
if (count < sizeof(msg))
return ret ? ret : -EINVAL;
_ret = userfaultfd_ctx_read(ctx, no_wait, &msg);
if (_ret < 0)
return ret ? ret : _ret;
if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
return ret ? ret : -EFAULT;
ret += sizeof(msg);
buf += sizeof(msg);
count -= sizeof(msg);
/*
* Allow to read more than one fault at time but only
* block if waiting for the very first one.
*/
no_wait = O_NONBLOCK;
}
}
static void __wake_userfault(struct userfaultfd_ctx *ctx,
struct userfaultfd_wake_range *range)
{
spin_lock_irq(&ctx->fault_pending_wqh.lock);
/* wake all in the range and autoremove */
if (waitqueue_active(&ctx->fault_pending_wqh))
__wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
range);
if (waitqueue_active(&ctx->fault_wqh))
__wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, range);
spin_unlock_irq(&ctx->fault_pending_wqh.lock);
}
static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
struct userfaultfd_wake_range *range)
{
unsigned seq;
bool need_wakeup;
/*
* To be sure waitqueue_active() is not reordered by the CPU
* before the pagetable update, use an explicit SMP memory
* barrier here. PT lock release or up_read(mmap_sem) still
* have release semantics that can allow the
* waitqueue_active() to be reordered before the pte update.
*/
smp_mb();
/*
* Use waitqueue_active because it's very frequent to
* change the address space atomically even if there are no
* userfaults yet. So we take the spinlock only when we're
* sure we've userfaults to wake.
*/
do {
seq = read_seqcount_begin(&ctx->refile_seq);
need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
waitqueue_active(&ctx->fault_wqh);
cond_resched();
} while (read_seqcount_retry(&ctx->refile_seq, seq));
if (need_wakeup)
__wake_userfault(ctx, range);
}
static __always_inline int validate_range(struct mm_struct *mm,
__u64 start, __u64 len)
{
__u64 task_size = mm->task_size;
if (start & ~PAGE_MASK)
return -EINVAL;
if (len & ~PAGE_MASK)
return -EINVAL;
if (!len)
return -EINVAL;
if (start < mmap_min_addr)
return -EINVAL;
if (start >= task_size)
return -EINVAL;
if (len > task_size - start)
return -EINVAL;
return 0;
}
static inline bool vma_can_userfault(struct vm_area_struct *vma)
{
return vma_is_anonymous(vma) || is_vm_hugetlb_page(vma) ||
vma_is_shmem(vma);
}
static int userfaultfd_register(struct userfaultfd_ctx *ctx,
unsigned long arg)
{
struct mm_struct *mm = ctx->mm;
struct vm_area_struct *vma, *prev, *cur;
int ret;
struct uffdio_register uffdio_register;
struct uffdio_register __user *user_uffdio_register;
unsigned long vm_flags, new_flags;
bool found;
bool basic_ioctls;
unsigned long start, end, vma_end;
user_uffdio_register = (struct uffdio_register __user *) arg;
ret = -EFAULT;
if (copy_from_user(&uffdio_register, user_uffdio_register,
sizeof(uffdio_register)-sizeof(__u64)))
goto out;
ret = -EINVAL;
if (!uffdio_register.mode)
goto out;
if (uffdio_register.mode & ~(UFFDIO_REGISTER_MODE_MISSING|
UFFDIO_REGISTER_MODE_WP))
goto out;
vm_flags = 0;
if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
vm_flags |= VM_UFFD_MISSING;
if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
vm_flags |= VM_UFFD_WP;
/*
* FIXME: remove the below error constraint by
* implementing the wprotect tracking mode.
*/
ret = -EINVAL;
goto out;
}
ret = validate_range(mm, uffdio_register.range.start,
uffdio_register.range.len);
if (ret)
goto out;
start = uffdio_register.range.start;
end = start + uffdio_register.range.len;
ret = -ENOMEM;
if (!mmget_not_zero(mm))
goto out;
down_write(&mm->mmap_sem);
if (!mmget_still_valid(mm))
goto out_unlock;
vma = find_vma_prev(mm, start, &prev);
if (!vma)
goto out_unlock;
/* check that there's at least one vma in the range */
ret = -EINVAL;
if (vma->vm_start >= end)
goto out_unlock;
/*
* If the first vma contains huge pages, make sure start address
* is aligned to huge page size.
*/
if (is_vm_hugetlb_page(vma)) {
unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
if (start & (vma_hpagesize - 1))
goto out_unlock;
}
/*
* Search for not compatible vmas.
*/
found = false;
basic_ioctls = false;
for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
cond_resched();
BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
!!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
/* check not compatible vmas */
ret = -EINVAL;
if (!vma_can_userfault(cur))
goto out_unlock;
/*
* UFFDIO_COPY will fill file holes even without
* PROT_WRITE. This check enforces that if this is a
* MAP_SHARED, the process has write permission to the backing
* file. If VM_MAYWRITE is set it also enforces that on a
* MAP_SHARED vma: there is no F_WRITE_SEAL and no further
* F_WRITE_SEAL can be taken until the vma is destroyed.
*/
ret = -EPERM;
if (unlikely(!(cur->vm_flags & VM_MAYWRITE)))
goto out_unlock;
/*
* If this vma contains ending address, and huge pages
* check alignment.
*/
if (is_vm_hugetlb_page(cur) && end <= cur->vm_end &&
end > cur->vm_start) {
unsigned long vma_hpagesize = vma_kernel_pagesize(cur);
ret = -EINVAL;
if (end & (vma_hpagesize - 1))
goto out_unlock;
}
/*
* Check that this vma isn't already owned by a
* different userfaultfd. We can't allow more than one
* userfaultfd to own a single vma simultaneously or we
* wouldn't know which one to deliver the userfaults to.
*/
ret = -EBUSY;
if (cur->vm_userfaultfd_ctx.ctx &&
cur->vm_userfaultfd_ctx.ctx != ctx)
goto out_unlock;
/*
* Note vmas containing huge pages
*/
if (is_vm_hugetlb_page(cur))
basic_ioctls = true;
found = true;
}
BUG_ON(!found);
if (vma->vm_start < start)
prev = vma;
ret = 0;
do {
cond_resched();
BUG_ON(!vma_can_userfault(vma));
BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
vma->vm_userfaultfd_ctx.ctx != ctx);
WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
/*
* Nothing to do: this vma is already registered into this
* userfaultfd and with the right tracking mode too.
*/
if (vma->vm_userfaultfd_ctx.ctx == ctx &&
(vma->vm_flags & vm_flags) == vm_flags)
goto skip;
if (vma->vm_start > start)
start = vma->vm_start;
vma_end = min(end, vma->vm_end);
new_flags = (vma->vm_flags & ~vm_flags) | vm_flags;
prev = vma_merge(mm, prev, start, vma_end, new_flags,
vma->anon_vma, vma->vm_file, vma->vm_pgoff,
vma_policy(vma),
((struct vm_userfaultfd_ctx){ ctx }),
vma_get_anon_name(vma));
if (prev) {
vma = prev;
goto next;
}
if (vma->vm_start < start) {
ret = split_vma(mm, vma, start, 1);
if (ret)
break;
}
if (vma->vm_end > end) {
ret = split_vma(mm, vma, end, 0);
if (ret)
break;
}
next:
/*
* In the vma_merge() successful mprotect-like case 8:
* the next vma was merged into the current one and
* the current one has not been updated yet.
*/
vm_write_begin(vma);
WRITE_ONCE(vma->vm_flags, new_flags);
vma->vm_userfaultfd_ctx.ctx = ctx;
vm_write_end(vma);
skip:
prev = vma;
start = vma->vm_end;
vma = vma->vm_next;
} while (vma && vma->vm_start < end);
out_unlock:
up_write(&mm->mmap_sem);
mmput(mm);
if (!ret) {
/*
* Now that we scanned all vmas we can already tell
* userland which ioctls methods are guaranteed to
* succeed on this range.
*/
if (put_user(basic_ioctls ? UFFD_API_RANGE_IOCTLS_BASIC :
UFFD_API_RANGE_IOCTLS,
&user_uffdio_register->ioctls))
ret = -EFAULT;
}
out:
return ret;
}
static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
unsigned long arg)
{
struct mm_struct *mm = ctx->mm;
struct vm_area_struct *vma, *prev, *cur;
int ret;
struct uffdio_range uffdio_unregister;
unsigned long new_flags;
bool found;
unsigned long start, end, vma_end;
const void __user *buf = (void __user *)arg;
ret = -EFAULT;
if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
goto out;
ret = validate_range(mm, uffdio_unregister.start,
uffdio_unregister.len);
if (ret)
goto out;
start = uffdio_unregister.start;
end = start + uffdio_unregister.len;
ret = -ENOMEM;
if (!mmget_not_zero(mm))
goto out;
down_write(&mm->mmap_sem);
if (!mmget_still_valid(mm))
goto out_unlock;
vma = find_vma_prev(mm, start, &prev);
if (!vma)
goto out_unlock;
/* check that there's at least one vma in the range */
ret = -EINVAL;
if (vma->vm_start >= end)
goto out_unlock;
/*
* If the first vma contains huge pages, make sure start address
* is aligned to huge page size.
*/
if (is_vm_hugetlb_page(vma)) {
unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
if (start & (vma_hpagesize - 1))
goto out_unlock;
}
/*
* Search for not compatible vmas.
*/
found = false;
ret = -EINVAL;
for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
cond_resched();
BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
!!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
/*
* Check not compatible vmas, not strictly required
* here as not compatible vmas cannot have an
* userfaultfd_ctx registered on them, but this
* provides for more strict behavior to notice
* unregistration errors.
*/
if (!vma_can_userfault(cur))
goto out_unlock;
found = true;
}
BUG_ON(!found);
if (vma->vm_start < start)
prev = vma;
ret = 0;
do {
cond_resched();
BUG_ON(!vma_can_userfault(vma));
/*
* Nothing to do: this vma is already registered into this
* userfaultfd and with the right tracking mode too.
*/
if (!vma->vm_userfaultfd_ctx.ctx)
goto skip;
WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
if (vma->vm_start > start)
start = vma->vm_start;
vma_end = min(end, vma->vm_end);
if (userfaultfd_missing(vma)) {
/*
* Wake any concurrent pending userfault while
* we unregister, so they will not hang
* permanently and it avoids userland to call
* UFFDIO_WAKE explicitly.
*/
struct userfaultfd_wake_range range;
range.start = start;
range.len = vma_end - start;
wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range);
}
new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
prev = vma_merge(mm, prev, start, vma_end, new_flags,
vma->anon_vma, vma->vm_file, vma->vm_pgoff,
vma_policy(vma),
NULL_VM_UFFD_CTX,
vma_get_anon_name(vma));
if (prev) {
vma = prev;
goto next;
}
if (vma->vm_start < start) {
ret = split_vma(mm, vma, start, 1);
if (ret)
break;
}
if (vma->vm_end > end) {
ret = split_vma(mm, vma, end, 0);
if (ret)
break;
}
next:
/*
* In the vma_merge() successful mprotect-like case 8:
* the next vma was merged into the current one and
* the current one has not been updated yet.
*/
vm_write_begin(vma);
WRITE_ONCE(vma->vm_flags, new_flags);
vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
vm_write_end(vma);
skip:
prev = vma;
start = vma->vm_end;
vma = vma->vm_next;
} while (vma && vma->vm_start < end);
out_unlock:
up_write(&mm->mmap_sem);
mmput(mm);
out:
return ret;
}
/*
* userfaultfd_wake may be used in combination with the
* UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
*/
static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
unsigned long arg)
{
int ret;
struct uffdio_range uffdio_wake;
struct userfaultfd_wake_range range;
const void __user *buf = (void __user *)arg;
ret = -EFAULT;
if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
goto out;
ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
if (ret)
goto out;
range.start = uffdio_wake.start;
range.len = uffdio_wake.len;
/*
* len == 0 means wake all and we don't want to wake all here,
* so check it again to be sure.
*/
VM_BUG_ON(!range.len);
wake_userfault(ctx, &range);
ret = 0;
out:
return ret;
}
static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
unsigned long arg)
{
__s64 ret;
struct uffdio_copy uffdio_copy;
struct uffdio_copy __user *user_uffdio_copy;
struct userfaultfd_wake_range range;
user_uffdio_copy = (struct uffdio_copy __user *) arg;
ret = -EAGAIN;
if (READ_ONCE(ctx->mmap_changing))
goto out;
ret = -EFAULT;
if (copy_from_user(&uffdio_copy, user_uffdio_copy,
/* don't copy "copy" last field */
sizeof(uffdio_copy)-sizeof(__s64)))
goto out;
ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
if (ret)
goto out;
/*
* double check for wraparound just in case. copy_from_user()
* will later check uffdio_copy.src + uffdio_copy.len to fit
* in the userland range.
*/
ret = -EINVAL;
if (uffdio_copy.src + uffdio_copy.len <= uffdio_copy.src)
goto out;
if (uffdio_copy.mode & ~UFFDIO_COPY_MODE_DONTWAKE)
goto out;
if (mmget_not_zero(ctx->mm)) {
ret = mcopy_atomic(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
uffdio_copy.len, &ctx->mmap_changing);
mmput(ctx->mm);
} else {
return -ESRCH;
}
if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
return -EFAULT;
if (ret < 0)
goto out;
BUG_ON(!ret);
/* len == 0 would wake all */
range.len = ret;
if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
range.start = uffdio_copy.dst;
wake_userfault(ctx, &range);
}
ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
out:
return ret;
}
static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
unsigned long arg)
{
__s64 ret;
struct uffdio_zeropage uffdio_zeropage;
struct uffdio_zeropage __user *user_uffdio_zeropage;
struct userfaultfd_wake_range range;
user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
ret = -EAGAIN;
if (READ_ONCE(ctx->mmap_changing))
goto out;
ret = -EFAULT;
if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
/* don't copy "zeropage" last field */
sizeof(uffdio_zeropage)-sizeof(__s64)))
goto out;
ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
uffdio_zeropage.range.len);
if (ret)
goto out;
ret = -EINVAL;
if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
goto out;
if (mmget_not_zero(ctx->mm)) {
ret = mfill_zeropage(ctx->mm, uffdio_zeropage.range.start,
uffdio_zeropage.range.len,
&ctx->mmap_changing);
mmput(ctx->mm);
} else {
return -ESRCH;
}
if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
return -EFAULT;
if (ret < 0)
goto out;
/* len == 0 would wake all */
BUG_ON(!ret);
range.len = ret;
if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
range.start = uffdio_zeropage.range.start;
wake_userfault(ctx, &range);
}
ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
out:
return ret;
}
static inline unsigned int uffd_ctx_features(__u64 user_features)
{
/*
* For the current set of features the bits just coincide. Set
* UFFD_FEATURE_INITIALIZED to mark the features as enabled.
*/
return (unsigned int)user_features | UFFD_FEATURE_INITIALIZED;
}
/*
* userland asks for a certain API version and we return which bits
* and ioctl commands are implemented in this kernel for such API
* version or -EINVAL if unknown.
*/
static int userfaultfd_api(struct userfaultfd_ctx *ctx,
unsigned long arg)
{
struct uffdio_api uffdio_api;
void __user *buf = (void __user *)arg;
unsigned int ctx_features;
int ret;
__u64 features;
ret = -EFAULT;
if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
goto out;
features = uffdio_api.features;
ret = -EINVAL;
if (uffdio_api.api != UFFD_API || (features & ~UFFD_API_FEATURES))
goto err_out;
ret = -EPERM;
if ((features & UFFD_FEATURE_EVENT_FORK) && !capable(CAP_SYS_PTRACE))
goto err_out;
/* report all available features and ioctls to userland */
uffdio_api.features = UFFD_API_FEATURES;
uffdio_api.ioctls = UFFD_API_IOCTLS;
ret = -EFAULT;
if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
goto out;
/* only enable the requested features for this uffd context */
ctx_features = uffd_ctx_features(features);
ret = -EINVAL;
if (cmpxchg(&ctx->features, 0, ctx_features) != 0)
goto err_out;
ret = 0;
out:
return ret;
err_out:
memset(&uffdio_api, 0, sizeof(uffdio_api));
if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
ret = -EFAULT;
goto out;
}
static long userfaultfd_ioctl(struct file *file, unsigned cmd,
unsigned long arg)
{
int ret = -EINVAL;
struct userfaultfd_ctx *ctx = file->private_data;
if (cmd != UFFDIO_API && !userfaultfd_is_initialized(ctx))
return -EINVAL;
switch(cmd) {
case UFFDIO_API:
ret = userfaultfd_api(ctx, arg);
break;
case UFFDIO_REGISTER:
ret = userfaultfd_register(ctx, arg);
break;
case UFFDIO_UNREGISTER:
ret = userfaultfd_unregister(ctx, arg);
break;
case UFFDIO_WAKE:
ret = userfaultfd_wake(ctx, arg);
break;
case UFFDIO_COPY:
ret = userfaultfd_copy(ctx, arg);
break;
case UFFDIO_ZEROPAGE:
ret = userfaultfd_zeropage(ctx, arg);
break;
}
return ret;
}
#ifdef CONFIG_PROC_FS
static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
{
struct userfaultfd_ctx *ctx = f->private_data;
wait_queue_entry_t *wq;
unsigned long pending = 0, total = 0;
spin_lock_irq(&ctx->fault_pending_wqh.lock);
list_for_each_entry(wq, &ctx->fault_pending_wqh.head, entry) {
pending++;
total++;
}
list_for_each_entry(wq, &ctx->fault_wqh.head, entry) {
total++;
}
spin_unlock_irq(&ctx->fault_pending_wqh.lock);
/*
* If more protocols will be added, there will be all shown
* separated by a space. Like this:
* protocols: aa:... bb:...
*/
seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
pending, total, UFFD_API, ctx->features,
UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
}
#endif
static const struct file_operations userfaultfd_fops = {
#ifdef CONFIG_PROC_FS
.show_fdinfo = userfaultfd_show_fdinfo,
#endif
.release = userfaultfd_release,
.poll = userfaultfd_poll,
.read = userfaultfd_read,
.unlocked_ioctl = userfaultfd_ioctl,
.compat_ioctl = userfaultfd_ioctl,
.llseek = noop_llseek,
};
static void init_once_userfaultfd_ctx(void *mem)
{
struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
init_waitqueue_head(&ctx->fault_pending_wqh);
init_waitqueue_head(&ctx->fault_wqh);
init_waitqueue_head(&ctx->event_wqh);
init_waitqueue_head(&ctx->fd_wqh);
seqcount_init(&ctx->refile_seq);
}
SYSCALL_DEFINE1(userfaultfd, int, flags)
{
struct userfaultfd_ctx *ctx;
int fd;
if (!sysctl_unprivileged_userfaultfd && !capable(CAP_SYS_PTRACE))
return -EPERM;
BUG_ON(!current->mm);
/* Check the UFFD_* constants for consistency. */
BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
if (flags & ~UFFD_SHARED_FCNTL_FLAGS)
return -EINVAL;
ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
if (!ctx)
return -ENOMEM;
refcount_set(&ctx->refcount, 1);
ctx->flags = flags;
ctx->features = 0;
ctx->released = false;
ctx->mmap_changing = false;
ctx->mm = current->mm;
/* prevent the mm struct to be freed */
mmgrab(ctx->mm);
fd = anon_inode_getfd("[userfaultfd]", &userfaultfd_fops, ctx,
O_RDONLY | (flags & UFFD_SHARED_FCNTL_FLAGS));
if (fd < 0) {
mmdrop(ctx->mm);
kmem_cache_free(userfaultfd_ctx_cachep, ctx);
}
return fd;
}
static int __init userfaultfd_init(void)
{
userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
sizeof(struct userfaultfd_ctx),
0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC,
init_once_userfaultfd_ctx);
return 0;
}
__initcall(userfaultfd_init);