[Samsung Galaxy S9 & S9+ Cross Device Development] ianmacd:
APGK - A Pretty Good Kernel

"Another kernel for the S9/S9+? Why? Aren't they all more or less the same?"

This kernel exists, because I couldn't find quite the right kernel for my device: one that was conservative enough in its feature set to favour stability over the inclusion of experimental code, yet one bold enough not to shy away from embracing low-risk self-contained enhancements. The concept is an obvious one, yet no other kernel for the S9/S9+ catered to this market, something that holds true to this day.

APGK differentiates itself from the alternatives by striking a happy medium between the standard Samsung kernel and some of the more adventurous alternatives, without compromising on the original's stability.

To that end, APGK judiciously draws from the work of others, cherry-picking only the juiciest and safest fruit from several sources, including, but not limited to the ElementalX and now defunct Notorious kernels.

Every development decision is carefully weighed, eschewing changes that could affect stability, either by pushing the device's tolerances to their limits or by introducing features whose potential usefulness is outweighed by the danger posed by their invasive nature. Patches that are not widely understood and whose effects are difficult to predict and/or measure after application do not make it into APGK's code base. I personally verify the scope and correct working of everything that I include.

The finished kernel is packaged in a custom-built installer, which offers a choice between hands-free and interactive installation. Automatic post-installation rooting with Magisk is also offered as a convenience.

"Why is this kernel called APGK?"

The full name is actually A Pretty Good Kernel. I did consider a few others and even delayed the initial release of the kernel in the pursuit of the perfect name, but at the end of the day, a name is just a name; and, to paraphrase Shakespeare, a kernel by any other name would be just as dull.

Importantly, the acronym APGK is easy to type and easy to say. And, as luck would have it, A Pretty Good Kernel happens to be a reasonable, modest description of what this project actually is. If you want a kernel called Testosterone or High Octane Rocket Fuel, you'll have to look elsewhere.

Key characteristics

Forked from a clean exynos-linux-stable (ELS) base (Linux 4.9.109 at project launch).

Updated with regular merges of the upstream Linux kernel, the android-4-9-o tree and updates to the stock Samsung kernel (downstreamed from ELS until v0.99.33; manually merged since then).

Packed into a boot.img (boot image) taken directly from Samsung's latest stock firmware and kept as close to the original as possible. No obscure boot-time kernel configuration is stashed away here, and no changes are made to any other part of the file system at either install time or run time. No kernel has any business touching any part of your device's file-system. APGK religiously adheres to this principle and is fully transparent.

Provides a fully automated installer, with the option of interactive installation to allow manual selection of features, and the ability to automatically root the device with Magisk in the post-installation phase.

Comes in standard, underclocking and overclocking flavours. Choose the kernel that fits your usage profile.

Removes a large number of debugging and logging features that bloat a release kernel and make it unnecessarily noisy.

Enabled extra Deadline I/O scheduler. The default scheduler remains CFQ.

Includes WireGuard VPN support (version 0.0.20180613 at the time of launch), which is regularly updated as available.

Includes @Lord Boeffla's generic kernel wakelock blocker. The default block-list is: wlan_rx_wake, wlan, wlan_wow_wl, wlan_extscan_wl, netmgr_wl and NETLINK.

Utilises Westwood+ TCP congestion algorithm by default (as of v0.99.27; previous versions used BIC).

Includes Veno TCP congestion algorithm (as of v0.99.27).

Includes @flar2's Sweep2Wake, DoubleTap2Wake and Sweep2Sleep wake gestures.

Includes @flar2's RGB colour control override.

Includes Paolo Valente's BFQ (Budget Fair Queuing) I/O scheduler (v8r7) (based on CFQ).

Includes Shaohua Li's FIOPS (Fair Input/Output) scheduler (based on CFQ).

Includes Miguel Boton's SIO (Simple Input/Output) scheduler (based on Noop, Deadline and V(R) IO).

Includes Brandon Berhent's Zen I/O scheduler (based on Noop, Deadline and SIO).

Includes Joe Maples' eponymous Maple I/O scheduler (based on Zen and SIO).

SELinux operates in enforcing mode and (as of 0.99.7) cannot be dynamically switched to permissive mode.

FAQ

Q. Is this kernel still actively developed?

