+ MEMORYSTATUS_DEBUG(1, "memorystatus_list_remove: removing pid %d\n", p->p_pid);
+
+ /*
+ * Check if this proc is locked (because we're performing a freeze).
+ * If so, we fail and instruct the caller to try again later.
+ */
+ if (p->p_memstat_state & P_MEMSTAT_LOCKED) {
+ return EAGAIN;
+ }
+
+ assert(!(p->p_memstat_state & P_MEMSTAT_INTERNAL));
+
+ bucket = &memstat_bucket[p->p_memstat_effectivepriority];
+
+ if (isSysProc(p) && system_procs_aging_band && (p->p_memstat_effectivepriority == system_procs_aging_band)) {
+ assert(bucket->count == memorystatus_scheduled_idle_demotions_sysprocs);
+ reschedule = TRUE;
+ } else if (isApp(p) && applications_aging_band && (p->p_memstat_effectivepriority == applications_aging_band)) {
+ assert(bucket->count == memorystatus_scheduled_idle_demotions_apps);
+ reschedule = TRUE;
+ }
+
+ /*
+ * Record idle delta
+ */
+
+ if (p->p_memstat_effectivepriority == JETSAM_PRIORITY_IDLE) {
+ uint64_t now = mach_absolute_time();
+ if (now > p->p_memstat_idle_start) {
+ p->p_memstat_idle_delta = now - p->p_memstat_idle_start;
+ }
+ }
+
+ TAILQ_REMOVE(&bucket->list, p, p_memstat_list);
+ bucket->count--;
+ if (p->p_memstat_relaunch_flags & (P_MEMSTAT_RELAUNCH_HIGH)) {
+ bucket->relaunch_high_count--;
+ }
+
+ memorystatus_list_count--;
+
+ /* If awaiting demotion to the idle band, clean up */
+ if (reschedule) {
+ memorystatus_invalidate_idle_demotion_locked(p, TRUE);
+ memorystatus_reschedule_idle_demotion_locked();
+ }
+
+ memorystatus_check_levels_locked();
+
+#if CONFIG_FREEZE
+ if (p->p_memstat_state & (P_MEMSTAT_FROZEN)) {
+ if (p->p_memstat_state & P_MEMSTAT_REFREEZE_ELIGIBLE) {
+ p->p_memstat_state &= ~P_MEMSTAT_REFREEZE_ELIGIBLE;
+ memorystatus_refreeze_eligible_count--;
+ }
+
+ memorystatus_frozen_count--;
+ memorystatus_frozen_shared_mb -= p->p_memstat_freeze_sharedanon_pages;
+ p->p_memstat_freeze_sharedanon_pages = 0;
+ }
+
+ if (p->p_memstat_state & P_MEMSTAT_SUSPENDED) {
+ memorystatus_suspended_count--;
+ }
+#endif
+
+#if DEVELOPMENT || DEBUG
+ if (p->p_pid == memorystatus_snapshot_owner) {
+ memorystatus_snapshot_owner = 0;
+ }
+#endif /* DEVELOPMENT || DEBUG */
+
+ if (p) {
+ ret = 0;
+ } else {
+ ret = ESRCH;
+ }
+
+ return ret;
+}
+
+/*
+ * Validate dirty tracking flags with process state.
+ *
+ * Return:
+ * 0 on success
+ * non-0 on failure
+ *
+ * The proc_list_lock is held by the caller.
+ */
+
+static int
+memorystatus_validate_track_flags(struct proc *target_p, uint32_t pcontrol)
+{
+ /* See that the process isn't marked for termination */
+ if (target_p->p_memstat_dirty & P_DIRTY_TERMINATED) {
+ return EBUSY;
+ }
+
+ /* Idle exit requires that process be tracked */
+ if ((pcontrol & PROC_DIRTY_ALLOW_IDLE_EXIT) &&
+ !(pcontrol & PROC_DIRTY_TRACK)) {
+ return EINVAL;
+ }
+
+ /* 'Launch in progress' tracking requires that process have enabled dirty tracking too. */
+ if ((pcontrol & PROC_DIRTY_LAUNCH_IN_PROGRESS) &&
+ !(pcontrol & PROC_DIRTY_TRACK)) {
+ return EINVAL;
+ }
+
+ /* Only one type of DEFER behavior is allowed.*/
+ if ((pcontrol & PROC_DIRTY_DEFER) &&
+ (pcontrol & PROC_DIRTY_DEFER_ALWAYS)) {
+ return EINVAL;
+ }
+
+ /* Deferral is only relevant if idle exit is specified */
+ if (((pcontrol & PROC_DIRTY_DEFER) ||
+ (pcontrol & PROC_DIRTY_DEFER_ALWAYS)) &&
+ !(pcontrol & PROC_DIRTY_ALLOWS_IDLE_EXIT)) {
+ return EINVAL;
+ }
+
+ return 0;
+}
+
+static void
+memorystatus_update_idle_priority_locked(proc_t p)
+{
+ int32_t priority;
+
+ MEMORYSTATUS_DEBUG(1, "memorystatus_update_idle_priority_locked(): pid %d dirty 0x%X\n", p->p_pid, p->p_memstat_dirty);
+
+ assert(isSysProc(p));
+
+ if ((p->p_memstat_dirty & (P_DIRTY_IDLE_EXIT_ENABLED | P_DIRTY_IS_DIRTY)) == P_DIRTY_IDLE_EXIT_ENABLED) {
+ priority = (p->p_memstat_dirty & P_DIRTY_AGING_IN_PROGRESS) ? system_procs_aging_band : JETSAM_PRIORITY_IDLE;
+ } else {
+ priority = p->p_memstat_requestedpriority;
+ }
+
+ if (p->p_memstat_state & P_MEMSTAT_PRIORITY_ASSERTION) {
+ /*
+ * This process has a jetsam priority managed by an assertion.
+ * Policy is to choose the max priority.
+ */
+ if (p->p_memstat_assertionpriority > priority) {
+ os_log(OS_LOG_DEFAULT, "memorystatus: assertion priority %d overrides priority %d for %s:%d\n",
+ p->p_memstat_assertionpriority, priority,
+ (*p->p_name ? p->p_name : "unknown"), p->p_pid);
+ priority = p->p_memstat_assertionpriority;
+ }
+ }
+
+ if (priority != p->p_memstat_effectivepriority) {
+ if ((jetsam_aging_policy == kJetsamAgingPolicyLegacy) &&
+ (priority == JETSAM_PRIORITY_IDLE)) {
+ /*
+ * This process is on its way into the IDLE band. The system is
+ * using 'legacy' jetsam aging policy. That means, this process
+ * has already used up its idle-deferral aging time that is given
+ * once per its lifetime. So we need to set the INACTIVE limits
+ * explicitly because it won't be going through the demotion paths
+ * that take care to apply the limits appropriately.
+ */
+
+ if (p->p_memstat_state & P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND) {
+ /*
+ * This process has the 'elevated inactive jetsam band' attribute.
+ * So, there will be no trip to IDLE after all.
+ * Instead, we pin the process in the elevated band,
+ * where its ACTIVE limits will apply.
+ */
+
+ priority = JETSAM_PRIORITY_ELEVATED_INACTIVE;
+ }
+
+ memorystatus_update_priority_locked(p, priority, false, true);
+ } else {
+ memorystatus_update_priority_locked(p, priority, false, false);
+ }
+ }
+}
+
+/*
+ * Processes can opt to have their state tracked by the kernel, indicating when they are busy (dirty) or idle
+ * (clean). They may also indicate that they support termination when idle, with the result that they are promoted
+ * to their desired, higher, jetsam priority when dirty (and are therefore killed later), and demoted to the low
+ * priority idle band when clean (and killed earlier, protecting higher priority procesess).
+ *
+ * If the deferral flag is set, then newly tracked processes will be protected for an initial period (as determined by
+ * memorystatus_sysprocs_idle_delay_time); if they go clean during this time, then they will be moved to a deferred-idle band
+ * with a slightly higher priority, guarding against immediate termination under memory pressure and being unable to
+ * make forward progress. Finally, when the guard expires, they will be moved to the standard, lowest-priority, idle
+ * band. The deferral can be cleared early by clearing the appropriate flag.
+ *
+ * The deferral timer is active only for the duration that the process is marked as guarded and clean; if the process
+ * is marked dirty, the timer will be cancelled. Upon being subsequently marked clean, the deferment will either be
+ * re-enabled or the guard state cleared, depending on whether the guard deadline has passed.
+ */
+
+int
+memorystatus_dirty_track(proc_t p, uint32_t pcontrol)
+{
+ unsigned int old_dirty;
+ boolean_t reschedule = FALSE;
+ boolean_t already_deferred = FALSE;
+ boolean_t defer_now = FALSE;
+ int ret = 0;
+
+ KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_DIRTY_TRACK),
+ p->p_pid, p->p_memstat_dirty, pcontrol, 0, 0);
+
+ proc_list_lock();
+
+ if ((p->p_listflag & P_LIST_EXITED) != 0) {
+ /*
+ * Process is on its way out.
+ */
+ ret = EBUSY;
+ goto exit;
+ }
+
+ if (p->p_memstat_state & P_MEMSTAT_INTERNAL) {
+ ret = EPERM;
+ goto exit;
+ }
+
+ if ((ret = memorystatus_validate_track_flags(p, pcontrol)) != 0) {
+ /* error */
+ goto exit;
+ }
+
+ old_dirty = p->p_memstat_dirty;
+
+ /* These bits are cumulative, as per <rdar://problem/11159924> */
+ if (pcontrol & PROC_DIRTY_TRACK) {
+ p->p_memstat_dirty |= P_DIRTY_TRACK;
+ }
+
+ if (pcontrol & PROC_DIRTY_ALLOW_IDLE_EXIT) {
+ p->p_memstat_dirty |= P_DIRTY_ALLOW_IDLE_EXIT;
+ }
+
+ if (pcontrol & PROC_DIRTY_LAUNCH_IN_PROGRESS) {
+ p->p_memstat_dirty |= P_DIRTY_LAUNCH_IN_PROGRESS;
+ }
+
+ if (old_dirty & P_DIRTY_AGING_IN_PROGRESS) {
+ already_deferred = TRUE;
+ }
+
+
+ /* This can be set and cleared exactly once. */
+ if (pcontrol & (PROC_DIRTY_DEFER | PROC_DIRTY_DEFER_ALWAYS)) {
+ if ((pcontrol & (PROC_DIRTY_DEFER)) &&
+ !(old_dirty & P_DIRTY_DEFER)) {
+ p->p_memstat_dirty |= P_DIRTY_DEFER;
+ }
+
+ if ((pcontrol & (PROC_DIRTY_DEFER_ALWAYS)) &&
+ !(old_dirty & P_DIRTY_DEFER_ALWAYS)) {
+ p->p_memstat_dirty |= P_DIRTY_DEFER_ALWAYS;
+ }
+
+ defer_now = TRUE;
+ }
+
+ MEMORYSTATUS_DEBUG(1, "memorystatus_on_track_dirty(): set idle-exit %s / defer %s / dirty %s for pid %d\n",
+ ((p->p_memstat_dirty & P_DIRTY_IDLE_EXIT_ENABLED) == P_DIRTY_IDLE_EXIT_ENABLED) ? "Y" : "N",
+ defer_now ? "Y" : "N",
+ p->p_memstat_dirty & P_DIRTY ? "Y" : "N",
+ p->p_pid);
+
+ /* Kick off or invalidate the idle exit deferment if there's a state transition. */
+ if (!(p->p_memstat_dirty & P_DIRTY_IS_DIRTY)) {
+ if ((p->p_memstat_dirty & P_DIRTY_IDLE_EXIT_ENABLED) == P_DIRTY_IDLE_EXIT_ENABLED) {
+ if (defer_now && !already_deferred) {
+ /*
+ * Request to defer a clean process that's idle-exit enabled
+ * and not already in the jetsam deferred band. Most likely a
+ * new launch.
+ */
+ memorystatus_schedule_idle_demotion_locked(p, TRUE);
+ reschedule = TRUE;
+ } else if (!defer_now) {
+ /*
+ * The process isn't asking for the 'aging' facility.
+ * Could be that it is:
+ */
+
+ if (already_deferred) {
+ /*
+ * already in the aging bands. Traditionally,
+ * some processes have tried to use this to
+ * opt out of the 'aging' facility.
+ */
+
+ memorystatus_invalidate_idle_demotion_locked(p, TRUE);
+ } else {
+ /*
+ * agnostic to the 'aging' facility. In that case,
+ * we'll go ahead and opt it in because this is likely
+ * a new launch (clean process, dirty tracking enabled)
+ */
+
+ memorystatus_schedule_idle_demotion_locked(p, TRUE);
+ }
+
+ reschedule = TRUE;
+ }
+ }
+ } else {
+ /*
+ * We are trying to operate on a dirty process. Dirty processes have to
+ * be removed from the deferred band. The question is do we reset the
+ * deferred state or not?
+ *
+ * This could be a legal request like:
+ * - this process had opted into the 'aging' band
+ * - but it's now dirty and requests to opt out.
+ * In this case, we remove the process from the band and reset its
+ * state too. It'll opt back in properly when needed.
+ *
+ * OR, this request could be a user-space bug. E.g.:
+ * - this process had opted into the 'aging' band when clean
+ * - and, then issues another request to again put it into the band except
+ * this time the process is dirty.
+ * The process going dirty, as a transition in memorystatus_dirty_set(), will pull the process out of
+ * the deferred band with its state intact. So our request below is no-op.
+ * But we do it here anyways for coverage.
+ *
+ * memorystatus_update_idle_priority_locked()
+ * single-mindedly treats a dirty process as "cannot be in the aging band".
+ */
+
+ if (!defer_now && already_deferred) {
+ memorystatus_invalidate_idle_demotion_locked(p, TRUE);
+ reschedule = TRUE;
+ } else {
+ boolean_t reset_state = (jetsam_aging_policy != kJetsamAgingPolicyLegacy) ? TRUE : FALSE;
+
+ memorystatus_invalidate_idle_demotion_locked(p, reset_state);
+ reschedule = TRUE;
+ }
+ }
+
+ memorystatus_update_idle_priority_locked(p);
+
+ if (reschedule) {
+ memorystatus_reschedule_idle_demotion_locked();
+ }
+
+ ret = 0;
+
+exit:
+ proc_list_unlock();
+
+ return ret;
+}
+
+int
+memorystatus_dirty_set(proc_t p, boolean_t self, uint32_t pcontrol)
+{
+ int ret;
+ boolean_t kill = false;
+ boolean_t reschedule = FALSE;
+ boolean_t was_dirty = FALSE;
+ boolean_t now_dirty = FALSE;
+#if CONFIG_DIRTYSTATUS_TRACKING
+ boolean_t notify_change = FALSE;
+ dirty_status_change_event_t change_event;
+#endif
+
+ MEMORYSTATUS_DEBUG(1, "memorystatus_dirty_set(): %d %d 0x%x 0x%x\n", self, p->p_pid, pcontrol, p->p_memstat_dirty);
+ KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_DIRTY_SET), p->p_pid, self, pcontrol, 0, 0);
+
+ proc_list_lock();
+
+ if ((p->p_listflag & P_LIST_EXITED) != 0) {
+ /*
+ * Process is on its way out.
+ */
+ ret = EBUSY;
+ goto exit;
+ }
+
+ if (p->p_memstat_state & P_MEMSTAT_INTERNAL) {
+ ret = EPERM;
+ goto exit;
+ }
+
+ if (p->p_memstat_dirty & P_DIRTY_IS_DIRTY) {
+ was_dirty = TRUE;
+ }
+
+ if (!(p->p_memstat_dirty & P_DIRTY_TRACK)) {
+ /* Dirty tracking not enabled */
+ ret = EINVAL;
+ } else if (pcontrol && (p->p_memstat_dirty & P_DIRTY_TERMINATED)) {
+ /*
+ * Process is set to be terminated and we're attempting to mark it dirty.
+ * Set for termination and marking as clean is OK - see <rdar://problem/10594349>.
+ */
+ ret = EBUSY;
+ } else {
+ int flag = (self == TRUE) ? P_DIRTY : P_DIRTY_SHUTDOWN;
+ if (pcontrol && !(p->p_memstat_dirty & flag)) {
+ /* Mark the process as having been dirtied at some point */
+ p->p_memstat_dirty |= (flag | P_DIRTY_MARKED);
+ memorystatus_dirty_count++;
+ ret = 0;
+ } else if ((pcontrol == 0) && (p->p_memstat_dirty & flag)) {
+ if ((flag == P_DIRTY_SHUTDOWN) && (!(p->p_memstat_dirty & P_DIRTY))) {
+ /* Clearing the dirty shutdown flag, and the process is otherwise clean - kill */
+ p->p_memstat_dirty |= P_DIRTY_TERMINATED;
+ kill = true;
+ } else if ((flag == P_DIRTY) && (p->p_memstat_dirty & P_DIRTY_TERMINATED)) {
+ /* Kill previously terminated processes if set clean */
+ kill = true;
+ }
+ p->p_memstat_dirty &= ~flag;
+ memorystatus_dirty_count--;
+ ret = 0;
+ } else {
+ /* Already set */
+ ret = EALREADY;
+ }
+ }
+
+ if (ret != 0) {
+ goto exit;
+ }
+
+ if (p->p_memstat_dirty & P_DIRTY_IS_DIRTY) {
+ now_dirty = TRUE;
+ }
+
+ if ((was_dirty == TRUE && now_dirty == FALSE) ||
+ (was_dirty == FALSE && now_dirty == TRUE)) {
+#if CONFIG_DIRTYSTATUS_TRACKING
+ if (dirtystatus_tracking_enabled) {
+ uint32_t pages = 0;
+ memorystatus_get_task_page_counts(p->task, &pages, NULL, NULL);
+ change_event.dsc_pid = p->p_pid;
+ change_event.dsc_event_type = (now_dirty == TRUE) ? kDirtyStatusChangedDirty : kDirtyStatusChangedClean;
+ change_event.dsc_time = mach_absolute_time();
+ change_event.dsc_pages = pages;
+ change_event.dsc_priority = p->p_memstat_effectivepriority;
+ strlcpy(&change_event.dsc_process_name[0], p->p_name, sizeof(change_event.dsc_process_name));
+ notify_change = TRUE;
+ }
+#endif
+
+ /* Manage idle exit deferral, if applied */
+ if ((p->p_memstat_dirty & P_DIRTY_IDLE_EXIT_ENABLED) == P_DIRTY_IDLE_EXIT_ENABLED) {
+ /*
+ * Legacy mode: P_DIRTY_AGING_IN_PROGRESS means the process is in the aging band OR it might be heading back
+ * there once it's clean again. For the legacy case, this only applies if it has some protection window left.
+ * P_DIRTY_DEFER: one-time protection window given at launch
+ * P_DIRTY_DEFER_ALWAYS: protection window given for every dirty->clean transition. Like non-legacy mode.
+ *
+ * Non-Legacy mode: P_DIRTY_AGING_IN_PROGRESS means the process is in the aging band. It will always stop over
+ * in that band on it's way to IDLE.
+ */
+
+ if (p->p_memstat_dirty & P_DIRTY_IS_DIRTY) {
+ /*
+ * New dirty process i.e. "was_dirty == FALSE && now_dirty == TRUE"
+ *
+ * The process will move from its aging band to its higher requested
+ * jetsam band.
+ */
+ boolean_t reset_state = (jetsam_aging_policy != kJetsamAgingPolicyLegacy) ? TRUE : FALSE;
+
+ memorystatus_invalidate_idle_demotion_locked(p, reset_state);
+ reschedule = TRUE;
+ } else {
+ /*
+ * Process is back from "dirty" to "clean".
+ */
+
+ if (jetsam_aging_policy == kJetsamAgingPolicyLegacy) {
+ if (((p->p_memstat_dirty & P_DIRTY_DEFER_ALWAYS) == FALSE) &&
+ (mach_absolute_time() >= p->p_memstat_idledeadline)) {
+ /*
+ * The process' hasn't enrolled in the "always defer after dirty"
+ * mode and its deadline has expired. It currently
+ * does not reside in any of the aging buckets.
+ *
+ * It's on its way to the JETSAM_PRIORITY_IDLE
+ * bucket via memorystatus_update_idle_priority_locked()
+ * below.
+ *
+ * So all we need to do is reset all the state on the
+ * process that's related to the aging bucket i.e.
+ * the AGING_IN_PROGRESS flag and the timer deadline.
+ */
+
+ memorystatus_invalidate_idle_demotion_locked(p, TRUE);
+ reschedule = TRUE;
+ } else {
+ /*
+ * Process enrolled in "always stop in deferral band after dirty" OR
+ * it still has some protection window left and so
+ * we just re-arm the timer without modifying any
+ * state on the process iff it still wants into that band.
+ */
+
+ if (p->p_memstat_dirty & P_DIRTY_DEFER_ALWAYS) {
+ memorystatus_schedule_idle_demotion_locked(p, TRUE);
+ reschedule = TRUE;
+ } else if (p->p_memstat_dirty & P_DIRTY_AGING_IN_PROGRESS) {
+ memorystatus_schedule_idle_demotion_locked(p, FALSE);
+ reschedule = TRUE;
+ }
+ }
+ } else {
+ memorystatus_schedule_idle_demotion_locked(p, TRUE);
+ reschedule = TRUE;
+ }
+ }
+ }
+
+ memorystatus_update_idle_priority_locked(p);
+
+ if (memorystatus_highwater_enabled) {
+ boolean_t ledger_update_needed = TRUE;
+ boolean_t use_active;
+ boolean_t is_fatal;
+ /*
+ * We are in this path because this process transitioned between
+ * dirty <--> clean state. Update the cached memory limits.
+ */
+
+ if (proc_jetsam_state_is_active_locked(p) == TRUE) {
+ /*
+ * process is pinned in elevated band
+ * or
+ * process is dirty
+ */
+ CACHE_ACTIVE_LIMITS_LOCKED(p, is_fatal);
+ use_active = TRUE;
+ ledger_update_needed = TRUE;
+ } else {
+ /*
+ * process is clean...but if it has opted into pressured-exit
+ * we don't apply the INACTIVE limit till the process has aged
+ * out and is entering the IDLE band.
+ * See memorystatus_update_priority_locked() for that.
+ */
+
+ if (p->p_memstat_dirty & P_DIRTY_ALLOW_IDLE_EXIT) {
+ ledger_update_needed = FALSE;
+ } else {
+ CACHE_INACTIVE_LIMITS_LOCKED(p, is_fatal);
+ use_active = FALSE;
+ ledger_update_needed = TRUE;
+ }
+ }
+
+ /*
+ * Enforce the new limits by writing to the ledger.
+ *
+ * This is a hot path and holding the proc_list_lock while writing to the ledgers,
+ * (where the task lock is taken) is bad. So, we temporarily drop the proc_list_lock.
+ * We aren't traversing the jetsam bucket list here, so we should be safe.
+ * See rdar://21394491.
+ */
+
+ if (ledger_update_needed && proc_ref_locked(p) == p) {
+ int ledger_limit;
+ if (p->p_memstat_memlimit > 0) {
+ ledger_limit = p->p_memstat_memlimit;
+ } else {
+ ledger_limit = -1;
+ }
+ proc_list_unlock();
+ task_set_phys_footprint_limit_internal(p->task, ledger_limit, NULL, use_active, is_fatal);
+ proc_list_lock();
+ proc_rele_locked(p);
+
+ MEMORYSTATUS_DEBUG(3, "memorystatus_dirty_set: new limit on pid %d (%dMB %s) priority(%d) dirty?=0x%x %s\n",
+ p->p_pid, (p->p_memstat_memlimit > 0 ? p->p_memstat_memlimit : -1),
+ (p->p_memstat_state & P_MEMSTAT_FATAL_MEMLIMIT ? "F " : "NF"), p->p_memstat_effectivepriority, p->p_memstat_dirty,
+ (p->p_memstat_dirty ? ((p->p_memstat_dirty & P_DIRTY) ? "isdirty" : "isclean") : ""));
+ }
+ }
+
+ /* If the deferral state changed, reschedule the demotion timer */
+ if (reschedule) {
+ memorystatus_reschedule_idle_demotion_locked();
+ }
+ }
+
+ if (kill) {
+ if (proc_ref_locked(p) == p) {
+ proc_list_unlock();
+ psignal(p, SIGKILL);
+ proc_list_lock();
+ proc_rele_locked(p);
+ }
+ }
+
+exit:
+ proc_list_unlock();
+
+#if CONFIG_DIRTYSTATUS_TRACKING
+ // Before returning, let's notify the dirtiness status if we have to
+ if (notify_change) {
+ memorystatus_send_dirty_status_change_note(&change_event, sizeof(change_event));
+ }
+#endif
+
+ return ret;
+}
+
+int
+memorystatus_dirty_clear(proc_t p, uint32_t pcontrol)
+{
+ int ret = 0;
+
+ MEMORYSTATUS_DEBUG(1, "memorystatus_dirty_clear(): %d 0x%x 0x%x\n", p->p_pid, pcontrol, p->p_memstat_dirty);
+
+ KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_DIRTY_CLEAR), p->p_pid, pcontrol, 0, 0, 0);
+
+ proc_list_lock();
+
+ if ((p->p_listflag & P_LIST_EXITED) != 0) {
+ /*
+ * Process is on its way out.
+ */
+ ret = EBUSY;
+ goto exit;
+ }
+
+ if (p->p_memstat_state & P_MEMSTAT_INTERNAL) {
+ ret = EPERM;
+ goto exit;
+ }
+
+ if (!(p->p_memstat_dirty & P_DIRTY_TRACK)) {
+ /* Dirty tracking not enabled */
+ ret = EINVAL;
+ goto exit;
+ }
+
+ if (!pcontrol || (pcontrol & (PROC_DIRTY_LAUNCH_IN_PROGRESS | PROC_DIRTY_DEFER | PROC_DIRTY_DEFER_ALWAYS)) == 0) {
+ ret = EINVAL;
+ goto exit;
+ }
+
+ if (pcontrol & PROC_DIRTY_LAUNCH_IN_PROGRESS) {
+ p->p_memstat_dirty &= ~P_DIRTY_LAUNCH_IN_PROGRESS;
+ }
+
+ /* This can be set and cleared exactly once. */
+ if (pcontrol & (PROC_DIRTY_DEFER | PROC_DIRTY_DEFER_ALWAYS)) {
+ if (p->p_memstat_dirty & P_DIRTY_DEFER) {
+ p->p_memstat_dirty &= ~(P_DIRTY_DEFER);
+ }
+
+ if (p->p_memstat_dirty & P_DIRTY_DEFER_ALWAYS) {
+ p->p_memstat_dirty &= ~(P_DIRTY_DEFER_ALWAYS);
+ }
+
+ memorystatus_invalidate_idle_demotion_locked(p, TRUE);
+ memorystatus_update_idle_priority_locked(p);
+ memorystatus_reschedule_idle_demotion_locked();
+ }
+
+ ret = 0;
+exit:
+ proc_list_unlock();
+
+ return ret;
+}
+
+int
+memorystatus_dirty_get(proc_t p, boolean_t locked)
+{
+ int ret = 0;
+
+ if (!locked) {
+ proc_list_lock();
+ }
+
+ if (p->p_memstat_dirty & P_DIRTY_TRACK) {
+ ret |= PROC_DIRTY_TRACKED;
+ if (p->p_memstat_dirty & P_DIRTY_ALLOW_IDLE_EXIT) {
+ ret |= PROC_DIRTY_ALLOWS_IDLE_EXIT;
+ }
+ if (p->p_memstat_dirty & P_DIRTY) {
+ ret |= PROC_DIRTY_IS_DIRTY;
+ }
+ if (p->p_memstat_dirty & P_DIRTY_LAUNCH_IN_PROGRESS) {
+ ret |= PROC_DIRTY_LAUNCH_IS_IN_PROGRESS;
+ }
+ }
+
+ if (!locked) {
+ proc_list_unlock();
+ }
+
+ return ret;
+}
+
+int
+memorystatus_on_terminate(proc_t p)
+{
+ int sig;
+
+ proc_list_lock();
+
+ p->p_memstat_dirty |= P_DIRTY_TERMINATED;
+
+ if (((p->p_memstat_dirty & (P_DIRTY_TRACK | P_DIRTY_IS_DIRTY)) == P_DIRTY_TRACK) ||
+ (p->p_memstat_state & P_MEMSTAT_SUSPENDED)) {
+ /*
+ * Mark as terminated and issue SIGKILL if:-
+ * - process is clean, or,
+ * - if process is dirty but suspended. This case is likely
+ * an extension because apps don't opt into dirty-tracking
+ * and daemons aren't suspended.
+ */
+#if DEVELOPMENT || DEBUG
+ if (p->p_memstat_state & P_MEMSTAT_SUSPENDED) {
+ os_log(OS_LOG_DEFAULT, "memorystatus: sending suspended process %s (pid %d) SIGKILL",
+ (*p->p_name ? p->p_name : "unknown"), p->p_pid);
+ }
+#endif /* DEVELOPMENT || DEBUG */
+ sig = SIGKILL;
+ } else {
+ /* Dirty, terminated, or state tracking is unsupported; issue SIGTERM to allow cleanup */
+ sig = SIGTERM;
+ }
+
+ proc_list_unlock();
+
+ return sig;
+}
+
+void
+memorystatus_on_suspend(proc_t p)
+{
+#if CONFIG_FREEZE
+ uint32_t pages;
+ memorystatus_get_task_page_counts(p->task, &pages, NULL, NULL);
+#endif
+ proc_list_lock();
+#if CONFIG_FREEZE
+ memorystatus_suspended_count++;
+#endif
+ p->p_memstat_state |= P_MEMSTAT_SUSPENDED;
+ proc_list_unlock();
+}
+
+extern uint64_t memorystatus_thaw_count_since_boot;
+
+void
+memorystatus_on_resume(proc_t p)
+{
+#if CONFIG_FREEZE
+ boolean_t frozen;
+ pid_t pid;
+#endif
+
+ proc_list_lock();
+
+#if CONFIG_FREEZE
+ frozen = (p->p_memstat_state & P_MEMSTAT_FROZEN);
+ if (frozen) {
+ /*
+ * Now that we don't _thaw_ a process completely,
+ * resuming it (and having some on-demand swapins)
+ * shouldn't preclude it from being counted as frozen.
+ *
+ * memorystatus_frozen_count--;
+ *
+ * We preserve the P_MEMSTAT_FROZEN state since the process
+ * could have state on disk AND so will deserve some protection
+ * in the jetsam bands.
+ */
+ if ((p->p_memstat_state & P_MEMSTAT_REFREEZE_ELIGIBLE) == 0) {
+ p->p_memstat_state |= P_MEMSTAT_REFREEZE_ELIGIBLE;
+ memorystatus_refreeze_eligible_count++;
+ }
+ p->p_memstat_thaw_count++;
+
+ memorystatus_thaw_count++;
+ memorystatus_thaw_count_since_boot++;
+ }
+
+ memorystatus_suspended_count--;
+
+ pid = p->p_pid;
+#endif
+
+ /*
+ * P_MEMSTAT_FROZEN will remain unchanged. This used to be:
+ * p->p_memstat_state &= ~(P_MEMSTAT_SUSPENDED | P_MEMSTAT_FROZEN);
+ */
+ p->p_memstat_state &= ~P_MEMSTAT_SUSPENDED;
+
+ proc_list_unlock();
+
+#if CONFIG_FREEZE
+ if (frozen) {
+ memorystatus_freeze_entry_t data = { pid, FALSE, 0 };
+ memorystatus_send_note(kMemorystatusFreezeNote, &data, sizeof(data));
+ }
+#endif
+}
+
+void
+memorystatus_on_inactivity(proc_t p)
+{
+#pragma unused(p)
+#if CONFIG_FREEZE
+ /* Wake the freeze thread */
+ thread_wakeup((event_t)&memorystatus_freeze_wakeup);
+#endif
+}
+
+/*
+ * The proc_list_lock is held by the caller.
+ */
+static uint32_t
+memorystatus_build_state(proc_t p)
+{
+ uint32_t snapshot_state = 0;
+
+ /* General */
+ if (p->p_memstat_state & P_MEMSTAT_SUSPENDED) {
+ snapshot_state |= kMemorystatusSuspended;
+ }
+ if (p->p_memstat_state & P_MEMSTAT_FROZEN) {
+ snapshot_state |= kMemorystatusFrozen;
+ }
+ if (p->p_memstat_state & P_MEMSTAT_REFREEZE_ELIGIBLE) {
+ snapshot_state |= kMemorystatusWasThawed;
+ }
+ if (p->p_memstat_state & P_MEMSTAT_PRIORITY_ASSERTION) {
+ snapshot_state |= kMemorystatusAssertion;
+ }
+
+ /* Tracking */
+ if (p->p_memstat_dirty & P_DIRTY_TRACK) {
+ snapshot_state |= kMemorystatusTracked;
+ }
+ if ((p->p_memstat_dirty & P_DIRTY_IDLE_EXIT_ENABLED) == P_DIRTY_IDLE_EXIT_ENABLED) {
+ snapshot_state |= kMemorystatusSupportsIdleExit;
+ }
+ if (p->p_memstat_dirty & P_DIRTY_IS_DIRTY) {
+ snapshot_state |= kMemorystatusDirty;
+ }
+
+ return snapshot_state;
+}
+
+static boolean_t
+kill_idle_exit_proc(void)
+{
+ proc_t p, victim_p = PROC_NULL;
+ uint64_t current_time, footprint_of_killed_proc;
+ boolean_t killed = FALSE;
+ unsigned int i = 0;
+ os_reason_t jetsam_reason = OS_REASON_NULL;
+
+ /* Pick next idle exit victim. */
+ current_time = mach_absolute_time();
+
+ jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_MEMORY_IDLE_EXIT);
+ if (jetsam_reason == OS_REASON_NULL) {
+ printf("kill_idle_exit_proc: failed to allocate jetsam reason\n");
+ }
+
+ proc_list_lock();
+
+ p = memorystatus_get_first_proc_locked(&i, FALSE);
+ while (p) {
+ /* No need to look beyond the idle band */
+ if (p->p_memstat_effectivepriority != JETSAM_PRIORITY_IDLE) {
+ break;
+ }
+
+ if ((p->p_memstat_dirty & (P_DIRTY_ALLOW_IDLE_EXIT | P_DIRTY_IS_DIRTY | P_DIRTY_TERMINATED)) == (P_DIRTY_ALLOW_IDLE_EXIT)) {
+ if (current_time >= p->p_memstat_idledeadline) {
+ p->p_memstat_dirty |= P_DIRTY_TERMINATED;
+ victim_p = proc_ref_locked(p);
+ break;
+ }
+ }
+
+ p = memorystatus_get_next_proc_locked(&i, p, FALSE);
+ }
+
+ proc_list_unlock();
+
+ if (victim_p) {
+ printf("memorystatus: killing_idle_process pid %d [%s] jetsam_reason->osr_code: %llu\n", victim_p->p_pid, (*victim_p->p_name ? victim_p->p_name : "unknown"), jetsam_reason->osr_code);
+ killed = memorystatus_do_kill(victim_p, kMemorystatusKilledIdleExit, jetsam_reason, &footprint_of_killed_proc);
+ proc_rele(victim_p);
+ } else {
+ os_reason_free(jetsam_reason);
+ }
+
+ return killed;
+}
+
+static void
+memorystatus_thread_wake(void)
+{
+ int thr_id = 0;
+ int active_thr = atomic_load(&active_jetsam_threads);
+
+ /* Wakeup all the jetsam threads */
+ for (thr_id = 0; thr_id < active_thr; thr_id++) {
+ thread_wakeup((event_t)&jetsam_threads[thr_id].memorystatus_wakeup);
+ }
+}
+
+#if CONFIG_JETSAM
+
+static void
+memorystatus_thread_pool_max()
+{
+ /* Increase the jetsam thread pool to max_jetsam_threads */
+ int max_threads = max_jetsam_threads;
+ printf("Expanding memorystatus pool to %d!\n", max_threads);
+ atomic_store(&active_jetsam_threads, max_threads);
+}
+
+static void
+memorystatus_thread_pool_default()
+{
+ /* Restore the jetsam thread pool to a single thread */
+ printf("Reverting memorystatus pool back to 1\n");
+ atomic_store(&active_jetsam_threads, 1);
+}
+
+#endif /* CONFIG_JETSAM */
+
+extern void vm_pressure_response(void);
+
+static int
+memorystatus_thread_block(uint32_t interval_ms, thread_continue_t continuation)
+{
+ struct jetsam_thread_state *jetsam_thread = jetsam_current_thread();
+
+ assert(jetsam_thread != NULL);
+ if (interval_ms) {
+ assert_wait_timeout(&jetsam_thread->memorystatus_wakeup, THREAD_UNINT, interval_ms, NSEC_PER_MSEC);
+ } else {
+ assert_wait(&jetsam_thread->memorystatus_wakeup, THREAD_UNINT);
+ }
+
+ return thread_block(continuation);
+}
+
+static boolean_t
+memorystatus_avail_pages_below_pressure(void)
+{
+#if CONFIG_JETSAM
+ return memorystatus_available_pages <= memorystatus_available_pages_pressure;
+#else /* CONFIG_JETSAM */
+ return FALSE;
+#endif /* CONFIG_JETSAM */
+}
+
+static boolean_t
+memorystatus_avail_pages_below_critical(void)
+{
+#if CONFIG_JETSAM
+ return memorystatus_available_pages <= memorystatus_available_pages_critical;
+#else /* CONFIG_JETSAM */
+ return FALSE;
+#endif /* CONFIG_JETSAM */
+}
+
+static boolean_t
+memorystatus_post_snapshot(int32_t priority, uint32_t cause)
+{
+ boolean_t is_idle_priority;
+
+ if (jetsam_aging_policy == kJetsamAgingPolicyLegacy) {
+ is_idle_priority = (priority == JETSAM_PRIORITY_IDLE);
+ } else {
+ is_idle_priority = (priority == JETSAM_PRIORITY_IDLE || priority == JETSAM_PRIORITY_IDLE_DEFERRED);
+ }
+#if CONFIG_JETSAM
+#pragma unused(cause)
+ /*
+ * Don't generate logs for steady-state idle-exit kills,
+ * unless it is overridden for debug or by the device
+ * tree.
+ */
+
+ return !is_idle_priority || memorystatus_idle_snapshot;
+
+#else /* CONFIG_JETSAM */
+ /*
+ * Don't generate logs for steady-state idle-exit kills,
+ * unless
+ * - it is overridden for debug or by the device
+ * tree.
+ * OR
+ * - the kill causes are important i.e. not kMemorystatusKilledIdleExit
+ */
+
+ boolean_t snapshot_eligible_kill_cause = (is_reason_thrashing(cause) || is_reason_zone_map_exhaustion(cause));
+ return !is_idle_priority || memorystatus_idle_snapshot || snapshot_eligible_kill_cause;
+#endif /* CONFIG_JETSAM */
+}
+
+static boolean_t
+memorystatus_action_needed(void)
+{
+#if CONFIG_JETSAM
+ return is_reason_thrashing(kill_under_pressure_cause) ||
+ is_reason_zone_map_exhaustion(kill_under_pressure_cause) ||
+ memorystatus_available_pages <= memorystatus_available_pages_pressure;
+#else /* CONFIG_JETSAM */
+ return is_reason_thrashing(kill_under_pressure_cause) ||
+ is_reason_zone_map_exhaustion(kill_under_pressure_cause);
+#endif /* CONFIG_JETSAM */
+}
+
+static boolean_t
+memorystatus_act_on_hiwat_processes(uint32_t *errors, uint32_t *hwm_kill, boolean_t *post_snapshot, __unused boolean_t *is_critical, uint64_t *memory_reclaimed)
+{
+ boolean_t purged = FALSE, killed = FALSE;
+
+ *memory_reclaimed = 0;
+ killed = memorystatus_kill_hiwat_proc(errors, &purged, memory_reclaimed);
+
+ if (killed) {
+ *hwm_kill = *hwm_kill + 1;
+ *post_snapshot = TRUE;
+ return TRUE;
+ } else {
+ if (purged == FALSE) {
+ /* couldn't purge and couldn't kill */
+ memorystatus_hwm_candidates = FALSE;
+ }
+ }
+
+#if CONFIG_JETSAM
+ /* No highwater processes to kill. Continue or stop for now? */
+ if (!is_reason_thrashing(kill_under_pressure_cause) &&
+ !is_reason_zone_map_exhaustion(kill_under_pressure_cause) &&
+ (memorystatus_available_pages > memorystatus_available_pages_critical)) {
+ /*
+ * We are _not_ out of pressure but we are above the critical threshold and there's:
+ * - no compressor thrashing
+ * - enough zone memory
+ * - no more HWM processes left.
+ * For now, don't kill any other processes.
+ */
+
+ if (*hwm_kill == 0) {
+ memorystatus_thread_wasted_wakeup++;
+ }
+
+ *is_critical = FALSE;
+
+ return TRUE;
+ }
+#endif /* CONFIG_JETSAM */
+
+ return FALSE;
+}
+
+/*
+ * kJetsamHighRelaunchCandidatesThreshold defines the percentage of candidates
+ * in the idle & deferred bands that need to be bad candidates in order to trigger
+ * aggressive jetsam.
+ */
+#define kJetsamHighRelaunchCandidatesThreshold (100)
+
+/* kJetsamMinCandidatesThreshold defines the minimum number of candidates in the
+ * idle/deferred bands to trigger aggressive jetsam. This value basically decides
+ * how much memory the system is ready to hold in the lower bands without triggering
+ * aggressive jetsam. This number should ideally be tuned based on the memory config
+ * of the device.
+ */
+#define kJetsamMinCandidatesThreshold (5)
+
+static boolean_t
+memorystatus_aggressive_jetsam_needed_sysproc_aging(__unused int jld_eval_aggressive_count, __unused int *jld_idle_kills, __unused int jld_idle_kill_candidates, int *total_candidates, int *elevated_bucket_count)
+{
+ boolean_t aggressive_jetsam_needed = false;
+
+ /*
+ * For the kJetsamAgingPolicySysProcsReclaimedFirst aging policy, we maintain the jetsam
+ * relaunch behavior for all daemons. Also, daemons and apps are aged in deferred bands on
+ * every dirty->clean transition. For this aging policy, the best way to determine if
+ * aggressive jetsam is needed, is to see if the kill candidates are mostly bad candidates.
+ * If yes, then we need to go to higher bands to reclaim memory.
+ */
+ proc_list_lock();
+ /* Get total candidate counts for idle and idle deferred bands */
+ *total_candidates = memstat_bucket[JETSAM_PRIORITY_IDLE].count + memstat_bucket[system_procs_aging_band].count;
+ /* Get counts of bad kill candidates in idle and idle deferred bands */
+ int bad_candidates = memstat_bucket[JETSAM_PRIORITY_IDLE].relaunch_high_count + memstat_bucket[system_procs_aging_band].relaunch_high_count;
+
+ *elevated_bucket_count = memstat_bucket[JETSAM_PRIORITY_ELEVATED_INACTIVE].count;
+
+ proc_list_unlock();
+
+ /* Check if the number of bad candidates is greater than kJetsamHighRelaunchCandidatesThreshold % */
+ aggressive_jetsam_needed = (((bad_candidates * 100) / *total_candidates) >= kJetsamHighRelaunchCandidatesThreshold);
+
+ /*
+ * Since the new aging policy bases the aggressive jetsam trigger on percentage of
+ * bad candidates, it is prone to being overly aggressive. In order to mitigate that,
+ * make sure the system is really under memory pressure before triggering aggressive
+ * jetsam.
+ */
+ if (memorystatus_available_pages > memorystatus_sysproc_aging_aggr_pages) {
+ aggressive_jetsam_needed = false;
+ }
+
+#if DEVELOPMENT || DEBUG
+ printf("memorystatus: aggressive%d: [%s] Bad Candidate Threshold Check (total: %d, bad: %d, threshold: %d %%); Memory Pressure Check (available_pgs: %llu, threshold_pgs: %llu)\n",
+ jld_eval_aggressive_count, aggressive_jetsam_needed ? "PASSED" : "FAILED", *total_candidates, bad_candidates,
+ kJetsamHighRelaunchCandidatesThreshold, (uint64_t)MEMORYSTATUS_LOG_AVAILABLE_PAGES, (uint64_t)memorystatus_sysproc_aging_aggr_pages);
+#endif /* DEVELOPMENT || DEBUG */
+ return aggressive_jetsam_needed;
+}
+
+/*
+ * Gets memory back from various system caches.
+ * Called before jetsamming in the foreground band in the hope that we'll
+ * avoid a jetsam.
+ */
+static void
+memorystatus_approaching_fg_band(boolean_t *corpse_list_purged)
+{
+ assert(corpse_list_purged != NULL);
+ pmap_release_pages_fast();
+ memorystatus_issue_fg_band_notify();
+ if (total_corpses_count() > 0 && !*corpse_list_purged) {
+ task_purge_all_corpses();
+ *corpse_list_purged = TRUE;
+ }
+}
+
+static boolean_t
+memorystatus_aggressive_jetsam_needed_default(__unused int jld_eval_aggressive_count, int *jld_idle_kills, int jld_idle_kill_candidates, int *total_candidates, int *elevated_bucket_count)
+{
+ boolean_t aggressive_jetsam_needed = false;
+ /* Jetsam Loop Detection - locals */
+ memstat_bucket_t *bucket;
+ int jld_bucket_count = 0;
+
+ proc_list_lock();
+ switch (jetsam_aging_policy) {
+ case kJetsamAgingPolicyLegacy:
+ bucket = &memstat_bucket[JETSAM_PRIORITY_IDLE];
+ jld_bucket_count = bucket->count;
+ bucket = &memstat_bucket[JETSAM_PRIORITY_AGING_BAND1];
+ jld_bucket_count += bucket->count;
+ break;
+ case kJetsamAgingPolicyAppsReclaimedFirst:
+ bucket = &memstat_bucket[JETSAM_PRIORITY_IDLE];
+ jld_bucket_count = bucket->count;
+ bucket = &memstat_bucket[system_procs_aging_band];
+ jld_bucket_count += bucket->count;
+ bucket = &memstat_bucket[applications_aging_band];
+ jld_bucket_count += bucket->count;
+ break;
+ case kJetsamAgingPolicyNone:
+ default:
+ bucket = &memstat_bucket[JETSAM_PRIORITY_IDLE];
+ jld_bucket_count = bucket->count;
+ break;
+ }
+
+ bucket = &memstat_bucket[JETSAM_PRIORITY_ELEVATED_INACTIVE];
+ *elevated_bucket_count = bucket->count;
+ *total_candidates = jld_bucket_count;
+ proc_list_unlock();
+
+ aggressive_jetsam_needed = (*jld_idle_kills > jld_idle_kill_candidates);
+
+#if DEVELOPMENT || DEBUG
+ if (aggressive_jetsam_needed) {
+ printf("memorystatus: aggressive%d: idle candidates: %d, idle kills: %d\n",
+ jld_eval_aggressive_count,
+ jld_idle_kill_candidates,
+ *jld_idle_kills);
+ }
+#endif /* DEVELOPMENT || DEBUG */
+ return aggressive_jetsam_needed;
+}
+
+static boolean_t
+memorystatus_act_aggressive(uint32_t cause, os_reason_t jetsam_reason, int *jld_idle_kills, boolean_t *corpse_list_purged, boolean_t *post_snapshot, uint64_t *memory_reclaimed)
+{
+ boolean_t aggressive_jetsam_needed = false;
+ boolean_t killed;
+ uint32_t errors = 0;
+ uint64_t footprint_of_killed_proc = 0;
+ int elevated_bucket_count = 0;
+ int total_candidates = 0;
+ *memory_reclaimed = 0;
+
+ /*
+ * The aggressive jetsam logic looks at the number of times it has been in the
+ * aggressive loop to determine the max priority band it should kill upto. The
+ * static variables below are used to track that property.
+ *
+ * To reset those values, the implementation checks if it has been
+ * memorystatus_jld_eval_period_msecs since the parameters were reset.
+ */
+ static int jld_eval_aggressive_count = 0;
+ static int32_t jld_priority_band_max = JETSAM_PRIORITY_UI_SUPPORT;
+ static uint64_t jld_timestamp_msecs = 0;
+ static int jld_idle_kill_candidates = 0;
+
+ if (memorystatus_jld_enabled == FALSE) {
+ /* If aggressive jetsam is disabled, nothing to do here */
+ return FALSE;
+ }
+
+ /* Get current timestamp (msecs only) */
+ struct timeval jld_now_tstamp = {0, 0};
+ uint64_t jld_now_msecs = 0;
+ microuptime(&jld_now_tstamp);
+ jld_now_msecs = (jld_now_tstamp.tv_sec * 1000);
+
+ /*
+ * The aggressive jetsam logic looks at the number of candidates and their
+ * properties to decide if aggressive jetsam should be engaged.
+ */
+ if (jetsam_aging_policy == kJetsamAgingPolicySysProcsReclaimedFirst) {
+ /*
+ * For the kJetsamAgingPolicySysProcsReclaimedFirst aging policy, the logic looks at the number of
+ * candidates in the idle and deferred band and how many out of them are marked as high relaunch
+ * probability.
+ */
+ aggressive_jetsam_needed = memorystatus_aggressive_jetsam_needed_sysproc_aging(jld_eval_aggressive_count,
+ jld_idle_kills, jld_idle_kill_candidates, &total_candidates, &elevated_bucket_count);
+ } else {
+ /*
+ * The other aging policies look at number of candidate processes over a specific time window and
+ * evaluate if the system is in a jetsam loop. If yes, aggressive jetsam is triggered.
+ */
+ aggressive_jetsam_needed = memorystatus_aggressive_jetsam_needed_default(jld_eval_aggressive_count,
+ jld_idle_kills, jld_idle_kill_candidates, &total_candidates, &elevated_bucket_count);
+ }
+
+ /*
+ * Check if its been really long since the aggressive jetsam evaluation
+ * parameters have been refreshed. This logic also resets the jld_eval_aggressive_count
+ * counter to make sure we reset the aggressive jetsam severity.
+ */
+ boolean_t param_reval = false;
+
+ if ((total_candidates == 0) ||
+ (jld_now_msecs > (jld_timestamp_msecs + memorystatus_jld_eval_period_msecs))) {
+ jld_timestamp_msecs = jld_now_msecs;
+ jld_idle_kill_candidates = total_candidates;
+ *jld_idle_kills = 0;
+ jld_eval_aggressive_count = 0;
+ jld_priority_band_max = JETSAM_PRIORITY_UI_SUPPORT;
+ param_reval = true;
+ }
+
+ /*
+ * If the parameters have been updated, re-evaluate the aggressive_jetsam_needed condition for
+ * the non kJetsamAgingPolicySysProcsReclaimedFirst policy since its based on jld_idle_kill_candidates etc.
+ */
+ if ((param_reval == true) && (jetsam_aging_policy != kJetsamAgingPolicySysProcsReclaimedFirst)) {
+ aggressive_jetsam_needed = (*jld_idle_kills > jld_idle_kill_candidates);
+ }
+
+ /*
+ * It is also possible that the system is down to a very small number of processes in the candidate
+ * bands. In that case, the decisions made by the memorystatus_aggressive_jetsam_needed_* routines
+ * would not be useful. In that case, do not trigger aggressive jetsam.
+ */
+ if (total_candidates < kJetsamMinCandidatesThreshold) {
+#if DEVELOPMENT || DEBUG
+ printf("memorystatus: aggressive: [FAILED] Low Candidate Count (current: %d, threshold: %d)\n", total_candidates, kJetsamMinCandidatesThreshold);
+#endif /* DEVELOPMENT || DEBUG */
+ aggressive_jetsam_needed = false;
+ }
+
+ if (aggressive_jetsam_needed == false) {
+ /* Either the aging policy or the candidate count decided that aggressive jetsam is not needed. Nothing more to do here. */
+ return FALSE;
+ }
+
+ /* Looks like aggressive jetsam is needed */
+ jld_eval_aggressive_count++;
+
+ if (jld_eval_aggressive_count == memorystatus_jld_eval_aggressive_count) {
+ memorystatus_approaching_fg_band(corpse_list_purged);
+ } else if (jld_eval_aggressive_count > memorystatus_jld_eval_aggressive_count) {
+ /*
+ * Bump up the jetsam priority limit (eg: the bucket index)
+ * Enforce bucket index sanity.
+ */
+ if ((memorystatus_jld_eval_aggressive_priority_band_max < 0) ||
+ (memorystatus_jld_eval_aggressive_priority_band_max >= MEMSTAT_BUCKET_COUNT)) {
+ /*
+ * Do nothing. Stick with the default level.
+ */
+ } else {
+ jld_priority_band_max = memorystatus_jld_eval_aggressive_priority_band_max;
+ }
+ }
+
+ /* Visit elevated processes first */
+ while (elevated_bucket_count) {
+ elevated_bucket_count--;
+
+ /*
+ * memorystatus_kill_elevated_process() drops a reference,
+ * so take another one so we can continue to use this exit reason
+ * even after it returns.
+ */
+
+ os_reason_ref(jetsam_reason);
+ killed = memorystatus_kill_elevated_process(
+ cause,
+ jetsam_reason,
+ JETSAM_PRIORITY_ELEVATED_INACTIVE,
+ jld_eval_aggressive_count,
+ &errors, &footprint_of_killed_proc);
+ if (killed) {
+ *post_snapshot = TRUE;
+ *memory_reclaimed += footprint_of_killed_proc;
+ if (memorystatus_avail_pages_below_pressure()) {
+ /*
+ * Still under pressure.
+ * Find another pinned processes.
+ */
+ continue;
+ } else {
+ return TRUE;
+ }
+ } else {
+ /*
+ * No pinned processes left to kill.
+ * Abandon elevated band.
+ */
+ break;
+ }
+ }
+
+ /*
+ * memorystatus_kill_processes_aggressive() allocates its own
+ * jetsam_reason so the kMemorystatusKilledProcThrashing cause
+ * is consistent throughout the aggressive march.
+ */
+ killed = memorystatus_kill_processes_aggressive(
+ kMemorystatusKilledProcThrashing,
+ jld_eval_aggressive_count,
+ jld_priority_band_max,
+ &errors, &footprint_of_killed_proc);
+
+ if (killed) {
+ /* Always generate logs after aggressive kill */
+ *post_snapshot = TRUE;
+ *memory_reclaimed += footprint_of_killed_proc;
+ *jld_idle_kills = 0;
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+
+static void
+memorystatus_thread(void *param __unused, wait_result_t wr __unused)
+{
+ boolean_t post_snapshot = FALSE;
+ uint32_t errors = 0;
+ uint32_t hwm_kill = 0;
+ boolean_t sort_flag = TRUE;
+ boolean_t corpse_list_purged = FALSE;
+ int jld_idle_kills = 0;
+ struct jetsam_thread_state *jetsam_thread = jetsam_current_thread();
+ uint64_t total_memory_reclaimed = 0;
+
+ assert(jetsam_thread != NULL);
+ if (jetsam_thread->inited == FALSE) {
+ /*
+ * It's the first time the thread has run, so just mark the thread as privileged and block.
+ * This avoids a spurious pass with unset variables, as set out in <rdar://problem/9609402>.
+ */
+
+ char name[32];
+ thread_wire(host_priv_self(), current_thread(), TRUE);
+ snprintf(name, 32, "VM_memorystatus_%d", jetsam_thread->index + 1);
+
+ /* Limit all but one thread to the lower jetsam bands, as that's where most of the victims are. */
+ if (jetsam_thread->index == 0) {
+ if (vm_pageout_state.vm_restricted_to_single_processor == TRUE) {
+ thread_vm_bind_group_add();
+ }
+ jetsam_thread->limit_to_low_bands = FALSE;
+ } else {
+ jetsam_thread->limit_to_low_bands = TRUE;
+ }
+#if CONFIG_THREAD_GROUPS
+ thread_group_vm_add();
+#endif
+ thread_set_thread_name(current_thread(), name);
+ jetsam_thread->inited = TRUE;
+ memorystatus_thread_block(0, memorystatus_thread);
+ }
+
+ KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_SCAN) | DBG_FUNC_START,
+ MEMORYSTATUS_LOG_AVAILABLE_PAGES, memorystatus_jld_enabled, memorystatus_jld_eval_period_msecs, memorystatus_jld_eval_aggressive_count, 0);
+
+ /*
+ * Jetsam aware version.
+ *
+ * The VM pressure notification thread is working it's way through clients in parallel.
+ *
+ * So, while the pressure notification thread is targeting processes in order of
+ * increasing jetsam priority, we can hopefully reduce / stop it's work by killing
+ * any processes that have exceeded their highwater mark.
+ *
+ * If we run out of HWM processes and our available pages drops below the critical threshold, then,
+ * we target the least recently used process in order of increasing jetsam priority (exception: the FG band).
+ */
+ while (memorystatus_action_needed()) {
+ boolean_t killed;
+ int32_t priority;
+ uint32_t cause;
+ uint64_t memory_reclaimed = 0;
+ uint64_t jetsam_reason_code = JETSAM_REASON_INVALID;
+ os_reason_t jetsam_reason = OS_REASON_NULL;
+
+ cause = kill_under_pressure_cause;
+ switch (cause) {
+ case kMemorystatusKilledFCThrashing:
+ jetsam_reason_code = JETSAM_REASON_MEMORY_FCTHRASHING;
+ break;
+ case kMemorystatusKilledVMCompressorThrashing:
+ jetsam_reason_code = JETSAM_REASON_MEMORY_VMCOMPRESSOR_THRASHING;
+ break;
+ case kMemorystatusKilledVMCompressorSpaceShortage:
+ jetsam_reason_code = JETSAM_REASON_MEMORY_VMCOMPRESSOR_SPACE_SHORTAGE;
+ break;
+ case kMemorystatusKilledZoneMapExhaustion:
+ jetsam_reason_code = JETSAM_REASON_ZONE_MAP_EXHAUSTION;
+ break;
+ case kMemorystatusKilledVMPageShortage:
+ /* falls through */
+ default:
+ jetsam_reason_code = JETSAM_REASON_MEMORY_VMPAGESHORTAGE;
+ cause = kMemorystatusKilledVMPageShortage;
+ break;
+ }
+
+ /* Highwater */
+ boolean_t is_critical = TRUE;
+ if (memorystatus_act_on_hiwat_processes(&errors, &hwm_kill, &post_snapshot, &is_critical, &memory_reclaimed)) {
+ total_memory_reclaimed += memory_reclaimed;
+ if (is_critical == FALSE) {
+ /*
+ * For now, don't kill any other processes.
+ */
+ break;
+ } else {
+ goto done;
+ }
+ }
+
+ jetsam_reason = os_reason_create(OS_REASON_JETSAM, jetsam_reason_code);
+ if (jetsam_reason == OS_REASON_NULL) {
+ printf("memorystatus_thread: failed to allocate jetsam reason\n");
+ }
+
+ /* Only unlimited jetsam threads should act aggressive */
+ if (!jetsam_thread->limit_to_low_bands &&
+ memorystatus_act_aggressive(cause, jetsam_reason, &jld_idle_kills, &corpse_list_purged, &post_snapshot, &memory_reclaimed)) {
+ total_memory_reclaimed += memory_reclaimed;
+ goto done;
+ }
+
+ /*
+ * memorystatus_kill_top_process() drops a reference,
+ * so take another one so we can continue to use this exit reason
+ * even after it returns
+ */
+ os_reason_ref(jetsam_reason);
+
+ /* LRU */
+ killed = memorystatus_kill_top_process(TRUE, sort_flag, cause, jetsam_reason, &priority, &errors, &memory_reclaimed);
+ sort_flag = FALSE;
+
+ if (killed) {
+ total_memory_reclaimed += memory_reclaimed;
+ if (memorystatus_post_snapshot(priority, cause) == TRUE) {
+ post_snapshot = TRUE;
+ }
+
+ /* Jetsam Loop Detection */
+ if (memorystatus_jld_enabled == TRUE) {
+ if ((priority == JETSAM_PRIORITY_IDLE) || (priority == system_procs_aging_band) || (priority == applications_aging_band)) {
+ jld_idle_kills++;
+ } else {
+ /*
+ * We've reached into bands beyond idle deferred.
+ * We make no attempt to monitor them
+ */
+ }
+ }
+
+ /*
+ * If we have jetsammed a process in or above JETSAM_PRIORITY_UI_SUPPORT
+ * then we attempt to relieve pressure by purging corpse memory and notifying
+ * anybody wanting to know this.
+ */
+ if (priority >= JETSAM_PRIORITY_UI_SUPPORT) {
+ memorystatus_approaching_fg_band(&corpse_list_purged);
+ }
+ goto done;
+ }
+
+ if (memorystatus_avail_pages_below_critical()) {
+ /*
+ * Still under pressure and unable to kill a process - purge corpse memory
+ * and get everything back from the pmap.
+ */
+ pmap_release_pages_fast();
+ if (total_corpses_count() > 0) {
+ task_purge_all_corpses();
+ corpse_list_purged = TRUE;
+ }
+
+ if (!jetsam_thread->limit_to_low_bands && memorystatus_avail_pages_below_critical()) {
+ /*
+ * Still under pressure and unable to kill a process - panic
+ */
+ panic("memorystatus_jetsam_thread: no victim! available pages:%llu\n", (uint64_t)MEMORYSTATUS_LOG_AVAILABLE_PAGES);
+ }
+ }
+
+done:
+
+ /*
+ * We do not want to over-kill when thrashing has been detected.
+ * To avoid that, we reset the flag here and notify the
+ * compressor.
+ */
+ if (is_reason_thrashing(kill_under_pressure_cause)) {
+ kill_under_pressure_cause = 0;
+#if CONFIG_JETSAM
+ vm_thrashing_jetsam_done();
+#endif /* CONFIG_JETSAM */
+ } else if (is_reason_zone_map_exhaustion(kill_under_pressure_cause)) {
+ kill_under_pressure_cause = 0;
+ }
+
+ os_reason_free(jetsam_reason);
+ }
+
+ kill_under_pressure_cause = 0;
+
+ if (errors) {
+ memorystatus_clear_errors();
+ }
+
+ if (post_snapshot) {
+ proc_list_lock();
+ size_t snapshot_size = sizeof(memorystatus_jetsam_snapshot_t) +
+ sizeof(memorystatus_jetsam_snapshot_entry_t) * (memorystatus_jetsam_snapshot_count);
+ uint64_t timestamp_now = mach_absolute_time();
+ memorystatus_jetsam_snapshot->notification_time = timestamp_now;
+ memorystatus_jetsam_snapshot->js_gencount++;
+ if (memorystatus_jetsam_snapshot_count > 0 && (memorystatus_jetsam_snapshot_last_timestamp == 0 ||
+ timestamp_now > memorystatus_jetsam_snapshot_last_timestamp + memorystatus_jetsam_snapshot_timeout)) {
+ proc_list_unlock();
+ int ret = memorystatus_send_note(kMemorystatusSnapshotNote, &snapshot_size, sizeof(snapshot_size));
+ if (!ret) {
+ proc_list_lock();
+ memorystatus_jetsam_snapshot_last_timestamp = timestamp_now;
+ proc_list_unlock();
+ }
+ } else {
+ proc_list_unlock();
+ }
+ }
+
+ KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_SCAN) | DBG_FUNC_END,
+ MEMORYSTATUS_LOG_AVAILABLE_PAGES, total_memory_reclaimed, 0, 0, 0);
+
+ memorystatus_thread_block(0, memorystatus_thread);
+}
+
+/*
+ * Returns TRUE:
+ * when an idle-exitable proc was killed
+ * Returns FALSE:
+ * when there are no more idle-exitable procs found
+ * when the attempt to kill an idle-exitable proc failed
+ */
+boolean_t
+memorystatus_idle_exit_from_VM(void)
+{
+ /*
+ * This routine should no longer be needed since we are
+ * now using jetsam bands on all platforms and so will deal
+ * with IDLE processes within the memorystatus thread itself.
+ *
+ * But we still use it because we observed that macos systems
+ * started heavy compression/swapping with a bunch of
+ * idle-exitable processes alive and doing nothing. We decided
+ * to rather kill those processes than start swapping earlier.
+ */
+
+ return kill_idle_exit_proc();
+}
+
+/*
+ * Callback invoked when allowable physical memory footprint exceeded
+ * (dirty pages + IOKit mappings)
+ *
+ * This is invoked for both advisory, non-fatal per-task high watermarks,
+ * as well as the fatal task memory limits.
+ */
+void
+memorystatus_on_ledger_footprint_exceeded(boolean_t warning, boolean_t memlimit_is_active, boolean_t memlimit_is_fatal)
+{
+ os_reason_t jetsam_reason = OS_REASON_NULL;
+
+ proc_t p = current_proc();
+
+#if VM_PRESSURE_EVENTS
+ if (warning == TRUE) {
+ /*
+ * This is a warning path which implies that the current process is close, but has
+ * not yet exceeded its per-process memory limit.
+ */
+ if (memorystatus_warn_process(p, memlimit_is_active, memlimit_is_fatal, FALSE /* not exceeded */) != TRUE) {
+ /* Print warning, since it's possible that task has not registered for pressure notifications */
+ os_log(OS_LOG_DEFAULT, "memorystatus_on_ledger_footprint_exceeded: failed to warn the current task (%d exiting, or no handler registered?).\n", p->p_pid);
+ }
+ return;
+ }
+#endif /* VM_PRESSURE_EVENTS */
+
+ if (memlimit_is_fatal) {
+ /*
+ * If this process has no high watermark or has a fatal task limit, then we have been invoked because the task
+ * has violated either the system-wide per-task memory limit OR its own task limit.
+ */
+ jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_MEMORY_PERPROCESSLIMIT);
+ if (jetsam_reason == NULL) {
+ printf("task_exceeded footprint: failed to allocate jetsam reason\n");
+ } else if (corpse_for_fatal_memkill != 0 && proc_send_synchronous_EXC_RESOURCE(p) == FALSE) {
+ /* Set OS_REASON_FLAG_GENERATE_CRASH_REPORT to generate corpse */
+ jetsam_reason->osr_flags |= OS_REASON_FLAG_GENERATE_CRASH_REPORT;
+ }
+
+ if (memorystatus_kill_process_sync(p->p_pid, kMemorystatusKilledPerProcessLimit, jetsam_reason) != TRUE) {
+ printf("task_exceeded_footprint: failed to kill the current task (exiting?).\n");
+ }
+ } else {
+ /*
+ * HWM offender exists. Done without locks or synchronization.
+ * See comment near its declaration for more details.
+ */
+ memorystatus_hwm_candidates = TRUE;
+
+#if VM_PRESSURE_EVENTS
+ /*
+ * The current process is not in the warning path.
+ * This path implies the current process has exceeded a non-fatal (soft) memory limit.
+ * Failure to send note is ignored here.
+ */
+ (void)memorystatus_warn_process(p, memlimit_is_active, memlimit_is_fatal, TRUE /* exceeded */);
+
+#endif /* VM_PRESSURE_EVENTS */
+ }
+}
+
+void
+memorystatus_log_exception(const int max_footprint_mb, boolean_t memlimit_is_active, boolean_t memlimit_is_fatal)
+{
+ proc_t p = current_proc();
+
+ /*
+ * The limit violation is logged here, but only once per process per limit.
+ * Soft memory limit is a non-fatal high-water-mark
+ * Hard memory limit is a fatal custom-task-limit or system-wide per-task memory limit.
+ */
+
+ os_log_with_startup_serial(OS_LOG_DEFAULT, "EXC_RESOURCE -> %s[%d] exceeded mem limit: %s%s %d MB (%s)\n",
+ ((p && *p->p_name) ? p->p_name : "unknown"), (p ? p->p_pid : -1), (memlimit_is_active ? "Active" : "Inactive"),
+ (memlimit_is_fatal ? "Hard" : "Soft"), max_footprint_mb,
+ (memlimit_is_fatal ? "fatal" : "non-fatal"));
+
+ return;
+}
+
+
+/*
+ * Description:
+ * Evaluates process state to determine which limit
+ * should be applied (active vs. inactive limit).
+ *
+ * Processes that have the 'elevated inactive jetsam band' attribute
+ * are first evaluated based on their current priority band.
+ * presently elevated ==> active
+ *
+ * Processes that opt into dirty tracking are evaluated
+ * based on clean vs dirty state.
+ * dirty ==> active
+ * clean ==> inactive
+ *
+ * Process that do not opt into dirty tracking are
+ * evalulated based on priority level.
+ * Foreground or above ==> active
+ * Below Foreground ==> inactive
+ *
+ * Return: TRUE if active
+ * False if inactive
+ */
+
+static boolean_t
+proc_jetsam_state_is_active_locked(proc_t p)
+{
+ if ((p->p_memstat_state & P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND) &&
+ (p->p_memstat_effectivepriority == JETSAM_PRIORITY_ELEVATED_INACTIVE)) {
+ /*
+ * process has the 'elevated inactive jetsam band' attribute
+ * and process is present in the elevated band
+ * implies active state
+ */
+ return TRUE;
+ } else if (p->p_memstat_dirty & P_DIRTY_TRACK) {
+ /*
+ * process has opted into dirty tracking
+ * active state is based on dirty vs. clean
+ */
+ if (p->p_memstat_dirty & P_DIRTY_IS_DIRTY) {
+ /*
+ * process is dirty
+ * implies active state
+ */
+ return TRUE;
+ } else {
+ /*
+ * process is clean
+ * implies inactive state
+ */
+ return FALSE;
+ }
+ } else if (p->p_memstat_effectivepriority >= JETSAM_PRIORITY_FOREGROUND) {
+ /*
+ * process is Foreground or higher
+ * implies active state
+ */
+ return TRUE;
+ } else {
+ /*
+ * process found below Foreground
+ * implies inactive state
+ */
+ return FALSE;
+ }
+}
+
+static boolean_t
+memorystatus_kill_process_sync(pid_t victim_pid, uint32_t cause, os_reason_t jetsam_reason)
+{
+ boolean_t res;
+
+ uint32_t errors = 0;
+ uint64_t memory_reclaimed = 0;
+
+ if (victim_pid == -1) {
+ /* No pid, so kill first process */
+ res = memorystatus_kill_top_process(TRUE, TRUE, cause, jetsam_reason, NULL, &errors, &memory_reclaimed);
+ } else {
+ res = memorystatus_kill_specific_process(victim_pid, cause, jetsam_reason);
+ }
+
+ if (errors) {
+ memorystatus_clear_errors();
+ }
+
+ if (res == TRUE) {
+ /* Fire off snapshot notification */
+ proc_list_lock();
+ size_t snapshot_size = sizeof(memorystatus_jetsam_snapshot_t) +
+ sizeof(memorystatus_jetsam_snapshot_entry_t) * memorystatus_jetsam_snapshot_count;
+ uint64_t timestamp_now = mach_absolute_time();
+ memorystatus_jetsam_snapshot->notification_time = timestamp_now;
+ if (memorystatus_jetsam_snapshot_count > 0 && (memorystatus_jetsam_snapshot_last_timestamp == 0 ||
+ timestamp_now > memorystatus_jetsam_snapshot_last_timestamp + memorystatus_jetsam_snapshot_timeout)) {
+ proc_list_unlock();
+ int ret = memorystatus_send_note(kMemorystatusSnapshotNote, &snapshot_size, sizeof(snapshot_size));
+ if (!ret) {
+ proc_list_lock();
+ memorystatus_jetsam_snapshot_last_timestamp = timestamp_now;
+ proc_list_unlock();
+ }
+ } else {
+ proc_list_unlock();
+ }
+ }
+
+ return res;
+}
+
+/*
+ * Jetsam a specific process.
+ */
+static boolean_t
+memorystatus_kill_specific_process(pid_t victim_pid, uint32_t cause, os_reason_t jetsam_reason)
+{
+ boolean_t killed;
+ proc_t p;
+ uint64_t killtime = 0;
+ uint64_t footprint_of_killed_proc;
+ clock_sec_t tv_sec;
+ clock_usec_t tv_usec;
+ uint32_t tv_msec;
+
+ /* TODO - add a victim queue and push this into the main jetsam thread */
+
+ p = proc_find(victim_pid);
+ if (!p) {
+ os_reason_free(jetsam_reason);
+ return FALSE;
+ }
+
+ proc_list_lock();
+
+ if (memorystatus_jetsam_snapshot_count == 0) {
+ memorystatus_init_jetsam_snapshot_locked(NULL, 0);
+ }
+
+ killtime = mach_absolute_time();
+ absolutetime_to_microtime(killtime, &tv_sec, &tv_usec);
+ tv_msec = tv_usec / 1000;
+
+ memorystatus_update_jetsam_snapshot_entry_locked(p, cause, killtime);
+
+ proc_list_unlock();
+
+ killed = memorystatus_do_kill(p, cause, jetsam_reason, &footprint_of_killed_proc);
+
+ os_log_with_startup_serial(OS_LOG_DEFAULT, "%lu.%03d memorystatus: killing_specific_process pid %d [%s] (%s %d) %lluKB - memorystatus_available_pages: %llu\n",
+ (unsigned long)tv_sec, tv_msec, victim_pid, ((p && *p->p_name) ? p->p_name : "unknown"),
+ memorystatus_kill_cause_name[cause], (p ? p->p_memstat_effectivepriority: -1),
+ footprint_of_killed_proc >> 10, (uint64_t)MEMORYSTATUS_LOG_AVAILABLE_PAGES);
+
+ proc_rele(p);
+
+ return killed;
+}
+
+
+/*
+ * Toggle the P_MEMSTAT_TERMINATED state.
+ * Takes the proc_list_lock.
+ */
+void
+proc_memstat_terminated(proc_t p, boolean_t set)
+{
+#if DEVELOPMENT || DEBUG
+ if (p) {
+ proc_list_lock();
+ if (set == TRUE) {
+ p->p_memstat_state |= P_MEMSTAT_TERMINATED;
+ } else {
+ p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
+ }
+ proc_list_unlock();
+ }
+#else
+#pragma unused(p, set)
+ /*
+ * do nothing
+ */
+#endif /* DEVELOPMENT || DEBUG */
+ return;
+}
+
+
+#if CONFIG_JETSAM
+/*
+ * This is invoked when cpulimits have been exceeded while in fatal mode.
+ * The jetsam_flags do not apply as those are for memory related kills.
+ * We call this routine so that the offending process is killed with
+ * a non-zero exit status.
+ */
+void
+jetsam_on_ledger_cpulimit_exceeded(void)
+{
+ int retval = 0;
+ int jetsam_flags = 0; /* make it obvious */
+ proc_t p = current_proc();
+ os_reason_t jetsam_reason = OS_REASON_NULL;
+
+ printf("task_exceeded_cpulimit: killing pid %d [%s]\n",
+ p->p_pid, (*p->p_name ? p->p_name : "(unknown)"));
+
+ jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_CPULIMIT);
+ if (jetsam_reason == OS_REASON_NULL) {
+ printf("task_exceeded_cpulimit: unable to allocate memory for jetsam reason\n");
+ }
+
+ retval = jetsam_do_kill(p, jetsam_flags, jetsam_reason);
+
+ if (retval) {
+ printf("task_exceeded_cpulimit: failed to kill current task (exiting?).\n");
+ }
+}
+
+#endif /* CONFIG_JETSAM */
+
+static void
+memorystatus_get_task_memory_region_count(task_t task, uint64_t *count)
+{
+ assert(task);
+ assert(count);
+
+ *count = get_task_memory_region_count(task);
+}
+
+
+#define MEMORYSTATUS_VM_MAP_FORK_ALLOWED 0x100000000
+#define MEMORYSTATUS_VM_MAP_FORK_NOT_ALLOWED 0x200000000
+
+#if DEVELOPMENT || DEBUG
+
+/*
+ * Sysctl only used to test memorystatus_allowed_vm_map_fork() path.
+ * set a new pidwatch value
+ * or
+ * get the current pidwatch value
+ *
+ * The pidwatch_val starts out with a PID to watch for in the map_fork path.
+ * Its value is:
+ * - OR'd with MEMORYSTATUS_VM_MAP_FORK_ALLOWED if we allow the map_fork.
+ * - OR'd with MEMORYSTATUS_VM_MAP_FORK_NOT_ALLOWED if we disallow the map_fork.
+ * - set to -1ull if the map_fork() is aborted for other reasons.
+ */
+
+uint64_t memorystatus_vm_map_fork_pidwatch_val = 0;
+
+static int sysctl_memorystatus_vm_map_fork_pidwatch SYSCTL_HANDLER_ARGS {
+#pragma unused(oidp, arg1, arg2)
+
+ uint64_t new_value = 0;
+ uint64_t old_value = 0;
+ int error = 0;
+
+ /*
+ * The pid is held in the low 32 bits.
+ * The 'allowed' flags are in the upper 32 bits.
+ */
+ old_value = memorystatus_vm_map_fork_pidwatch_val;
+
+ error = sysctl_io_number(req, old_value, sizeof(old_value), &new_value, NULL);
+
+ if (error || !req->newptr) {
+ /*
+ * No new value passed in.
+ */
+ return error;
+ }
+
+ /*
+ * A new pid was passed in via req->newptr.
+ * Ignore any attempt to set the higher order bits.
+ */
+ memorystatus_vm_map_fork_pidwatch_val = new_value & 0xFFFFFFFF;
+ printf("memorystatus: pidwatch old_value = 0x%llx, new_value = 0x%llx \n", old_value, new_value);
+
+ return error;
+}
+
+SYSCTL_PROC(_kern, OID_AUTO, memorystatus_vm_map_fork_pidwatch, CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_MASKED,
+ 0, 0, sysctl_memorystatus_vm_map_fork_pidwatch, "Q", "get/set pid watched for in vm_map_fork");
+
+
+/*
+ * Record if a watched process fails to qualify for a vm_map_fork().
+ */
+void
+memorystatus_abort_vm_map_fork(task_t task)
+{
+ if (memorystatus_vm_map_fork_pidwatch_val != 0) {
+ proc_t p = get_bsdtask_info(task);
+ if (p != NULL && memorystatus_vm_map_fork_pidwatch_val == (uint64_t)p->p_pid) {
+ memorystatus_vm_map_fork_pidwatch_val = -1ull;
+ }
+ }
+}
+
+static void
+set_vm_map_fork_pidwatch(task_t task, uint64_t x)
+{
+ if (memorystatus_vm_map_fork_pidwatch_val != 0) {
+ proc_t p = get_bsdtask_info(task);
+ if (p && (memorystatus_vm_map_fork_pidwatch_val == (uint64_t)p->p_pid)) {
+ memorystatus_vm_map_fork_pidwatch_val |= x;
+ }
+ }
+}
+
+#else /* DEVELOPMENT || DEBUG */
+
+
+static void
+set_vm_map_fork_pidwatch(task_t task, uint64_t x)
+{
+#pragma unused(task)
+#pragma unused(x)
+}
+
+#endif /* DEVELOPMENT || DEBUG */
+
+/*
+ * Called during EXC_RESOURCE handling when a process exceeds a soft
+ * memory limit. This is the corpse fork path and here we decide if
+ * vm_map_fork will be allowed when creating the corpse.
+ * The task being considered is suspended.
+ *
+ * By default, a vm_map_fork is allowed to proceed.
+ *
+ * A few simple policy assumptions:
+ * If the device has a zero system-wide task limit,
+ * then the vm_map_fork is allowed. macOS always has a zero
+ * system wide task limit (unless overriden by a boot-arg).
+ *
+ * And if a process's memory footprint calculates less
+ * than or equal to quarter of the system-wide task limit,
+ * then the vm_map_fork is allowed. This calculation
+ * is based on the assumption that a process can
+ * munch memory up to the system-wide task limit.
+ */
+extern boolean_t corpse_threshold_system_limit;
+boolean_t
+memorystatus_allowed_vm_map_fork(task_t task)
+{
+ boolean_t is_allowed = TRUE; /* default */
+
+ uint64_t footprint_in_bytes;
+ uint64_t max_allowed_bytes;
+
+ if (max_task_footprint_mb == 0) {
+ set_vm_map_fork_pidwatch(task, MEMORYSTATUS_VM_MAP_FORK_ALLOWED);
+ return is_allowed;
+ }
+
+ footprint_in_bytes = get_task_phys_footprint(task);
+
+ /*
+ * Maximum is 1/4 of the system-wide task limit by default.
+ */
+ max_allowed_bytes = ((uint64_t)max_task_footprint_mb * 1024 * 1024) >> 2;
+
+#if DEBUG || DEVELOPMENT
+ if (corpse_threshold_system_limit) {
+ max_allowed_bytes = (uint64_t)max_task_footprint_mb * (1UL << 20);
+ }
+#endif /* DEBUG || DEVELOPMENT */
+
+ if (footprint_in_bytes > max_allowed_bytes) {
+ printf("memorystatus disallowed vm_map_fork %lld %lld\n", footprint_in_bytes, max_allowed_bytes);
+ set_vm_map_fork_pidwatch(task, MEMORYSTATUS_VM_MAP_FORK_NOT_ALLOWED);
+ return !is_allowed;
+ }
+
+ set_vm_map_fork_pidwatch(task, MEMORYSTATUS_VM_MAP_FORK_ALLOWED);
+ return is_allowed;
+}
+
+void
+memorystatus_get_task_page_counts(task_t task, uint32_t *footprint, uint32_t *max_footprint_lifetime, uint32_t *purgeable_pages)
+{
+ assert(task);
+ assert(footprint);
+
+ uint64_t pages;
+
+ pages = (get_task_phys_footprint(task) / PAGE_SIZE_64);
+ assert(((uint32_t)pages) == pages);
+ *footprint = (uint32_t)pages;
+
+ if (max_footprint_lifetime) {
+ pages = (get_task_phys_footprint_lifetime_max(task) / PAGE_SIZE_64);
+ assert(((uint32_t)pages) == pages);
+ *max_footprint_lifetime = (uint32_t)pages;
+ }
+ if (purgeable_pages) {
+ pages = (get_task_purgeable_size(task) / PAGE_SIZE_64);
+ assert(((uint32_t)pages) == pages);
+ *purgeable_pages = (uint32_t)pages;
+ }
+}
+
+static void
+memorystatus_get_task_phys_footprint_page_counts(task_t task,
+ uint64_t *internal_pages, uint64_t *internal_compressed_pages,
+ uint64_t *purgeable_nonvolatile_pages, uint64_t *purgeable_nonvolatile_compressed_pages,
+ uint64_t *alternate_accounting_pages, uint64_t *alternate_accounting_compressed_pages,
+ uint64_t *iokit_mapped_pages, uint64_t *page_table_pages, uint64_t *frozen_to_swap_pages)
+{
+ assert(task);
+
+ if (internal_pages) {
+ *internal_pages = (get_task_internal(task) / PAGE_SIZE_64);
+ }
+
+ if (internal_compressed_pages) {
+ *internal_compressed_pages = (get_task_internal_compressed(task) / PAGE_SIZE_64);
+ }
+
+ if (purgeable_nonvolatile_pages) {
+ *purgeable_nonvolatile_pages = (get_task_purgeable_nonvolatile(task) / PAGE_SIZE_64);
+ }
+
+ if (purgeable_nonvolatile_compressed_pages) {
+ *purgeable_nonvolatile_compressed_pages = (get_task_purgeable_nonvolatile_compressed(task) / PAGE_SIZE_64);
+ }
+
+ if (alternate_accounting_pages) {
+ *alternate_accounting_pages = (get_task_alternate_accounting(task) / PAGE_SIZE_64);
+ }
+
+ if (alternate_accounting_compressed_pages) {
+ *alternate_accounting_compressed_pages = (get_task_alternate_accounting_compressed(task) / PAGE_SIZE_64);
+ }
+
+ if (iokit_mapped_pages) {
+ *iokit_mapped_pages = (get_task_iokit_mapped(task) / PAGE_SIZE_64);
+ }
+
+ if (page_table_pages) {
+ *page_table_pages = (get_task_page_table(task) / PAGE_SIZE_64);
+ }
+
+#if CONFIG_FREEZE
+ if (frozen_to_swap_pages) {
+ *frozen_to_swap_pages = (get_task_frozen_to_swap(task) / PAGE_SIZE_64);
+ }
+#else /* CONFIG_FREEZE */
+#pragma unused(frozen_to_swap_pages)
+#endif /* CONFIG_FREEZE */
+}
+
+#if CONFIG_FREEZE
+/*
+ * Copies the source entry into the destination snapshot.
+ * Returns true on success. Fails if the destination snapshot is full.
+ * Caller must hold the proc list lock.
+ */
+static bool
+memorystatus_jetsam_snapshot_copy_entry_locked(memorystatus_jetsam_snapshot_t *dst_snapshot, unsigned int dst_snapshot_size, const memorystatus_jetsam_snapshot_entry_t *src_entry)
+{
+ LCK_MTX_ASSERT(proc_list_mlock, LCK_MTX_ASSERT_OWNED);
+ assert(dst_snapshot);
+
+ if (dst_snapshot->entry_count == dst_snapshot_size) {
+ /* Destination snapshot is full. Can not be updated until it is consumed. */
+ return false;
+ }
+ if (dst_snapshot->entry_count == 0) {
+ memorystatus_init_jetsam_snapshot_header(dst_snapshot);
+ }
+ memorystatus_jetsam_snapshot_entry_t *dst_entry = &dst_snapshot->entries[dst_snapshot->entry_count++];
+ memcpy(dst_entry, src_entry, sizeof(memorystatus_jetsam_snapshot_entry_t));
+ return true;
+}
+#endif /* CONFIG_FREEZE */
+
+static bool
+memorystatus_init_jetsam_snapshot_entry_with_kill_locked(memorystatus_jetsam_snapshot_t *snapshot, proc_t p, uint32_t kill_cause, uint64_t killtime, memorystatus_jetsam_snapshot_entry_t **entry)
+{
+ LCK_MTX_ASSERT(proc_list_mlock, LCK_MTX_ASSERT_OWNED);
+ memorystatus_jetsam_snapshot_entry_t *snapshot_list = snapshot->entries;
+ size_t i = snapshot->entry_count;
+
+ if (memorystatus_init_jetsam_snapshot_entry_locked(p, &snapshot_list[i], (snapshot->js_gencount)) == TRUE) {
+ *entry = &snapshot_list[i];
+ (*entry)->killed = kill_cause;
+ (*entry)->jse_killtime = killtime;
+
+ snapshot->entry_count = i + 1;
+ return true;
+ }
+ return false;
+}
+
+/*
+ * This routine only acts on the global jetsam event snapshot.
+ * Updating the process's entry can race when the memorystatus_thread
+ * has chosen to kill a process that is racing to exit on another core.
+ */
+static void
+memorystatus_update_jetsam_snapshot_entry_locked(proc_t p, uint32_t kill_cause, uint64_t killtime)
+{
+ memorystatus_jetsam_snapshot_entry_t *entry = NULL;
+ memorystatus_jetsam_snapshot_t *snapshot = NULL;
+ memorystatus_jetsam_snapshot_entry_t *snapshot_list = NULL;
+
+ unsigned int i;
+#if CONFIG_FREEZE
+ bool copied_to_freezer_snapshot = false;
+#endif /* CONFIG_FREEZE */
+
+ LCK_MTX_ASSERT(proc_list_mlock, LCK_MTX_ASSERT_OWNED);
+
+ if (memorystatus_jetsam_snapshot_count == 0) {
+ /*
+ * No active snapshot.
+ * Nothing to do.
+ */
+ goto exit;
+ }
+
+ /*
+ * Sanity check as this routine should only be called
+ * from a jetsam kill path.
+ */
+ assert(kill_cause != 0 && killtime != 0);
+
+ snapshot = memorystatus_jetsam_snapshot;
+ snapshot_list = memorystatus_jetsam_snapshot->entries;
+
+ for (i = 0; i < memorystatus_jetsam_snapshot_count; i++) {
+ if (snapshot_list[i].pid == p->p_pid) {
+ entry = &snapshot_list[i];
+
+ if (entry->killed || entry->jse_killtime) {
+ /*
+ * We apparently raced on the exit path
+ * for this process, as it's snapshot entry
+ * has already recorded a kill.
+ */
+ assert(entry->killed && entry->jse_killtime);
+ break;
+ }
+
+ /*
+ * Update the entry we just found in the snapshot.
+ */
+
+ entry->killed = kill_cause;
+ entry->jse_killtime = killtime;
+ entry->jse_gencount = snapshot->js_gencount;
+ entry->jse_idle_delta = p->p_memstat_idle_delta;
+#if CONFIG_FREEZE
+ entry->jse_thaw_count = p->p_memstat_thaw_count;
+ entry->jse_freeze_skip_reason = p->p_memstat_freeze_skip_reason;
+#else /* CONFIG_FREEZE */
+ entry->jse_thaw_count = 0;
+ entry->jse_freeze_skip_reason = kMemorystatusFreezeSkipReasonNone;
+#endif /* CONFIG_FREEZE */
+
+ /*
+ * If a process has moved between bands since snapshot was
+ * initialized, then likely these fields changed too.
+ */
+ if (entry->priority != p->p_memstat_effectivepriority) {
+ strlcpy(entry->name, p->p_name, sizeof(entry->name));
+ entry->priority = p->p_memstat_effectivepriority;
+ entry->state = memorystatus_build_state(p);
+ entry->user_data = p->p_memstat_userdata;
+ entry->fds = p->p_fd->fd_nfiles;
+ }
+
+ /*
+ * Always update the page counts on a kill.
+ */
+
+ uint32_t pages = 0;
+ uint32_t max_pages_lifetime = 0;
+ uint32_t purgeable_pages = 0;
+
+ memorystatus_get_task_page_counts(p->task, &pages, &max_pages_lifetime, &purgeable_pages);
+ entry->pages = (uint64_t)pages;
+ entry->max_pages_lifetime = (uint64_t)max_pages_lifetime;
+ entry->purgeable_pages = (uint64_t)purgeable_pages;
+
+ uint64_t internal_pages = 0;
+ uint64_t internal_compressed_pages = 0;
+ uint64_t purgeable_nonvolatile_pages = 0;
+ uint64_t purgeable_nonvolatile_compressed_pages = 0;
+ uint64_t alternate_accounting_pages = 0;
+ uint64_t alternate_accounting_compressed_pages = 0;
+ uint64_t iokit_mapped_pages = 0;
+ uint64_t page_table_pages = 0;
+ uint64_t frozen_to_swap_pages = 0;
+
+ memorystatus_get_task_phys_footprint_page_counts(p->task, &internal_pages, &internal_compressed_pages,
+ &purgeable_nonvolatile_pages, &purgeable_nonvolatile_compressed_pages,
+ &alternate_accounting_pages, &alternate_accounting_compressed_pages,
+ &iokit_mapped_pages, &page_table_pages, &frozen_to_swap_pages);
+
+ entry->jse_internal_pages = internal_pages;
+ entry->jse_internal_compressed_pages = internal_compressed_pages;
+ entry->jse_purgeable_nonvolatile_pages = purgeable_nonvolatile_pages;
+ entry->jse_purgeable_nonvolatile_compressed_pages = purgeable_nonvolatile_compressed_pages;
+ entry->jse_alternate_accounting_pages = alternate_accounting_pages;
+ entry->jse_alternate_accounting_compressed_pages = alternate_accounting_compressed_pages;
+ entry->jse_iokit_mapped_pages = iokit_mapped_pages;
+ entry->jse_page_table_pages = page_table_pages;
+ entry->jse_frozen_to_swap_pages = frozen_to_swap_pages;
+
+ uint64_t region_count = 0;
+ memorystatus_get_task_memory_region_count(p->task, ®ion_count);
+ entry->jse_memory_region_count = region_count;
+
+ goto exit;
+ }
+ }
+
+ if (entry == NULL) {
+ /*
+ * The entry was not found in the snapshot, so the process must have
+ * launched after the snapshot was initialized.
+ * Let's try to append the new entry.
+ */
+ if (memorystatus_jetsam_snapshot_count < memorystatus_jetsam_snapshot_max) {
+ /*
+ * A populated snapshot buffer exists
+ * and there is room to init a new entry.
+ */
+ assert(memorystatus_jetsam_snapshot_count == snapshot->entry_count);
+
+ if (memorystatus_init_jetsam_snapshot_entry_with_kill_locked(snapshot, p, kill_cause, killtime, &entry)) {
+ memorystatus_jetsam_snapshot_count++;
+
+ if (memorystatus_jetsam_snapshot_count >= memorystatus_jetsam_snapshot_max) {
+ /*
+ * We just used the last slot in the snapshot buffer.
+ * We only want to log it once... so we do it here
+ * when we notice we've hit the max.
+ */
+ printf("memorystatus: WARNING snapshot buffer is full, count %d\n",
+ memorystatus_jetsam_snapshot_count);
+ }
+ }
+ }
+ }
+
+exit:
+ if (entry) {
+#if CONFIG_FREEZE
+ if (memorystatus_jetsam_use_freezer_snapshot && isApp(p)) {
+ /* This is an app kill. Record it in the freezer snapshot so dasd can incorporate this in its recommendations. */
+ copied_to_freezer_snapshot = memorystatus_jetsam_snapshot_copy_entry_locked(memorystatus_jetsam_snapshot_freezer, memorystatus_jetsam_snapshot_freezer_max, entry);
+ if (copied_to_freezer_snapshot && memorystatus_jetsam_snapshot_freezer->entry_count == memorystatus_jetsam_snapshot_freezer_max) {
+ /*
+ * We just used the last slot in the freezer snapshot buffer.
+ * We only want to log it once... so we do it here
+ * when we notice we've hit the max.
+ */
+ os_log_error(OS_LOG_DEFAULT, "memorystatus: WARNING freezer snapshot buffer is full, count %zu",
+ memorystatus_jetsam_snapshot_freezer->entry_count);
+ }
+ }
+#endif /* CONFIG_FREEZE */
+ } else {
+ /*
+ * If we reach here, the snapshot buffer could not be updated.
+ * Most likely, the buffer is full, in which case we would have
+ * logged a warning in the previous call.
+ *
+ * For now, we will stop appending snapshot entries.
+ * When the buffer is consumed, the snapshot state will reset.
+ */
+
+ MEMORYSTATUS_DEBUG(4, "memorystatus_update_jetsam_snapshot_entry_locked: failed to update pid %d, priority %d, count %d\n",
+ p->p_pid, p->p_memstat_effectivepriority, memorystatus_jetsam_snapshot_count);
+
+#if CONFIG_FREEZE
+ /* We still attempt to record this in the freezer snapshot */
+ if (memorystatus_jetsam_use_freezer_snapshot && isApp(p)) {
+ snapshot = memorystatus_jetsam_snapshot_freezer;
+ if (snapshot->entry_count < memorystatus_jetsam_snapshot_freezer_max) {
+ copied_to_freezer_snapshot = memorystatus_init_jetsam_snapshot_entry_with_kill_locked(snapshot, p, kill_cause, killtime, &entry);
+ if (copied_to_freezer_snapshot && memorystatus_jetsam_snapshot_freezer->entry_count == memorystatus_jetsam_snapshot_freezer_max) {
+ /*
+ * We just used the last slot in the freezer snapshot buffer.
+ * We only want to log it once... so we do it here
+ * when we notice we've hit the max.
+ */
+ os_log_error(OS_LOG_DEFAULT, "memorystatus: WARNING freezer snapshot buffer is full, count %zu",
+ memorystatus_jetsam_snapshot_freezer->entry_count);
+ }
+ }
+ }
+#endif /* CONFIG_FREEZE */
+ }
+
+ return;
+}
+
+#if CONFIG_JETSAM
+void
+memorystatus_pages_update(unsigned int pages_avail)
+{
+ memorystatus_available_pages = pages_avail;
+
+#if VM_PRESSURE_EVENTS
+ /*
+ * Since memorystatus_available_pages changes, we should
+ * re-evaluate the pressure levels on the system and
+ * check if we need to wake the pressure thread.
+ * We also update memorystatus_level in that routine.
+ */
+ vm_pressure_response();
+
+ if (memorystatus_available_pages <= memorystatus_available_pages_pressure) {
+ if (memorystatus_hwm_candidates || (memorystatus_available_pages <= memorystatus_available_pages_critical)) {
+ memorystatus_thread_wake();
+ }
+ }
+#if CONFIG_FREEZE
+ /*
+ * We can't grab the freezer_mutex here even though that synchronization would be correct to inspect
+ * the # of frozen processes and wakeup the freezer thread. Reason being that we come here into this
+ * code with (possibly) the page-queue locks held and preemption disabled. So trying to grab a mutex here
+ * will result in the "mutex with preemption disabled" panic.
+ */
+
+ if (memorystatus_freeze_thread_should_run() == TRUE) {
+ /*
+ * The freezer thread is usually woken up by some user-space call i.e. pid_hibernate(any process).
+ * That trigger isn't invoked often enough and so we are enabling this explicit wakeup here.
+ */
+ if (VM_CONFIG_FREEZER_SWAP_IS_ACTIVE) {
+ thread_wakeup((event_t)&memorystatus_freeze_wakeup);
+ }
+ }
+#endif /* CONFIG_FREEZE */
+
+#else /* VM_PRESSURE_EVENTS */
+
+ boolean_t critical, delta;
+
+ if (!memorystatus_delta) {
+ return;
+ }
+
+ critical = (pages_avail < memorystatus_available_pages_critical) ? TRUE : FALSE;
+ delta = ((pages_avail >= (memorystatus_available_pages + memorystatus_delta))
+ || (memorystatus_available_pages >= (pages_avail + memorystatus_delta))) ? TRUE : FALSE;
+
+ if (critical || delta) {
+ unsigned int total_pages;
+
+ total_pages = (unsigned int) atop_64(max_mem);
+#if CONFIG_SECLUDED_MEMORY
+ total_pages -= vm_page_secluded_count;
+#endif /* CONFIG_SECLUDED_MEMORY */
+ memorystatus_level = memorystatus_available_pages * 100 / total_pages;
+ memorystatus_thread_wake();
+ }
+#endif /* VM_PRESSURE_EVENTS */
+}
+#endif /* CONFIG_JETSAM */
+
+static boolean_t
+memorystatus_init_jetsam_snapshot_entry_locked(proc_t p, memorystatus_jetsam_snapshot_entry_t *entry, uint64_t gencount)
+{
+ clock_sec_t tv_sec;
+ clock_usec_t tv_usec;
+ uint32_t pages = 0;
+ uint32_t max_pages_lifetime = 0;
+ uint32_t purgeable_pages = 0;
+ uint64_t internal_pages = 0;
+ uint64_t internal_compressed_pages = 0;
+ uint64_t purgeable_nonvolatile_pages = 0;
+ uint64_t purgeable_nonvolatile_compressed_pages = 0;
+ uint64_t alternate_accounting_pages = 0;
+ uint64_t alternate_accounting_compressed_pages = 0;
+ uint64_t iokit_mapped_pages = 0;
+ uint64_t page_table_pages = 0;
+ uint64_t frozen_to_swap_pages = 0;
+ uint64_t region_count = 0;
+ uint64_t cids[COALITION_NUM_TYPES];
+
+ memset(entry, 0, sizeof(memorystatus_jetsam_snapshot_entry_t));
+
+ entry->pid = p->p_pid;
+ strlcpy(&entry->name[0], p->p_name, sizeof(entry->name));
+ entry->priority = p->p_memstat_effectivepriority;
+
+ memorystatus_get_task_page_counts(p->task, &pages, &max_pages_lifetime, &purgeable_pages);
+ entry->pages = (uint64_t)pages;
+ entry->max_pages_lifetime = (uint64_t)max_pages_lifetime;
+ entry->purgeable_pages = (uint64_t)purgeable_pages;
+
+ memorystatus_get_task_phys_footprint_page_counts(p->task, &internal_pages, &internal_compressed_pages,
+ &purgeable_nonvolatile_pages, &purgeable_nonvolatile_compressed_pages,
+ &alternate_accounting_pages, &alternate_accounting_compressed_pages,
+ &iokit_mapped_pages, &page_table_pages, &frozen_to_swap_pages);
+
+ entry->jse_internal_pages = internal_pages;
+ entry->jse_internal_compressed_pages = internal_compressed_pages;
+ entry->jse_purgeable_nonvolatile_pages = purgeable_nonvolatile_pages;
+ entry->jse_purgeable_nonvolatile_compressed_pages = purgeable_nonvolatile_compressed_pages;
+ entry->jse_alternate_accounting_pages = alternate_accounting_pages;
+ entry->jse_alternate_accounting_compressed_pages = alternate_accounting_compressed_pages;
+ entry->jse_iokit_mapped_pages = iokit_mapped_pages;
+ entry->jse_page_table_pages = page_table_pages;
+ entry->jse_frozen_to_swap_pages = frozen_to_swap_pages;
+
+ memorystatus_get_task_memory_region_count(p->task, ®ion_count);
+ entry->jse_memory_region_count = region_count;
+
+ entry->state = memorystatus_build_state(p);
+ entry->user_data = p->p_memstat_userdata;
+ memcpy(&entry->uuid[0], &p->p_uuid[0], sizeof(p->p_uuid));
+ entry->fds = p->p_fd->fd_nfiles;
+
+ absolutetime_to_microtime(get_task_cpu_time(p->task), &tv_sec, &tv_usec);
+ entry->cpu_time.tv_sec = (int64_t)tv_sec;
+ entry->cpu_time.tv_usec = (int64_t)tv_usec;
+
+ assert(p->p_stats != NULL);
+ entry->jse_starttime = p->p_stats->ps_start; /* abstime process started */
+ entry->jse_killtime = 0; /* abstime jetsam chose to kill process */
+ entry->killed = 0; /* the jetsam kill cause */
+ entry->jse_gencount = gencount; /* indicates a pass through jetsam thread, when process was targeted to be killed */
+
+ entry->jse_idle_delta = p->p_memstat_idle_delta; /* Most recent timespan spent in idle-band */
+
+#if CONFIG_FREEZE
+ entry->jse_freeze_skip_reason = p->p_memstat_freeze_skip_reason;
+ entry->jse_thaw_count = p->p_memstat_thaw_count;
+#else /* CONFIG_FREEZE */
+ entry->jse_thaw_count = 0;
+ entry->jse_freeze_skip_reason = kMemorystatusFreezeSkipReasonNone;
+#endif /* CONFIG_FREEZE */
+
+ proc_coalitionids(p, cids);
+ entry->jse_coalition_jetsam_id = cids[COALITION_TYPE_JETSAM];
+
+ return TRUE;
+}
+
+static void
+memorystatus_init_snapshot_vmstats(memorystatus_jetsam_snapshot_t *snapshot)
+{
+ kern_return_t kr = KERN_SUCCESS;
+ mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
+ vm_statistics64_data_t vm_stat;
+
+ if ((kr = host_statistics64(host_self(), HOST_VM_INFO64, (host_info64_t)&vm_stat, &count)) != KERN_SUCCESS) {
+ printf("memorystatus_init_jetsam_snapshot_stats: host_statistics64 failed with %d\n", kr);
+ memset(&snapshot->stats, 0, sizeof(snapshot->stats));
+ } else {
+ snapshot->stats.free_pages = vm_stat.free_count;
+ snapshot->stats.active_pages = vm_stat.active_count;
+ snapshot->stats.inactive_pages = vm_stat.inactive_count;
+ snapshot->stats.throttled_pages = vm_stat.throttled_count;
+ snapshot->stats.purgeable_pages = vm_stat.purgeable_count;
+ snapshot->stats.wired_pages = vm_stat.wire_count;
+
+ snapshot->stats.speculative_pages = vm_stat.speculative_count;
+ snapshot->stats.filebacked_pages = vm_stat.external_page_count;
+ snapshot->stats.anonymous_pages = vm_stat.internal_page_count;
+ snapshot->stats.compressions = vm_stat.compressions;
+ snapshot->stats.decompressions = vm_stat.decompressions;
+ snapshot->stats.compressor_pages = vm_stat.compressor_page_count;
+ snapshot->stats.total_uncompressed_pages_in_compressor = vm_stat.total_uncompressed_pages_in_compressor;
+ }
+
+ get_zone_map_size(&snapshot->stats.zone_map_size, &snapshot->stats.zone_map_capacity);
+
+ bzero(snapshot->stats.largest_zone_name, sizeof(snapshot->stats.largest_zone_name));
+ get_largest_zone_info(snapshot->stats.largest_zone_name, sizeof(snapshot->stats.largest_zone_name),
+ &snapshot->stats.largest_zone_size);
+}
+
+/*
+ * Collect vm statistics at boot.
+ * Called only once (see kern_exec.c)
+ * Data can be consumed at any time.
+ */
+void
+memorystatus_init_at_boot_snapshot()
+{
+ memorystatus_init_snapshot_vmstats(&memorystatus_at_boot_snapshot);
+ memorystatus_at_boot_snapshot.entry_count = 0;
+ memorystatus_at_boot_snapshot.notification_time = 0; /* updated when consumed */
+ memorystatus_at_boot_snapshot.snapshot_time = mach_absolute_time();
+}
+
+static void
+memorystatus_init_jetsam_snapshot_header(memorystatus_jetsam_snapshot_t *snapshot)
+{
+ memorystatus_init_snapshot_vmstats(snapshot);
+ snapshot->snapshot_time = mach_absolute_time();
+ snapshot->notification_time = 0;
+ snapshot->js_gencount = 0;
+}
+
+static void
+memorystatus_init_jetsam_snapshot_locked(memorystatus_jetsam_snapshot_t *od_snapshot, uint32_t ods_list_count )
+{
+ proc_t p, next_p;
+ unsigned int b = 0, i = 0;
+
+ memorystatus_jetsam_snapshot_t *snapshot = NULL;
+ memorystatus_jetsam_snapshot_entry_t *snapshot_list = NULL;
+ unsigned int snapshot_max = 0;
+
+ LCK_MTX_ASSERT(proc_list_mlock, LCK_MTX_ASSERT_OWNED);
+
+ if (od_snapshot) {
+ /*
+ * This is an on_demand snapshot
+ */
+ snapshot = od_snapshot;
+ snapshot_list = od_snapshot->entries;
+ snapshot_max = ods_list_count;
+ } else {
+ /*
+ * This is a jetsam event snapshot
+ */
+ snapshot = memorystatus_jetsam_snapshot;
+ snapshot_list = memorystatus_jetsam_snapshot->entries;
+ snapshot_max = memorystatus_jetsam_snapshot_max;
+ }
+
+ memorystatus_init_jetsam_snapshot_header(snapshot);
+
+ next_p = memorystatus_get_first_proc_locked(&b, TRUE);
+ while (next_p) {
+ p = next_p;
+ next_p = memorystatus_get_next_proc_locked(&b, p, TRUE);
+
+ if (FALSE == memorystatus_init_jetsam_snapshot_entry_locked(p, &snapshot_list[i], snapshot->js_gencount)) {
+ continue;
+ }
+
+ MEMORYSTATUS_DEBUG(0, "jetsam snapshot pid %d, uuid = %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n",
+ p->p_pid,
+ p->p_uuid[0], p->p_uuid[1], p->p_uuid[2], p->p_uuid[3], p->p_uuid[4], p->p_uuid[5], p->p_uuid[6], p->p_uuid[7],
+ p->p_uuid[8], p->p_uuid[9], p->p_uuid[10], p->p_uuid[11], p->p_uuid[12], p->p_uuid[13], p->p_uuid[14], p->p_uuid[15]);
+
+ if (++i == snapshot_max) {
+ break;
+ }
+ }
+
+ snapshot->entry_count = i;
+
+ if (!od_snapshot) {
+ /* update the system buffer count */
+ memorystatus_jetsam_snapshot_count = i;
+ }
+}
+
+#if DEVELOPMENT || DEBUG
+
+#if CONFIG_JETSAM
+static int
+memorystatus_cmd_set_panic_bits(user_addr_t buffer, size_t buffer_size)
+{
+ int ret;
+ memorystatus_jetsam_panic_options_t debug;
+
+ if (buffer_size != sizeof(memorystatus_jetsam_panic_options_t)) {
+ return EINVAL;
+ }
+
+ ret = copyin(buffer, &debug, buffer_size);
+ if (ret) {
+ return ret;
+ }
+
+ /* Panic bits match kMemorystatusKilled* enum */
+ memorystatus_jetsam_panic_debug = (memorystatus_jetsam_panic_debug & ~debug.mask) | (debug.data & debug.mask);
+
+ /* Copyout new value */
+ debug.data = memorystatus_jetsam_panic_debug;
+ ret = copyout(&debug, buffer, sizeof(memorystatus_jetsam_panic_options_t));
+
+ return ret;
+}
+#endif /* CONFIG_JETSAM */
+
+/*
+ * Verify that the given bucket has been sorted correctly.
+ *
+ * Walks through the bucket and verifies that all pids in the
+ * expected_order buffer are in that bucket and in the same
+ * relative order.
+ *
+ * The proc_list_lock must be held by the caller.
+ */
+static int
+memorystatus_verify_sort_order(unsigned int bucket_index, pid_t *expected_order, size_t num_pids)
+{
+ LCK_MTX_ASSERT(proc_list_mlock, LCK_MTX_ASSERT_OWNED);
+
+ int error = 0;
+ proc_t p = NULL;
+ size_t i = 0;
+
+ /*
+ * NB: We allow other procs to be mixed in within the expected ones.
+ * We just need the expected procs to be in the right order relative to each other.
+ */
+ p = memorystatus_get_first_proc_locked(&bucket_index, FALSE);
+ while (p) {
+ if (p->p_pid == expected_order[i]) {
+ i++;
+ }
+ if (i == num_pids) {
+ break;
+ }
+ p = memorystatus_get_next_proc_locked(&bucket_index, p, FALSE);
+ }
+ if (i != num_pids) {
+ char buffer[128];
+ size_t len = sizeof(buffer);
+ size_t buffer_idx = 0;
+ os_log_error(OS_LOG_DEFAULT, "memorystatus_verify_sort_order: Processes in bucket %d were not sorted properly\n", bucket_index);
+ for (i = 0; i < num_pids; i++) {
+ int num_written = snprintf(buffer + buffer_idx, len - buffer_idx, "%d,", expected_order[i]);
+ if (num_written <= 0) {
+ break;
+ }
+ if (buffer_idx + (unsigned int) num_written >= len) {
+ break;
+ }
+ buffer_idx += num_written;
+ }
+ os_log_error(OS_LOG_DEFAULT, "memorystatus_verify_sort_order: Expected order [%s]", buffer);
+ memset(buffer, 0, len);
+ buffer_idx = 0;
+ p = memorystatus_get_first_proc_locked(&bucket_index, FALSE);
+ i = 0;
+ os_log_error(OS_LOG_DEFAULT, "memorystatus_verify_sort_order: Actual order:");
+ while (p) {
+ int num_written;
+ if (buffer_idx == 0) {
+ num_written = snprintf(buffer + buffer_idx, len - buffer_idx, "%zu: %d,", i, p->p_pid);
+ } else {
+ num_written = snprintf(buffer + buffer_idx, len - buffer_idx, "%d,", p->p_pid);
+ }
+ if (num_written <= 0) {
+ break;
+ }
+ buffer_idx += (unsigned int) num_written;
+ assert(buffer_idx <= len);
+ if (i % 10 == 0) {
+ os_log_error(OS_LOG_DEFAULT, "memorystatus_verify_sort_order: %s", buffer);
+ buffer_idx = 0;
+ }
+ p = memorystatus_get_next_proc_locked(&bucket_index, p, FALSE);
+ i++;
+ }
+ if (buffer_idx != 0) {
+ os_log_error(OS_LOG_DEFAULT, "memorystatus_verify_sort_order: %s", buffer);
+ }
+ error = EINVAL;
+ }
+ return error;
+}
+
+/*
+ * Triggers a sort_order on a specified jetsam priority band.
+ * This is for testing only, used to force a path through the sort
+ * function.
+ */
+static int
+memorystatus_cmd_test_jetsam_sort(int priority,
+ int sort_order,
+ user_addr_t expected_order_user,
+ size_t expected_order_user_len)
+{
+ int error = 0;
+ unsigned int bucket_index = 0;
+ static size_t kMaxPids = 8;
+ pid_t expected_order[kMaxPids];
+ size_t copy_size = sizeof(expected_order);
+ size_t num_pids;
+
+ if (expected_order_user_len < copy_size) {
+ copy_size = expected_order_user_len;
+ }
+ num_pids = copy_size / sizeof(pid_t);
+
+ error = copyin(expected_order_user, expected_order, copy_size);
+ if (error != 0) {
+ return error;
+ }
+
+ if (priority == -1) {
+ /* Use as shorthand for default priority */
+ bucket_index = JETSAM_PRIORITY_DEFAULT;
+ } else {
+ bucket_index = (unsigned int)priority;
+ }
+
+ /*
+ * Acquire lock before sorting so we can check the sort order
+ * while still holding the lock.
+ */
+ proc_list_lock();
+
+ memorystatus_sort_bucket_locked(bucket_index, sort_order);
+
+ if (expected_order_user != CAST_USER_ADDR_T(NULL) && expected_order_user_len > 0) {
+ error = memorystatus_verify_sort_order(bucket_index, expected_order, num_pids);
+ }
+
+ proc_list_unlock();
+
+ return error;
+}
+
+#endif /* DEVELOPMENT || DEBUG */
+
+/*
+ * Prepare the process to be killed (set state, update snapshot) and kill it.
+ */
+static uint64_t memorystatus_purge_before_jetsam_success = 0;
+
+static boolean_t
+memorystatus_kill_proc(proc_t p, uint32_t cause, os_reason_t jetsam_reason, boolean_t *killed, uint64_t *footprint_of_killed_proc)
+{
+ pid_t aPid = 0;
+ uint32_t aPid_ep = 0;
+
+ uint64_t killtime = 0;
+ clock_sec_t tv_sec;
+ clock_usec_t tv_usec;
+ uint32_t tv_msec;
+ boolean_t retval = FALSE;
+
+ aPid = p->p_pid;
+ aPid_ep = p->p_memstat_effectivepriority;
+
+ if (cause != kMemorystatusKilledVnodes && cause != kMemorystatusKilledZoneMapExhaustion) {
+ /*
+ * Genuine memory pressure and not other (vnode/zone) resource exhaustion.
+ */
+ boolean_t success = FALSE;
+ uint64_t num_pages_purged;
+ uint64_t num_pages_reclaimed = 0;
+ uint64_t num_pages_unsecluded = 0;
+
+ networking_memstatus_callout(p, cause);
+ num_pages_purged = vm_purgeable_purge_task_owned(p->task);
+ num_pages_reclaimed += num_pages_purged;
+#if CONFIG_SECLUDED_MEMORY
+ if (cause == kMemorystatusKilledVMPageShortage &&
+ vm_page_secluded_count > 0 &&
+ task_can_use_secluded_mem(p->task, FALSE)) {
+ /*
+ * We're about to kill a process that has access
+ * to the secluded pool. Drain that pool into the
+ * free or active queues to make these pages re-appear
+ * as "available", which might make us no longer need
+ * to kill that process.
+ * Since the secluded pool does not get refilled while
+ * a process has access to it, it should remain
+ * drained.
+ */
+ num_pages_unsecluded = vm_page_secluded_drain();
+ num_pages_reclaimed += num_pages_unsecluded;
+ }
+#endif /* CONFIG_SECLUDED_MEMORY */
+
+ if (num_pages_reclaimed) {
+ /*
+ * We actually reclaimed something and so let's
+ * check if we need to continue with the kill.
+ */
+ if (cause == kMemorystatusKilledHiwat) {
+ uint64_t footprint_in_bytes = get_task_phys_footprint(p->task);
+ uint64_t memlimit_in_bytes = (((uint64_t)p->p_memstat_memlimit) * 1024ULL * 1024ULL); /* convert MB to bytes */
+ success = (footprint_in_bytes <= memlimit_in_bytes);
+ } else {
+ success = (memorystatus_avail_pages_below_pressure() == FALSE);
+#if CONFIG_SECLUDED_MEMORY
+ if (!success && num_pages_unsecluded) {
+ /*
+ * We just drained the secluded pool
+ * because we're about to kill a
+ * process that has access to it.
+ * This is an important process and
+ * we'd rather not kill it unless
+ * absolutely necessary, so declare
+ * success even if draining the pool
+ * did not quite get us out of the
+ * "pressure" level but still got
+ * us out of the "critical" level.
+ */
+ success = (memorystatus_avail_pages_below_critical() == FALSE);
+ }
+#endif /* CONFIG_SECLUDED_MEMORY */
+ }
+
+ if (success) {
+ memorystatus_purge_before_jetsam_success++;
+
+ os_log_with_startup_serial(OS_LOG_DEFAULT, "memorystatus: reclaimed %llu pages (%llu purged, %llu unsecluded) from pid %d [%s] and avoided %s\n",
+ num_pages_reclaimed, num_pages_purged, num_pages_unsecluded, aPid, ((p && *p->p_name) ? p->p_name : "unknown"), memorystatus_kill_cause_name[cause]);
+
+ *killed = FALSE;
+
+ return TRUE;
+ }
+ }
+ }
+
+#if CONFIG_JETSAM && (DEVELOPMENT || DEBUG)
+ MEMORYSTATUS_DEBUG(1, "jetsam: killing pid %d [%s] - %lld Mb > 1 (%d Mb)\n",
+ aPid, (*p->p_name ? p->p_name : "unknown"),
+ (footprint_in_bytes / (1024ULL * 1024ULL)), /* converted bytes to MB */
+ p->p_memstat_memlimit);
+#endif /* CONFIG_JETSAM && (DEVELOPMENT || DEBUG) */
+
+ killtime = mach_absolute_time();
+ absolutetime_to_microtime(killtime, &tv_sec, &tv_usec);
+ tv_msec = tv_usec / 1000;
+
+ proc_list_lock();
+ memorystatus_update_jetsam_snapshot_entry_locked(p, cause, killtime);
+ proc_list_unlock();
+
+ char kill_reason_string[128];
+
+ if (cause == kMemorystatusKilledHiwat) {
+ strlcpy(kill_reason_string, "killing_highwater_process", 128);
+ } else {
+ if (aPid_ep == JETSAM_PRIORITY_IDLE) {
+ strlcpy(kill_reason_string, "killing_idle_process", 128);
+ } else {
+ strlcpy(kill_reason_string, "killing_top_process", 128);
+ }
+ }
+
+ /*
+ * memorystatus_do_kill drops a reference, so take another one so we can
+ * continue to use this exit reason even after memorystatus_do_kill()
+ * returns
+ */
+ os_reason_ref(jetsam_reason);
+
+ retval = memorystatus_do_kill(p, cause, jetsam_reason, footprint_of_killed_proc);
+ *killed = retval;
+
+ os_log_with_startup_serial(OS_LOG_DEFAULT, "%lu.%03d memorystatus: %s pid %d [%s] (%s %d) %lluKB - memorystatus_available_pages: %llu",
+ (unsigned long)tv_sec, tv_msec, kill_reason_string,
+ aPid, ((p && *p->p_name) ? p->p_name : "unknown"),
+ memorystatus_kill_cause_name[cause], aPid_ep,
+ (*footprint_of_killed_proc) >> 10, (uint64_t)MEMORYSTATUS_LOG_AVAILABLE_PAGES);
+
+ return retval;
+}
+
+/*
+ * Jetsam the first process in the queue.
+ */
+static boolean_t
+memorystatus_kill_top_process(boolean_t any, boolean_t sort_flag, uint32_t cause, os_reason_t jetsam_reason,
+ int32_t *priority, uint32_t *errors, uint64_t *memory_reclaimed)
+{
+ pid_t aPid;
+ proc_t p = PROC_NULL, next_p = PROC_NULL;
+ boolean_t new_snapshot = FALSE, force_new_snapshot = FALSE, killed = FALSE, freed_mem = FALSE;
+ unsigned int i = 0;
+ uint32_t aPid_ep;
+ int32_t local_max_kill_prio = JETSAM_PRIORITY_IDLE;
+ uint64_t footprint_of_killed_proc = 0;
+
+#ifndef CONFIG_FREEZE
+#pragma unused(any)
+#endif
+
+ KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_JETSAM) | DBG_FUNC_START,
+ MEMORYSTATUS_LOG_AVAILABLE_PAGES, 0, 0, 0, 0);
+
+
+#if CONFIG_JETSAM
+ if (sort_flag == TRUE) {
+ (void)memorystatus_sort_bucket(JETSAM_PRIORITY_FOREGROUND, JETSAM_SORT_DEFAULT);
+ }
+
+ local_max_kill_prio = max_kill_priority;
+
+ force_new_snapshot = FALSE;
+
+#else /* CONFIG_JETSAM */
+
+ if (sort_flag == TRUE) {
+ (void)memorystatus_sort_bucket(JETSAM_PRIORITY_IDLE, JETSAM_SORT_DEFAULT);
+ }
+
+ /*
+ * On macos, we currently only have 2 reasons to be here:
+ *
+ * kMemorystatusKilledZoneMapExhaustion
+ * AND
+ * kMemorystatusKilledVMCompressorSpaceShortage
+ *
+ * If we are here because of kMemorystatusKilledZoneMapExhaustion, we will consider
+ * any and all processes as eligible kill candidates since we need to avoid a panic.
+ *
+ * Since this function can be called async. it is harder to toggle the max_kill_priority
+ * value before and after a call. And so we use this local variable to set the upper band
+ * on the eligible kill bands.
+ */
+ if (cause == kMemorystatusKilledZoneMapExhaustion) {
+ local_max_kill_prio = JETSAM_PRIORITY_MAX;
+ } else {
+ local_max_kill_prio = max_kill_priority;
+ }
+
+ /*
+ * And, because we are here under extreme circumstances, we force a snapshot even for
+ * IDLE kills.
+ */
+ force_new_snapshot = TRUE;
+
+#endif /* CONFIG_JETSAM */
+
+ if (cause != kMemorystatusKilledZoneMapExhaustion &&
+ jetsam_current_thread() != NULL &&
+ jetsam_current_thread()->limit_to_low_bands &&
+ local_max_kill_prio > JETSAM_PRIORITY_BACKGROUND) {
+ local_max_kill_prio = JETSAM_PRIORITY_BACKGROUND;
+ }
+
+ proc_list_lock();
+
+ next_p = memorystatus_get_first_proc_locked(&i, TRUE);
+ while (next_p && (next_p->p_memstat_effectivepriority <= local_max_kill_prio)) {
+ p = next_p;
+ next_p = memorystatus_get_next_proc_locked(&i, p, TRUE);
+
+
+ aPid = p->p_pid;
+ aPid_ep = p->p_memstat_effectivepriority;
+
+ if (p->p_memstat_state & (P_MEMSTAT_ERROR | P_MEMSTAT_TERMINATED)) {
+ continue; /* with lock held */
+ }
+
+ if (cause == kMemorystatusKilledVnodes) {
+ /*
+ * If the system runs out of vnodes, we systematically jetsam
+ * processes in hopes of stumbling onto a vnode gain that helps
+ * the system recover. The process that happens to trigger
+ * this path has no known relationship to the vnode shortage.
+ * Deadlock avoidance: attempt to safeguard the caller.
+ */
+
+ if (p == current_proc()) {
+ /* do not jetsam the current process */
+ continue;
+ }
+ }
+
+#if CONFIG_FREEZE
+ boolean_t skip;
+ boolean_t reclaim_proc = !(p->p_memstat_state & P_MEMSTAT_LOCKED);
+ if (any || reclaim_proc) {
+ skip = FALSE;
+ } else {
+ skip = TRUE;
+ }
+
+ if (skip) {
+ continue;
+ } else
+#endif
+ {
+ if (proc_ref_locked(p) == p) {
+ /*
+ * Mark as terminated so that if exit1() indicates success, but the process (for example)
+ * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
+ * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
+ * acquisition of the proc lock.
+ */
+ p->p_memstat_state |= P_MEMSTAT_TERMINATED;
+ } else {
+ /*
+ * We need to restart the search again because
+ * proc_ref_locked _can_ drop the proc_list lock
+ * and we could have lost our stored next_p via
+ * an exit() on another core.
+ */
+ i = 0;
+ next_p = memorystatus_get_first_proc_locked(&i, TRUE);
+ continue;
+ }
+
+ /*
+ * Capture a snapshot if none exists and:
+ * - we are forcing a new snapshot creation, either because:
+ * - on a particular platform we need these snapshots every time, OR
+ * - a boot-arg/embedded device tree property has been set.
+ * - priority was not requested (this is something other than an ambient kill)
+ * - the priority was requested *and* the targeted process is not at idle priority
+ */
+ if ((memorystatus_jetsam_snapshot_count == 0) &&
+ (force_new_snapshot || memorystatus_idle_snapshot || ((!priority) || (priority && (aPid_ep != JETSAM_PRIORITY_IDLE))))) {
+ memorystatus_init_jetsam_snapshot_locked(NULL, 0);
+ new_snapshot = TRUE;
+ }
+
+ proc_list_unlock();
+
+ freed_mem = memorystatus_kill_proc(p, cause, jetsam_reason, &killed, &footprint_of_killed_proc); /* purged and/or killed 'p' */
+ /* Success? */
+ if (freed_mem) {
+ if (killed) {
+ *memory_reclaimed = footprint_of_killed_proc;
+ if (priority) {
+ *priority = aPid_ep;
+ }
+ } else {
+ /* purged */
+ proc_list_lock();
+ p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
+ proc_list_unlock();
+ }
+ proc_rele(p);
+ goto exit;
+ }
+
+ /*
+ * Failure - first unwind the state,
+ * then fall through to restart the search.
+ */
+ proc_list_lock();
+ proc_rele_locked(p);
+ p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
+ p->p_memstat_state |= P_MEMSTAT_ERROR;
+ *errors += 1;
+
+ i = 0;
+ next_p = memorystatus_get_first_proc_locked(&i, TRUE);
+ }
+ }
+
+ proc_list_unlock();
+
+exit:
+ os_reason_free(jetsam_reason);
+
+ if (!killed) {
+ *memory_reclaimed = 0;
+
+ /* Clear snapshot if freshly captured and no target was found */
+ if (new_snapshot) {
+ proc_list_lock();
+ memorystatus_jetsam_snapshot->entry_count = memorystatus_jetsam_snapshot_count = 0;
+ proc_list_unlock();
+ }
+ }
+
+ KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_JETSAM) | DBG_FUNC_END,
+ MEMORYSTATUS_LOG_AVAILABLE_PAGES, killed ? aPid : 0, killed, *memory_reclaimed, 0);
+
+ return killed;
+}
+
+/*
+ * Jetsam aggressively
+ */
+static boolean_t
+memorystatus_kill_processes_aggressive(uint32_t cause, int aggr_count,
+ int32_t priority_max, uint32_t *errors, uint64_t *memory_reclaimed)
+{
+ pid_t aPid;
+ proc_t p = PROC_NULL, next_p = PROC_NULL;
+ boolean_t new_snapshot = FALSE, killed = FALSE;
+ int kill_count = 0;
+ unsigned int i = 0;
+ int32_t aPid_ep = 0;
+ unsigned int memorystatus_level_snapshot = 0;
+ uint64_t killtime = 0;
+ clock_sec_t tv_sec;
+ clock_usec_t tv_usec;
+ uint32_t tv_msec;
+ os_reason_t jetsam_reason = OS_REASON_NULL;
+ uint64_t footprint_of_killed_proc = 0;
+
+ *memory_reclaimed = 0;
+
+ KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_JETSAM) | DBG_FUNC_START,
+ MEMORYSTATUS_LOG_AVAILABLE_PAGES, priority_max, 0, 0, 0);
+
+ if (priority_max >= JETSAM_PRIORITY_FOREGROUND) {
+ /*
+ * Check if aggressive jetsam has been asked to kill upto or beyond the
+ * JETSAM_PRIORITY_FOREGROUND bucket. If yes, sort the FG band based on
+ * coalition footprint.
+ */
+ memorystatus_sort_bucket(JETSAM_PRIORITY_FOREGROUND, JETSAM_SORT_DEFAULT);
+ }
+
+ jetsam_reason = os_reason_create(OS_REASON_JETSAM, cause);
+ if (jetsam_reason == OS_REASON_NULL) {
+ printf("memorystatus_kill_processes_aggressive: failed to allocate exit reason\n");
+ }
+
+ proc_list_lock();
+
+ next_p = memorystatus_get_first_proc_locked(&i, TRUE);
+ while (next_p) {
+ if (((next_p->p_listflag & P_LIST_EXITED) != 0) ||
+ ((unsigned int)(next_p->p_memstat_effectivepriority) != i)) {
+ /*
+ * We have raced with next_p running on another core.
+ * It may be exiting or it may have moved to a different
+ * jetsam priority band. This means we have lost our
+ * place in line while traversing the jetsam list. We
+ * attempt to recover by rewinding to the beginning of the band
+ * we were already traversing. By doing this, we do not guarantee
+ * that no process escapes this aggressive march, but we can make
+ * skipping an entire range of processes less likely. (PR-21069019)
+ */
+
+ MEMORYSTATUS_DEBUG(1, "memorystatus: aggressive%d: rewinding band %d, %s(%d) moved or exiting.\n",
+ aggr_count, i, (*next_p->p_name ? next_p->p_name : "unknown"), next_p->p_pid);
+
+ next_p = memorystatus_get_first_proc_locked(&i, TRUE);
+ continue;
+ }
+
+ p = next_p;
+ next_p = memorystatus_get_next_proc_locked(&i, p, TRUE);
+
+ if (p->p_memstat_effectivepriority > priority_max) {
+ /*
+ * Bail out of this killing spree if we have
+ * reached beyond the priority_max jetsam band.
+ * That is, we kill up to and through the
+ * priority_max jetsam band.
+ */
+ proc_list_unlock();
+ goto exit;
+ }
+
+ aPid = p->p_pid;
+ aPid_ep = p->p_memstat_effectivepriority;
+
+ if (p->p_memstat_state & (P_MEMSTAT_ERROR | P_MEMSTAT_TERMINATED)) {
+ continue;
+ }
+
+ /*
+ * Capture a snapshot if none exists.
+ */
+ if (memorystatus_jetsam_snapshot_count == 0) {
+ memorystatus_init_jetsam_snapshot_locked(NULL, 0);
+ new_snapshot = TRUE;
+ }
+
+ /*
+ * Mark as terminated so that if exit1() indicates success, but the process (for example)
+ * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
+ * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
+ * acquisition of the proc lock.
+ */
+ p->p_memstat_state |= P_MEMSTAT_TERMINATED;
+
+ killtime = mach_absolute_time();
+ absolutetime_to_microtime(killtime, &tv_sec, &tv_usec);
+ tv_msec = tv_usec / 1000;
+
+ /* Shift queue, update stats */
+ memorystatus_update_jetsam_snapshot_entry_locked(p, cause, killtime);
+
+ /*
+ * In order to kill the target process, we will drop the proc_list_lock.
+ * To guaranteee that p and next_p don't disappear out from under the lock,
+ * we must take a ref on both.
+ * If we cannot get a reference, then it's likely we've raced with
+ * that process exiting on another core.
+ */
+ if (proc_ref_locked(p) == p) {
+ if (next_p) {
+ while (next_p && (proc_ref_locked(next_p) != next_p)) {
+ proc_t temp_p;
+
+ /*
+ * We must have raced with next_p exiting on another core.
+ * Recover by getting the next eligible process in the band.
+ */
+
+ MEMORYSTATUS_DEBUG(1, "memorystatus: aggressive%d: skipping %d [%s] (exiting?)\n",
+ aggr_count, next_p->p_pid, (*next_p->p_name ? next_p->p_name : "(unknown)"));
+
+ temp_p = next_p;
+ next_p = memorystatus_get_next_proc_locked(&i, temp_p, TRUE);
+ }
+ }
+ proc_list_unlock();
+
+ printf("%lu.%03d memorystatus: %s%d pid %d [%s] (%s %d) - memorystatus_available_pages: %llu\n",
+ (unsigned long)tv_sec, tv_msec,
+ ((aPid_ep == JETSAM_PRIORITY_IDLE) ? "killing_idle_process_aggressive" : "killing_top_process_aggressive"),
+ aggr_count, aPid, (*p->p_name ? p->p_name : "unknown"),
+ memorystatus_kill_cause_name[cause], aPid_ep, (uint64_t)MEMORYSTATUS_LOG_AVAILABLE_PAGES);
+
+ memorystatus_level_snapshot = memorystatus_level;
+
+ /*
+ * memorystatus_do_kill() drops a reference, so take another one so we can
+ * continue to use this exit reason even after memorystatus_do_kill()
+ * returns.
+ */
+ os_reason_ref(jetsam_reason);
+ killed = memorystatus_do_kill(p, cause, jetsam_reason, &footprint_of_killed_proc);
+
+ /* Success? */
+ if (killed) {
+ *memory_reclaimed += footprint_of_killed_proc;
+ proc_rele(p);
+ kill_count++;
+ p = NULL;
+ killed = FALSE;
+
+ /*
+ * Continue the killing spree.
+ */
+ proc_list_lock();
+ if (next_p) {
+ proc_rele_locked(next_p);
+ }
+
+ if (aPid_ep == JETSAM_PRIORITY_FOREGROUND && memorystatus_aggressive_jetsam_lenient == TRUE) {
+ if (memorystatus_level > memorystatus_level_snapshot && ((memorystatus_level - memorystatus_level_snapshot) >= AGGRESSIVE_JETSAM_LENIENT_MODE_THRESHOLD)) {
+#if DEVELOPMENT || DEBUG
+ printf("Disabling Lenient mode after one-time deployment.\n");
+#endif /* DEVELOPMENT || DEBUG */
+ memorystatus_aggressive_jetsam_lenient = FALSE;
+ break;
+ }
+ }
+
+ continue;
+ }
+
+ /*
+ * Failure - first unwind the state,
+ * then fall through to restart the search.
+ */
+ proc_list_lock();
+ proc_rele_locked(p);
+ if (next_p) {
+ proc_rele_locked(next_p);
+ }
+ p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
+ p->p_memstat_state |= P_MEMSTAT_ERROR;
+ *errors += 1;
+ p = NULL;
+ }
+
+ /*
+ * Failure - restart the search at the beginning of
+ * the band we were already traversing.
+ *
+ * We might have raced with "p" exiting on another core, resulting in no
+ * ref on "p". Or, we may have failed to kill "p".
+ *
+ * Either way, we fall thru to here, leaving the proc in the
+ * P_MEMSTAT_TERMINATED or P_MEMSTAT_ERROR state.
+ *
+ * And, we hold the the proc_list_lock at this point.
+ */
+
+ next_p = memorystatus_get_first_proc_locked(&i, TRUE);
+ }
+
+ proc_list_unlock();
+
+exit:
+ os_reason_free(jetsam_reason);
+
+ /* Clear snapshot if freshly captured and no target was found */
+ if (new_snapshot && (kill_count == 0)) {
+ proc_list_lock();
+ memorystatus_jetsam_snapshot->entry_count = memorystatus_jetsam_snapshot_count = 0;
+ proc_list_unlock();
+ }
+
+ KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_JETSAM) | DBG_FUNC_END,
+ MEMORYSTATUS_LOG_AVAILABLE_PAGES, 0, kill_count, *memory_reclaimed, 0);
+
+ if (kill_count > 0) {
+ return TRUE;
+ } else {
+ return FALSE;
+ }
+}
+
+static boolean_t
+memorystatus_kill_hiwat_proc(uint32_t *errors, boolean_t *purged, uint64_t *memory_reclaimed)
+{
+ pid_t aPid = 0;
+ proc_t p = PROC_NULL, next_p = PROC_NULL;
+ boolean_t new_snapshot = FALSE, killed = FALSE, freed_mem = FALSE;
+ unsigned int i = 0;
+ uint32_t aPid_ep;
+ os_reason_t jetsam_reason = OS_REASON_NULL;
+ KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_JETSAM_HIWAT) | DBG_FUNC_START,
+ MEMORYSTATUS_LOG_AVAILABLE_PAGES, 0, 0, 0, 0);
+
+ jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_MEMORY_HIGHWATER);
+ if (jetsam_reason == OS_REASON_NULL) {
+ printf("memorystatus_kill_hiwat_proc: failed to allocate exit reason\n");
+ }
+
+ proc_list_lock();
+
+ next_p = memorystatus_get_first_proc_locked(&i, TRUE);
+ while (next_p) {
+ uint64_t footprint_in_bytes = 0;
+ uint64_t memlimit_in_bytes = 0;
+ boolean_t skip = 0;
+
+ p = next_p;
+ next_p = memorystatus_get_next_proc_locked(&i, p, TRUE);
+
+ aPid = p->p_pid;
+ aPid_ep = p->p_memstat_effectivepriority;
+
+ if (p->p_memstat_state & (P_MEMSTAT_ERROR | P_MEMSTAT_TERMINATED)) {
+ continue;
+ }
+
+ /* skip if no limit set */
+ if (p->p_memstat_memlimit <= 0) {
+ continue;
+ }
+
+ footprint_in_bytes = get_task_phys_footprint(p->task);
+ memlimit_in_bytes = (((uint64_t)p->p_memstat_memlimit) * 1024ULL * 1024ULL); /* convert MB to bytes */
+ skip = (footprint_in_bytes <= memlimit_in_bytes);
+
+#if CONFIG_FREEZE
+ if (!skip) {
+ if (p->p_memstat_state & P_MEMSTAT_LOCKED) {
+ skip = TRUE;
+ } else {
+ skip = FALSE;
+ }
+ }
+#endif
+
+ if (skip) {
+ continue;
+ } else {
+ if (memorystatus_jetsam_snapshot_count == 0) {
+ memorystatus_init_jetsam_snapshot_locked(NULL, 0);
+ new_snapshot = TRUE;
+ }
+
+ if (proc_ref_locked(p) == p) {
+ /*
+ * Mark as terminated so that if exit1() indicates success, but the process (for example)
+ * is blocked in task_exception_notify(), it'll be skipped if encountered again - see
+ * <rdar://problem/13553476>. This is cheaper than examining P_LEXIT, which requires the
+ * acquisition of the proc lock.
+ */
+ p->p_memstat_state |= P_MEMSTAT_TERMINATED;
+
+ proc_list_unlock();
+ } else {
+ /*
+ * We need to restart the search again because
+ * proc_ref_locked _can_ drop the proc_list lock
+ * and we could have lost our stored next_p via
+ * an exit() on another core.
+ */
+ i = 0;
+ next_p = memorystatus_get_first_proc_locked(&i, TRUE);
+ continue;
+ }
+
+ footprint_in_bytes = 0;
+ freed_mem = memorystatus_kill_proc(p, kMemorystatusKilledHiwat, jetsam_reason, &killed, &footprint_in_bytes); /* purged and/or killed 'p' */
+
+ /* Success? */
+ if (freed_mem) {
+ if (killed == FALSE) {
+ /* purged 'p'..don't reset HWM candidate count */
+ *purged = TRUE;
+
+ proc_list_lock();
+ p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
+ proc_list_unlock();
+ } else {
+ *memory_reclaimed = footprint_in_bytes;
+ }
+ proc_rele(p);
+ goto exit;
+ }
+ /*
+ * Failure - first unwind the state,
+ * then fall through to restart the search.
+ */
+ proc_list_lock();
+ proc_rele_locked(p);
+ p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
+ p->p_memstat_state |= P_MEMSTAT_ERROR;
+ *errors += 1;
+
+ i = 0;
+ next_p = memorystatus_get_first_proc_locked(&i, TRUE);
+ }
+ }
+
+ proc_list_unlock();
+
+exit:
+ os_reason_free(jetsam_reason);
+
+ if (!killed) {
+ *memory_reclaimed = 0;
+
+ /* Clear snapshot if freshly captured and no target was found */
+ if (new_snapshot) {
+ proc_list_lock();
+ memorystatus_jetsam_snapshot->entry_count = memorystatus_jetsam_snapshot_count = 0;
+ proc_list_unlock();
+ }
+ }
+
+ KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_JETSAM_HIWAT) | DBG_FUNC_END,
+ MEMORYSTATUS_LOG_AVAILABLE_PAGES, killed ? aPid : 0, killed, *memory_reclaimed, 0);
+
+ return killed;
+}
+
+/*
+ * Jetsam a process pinned in the elevated band.
+ *
+ * Return: true -- a pinned process was jetsammed
+ * false -- no pinned process was jetsammed
+ */
+boolean_t
+memorystatus_kill_elevated_process(uint32_t cause, os_reason_t jetsam_reason, unsigned int band, int aggr_count, uint32_t *errors, uint64_t *memory_reclaimed)
+{
+ pid_t aPid = 0;
+ proc_t p = PROC_NULL, next_p = PROC_NULL;
+ boolean_t new_snapshot = FALSE, killed = FALSE;
+ int kill_count = 0;
+ uint32_t aPid_ep;
+ uint64_t killtime = 0;
+ clock_sec_t tv_sec;
+ clock_usec_t tv_usec;
+ uint32_t tv_msec;
+ uint64_t footprint_of_killed_proc = 0;
+
+
+ KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_JETSAM) | DBG_FUNC_START,
+ MEMORYSTATUS_LOG_AVAILABLE_PAGES, 0, 0, 0, 0);
+
+#if CONFIG_FREEZE
+ boolean_t consider_frozen_only = FALSE;
+
+ if (band == (unsigned int) memorystatus_freeze_jetsam_band) {
+ consider_frozen_only = TRUE;
+ }
+#endif /* CONFIG_FREEZE */
+
+ proc_list_lock();
+
+ next_p = memorystatus_get_first_proc_locked(&band, FALSE);
+ while (next_p) {
+ p = next_p;
+ next_p = memorystatus_get_next_proc_locked(&band, p, FALSE);
+
+ aPid = p->p_pid;
+ aPid_ep = p->p_memstat_effectivepriority;
+
+ /*
+ * Only pick a process pinned in this elevated band
+ */
+ if (!(p->p_memstat_state & P_MEMSTAT_USE_ELEVATED_INACTIVE_BAND)) {
+ continue;
+ }
+
+ if (p->p_memstat_state & (P_MEMSTAT_ERROR | P_MEMSTAT_TERMINATED)) {
+ continue;
+ }
+
+#if CONFIG_FREEZE
+ if (consider_frozen_only && !(p->p_memstat_state & P_MEMSTAT_FROZEN)) {
+ continue;
+ }
+
+ if (p->p_memstat_state & P_MEMSTAT_LOCKED) {
+ continue;
+ }
+#endif /* CONFIG_FREEZE */
+
+#if DEVELOPMENT || DEBUG
+ MEMORYSTATUS_DEBUG(1, "jetsam: elevated%d process pid %d [%s] - memorystatus_available_pages: %d\n",
+ aggr_count,
+ aPid, (*p->p_name ? p->p_name : "unknown"),
+ MEMORYSTATUS_LOG_AVAILABLE_PAGES);
+#endif /* DEVELOPMENT || DEBUG */
+
+ if (memorystatus_jetsam_snapshot_count == 0) {
+ memorystatus_init_jetsam_snapshot_locked(NULL, 0);
+ new_snapshot = TRUE;
+ }
+
+ p->p_memstat_state |= P_MEMSTAT_TERMINATED;
+
+ killtime = mach_absolute_time();
+ absolutetime_to_microtime(killtime, &tv_sec, &tv_usec);
+ tv_msec = tv_usec / 1000;
+
+ memorystatus_update_jetsam_snapshot_entry_locked(p, cause, killtime);
+
+ if (proc_ref_locked(p) == p) {
+ proc_list_unlock();
+
+ /*
+ * memorystatus_do_kill drops a reference, so take another one so we can
+ * continue to use this exit reason even after memorystatus_do_kill()
+ * returns
+ */
+ os_reason_ref(jetsam_reason);
+ killed = memorystatus_do_kill(p, cause, jetsam_reason, &footprint_of_killed_proc);
+
+ os_log_with_startup_serial(OS_LOG_DEFAULT, "%lu.%03d memorystatus: killing_top_process_elevated%d pid %d [%s] (%s %d) %lluKB - memorystatus_available_pages: %llu\n",
+ (unsigned long)tv_sec, tv_msec,
+ aggr_count,
+ aPid, ((p && *p->p_name) ? p->p_name : "unknown"),
+ memorystatus_kill_cause_name[cause], aPid_ep,
+ footprint_of_killed_proc >> 10, (uint64_t)MEMORYSTATUS_LOG_AVAILABLE_PAGES);
+
+ /* Success? */
+ if (killed) {
+ *memory_reclaimed = footprint_of_killed_proc;
+ proc_rele(p);
+ kill_count++;
+ goto exit;
+ }
+
+ /*
+ * Failure - first unwind the state,
+ * then fall through to restart the search.
+ */
+ proc_list_lock();
+ proc_rele_locked(p);
+ p->p_memstat_state &= ~P_MEMSTAT_TERMINATED;
+ p->p_memstat_state |= P_MEMSTAT_ERROR;
+ *errors += 1;
+ }
+
+ /*
+ * Failure - restart the search.
+ *
+ * We might have raced with "p" exiting on another core, resulting in no
+ * ref on "p". Or, we may have failed to kill "p".
+ *
+ * Either way, we fall thru to here, leaving the proc in the
+ * P_MEMSTAT_TERMINATED state or P_MEMSTAT_ERROR state.
+ *
+ * And, we hold the the proc_list_lock at this point.
+ */
+
+ next_p = memorystatus_get_first_proc_locked(&band, FALSE);
+ }
+
+ proc_list_unlock();
+
+exit:
+ os_reason_free(jetsam_reason);
+
+ if (kill_count == 0) {
+ *memory_reclaimed = 0;
+
+ /* Clear snapshot if freshly captured and no target was found */
+ if (new_snapshot) {
+ proc_list_lock();
+ memorystatus_jetsam_snapshot->entry_count = memorystatus_jetsam_snapshot_count = 0;
+ proc_list_unlock();
+ }
+ }
+
+ KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_JETSAM) | DBG_FUNC_END,
+ MEMORYSTATUS_LOG_AVAILABLE_PAGES, killed ? aPid : 0, kill_count, *memory_reclaimed, 0);
+
+ return killed;
+}
+
+static boolean_t
+memorystatus_kill_process_async(pid_t victim_pid, uint32_t cause)
+{
+ /*
+ * TODO: allow a general async path
+ *
+ * NOTE: If a new async kill cause is added, make sure to update memorystatus_thread() to
+ * add the appropriate exit reason code mapping.
+ */
+ if ((victim_pid != -1) ||
+ (cause != kMemorystatusKilledVMPageShortage &&
+ cause != kMemorystatusKilledVMCompressorThrashing &&
+ cause != kMemorystatusKilledVMCompressorSpaceShortage &&
+ cause != kMemorystatusKilledFCThrashing &&
+ cause != kMemorystatusKilledZoneMapExhaustion)) {
+ return FALSE;
+ }
+
+ kill_under_pressure_cause = cause;
+ memorystatus_thread_wake();
+ return TRUE;
+}
+
+boolean_t
+memorystatus_kill_on_VM_compressor_space_shortage(boolean_t async)
+{
+ if (async) {
+ return memorystatus_kill_process_async(-1, kMemorystatusKilledVMCompressorSpaceShortage);
+ } else {
+ os_reason_t jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_MEMORY_VMCOMPRESSOR_SPACE_SHORTAGE);
+ if (jetsam_reason == OS_REASON_NULL) {
+ printf("memorystatus_kill_on_VM_compressor_space_shortage -- sync: failed to allocate jetsam reason\n");
+ }
+
+ return memorystatus_kill_process_sync(-1, kMemorystatusKilledVMCompressorSpaceShortage, jetsam_reason);
+ }
+}
+
+#if CONFIG_JETSAM
+boolean_t
+memorystatus_kill_on_VM_compressor_thrashing(boolean_t async)
+{
+ if (async) {
+ return memorystatus_kill_process_async(-1, kMemorystatusKilledVMCompressorThrashing);
+ } else {
+ os_reason_t jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_MEMORY_VMCOMPRESSOR_THRASHING);
+ if (jetsam_reason == OS_REASON_NULL) {
+ printf("memorystatus_kill_on_VM_compressor_thrashing -- sync: failed to allocate jetsam reason\n");
+ }
+
+ return memorystatus_kill_process_sync(-1, kMemorystatusKilledVMCompressorThrashing, jetsam_reason);
+ }
+}
+
+boolean_t
+memorystatus_kill_on_VM_page_shortage(boolean_t async)
+{
+ if (async) {
+ return memorystatus_kill_process_async(-1, kMemorystatusKilledVMPageShortage);
+ } else {
+ os_reason_t jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_MEMORY_VMPAGESHORTAGE);
+ if (jetsam_reason == OS_REASON_NULL) {
+ printf("memorystatus_kill_on_VM_page_shortage -- sync: failed to allocate jetsam reason\n");
+ }
+
+ return memorystatus_kill_process_sync(-1, kMemorystatusKilledVMPageShortage, jetsam_reason);
+ }
+}
+
+boolean_t
+memorystatus_kill_on_FC_thrashing(boolean_t async)
+{
+ if (async) {
+ return memorystatus_kill_process_async(-1, kMemorystatusKilledFCThrashing);
+ } else {
+ os_reason_t jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_MEMORY_FCTHRASHING);
+ if (jetsam_reason == OS_REASON_NULL) {
+ printf("memorystatus_kill_on_FC_thrashing -- sync: failed to allocate jetsam reason\n");
+ }
+
+ return memorystatus_kill_process_sync(-1, kMemorystatusKilledFCThrashing, jetsam_reason);
+ }
+}
+
+boolean_t
+memorystatus_kill_on_vnode_limit(void)
+{
+ os_reason_t jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_VNODE);
+ if (jetsam_reason == OS_REASON_NULL) {
+ printf("memorystatus_kill_on_vnode_limit: failed to allocate jetsam reason\n");
+ }
+
+ return memorystatus_kill_process_sync(-1, kMemorystatusKilledVnodes, jetsam_reason);
+}
+
+#endif /* CONFIG_JETSAM */
+
+boolean_t
+memorystatus_kill_on_zone_map_exhaustion(pid_t pid)
+{
+ boolean_t res = FALSE;
+ if (pid == -1) {
+ res = memorystatus_kill_process_async(-1, kMemorystatusKilledZoneMapExhaustion);
+ } else {
+ os_reason_t jetsam_reason = os_reason_create(OS_REASON_JETSAM, JETSAM_REASON_ZONE_MAP_EXHAUSTION);
+ if (jetsam_reason == OS_REASON_NULL) {
+ printf("memorystatus_kill_on_zone_map_exhaustion: failed to allocate jetsam reason\n");
+ }
+
+ res = memorystatus_kill_process_sync(pid, kMemorystatusKilledZoneMapExhaustion, jetsam_reason);
+ }
+ return res;
+}
+
+void
+memorystatus_on_pageout_scan_end(void)
+{
+ /* No-op */
+}
+
+/* Return both allocated and actual size, since there's a race between allocation and list compilation */
+static int
+memorystatus_get_priority_list(memorystatus_priority_entry_t **list_ptr, size_t *buffer_size, size_t *list_size, boolean_t size_only)
+{
+ uint32_t list_count, i = 0;
+ memorystatus_priority_entry_t *list_entry;
+ proc_t p;
+
+ list_count = memorystatus_list_count;
+ *list_size = sizeof(memorystatus_priority_entry_t) * list_count;
+
+ /* Just a size check? */
+ if (size_only) {
+ return 0;
+ }
+
+ /* Otherwise, validate the size of the buffer */
+ if (*buffer_size < *list_size) {
+ return EINVAL;
+ }
+
+ *list_ptr = kheap_alloc(KHEAP_TEMP, *list_size, Z_WAITOK | Z_ZERO);
+ if (!*list_ptr) {
+ return ENOMEM;
+ }
+
+ *buffer_size = *list_size;
+ *list_size = 0;
+
+ list_entry = *list_ptr;
+
+ proc_list_lock();
+
+ p = memorystatus_get_first_proc_locked(&i, TRUE);
+ while (p && (*list_size < *buffer_size)) {
+ list_entry->pid = p->p_pid;
+ list_entry->priority = p->p_memstat_effectivepriority;
+ list_entry->user_data = p->p_memstat_userdata;
+
+ if (p->p_memstat_memlimit <= 0) {
+ task_get_phys_footprint_limit(p->task, &list_entry->limit);
+ } else {
+ list_entry->limit = p->p_memstat_memlimit;
+ }
+
+ list_entry->state = memorystatus_build_state(p);
+ list_entry++;
+
+ *list_size += sizeof(memorystatus_priority_entry_t);
+
+ p = memorystatus_get_next_proc_locked(&i, p, TRUE);
+ }
+
+ proc_list_unlock();
+
+ MEMORYSTATUS_DEBUG(1, "memorystatus_get_priority_list: returning %lu for size\n", (unsigned long)*list_size);
+
+ return 0;
+}
+
+static int
+memorystatus_get_priority_pid(pid_t pid, user_addr_t buffer, size_t buffer_size)
+{
+ int error = 0;
+ memorystatus_priority_entry_t mp_entry;
+ kern_return_t ret;
+
+ /* Validate inputs */
+ if ((pid == 0) || (buffer == USER_ADDR_NULL) || (buffer_size != sizeof(memorystatus_priority_entry_t))) {
+ return EINVAL;
+ }
+
+ proc_t p = proc_find(pid);
+ if (!p) {
+ return ESRCH;
+ }
+
+ memset(&mp_entry, 0, sizeof(memorystatus_priority_entry_t));
+
+ mp_entry.pid = p->p_pid;
+ mp_entry.priority = p->p_memstat_effectivepriority;
+ mp_entry.user_data = p->p_memstat_userdata;
+ if (p->p_memstat_memlimit <= 0) {
+ ret = task_get_phys_footprint_limit(p->task, &mp_entry.limit);
+ if (ret != KERN_SUCCESS) {
+ proc_rele(p);
+ return EINVAL;
+ }
+ } else {
+ mp_entry.limit = p->p_memstat_memlimit;
+ }
+ mp_entry.state = memorystatus_build_state(p);
+
+ proc_rele(p);
+
+ error = copyout(&mp_entry, buffer, buffer_size);
+
+ return error;
+}
+
+static int
+memorystatus_cmd_get_priority_list(pid_t pid, user_addr_t buffer, size_t buffer_size, int32_t *retval)
+{
+ int error = 0;
+ boolean_t size_only;
+ size_t list_size;
+
+ /*
+ * When a non-zero pid is provided, the 'list' has only one entry.
+ */
+
+ size_only = ((buffer == USER_ADDR_NULL) ? TRUE: FALSE);
+
+ if (pid != 0) {
+ list_size = sizeof(memorystatus_priority_entry_t) * 1;
+ if (!size_only) {
+ error = memorystatus_get_priority_pid(pid, buffer, buffer_size);
+ }
+ } else {
+ memorystatus_priority_entry_t *list = NULL;
+ error = memorystatus_get_priority_list(&list, &buffer_size, &list_size, size_only);
+
+ if (error == 0) {
+ if (!size_only) {
+ error = copyout(list, buffer, list_size);
+ }
+ }
+
+ if (list) {
+ kheap_free(KHEAP_TEMP, list, buffer_size);
+ }
+ }
+
+ if (error == 0) {
+ assert(list_size <= INT32_MAX);
+ *retval = (int32_t) list_size;
+ }
+
+ return error;
+}
+
+static void
+memorystatus_clear_errors(void)
+{
+ proc_t p;
+ unsigned int i = 0;
+
+ KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_CLEAR_ERRORS) | DBG_FUNC_START, 0, 0, 0, 0, 0);
+
+ proc_list_lock();
+
+ p = memorystatus_get_first_proc_locked(&i, TRUE);
+ while (p) {
+ if (p->p_memstat_state & P_MEMSTAT_ERROR) {
+ p->p_memstat_state &= ~P_MEMSTAT_ERROR;
+ }
+ p = memorystatus_get_next_proc_locked(&i, p, TRUE);
+ }
+
+ proc_list_unlock();
+
+ KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_CLEAR_ERRORS) | DBG_FUNC_END, 0, 0, 0, 0, 0);
+}
+
+#if CONFIG_JETSAM
+static void
+memorystatus_update_levels_locked(boolean_t critical_only)
+{
+ memorystatus_available_pages_critical = memorystatus_available_pages_critical_base;
+
+ /*
+ * If there's an entry in the first bucket, we have idle processes.
+ */
+
+ memstat_bucket_t *first_bucket = &memstat_bucket[JETSAM_PRIORITY_IDLE];
+ if (first_bucket->count) {
+ memorystatus_available_pages_critical += memorystatus_available_pages_critical_idle_offset;
+
+ if (memorystatus_available_pages_critical > memorystatus_available_pages_pressure) {
+ /*
+ * The critical threshold must never exceed the pressure threshold
+ */
+ memorystatus_available_pages_critical = memorystatus_available_pages_pressure;
+ }
+ }
+
+ if (memorystatus_jetsam_policy & kPolicyMoreFree) {
+ memorystatus_available_pages_critical += memorystatus_policy_more_free_offset_pages;
+ }
+
+ if (critical_only) {
+ return;
+ }
+
+#if VM_PRESSURE_EVENTS
+ memorystatus_available_pages_pressure = (int32_t)(pressure_threshold_percentage * (atop_64(max_mem) / 100));
+#endif
+}
+
+void
+memorystatus_fast_jetsam_override(boolean_t enable_override)
+{
+ /* If fast jetsam is not enabled, simply return */
+ if (!fast_jetsam_enabled) {
+ return;
+ }
+
+ if (enable_override) {
+ if ((memorystatus_jetsam_policy & kPolicyMoreFree) == kPolicyMoreFree) {
+ return;
+ }
+ proc_list_lock();
+ memorystatus_jetsam_policy |= kPolicyMoreFree;
+ memorystatus_thread_pool_max();
+ memorystatus_update_levels_locked(TRUE);
+ proc_list_unlock();
+ } else {
+ if ((memorystatus_jetsam_policy & kPolicyMoreFree) == 0) {
+ return;
+ }
+ proc_list_lock();
+ memorystatus_jetsam_policy &= ~kPolicyMoreFree;
+ memorystatus_thread_pool_default();
+ memorystatus_update_levels_locked(TRUE);
+ proc_list_unlock();
+ }
+}
+
+
+static int
+sysctl_kern_memorystatus_policy_more_free SYSCTL_HANDLER_ARGS
+{
+#pragma unused(arg1, arg2, oidp)
+ int error = 0, more_free = 0;
+
+ /*
+ * TODO: Enable this privilege check?
+ *
+ * error = priv_check_cred(kauth_cred_get(), PRIV_VM_JETSAM, 0);
+ * if (error)
+ * return (error);
+ */
+
+ error = sysctl_handle_int(oidp, &more_free, 0, req);
+ if (error || !req->newptr) {
+ return error;
+ }
+
+ if (more_free) {
+ memorystatus_fast_jetsam_override(true);
+ } else {
+ memorystatus_fast_jetsam_override(false);
+ }
+
+ return 0;
+}
+SYSCTL_PROC(_kern, OID_AUTO, memorystatus_policy_more_free, CTLTYPE_INT | CTLFLAG_WR | CTLFLAG_LOCKED | CTLFLAG_MASKED,
+ 0, 0, &sysctl_kern_memorystatus_policy_more_free, "I", "");
+
+#endif /* CONFIG_JETSAM */
+
+/*
+ * Get the at_boot snapshot
+ */
+static int
+memorystatus_get_at_boot_snapshot(memorystatus_jetsam_snapshot_t **snapshot, size_t *snapshot_size, boolean_t size_only)
+{
+ size_t input_size = *snapshot_size;
+
+ /*
+ * The at_boot snapshot has no entry list.
+ */
+ *snapshot_size = sizeof(memorystatus_jetsam_snapshot_t);
+
+ if (size_only) {
+ return 0;
+ }
+
+ /*
+ * Validate the size of the snapshot buffer
+ */
+ if (input_size < *snapshot_size) {
+ return EINVAL;
+ }
+
+ /*
+ * Update the notification_time only
+ */
+ memorystatus_at_boot_snapshot.notification_time = mach_absolute_time();
+ *snapshot = &memorystatus_at_boot_snapshot;
+
+ MEMORYSTATUS_DEBUG(7, "memorystatus_get_at_boot_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%d)\n",
+ (long)input_size, (long)*snapshot_size, 0);
+ return 0;
+}
+
+/*
+ * Get the previous fully populated snapshot
+ */
+static int
+memorystatus_get_jetsam_snapshot_copy(memorystatus_jetsam_snapshot_t **snapshot, size_t *snapshot_size, boolean_t size_only)
+{
+ size_t input_size = *snapshot_size;
+
+ if (memorystatus_jetsam_snapshot_copy_count > 0) {
+ *snapshot_size = sizeof(memorystatus_jetsam_snapshot_t) + (sizeof(memorystatus_jetsam_snapshot_entry_t) * (memorystatus_jetsam_snapshot_copy_count));
+ } else {
+ *snapshot_size = 0;
+ }
+
+ if (size_only) {
+ return 0;
+ }
+
+ if (input_size < *snapshot_size) {
+ return EINVAL;
+ }
+
+ *snapshot = memorystatus_jetsam_snapshot_copy;
+
+ MEMORYSTATUS_DEBUG(7, "memorystatus_get_jetsam_snapshot_copy: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
+ (long)input_size, (long)*snapshot_size, (long)memorystatus_jetsam_snapshot_copy_count);
+
+ return 0;
+}
+
+#if CONFIG_FREEZE
+static int
+memorystatus_get_jetsam_snapshot_freezer(memorystatus_jetsam_snapshot_t **snapshot, size_t *snapshot_size, boolean_t size_only)
+{
+ size_t input_size = *snapshot_size;
+
+ if (memorystatus_jetsam_snapshot_freezer->entry_count > 0) {
+ *snapshot_size = sizeof(memorystatus_jetsam_snapshot_t) + (sizeof(memorystatus_jetsam_snapshot_entry_t) * (memorystatus_jetsam_snapshot_freezer->entry_count));
+ } else {
+ *snapshot_size = 0;
+ }
+ assert(*snapshot_size <= memorystatus_jetsam_snapshot_freezer_size);
+
+ if (size_only) {
+ return 0;
+ }
+
+ if (input_size < *snapshot_size) {
+ return EINVAL;
+ }
+
+ *snapshot = memorystatus_jetsam_snapshot_freezer;
+
+ MEMORYSTATUS_DEBUG(7, "memorystatus_get_jetsam_snapshot_freezer: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
+ (long)input_size, (long)*snapshot_size, (long)memorystatus_jetsam_snapshot_freezer->entry_count);
+
+ return 0;
+}
+#endif /* CONFIG_FREEZE */
+
+static int
+memorystatus_get_on_demand_snapshot(memorystatus_jetsam_snapshot_t **snapshot, size_t *snapshot_size, boolean_t size_only)
+{
+ size_t input_size = *snapshot_size;
+ uint32_t ods_list_count = memorystatus_list_count;
+ memorystatus_jetsam_snapshot_t *ods = NULL; /* The on_demand snapshot buffer */
+
+ *snapshot_size = sizeof(memorystatus_jetsam_snapshot_t) + (sizeof(memorystatus_jetsam_snapshot_entry_t) * (ods_list_count));
+
+ if (size_only) {
+ return 0;
+ }
+
+ /*
+ * Validate the size of the snapshot buffer.
+ * This is inherently racey. May want to revisit
+ * this error condition and trim the output when
+ * it doesn't fit.
+ */
+ if (input_size < *snapshot_size) {
+ return EINVAL;
+ }
+
+ /*
+ * Allocate and initialize a snapshot buffer.
+ */
+ ods = kalloc(*snapshot_size);
+ if (!ods) {
+ return ENOMEM;
+ }
+
+ memset(ods, 0, *snapshot_size);
+
+ proc_list_lock();
+ memorystatus_init_jetsam_snapshot_locked(ods, ods_list_count);
+ proc_list_unlock();
+
+ /*
+ * Return the kernel allocated, on_demand buffer.
+ * The caller of this routine will copy the data out
+ * to user space and then free the kernel allocated
+ * buffer.
+ */
+ *snapshot = ods;
+
+ MEMORYSTATUS_DEBUG(7, "memorystatus_get_on_demand_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
+ (long)input_size, (long)*snapshot_size, (long)ods_list_count);
+
+ return 0;
+}
+
+static int
+memorystatus_get_jetsam_snapshot(memorystatus_jetsam_snapshot_t **snapshot, size_t *snapshot_size, boolean_t size_only)
+{
+ size_t input_size = *snapshot_size;
+
+ if (memorystatus_jetsam_snapshot_count > 0) {
+ *snapshot_size = sizeof(memorystatus_jetsam_snapshot_t) + (sizeof(memorystatus_jetsam_snapshot_entry_t) * (memorystatus_jetsam_snapshot_count));
+ } else {
+ *snapshot_size = 0;
+ }
+
+ if (size_only) {
+ return 0;
+ }
+
+ if (input_size < *snapshot_size) {
+ return EINVAL;
+ }
+
+ *snapshot = memorystatus_jetsam_snapshot;
+
+ MEMORYSTATUS_DEBUG(7, "memorystatus_get_jetsam_snapshot: returned inputsize (%ld), snapshot_size(%ld), listcount(%ld)\n",
+ (long)input_size, (long)*snapshot_size, (long)memorystatus_jetsam_snapshot_count);
+
+ return 0;
+}
+
+
+static int
+memorystatus_cmd_get_jetsam_snapshot(int32_t flags, user_addr_t buffer, size_t buffer_size, int32_t *retval)
+{
+ int error = EINVAL;
+ boolean_t size_only;
+ boolean_t is_default_snapshot = FALSE;
+ boolean_t is_on_demand_snapshot = FALSE;
+ boolean_t is_at_boot_snapshot = FALSE;
+#if CONFIG_FREEZE
+ bool is_freezer_snapshot = false;
+#endif /* CONFIG_FREEZE */
+ memorystatus_jetsam_snapshot_t *snapshot;
+
+ size_only = ((buffer == USER_ADDR_NULL) ? TRUE : FALSE);
+
+ if (flags == 0) {
+ /* Default */
+ is_default_snapshot = TRUE;
+ error = memorystatus_get_jetsam_snapshot(&snapshot, &buffer_size, size_only);
+ } else {
+ if (flags & ~(MEMORYSTATUS_SNAPSHOT_ON_DEMAND | MEMORYSTATUS_SNAPSHOT_AT_BOOT | MEMORYSTATUS_SNAPSHOT_COPY | MEMORYSTATUS_FLAGS_SNAPSHOT_FREEZER)) {
+ /*
+ * Unsupported bit set in flag.
+ */
+ return EINVAL;
+ }
+
+ if (flags & (flags - 0x1)) {
+ /*
+ * Can't have multiple flags set at the same time.
+ */
+ return EINVAL;
+ }
+
+ if (flags & MEMORYSTATUS_SNAPSHOT_ON_DEMAND) {
+ is_on_demand_snapshot = TRUE;
+ /*
+ * When not requesting the size only, the following call will allocate
+ * an on_demand snapshot buffer, which is freed below.
+ */
+ error = memorystatus_get_on_demand_snapshot(&snapshot, &buffer_size, size_only);
+ } else if (flags & MEMORYSTATUS_SNAPSHOT_AT_BOOT) {
+ is_at_boot_snapshot = TRUE;
+ error = memorystatus_get_at_boot_snapshot(&snapshot, &buffer_size, size_only);
+ } else if (flags & MEMORYSTATUS_SNAPSHOT_COPY) {
+ error = memorystatus_get_jetsam_snapshot_copy(&snapshot, &buffer_size, size_only);
+#if CONFIG_FREEZE
+ } else if (flags & MEMORYSTATUS_FLAGS_SNAPSHOT_FREEZER) {
+ is_freezer_snapshot = true;
+ error = memorystatus_get_jetsam_snapshot_freezer(&snapshot, &buffer_size, size_only);
+#endif /* CONFIG_FREEZE */
+ } else {
+ /*
+ * Invalid flag setting.
+ */
+ return EINVAL;
+ }
+ }
+
+ if (error) {
+ goto out;
+ }
+
+ /*
+ * Copy the data out to user space and clear the snapshot buffer.
+ * If working with the jetsam snapshot,
+ * clearing the buffer means, reset the count.
+ * If working with an on_demand snapshot
+ * clearing the buffer means, free it.
+ * If working with the at_boot snapshot
+ * there is nothing to clear or update.
+ * If working with a copy of the snapshot
+ * there is nothing to clear or update.
+ * If working with the freezer snapshot
+ * clearing the buffer means, reset the count.
+ */
+ if (!size_only) {
+ if ((error = copyout(snapshot, buffer, buffer_size)) == 0) {
+#if CONFIG_FREEZE
+ if (is_default_snapshot || is_freezer_snapshot) {
+#else
+ if (is_default_snapshot) {
+#endif /* CONFIG_FREEZE */
+ /*
+ * The jetsam snapshot is never freed, its count is simply reset.
+ * However, we make a copy for any parties that might be interested
+ * in the previous fully populated snapshot.
+ */
+ proc_list_lock();
+#if DEVELOPMENT || DEBUG
+ if (memorystatus_snapshot_owner != 0 && memorystatus_snapshot_owner != current_proc()->p_pid) {
+ /* Snapshot is currently owned by someone else. Don't consume it. */
+ proc_list_unlock();
+ goto out;
+ }
+#endif /* (DEVELOPMENT || DEBUG)*/
+ if (is_default_snapshot) {
+ memcpy(memorystatus_jetsam_snapshot_copy, memorystatus_jetsam_snapshot, memorystatus_jetsam_snapshot_size);
+ memorystatus_jetsam_snapshot_copy_count = memorystatus_jetsam_snapshot_count;
+ snapshot->entry_count = memorystatus_jetsam_snapshot_count = 0;
+ memorystatus_jetsam_snapshot_last_timestamp = 0;
+ }
+#if CONFIG_FREEZE
+ else if (is_freezer_snapshot) {
+ memorystatus_jetsam_snapshot_freezer->entry_count = 0;
+ }
+#endif /* CONFIG_FREEZE */
+ proc_list_unlock();
+ }
+ }
+
+ if (is_on_demand_snapshot) {
+ /*
+ * The on_demand snapshot is always freed,
+ * even if the copyout failed.
+ */
+ if (snapshot) {
+ kfree(snapshot, buffer_size);
+ }
+ }
+ }
+
+out:
+ if (error == 0) {
+ assert(buffer_size <= INT32_MAX);
+ *retval = (int32_t) buffer_size;
+ }
+ return error;
+}
+
+#if DEVELOPMENT || DEBUG
+static int
+memorystatus_cmd_set_jetsam_snapshot_ownership(int32_t flags)
+{
+ int error = EINVAL;
+ proc_t caller = current_proc();
+ assert(caller != kernproc);
+ proc_list_lock();
+ if (flags & MEMORYSTATUS_FLAGS_SNAPSHOT_TAKE_OWNERSHIP) {
+ if (memorystatus_snapshot_owner == 0) {
+ memorystatus_snapshot_owner = caller->p_pid;
+ error = 0;
+ } else if (memorystatus_snapshot_owner == caller->p_pid) {
+ error = 0;
+ } else {
+ /* We don't allow ownership to be taken from another proc. */
+ error = EBUSY;
+ }
+ } else if (flags & MEMORYSTATUS_FLAGS_SNAPSHOT_DROP_OWNERSHIP) {
+ if (memorystatus_snapshot_owner == caller->p_pid) {
+ memorystatus_snapshot_owner = 0;
+ error = 0;
+ } else if (memorystatus_snapshot_owner != 0) {
+ /* We don't allow ownership to be taken from another proc. */
+ error = EPERM;
+ }
+ }
+ proc_list_unlock();
+
+ return error;
+}
+#endif /* DEVELOPMENT || DEBUG */
+
+/*
+ * Routine: memorystatus_cmd_grp_set_priorities
+ * Purpose: Update priorities for a group of processes.
+ *
+ * [priority]
+ * Move each process out of its effective priority
+ * band and into a new priority band.
+ * Maintains relative order from lowest to highest priority.
+ * In single band, maintains relative order from head to tail.
+ *
+ * eg: before [effectivepriority | pid]
+ * [18 | p101 ]
+ * [17 | p55, p67, p19 ]
+ * [12 | p103 p10 ]
+ * [ 7 | p25 ]
+ * [ 0 | p71, p82, ]
+ *
+ * after [ new band | pid]
+ * [ xxx | p71, p82, p25, p103, p10, p55, p67, p19, p101]
+ *
+ * Returns: 0 on success, else non-zero.
+ *
+ * Caveat: We know there is a race window regarding recycled pids.
+ * A process could be killed before the kernel can act on it here.
+ * If a pid cannot be found in any of the jetsam priority bands,
+ * then we simply ignore it. No harm.
+ * But, if the pid has been recycled then it could be an issue.
+ * In that scenario, we might move an unsuspecting process to the new
+ * priority band. It's not clear how the kernel can safeguard
+ * against this, but it would be an extremely rare case anyway.
+ * The caller of this api might avoid such race conditions by
+ * ensuring that the processes passed in the pid list are suspended.
+ */
+
+
+static int
+memorystatus_cmd_grp_set_priorities(user_addr_t buffer, size_t buffer_size)
+{
+ /*
+ * We only handle setting priority
+ * per process
+ */
+
+ int error = 0;
+ memorystatus_properties_entry_v1_t *entries = NULL;
+ size_t entry_count = 0;
+
+ /* This will be the ordered proc list */
+ typedef struct memorystatus_internal_properties {
+ proc_t proc;
+ int32_t priority;
+ } memorystatus_internal_properties_t;
+
+ memorystatus_internal_properties_t *table = NULL;
+ size_t table_size = 0;
+ uint32_t table_count = 0;
+
+ size_t i = 0;
+ uint32_t bucket_index = 0;
+ boolean_t head_insert;
+ int32_t new_priority;
+
+ proc_t p;
+
+ /* Verify inputs */
+ if ((buffer == USER_ADDR_NULL) || (buffer_size == 0)) {
+ error = EINVAL;
+ goto out;
+ }
+
+ entry_count = (buffer_size / sizeof(memorystatus_properties_entry_v1_t));
+ if (entry_count == 0) {
+ /* buffer size was not large enough for a single entry */
+ error = EINVAL;
+ goto out;
+ }
+
+ if ((entries = kheap_alloc(KHEAP_TEMP, buffer_size, Z_WAITOK)) == NULL) {
+ error = ENOMEM;
+ goto out;
+ }
+
+ KERNEL_DEBUG_CONSTANT(BSDDBG_CODE(DBG_BSD_MEMSTAT, BSD_MEMSTAT_GRP_SET_PROP) | DBG_FUNC_START, MEMORYSTATUS_FLAGS_GRP_SET_PRIORITY, entry_count, 0, 0, 0);
+
+ if ((error = copyin(buffer, entries, buffer_size)) != 0) {
+ goto out;
+ }
+
+ /* Verify sanity of input priorities */
+ if (entries[0].version == MEMORYSTATUS_MPE_VERSION_1) {
+ if ((buffer_size % MEMORYSTATUS_MPE_VERSION_1_SIZE) != 0) {
+ error = EINVAL;
+ goto out;
+ }
+ } else {
+ error = EINVAL;
+ goto out;
+ }
+
+ for (i = 0; i < entry_count; i++) {
+ if (entries[i].priority == -1) {
+ /* Use as shorthand for default priority */
+ entries[i].priority = JETSAM_PRIORITY_DEFAULT;
+ } else if ((entries[i].priority == system_procs_aging_band) || (entries[i].priority == applications_aging_band)) {
+ /* Both the aging bands are reserved for internal use;
+ * if requested, adjust to JETSAM_PRIORITY_IDLE. */
+ entries[i].priority = JETSAM_PRIORITY_IDLE;
+ } else if (entries[i].priority == JETSAM_PRIORITY_IDLE_HEAD) {
+ /* JETSAM_PRIORITY_IDLE_HEAD inserts at the head of the idle
+ * queue */
+ /* Deal with this later */
+ } else if ((entries[i].priority < 0) || (entries[i].priority >= MEMSTAT_BUCKET_COUNT)) {
+ /* Sanity check */
+ error = EINVAL;
+ goto out;
+ }
+ }
+
+ table_size = sizeof(memorystatus_internal_properties_t) * entry_count;
+ if ((table = kheap_alloc(KHEAP_TEMP, table_size, Z_WAITOK | Z_ZERO)) == NULL) {
+ error = ENOMEM;
+ goto out;
+ }
+
+
+ /*
+ * For each jetsam bucket entry, spin through the input property list.
+ * When a matching pid is found, populate an adjacent table with the
+ * appropriate proc pointer and new property values.
+ * This traversal automatically preserves order from lowest
+ * to highest priority.
+ */
+
+ bucket_index = 0;
+
+ proc_list_lock();
+
+ /* Create the ordered table */
+ p = memorystatus_get_first_proc_locked(&bucket_index, TRUE);
+ while (p && (table_count < entry_count)) {
+ for (i = 0; i < entry_count; i++) {
+ if (p->p_pid == entries[i].pid) {
+ /* Build the table data */
+ table[table_count].proc = p;
+ table[table_count].priority = entries[i].priority;
+ table_count++;
+ break;
+ }