Memory recovery mechanism for Android OS [go]

Source: Internet
Author: User

Turn from: http://www.ibm.com/developerworks/cn/opensource/os-cn-android-mmry-rcycl/Android APP's operating environment

Android is a Linux-based kernel for mobile terminal operating systems. In order to adapt to its special needs as a mobile platform operating system, Google has made a special design and optimization, making its process scheduling and resource management and other platforms of Linux have obvious differences. It consists of the following levels:

  1. Application Framework

    The application Framework separates the entire operating system into two parts. For app developers, all apps run on the application Framework and don't need to be concerned about the bottom of the system. The application Framework layer provides a rich application programming interface for application developers, such as Activity manager,content provider,notification Manager, and various widget resources. At the application Framework level, Activity is the most basic component of an APP. Typically each activity corresponds to a view (or one screen) on the screen, and an APP can have one or more activity. The application is packaged into an. apk format file that is interpreted by the Dalvik VM for execution.

  2. Dalvik VMS

    The Dalvik virtual machine uses a register schema rather than the JVM's stack structure. The. class file compiled by the Java program does not interpret execution in Dalvik. So Google provides a DX tool for converting. class files into the. dex format that DALIVK can recognize. Details of specific Dalvik VMs are not the focus of this article and are no longer discussed below.

  3. Linux kernel

    As mentioned above, all apps are written in Java code and interpreted in the Dalvik VM. In the Android operating system, each Instance of each Dalvik VM corresponds to a process in the Linux kernel. You can use the ADB shell tool to view the current process in the system. As shown, Android2.3.3 the list of processes in the kernel after startup.

    Figure 1. List of processes in Android 2.3 (partial)

    In Figure 1, each entry with a UID ID of app_xx is a process occupied by an app, and the Android design allows each application to be interpreted by a separate Dalvik instance, and each Linux kernel process loads a Dalvik instance, providing a The operating environment of PP. This way, each APP's resources are completely shielded from each other. While the difficulty of inter-process communication is introduced, it also brings more security.

Android Memory Recycling Principle

The following will analyze the Android operating system resource management mechanism from the application Framework and Linux kernel two levels.

The reason why Android uses a special resource management mechanism is that it is designed to target mobile terminals, and all available memory is limited to system RAM, and the corresponding optimization scheme must be designed for this limitation. When the Android application exits, it does not clean up the memory it consumes, and the Linux kernel process continues to exist, so-called "quit without shutting down". This allows the user to get a response at the first time when invoking the program. When system memory is low, the system activates the memory reclamation process. To ensure that the user experience is not affected by memory reclamation (such as killing the current active process), Android is based on the components that are running in the process and its status, which specifies the default five recycling priorities:

Importance_foreground:

Importance_visible:

Importance_service:

Importance_background:

Importance_empty:

The order of recovery for these priority levels is Empty process, Background process, Service process, Visible process, Foreground process. See the http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html file for the partitioning principle.

Activitymanagerservice centrally manages memory resource allocations for all processes. The Activitymanagerservice object must be called before all processes need to request or free memory before the next action can be obtained, or activitymanagerservice will "do it" directly. Several important member methods in class Activitymanagerservice that involve memory reclamation are as follows: Trimapplications (), updateoomadjlocked (), activityidleinternal (). These member methods are primarily responsible for the Android default memory recovery mechanism, and if the memory recycling mechanism in the Linux kernel is not disabled, the default recycle is skipped.

Default Recycle process

Memory recycling in the Android operating system can be divided into two levels, that is, the default memory recovery and kernel-level memory recovery, this chapter focuses on the default memory recycling mechanism to study, the Linux kernel layer of memory recycling mechanism will be described in the next. All code in this chapter can be found in Activitymanagerservice.java.

Recycle Action entry: activityidleinternal ()

The trigger point for memory recovery in Android is broadly divided into three scenarios. First, the user program calls StartActivity () to make the currently active activity overwritten; second, the user presses the back key to exit the current application; third, start a new application. The function interfaces that are ultimately called by these events that trigger memory reclamation are activityidleinternal (). When Activitymanagerservice receives an asynchronous message idle_timeout_msg or Idle_now_msg, activityidleinternal () is called. The code is as follows:

Listing 1. How to handle idle_now_msg
Case idle_now_msg:{  IBinder token = (ibinder) msg.obj;     Activityidle (token, null);  }  Break
Listing 2. How to handle idle_timeout_msg
Case IDLE_TIMEOUT_MSG: {  if (mdiddexopt) {         mdiddexopt = false;         Message nmsg = Mhandler.obtainmessage (idle_timeout_msg);         Nmsg.obj = msg.obj;         Mhandler.sendmessagedelayed (nmsg, idle_timeout);         return;     }     IBinder token = (ibinder) msg.obj;     SLOG.W (TAG, "Activity idle timeout for" + token);     Activityidleinternal (token, true, NULL);  }  Break