A. No. Version 1.0.56 was the final ianmacd release on 16th November 2019. No other person has come forward to take over maintenance of the project.

Q. Can I overclock or underclock the CPU using this kernel?

A. Yes.

The underclocking kernel is identical in specification to the one offered by ElementalX: the big cluster CPU (Samsung Mongoose 3) is limited to 2.314 GHz instead of the usual 2.704 GHz. If you need to maximise the amount of time the device can last on a single battery charge, this may be the kernel variant for you. It comes at the expense of a small performance penalty that you may not even notice in practice.

The overclocking kernel is a little more involved. This kernel will boost the maximum frequency of the big cluster CPU to 2.964 GHz from the usual 2.704 GHz (2.496 GHz vs. 2.314 GHz in dual mode; 2.002 GHz vs. 1.794 GHz in triple/quad mode). This is slightly higher than the boost provided by ElementalX's overclocking kernel, which provides for frequencies up to 2.886 GHz. Additionally, APGK's overclocking kernel will boost the small cluster 's (ARM Cortex-A55) maximum frequency to 2.002 GHz from the usual 1.794 GHz. This is identical to ElementalX's mode 2 overclocking behaviour.

Furthermore, APGK's overclocking kernel also features GPU overclocking. The Mali-G72 GPU has its maximum frequency boosted to 598 MHz from 572 MHz, and its minimum frequency boosted to 299 MHz from 260 MHz. This is identical to the behaviour of the Notorious kernel in its final release before being abandoned. Gamers in particular may appreciate the slight performance increase this provides.

It should go without saying that the overclocking kernel will incur, at a minimum, a small battery performance penalty. Whether the gains outweigh the cost will depend on individual usage and is for the user himself to determine. Furthermore, there may be an additional tax to pay in the form of reduced device stability. The overclocking kernel has proven 100% stable on my S9+ during testing, but it is entirely possible that individual units may demonstrate a lower tolerance. If you find your device spontaneously rebooting on the overclocking kernel, simply revert to using the standard kernel.

To install the underclocking kernel instead of the standard kernel, either create a file on your external SD card called .apgk_underclock or rename the APGK archive to contain _underclock in the name.

Similarly, to install the overclocking kernel instead of the standard kernel, either create a file on your external SD card called .apgk_overclock or rename the APGK archive to contain the string _overclock.

Then, simply install APGK as usual. The installer will infer your wishes from the renamed ZIP file or the presence of the dot-file and install the appropriate kernel. On-screen messages will confirm that the correct kernel is being installed.

As an alternative to providing hints to the installer via the file-system, you may prefer to utilise interactive installation mode. See below for details.

Use MTweaks or EX Kernel Manager to verify the modified CPU and GPU frequencies, and look for either the -uc or the -oc suffix to the kernel's name (obtainable, for example, with uname -a) to indicate that you have installed the underclocking or the overclocking variant, respectively.​

Q. Can I run SELinux in permissive mode with this kernel?

A. No. APGK's SELinux mode was enforcing by default until version 0.99.7, at which time this became the only permitted mode. It is no longer possible to dynamically switch to permissive mode after booting.

Despite what some others may tell you, running SELinux in permissive mode is a terrible idea, because it makes it much easier for a process with elevated privileges to wreak havoc on your device. Not only that, permissive mode is almost never actually necessary to achieve the goal that the user is pursuing.

If you believe that you cannot get by without SELinux in permissive mode, you can simply recompile APGK from source with the feature enabled. The GPL is a wonderful thing.​

Q. How does interactive installation mode work?

A. If the ZIP file name contains the string _interactive or a dot-file called .apgk_interactive is present in the root of the external SD card, interactive installation mode is triggered. Selections made in this mode will overrides any implied by the archive name or the presence of dot-files on the file-system.

In interactive mode, you will be asked questions regarding which kernel to install and whether to root the device afterwards with Magisk. Selections are made using the Bixby and Volume buttons. Just follow the on-screen prompts.​

Q. Can I safely use I/O scheduler X?

A. Maybe. Probably even. Although no guarantee of any kind is provided regarding the usability of this kernel, you should experience no problems whatsoever using the default I/O scheduler (CFQ). Others are configured at your own risk and may yield degraded performance.​

