Android L shutdown Flowchart
The following is a simple flowchart from java to the kernel layer.
ShutdownThread. java File
Stop playing music, because playing shutdown music may be used later.
The Code is as follows:
private static void beginShutdownSequence(Context context) { .... //acquire audio focus to make the other apps to stop playing muisc mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); mAudioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
Show system dialog to indicate phone is shutting down. If there is no shutdown animation, show a shutdown prompt.
The Code is as follows:
if (!checkAnimationFileExist()) { // throw up an indeterminate system dialog to indicate radio is // shutting down. ProgressDialog pd = new ProgressDialog(context); pd.setTitle(context.getText(com.android.internal.R.string.power_off)); pd.setMessage(context.getText(com.android.internal.R.string.shutdown_progress)); pd.setIndeterminate(true); pd.setCancelable(false); pd.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG); pd.show(); }
Hold the wakelock, make sure we never fall asleep again, catch the lock to prevent sleep during Machine Shutdown
The Code is as follows:
SInstance. mCpuWakeLock = sInstance. mPowerManager. newWakeLock (PowerManager. PARTIAL_WAKE_LOCK, TAG +-cpu); // This only locks the cpu and does not enter sleep, but the screen is off. The full lock is required to ensure that the screen is always on sInstance. mCpuWakeLock. setReferenceCounted (false); sInstance. mCpuWakeLock. acquire ();
Make sure the screen stays on and catch a full lock to prevent the screen from being half-dark.
The Code is as follows:
SInstance. mScreenWakeLock = sInstance. mPowerManager. newWakeLock (PowerManager. FULL_WAKE_LOCK, TAG +-screen); // keep sInstance always on srceen. mScreenWakeLock. setReferenceCounted (false); sInstance. mScreenWakeLock. acquire ();
Start a new process
Sending shutdown broadcast, send a broadcast, notify each app to save the data quickly, I want to shut down
The Code is as follows:
Intent intent = new Intent (Intent. ACTION_SHUTDOWN); intent. addFlags (Intent. FLAG_RECEIVER_FOREGROUND); mContext. sendOrderedBroadcastAsUser (intent, // broadcast UserHandle. ALL, null, br, mHandler, 0, null, null );
Shutdown activity manager, disable activity manager, that is, disable AppOpsService, UsageStatsService, BatteryStatsService
Note: android L and KK are different in disabling UsageStatsService.
The Code is as follows:
[ActivityManagerService. java]
final IActivityManager am = ActivityManagerNative.asInterface(ServiceManager.checkService(activity)); if (am != null) { try { am.shutdown(MAX_BROADCAST_TIME); } catch (RemoteException e) { } }
Shutdown the package manager and save the app usage time to disk. This is a new feature of android L.
The Code is as follows:
[PackageManagerService. java]
final PackageManagerService pm = (PackageManagerService) ServiceManager.getService(package); if (pm != null) { pm.shutdown(); }
Show shutdown animation, playing the shutdown animation
The Code is as follows:
Private static void showShutdownAnimation () {/** When boot completed, service. bootanim. exit property is set to 1. * Bootanimation checks this property to stop showing the boot animation. * Since we use the same code for shutdown animation, we * need to reset this property to 0. if this is not set to 0 then shutdown * will stop and exit after displaying the first frame of the animation */SystemPr Operties. set (service. bootanim. exit, 0); SystemProperties. set (ctl. start, bootanim); // The bootanim process is also used in the same way as the animation of the switch. }
Shutdown radio [NFC, BT, MODEM]. Note that disabling modem is different from andorid KK.
The Code is as follows:
ShutdownRadios (MAX_RADIO_WAIT_TIME );
Shutdown MountService. In particular, shutdown may fail.
The Code is as follows:
// Set initial variables and time out time. mActionDone = false; final long endShutTime = SystemClock.elapsedRealtime() + MAX_SHUTDOWN_WAIT_TIME; synchronized (mActionDoneSync) { try { final IMountService mount = IMountService.Stub.asInterface( ServiceManager.checkService(mount)); if (mount != null) { mount.shutdown(observer); } else { Log.w(TAG, MountService unavailable for shutdown); } } catch (Exception e) { Log.e(TAG, Exception during MountService shutdown, e); } while (!mActionDone) { long delay = endShutTime - SystemClock.elapsedRealtime(); if (delay <= 0) { Log.w(TAG, Shutdown wait timed out); break; } try { mActionDoneSync.wait(delay); } catch (InterruptedException e) { } } }
After the upper-layer shutdown process is completed, the shutdown action will be executed below.
The Code is as follows:
Public static void rebootOrShutdown (boolean reboot, String reason) {deviceRebootOrShutdown (reboot, reason); if (reboot) {Log. I (TAG, Rebooting, reason: + reason); PowerManagerService. lowLevelReboot (reason); // restart Log. e (TAG, Reboot failed, will attempt shutdown instead);} else if (SHUTDOWN_VIBRATE_MS> 0) {// vibrate before shutting down Vibrator vibrator = new SystemVibrator (); try {vibrator. vibrate (SHUTDOWN_VIBRATE_MS, VIBRATION_ATTRIBUTES);} catch (Exception e) {// Failure to vibrate shouldn't interrupt shutdown. just log it. log. w (TAG, Failed to vibrate during shutdown ., e);} // vibrator is asynchronous so we need to wait to avoid shutting down too soon. try {Thread. sleep (SHUTDOWN_VIBRATE_MS);} catch (InterruptedException unused) {}} // Shutdown power Log. I (TAG, locking Ming low-level shutdown ...); powerManagerService. lowLevelShutdown (); // shutdown}
From the code point of view, it will always go to lowLevelShutdown (), but if it is restarted, it won't, And lowLevelReboot () will stop.
LowLevelShutdown () and lowLevelReboot () are both implemented in PowerManagerService. java. In fact, they all set an attribute: SystemProperties. set (sys. powerctl, xxx );
This action triggers the Shutdown Process, which involves four main functions of the init process. For more information, see the init process in Android.
Sys. powerctl attribute trigger switch defined in init. rc
on property:sys.powerctl=* powerctl ${sys.powerctl}
Let's explain this sentence, on property: sys. powerctl = * indicates when the attribute sys. if powerctl is set to any value, it will run here. The trigger action is powerctl $ {sys. powerctl}, which means to call the powerctl command and. the value of powerctl is passed to it. The powerctl command is executed in the init process.
The following table shows that the operation corresponding to powerctl is do_powerctl.
[System/core/init/keywords. h]
KEYWORD(powerctl, COMMAND, 1, do_powerctl)
Implementation of do_powerctl
The Code is as follows:
[System/core/init/builtins. c]
int do_powerctl(int nargs, char **args){.... return android_reboot(cmd, 0, reboot_target);}
It calls the android_reboot () function and implements the following:
[System/core/libcutils/android_reboot.c]
int android_reboot(int cmd, int flags UNUSED, char *arg){ int ret; sync(); remount_ro(); switch (cmd) { case ANDROID_RB_RESTART: ret = reboot(RB_AUTOBOOT); break; case ANDROID_RB_POWEROFF: ret = reboot(RB_POWER_OFF); break; case ANDROID_RB_RESTART2: ret = syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, arg); break; default: ret = -1; } return ret;}
Here we can see its main work:
Sync () writes back the content of the block device, which is a blocking operation.
Remount_ro () remount the block device into ro. Here there is a key LOG: SysRq: Emergency Remount R/O, which is the last LOG that can be seen in logkit, because remount is ro, the subsequent LOG will be exported through the last kmsg technology.
Reboot () or syscall (_ NR_reboot... This is different from android KK. Here we use the syscall function directly, and KK is compiled.
Later, syscall (_ NR_reboot... you know that the _ NR_reboot System of linux is called directly. Where will this system call run? I will talk about it later.
The reboot () function is implemented as follows:
[Bionic/libc/bionic/reboot. cpp]
int reboot(int mode) { return __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, mode, NULL);}
_ Reboot is called, which is implemented in the compilation as follows:
[Bionic/libc/arch-arm/syscils/_ reboot. S]
ENTRY (_ reboot) mov ip, r7 ldr r7, =__ NR_reboot // also run to the _ NR_reboot system to call swi #0 mov r7, ip CEN r0, # (MAX_ERRNO + 1) bxls lr neg r0, r0 B _ set_errno_internalEND (_ reboot)
_ Where is the kernel entry corresponding to NR_reboot?
As follows:
[Bionic/libc/kernel/uapi/asm-generic/unistd. h]
#define __NR_reboot 142
The kernel entry is as follows:
Note: bionic/libc/kernel/uapi/asm-generic/unistd. h corresponds to kernel/include/uapi/asm-generic/unistd. h, facilitating code tracing in the future
[Kernel/include/uapi/asm-generic/unistd. h]
#define __NR_reboot 142__SYSCALL(__NR_reboot, sys_reboot)
_ NR_reboot ing to sys_reboot
Sys_reboot cannot be found in grep. Actually, it is here
Define with SYSCALL_DEFINE
[Kernel/sys. c]
SYSCALL_DEFINE4(reboot, int, magic1, int, magic2, unsigned int, cmd,void __user *, arg){struct pid_namespace *pid_ns = task_active_pid_ns(current);char buffer[256];int ret = 0;/* We only trust the superuser with rebooting the system. */if (!ns_capable(pid_ns->user_ns, CAP_SYS_BOOT))return -EPERM;/* For safety, we require magic arguments. */if (magic1 != LINUX_REBOOT_MAGIC1 || (magic2 != LINUX_REBOOT_MAGIC2 && magic2 != LINUX_REBOOT_MAGIC2A &&magic2 != LINUX_REBOOT_MAGIC2B && magic2 != LINUX_REBOOT_MAGIC2C))return -EINVAL;/* * If pid namespaces are enabled and the current task is in a child * pid_namespace, the command is handled by reboot_pid_ns() which will * call do_exit(). */ret = reboot_pid_ns(pid_ns, cmd);if (ret)return ret;/* Instead of trying to make the power_off code look like * halt when pm_power_off is not set do it the easy way. */if ((cmd == LINUX_REBOOT_CMD_POWER_OFF) && !pm_power_off)cmd = LINUX_REBOOT_CMD_HALT;mutex_lock(&reboot_mutex);switch (cmd) {case LINUX_REBOOT_CMD_RESTART:kernel_restart(NULL);break;case LINUX_REBOOT_CMD_CAD_ON:C_A_D = 1;break;case LINUX_REBOOT_CMD_CAD_OFF:C_A_D = 0;break;case LINUX_REBOOT_CMD_HALT:kernel_halt();do_exit(0);panic(cannot halt);case LINUX_REBOOT_CMD_POWER_OFF:kernel_power_off();do_exit(0);break;case LINUX_REBOOT_CMD_RESTART2:if (strncpy_from_user(&buffer[0], arg, sizeof(buffer) - 1) < 0) {ret = -EFAULT;break;}buffer[sizeof(buffer) - 1] = '';kernel_restart(buffer);break;#ifdef CONFIG_KEXECcase LINUX_REBOOT_CMD_KEXEC:ret = kernel_kexec();break;#endif#ifdef CONFIG_HIBERNATIONcase LINUX_REBOOT_CMD_SW_SUSPEND:ret = hibernate();break;#endifdefault:ret = -EINVAL;break;}mutex_unlock(&reboot_mutex);return ret;}
There are many branches. We only care about the kernel_power_off () and kernel_restart () functions.
As follows:
Void kernel_power_off (void) {kernel_shutdown_prepare (SYSTEM_POWER_OFF); // disable peripherals if (idle) pm_power_off_prepare (); disconnect (); syscore_shutdown (); // disable syscoreprintk (KERN_EMERG Power down .); // key print kmsg_dump (KMSG_DUMP_POWEROFF); machine_power_off ();}
Void kernel_restart (char * cmd) {kernel_restart_prepare (cmd); // disable the peripherals migrate_to_reboot_cpu (); syscore_shutdown (); // disable syscoreif (! Cmd) printk (KERN_EMERG Restarting system .); // key print elseprintk (KERN_EMERG Restarting system with command '% s '., cmd); kmsg_dump (KMSG_DUMP_RESTART); machine_restart (cmd );}
Execute the XX_prepare () function.
static void kernel_shutdown_prepare(enum system_states state){blocking_notifier_call_chain(&reboot_notifier_list,(state == SYSTEM_HALT)?SYS_HALT:SYS_POWER_OFF, NULL);system_state = state;usermodehelper_disable();device_shutdown();}
void kernel_restart_prepare(char *cmd){blocking_notifier_call_chain(&reboot_notifier_list, SYS_RESTART, cmd);system_state = SYSTEM_RESTART;usermodehelper_disable();device_shutdown();}
Except for the previous differences, the device_shutdown () function is called to disable peripherals.
Machine_power_off () machine_resestart () function implementation
Void machine_power_off (void) {preempt_disable (); smp_send_stop (); if (pm_power_off) pm_power_off (); // shutdown}
Void machine_restart (char * cmd) {preempt_disable (); smp_send_stop (); /* Flush the console to make sure all the relevant messages make it * out to the console drivers */arm_machine_flush_console (); arm_pm_restart (reboot_mode, cmd ); // restart/* Give a grace period for failure to restart of 1 s */mdelay (1000);/* Whoops-the platform was unable to reboot. tell the user! */Printk (Reboot failed -- System halted); local_irq_disable (); while (1 );}
Pm_power_offf () arm_pm_restart () is a function pointer.
The assignment value is as follows:
[Kernel/drivers/power/reset/msm-poweroff.c]
pm_power_off = do_msm_poweroff;arm_pm_restart = do_msm_restart;
Qualcomm platform shutdown code is different from before, and now the file msm-poweroff.c is restart. c.
Do_msm_poweroff () and do_msm_restart () are implemented as follows:
Static void do_msm_poweroff (void ){.... pr_notice (Powering off the SoC); // key print # ifdef unlock (0); // shutdown, so the dloadmode is 0 # endifqpnp_pon_system_pwr_off (PON_POWER_OFF_SHUTDOWN); // configure PMIC, shutdown ..... /* MSM initiated power off, lower ps_hold */_ raw_writel (0, msm_ps_hold); // pull PS_HOLD and perform shutdown. Mdelay (10000); pr_err (Powering off has failed); return ;}
Static void do_msm_restart (enum reboot_mode, const char * cmd )... pr_notice (Going down for restart now); // key print msm_restart_prepare (cmd); // action before restart preparation # ifdef CONFIG_MSM_DLOAD_MODE/** Trigger a watchdog bite here and if this fails, * device will take the usual restart path. */if (WDOG_BITE_ON_PANIC & in_panic) msm_trigger_wdog_bite (); # endif .... halt_spmi_pmic_arbiter () ;__ raw_writel (0, msm_ps_hold); // pull PS_HOLD to restart mdelay (10000 );}
Msm_restart_prepare () Implementation
Static void msm_restart_prepare (const char * cmd) {# ifdef CONFIG_MSM_DLOAD_MODE/* Write download mode flags if we're panic 'ing * Write download mode flags if restart_mode says so * Kill download mode if master-kill switch is set */set_dload_mode (download_mode & (in_panic | restart_mode = RESTART_DLOAD )); // set dload # endif/* Hard reset the PMIC unless memory contents must be maintained. */if (get_dload _ Mode () | (cmd! = NULL & cmd [0]! = '') Qpnp_pon_system_pwr_off (PON_POWER_OFF_WARM_RESET); // set PIMC to hot restart (PON_POWER_OFF_HARD_RESET); // set PIMC to hard restart if (cmd! = NULL) {if (! Strncmp (cmd, bootloader, 10) {__ raw_writel (0x77665500, restart_reason); // write some stuff to IMEM for bootloader, recovery, etc.} else if (! Strncmp (cmd, recovery, 8) {__ raw_writel (0x77665502, restart_reason);} else if (! Strcmp (cmd, rtc) {__ raw_writel (0x77665503, restart_reason);} else if (! Strncmp (cmd, oem-, 4) {unsigned long code; int ret; ret = kstrtoul (cmd + 4, 16, & code); if (! Ret) _ raw_writel (0x6f656d00 | (code & 0xff), restart_reason);} else if (! Strncmp (cmd, edl, 3) {enable_emergency_dload_mode ();} else {__ raw_writel (0x77665501, restart_reason );}}.....}
Do_msm_poweroff () and do_msm_restart () both set dload and PMIC. The only difference is that do_msm_restart () has a _ raw_writel action, that is, reason writes to IMEM, the purpose is to determine which mode should be entered when the system restarts and enters sbl1, for example, the bootloader mode we are using and restore the factory-configured recovery mode.