Idle_now_msg by the activity switch and activiy focus changes and other events, idle_timeout_msg in the event startup timeout, the general timeout is set to 10s, if 10s within a Activit Y still does not start successfully, the asynchronous message idle_timeout_msg is sent for resource recycling. The main task of activityidleinternal () is to change the status information of the Activity in the system and add it to a different state list. Its main work is as follows:

First, call the Scheduleappgcslocked () method to notify all the in-progress tasks to be garbage collected. Scheduleappgcslocked () will schedule the JVM's garbage collect to reclaim a portion of the memory space, only to notify each process of its own process garbage check and schedule the collection time, rather than synchronous reclamation. Then, remove all the contents of the Mstoppingactivities and Mfinishigactivities lists, temporarily in the temporary variable. These two lists store the activity object with the current status of stop and Finishi, respectively. For the stop list, if the activity's finish status is true, determine whether to stop immediately, call Destroyactivitylocked () to notify the target process to call the OnDestroy () method if you want to stop immediately, or call R first Esumetopactivity () runs the next Activity. If the finish status is false, calling stopactivitylocked () notifies the client process to stop the activity, which typically occurs after calling StartActivity (). For the finish list, call destroyactivitylocked () directly to notify the client process to destroy the target Activity.

The destroyactivitylocked function here does not really change the use of memory, just change its state to "allow recycling", and really recycle it in the trimapplications () function that is about to be called below.

Recycle process function trimapplications ()

The structure of the trimapplications () function is as follows:

Listing 3. trimapplications function
Private final void Trimapplications () {  synchronized (this) {         //First remove any unused application processes SE package         //have been removed.         For (I=mremovedprocesses.size ()-1; i>=0; i--) {            (1)//kill process;         }           if (!updateoomadjlocked ()) {            (2)//do something default         }         //Finally, if there is too many activities now Runn ING, try to         //finish as many as we can-get back to the limit.            (3) Do something     }  }

The positions of the three ordinal numbers in Listing 3 are respectively responsible for the following tasks:

(1) When the program executes to Trimapplications (), first check the process in the Mremovedprocesses list. The Mremovedprocesses list mainly contains the process of crash, the process that is not responding within 5 seconds and is selected by the user for forced shutdown, and the process that the application development calls Killbackgroundprocess want to kill. Call process.killprocess to kill all such processes.

(2) Call the updateoomadjlocked () function, if successful return, the Linux kernel supports the SETOOMADJ () interface, updateoomadjlocked will modify the value of Adj and notify the Linux kernel, the kernel according to the Adj value and memory Dynamically Manage process resources (Lowmemorykiller and Oom_killer) in a situation. If updateoomadjlocked () returns false, the current system does not support the Setoomadj () interface and the default resource collection will be done locally.

(3) Finally, if too much activity is currently running, the excess activity is recycled. Most of the code for Trimapplications () is in the process of disposing of the default resource collection that Oom_killer does not exist, and the following is a further analysis of its default recycling process (that is, the location of the Code listing (2)). The recycling process can be described as follows.

 

Step one, gets the collation of all currently running processes in mlruprocesses,mlruprocesses by the most recent usage time. The processes that cannot be closed in mlruprocesses are counted, and the processes that cannot be closed include the process that runs the service, the process that runs broadcast receiver, and so on, as shown in the following code.

Listing 4. Counting processes that cannot be closed
if (app.persistent | | app.services.size ()! = 0             | | App.curreceiver! = NULL             | | app.persistentactivities > 0) {
   //Don ' t count processes holding services against our     //maximum process count.         numserviceprocs++;  }

Step two, set the current maximum number of running processes Curmaxprocs = Curmaxprocs + Numserviceprocs (that is, the default maximum number of processes and the number of processes running the Service), if the number of current processes Mremovedprocesses.size () is larger than this value, traversing all currently running processes, killing those processes that meet the criteria, and freeing up memory. The cleanup process is shown in Listing 5 (part of the code omitted). As you can see from the code in Listing 5, the condition that the process is killed is:

    • It must be a non-persistent process, not a system process;
    • Must be an empty process, that is, no activity exists in the process. If the Activity process is killed, it is possible to close the program that the user is using, or to make the application recover more time-delayed, thereby affecting the user experience;
    • There must be no broadcast receiver. Running broadcast receiver is generally waiting for an event to occur, and the user does not want such programs to be forcibly shut down by the system;
    • The number of service in the process must be 0. The existence of a service process is likely to provide some kind of services, such as GPS location services, for one or more programs. Killing such a process will cause other processes to not service properly.

The above conditions are indispensable.

Listing 5. Cleanup process
 if (!app.persistent && app.activities.size () = = 0 && app.curreceiver = = null && app.services.size () = = 0) {if (app.pid > 0 && app.pid! = my_pid) {Pro         Cess.killprocess (APP.PID);             } else {try {app.thread.scheduleExit ();             } catch (Exception e) {//Ignore exceptions. }}//Todo:for Now we assume the application are not buggy//or evil, and would quit as a result         of our request.         Eventually we need to drive this off of the death//notification, and kill the process if it takes too long.         Cleanupapplicationrecordlocked (app, False, I);  i--; }

Step three, check the currently running process again, and if Mremovedprocesses.size () is still greater than curmaxprocs, then the relaxation condition is recycled again. The judging conditions are shown in Listing 6 (part of the code omitted). In the following code, when the value of the Boolean variable canquit is true, the process can be recycled. The value of Canquit is divided into two steps, first of all based on the properties of the process. 1. Must be a non-persistent process, that is, not a system process; 2. There must be no broadcast receiver;3. The number of service in the process must be 0;4. The number of activity for the persistent type is 0. Unlike step two, the only difference is in 4th, where the process is not required to be empty, as long as there is no persistent type of activity in the process (activity is persistent type specified in development phase). When these conditions are met, then the properties of each activity in the process are checked, and all activity in the process must also meet three conditions: The activity's state has been saved, is currently in an invisible state, and the activity has been Stop. At this point the kill process will only slow down the next time the program is loaded, the next time it will be restored to the state before shutdown, and will not have a fatal impact on the user experience, so the Canquit is set to true. This is also different from the method of recovery of step two, because the number of activity in the process is not 0, the next step is to perform destroyactivitylocked () destruction on each activity, and then kill the process.

Listing 6. Perform destroyactivitylocked () destruction
 Boolean canquit =!app.persistent && app.curreceiver = null && APP.SERVICES.S  ize () = = 0 && app.persistentactivities = = 0;  int NUMA = App.activities.size ();     for (j=0; J<numa && Canquit; j + +) {Historyrecord R = (Historyrecord) app.activities.get (j);  Canquit = (R.havestate | |!r.statenotneeded) &&!r.visible && r.stopped;     } if (Canquit) {//Finish all of the activities, and then the app itself.         for (j=0; j<numa; J + +) {Historyrecord R = (Historyrecord) app.activities.get (j);         if (!r.finishing) {destroyactivitylocked (R, False);     } R.resultto = null;     } if (App.pid > 0 && app.pid! = my_pid) {process.killprocess (app.pid);     } cleanupapplicationrecordlocked (app, False, I);     i--;  Dump (); }

Step four, the above 3 processes are resource recycling for the entire process. After the above process has been completed, the resource of the Activity will be recycled at a much smaller granularity. Similar to the above, the list Mlruactivities stores all currently running Activity, with the same collation as the least access principle. Mlruactivities.size () returns the number of Activity that is running in the system when it is greater than max_activities (Max_activities is a constant with a general value of 20, which represents the maximum allowable simultaneous presence of the system Activity). The Activity that partially satisfies the condition is recycled to reduce memory usage. The recycle condition code is shown in Listing 7:

Listing 7. Recycle condition Code
Finally, if there is too many activities now running, try to  //finish as many as we can-get back to the Li MIT.  for (   i=0;         I<mlruactivities.size ()             && mlruactivities.size ()  > curmaxactivities;         i++) {  final historyrecord R         = (Historyrecord) mlruactivities.get (i);     We can finish this one if we has its icicle saved     and//It's not persistent.     if ((r.havestate | |!r.statenotneeded) &&!r.visible             && r.stopped &&!r.persistent && amp;!r.finishing) {         final int origsize = Mlruactivities.size ();         Destroyactivitylocked (R, True);         if (origsize  > Mlruactivities.size ()) {             i--;         }     }  }

Only the memory resources of the Activity are recycled, and the process is not killed and the process is not affected. When the process needs to invoke the Activity that was killed, it can reply from the saved state, which of course may require a relatively long delay.

Memory recycling in the Linux kernel Lowmemorykiller

As mentioned above, a function called updateoomadjlocked () is executed in the trimapplications () function, and if False is returned, a default recycle is performed, and if True does not perform a default memory reclamation. updateoomadjlocked will update a variable named adj for each process and inform the Linux kernel that the kernel maintains a data structure that contains adj (that is, the process table) and checks the system memory usage by Lowmemorykiller. Kill some processes and free memory in case of low memory. The following is a study of the memory-recycling mechanism that matches this Android Framework with the Linux kernel.

Since all applications in the Android operating system are running in a standalone Dalvik virtual machine environment, the Linux kernel cannot know the running state of each process and cannot maintain an appropriate Adj value for each process, so Android application The Framework must provide a set of mechanisms to dynamically update the adj of each process. This is updateoomadjlocked ().

Updateoomadjlocked () is located in Activitymanagerservice, whose primary role is to select a suitable adj value for the process and notify the Linux kernel to update the value. Updateoomadjlocked first calls computeoomadjlocked () to calculate the value of the Adj, and then returns to Updateoomadjlocked () to further revise its value. The estimation process can be found in the code.

About adj, which is defined in Task_struct->signal_struct->adj, file/kernel/include/linux/sched.h. The substance is a variable in the process data structure that represents the order of precedence of the kill process when an out of Memory occurs. Lowmemorykiller uses this variable to judge the importance of the process and to free up some space when the memory is low, in fact the file is now/kernel/drivers/staging/android/lowmemorykiller.c. Lowmemorykiller defines two arrays: Lowmem_adj and Lowmem_minfree. Where Lowmen_adj defines a series of Adj key values, and each element of Lowmem_minfree represents a memory threshold value. The following code four thresholds are 6MB,8MB,16MB and 64MB, respectively, when the memory is less than 64MB, adj greater than or equal to 12 of those processes will be killed and recycled, memory less than 16MB, adj greater than or equal to 6 of those processes will be killed and recycled, memory less than 8MB , those processes with adj greater than or equal to 1 will be killed and recycled, and when the memory is less than 6MB, all processes adj greater than or equal to 0 will be killed and recycled. Each process in the kernel holds a adj with a value range of 17 to 15, the smaller the value, the higher the importance of the process, and the lower the recycling priority, where 17 means that auto-reclamation is disabled. Only 0-15 of the Android system is used.

Listing 8. Each process holds a adj
static int Lowmem_adj[6] = {         0,         1,         6,         N,  };  static int lowmem_adj_size = 4;  Static size_t lowmem_minfree[6] = {         3 * 8MB,/      * 6MB */         2 * 1024x768,///         4 * 1024x768,/     * 16MB */         * 1024x768,/* 64MB */  };  static int lowmem_minfree_size = 4;

Lowmemorykiller Register a Lowmem_shrinker,lowmem_shrinker is implemented using the Cache Shrinker in the standard Linux kernel, and when the free memory page is low, the kernel thread KSWAPD will use the registered Lo Wmem_shrinker to reclaim memory pages.

Listing 9. Reclaim memory pages with registered Lowmem_shrinker
static struct Shrinker Lowmem_shrinker = {                     . Shrink = Lowmem_shrink,         . seeks = Default_seeks * +  };  static int __init lowmem_init (void)  {         task_free_register (&TASK_NB);         Register_shrinker (&lowmem_shrinker);         return 0;  }

The Lowmem_shrink code is in the function Lowmem_shrink, and the main structure of the function is given below. Lowmem_shrink iterates through all processes according to the above rules, selects the processes that need to be closed, and forces the end of these processes by sending a signal that cannot be ignored SIGKILL

Listing 10. Force End Process
static int Lowmem_shrink (struct shrinker *s, int nr_to_scan, gfp_t gfp_mask)  {         for_each_process (p) {            // Select processes to be forced          }         if (selected) {                Force_sig (SIGKILL, selected);                REM-= selected_tasksize;         } else         rem =-1;         return REM;  }
Oom_killer.

If none of the above methods can free up enough memory space, then an out of memory exception will occur when the application is allocated for the new process, and Oom_killer will make the final effort to kill some processes to free up space. The Oom_killer in Android inherits from the standard Linux 2.6 kernel, which is used to allocate memory for the processing of the memories. Android does not modify the way it is implemented. Its position is in the linux/mm/oom_kill.c. Oom_killer iterates through the process and calculates the badness value of all processes, choosing badness the largest process to kill it. The declaration of the function badness is as follows:

unsigned long badness (struct task_struct *p, unsigned long uptime) function select_bad_process returns the process that will be killed.

Listing 11. Return to the process that will be killed
static struct task_struct *select_bad_process (unsigned long *ppoints,                                             struct mem_cgroup *mem)  {         For_each_ Process (p) {                points = badness (P, uptime.tv_sec);                if (Points > *ppoints | |!chosen) {                        chosen = p;                        *ppoints = Points;                }         }         return chosen;  }

Finally, as with Lowmemorykiller, the selected process is ended by sending SIGKILL. Since Oom_killer is no different from the standard Linux kernel, it is no longer studied in detail.

Summarize

This paper studies the mechanism of memory recovery on the Android operating system. This includes the default recycling of the application Framework layer and the Lowmemorykiller, Oom_killer in the Linux kernel. In general, application developers do not need to control or modify the system's memory management and recycling, but in-depth understanding of these system-level management mechanisms is still necessary, especially to more reasonable design of the application, so that the application process in its life cycle of efficient operation. However, if the system-level developers want to optimize the memory management mechanism, the understanding of the original mechanism is an essential prerequisite.

Memory recovery mechanism for Android OS [go]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.