Q. Can I safely block wakelock X?

A. Again, perhaps. However, unless you know what a particular wakelock does and and have determined that it is causing an actual problem on your device, I suggest you leave it alone.​

Q. Is this kernel safe to use? Who are you, anyway? Can you be trusted?

A. At the height of its popularity, well over 100 people were using APGK as their kernel of choice. I have personally used nothing else on my S9+ since June 2018.

APGK went through almost 40 public beta releases and an untold number of internal test builds over a 6 month period before finally seeing its stable v1.0.0 release on New Year's Eve 2018. That was followed by a further 56 stable releases, so this kernel has proven itself in the field.

As the maintainer of APGK, I know exactly what's in it. The only risk I'm exposing myself to when I run it is that of my own incompetence, i.e. the possibility that I've made a mistake somewhere. You, however, don't know who you're dealing with and should therefore exercise due caution and at least pause for a moment to consider what you're installing, and the far-reaching powers you are about to grant this unaudited code over your device. Although I provide a link to the source code below, you have only my word for it that this code bears any relationship to the kernel actually provided in the installer.

Please see the Installation section below for an important note regarding the use of this kernel in combination with unmodified Samsung firmware.
​

Q. Does this kernel also work on Android 9 (Pie)?

A. It would, if someone were to go to the trouble of merging Samsung's Android 9 kernel sources, building APGK against them and packaging the resulting kernel inside a boot image modified from the one supplied with Samsung's official Android 9 firmware. During my ownership of an S9+, I chose not to update it to Android 9, however, and was therefore unable to test kernels built for that version of the operating system. For that reason, official APGK builds continued to target Android 8.0 (Oreo).​

Q. Can I safely root this kernel?

A. Of course. What use would it be if you couldn't? I recommend Magisk for the task. Magisk has matured to the point that it is now the de facto root solution for Android devices.

It just so happens that I also produce my own builds of Magisk, which you are welcome to use. These are release builds (as opposed to debugging builds) and are produced from my own fork of @topjohnwu's original source code, sometimes augmented with patches. You can use anyone's builds, though.

Again, these builds work for me on various Samsung devices, but you should approach them with the appropriate caution.​

Q. Can I auto-root the APGK kernel with Magisk at installation time?

A. As of version 0.99.19, yes. This feature was extended and improved over the next few versions and is now mature.

To make use of this facility, either rename the APGK zip file to contain the string _magisk or create a file called .apgk_magisk in either the root of your external SD card or in the standard Download directory of the internal SD card. Alternatively, you may utilise interactive installation mode. See above for details.

If any of these trigger conditions is met, the installer then looks in the standard internal Download directory as well as in ./Magisk (if present) on the external SD card (if present) for a suitable Magisk zip file to install. Preference is given to versioned files matching the glob Magisk-v*, in which case the latest according to lexical sort order will be used. If none is found, the installer then looks for unversioned release builds (e.g. official Canary channel release builds) called magisk-release.zip in the same locations, selecting the one with the most recent timestamp. If none is found, the installer will then try to find unversioned debug builds (e.g. official Canary channel debug builds) called magisk-debug.zip, again picking the one with the most recent timestamp. Finally, the installer falls back to looking for the most recent file called Magisk.zip or magisk.zip. If still no files have been found by this stage, chaining of Magisk is abandoned.

For example:

star2lte:/ $ ls -l /storage/0000-0000/.apgk_magisk
-rwxrwx--x 1 root sdcard_rw 0 2018-09-15 14:31 /storage/0000-0000/.apgk_magisk
star2lte:/ $ ls /storage/0000-0000/Magisk/Magisk-* | tail -n 3
/storage/0000-0000/Magisk/Magisk-v17.2-2018091001-ianmacd.zip
/storage/0000-0000/Magisk/Magisk-v17.2-2018091201-ianmacd.zip
/storage/0000-0000/Magisk/Magisk-v17.2-2018091501-ianmacd.zip

When you flash the APGK archive in TWRP, the most recent version of Magisk that could be found will now be used to automatically root your kernel, i.e. Magisk-v17.2-2018091501-ianmacd.zip in this example.​

Q. Can I use this kernel on an 'N' (Korean) model device?

A. At least one user has reported success flashing this kernel onto an 'N' model device. Since version 0.99.17, the APGK installer allows flashing onto the G960N/G965N.​

Q. Why doesn't APGK have its own Telegram group?

A. Because it has been my experience that Android-themed Telegram groups invariably degenerate into seething cesspits of ignorance, superstition and — on a good day — pseudo-science. I don't wish to police or even inhabit such a forum. Of course, it's a free world (or so I still like to tell myself), so you are at liberty to create your own Telegram group for APGK if you wish. Just please don't invite me to it.
​

Building

Building a kernel is beyond the scope of this document. If you really want to build this kernel from scratch, start with this handy reference tailored to building kernels for Android.

Download

See posting #2 in this thread for links to the latest and all previous versions.

Installation

Make a back-up of your existing boot partition using the custom recovery environment provided by TWRP. If your device doesn't yet have TWRP, you will need to install that first. Then, use TWRP to flash the APGK ZIP file. The boot image will automatically be installed in the boot partition.

If your device has unmodified Samsung firmware, you will encounter problems with Bluetooth (namely delayed initiation and forgotten pairings) after installing this or any other custom kernel. To remedy this, you will need to patch your system with modified libsecure_storage.so libraries. Some custom kernel installers actually silently install these without your permission, overwriting your system libraries and transparently circumventing the problem before you can run into it. This approach necessarily modifies your device's file-system, however, which may not be what you want. At the very least, the user should be made aware what is happening to his device.

For this reason, I have instead prepared a companion Magisk module that achieves the same goal without modifying the file-system. This will allow you to run a custom kernel (not just this one, but any custom kernel) on pristine stock firmware without any Bluetooth issues. The module is attached to this posting for your convenience, but can also be found in the official Magisk module repository, accessible from Magisk Manager on your phone. If you use this Magisk module, you may wish to also disable the secure_storage_daemon by editing /system/etc/init/secure_storage_daemon.rc (change start to stop), as it no longer serves a purpose.

In a similar vein, you may encounter authentication errors when connecting to wireless networks after installing this or any other custom kernel. This problem is not serious, and easily remedied by re-entering your passphrase for any affected networks.

Finally, if SecurityLogAgent notifies you that unauthorised actions have been detected, do not be alarmed. This is a normal consequence of having installed a custom kernel. You may wish to disable SecurityLogAgent to avoid being repeatedly notified. Most custom ROMs and some kernel installers simply remove it, but again, I leave this up to the user.

If the above issues sound like more trouble than they're worth, you may be happier simply sticking to Samsung's stock kernel, which, in the case of the S9 and S9+ at least, is a perfectly good kernel.

Configuration

You are encouraged to use either MTweaks (a modified version of Kernel Aduitor) or EX Kernel Manager to manage the features provided by this kernel.

Source code

APGK's GitHub repository.

References

A useful overview of Android I/O schedulers.

The same author has produced a guide to CPU governors, I/O schedulers (and more).

For more information on the some of the individual schedulers included in this kernel, you can also look under Documentation/block in the kernel source.

Additionally, Documentation/cpu-freq/governors.txt may be interesting for exhaustive information on the Linux CPUFreq governors, although APGK has abandoned support for all but schedutil as of version 0.99.11.

The WireGuard user guide, control app, home page and source code.

The ELS source code.

The ElementalX home page, source code and XDA thread.

The Notorious source code and XDA thread. The Notorious project is now defunct.

The BFQ home page.

Credits

Thank you to everyone in the wider Linux kernel universe for getting us this far. Closer to home, I am grateful to the following Android luminaries for their considerable, ongoing contributions:

@Farovitus for providing and maintaining ELS, his dedication to experimentation in Notorious, and his permanent good grace and willingness to help other people.

@AndreiLux for the insights arising from his journey to the centre of the G96X kernel.

@osm0sis for Android Image Kitchen, which has saved me a huge amount of work in packing and unpacking boot images.

An honorary mention is due to @Chainfire, the extent of whose benefaction to the Android community is still not fully understood or appreciated in some quarters.

Thanks also to [MENTION=7281938]Maxiroe1912[/MENTION] for his help with testing the G960F build of 0.99.2, the dual installer ZIP, and the libsecure_storage kernel companion Magisk module.​