X

News, tips, partners, and perspectives for the Oracle Linux operating system and upstream Linux kernel work

Recent Posts

Announcements

Partner: Microsoft @ Oracle OpenWorld

We are happy to welcome our partner, and conference Bronze Sponsor, Microsoft to Oracle OpenWorld 2019. There are many exciting things you will want to learn about the areas of collaboration between companies. To begin, please visit Microsoft representatives at The Exchange, in Moscone South, booth #1511. For more in-depth information, make sure to register for these sessions: Monday, September 16, 11:15 AM - 12:00 PM | Moscone South - Room 151D Oracle on Azure: An Overview [CON6620] Speakers: Romit Girdhar, Senior Software Engineer, Microsoft Edward Burns, Principal Architect, Microsoft Monday, September 16, 01:45 PM - 02:30 PM | Moscone South - Room 210 Microsoft Azure and Oracle Cloud Infrastructure: Seattle's Newest Power Couple [BUS3362] Speakers: FS Nooruddin, Vice President Information Technology, Gap Inc. Umakanth Puppala, Program Manager, Microsoft Chinmay Joshi, Principal Product Manager, Oracle Monday, September 16, 02:45 PM - 03:05 PM | The Exchange Lobby (Moscone South) Elevating Your Multicloud Strategy: Azure and Oracle Cloud Infrastructure Interconnect [THT6633] Speakers: Umakanth Puppala, Program Manager, Microsoft Chinmay Joshi, Principal Product Manager, Oracle Wednesday, September 18, 10:00 AM - 10:45 AM | Moscone South - Room 155C Connecting Oracle Cloud to Microsoft Azure: Technical Deep-Dive and Demo [CON6696] Speakers: Romit Girdhar, Senior Software Engineer, Microsoft Chinmay Joshi, Principal Product Manager, Oracle Oracle OpenWorld is the perfect opportunity to immerse yourself in all that’s new with Oracle and Microsoft.  

We are happy to welcome our partner, and conference Bronze Sponsor, Microsoft to Oracle OpenWorld 2019. There are many exciting things you will want to learn about the areas of collaboration...

Announcements

Partner: Lenovo @ Oracle OpenWorld 2019

The Oracle Linux and Virtualization team, on behalf of Oracle, is delighted to welcome Platinum Sponsor Lenovo to Oracle OpenWorld 2019. Lenovo works closely with us to certify their hardware, through the HCL program, to run our software. Please be sure to attend our joint session: Monday, September 16, 02:45 PM - 03:30 PM | Moscone South - Room 152D Data-Driven to Insight-Driven Transformation by Oracle Autonomous Database [CON4565] This session discusses how Oracle Autonomous Database and Oracle Linux on Lenovo infrastructure enables this digital transformation through insight-driven analytics, eliminating the manual task of database patching and upgrades, reducing human error, and increasing productivity. Speakers: Michele Resta, Sr Director, Oracle Prasad Venkatachar, Sr Solutions Product Manager, Lenovo (United States) Inc. You can also meet Lenovo representatives at The Exchange, in Moscone South, booth #1211. While you’re there, check out the theater schedule for a joint presentation by the Oracle Linux and Virtualization team and Lenovo on the companies’ alliance.                                                                                                                                                  

The Oracle Linux and Virtualization team, on behalf of Oracle, is delighted to welcome Platinum Sponsor Lenovo to Oracle OpenWorld 2019. Lenovo works closely with us to certify their hardware, through...

Linux Kernel Development

Soft Affinity - When Hard Partitioning Is Too Much

Scheduler Soft Affinity Oracle Linux kernel developer Subhra Mazumdar presents a new interface to the Linux scheduler he is proposing. Servers are getting bigger and bigger with more CPU cores, memory and I/O. This trend has lead to workload consolidation (e.g multiple virtual machines (VMs) and containers running on the same physical host). Each VM or container can run a different instance of the same or different workload. Oracle Database has a similar virtualization feature called Oracle Multitenant where a root Database can be enabled to act as a Container Database (CDB) and house multiple lightweight Pluggable Databases (PDBs), all running in the same host. This allows for very dense DB consolidation. Large servers usually have multiple sockets or NUMA (Non Uniform Memory Access) nodes with each node having its own CPU cores and attached memory. Cache coherence and remote memory access is facilitated by inter-socket links (QPI in case of Intel) but usually much more costlier than local access and coherence. When running multiple instances of a workload in a single NUMA host, it is good practice to partition them e.g give a NUMA node partition to each DB instance for best performance. Currently the Linux kernel provides two interfaces to hard partition instances: sched_setaffinity() system call or cpuset.cpus cgroup interface. This doesn't allow one instance to burst out of its partition and use potentially available CPUs of other partitions when they are idle. Another option is to allow all instances to spread across the system without any affinity, but this suffers from a cache coherence penalty across sockets when all instances are busy. Autonuma Balancer One potential way to achieve the desired behavior is to use the Linux autonuma balancer which migrates pages and threads to align them. For example, if each DB instance has memory pinned to one NUMA node, autonuma can migrate threads to their corresponding nodes when all instances are busy, thus automatically partitioning them. Motivational experiments, however, show not much benefit is achieved by enabling autonuma. In this case 2 DB instances were run on a 2 socket system, each with 22 cores. Each DB instance was running an OLTP load (TPC-C) and had its memory allocated from one NUMA node using numactl. But autonuma ON vs OFF didn't make any difference. The following statistics show (for different number of TPC-C users) the migration of pages by autonuma, which didn't have any performance benefit. This also shows that numactl only restricts the initial memory allocation to a NUMA node and autonuma balancer is free to migrate them later. Below numa_hint_faults is the total number of NUMA hinting faults, numa_hint_faults_local is the number of local faults so the rest are remote and numa_pages_migrated is the number of pages migrated by autonuma. users (2x16) no affinity numa_hint_faults 1672485 numa_hint_faults_local 1158283 numa_pages_migrated 373670 users (2x24) no affinity numa_hint_faults 2267425 numa_hint_faults_local 1548501 numa_pages_migrated 586473 users (2x32) no affinity numa_hint_faults 1916625 numa_hint_faults_local 1499772 numa_pages_migrated 229581 Other disadvantages of autonuma balancer are a) it can be ineffective in case of memory spread among all NUMA nodes and b) can be slow to react due to periodic scanning. Soft Affinity Given the above drawbacks, a logical way to achieve the best of both worlds is via the Linux task scheduler. A new interface can be added to specify the scheduler prefer a given a set of CPUs while scheduling a task, but using other available CPUs if the preferred set is all busy. The interface can either be a new system call (e.g sched_setaffinity2() that takes an extra parameter to specify HARD or SOFT affinity) or by adding a new parameter to cpuset (e.g cpuset.soft_cpus). It is important to note that Soft Affinity is orthogonal to cpu.shares: the latter decides how many CPU cycles to consume while former decides where to preferably consume those cycles. Under the hood the scheduler will add an extra set, cpu_preferred, in addition to the existing cpu_allowed set per task. cpu_preferred will be set as requested by the user using any of the above interfaces and will be a subset of cpu_allowed. In the first level of search, the scheduler chooses the last level cache (LLC) domain, which is typically a NUMA node. Here the scheduler will always use cpu_preferred to prune out remaining CPUs. Once LLC domain is selected, it will first search the cpu_preferred set and then (cpu_allowed - cpu_preferred) set to find an idle CPU and enqueue the thread. This only changes the wake up path of the scheduler, the idle balancing path is intentionally kept unchanged: together they achieve the "softness" of scheduling. With such an implementation, experiments were run with 2 instances of Hackbench and then 2 instances of DB by soft affinitizing each instance to one NUMA node on a 2-socket system. Another set of runs were done with only 1 instance active but still soft affinitized to the corresponding node. The load in each instance of Hackbench or DB was varied by varying the number of groups and number of users respectively. The following graphs outline the performance gain (or regression) for hard affinity and soft affinity with respect to no affinity. Hackbench shows little improvement for hard or soft affinity (possibly due to less data sharing) while the DB shows substantial improvement for the 2 instance case. For 1 instance, Hackbench shows significant regression while DB achieves performance very close to no affinity. The DB seems to achieve best of both worlds with such a basic implementation: improvement like hard affinity and almost no regression like no affinity. Load Based Soft Affinity While basic impleme ntation of Soft Affinity above worked well for DB, Hackbench showed serious regression for 1 instance case due to not using CPUs in the system efficiently. This begs the question: should the decision to trade off cache coherence for CPUs be conditional? The optimum trade off point of a given workload will depend on amount of data sharing between threads, the coherence overhead of the system and how much extra CPUs will help the workload. Unfortunately the kernel can't find this online, offline workload profiling is needed to quantify the different cost metrics. A reasonable approach to solve this is having kernel tunables that will allow tuning for different workloads. Two scheduler related kernel tunables are introduced for this purpose: sched_preferred and sched_allowed. The ratio of CPU utilization of cpu_preferred set and cpu_allowed set is compared to the ratio sched_allowed:sched_preferred; if greater the scheduler will choose cpu_allowed set in the first level of search, if lesser it will choose the cpu_preferred set. Setting the relative values of the tunables Soft Affinity can be made "harder" or "softer". To compare the utilization of two sets we can't iterate over all CPUs as that will add significant overhead. Hence two sample CPUs are chosen, one from each set and compared. The same experiments were run with the new load based Soft Affinity. Following graphs have the tunable pair (sched_preferred, sched_allowed) sorted from softest to hardest value. As can be seen, for DB case, harder Soft Affinity works best similar to the previous basic implementation. For Hackbench, a softer Soft Affinity works best thereby preserving the improvements but minimizing the regression. A separate set of experiments were also done (graphs not shown) where memory of each DB instance was spread evenly among NUMA nodes. This had similar improvements thus proving that the benefit of partitioning is primarily due to LLC sharing and saving cross socket coherence overhead. Soft Affinity Overhead The final goal of Soft Affinity is to introduce no overhead if not used. The scheduler wake-up path adds a few more conditions but breaks early if cpu_preferred == cpu_allowed. This keeps overhead minimal as shown in the following graph which compares the performance of Hackbench for 1 and 2 instance case for a varying number of groups. The difference in the last column is actually the improvement of Soft Affinity kernel with respect to the baseline kernel. This is actually within the noise margin but proves that overhead of Soft Affinity is negligible. The latest version of Soft Affinity with load based tunables has been posted upstream, you can find it here: https://lkml.org/lkml/2019/6/26/1044

Scheduler Soft Affinity Oracle Linux kernel developer Subhra Mazumdar presents a new interface to the Linux scheduler he is proposing. Servers are getting bigger and bigger with more CPU cores, memory...

Announcements

Join Oracle Executives for Linux and Virtualization Sessions at Oracle OpenWorld 2019

With Oracle OpenWorld and Code One starting next week, you’ll want to have your schedule locked down soon. If the sessions below aren’t on your agenda, you’ll want to register and add them. These sessions are presented by Oracle’s Linux and Virtualization executives. In these sessions, you’ll hear from the technology leaders helping to foster innovation at Oracle. These executives envision, develop, and help build the products, services, and technologies that are enabling customers’ success – in the cloud and on premise. Join them to learn about the vision, strategies, and breakthroughs that are paving the way to a bold new future. Inspiration starts here. We look forward to seeing you at these sessions! Date/Time Title Speaker(s) Location Tuesday September 17     11:15 a.m. – 12:00 p.m. Oracle’s Open Cloud Infrastructure Strategy    Ajay Srivastava, Senior Vice President, Operating Systems and Virtualization, Oracle Moscone South Room 210   12:30 p.m. – 01:15 p.m. Cloud Platform and Middleware Strategy Roadmap    Edward Screven, Chief Corporate Architect, Oracle YCBA Theater 01:45 p.m. – 02:30 p.m. Oracle Linux : State of the Penguin    Wim Coekaerts, Senior Vice President, Linux and Virtualization Engineering, Oracle Moscone South Room 210 04:00 p.m. – 04:20 p.m. How to Get Started with Cloud Native   Karen Sigman, Vice President, Product and Partner Marketing The Exchange, Moscone South  Theater 1 Wednesday,    September 18     11:15 a.m. – 12:00 p.m.   Oracle's Infrastructure Strategy for Cloud and On-Premises   Wim Coekaerts, SVP, Linux and Virtualization Engineering Ali Alasti, SVP, Hardware Development, x86 Management Ajay Srivastava, SVP, Operating Systems and Virtualization YCBA Theater To learn more about Oracle Linux and Virtualization sessions, HOLs, and demo kiosks (at The Exchange), take a look at recent blogs. 

With Oracle OpenWorld and Code One starting next week, you’ll want to have your schedule locked down soon. If the sessions below aren’t on your agenda, you’ll want to register and add them. These...

Announcements

Two Places to Meet the Oracle Linux and Virtualization Team at Oracle OpenWorld

The Oracle Linux and Virtualization team will be out in force at Oracle OpenWorld. There is a lot in store for attendees. We look forward to sharing the latest updates and demoing the latest innovations. In addition to our sessions and Hands on Labs, there are two more places to find Linux and virtualization experts… 1. @ The Exchange, Exhibition Level, Moscone South At The Exchange, the team will be ready to answer your questions and show you how the latest products and cloud offerings can help address your business needs. You will find us at the following kiosks: Public Cloud Infrastructure Showcase CIS-001 > Increasing IT Efficiency and Agility with Oracle Virtualization  Operating systems, containers, and virtualization are the fundamental building blocks of modern IT infrastructure. Come to this demo kiosk to learn how Oracle Linux and Oracle virtualization products help increase IT efficiency and agility—on premises and in the cloud. CIS-002 > Jump-Start Your Development with Oracle Linux and Oracle Cloud  Oracle Linux offers an open, integrated operating environment with application development tools, management tools, containers, and orchestration capabilities that enable DevOps teams to efficiently build reliable, secure cloud native applications. Developers worldwide use Oracle VM VirtualBox to run Oracle Linux with the cloud native software on their desktop and easily deploy to the cloud. In addition, Oracle Cloud developer tools such as Terraform, SDKs, and CLI are available on Oracle Linux for an improved experience. Come to this demo kiosk to learn more about speeding up your development and your move to the cloud. CIS-003 > Oracle Linux and Virtualization Management with Oracle Enterprise Manager 13c In this demo, learn how to monitor and manage Oracle Linux and Oracle Virtualization technologies with Oracle Enterprise Manager 13c. Learn how Oracle Enterprise Manager 13c optimizes Oracle Linux and virtualization resources in a multi-private-cloud environment. CIS-005 > Secure Your Cloud Infrastructure with Oracle Linux, Ksplice, Oracle Secure Global Desktop Oracle Linux is the only Linux distribution that supports live, nondisruptive patching, both in the kernel space and in the user space. That means you can immediately apply security patches without impacting your production environment-and without rebooting. To date, more than 1 million patches have been delivered in this fashion through Ksplice. In this demo, learn how to use Oracle Secure Global Desktop to enable your workforce to connect from nearly any device, anywhere, while providing administrators with the tools they need to control access to applications and desktop environments, in the cloud and in the data center. On-Premise Infrastructure Showcase OPI-005 > Building a Cloud Native Environment with Oracle Linux Oracle Linux offers an open, integrated operating environment with application development tools, management tools, containers, and orchestration capabilities that enable DevOps teams to efficiently build reliable, secure cloud native applications. Come to this demo kiosk to learn how Oracle Linux can help you enhance productivity. OPI-006 > Oracle Linux Solutions for ISVs, OEMs, Embedded, and Cloud Platforms Come to this demo to understand how Oracle Linux solutions can be a foundation to help you grow your applications or services to extend your reach into new markets. OPI-007 > Increasing IT Efficiency and Agility with Oracle Virtualization Operating systems, containers, and virtualization are the fundamental building blocks of modern IT infrastructure. Come to this demo kiosk to learn how Oracle Linux and Oracle virtualization products help increase IT efficiency and agility-on premises and in the cloud. OPI-008 > Secure Your Cloud Infrastructure with Oracle Linux, Ksplice, Oracle Secure Global Desktop  Oracle Linux is the only Linux distribution that supports live, nondisruptive patching, both in the kernel space and in the user space. That means you can immediately apply security patches without impacting your production environment—and without rebooting. To date, more than 1 million patches have been delivered in this fashion through Ksplice. In this demo, learn how to use Oracle Secure Global Desktop to enable your workforce to connect from nearly any device, anywhere, while providing administrators with the tools they need to control access to applications and desktop environments, in the cloud and in the data center.   2. @ The Developer Appreciation Event – Sunday, September 15, 6:30 p.m. – 9:30 p.m. Join us for an informal gathering. Have a brew and some light hors d’oeuvres; converse with Oracle product experts; and experience some of the latest demos in a developer-only environment. Please let us know if you can make it. Kindly reply via: sign me up for the Oracle Developer Appreciation event on Sunday evening, September 15 in San Francisco. We look forwarding to spending time with you at Oracle OpenWorld. The Linux and Virtualization Team

The Oracle Linux and Virtualization team will be out in force at Oracle OpenWorld. There is a lot in store for attendees. We look forward to sharing the latest updates and demoing the latest...

Announcements

Oracle Linux and Virtualization Hands On Labs at Oracle OpenWorld & Oracle CodeOne

Ready to roll up your sleeves and dive into the latest tools and technologies? You’ll find five Hands On Labs (HOLs) at this year’s Oracle OpenWorld and CodeOne conferences that will help you optimize and secure your environment. Topics include Oracle Linux Cloud Native Environment, Oracle VM VirtualBox, Kata Containers, KVM, Terraform and more. Register now to be sure you have a seat. Let the learning begin! @Oracle OpenWorld – HOLs are 1-hour sessions Date HOL Title/Description/Speaker Time Location Monday, September 16 Infrastructure as Code: Oracle Linux, Terraform, and Oracle Cloud Infrastructure HOL1512 In this hands-on lab see how to easily install and configure Terraform for Oracle Cloud Infrastructure on Oracle Linux 7, and then use it to provision infrastructure in Oracle Cloud Infrastructure. Speakers: Christophe Pauliat, Master Principal Sales Consultant, Oracle Solution Center, Oracle Simon Hayler, Product Manager, Oracle Matthieu Bordonne, Principal Sales Consultant, Emea Oracle Solution Center, Oracle 10:00 a.m. - 11:00 a.m.   Moscone West Room 3022B Tuesday, September 17 Secure Container Orchestration Using Oracle Linux Cloud Native (Kubernetes/Kata) HOL5303 Learn to use Vagrant to automatically deploy Oracle Cloud Infrastructure Container Service Classic for use with a Kubernetes cluster, on an Oracle Linux 7 virtual machine using Oracle VM VirtualBox. Once the cluster is deployed, learn how to deploy secured containers with Kata Containers. Speaker: Simon Coter, Director of Product Management, Linux and Virtualization, Oracle   2:15 p.m. - 3:15 p.m.     Moscone West Room 3022B   Set Up a Kernel-Based VM with Oracle Linux 7, UEK5, Oracle Linux Virtualization Manager HOL5308 Walk through the planning and deployment of an infrastructure-as-a-service (IaaS) environment with an Oracle Linux KVM as the foundation. Speaker: Simon Coter, Director of Product Management, Linux and Virtualization, Oracle   3:45 p.m. - 4:45 p.m.     Moscone West Room 3022B Wednesday, September 18 Create a HA-NFS server Using Gluster, Corosync, and Pacemaker HOL5373 Learn how to build a three-node highly available shared-nothing NFS storage cluster on Oracle Linux 7 using open source tools. The lab also covers the installation and configuration of Gluster to enable storage replication between all three nodes, followed by the configuration of a highly available NFS server. Speakers: Avi Miller, Senior Manager, Oracle Linux and Virtualization Product Management, Oracle David Gilpin, Principal Product Manager, Oracle   3:45 p.m. - 4:45 p.m.  Moscone West - Room 3022B   Moscone West Room 3022B     @Oracle CodeOne – HOLs are 2-hour sessions Date HOL Title/Description/Speaker Time Location Tuesday, September 17 Learning Oracle Linux Cloud Native from the Ground Up – BYOL HOL5780 PLEASE NOTE: YOU MUST BRING YOUR OWN LAPTOP (BYOL) TO PARTICIPATE IN THIS HANDS-ON LAB. This lab will walk participants through a full installation of the Oracle Linux Cloud Native Environment. Go through the basic installation and configuration of the core components, including the container runtime engine, Kubernetes for orchestration, Istio, Prometheus, and Grafana—to name a few. In addition, the lab will cover more-advanced concepts. No preparation required. Speakers: Michele Casey, Senior Director Product Management, Oracle Linux, Oracle Thomas Tanaka, Principal Member of Technical Staff, Oracle Wiekus Beukes, Software Development Senior Director, Oracle Tom Cocozzello, Principal Member of Technical Staff, Oracle   9:00 a.m. - 11:00 a.m.     Moscone West Room 3024B Wednesday, September 18 Learning Oracle Linux Cloud Native from the Ground Up – BYOL HOL5780 PLEASE NOTE: YOU MUST BRING YOUR OWN LAPTOP (BYOL) TO PARTICIPATE IN THIS HANDS-ON LAB. This lab will walk participants through a full installation of the Oracle Linux Cloud Native Environment. Go through the basic installation and configuration of the core components, including the container runtime engine, Kubernetes for orchestration, Istio, Prometheus, and Grafana—to name a few. In addition, the lab will cover more-advanced concepts. No preparation required. Speakers: Michele Casey, Senior Director Product Management, Oracle Linux, Oracle Thomas Tanaka, Principal Member of Technical Staff, Oracle Wiekus Beukes, Software Development Senior Director, Oracle Tom Cocozzello, Principal Member of Technical Staff, Oracle   2:45 p.m. - 4:45 p.m.     Moscone West Room 3024C    

Ready to roll up your sleeves and dive into the latest tools and technologies? You’ll find five Hands On Labs (HOLs) at this year’s Oracle OpenWorld and CodeOne conferences that will help you optimize...

Announcements

Join Oracle’s Linux Developers @ the Linux Plumbers Conference in Lisbon – September 9-11

Oracle is pleased to support the open source community as a Silver Sponsor of the Linux Foundation’s Linux Plumbers Conference (LPC). We look forward to meeting with peers from around the world in Lisbon, Portugal, September 9 – 11 at the Corinthia Hotel. LPC is a developer conference for the open source community. It brings together the top developers working on the “plumbing” of Linux — kernel subsystems, core libraries, windowing systems, etc.  LPC brings Linux and open source experts together for three days of intensive work on core design problems. This year, LPC is composed of several tracks: Refereed Talks; Networking Summit; Kernel Summit; and many Microconferences. Oracle’s Linux and MySQL developers will be presenting in several sessions in the various tracks. If you are attending LPC, please be sure to join us for these sessions: In the Refereed Talks track, you can attend: Kernel Address Space Isolation, with Alexandre Chartre + others In the Networking track, join us for: BPF packet capture helpers, libbpf interfaces, with Alan Maguire Some of this year’s Microconferences, including Testing and Fuzzing, Toolchains, and Scheduler are organized by Oracle Linux Engineers. Within the Microconferences, Oracle engineers will lead discussions on the following topics: Testing and Fuzzing Microconference: Collaboration/unification around unit testing frameworks, with Dr. Knut Omang Toolchain Microconference: eBPF support in the GNU Toolchain, with Jose Marchesi CTF in the GNU toolchains, with Nick Alcock Scheduler Microconference: Task latency-nice, with Subhra Mazumdar Distribution kernels Microconference: Being Kernel Maintainer at Oracle - Lessons & Challenges, with Allen Pais Databases Microconference: Dimitri Kravtchuk of MySQL will be discussing several topics: io_uring - excitement - looking for feedback & potential issues Filesystem atomic writes / O_ATOMIC MySQL @EXT4 performance impacts with latest Linux kernels MySQL @XFS IP / UNIX Socket Backlog Syscall overhead from Spectre/Meltdown fixes New InnoDB REDO log design and MT sync challenges, with Pawal Olchawa Containers and Checkpoint/Restore Microconference: Cgroup v1/v2 Abstraction Layer, with Tom Hromatka RDMS Microconference: Shared IB Objects, with Yuval Shaia System Boot and Security Microconference: TrenchBoot - how to nicely boot system with Intel TXT and AMD SVM, with Daniel Kiper LPC provides a forum to generate vigorous discussion and helps lead the community to beneficial change. Oracle’s Linux developers look forward to meeting and collaborating with everyone in Lisbon.

Oracle is pleased to support the open source community as a Silver Sponsor of the Linux Foundation’s Linux Plumbers Conference (LPC). We look forward to meeting with peers from around the world in...

Announcements

Top 10 Oracle Linux and Virtualization Sessions at Oracle OpenWorld 2019

The Oracle Linux and Virtualization team welcomes you to Oracle OpenWorld and Oracle Code One 2019, September 16-19, in San Francisco. We look forward to bringing you – our customers and partners – together with product experts, executives, and industry luminaries to discuss the future and highlight new developments. The lineup of keynotes and sessions will help answer your questions and enable you to bring your best ideas to bear on your business strategies. Hands on Labs and Developer sessions will offer deep dives into the technologies you need to drive innovation. Remember to register for sessions ahead of time to make sure you have a seat.  To help you plan your time, below is a sampling of the Linux and Virtualization sessions.  Top 10 Sessions, and a few more… Date Session Title/Speaker Time Location Monday, September 16 Building Government-Grade Secure Systems Using Open Source Customer Case Study Session Speakers: Kai Martius, Chief Technical Officer, secunet Security Networks AG Honglin Su, Senior Director, Oracle Linux and Virtualization Product Management 09:00 a.m. - 09:45 a.m. Moscone South Room 155A   App Development with Oracle Cloud Infrastructure/Oracle Autonomous Database: Get Started Developer Session Speaker: Sergio Leunissen, Vice President, Oracle Linux and Virtualization Development 01:30 p.m. - 02:15 p.m. Moscone South Room 201   Oracle Cloud Infrastructure Behind the Scenes: Deep Dive into the Software Conference Session Speaker: Rita Ousterhout, Senior Director, Oracle Linux and Virtualization Development 01:45 p.m. - 02:30 p.m. Moscone South Room 155A   Using Oracle's Cloud Native Environment to Kickstart Your Private Cloud Conference Session Speakers: Michele Casey, Senior Director, Oracle Linux Product Management Tom Cocozzello, Principal Member of Technical Staff, Oracle Linux and Virtualization Development David Gilpin, Principal Product Manager, Oracle Linux 01:45 p.m. - 02:30 p.m. Moscone South Room 155B   Open Container Virtualization: Security of Virtualization, Speed of Containers Customer Session Speakers: Katsuaki Shimadera, Security Architect, Recruit Technologies Co., Ltd. Simon Coter, Director, Oracle Linux and Virtualization Product Management 02:45 p.m. - 03:30 p.m. Moscone South Room 152B Tuesday, September 17 Oracle’s Open Cloud Infrastructure Strategy  Executive Session Speaker: Ajay Srivastava, Senior Vice President, Operating Systems and Virtualization, Oracle 11:15 a.m. - 12:00 p.m. Moscone South Room 210     Cloud Platform and Middleware Strategy Roadmap  Executive Session Speaker: Edward Screven, Chief Corporate Architect, Oracle 12:30 p.m. – 01:15 p.m. YCBA Theater   Oracle Linux: State of the Penguin  Executive Session Speaker: Wim Coekaerts, Senior Vice President, Linux and Virtualization Engineering, Oracle 01:45 p.m. - 02:30 p.m. Moscone South Room 210   Strategic Considerations to Achieve Business Impact with Cloud Native Projects Conference Session Speaker: Mickey Bharat, Senior Director, Worldwide Embedded Sales, Oracle Linux and Virtualization 03:15 p.m. – 04:00 p.m. Moscone South Room 152B   How to Get Started with Cloud Native Theater Session Speaker: Karen Sigman, Vice President, Product and Partner Marketing 04:00 p.m. - 04:20 p.m. The Exchange, Moscone South  Theater 1   Securing Oracle Linux 7 Conference Session Speakers: Erik Benner, Vice President of Enterprise Transformation, Mythics, Inc. Avi Miller, Senior Manager, Oracle Linux and Virtualization Product Management 04:15 p.m. - 05:00 p.m. Moscone South  Room 210   Oracle Linux and Oracle VM VirtualBox: The Enterprise Cloud Development Platform Product Overview and Roadmap Session Speaker: Simon Coter, Director, Oracle Linux and Virtualization Product Management 05:15 p.m. - 06:00 p.m. Moscone South Room 152B Wednesday, September 18 Oracle's Infrastructure Strategy for Cloud and On-Premises Executive Session Speakers: Wim Coekaerts, SVP, Linux and Virtualization Engineering Ali Alasti, SVP, Hardware Development, x86 Management Ajay Srivastava, SVP, Operating Systems and Virtualization 11:15 a.m. - 12:00 p.m.   YCBA Theater   Oracle Linux: A Cloud-Ready, Optimized Platform for Oracle Cloud Infrastructure Customer Session Speakers: Ryan Volkmann, Senior Manager IT PMO, Nidec Julie Wong, Director, Oracle Linux and Virtualization Product Management 04:45 p.m. - 05:30 p.m. Moscone South Room 152D   Understanding the Oracle Linux Cloud Native Environment Developer Session Speaker: Michele Casey, Senior Director, Oracle Linux Product Management 05:00 p.m. - 05:45 p.m. Moscone South  Room 206 Add these sessions to your schedule and don't forget to bookmark the Oracle Linux and Virtualization Program Guide for more details on these and all of our other sessions. #OOW19 and #CodeOne will provide opportunities to discover innovative technologies, get answers to your most important questions, and foster ideas with like-minded peers. Stay tuned to this blog for more information on Hands-on-Labs (HOLs) and demo areas in The Exchange in the coming days. We look forward to spending time with you at Oracle OpenWorld 2019!

The Oracle Linux and Virtualization team welcomes you to Oracle OpenWorld and Oracle Code One 2019, September 16-19, in San Francisco. We look forward to bringing you – our customers and partners –...

Perspectives

Getting started with Oracle Linux Virtualization Manager

Oracle recently announced the general availability of Oracle Linux Virtualization Manager. This new server virtualization management platform can be easily deployed to configure, monitor, and manage an Oracle Linux Kernel-based Virtual Machine (KVM) environment with enterprise-grade performance and support from Oracle.  Installing the new Manager and getting Oracle Linux KVM servers connected for your test or development environment is simple and can be done very quickly. Oracle Linux Virtualization Manager 4.2.8 can be installed from the Oracle Linux Yum Server or the Oracle Unbreakable Linux Network.  The steps to get up and running from these two sites are outlined below: Oracle Linux Yum Server. Install Oracle Linux 7 Update 6 on the host machine. # yum install https://yum.oracle.com/repo/OracleLinux/OL7/ovirt42/x86_64/ovirt-release42.rpm # yum install ovirt-engine Run the engine-setup command to configure Oracle Linux Virtualization Manager. Add Oracle Linux KVM Compute Hosts, Storage and Logical Networks - and then create your new Virtual Machines. Oracle Unbreakable Linux Network. Install Oracle Linux 7 Update 6 on the host machine. Log in to https://linux.oracle.com with your ULN user name and password. On the Systems tab, click the link named for the host registered machine. On the System Details page, click Manage Subscriptions. On the System Summary page, subscribe to the following channels: ol7_x86_64_latest ol7_x86_64_optional_latest ol7_x86_64_kvm_utils ol7_x86_64_ovirt42 ol7_x86_64_ovirt42_extras ol7_x86_64_gluster312 ol7_x86_64_UEKR5 Click Save Subscriptions. # yum install ovirt-engine Run the engine-setup command to configure Oracle Linux Virtualization Manager. Add Oracle Linux KVM Compute Hosts, Storage and Logical Networks - and then create your new Virtual Machines. For additional information on setting up your Oracle Linux Virtualization Manager please review the Installation Guide and the Getting Started Guide which are available from the Oracle Linux Virtualization Manager Document Library. Oracle Linux Virtualization Manager Support Support for Oracle Linux Virtualization Manager is available to customers with an Oracle Linux Premier Support subscription. Refer to Oracle Linux 7 License Information User Manual for information about Oracle Linux support levels.

Oracle recently announced the general availability of Oracle Linux Virtualization Manager. This new server virtualization management platform can be easily deployed to configure, monitor, and manage...

Announcements

Announcing Oracle Linux 7 Update 7

Oracle is pleased to announce the general availability of Oracle Linux 7 Update 7. Individual RPM packages are available on the Unbreakable Linux Network (ULN) and the Oracle Linux yum server. ISO installation images will soon be available for download from the Oracle Software Delivery Cloud and Docker images will soon be available via Oracle Container Registry and Docker Hub. Oracle Linux 7 Update 7 ships with the following kernel packages, that include bug fixes, security fixes and enhancements: Unbreakable Enterprise Kernel (UEK) Release 5 (kernel-uek-4.14.35-1902.3.2.el7) for x86-64 and aarch64 Red Hat Compatible Kernel (RHCK) (kernel-3.10.0-1062.el7) for x86-64 only Notable new features for all architectures NetworkManager NetworkManager enables you to configure virtual LAN (VLAN) filtering on bridge interfaces, and define VLANs directly on bridge ports. NetworkManager also adds the capability to configure policy routing rules by using the GUI. Security Package Updates for Network Security Services (NSS), scap-security-guide and shadow-utils. SCAP Security Guide support for Universal Base Image (UBI) containers and images. UBI containers and images can now be scanned against any profile that is shipped in the SCAP Security Guide. Rules that are inapplicable to UBI images and containers are automatically skipped. Important changes introduced in this release btrfs: Starting with Oracle Linux 7 Update 4, btrfs is deprecated in RHCK. Note that BTRFS is fully supported with UEK R4 and UEK R5. MySQL Community Packages: Starting with Oracle Linux 7 Update 5, the MySQL Community Packages are no longer included on the Oracle Linux 7 ISO. These packages are available for download from the Oracle Linux yum server and ULN. Notable features available as a technology preview in RHCK Systemd Importd features for container image imports and exports File Systems Block and object storage layouts for parallel NFS (pNFS) DAX (Direct Access) for direct persistent memory mapping from an application for the ext4 and XFS file systems OverlayFS remains in technical preview Kernel Heterogeneous memory management (HMM) No-IOMMU mode virtual I/O feature Networking Cisco VIC InfiniBand kernel driver and Cisco libusnic_verbs driver for Cisco User Space Network Single-Root I/O virtualization (SR-IOV) in the qlcnic driver Cisco proprietary User Space Network Interface Controller in UCM servers provided in the libusnic_verbs driver Trusted Network Connect Storage Multi-queue I/O scheduling for SCSI (disabled by default) Plug-in for the libStorageMgmt API used for storage array management For more details about these and other new features and changes, please consult the Oracle Linux 7 Update 7 Release Notes for x86-64 and aarch64 platforms. Oracle Linux can be downloaded, used, and distributed free of charge and all updates and errata are freely available. Customers decide which of their systems require a support subscription. This makes Oracle Linux an ideal choice for development, testing, and production systems. The customer decides which support coverage is best for each individual system while keeping all systems up to date and secure. Customers with Oracle Linux Premier Support also receive support for additional Linux programs, including Gluster Storage, Oracle Linux Software Collections, and zero-downtime kernel updates using Oracle Ksplice. Application Compatibility Oracle Linux maintains user space compatibility with Red Hat Enterprise Linux (RHEL), which is independent of the kernel version that underlies the operating system. Existing applications in user space will continue to run unmodified on Oracle Linux 7 Update 7 with UEK Release 5 and no re-certifications are needed for applications already certified with Red Hat Enterprise Linux 7 or Oracle Linux 7. For more information about Oracle Linux, please visit www.oracle.com/linux. Oracle Linux Resources: Documentation Oracle Linux Software Download Oracle Linux Oracle Container Registry Blogs Oracle Linux Blog Community Pages Oracle Linux Social Media Oracle Linux on YouTube Oracle Linux on Facebook Oracle Linux on Twitter Data Sheets, White Papers, Videos, Training, Support & more Oracle Linux Product Training and Education Oracle Linux For community-based support, please visit the Oracle Linux space on the Oracle Developer Community.

Oracle is pleased to announce the general availability of Oracle Linux 7 Update 7. Individual RPM packages are available on the Unbreakable Linux Network (ULN) and the Oracle Linux yum server. ISO...

Linux

Learn to Monitor Cloud Apps and Services with Prometheus

Want to know what is happening in your cloud-native environment at a given time? When using Prometheus to monitor your cloud workloads, you can historically collect and view metrics from configured targets to determine the moment in time when failures occur. Get an introduction to Prometheus and learn how to install and configure Prometheus through video content. Prometheus is a monitoring system, which collects metrics from configured targets at given intervals. It uses a powerful multidimensional data model with its own query language (PromQL). These features aid in discovering trends, events, and errors. The Prometheus server stores the collected metrics in a time-series database, and its query language allows for the effortless monitoring of CPU usage, memory usage, amount of HTTP request served, etc. The four major components of Prometheus are: Gathering component for accumulating data from various systems Storage component for storing gathered data for future use Viewing component for getting information from stored data Alerting component for processing the stored data and triggering alerts based on certain conditions Start your discovery today to learn more about Prometheus' architectural components, its multidimensional data model Continue your learning on how to install, configure and test Prometheus. Resources: Oracle Linux Cloud Native Environment Training Oracle Linux Cloud Native Environment product information Oracle Linux training courses Oracle Linux product documentation

Want to know what is happening in your cloud-native environment at a given time? When using Prometheus to monitor your cloud workloads, you can historically collect and view metrics from configured...

Linux

Learn About Communication Between Microservices with Istio

Get started today developing your Istio service mesh expertise by learning more about implementing Istio in a Kubernetes cluster. Istio is an open source independent service mesh that provides the fundamentals you need to successfully run a distributed microservice architecture. Istio provides a uniform way to integrate microservices and includes service discovery, load balancing, security, recovery, telemetry, and policy enforcement capabilities. An Istio service mesh is logically split into a data plane and a control plane. The data plane is composed of a set of intelligent proxies (Envoy) deployed as sidecars. This sidecar design means that communication proxies run in their own containers beside every service container. These proxies mediate and control all network communication between microservices and helps ensure that communication is reliable and secure. The control plane consists of Pilot, Mixer, Citadel, and Gallery. Pilot enables service discovery by the proxies, provides input for proxy load balancing pools, and provides routing rules to proxies. Mixer collects telemetry from Envoy sidecars and provides policy checking. Citadel is responsible for certification issuance and rotation. Galley validates and distributes configuration information within Istio. Leverage these videos to follow technical presentations and demonstrations on how to build your Oracle Container Services for Kubernetes cluster, and how to install Istio and deploy an application with automatic proxy sidecar injection enabled. Oracle Linux Cloud Native Environment Training Oracle Container Services for use with Kubernetes User’s Guide Oracle Linux Cloud Native Environment datasheet Oracle Linux Curriculum

Get started today developing your Istio service mesh expertise by learning more about implementing Istio in a Kubernetes cluster. Istio is an open source independent service mesh that provides the...

Linux

Learn to Drive Efficient Deployments with Kata Containers

Kata containers help you drive efficiency for your container deployments. With Oracle Linux Cloud Native Environment training, we bring you a series of free, short videos to help get you started with implementing Kata container technologies in your Kubernetes cluster with Oracle Linux. Supporting Open Container Initiative compatible containers, Kata allows you to efficiently deploy containers in lightweight virtual machines (VMs) that deliver performance and security with less overhead than standard container deployments. Kata container lightweight VMs look and operate like regular containers but do not share the same underlying kernel. They use hardware virtualization to allow each container to run its own VM and kernel. Kata on Kubernetes cluster is easy to install and set up, bringing solid performance and security returns to your Oracle Linux infrastructure investment. Get started today with developing your Kata container expertise by learning more about implementing Kata. Follow these links to find technical videos on how to build your Kubernetes cluster, and how to install and set up Kata in your cluster worker nodes. Oracle Linux Cloud Native Environment Training Oracle Container Services for use with Kubernetes User’s Guide Oracle Linux Curriculum

Kata containers help you drive efficiency for your container deployments. With Oracle Linux Cloud Native Environment training, we bring you a series of free, short videos to help get you started...

Linux

First Step on Your Oracle Linux System Admin Learning

Get started on your Linux learning with Oracle Linux System Administration I. This course offers extensive hands-on experience including installing the Oracle Linux operating system, configuring basic Linux services, preparing a system for the Oracle database, and monitoring and troubleshooting a running Oracle Linux system. Important to sys admins, this course provides students with the skills to handle networking, storage, security, monitoring, troubleshooting and more. Students are also introduced to the Oracle Cloud Infrastructure and learn how to create an Oracle Linux instance on the cloud, set up a Virtual Cloud Network (VCN), and attach a block volume to an Oracle Linux instance on the cloud. By taking Oracle Linux System Administration I, students learn to: Install Oracle Linux 7 operating system Configure a system to use the Unbreakable Enterprise Kernel (UEK) Set up users and groups Configure networking and storage devices Update a system using the Oracle's Unbreakable Linux Network (ULN) Use Ksplice technology to update the kernel on a running system And many more This Oracle Linux System Administration I course is the first of 3 new Oracle Linux System Administration courses, so you can continue your learning with: Oracle Linux System Administration II Oracle Linux System Administration III Resources: Oracle Linux curriculum Oracle Linux product documentation Linux on Oracle Cloud Infrastructure learning path Oracle Linux Cloud Native Environment learning path

Get started on your Linux learning with Oracle Linux System Administration I. This course offers extensive hands-on experience including installing the Oracle Linux operating system, configuring basic...

Announcements

Announcing the Release of Oracle Linux 8

Oracle is pleased to announce the general availability of Oracle Linux 8.   With Oracle Linux 8, the core operating environment and associated packages for a typical Oracle Linux 8 server are distributed through a combination of BaseOS and Applications Streams. BaseOS gives you a running user space for the operating environment. Application Streams provides a range of applications that were previously distributed in Software Collections, as well as other products and programs, that can run within the user space. Notable new features in this release Oracle Linux 8 introduces numerous enhancements and new features. Highlights include: Application Streams Oracle Linux 8 introduces the concept of Application Streams, where multiple versions of user space components can be delivered and updated more frequently than the core operating system packages. Application Streams contain the necessary system components and a range of applications that were previously distributed in Software Collections, as well as other products and programs. A list of Application Streams supported on Oracle Linux 8 is available here. System Management Dandified Yum, a new version of the yum tool based on DNF technology, is a software package manager that installs, updates, and removes packages on RPM-based Linux distributions Cockpit, an easy-to-use, lightweight and simple yet powerful remote manager for GNU/Linux servers, is an interactive server administration interface that offers a live Linux session via a web browser RPM Improvements Oracle Linux 8 ships with version 4.14 of RPM, which introduces many improvements and support for several new features Installation, Boot and Image Creation inst.addrepo=name boot parameter has been added to the installer. You can use this parameter to specify an additional repository during an installation By default, the Oracle Linux 8 installer uses the disk encryption specification LUKS2 (Linux Unified Key Setup 2) format Kernel The modinfo command has been updated to recognize and display signature information for modules that are signed with CMS and PKCS#7 formatted signatures A set of kernel modules have been moved to the kernel-modules-extra package, which means none of these modules are installed by default; as a consequence, non-root users cannot load these components, as they are also blacklisted by default Memory bus limits have been extended to 128 PiB of virtual address space and 4 PB of physical memory capacity. The I/O memory management unit (IOMMU) code in the Linux kernel is also updated to enable 5-level paging tables The early kdump feature enables the crash kernel and initramfs to load early so that it can capture vmcore information, including early kernel crashes Containers and Virtualization New container tools:  podman, buildah and skopeo, compatible with Open Container Initiative (OCI), are now available with the Oracle Linux 8. These tools can be used to manage the same Linux containers that are produced and managed by Docker and other compatible container engines. Q35 machine type, support for KVM, which is a more modern PCI Express-based machine type, is now available for KVM Additional information is included in KVM guest crash reports, which makes it easier to diagnose and fix problems when using KVM virtualization Filesystem and Storage Enhanced Device Mapper Multipathing SCSI Multiqueue driver enables block layer performance to scale well with fast solid-state drives (SSDs) and multi-core systems Stratis, an easy solution to manage local storage XFS support for shared COW data extents, shared copy-on-write (COW) data extent functionality, whereby two or more files can share a common set of data blocks. This feature is similar to Copy on write (COW) functionality that is found in other file systems, where if either of the files that are sharing common blocks change, XFS breaks the link to those common blocks and then creates a new file Identity Management Several major identity management (IdM) features and enhancements, including session recording, enhanced Microsoft AD integration and new password syntax check IdM server and client packages are distributed as a module; the IdM server module stream is called the DL1 stream and it contains multiple profiles (server, dns, adtrust, client, and default) Networking iptables network packet filtering framework has been replaced with nftables; the nftables framework includes packet classification facilities, several improvements and provides improved performance iptables-translate and ip6tables-translate commands are now available to convert existing rules to their nftables equivalents, thereby facilitating the move to Oracle Linux 8 IPVLAN virtual network driver enables network connectivity for multiple containers by exposing a single MAC address to the local network Networking, UDP, and TCP updated to release 4.18 with improved performance Security OpenSSH updated to release 7.8p1, enhancing access security  LUKS2 (Linux Unified Key Setup) is now the default format for encrypted volumes OpenSCAP has been updated to the release 1.3.0 with improvements to the command-line interface as well as consolidation of OpenSCAP API have been addressed SELinux now supports the map permission feature, to help prevent direct memory access to various file system objects and introduces new SELinux booleans Transport Layer Security (TLS) 1.3 is enabled by default in major back-end cryptographic libraries Support Oracle Linux can be downloaded, used, and distributed free of charge and updates and errata are freely available. Customers decide which of their systems require a support subscription. This makes Oracle Linux an ideal choice for development, testing, and production systems. The customer decides which support coverage is best for each individual system while keeping all systems up-to-date and secure. Customers with Oracle Linux Premier Support also receive support for additional Linux programs, including zero-downtime kernel updates using Oracle Ksplice, Oracle Linux Virtualization Manager and Oracle Linux Cloud Native Environment. Oracle Linux Premier Support is included with Oracle Cloud Infrastructure subscriptions at no additional cost. Further information Oracle Linux 8 installation software is now available as: ISO from the Oracle Software Delivery Cloud for x86-64 architecture Individual RPM packages via the Unbreakable Linux Network (ULN) and the Oracle Linux Yum Server Developer Preview ISO from Oracle Linux on Oracle Technology Network for aarch64 architecture Additional Oracle Linux 8 software options are also available on: Docker images via Oracle Container Registry and Docker Hub Platform image on Oracle Cloud Infrastructure Marketplace Oracle Linux 8 ships with the Red Hat Compatible Kernel (RHCK) kernel package kernel-4.18.0-80.el8. It is tested as a bundle, as shipped on the installation media image. The Unbreakable Enterprise Kernel (UEK), which is being built from a more current upstream kernel version, is undergoing final development. Oracle Linux 8 offers developers the opportunity to get started with 8.0 capabilities as well as get updates for free. Oracle Linux maintains binary compatibility with Red Hat Enterprise Linux (RHEL), which is independent of the kernel version that underlies the operating environment. Existing applications in user space will continue to run unmodified on Oracle Linux 8 and no re-certifications are needed for applications already certified with Red Hat Enterprise Linux 8.  Resources Documentation Oracle Linux Oracle Linux 8 Release Notes Software Download Oracle Linux download instructions Oracle Software Delivery Cloud Oracle Container Registry Community Pages Oracle Linux Community Space Social Media Oracle Linux on YouTube Oracle Linux on Facebook Oracle Linux on Twitter Data Sheets, White Papers, Videos, Training, Support & more Oracle Linux Product Training and Education Oracle Linux

Oracle is pleased to announce the general availability of Oracle Linux 8.   With Oracle Linux 8, the core operating environment and associated packages for a typical Oracle Linux 8 server are...

Linux Kernel Development

Improve Security with Address Space Isolation (ASI)

Address Space Isolation In this blog post, Oracle Linux kernel developers Alexandre Chartre and Konrad Rzeszutek Wilk give an update on the Spectre v1 and L1TF software solutions. Introduction In August of 2018 the L1TF speculative execution side channel vulnerabilities were presented (see Foreshadow – Next Generation (NG). However the story is more complicated. In particular, an explanation in L1TF - L1 Terminal Fault mentions that if hyper-threading is enabled, and the host is running an untrusted guest - there is a possibility of one thread snooping the other thread. Also the recent Microarchitectural Data Sampling, aka Fallout, aka RIDL, aka Zombieland demonstrated that there are more low-level hardware resources that are shared between hyperthreads. Guests on Linux are treated the same way as any application in the host kernel, which means that the Completely Fair Scheduler (CFQ) does not distinguish whether guests should only run on specific threads of a core. Patches for core scheduling provide such a capability but, unfortunately, its performance is rather abysmal and as Linus mentions: Because performance is all that matters. If performance is bad, then it's pointless, since just turning off SMT is the answer. However turning off SMT (hyperthreading) is not a luxury that everyone can afford. But then, with hyperthreading enabled, a malicious guest running on one hyperthread can snoop from the other hyperthread, if the host kernel is not hardened. Details of data leak exploit There are two pieces of exploitation technologies combined: Spectre v1 code gadgets - that is any code in the kernel that accesses user controlled memory under speculation A malicious guest which is executing the actual L1TF attack In fact a Proof of Concept has been posted RFC x86/speculation: add L1 Terminal Fault / Foreshadow demo which does exactly that. The reason this is possible is due to the fact that hyperthreads share CPU resources - and a well-timed attack can occur in between the time we exit in the hypervisor and go back to running the guest: Thread #0 performs an operation that requires the help of the hypervisor, such as cpuid. Thread #1 spins in its attack code without invoking the hypervisor. Thread #0 pulls data in the cache using Spectre v1 code gadget. Thread #1 measure CPU resources to leak speculatively accessed data. Thread #0 flushes the cache and then resumes executing the guest. This is how an attacker can leak the kernel data - using a combination of Spectre v1 code gadgets and using L1TF attack in the little VMEXIT windows that an guest can force. Solutions As mentioned disabling hyperthreading automatically solves the security problem, but that may not be a solution as it halves the capacity of a cluster of machines. All the solutions revolve around the idea of allowing code gadgets to exist but they would either not be able to be execute in the speculative path, or they can execute - but are only be able to collect non-sensitive data. The first solution that comes in mind is - can we inhibit the secondary thread from executing code gadgets. One naive approach is to simply always kick the other sibling whenever we enter the kernel (or hypervisor) and have the other sibling spin until we are done in a safe space. Not surprisingly the performance was abysmal. Several other solutions that followed this path that have been proposed, including:   Co-scheduling - modifying the scheduler to run tasks of the same group and on the same core executing simultaneously, whenever they are executed Core-scheduling - different implementation but the same effect. Both of those follow the same pattern - lock-step enter the kernel (or hypervisor) when needed on both threads. This mitigates the Specte v1 issue by the guest or user space program not being able to leverage it - but it comes with unpleasant performance characteristics (on some workloads worst performance than turning hyperthreading off). Another solution includes proactively patching the kernel for Spectre v1 code gadgets, along with meticulous nanny-sitting of the scheduler to never schedule one customer guests from sharing another customer siblings, and other low-level mitigations not explained in this blog.   However that solution also does not solve the problem of the host kernel being leaked using the Spectre v1 code gadgets and L1TF attack (see _Details of data leak exploit_ above). But what if just remove sensitive data from being mapped to that virtual address space to begin with? This would mean even if the code gadgets were found they would never be able to bridge the gap to the attacker controlled signal array.   eXclusive Page Frame Ownership (XPFO)) One idea that has been proposed in order to reduce sensitive data is to remove from kernel memory pages that solely belong to a userspace process and that the kernel don't currently need to access. This idea is implemented in a patch series called XPFO that can be found here: Add support for eXclusive Page Frame Ownership, earlier explained in 2016 Exclusive page-frame ownership and the original author's patches Add support for eXclusive Page Frame Ownership (XPFO). Unfortunately this solution does not help with protecting the hypervisor from having data leaked, just protects user space data. Which for guest to guest protection is enough - even if a naughty guest caused the hypervisor to speculatively execute Spectre v1 code gadgets along with spilling the hypervisor data using L1TF attack - the hypervisor at that point has only the naughty guest mapped on the core and not the other guest's memory on the same core - so only hypervisor data is leaked and other guests' vCPUs register data. Only is not good enough - we want better security. And if one digs in deeper there are also some other issue such as non trivial performance hit as a result of TLB flushes which make it slower than just disabling hyperthreading. Also if vhost is used then XPFO does not help at all as each guest vhost thread ends up mapping the guest memory in the kernel virtual address space and re-opening the can of worms. Process-local memory allocations Process-local memory allocations (v2) addresses this problem a bit differently - mainly that each process has a kernel virtual address space slot (local, or more of secret) in which the kernel can squirrel sensitive data on behalf of the process. The patches focus only on one module (kvm) which would save guest vCPU registers in this secret area. Each guest is considered a separate process, which means that each guest is precluded from touching the other guest secret data. The "goal here is to make it harder for a random thread using cache load gadget (usually a bounds check of a system call argument plus array access suffices) to prefetch interesting data into the L1 cache and use L1TF to leak this data." However there are still issues - all of the guests memory is globally mapped inside the kernel. And the kernel memory itself can still be leaked in the guest. This is similar to XPFO in that it is a black-list approach - we decide on specific items in the kernel virtual address space and remove them. And it fails short of what XPFO does (XPFO removes the guest memory from the kernel address space). Combining XPFO with Process-local memory allocations would provide much better security than using them separately. Address Space Isolation Address Space Isolation is a new solution which isolates restricted/secret and non-secret code and data inside the kernel. This effectively introduces a firewall between sensitive and non-sensitive kernel data while retaining the performance (we hope). This design is inspired by Microsoft Hyper-V HyperClear Mitigation for L1 Terminal Fault. Liran Alon who sketched out the idea thought about this idea as follow: The most naive approach to prevent the SMT attack vector is to force sibling hyperthreads to exit every time one hyperthread exits. But it introduce in-practical perf hit. Therefore, next thought was to just remove what could be leaked to begin with. We assume that everything that could be leaked is something that is mapped into the virtual address space that the hyperthread is executing in after it exits to host. Because we assume that leakable CPU resources are only loaded with sensitive data from virtual address space. This is an important assumption. Going forward with this assumption, we need techniques to remove sensitive information from host virtual address space. XPFO and Kernel-Process-Local-Memory patch series goes with a black-list approach to remove explicitly specific parts of virtual address space which we consider to have sensitive information. The problem with this approach is that we are maybe missing here something and therefore a white-list approach is preferred. At this point, after being inspired from Microsoft HyperClear, the KVM ASI came about. The unique distinction about KVM ASI is that it creates a separate virtual address space for most of the exits to host that is built in a white-list approach: we only map the minimum information necessary to handle these exits and do not map sensitive information. Some exits may require more or sensitive information, and in those cases we kick the sibling hyperthreads and switch to the full address space. Details of Address Space Isolation QEMU and the KVM kernel module work together to manage a guest, and each guest is associated with a QEMU process. From userspace, QEMU uses the KVM_RUN ioctl (#1 and #2) to request KVM to run the VM (#3) from the kernel using Intel Virtual Machine Extensions (VMX). When an event causes the VM to return (VM-Exit, step #4) to KVM, KVM handles the VM-Exit (#5) and then transfer control to the VM again (VM-Enter). See below: However, most of the KVM VM-Exit handlers only need to access per-VM structures and KVM/vmlinux code and data that is not sensitive. Therefore, these KVM VM-Exit handlers can be run in an address space different from the standard kernel address space. So, we can define a KVM address space, separated from the kernel address space, which only needs to map the code and data required for running these KVM VM-Exit handlers (#5 see below). This provides a white-list approach of exactly what could be leaked while running the KVM VM-Exit code (in the picture below it is yellowish). When the KVM VM-Exit (#5a see below) code reaches a point where it does architecturally need to access sensitive data (and therefore not mapped in this isolated virtual address space), then it will kick all sibling hyperthreads outside of guest and switch to the full kernel address space. This kicking guarantees that there is no untrusted guest code running on sibling hyperthreads while KVM is bringing data into the L1 cache with the full kernel address space mapped. This overall operation happens, for example, when KVM needs to return to QEMU or the host needs to run an interrupt handler. Note that KVM flushes the L1 cache before VM-Enter back to running guest code to ensure nothing is leaked via the L1 cache back to the guest. In effect, we have made the KVM module a less privileged kernel module. That has three fantastic side-effects: The guest already knows about guest data on which KVM operates most of the time so if it is leaked to the guest that is okay. If the attacker does exploit a code gadget, it will only be able to run on the KVM module address space, not outside of it. Nice side-affect of ASI is that it can also assist against ROP exploitation and architectural (not speculative) info-leak vulnerabilities because much less information is mapped in the exit handler virtual address space.` If the KVM module needs to access restricted data or routines, it needs to switch to the full kernel page-table, and also bring the other sibling back to the kernel so that the other thread will be unable to insert code gadgets and slurp data in. Show me the code?! The first version, posted back in May, RFC KVM 00/27 KVM Address Space Isolation received many responses from the community. These patches - RFC v2 00/27 Kernel Address Space Isolation posted by Alexandre Chartre are the second step in this. The patches are posted as a Request For Comments which solicits guidance from the the Linux Kernel community on how they would like this to be done. The framework is more generic with the first user being KVM but could very well be extended to other modules   Thanks We would like also to thank the following folks for help with this article: Mark Kanda Darren Kenny Liran Alon Bhavesh Davda

Address Space Isolation In this blog post, Oracle Linux kernel developers Alexandre Chartre and Konrad Rzeszutek Wilk give an update on the Spectre v1 and L1TF software solutions. Introduction In August...

Announcements

OpenSSL Cryptographic Module for Oracle Linux 7.5 and 7.6 Received FIPS 140-2 Certification

OpenSSL cryptographic module for Oracle Linux 7.5 and 7.6 has just received FIPS 140-2 Level 1 certification. This is the first completed FIPS 140-2 certification with the latest Oracle Linux 7.6 update, ahead of any other Linux distributions. This certification adds to recent, related certifications and advancements, which enable Oracle Linux to deliver more security features that can help keep systems secure and improve the speed and stability of your operations on premises and in the cloud. Conformance with the FIPS 140-2 standard provides assurance to government and industry purchasers that products are correctly implementing cryptographic functions as the FIPS 140-2 standard specifies. FIPS 140-2 is a public sector procurement requirement in both the United States and Canada for any products claiming or providing encryption. The FIPS 140-2 program is jointly administered by the National Institute of Standards and Technology (NIST) in the US and the Canadian Center for Cyber Security (CCCE) in Canada. The joint program is called the CMVP (Cryptographic Module Validation Program). The platforms that are used for Oracle Linux 7.5 and 7.6 OpenSSL cryptographic module FIPS 140 validation testing include Oracle Server X7-2, running Oracle Linux 7.5 and 7.6. Oracle “vendor affirms” that the FIPS validation is maintained on other x86-64 equivalent hardware that has been qualified, per the Oracle Linux Hardware Certification List (HCL), on the corresponding Oracle Linux releases. Oracle Linux cryptographic modules enable FIPS 140 compliant operations for key use cases such as data protection and integrity, remote administration, cryptographic key generation, and key/certificate management. The packages that are FIPS 140-2 level 1 certified for Oracle Linux 7 can be obtained from Oracle Linux yum server. When the packages are installed, you can enable FIPS mode by following the Oracle Linux 7 Documentation. Oracle Linux is engineered for open cloud infrastructure. It delivers leading performance, scalability, reliability, and security for enterprise SaaS and PaaS workloads, as well as traditional enterprise applications. Oracle Linux Support offers access to award-winning Oracle support resources and Linux support specialists, zero-downtime updates using Ksplice, additional management tools such as Oracle Enterprise Manager and lifetime support, all at a low cost. Unlike many other commercial Linux distributions, Oracle Linux is easy to download and completely free to use, distribute, and update. The Oracle Linux images that are available on Oracle Cloud Infrastructure are updated frequently to provide access to the latest security updates, and Oracle Linux Premier Support is provided at no additional cost to Oracle Cloud Infrastructure subscribers.  For a matrix of Oracle security evaluations that are currently in progress, as well as those completed, please refer to Oracle Security Evaluations. Visit Oracle Linux Security to learn how Oracle Linux can help keep your systems secure and improve the speed and stability of your operations.

OpenSSL cryptographic module for Oracle Linux 7.5 and 7.6 has just received FIPS 140-2 Level 1 certification. This is the first completed FIPS 140-2 certification with the latest Oracle Linux...

Oracle Sponsors KubeCon + CloudNativeCon + Open Source Summit China 2019

Oracle is a committed and active member of the Linux community and is a gold sponsor of KubeCon + CloudNativeCon + Open Source Summit China 2019 (Shanghai, June 24-26, 2019). A founding platinum member of The Linux Foundation® and also a platinum member of Cloud Native Computing Foundation® (CNCF®), Oracle is dedicated to the worldwide success of Linux for organizations of all sizes and across all industries. Oracle continues to expand its commitment to open source and cloud native solutions targeted at helping move enterprise workloads to the cloud. At KubeCon + CloudNativeCon Europe 2019 in Barcelona last month, Oracle announced Oracle Cloud Infrastructure Service Broker for Kubernetes and highlighted a recent set of Oracle open source solutions that facilitate enterprise cloud migrations including Helidon, GraalVM, Fn Project, MySQL Operator for Kubernetes, and WebLogic Operator for Kubernetes. Oracle is enabling enterprise developers to embrace cloud native culture and open source and make it easier to move enterprise workloads to the cloud. That includes everyone, from database application teams, to Java developers, to WebLogic system engineers, to Go, Python, Ruby, Scala, Kotlin, JavaScript, Node.js developers and more. For example, the Oracle Cloud Developer Image provides a comprehensive development platform on Oracle Cloud Infrastructure that includes Oracle Linux, Oracle Java SE support, Terraform, and many SDKs.  It reduces the time it takes to get started on Oracle’s cloud infrastructure and makes it fast and easy, just a matter of minutes, to provision and run Oracle Autonomous Database. Operating systems, containers, and virtualization are the fundamental building blocks of modern IT infrastructure. Oracle combines them all into one integrated open source offering: Oracle Linux. Operating on your choice of hardware—in your data center or in the cloud—Oracle Linux provides the reliability, scalability, security, and performance for demanding enterprise and cloud workloads. We are pleased to share, below, the latest Oracle Linux developments and releases that can help accelerate your digital transformation. With Oracle Linux, you have a complete DevOps environment which is modern, optimized, and secure and is designed for hybrid and multi-cloud deployments at enterprise scale. Oracle Linux Cloud Native Environment—This curated set of open source software is selected from CNCF projects. Recently, the technology preview of Oracle Container Runtime for Kata was released, which aims to further protect cloud native, container-based microservices, by leveraging the security and isolation provided by virtual machines. Updates have been made to Oracle Container Runtime for Docker and Oracle Container Services for use with Kubernetes. Additionally, many Oracle software products are available as Docker container images that can be downloaded from Oracle Container Registry, and you can download Dockerfiles and samples from GitHub to build your own Docker container images for Oracle software. Unbreakable Enterprise Kernel (UEK) Release 5 Update 2—Available on Intel and AMD (x86_64) and Arm (aarch64) platforms, UEK Release 5 Update 2 for Oracle Linux 7 is based on the mainline kernel version 4.14.35 and includes several new features, added functionality, and bug fixes across a range of subsystems. Oracle Linux Virtualization Manager—This new server virtualization management platform can be easily deployed to configure, monitor, and manage an Oracle Linux Kernel-based Virtual Machine (KVM) environment with enterprise-grade performance and support from Oracle. Based on the open source oVirt project, Oracle Linux Virtualization Manager allows enterprise customers to continue supporting their on-premises data center deployments with the KVM hypervisor already available on Oracle Linux 7.6 with the Unbreakable Enterprise Kernel Release 5. Oracle Linux KVM is a feature that has been delivered and supported as part of Oracle Linux for some time. With the release of the UEK Release 5, the Oracle Linux server virtualization solution with KVM has been enhanced. Oracle Linux KVM is the same hypervisor used in Oracle Cloud Infrastructure, giving users an easy migration path to move workloads into Oracle Cloud in the future. Gluster Storage Release 5 for Oracle Linux 7—Gluster is a scalable, distributed file system that aggregates disk storage resources from multiple servers into a single global namespace. The new Gluster Storage Release 5 for Oracle Linux 7, based on the stable release of the upstream Gluster 5, brings customers higher performance, new storage capabilities and improved management. Security and Compliance—Oracle Linux is one of the most secure operating environments. Oracle Linux 7 has just received both a Common Criteria (CC) Certification which was performed against the National Information Assurance Partnership (NIAP) General Purpose Operating System Protection Profile (OSPP) v4.1 as well as a FIPS 140-2 validation of its cryptographic modules. Oracle Linux is currently one of only two operating systems—and the only Linux distribution—on the NIAP Product Compliant List. AMD Secure Memory Encryption—Oracle Linux 7 with UEK Release 5 enables hardware-accelerated memory encryption for data-in-use protection, such as Secure Memory Encryption (SME) for bare metal servers and Secure Encrypted Virtualization (SEV) for virtual machines, available on AMD EPYC processor-based systems. In particular, the SEV capability encrypts the memory of KVM guests so that the hypervisor can’t see the memory even when dumped. Zero-Downtime Patching with Oracle Ksplice—With Oracle Ksplice, you can immediately apply security patches (hypervisor, kernel, and user space) without impacting production environments—and without rebooting. When patching systems with the new Ksplice feature, Known Exploit Detection, not only is the security vulnerability closed, but tripwires are laid down for privilege escalation vulnerabilities. This means that if an attacker attempts to exploit a CVE that was patched, Ksplice notifies you. Moreover, Ksplice Known Exploit Detection will work from inside a container. If a container attempts to exploit a privilege escalation vulnerability, Ksplice will notify at the host level. This, combined with Kata Containers and AMD SEV for secure memory, provides strong protection for running containers. Ksplice zero-downtime patching support is provided to Oracle Cloud Infrastructure subscribers at no additional cost, for Oracle Linux instances, and is also available for Red Hat Enterprise Linux and CentOS instances deployed on Oracle Cloud Infrastructure. To get started, Oracle Linux is freely available—to download, use, and distribute—at Oracle Software Delivery Cloud. Updates can be obtained from Oracle Linux yum server. Additionally, Oracle VM VirtualBox, the most popular cross-platform virtualization software for development environments, can be downloaded on your desktop to run Oracle Linux and the cloud native software covered above, allowing you to easily deploy to the cloud. By using Vagrant boxes for Oracle software on GitHub, you have a more streamlined way to create virtual machines with Oracle software fully configured and ready to go inside of them. Oracle is offering up to 3,500 free hours on Oracle Cloud to developers that would like to use our cloud for their development environment. To learn more about Oracle Linux at KubeCon + CloudNativeCon + Open Source Summit China 2019, attend this session (June 25) and visit the Oracle booth.

Oracle is a committed and active member of the Linux community and is a gold sponsor of KubeCon + CloudNativeCon + Open Source Summit China 2019 (Shanghai, June 24-26, 2019). A founding platinum...

Linux Kernel Development

The Power of XDP

The Power of XDP Oracle Linux kernel developer Alan Maguire talks about XDP, the eXpress DataPath which uses BPF to accelerate packet processing. For more background on BPF, see the series on BPF, wherein he presented an in depth look at the kernel's "Berkeley Packet Filter" -- a useful and extensible kernel function for much more than packet filtering. [Important note: the BPF blog series referred to BPF functionality available in the 4.14 kernel. The functionality described here is for the most part present in that kernel also, but a few of the libbpf functions used in the example program and the layout of the xdp_md metadata structure have changed, and here we refer to the up-to-date (as of the 5.2 kernel) versions.] In previous blog entries I gave a general description of BPF and applied BPF concepts to building tc-bpf programs. In that case, such programs are attached to tc ingress and egress hooks and can carry out packet transformation and other activities there. However, such processing happens after the packet metadata - in Linux this is a "struct sk_buff" - has been allocated. As such there are earlier intervention points where BPF could operate. The goal of XDP is to offer comparable performance to kernel bypass solutions while working with the existing kernel networking stack. For example, we may drop or forward packets directly using XDP, or perhaps simply pass them through the network stack for normal processing. XDP metadata As mentioned in the first article of the BPF series, XDP allows us to attach BPF programs early in packet receive codepaths. A key focus of the design is to minimize overheads, so each packet uses a minimal metadata descriptor: /* user accessible metadata for XDP packet hook * new fields must be added to the end of this structure */ struct xdp_md { __u32 data; __u32 data_end; __u32 data_meta; /* Below access go through struct xdp_rxq_info */ __u32 ingress_ifindex; /* rxq->dev->ifindex */ __u32 rx_queue_index; /* rxq->queue_index */ }; Contrast this to the struct sk_buff definition as described here: https://www.netdevconf.org/2.2/slides/miller-datastructurebloat-keynote.pdf Each sk_buff requires an allocation of at least 216 bytes of metadata. This translates into observable performance costs. XDP program execution XDP comes in two flavours; native XDP requires driver support, and packets are processed before sk_buffs are allocated. This allows us to realize the benefits of a minimal metadata descriptor. The hook comprises a call to bpf_prog_run_xdp, and after calling this function the driver must handle the possible return values - see below for a description of these. As an example, the bnxt_rx_pkt function calls bnxt_rx_xdp, which in turn verifies if an XDP program has been loaded for the RX ring, and if so sets up metadata buffer and calls bpf_prog_run_xdp. bnxt_rx_pkt is called directly from device polling functions and so is called via the net_rx_action for both interrupt processing and polling; in short we are getting our hands on the packet as soon as possible in the receive codepath. generic XDP, where the XDP hooks are called from within the networking stack after the sk_buff has been allocated. Generic XDP allows us to use the benefits of XDP - though at a slightly higer performance cost - without underlying driver support. In this case bpf_prog_run_xdp is called as via netdev's netif_receive_generic_xdp function; i.e. after the skb has been allocated and set up. To ensure that XDP processing works, the skb has to be linearized (made contiguous rather than chunked in data fragments) - again this can cost performance. XDP actions XDP programs can signal a desired behaviour by returning XDP_DROP: drops with XDP are fast, the buffers are just recycled to the rx ring queue XDP_PASS: pass to the normal networking stack, possibly after modification XDP_TX: send out same NIC packet arrived from, after modifying packet XDP_REDIRECT: Using the XDP_REDIRECT action from an XDP program, the program can redirect ingress frames to other XDP enabled netdev Adding support for XDP to a driver requires adding the receive hook calling bpf_prog_run_xdp and handling the various outcomes, and adding setup/teardown functions which dedicate buffer rings to XDP. An example - xdping From the above set of actions, and the desire to minimize per-packet overhead, we can see that use cases such as Distributed Denial of Service mitigation and load balancing make sense. To help illustrate the key concepts in XDP, here we present a fully-worked example of our own. This example is available in recent bpf-next kernels; see https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git/tree/tools/testing/selftests/bpf/xdping.c ...for the userspace program; https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git/tree/tools/testing/selftests/bpf/xdping.h ...for the shared header; and https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git/tree/tools/testing/selftests/bpf/progs/xdping_kern.c ...for the BPF program. xdping is a C program that uses XDP, BPF maps and the ping program to measure round-trip times (RTT) in a similar manner to ping, but with xdping we measure round-trip time from XDP itself, instead of invoking all the additional layers of IP, ICMP and user-space-to-kernel interactions. The idea is that by presenting round-trip times as measured in XDP versus those measured via a traditional ping we can see how much processing traffic in XDP directly can save us in terms of response latency eliminate variations in RTT due to the additional processing layers xdping can operate in either client or server modes. As a client, it is responsible for generating ICMP requests and receiving ICMP replies, measuring RTT and saving the result in a BPF map. It does this by receiving a ping-generated ICMP reply, turning that back into an ICMP request, noting the time and sending it. When the reply is received, the RTT can be calculated As a server, it is responsible for receiving ICMP requests, turning them back into replies Note that the above approach is necessary because XDP is receive-driven; i.e. the XDP hooks are in the receive codepaths. With AF_XDP - the topic of our next XDP blog entry - transmission is also possible, but here we stick to core XDP. Let's see what the program looks like! # ./xdping -I eth4 192.168.55.7 Setting up xdp for eth4, please wait... Normal ping RTT data: PING 192.168.55.7 (192.168.55.7) from 192.168.55.8 eth4: 56(84) bytes of data. 64 bytes from 192.168.55.7: icmp_seq=1 ttl=64 time=0.206 ms 64 bytes from 192.168.55.7: icmp_seq=2 ttl=64 time=0.165 ms 64 bytes from 192.168.55.7: icmp_seq=3 ttl=64 time=0.162 ms 64 bytes from 192.168.55.7: icmp_seq=8 ttl=64 time=0.470 ms --- 192.168.55.7 ping statistics --- 4 packets transmitted, 4 received, 0% packet loss, time 3065ms rtt min/avg/max/mdev = 0.162/0.250/0.470/0.129 ms XDP RTT data: 64 bytes from 192.168.55.7: icmp_seq=5 ttl=64 time=0.03003 ms 64 bytes from 192.168.55.7: icmp_seq=6 ttl=64 time=0.02665 ms 64 bytes from 192.168.55.7: icmp_seq=7 ttl=64 time=0.02453 ms 64 bytes from 192.168.55.7: icmp_seq=8 ttl=64 time=0.02633 ms Note that - unlike ping where it is optional - we must specify an interface for use in ping'ing; we need to know where to load the XDP program. Note also that the RTT measurements from XDP are significantly quicker than those reported by ping. Now ping has support for timestaming, where the network stack processing can use IP timestamps to get more accurate numbers, but not all systems have timestamping enabled. Finally notice one other thing; each ICMP echo packet has an associated sequence number, and we see these reported in the ping output. However note that the final icmp_seq=8 and not 4 as we might expect. This is because our XDP program took that 4th reply, rewrote as a request with sequence number 5 and sent it out. Then when it got that reply and measured the RTT, it did the same again for seq number 6 and so on until it got the 8th reply, realized it had all the numbers it needed (by defalt we do 4 requests, that can be changed with the "-c count" option to xdping) and instead of returning XDP_TX ("send out this modified packet") the program returns XDP_PASS ("pass this packet to the networking stack"). So the ping program finally sees ICMP reply number 8, hence the output. To store RTTs we need a common data structure to store in a BPF map which we shall key using the target (remote) IP address. xdping.h can store this info and be included by the userspace and kernel programs: /* SPDX-License-Identifier: GPL-2.0 */ /* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. */ #define XDPING_MAX_COUNT 10 #define XDPING_DEFAULT_COUNT 4 struct pinginfo { __u64 start; __be16 seq; __u16 count; __u32 pad; __u64 times[XDPING_MAX_COUNT]; }; We store the number of ICMP requests to make ("count"), the start time for the current request ("start"), the current sequence number ("seq") and the RTTs ("times"). Next, here is the implementation of the ping client code for the BPF program, xdping_kern.c: SEC("xdpclient") int xdping_client(struct xdp_md *ctx) { void *data_end = (void *)(long)ctx->data_end; void *data = (void *)(long)ctx->data; struct pinginfo *pinginfo = NULL; struct ethhdr *eth = data; struct icmphdr *icmph; struct iphdr *iph; __u64 recvtime; __be32 raddr; __be16 seq; int ret; __u8 i; ret = icmp_check(ctx, ICMP_ECHOREPLY); if (ret != XDP_TX) return ret; iph = data + sizeof(*eth); icmph = data + sizeof(*eth) + sizeof(*iph); raddr = iph->saddr; /* Record time reply received. */ recvtime = bpf_ktime_get_ns(); pinginfo = bpf_map_lookup_elem(&ping_map, &raddr); if (!pinginfo || pinginfo->seq != icmph->un.echo.sequence) return XDP_PASS; if (pinginfo->start) { #pragma clang loop unroll(full) for (i = 0; i < XDPING_MAX_COUNT; i++) { if (pinginfo->times[i] == 0) break; } /* verifier is fussy here... */ if (i < XDPING_MAX_COUNT) { pinginfo->times[i] = recvtime - pinginfo->start; pinginfo->start = 0; i++; } /* No more space for values? */ if (i == pinginfo->count || i == XDPING_MAX_COUNT) return XDP_PASS; } /* Now convert reply back into echo request. */ swap_src_dst_mac(data); iph->saddr = iph->daddr; iph->daddr = raddr; icmph->type = ICMP_ECHO; seq = bpf_htons(bpf_ntohs(icmph->un.echo.sequence) + 1); icmph->un.echo.sequence = seq; icmph->checksum = 0; icmph->checksum = ipv4_csum(icmph, ICMP_ECHO_LEN); pinginfo->seq = seq; pinginfo->start = bpf_ktime_get_ns(); return XDP_TX; } In the full program, there are two ELF sections; one for the client mode (turn replies into requests and send them, measure RTT), and one for the server (turn requests into replies and send them out). Finally, the user-space program loads the XDP program, intializes the map used by it and kicks off the ping. Here is the main() function that sets up XDP and runs the ping: int main(int argc, char **argv) { __u32 mode_flags = XDP_FLAGS_DRV_MODE | XDP_FLAGS_SKB_MODE; struct addrinfo *a, hints = { .ai_family = AF_INET }; struct rlimit r = {RLIM_INFINITY, RLIM_INFINITY}; __u16 count = XDPING_DEFAULT_COUNT; struct pinginfo pinginfo = { 0 }; const char *optstr = "c:I:NsS"; struct bpf_program *main_prog; int prog_fd = -1, map_fd = -1; struct sockaddr_in rin; struct bpf_object *obj; struct bpf_map *map; char *ifname = NULL; char filename[256]; int opt, ret = 1; __u32 raddr = 0; int server = 0; char cmd[256]; while ((opt = getopt(argc, argv, optstr)) != -1) { switch (opt) { case 'c': count = atoi(optarg); if (count < 1 || count > XDPING_MAX_COUNT) { fprintf(stderr, "min count is 1, max count is %d\n", XDPING_MAX_COUNT); return 1; } break; case 'I': ifname = optarg; ifindex = if_nametoindex(ifname); if (!ifindex) { fprintf(stderr, "Could not get interface %s\n", ifname); return 1; } break; case 'N': xdp_flags |= XDP_FLAGS_DRV_MODE; break; case 's': /* use server program */ server = 1; break; case 'S': xdp_flags |= XDP_FLAGS_SKB_MODE; break; default: show_usage(basename(argv[0])); return 1; } } if (!ifname) { show_usage(basename(argv[0])); return 1; } if (!server && optind == argc) { show_usage(basename(argv[0])); return 1; } if ((xdp_flags & mode_flags) == mode_flags) { fprintf(stderr, "-N or -S can be specified, not both.\n"); show_usage(basename(argv[0])); return 1; } if (!server) { /* Only supports IPv4; see hints initiailization above. */ if (getaddrinfo(argv[optind], NULL, &hints, &a) || !a) { fprintf(stderr, "Could not resolve %s\n", argv[optind]); return 1; } memcpy(&rin, a->ai_addr, sizeof(rin)); raddr = rin.sin_addr.s_addr; freeaddrinfo(a); } if (setrlimit(RLIMIT_MEMLOCK, &r)) { perror("setrlimit(RLIMIT_MEMLOCK)"); return 1; } snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]); if (bpf_prog_load(filename, BPF_PROG_TYPE_XDP, &obj, &prog_fd)) { fprintf(stderr, "load of %s failed\n", filename); return 1; } main_prog = bpf_object__find_program_by_title(obj, server ? "xdpserver" : "xdpclient"); if (main_prog) prog_fd = bpf_program__fd(main_prog); if (!main_prog || prog_fd < 0) { fprintf(stderr, "could not find xdping program"); return 1; } map = bpf_map__next(NULL, obj); if (map) map_fd = bpf_map__fd(map); if (!map || map_fd < 0) { fprintf(stderr, "Could not find ping map"); goto done; } signal(SIGINT, cleanup); signal(SIGTERM, cleanup); printf("Setting up XDP for %s, please wait...\n", ifname); printf("XDP setup disrupts network connectivity, hit Ctrl+C to quit\n"); if (bpf_set_link_xdp_fd(ifindex, prog_fd, xdp_flags) < 0) { fprintf(stderr, "Link set xdp fd failed for %s\n", ifname); goto done; } if (server) { close(prog_fd); close(map_fd); printf("Running server on %s; press Ctrl+C to exit...\n", ifname); do { } while (1); } /* Start xdping-ing from last regular ping reply, e.g. for a count * of 10 ICMP requests, we start xdping-ing using reply with seq number * 10. The reason the last "real" ping RTT is much higher is that * the ping program sees the ICMP reply associated with the last * XDP-generated packet, so ping doesn't get a reply until XDP is done. */ pinginfo.seq = htons(count); pinginfo.count = count; if (bpf_map_update_elem(map_fd, &raddr, &pinginfo, BPF_ANY)) { fprintf(stderr, "could not communicate with BPF map: %s\n", strerror(errno)); cleanup(0); goto done; } /* We need to wait for XDP setup to complete. */ sleep(10); snprintf(cmd, sizeof(cmd), "ping -c %d -I %s %s", count, ifname, argv[optind]); printf("\nNormal ping RTT data\n"); printf("[Ignore final RTT; it is distorted by XDP using the reply]\n"); ret = system(cmd); if (!ret) ret = get_stats(map_fd, count, raddr); cleanup(0); done: if (prog_fd > 0) close(prog_fd); if (map_fd > 0) close(map_fd); return ret; Conclusion We've talked about XDP programs; where they run, what they can do and provided a code example. I hope this inspires you to play around with XDP! Next time we'll cover AF_XDP, a new socket type which uses XDP to support a more complete range of kernel bypass functionality. Be sure to visit our series on BPF,  and stay tuned for our next blog posts! 1. BPF program types 2. BPF helper functions for those programs 3. BPF userspace communication 4. BPF program build environment 5. BPF bytecodes and verifier 6. BPF Packet Transformation

The Power of XDP Oracle Linux kernel developer Alan Maguire talks about XDP, the eXpress DataPath which uses BPF to accelerate packet processing. For more background on BPF, see the series on...

Linux

Getting Started with Oracle Arm Toolset 8

Contents: Why Arm Toolset 8? | devtoolset-8 or armtoolset-8? | Steps | (1) Download .repo | (2) Enable the collection | (3) yum install | (4) Start a shell | (5) Verify | (6) Problems? | Sources Why Use Oracle Arm Toolset 8? Oracle Linux 7 for Arm includes "Oracle Arm Toolset 8", which provides many popular development tools, including: gcc v8.2.0 Supports the 2017 revision of the ISO C standard. g++ v8.2.0 Supports the 2017 revision of the  ISO C++ standard. gfortran v8.2.0 Supports Fortran 2018 go 1.11.1 The Go Programming Language gdb v8.2 The GNU debugger binutils v2.31   Binary utilities The above versions are much more recent than the base system versions. The base system versions are intentionally kept stable for many years, in order to help ensure compatibility for device drivers and other components that may be intimately tied to a specific compiler version. For your own applications, you might want to use more modern language features. For example, Oracle Arm Toolset 8 includes support for C++17.   Illustration credit: adapted by Jamie Henning from wikipedia, license CC-by-2.0 For a complete list of the software packages in Oracle Arm Toolset 8, see the yum repo page Oracle Linux 7 Software Collections. devtoolset-8 or armtoolset-8? If you want to use GCC v8, you will see 2 package sets at Oracle Linux 7 Software Collections: devtoolset-8-gcc-8.2.1-3.el7.aarch64.rpm devtoolset-8-gcc-c++-8.2.1-3.el7.aarch64.rpm devtoolset-8-gcc-gdb-plugin-8.2.1-3.el7.aarch64.rpm . . . [etc] and oracle-armtoolset-8-gcc-8.2.0-6.el7_6.aarch64.rpm oracle-armtoolset-8-gcc-c++-8.2.0-6.el7_6.aarch64.rpm oracle-armtoolset-8-gcc-gdb-plugin-8.2.0-6.el7_6.aarch64.rpm . . . How can you decide which collection to choose? A few differences can be seen in the lists of packages. For example: oracle-armtoolset-8 includes the languages Ada and Go; devtoolset-8 includes an updated version of GNU make. oracle-armtoolset-8 updates support for certain platform-specific optimizations. The most important difference is in shared library handling for C++ applications: C++ applications compiled with oracle-armtoolset-8 require run-time systems to install oracle-armtoolset-8-libstdc++ C++ applications compiled with devtoolset-8 rely only on the system libstdc++ v4.8.5 Of course, the v4.8.5 library does not support C++17 features. The devtoolset compilers solve that problem using non-shared linking for library functions that are newer than the 4.8.5 system C++ library. (To be specific: /opt/rh/devtoolset-8/root/usr/lib/gcc/aarch64-redhat-linux/8/libstdc++.so is a linker script that resolves symbols from the v4.8.5 shared library /usr/lib64/libstdc++.so.6 when possible, or from the v8 libstdc++_nonshared.a otherwise.) The devtoolset method has the usual advantage of static linking: fewer runtime dependencies.  The system administrator need not install a new C++ library. The devtoolset method has the usual disadvantages, reducing both security and maintainability. For more detail, use your favorite search engine to look for: static linking considered harmful Summary: The choice is yours: both provide modern GCC v8 features; from a security and maintainability point of view, you may prefer Oracle Arm Toolset 8.     Installation Steps for Oracle Arm Toolset 8 (1) Download the .repo Download the Oracle Linux repo file: # cd /etc/yum.repos.d # wget http://yum.oracle.com/aarch64/public-yum-ol7.repo (2) Enable the collection In the repo file, set enabled=1 for ol7_software_collections: Edit the .repo file. Notice that there are many repositories. At minimum, you should edit the section about the Software Collection Library to set  enabled=1 While you are there, review the other repositories, and decide whether you would like to enable any others. You can view the Software Collection Library in a browser by going to:  http://yum.oracle.com/repo/OracleLinux/OL7/SoftwareCollections/aarch64/index.html [ol7_software_collections] name=Software Collection Library for Oracle Linux 7 ($basearch) baseurl=https://yum.oracle.com/repo/OracleLinux/OL7/SoftwareCollections/$basearch/ gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle gpgcheck=1 enabled=1 (3) Yum Install # yum install policycoreutils-python # yum install 'oracle-armtoolset-8*' (3a) Why 2 steps? The reason for doing the installation in two steps above is that it avoids a possible installation issue -- one user reported Error unpacking rpm package oracle-armtoolset-8-runtime when the installation was done as a single step. As of April 2019, the possible issue is under investigation; in the meantime, the above method is recommended. (3b) To start over: If you encounter the above installation issue, to start over, try this sequence: # yum remove 'oracle-armtoolset-8*' # yum remove policycoreutils-python # rm -Rf /opt/oracle/oracle-armtoolset-8/ # yum install policycoreutils-python # yum install 'oracle-armtoolset-8*' (4) Start a shell with the software collection $ scl enable oracle-armtoolset-8 bash Note that this will start a new shell.   (Of course, you could change the word ‘bash’ above to some other shell if you prefer.) (5) Verify Verify that the gcc command invokes the correct copy, and that paths are set as expected: which gcc echo $PATH echo $MANPATH echo $INFOPATH echo $LD_LIBRARY_PATH  Expected output: The which command should return: /opt/oracle/oracle-armtoolset-8/root/usr/bin/gcc All four echo commands should begin with: /opt/oracle/oracle-armtoolset-8/   (6) Problems? Wrong gcc? Wrong paths? If Step (5) gives unexpected output, then check whether your shell initialization files are re-setting the path variables. If so here are four possible solutions: (6a) norc Depending on your shell, there is probably an option to start up without initialization. For example, if you are a bash user, you could say: scl enable oracle-armtoolset-8 "bash --noprofile --norc" (6b) silence Alternatively, you can edit your shell initialization files to avoid setting paths, leaving it up to  scl instead. (6c) (RECOMMENDED) Set paths only in your login shell initialization files. The easiest solution is probably to check out the documentation for your shell and notice that it probably executes certain file(s) at login time and certain other file(s) when a new sub shell is created. For example, bash at login time will look for    ~/.bash_profile, ~/.bash_login, or ~/.profile and for sub shells it looks for    ~/.bashrc If you do your path setting in ~/.bash_profile and avoid touching paths in .bashrc, then the scl enable command will successfully add Oracle Arm Toolset 8 to your paths. (6d) (Kludge) enable last  If for some reason you wish to set paths in your sub shell initialization file, then please ensure that the toolset's enable scriptlet is done last. Here is an example from the bottom of my current .bashrc # If this is a shell created by 'scl enable', then make sure that the # 'enable' scriplet is done last, after all other path setting has # been completed. grandparent_cmd=$(ps -o cmd= $(ps -o ppid= $PPID)) if [[ "$grandparent_cmd" =~ "scl enable" ]] ; then #echo "looks like scl" grandparent_which=${grandparent_cmd/scl enable} grandparent_which=${grandparent_which/bash} grandparent_which=${grandparent_which// } grandparent_enable=$(ls /opt/*/$grandparent_which/enable 2>/dev/null) if [[ -f $grandparent_enable ]] ; then sourceit="source $grandparent_enable" echo doing "'$sourceit'" $sourceit else echo "did not find the enable scriplet for '$grandparent_which'" fi fi Sources If you would like the sources, please see  http://yum.oracle.com/repo/OracleLinux/OL7/SoftwareCollections/aarch64/index_src.html

Contents: Why Arm Toolset 8? | devtoolset-8 or armtoolset-8? | Steps | (1) Download .repo | (2) Enable the collection | (3) yum install | (4) Start a shell | (5) Verify | (6) Problems? | Sources Why Us...

Announcements

Announcing Oracle Linux Virtualization Manager

Announcing Oracle Linux Virtualization Manager  Oracle is pleased to announce the general availability of Oracle Linux Virtualization Manager. This new server virtualization management platform can be easily deployed to configure, monitor, and manage an Oracle Linux Kernel-based Virtual Machine (KVM) environment with enterprise-grade performance and support from Oracle. Based on the open source oVirt project, Oracle Linux Virtualization Manager allows enterprise customers to continue supporting their on-premises data center deployments with the KVM hypervisor already available on Oracle Linux 7.6 with the Unbreakable Enterprise Kernel Release 5. Oracle Linux KVM is a feature that has been delivered and supported as part of Oracle Linux for some time. With the release of the Unbreakable Enterprise Kernel Release 5, the Oracle Linux server virtualization solution with KVM has been enhanced. Oracle Linux KVM is the same hypervisor used in Oracle Cloud Infrastructure, giving users an easy migration path to move workloads into Oracle Cloud in the future. Oracle Linux Virtualization Manager release 4.2.8, the first release of this new management platform, supports multiple hosts running Oracle Linux KVM. The heart of the manager is the ovirt-engine which is used to discover KVM hosts and configure storage and networking for the virtualized data center. Oracle Linux Virtualization Manager offers a web-based User Interface (UI) and a Representation State Transfer (REST) Application Programming Interface (API) which can be used to manage your Oracle Linux KVM infrastructure. Oracle Linux Virtualization Manager delivers high performance with a modern web UI. A REST API is available for users that need to integrate with other management systems, or prefer to automate repetitive tasks with scripts. For most day to day operations, many users will rely on the administrative portal or the lighter weight VM portal. These portals (and the REST API Guide) can be accessed from the Oracle Linux Virtualization Manager landing page when first connected with a browser: After logging in from the main landing page, users are presented with a dashboard view which shows all of the key information about their deployment (VM counts, Host counts, Clusters, Storage, etc.), including the current status of each entity, in addition to key performance metrics: From the dashboard, users can move to the Compute view for Hosts, Virtual Machines, Templates, Data Centers, Clusters and Pools, to configure or edit their virtual environments. Additional menus and sub-menus for Network, Storage, Administration, and Events provide full control, with logical workflows, in an easy to use web interface. Notable Features In addition to the base virtualization management features required to operate your data center, notable features in Oracle Linux Virtualization Manager include: Snapshot - create a view of a running virtual machine at a given point in time. Multiple snapshots can be saved and used to return to a previous state, in the event of a problem. The snapshot feature is accessed from the Virtual Machines view: Role Based Access - define different users with different levels of operational permission within Oracle Linux Virtualization Manager: More information on these features can be found in the Oracle Linux Virtualization Manager Document Library. Additional features will be described in more detail in future blogs. In addition to these supported features, planned features may first be made available as technology previews, to allow users to test them in a development environment and offer feedback before the feature is supported. Getting Started Users can take either a previously deployed version of Oracle Linux and turn the OS into a KVM host, or a KVM configuration can be set up from a base Oracle Linux installation. Instructions and reference material can be found in the Oracle Linux Administrator's Guide for Release 7. Oracle Linux Virtualization Manager 4.2.8 can be installed from the Oracle Linux yum server or the Oracle Unbreakable Linux Network. Two new channels have been created in the Oracle Linux 7 repositories that users will access to install or update Oracle Linux Virtualization Manager: oVirt 4.2 - base packages required for Oracle Linux Virtualization Manager oVirt 4.2 Extra Packages - extra packages for Oracle Linux Virtualization Manager Oracle Linux 7.6 hosts can be installed with installation media (ISO images) that is available from Oracle Software Delivery Cloud. Instructions to download the Oracle Linux 7.6 ISO can be found on Oracle Technology Network. Using the "Minimal Install" option, during the installation process, sets up a base KVM system which can then be updated using the KVM Utilities channel in the Oracle Linux 7 repositories. This and other important packages for your Oracle Linux KVM host can be installed from the Oracle Linux yum server and the Oracle Unbreakable Linux Network: Latest - Latest packages released for Oracle Linux 7 UEK Release 5 - Latest Unbreakable Enterprise Kernel Release 5 packages for Oracle Linux 7 KVM Utilities - KVM Utils for Oracle Linux 7 Optional Latest - Latest packages released for Oracle Linux 7 Both Oracle Linux Virtualization Manager and Oracle Linux can be downloaded, used, and distributed free of charge and all updates and errata are freely available Oracle Linux Virtualization Manager Support Support for Oracle Linux Virtualization Manager is available to customers with an Oracle Linux Premier Support subscription. Refer to Oracle Linux 7 License Information User Manual for information about Oracle Linux support levels.

Announcing Oracle Linux Virtualization Manager  Oracle is pleased to announce the general availability of Oracle Linux Virtualization Manager. This new server virtualization management platform can be...

Announcements

New Lenovo Servers with Ampere Arm Processors now Qualified on Oracle Linux

Continuing the companies’ close collaboration, Oracle, Ampere, and Lenovo have completed joint development and testing to qualify Oracle Linux on new Lenovo servers. The Lenovo ThinkSystem HR330A and HR350A include the powerful Ampere eMAG™ Arm® (aarch64) processor and are certified and supported, through the Oracle HCL program, with Oracle Linux 7 Update 6 with the Unbreakable Enterprise Kernel (UEK) Release 5. UEK5 is based on the upstream LTS (long-term stable) kernel version 4.14 and is designed and recommended for enterprise workloads requiring stability, scalability, and performance. Oracle Linux 7 Update 6 (aarch64) is available from Oracle Software Delivery Cloud. Customers deploying these world-class systems deserve world-class support, and that’s just what they’ll get with Oracle Linux support. Oracle offers two levels of support subscriptions for Oracle Linux: Basic and Premier. As always, to support developers and users, Oracle Linux is free to download, use, and distribute. All Oracle Linux updates are freely available on the Oracle Linux yum server, to help users match development and test environments to the same patch level used in production. For more information on the engineering efforts involving Oracle Linux for Arm, please read this blog from Wim Coekaerts, Oracle Senior Vice President, Development. Additional Resources: Oracle Linux Hardware Certification List (HCL) Oracle Linux for Arm data sheet Oracle Linux 7 documentation Oracle Linux FAQ Oracle Linux Support Lenovo ThinkSystem datasheet: HR330A and HR350A

Continuing the companies’ close collaboration, Oracle, Ampere, and Lenovo have completed joint development and testing to qualify Oracle Linux on new Lenovo servers. The Lenovo ThinkSystem HR330A and H...

Announcements

Announcing Gluster Storage Release 5 for Oracle Linux 7

The Oracle Linux and Virtualization team is pleased to announce the release of Gluster Storage Release 5 for Oracle Linux 7, bringing customers higher performance, new storage capabilities and improved management. Gluster Storage is an open source, POSIX compatible file system capable of supporting thousands of clients while using commodity hardware. Gluster provides a scalable, distributed file system that aggregates disk storage resources from multiple servers into a single global namespace. Gluster provides built-in optimization for different workloads and can be accessed using an optimized Gluster FUSE client or standard protocols including SMB/CIFS. Gluster can be configured to enable both distribution and replication of content with quota support, snapshots, and bit-rot detection for self-healing. New Features Gluster Storage Release 5 introduces the support for the following new important capabilities: Gluster block storage: Gluster volumes can be set up as an iSCSI back-store to provide block storage using the gluster-block and tcmu-runner packages. Files on volumes are exported as block storage (iSCSI LUNs). Thanks to this new supported feature your Gluster cluster can act as an iSCSI storage for your development as well as production environments and grant an Enterprise Storage Level with a lower TCO For further details see "Chapter 4 Accessing Volumes" on "Gluster Storage for Oracle Linux User's Guide". Heketi scripted cluster automation: The heketi and heketi-client packages automate the management of a Gluster cluster. Trusted storage pools and volumes can be provisioned and managed using the heketi-cli command, and custom scripts can be written using the API functions exposed by the Heketi service. It is particularly useful for set-up steps during cloud-based deployments that can be automated without requiring manual systems administration. The introduction of Heketi API support opens Gluster as a real Storage-as-a-Service solution for your infrastructure. For further details see "Chapter 5 Automating Volume Lifecycle with Heketi" on "Gluster Storage for Oracle Linux User's Guide". Further enhancement and new features in Gluster Storage Release 5 for Oracle Linux 7 are: Performance Network throughput usage increased up to 5 times Standalone Dentry serializer feature is now enabled by default Python code in Gluster packages is Python 3 ready Added noatime option in utime xlator Enabling the utime and ctime feature enables Gluster to maintain consistent change and modification timestamps on files and directories across bricks. Gluster Storage Release 5 for Oracle Linux 7 supports: The Unbreakable Enterprise Kernel (Release 4 and higher) and the Red Hat Compatible Kernel on x86_64 architecture. The Unbreakable Enterprise Kernel (Release 5) on aarch64 architecture. Configurations upgraded from an existing Gluster Storage Release 3.12 and Gluster Storage Release 4.1. Installation Gluster Storage is available on the Unbreakable Linux Network (ULN) and the Oracle Linux yum server. It is currently available for the x86_64 and aarch64 architectures and can be installed on any Oracle Linux 7 server running the Unbreakable Enterprise Kernel (UEK) Release 4 or 5 or the Red Hat Compatible Kernel (RHCK).  For more information on hardware requirements and how to install and configure Gluster, please review the Gluster Storage for Oracle Linux Release 5 documentation. Support Support for Gluster Storage is available to customers with an Oracle Linux Premier support subscription. Refer to Oracle Linux 7 License Information User Manual for information about Oracle Linux support levels. Oracle Linux Resources: Documentation Oracle Linux Software Download Oracle Linux Oracle Container Registry Blogs Oracle Linux Blog Community Pages Oracle Linux Social Media Oracle Linux on YouTube Oracle Linux on Facebook Oracle Linux on Twitter Data Sheets, White Papers, Videos, Training, Support & more Oracle Linux Product Training and Education Oracle Linux For community-based support, please visit the Oracle Linux space on the Oracle Developer Community.

The Oracle Linux and Virtualization team is pleased to announce the release of Gluster Storage Release 5 for Oracle Linux 7, bringing customers higher performance, new storage capabilities and...

Announcements

Announcing the general availability of the Unbreakable Enterprise Kernel Release 5 Update 2

The Unbreakable Enterprise Kernel (UEK) for Oracle Linux provides the latest open source innovations and key optimizations and security to enterprise cloud workloads. It is the Linux kernel that powers Oracle Cloud and Oracle Engineered Systems such as Oracle Exadata Database Machine as well as Oracle Linux on any Intel-64, AMD-64 or ARM hardware. What's New? UEK R5 Update 2 is based on the mainline kernel version 4.14.35. Through actively monitoring upstream check-ins and collaboration with partners and customers, Oracle continues to improve and apply critical bug and security fixes to the Unbreakable Enterprise Kernel (UEK) R5 for Oracle Linux. This update includes several new features, added functionality, and bug fixes across a range of subsystems. Notable changes: Pressure Stall Information (PSI) patchset implemented. PSI is designed to help system administrators maximize server resources and can be used to pinpoint and troubleshoot resource utilization issues. Implementation of the ktask framework for parallelizing CPU-intensive work. The ktask framework parallelizes CPU-intensive work in the kernel. This helps improve performance by harnessing idle CPUs, to complete jobs more quickly. DTrace support for libpcap packet capture. Kernel and userspace updates enable support for libpcap-based packet capture in DTrace. File system and storage fixes. Fixes to btrfs, CIFS, ext4, OCFS2, and XFS file systems. Virtualization features and updates. Upstream improvements from the 4.19 kernel for KVM, Xen, and Hyper-V, including major updates and security fixes for KVM; numerous security fixes and code enhancements for Hyper-V; fix for the Xen blkfront hotplug issue; and a fix for the Xen x86 guest clock scheduler. Driver updates. In close cooperation with hardware and software vendors, several device drivers have been updated. Kernel tuning dedicated to the Arm platform. Further kernel tuning for Arm platforms and parameters for unsupported hardware have been disabled, to improve stability and performance. NVMe updates. Fixes and improvements for NVMe are included from upstream Linux kernel versions 4.18 through 4.21. For more details on these and other new features and changes, please consult the Release Notes for the UEK R5 Update 2. Security (CVE) Fixes A full list of CVEs fixed in this release can be found in the Release Notes for the UEK R5 Update 2. Supported Upgrade Path Customers can upgrade existing Oracle Linux 7 Update 5 (and later) servers using the Unbreakable Linux Network or the Oracle Linux yum server. Software Download Oracle Linux can be downloaded, used, and distributed free of charge and all updates and errata are freely available. This allows organizations to decide which systems require a support subscription and makes Oracle Linux an ideal choice for development, testing, and production systems. The user decides which support coverage is the best for each system individually, while keeping all systems up-to-date and secure. Customers with Oracle Linux Premier Support also receive access to zero-downtime kernel updates using Oracle Ksplice. Compatibility UEK R5 Update 2 is fully compatible with the UEK R5 GA release. The kernel ABI for UEK R5 remains unchanged in all subsequent updates to the initial release. UEK R5 includes changes to the kernel ABI relative to UEK R4 that require recompilation of third-party kernel modules. About Oracle Linux The Oracle Linux operating system is engineered for an open cloud infrastructure. It delivers leading performance, scalability and reliability for enterprise SaaS and PaaS workloads as well as traditional enterprise applications. Oracle Linux Support offers access to award-winning Oracle support resources and Linux support specialists; zero-downtime updates using Ksplice; additional management tools such as Oracle Enterprise Manager and Spacewalk; and lifetime support, all at a low cost. And unlike many other commercial Linux distributions, Oracle Linux is easy to download, completely free to use, distribute, and update. Oracle tests the UEK intensively with demanding Oracle workloads, and recommends the UEK for Oracle deployments and all other enterprise deployments. Resources – Oracle Linux Documentation Oracle Linux Software Download Oracle Linux Blogs Oracle Linux Blog Oracle Virtualization Blog Community Pages Oracle Linux Social Media Oracle Linux on YouTube Oracle Linux on Facebook Oracle Linux on Twitter Data Sheets, White Papers, Videos, Training, Support & more Oracle Linux Product Training and Education Oracle Linux - education.oracle.com/linux

The Unbreakable Enterprise Kernel (UEK) for Oracle Linux provides the latest open source innovations and key optimizations and security to enterprise cloud workloads. It is the Linux kernel that...

Linux

Cisco Qualifies Cisco Tetration Platform on Oracle Linux Running on Oracle Exadata Database Machine

To provide mutual customers with greater application insights and security, Cisco has qualified the Cisco Tetration platform on Oracle Linux running on Oracle Exadata Database Machine. This combination is available in a Tetration SaaS offering, powered by Oracle Cloud Infrastructure, or on-premises deployments. The Cisco Tetration platform uses workload and network telemetry data to perform advanced analytics using an algorithmic approach and provides comprehensive workload protection for a multi-cloud data center. This algorithmic approach includes unsupervised machine-learning techniques and behavioral analysis. The platform provides a ready-to-use solution for: Visibility into application components, communications, and dependencies, to enable implementation of a zero-trust model in the data center Automatic generation of a whitelist policy, based on application behavior, including existing security policy mandated by business requirements Consistent enforcement of segmentation policies across a multi-cloud infrastructure to minimize lateral movement Identification of software vulnerabilities and exposures to reduce the attack surface Process behavior baselining and identification of deviations for faster detection of Indicators of Compromise (IOCs) By using a multidimensional workload protection approach, Cisco Tetration significantly reduces the attack surface, minimizes lateral movement in case of security incidents, and quickly identifies anomalous behaviors within the data center. Learn more at: https://www.cisco.com/c/en/us/products/collateral/data-center-analytics/tetration-analytics/datasheet-c78-737256.html https://www.cisco.com/c/en/us/products/data-center-analytics/tetration-analytics/index.html https://www.youtube.com/watch?v=_LGLFLDiTTU  

To provide mutual customers with greater application insights and security, Cisco has qualified the Cisco Tetration platform on Oracle Linux running on Oracle Exadata Database Machine....

Linux Kernel Development

Using AMD Secure Memory Encryption with Oracle Linux

Oracle Linux kernel developer Boris Ostrovsky wrote this explanation of AMD's memory encryption technologies.  AMD SME and SEV Introduction Disk encryption by now has become a standard procedure to protect information from an intruder who has physical access to the system but is not able, for example, to log in. However, the other system component used for storing data, system memory, remains largely vulnerable. It is true that extracting data from memory is typically more difficult but techniques like cold-boot attacks show that this is not an impossible task. To make things worse, introduction of non-volatile memory allows one to physically remove the NVDIMM chips from the system and examine their contents at some later time, making data there as easy to access as it would be on a non-encrypted hard drive. To protect system memory from such attacks, hardware manufacturers have been adding support for memory encryption. For example, when AMD recently introduced their EPYC processors, one of the new features was the support for Secure Memory Encryption. (Some of the desktop variants, such as Ryzen Pro, also included this). Secure Memory Encryption (SME) With SME, the data that the processor writes to memory passes through an encryption engine that scrambles it before committing. Conversely, when the data is read, the encryption engine unscrambles it and presents to the processor in its original format. All this is done without any software intervention. The encryption engine implements AES algorithm with an 128-bit encryption key. The key is managed by on-the-chip AMD Secure Processor (AMD-SP) and is generated anew after each reset. The key is not accessible to the software. There are a couple of ways SME can be used. The first is Transparent SME (TSME). In this mode, any software (operating system or hypervisor) will have its memory encrypted, without any special SME support in SW. This mode is enabled by BIOS setting (if the BIOS vendor decides to expose it). While TSME is the easiest to use, it has some limitations. The biggest one is that it does not allow the use of SEV which we will discuss in a moment. The other way of using SME is more flexible in that, in addition to enabling SEV, it also allows encrypting only certain memory regions (with page granularity). This is achieved by setting (typically) bit 47 of the physical address, and therefore requires OS/hypervisor support: for pages that should be encrypted, bit 47 (known as C bit) needs to be set. Secure Encrypted Virtualization (SEV) When a guest is executing on a hypervisor, the latter has access to all the resources used by the guest, including guest's memory. This is obviously not an ideal situation: the guest may be running a highly sensitive application and does not want anyone to see its data. If the hypervisor is compromised, then the guest's secrets can be too. That's where SEV comes to help. With SEV, each guest is assigned (by AMD-SP) an encryption key and can encrypt its pages using the same technique as what is used for SME on bare metal (PTE's C bit). The most important part to keep in mind here is that the key is not available to the hypervisor and therefore it cannot snoop on guest's data (unless the guest decides not to encrypt specific pages, for example, those shared with the hypervisor, such as DMA buffers). Software support SME UEK support for SME is enabled by setting CONFIG_CRYPTO_DEV_SP_PSP and CONFIG_AMD_MEM_ENCRYPT build options. After that, specifying mem_encrypt=on on kernel boot command line will activate SME. Alternatively, if CONFIG_AMD_MEM_ENCRYPT_ACTIVE_BY_DEFAULT is set in the kernel's .config file, then SME is active by default. To verify that SME is on: [root@host ~]# dmesg | grep SME [ 0.000000] AMD Secure Memory Encryption (SME) active [root@host ~]# Keep in mind that SME needs to be enabled by system firmware, and some BIOSes may have it turned off by default. You can check whether it is on by first making sure that the feature is present in the hardware by looking at CPUID Fn8000_001F[EAX].[0]: [root@host ~]# cpuid -r -1 -l 0x8000001f CPU: 0x8000001f 0x00: eax=0x0000000f ebx=0x0000016f ecx=0x0000000f edx=0x00000001 [root@host ~]# and then see if it is enabled by verifying that bit 23 of MSR 0xC0010010 is set: [root@host ~]# rdmsr 0xC0010010 f40000 [root@host ~]# For a quick demo of SME functionality we can use smetest.c, which is provided at the end of this blog post. The driver allocates a page where a secret string is stored and then prints the contents of that page (as stored in DRAM) either with SME enabled on that page (i.e. bit C set on the PTE) or when the page is accessed as unencrypted (bit C is cleared). Since the data was originally stored in memory in encrypted form, trying to access it with encryption disabled should be unsuccessful. The relevant part of the driver is the ioctl routine: static long smetest_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { int ret = 0; char buf[strlen(SECRET_DATA) + 1]; if (!mem_encrypt_active()) return -ENXIO; switch (cmd) { case 1: ret = set_memory_decrypted((unsigned long)secret, 1); case 0: break; default: return -EINVAL; } if (ret) return ret; memcpy(buf, secret, strlen(SECRET_DATA) + 1); if (cmd == 1) { /* Re-encrypt memory */ ret = set_memory_encrypted((unsigned long)secret, 1); /* Make sure string is terminated */ buf[strlen(SECRET_DATA)] = 0; } printk("Secret data is: %s\n", buf); return ret; } When cmd is 0, the C bit on the PTE is kept and therefore the data is decrypted before it is copied into buf. When cmd is 1, set_memory_decrypted() will clear the bit (and also flush caches and TLBs) so the contents of the memory will be read by the processor without passing through the encryption engine. (Notice that we need to terminate the string in this case since the NULL character will be scrambled). Userspace code is: #include <stdlib.h> #include <errno.h> main(int argc, char *argv) { int f; f = open("/dev/smetest", 0); if (f == -1) { perror("open"); exit(errno); } if (ioctl(f, 0)) perror("ioctl(0)"); if (ioctl(f, 1)) perror("ioctl(1)"); close(f); } Here are the results: [root@host ~]# insmod ./smetest.ko [root@host ~]# ./a.out [root@host ~]# dmesg [ 1129.283633] secret is my secret [ 1133.687482] Secret data is: my secret [ 1133.696322] Secret data is: \xffffff81\xffffff83\xffffff93\xffffffa8\xffffffe6\xffffffc\xffffff84\xfffffffc\xffffffb7 [root@host ~]# SEV To enable SEV, CONFIG_KVM_AMD_SEV needs to be set in the Linux configuration file. A newer qemu (such as qemu-3.0.0-4.el7) and OVMF is also required. Start the guest by specifying new qemu object, sev-guest and set machine's memory-encryption attribute. For example: [root@host ~]# qemu-system-x86_64 -enable-kvm -cpu EPYC -machine q35 -smp 1 -m 1G -drive if=pflash,format=raw,unit=0,file=/usr/share/OVMF/OVMF_CODE.pure-efi.fd,readonly -drive if=pflash,format=raw,unit=1,file=/usr/share/OVMF/OVMF_VARS.fd -drive file=./ol76-uefi.qcow2,if=none,id=disk0,format=qcow2 -device virtio-scsi-pci,id=scsi,disable-legacy=on,iommu_platform=true -device scsi-hd,drive=disk0 -nographic -s -device virtio-rng-pci,disable-legacy=on,iommu_platform=true -object sev-guest,id=sev0,cbitpos=47,reduced-phys-bits=1 -machine memory-encryption=sev0 To see whether SEV is available check CPUID Fn8000_001F[EAX].[1]: [root@guest ~]# cpuid -r -1 -l 0x8000001f CPU: 0x8000001f 0x00: eax=0x00000002 ebx=0x0000006f ecx=0x00000000 edx=0x00000000 [root@guest ~]# And to verify that it is active, look at bit 1 of MSR 0xc0010131: [root@guest ~]# rdmsr 0xc0010131 1 [root@guest ~]# You can also verify this by looking at dmesg output to see whether SEV is on: [root@guest ~]# dmesg | grep SEV [ 0.001000] AMD Secure Encrypted Virtualization (SEV) active [ 1.727193] SEV is active and system is using DMA bounce buffers [root@guest ~]# Recall that the main reason behind SEV is to protect guest's memory from being snooped on by the hypervisor. Here is a small example that demonstrates this: #include <stdio.h> #include <stdlib.h> main(int argc, char *argv[]) { char str[32]; int secret = -1; if (argc > 1) secret = atoi(argv[1]); sprintf(str, "My secret is %d\n", secret); sleep(10000); } We run the above code as: root@guest ~]# ./a.out 123 & [1] 3698 [root@guest ~]# We then drop to qemu monitor (Ctrl-A C) and save guest's memory into a file: (qemu) dump-guest-memory /tmp/encrypted (qemu) Now start the guest without SEV (by dropping '-object sev-guest,id=sev0,cbitpos=47,reduced-phys-bits=1 -machine memory-encryption=sev0' options) and save its memory in /tmp/unencrypted. Let's first search unencrypted guest's memory: [root@host ~]# strings /tmp/unencrypted | grep "My secret" My secret is 123 My secret is %d My secret is %d [root@host ~]# and then [root@host ~]# strings /tmp/encrypted | grep "My secret" My secret is %d [root@host ~]# The secret string cannot be discovered when SEV is turned on. (Note that we still see "My secret is %d" string. This is because when the executable was fetched from the disk it was first placed into a buffer shared between the hypervisor (host) and the guest. Since the hypervisor cannot access the guest's encrypted memory, those shared buffers are not encrypted.) Limitations While SEV allows guests to hide contents of their memory, another component that a guest may wish to hide from the host is guest's registers. For example, various encryption keys (such as ssh keys, pgp keys etc.) are often stored in floating-point registers such as %xmm and %ymm and therefore it is important that access to that information is not allowed to any entity outside the guest. Currently it is not possible to limit hypervisor's visibility into this state, although AMD promises that future processors will support SEV-ES (Encrypted State) to address this issue. Another limitation of running guests with SEV is that at the moment live migration (and save/restore in general) are not properly supported. References https://developer.amd.com/sev/ AMD64 Architecture Programmer's Manual Volume 2: System Programming (chapters 7.10 and 15.34 in particular) https://www.kernel.org/doc/Documentation/x86/amd-memory-encryption.txt   Sample kernel module smetest.c https://github.com/oracle/linux-blog-sample-code/blob/amd-sev/smetest.c  

Oracle Linux kernel developer Boris Ostrovsky wrote this explanation of AMD's memory encryption technologies.  AMD SME and SEV Introduction Disk encryption by now has become a standard procedure...

Announcements

Oracle Cloud Developer Image Adds Java SE 11 and 12 and Oracle SQL Developer

We are pleased to announce an exciting new release of the Oracle Cloud Developer Image on Oracle Cloud Infrastructure. The Oracle Cloud Developer Image is an Oracle Linux 7 based, ready-to-run image that allows you to rapidly set up a development environment on Oracle Cloud Infrastructure with the latest Oracle Cloud Infrastructure client tools and Software Development Kits (SDKs), choice of development languages, and database connectors and tools. By deploying the Oracle Cloud Developer Image on Oracle Cloud Infrastructure, you can dramatically reduce the time and cost to develop your cloud applications.  Why is this release exciting?  Two reasons:  First, Oracle Java SE 11 and 12 have been added to the Oracle Cloud Developer Image, and support is now included with Oracle Cloud Infrastructure subscriptions. With the bundling of Oracle Java SE in the image, you can get your enterprise Java development environment up and running in no time and quickly start developing secure, portable, and high-performance applications in the cloud. Second, the Oracle Cloud Developer Image now makes it faster and easier for you to deploy the Oracle SQL Developer integrated development environment in Oracle Cloud, including Oracle SQL Developer Command Line (SQLcl), both now bundled in this new release. Oracle SQL Developer is a free graphical tool that enhances productivity and simplifies database development tasks and management of Oracle databases in both traditional and cloud deployments. SQLcl is a powerful free command line interface that allows you to author, and interactively or batch execute SQL and PL/SQL on Oracle Database.   Here’s a list of what’s included in this latest release of the Oracle Cloud Developer Image on Oracle Cloud Infrastructure: Latest Oracle Linux 7 image for Oracle Cloud Infrastructure Development Languages, Oracle Database Connectors and Tools Oracle Java Platform, Standard Edition (Java SE) 8, 11, 12 Python 3.6 and cx_Oracle 7  Node.js 10 and node-oracledb Go 1.12 Oracle Instant Client 18.5 Oracle SQL Developer 19.1 Oracle SQL Developer Command Line (SQLcl) 19.1 Oracle Cloud Infrastructure Command Line Interface (CLI), Software Development Kits (SDKs) and Tools Oracle Cloud Infrastructure CLI Python, Java, Go, and Ruby Oracle Cloud Infrastructure SDKs Terraform and Oracle Cloud Infrastructure Terraform Provider Oracle Cloud Infrastructure Utilities Other Oracle Container Runtime for Docker Access to Extra Packages for Enterprise Linux (EPEL) via Oracle Linux Yum Server GUI Desktop with access via VNC Server The Oracle Cloud Developer Image is available at no additional cost to Oracle Cloud Infrastructure subscribers. If you do not have an Oracle Cloud Infrastructure account, register for one here. You can try out the Oracle Cloud Developer Image today with available free subscription credits on Oracle Cloud Infrastructure. Getting started is easy and just takes minutes. Simply log into your Oracle Cloud Infrastructure console, and deploy the image from the Marketplace by selecting Marketplace under the main navigation menu under Solutions, Platform and Edge. Search for and select ‘Oracle Cloud Developer Image’. Follow the click-through instructions to launch the Oracle Cloud Developer Image instance. We are always looking for ways to enhance developers' user experience with the Oracle Cloud Developer Image. Your feedback is appreciated. Please send your comments and questions to oraclelinux-info_ww_grp@oracle.com or post them on the Oracle Linux for Oracle Cloud Infrastructure Community. Learn more about the Oracle Cloud Developer Image  Oracle Cloud Marketplace: Oracle Cloud Developer Image Support for Oracle Java SE now Included with Oracle Cloud Infrastructure Run Oracle SQL Developer and Connect to Oracle Autonomous Database Get Started with Autonomous Database and SQLcl in No Time Using Oracle Cloud Developer Image Announcing the Oracle Cloud Developer Image for Oracle Cloud Infrastructure

We are pleased to announce an exciting new release of the Oracle Cloud Developer Image on Oracle Cloud Infrastructure. The Oracle Cloud Developer Image is an Oracle Linux 7 based, ready-to-run image...

Announcements

Oracle Database now available in the Oracle Cloud Marketplace

"From this day forward, Oracle Database deployment will never be the same" ....just because in about 7~20 minutes you will have a fully functional Single Instance Oracle Database on any Oracle Cloud Infrastructure shape, BareMetal included!!! I'm so pleased and honored to announce the "Oracle Database" availability in the "Oracle Cloud MarketPlace". By leveraging the "Oracle Database" you will have the option to automatically deploy a fully functional Database environment by pasting a simple cloud-config script; the deployment allows for basic customization of the environment, further configurations, like adding extra disks, NICs, is always possible post-deployment. The framework allows for simple cleanup and re-deployment, via the Marketplace interface (terminate instance and re-launch), or cleanup the Instance within and re-deploy the same Instance with changed settings (see Usage Info below). To easily introduce to the different customization options, available with the "Oracle Database" we also created a dedicated document with examples on the Oracle Database customization deployment. The deployed Instance will be based on the following software stack: Oracle Cloud Infrastructure Native Instance Oracle Linux 7.6 UEK5 (Unbreakable Enterprise Kernel, release 5) Oracle Database 12cR2 or Oracle Database 18c For further information: Oracle Database deployment on Oracle Cloud Infrastructure Oracle Database on Oracle Cloud MarketPlace Oracle Cloud Marketplace Oracle Cloud: Try it for free

"From this day forward, Oracle Database deployment will never be the same" ....just because in about 7~20 minutes you will have a fully functional Single Instance Oracle Database on any Oracle...

Linux Kernel Development

An update on Meltdown and Enhanced IBRS

In this blog post, Oracle Linux kernel developer Konrad Rzeszutek Wilk gives an update on the state of speculative execution vulnerabilities and mitigations in 2019. In early 2018, researchers announced a novel mechanism to extract sensitive data from CPU cores using the processor's own speculative execution engine. These exploits are termed Speculative Execution Side Channel Vulnerabilities and were described in the meltdown.pdf and spectre.pdf papers. An additional side channel attack was released later in the year, called L1TF. Speculative execution side channel vulnerabilities exploit a race condition in the complicated out-of-order architecture of CPUs. This post describes the state of the art mitigations for such vulnerabilities. A Brief Review of Mitigations First, a brief review of the existing mitigations for speculative execution side channel vulnerabilities. The Linux mitigation for Meltdown is known as KPTI, also known as KAISER: Kernel page table isolation - the window of kernel code that each application has to have mapped is shrunk. For Spectre_v2, there are two existing mitigations: Updated microcode and use a new Model Specific Register (MSR) opcode to frob the CPU to flush it's branch predictors. This is known as Indirect Branch Restricted Speculation (IBRS) albeit the MSR in the documentation is called SPEC_CTRL. A software only mitigation known as retpoline where the branch predictor is slogged through the rodeo so that its predictions are always incorrect. Either mitigation is used on every transition to the kernel. Because they are called so often, these mitigations can have a serious impact on system performance. The L1TF mitigations for applications are much simpler and require changes in handling applications page tables. Mitigations to run VMs also required another microcode update and usage of a new MSR. Note that upstream Linux has not accepted IBRS mitigations - however Oracle (along with other Linux distributions) provides this support so that systems with Skylake CPUs can be mitigated. Read more about that in our blog post on retpoline. EIBRS, you're my only hope When this started (January of 2018), Intel added a flag which would tell the operating system whether any or some of these mitigations would be necessary. If the CPU exposes that it is impervious to Rogue Data Cache Load (RDCL) then this CPU is not affected by L1TF and Meltdown attacks. Great! The Spectre_v2 story is much more complicated. Recall that there are two mitigations: Updated microcode and usage of a new MSR called SPEC_CTRL. Using retpoline - a software construct generated by the compiler. There is a third one that is called the Enhanced Indirect Branch Restricted Speculation or EIBRS. This has only to be activated once, not on every every transition to a more privileged mode like the prior Spectre_v2 mitigations. This means that there are now three mitigations against Spectre_v2: IBRS, Retpoline, EIBRS Oracle's X8 Generation of Engineered Systems and x86 Servers The Oracle's X8 generation of Engineered Systems and x86 servers machines are powered by a Intel Cascade Lake CPUs. This family of CPUs are also known as EIBRS-capable and not susceptible to Rogue Data Cache Load (RDCL) attacks. Simply put, this means that the CPU is not affected by Meltdown or L1TF exploits and that it can pick the fastest of the Spectre_v2 mitigations. The Unbreakable Enterprise Kernel (UEK) takes advantage of that and reports this using both SysFS and using the kernel ring buffers: Using SysFS: $ cat /sys/devices/system/cpu/vulnerabilities/meltdown Not affected $ cat /sys/devices/system/cpu/vulnerabilities/l1tf Not affected $ cat /sys/devices/system/cpu/vulnerabilities/spectre_v2 Mitigation: Enhanced IBRS, IBPB: conditional Kernel ring buffer: # dmesg | grep Spectre [ 0.085762] Spectre V2 : Options: IBRS(enhanced) IBPB retpoline [ 0.085763] Spectre V2 : Mitigation: Enhanced IBRS [ 0.085765] Spectre V2 : Spectre v2 mitigation: Filling RSB on context switch [ 0.085778] Spectre V2 : mitigation: Enabling conditional Indirect Branch Prediction Barrier Or /proc/cpuinfo bugs flags: $ cat /proc/cpuinfo | grep bugs | uniq bugs : spectre_v1 spectre_v2 spec_store_bypass The spectre_v2 flag is still visible as what EIBRS offers is a hardware mechanism to squash branch prediction attacks. Folks can toggle to use retpoline or Enhanced IBRS on these CPUs. You can confirm this by looking at the kernel ring buffer output: [ 0.085762] Spectre V2 : Options: IBRS(enhanced) IBPB retpoline The same output on X7 (Skylake) would be: Spectre V2 : Options: IBRS(basic) IBPB retpoline What about the Spectre v1 A keen observer might notice that the list of bugs still includes Spectre_v1. However, a mitigation is in place for this as well: $ cat /sys/devices/system/cpu/vulnerabilities/spectre_v1 Mitigation: __user pointer sanitization N.B. UEK4 will report lfence mitigation. Solving Spectre_v1 attacks, also know as code gadgets, is a continuing effort. Oracle is using an internally developed static analyzer called Parfait along with an open source static analyzer known as smatch documentation to find them and fix them as they are discovered. The story doesn't end here, though. There is on-going research in the compiler communities to come up with a better solution to this problem. However, it is a very difficult one to solve completely. Resources Documentations that go in details: Reading privileged memory with a side-channel Retpoline: a software construct for preventing branch-target-injection Retpoline: A Branch Target Injection Mitigation Deep Dive: Retpoline: A Branch Target Injection Mitigation Speculative Execution Side Channel Mitigations v3.0 Intel Analysis of Speculative Execution Side Channels SOFTWARE TECHNIQUES FOR MANAGING SPECULATION ON AMD PROCESSORS L1TF Deep Dive: Indirect Branch Restricted Speculation-a Linux kernel boot parameters L1TF - L1 Terminal Fault

In this blog post, Oracle Linux kernel developer Konrad Rzeszutek Wilk gives an update on the state of speculative execution vulnerabilities and mitigations in 2019. In early 2018, researchers...

Linux

Linux kernel 5.0: Features and Developments We Are Watching

Thanks to Chuck Anderson, Linux kernel developer, Oracle, for compiling the information in this post. Enhancements to mainline Linux continue at a steady pace, though we don’t always hear a lot about this work. With the 5.1 release upon us, we wanted to give a shout out to some important and notable additions that the 5.0 release brought to bear. Some we chose because our kernel developers are directly involved, some because they affect Oracle workloads, and others simply because they piqued our interest. Here are our top picks. For a complete overview of Linux kernel 5.0 new features, see LWN. Valuable New Features: arm64 support The arm64 architecture has gained support for a number of features including the kexec_file_load() system call, 52-bit virtual address support for user space, hotpluggable memory, per-thread stack canaries, and pointer authentication (for user space only at this point). This commit has some documentation for the pointer-authentication feature. Retpoline-elimination The first two of the retpoline-elimination mechanisms described in this article have been merged, improving performance in core parts of the DMA mapping and networking layers. Core Kernel Changes: The long-awaited energy-aware scheduling patches have found their way into the mainline. This code adds a new energy model that allows the scheduler to determine the relative power cost of scheduling decisions. This enables the mainline scheduler to get better results on mobile devices and, should reduce or eliminate the scheduler patching that various vendors engage in now. The cpuset controller now works (with reduced features) under the version-2 control-group API. See the documentation updates in this commit for details. There is also a new "dynamic events" interface to the tracing subsystem. It unifies the three distinct interfaces (for kprobes, uprobes, and synthetic events) into a single control file. See this patch posting for a brief overview of how this interface works. Improving idle behavior in tickless systems Lead paragraph: "Most processors spend a great deal of their time doing nothing, waiting for devices and timer interrupts. In these cases, they can switch to idle modes that shut down parts of their internal circuitry, especially stopping certain clocks. This lowers power consumption significantly and avoids draining device batteries. There are usually a number of idle modes available; the deeper the mode is, the less power the processor needs. The tradeoff is that the cost of switching to and from deeper modes is higher; it takes more time and the content of some caches is also lost. In the Linux kernel, the cpuidle subsystem has the task of predicting which choice will be the most appropriate. Recently, Rafael Wysocki proposed a new governor for systems with tickless operation enabled that is expected to be more accurate than the existing menu governor." Ringing in a new asynchronous I/O API: io_uring io_uring is a new asynchronous I/O kernel interface whose development we’ve been watching with great interest, not only because it promises to deliver buffered asynchronous I/O via a simplified interface, but especially for its efficiency, scalability and the performance gains that come with it. For more background, see this article by the architect and lead io_uring developer, Jens Axboe. Lead paragraph: "While the kernel has had support for asynchronous I/O (AIO) since the 2.5 development cycle, it has also had people complaining about AIO for about that long. The current interface is seen as difficult to use and inefficient; additionally, some types of I/O are better supported than others. That situation may be about to change with the introduction of a proposed new interface from Jens Axboe called "io_uring". As might be expected from the name, io_uring introduces just what the kernel needed more than anything else: yet another ring buffer." Pressure stall monitors Lead paragraph: "One of the useful features added during the 4.20 development cycle was the availability of pressure-stall information, which provides visibility into how resource-constrained the system is. Interest in using this information has spread beyond the data-center environment where it was first implemented, but it turns out that there some shortcomings in the current interface that affect other use cases. Suren Baghdasaryan has posted a patch set aimed at making pressure-stall information more useful for the Android use case — and, most likely, for many other use cases as well." Persistent memory for transient data Lead paragraph: "Arguably, the most notable characteristic of persistent memory is that it is persistent: it retains its contents over power cycles. One other important aspect of these persistent-memory arrays that, we are told, will soon be everywhere, is their sheer size and low cost; persistent memory is a relatively inexpensive way to attach large amounts of memory to a system. Large, cheap memory arrays seem likely to be attractive to users who may not care about persistence and who can live with slower access speeds. Supporting such users is the objective of a pair of patch sets that have been circulating in recent months." Concurrency management in BPF Lead paragraph "In the beginning, programs run on the in-kernel BPF virtual machine had no persistent internal state and no data that was shared with any other part of the system. The arrival of eBPF and, in particular, its maps functionality, has changed that situation, though, since a map can be shared between two or more BPF programs as well as with processes running in user space. That sharing naturally leads to concurrency problems, so the BPF developers have found themselves needing to add primitives to manage concurrency (the "exchange and add" or XADD instruction, for example). The next step is the addition of a spinlock mechanism to protect data structures, which has also led to some wider discussions on what the BPF memory model should look like." io_uring, SCM_RIGHTS, and reference-count cycles Lead paragraph: "The io_uring mechanism that was described here, in January has been through a number of revisions since then; those changes have generally been fixing implementation issues rather than changing the user-space API. In particular, this patch set seems to have received more than the usual amount of security-related review, which can only be a good thing. Security concerns became a bit of an obstacle for io_uring, though, when virtual filesystem (VFS) maintainer Al Viro threatened to veto the merging of the whole thing. It turns out that there were some reference-counting issues that required his unique experience to straighten out." Per-vector software-interrupt masking Lead paragraph: "Software interrupts (or "softirqs") are one of the oldest deferred-execution mechanisms in the kernel, and that age shows at times. Some developers have been occasionally heard to mutter about removing them, but softirqs are too deeply embedded into how the kernel works to be easily ripped out; most developers just leave them alone. So the recent per-vector softirq masking patch set from Frederic Weisbecker is noteworthy as an exception to that rule. Weisbecker is not getting rid of softirqs, but he is trying to reduce their impact and improve their latency." Memory-mapped I/O without mysterious macros Lead paragraph:"Concurrency is hard even when the hardware's behavior is entirely deterministic; it gets harder in situations where operations can be reordered in seemingly random ways. In these cases, developers tend to reach for barriers as a way of enforcing ordering, but explicit barriers are tricky to use and are often not the best way to think about the problem. It is thus common to see explicit barriers removed as code matures. That now seems to be happening with an especially obscure type of barrier used with memory-mapped I/O (MMIO) operations." Reimplementing printk() Lead paragraph: "The venerable printk() function has been part of Linux since the very beginning, though it has undergone a fair number of changes along the way. Now, John Ogness is proposing to fundamentally rework printk() in order to get rid of handful of issues that currently plague it. The proposed code does this by adding yet another ring-buffer implementation to the kernel; this one is aimed at making printk() work better from hard-to-handle contexts. For a task that seems conceptually simple—printing messages to the console—printk() is actually a rather complex beast; that won't change if these patches are merged, though many of the problems with the current implementation will be removed." The RCU API, 2019 edition Lead paragraph:"Read-copy update (RCU) is a synchronization mechanism that was added to the Linux kernel in October 2002. RCU is most frequently described as a replacement for reader-writer locking, but has also been used in a number of other ways. RCU is notable in that readers do not directly synchronize with updaters, which makes RCU read paths extremely fast; that also permits RCU readers to accomplish useful work even when running concurrently with updaters. Although the basic idea behind RCU has not changed in decades following its introduction into DYNIX/ptx, the API has evolved significantly over the five years since the 2014 edition of the RCU API, to say nothing of the nine years since the 2010 edition of the RCU API." Containers as kernel objects — again Lead paragraph: "Linus Torvalds once famously said that there is no design behind the Linux kernel. That may be true, but there are still some guiding principles behind the evolution of the kernel; one of those, to date, has been that the kernel does not recognize "containers" as objects in their own right. Instead, the kernel provides the necessary low-level features, such as namespaces and control groups, to allow user space to create its own container abstraction. This refusal to dictate the nature of containers has led to a diverse variety of container models and a lot of experimentation. But that doesn't stop those who would still like to see the kernel recognize containers as first-class kernel-supported objects." Internal Kernel Changes: There is a new "software node" concept that is meant to be analogous to the "firmware nodes" created in ACPI or device-tree descriptions. See this commit for some additional information. The software-tag-based mode for KASAN has been added for the arm64 architecture. The switch to using JSON schemas for device-tree bindings has begun with the merging of the core infrastructure and the conversion of a number of binding files. The long-deprecated SUBDIRS= build option is going away in the 5.3 merge window; users will start seeing a warning as of 5.0. The M= option should be used instead. The venerable access_ok() function, which verifies that an address lies within the user-space region, has lost its first argument. This argument was either VERIFY_READ or VERIFY_WRITE depending on the type of access, but no implementation of access_ok() actually used that information. Filesystems and Block Layer Changes: The Btrfs filesystem has regained the ability to host swap files, though with a lot of limitations (no copy-on-write, must be stored on a single device, and no compression allowed, for example). The fanotify() mechanism supports a new FAN_OPEN_EXEC request to receive notifications when a file is opened to be executed. The legacy (non-multiqueue) block layer code has been removed, now that no drivers require it. The legacy I/O schedulers (including CFQ and deadline) have been removed as well. Networking Changes: Generic receive offload (GRO) can now be enabled on plain UDP sockets. Benchmark numbers in this commit show a significant increase in receive bandwidth and a large reduction in the number of system calls required. ICMP error handling for UDP tunnels is now supported. The MSG_ZEROCOPY option is now supported for UDP sockets. Security Changes Support for the Streebog hash function (also known as GOST R 34.11-2012) has been added to the cryptographic subsystem. The kernel is now able to support non-volatile memory arrays with built-in security features; see Documentation/nvdimm/security.txt for details. A small piece of the secure-boot lockdown patch set has landed in the form of additional control over the kexec_load_file() system call. There is a new keyring (called .platform) for keys provided by the platform; it cannot be updated by a running system. Keys in this ring can be used to control which images may be run via kexec_load_file(). It has also become possible for security modules to prevent calls to kexec_load(), which cannot be verified in the same manner. The secure computing (seccomp) mechanism can now defer policy decisions to user space. See this new documentation for details on the final version of the API. The fscrypt filesystem encryption subsystem has gained support for the Adiantum encryption mode (which was added earlier in the merge window). The semantics of the mincore() system call have changed. In this commit, Linus Torvalds explains, how the new semantics of this system call restrict access to pages that are mapped by the calling process. An ancient OpenSSH vulnerability Lead paragraph:: "An advisory from Harry Sintonen describes several vulnerabilities in the scp clients shipped with OpenSSH, PuTTY, and others. "Many scp clients fail to verify if the objects returned by the scp server match those it asked for. This issue dates back to 1983 and rcp, on which scp is based. A separate flaw in the client allows the target directory attributes to be changed arbitrarily. Finally, two vulnerabilities in clients may allow server to spoof the client output." The outcome is that a hostile (or compromised) server can overwrite arbitrary files on the client side. There do not yet appear to be patches available to address these problems." Defending against page-cache attacks Lead paragraph: "The kernel's page cache works to improve performance by minimizing disk I/O and increasing the sharing of physical memory. But, like other performance-enhancing techniques that involve resources shared across security boundaries, the page cache can be abused as a way to extract information that should be kept secret. A recent paper [PDF] by Daniel Gruss and colleagues showed how the page cache can be targeted for a number of different attacks, leading to an abrupt change in how the mincore() system call works at the end of the 5.0 merge window. But subsequent discussion has made it clear that mincore() is just the tip of the iceberg; it is unclear what will really need to be done to protect a system against page-cache attacks or what the performance cost might be." Fixing page-cache side channels, second attempt Lead paragraph:"The kernel's page cache, which holds copies of data stored in filesystems, is crucial to the performance of the system as a whole. But, as has recently been demonstrated, it can also be exploited to learn about what other users in the system are doing and extract information that should be kept secret. In January, the behavior of the mincore() system call was changed in an attempt to close this vulnerability, but that solution was shown to break existing applications while not fully solving the problem. A better solution will have to wait for the 5.1 development cycle, but the shape of the proposed changes has started to come into focus." A proposed API for full-memory encryption Lead paragraph: "Hardware memory encryption is, or will soon be, available on multiple generic CPUs. In its absence, data is stored — and passes between the memory chips and the processor — in the clear. Attackers may be able to access it by using hardware probes or by directly accessing the chips, which is especially problematic with persistent memory. One new memory-encryption offering is Intel's Multi-Key Total Memory Encryption (MKTME) [PDF]; AMD's equivalent is called Secure Encrypted Virtualization (SEV). The implementation of support for this feature is in progress for the Linux kernel. Recently, Alison Schofield proposed a user-space API for MKTME, provoking a long discussion on how memory encryption should be exposed to the user, if at all." Other Developments of Note Snowpatch: continuous-integration testing for the kernel Lead paragraph: "Many projects use continuous-integration (CI) testing to improve the quality of the software they produce. By running a set of tests after every commit, CI systems can identify problems quickly, before they find their way into a release and bite unsuspecting users. The Linux kernel project lags many others in its use of CI testing for a number of reasons, including a fundamental mismatch with how kernel developers tend to manage their workflows. At linux.conf.au 2019, Russell Currey described a CI system called Snowpatch that, he hopes, will bridge the gap and bring better testing to the kernel development process." The Firecracker virtual machine monitor The Firecracker virtual machine monitor is not strictly speaking a Linux kernel 5.0 feature but it does use the KVM API. Lead paragraph:"Cloud computing services that run customer code in short-lived processes are often called "serverless". But under the hood, virtual machines (VMs) are usually launched to run that isolated code on demand. The boot times for these VMs can be slow. This is the cause of noticeable start-up latency in a serverless platform like Amazon Web Services (AWS) Lambda. To address the start-up latency, AWS developed Firecracker, a lightweight virtual machine monitor (VMM), which it recently released as open-source software. Firecracker emulates a minimal device model to launch Linux guest VMs more quickly. It's an interesting exploration of improving security and hardware utilization by using a minimal VMM built with almost no legacy emulation."   As covered above, there are many interesting developments in mainline Linux kernel 5.0, some of which we believe are interesting for Oracle customers. As of this writing 5.0.10 is considered stable. We will continue to monitor developments in upcoming kernels, so look for a blog post with highlights in the next few months. Additional Resources: For more on mainline Linux and other related topics, see: LWN Oracle’s Linux Kernel Development blog  

Thanks to Chuck Anderson, Linux kernel developer, Oracle, for compiling the information in this post. Enhancements to mainline Linux continue at a steady pace, though we don’t always hear a lot about...

Events

Meet the Oracle Linux and Virtualization Team at Dell Technologies World

April 29 – May 2, 2019, Las Vegas, Nevada   Heading to Las Vegas next week for Dell Technologies World, April 29 – May 2, 2019, at The Venetian hotel? It’s a great opportunity to learn about the latest advancements in Oracle Linux and virtualization technologies. Optimized for hybrid cloud environments, these Oracle offerings are used in both on-premises and cloud deployments, running billions of transactions per day.  At the conference, you can also learn about Oracle and Dell EMC’s deep engineering relationship. The companies have been working together for many years on industry solutions like data integrity, and to provide support for mutual customers. DELL EMC works closely with Oracle to qualify its servers and storage on Oracle Linux and Oracle VM and to provide validated configurations to help customers efficiently deploy joint solutions. Here’s where you can learn more: Oracle Linux and Virtualization @ Dell Technologies World Demos with Product Experts in Booth #124 Stop by our booth – #124 – meet our team and learn about Oracle Linux, Oracle VM, Oracle VM VirtualBox, cloud native solutions, and more. Talk with product experts, let us answer your questions, and guide you to the best solution for your business. Presentations Tuesday, April 30, @ 4:00 PM  Location: Theater 4 in the Storage Section of the Dell Technologies Infrastructure Solutions Booth Simplify Cloud Infrastructure Deployments, Increase Performance and Enhance Data Integrity with Oracle and Dell EMC This session will cover how to achieve peak performance for Oracle workloads running on Oracle Linux with Dell EMC servers and storage. You'll also learn how Oracle and Dell EMC's collaboration, including joint qualifications and data integrity standards, can help you save time and costs on cloud infrastructure and on-premises deployments. Speakers: Michele Resta, Product Management Senior Director, Oracle Linux and Virtualization Yaron Dar, Director, Partner Engineering, Dell EMC Wednesday, May 1, @ 12:10 PM Location: World Chat Theatre A on the Exhibit Floor Build a Cloud Native Environment with Oracle Linux Tried, tested, and tuned for enterprise workloads, Oracle Linux is used by developers worldwide. Oracle Linux offers an open, integrated operating environment with application development tools, management tools, containers, and orchestration capabilities, which enable DevOps teams to efficiently build reliable, secure cloud native applications. In this session learn how Oracle Linux can help you enhance productivity. Speaker: Ken Ellis, Sales Consulting Director, Oracle Monday, Apr 29, 4:30 PM – Location: Marco Polo 704 or Thursday, May 2, 1:00 PM – Location: Delfino 4005 Dell EMC PowerMax & Oracle: Performance, Availability & Efficiency Deep-Dive This session will focus on proof points, best practices, and guidelines for achieving peak performance for Oracle workloads, maintaining high availability through disasters, and achieving amazing data reduction and storage efficiency for Oracle databases. Speaker:  Yaron Dar, Director, Partner Engineering, Dell EMC Engage with Us on Social Media We will keep you up-to-date on conference happenings. Join the conversation via #OracleLinux @OracleLinux Register for Dell Technologies World, where you can learn new capabilities, how to reinvent processes, innovate faster and create value that will change the game for your business.  We look forward to seeing you at the conference. The Oracle Linux and Virtualization team

April 29 – May 2, 2019, Las Vegas, Nevada   Heading to Las Vegas next week for Dell Technologies World, April 29 – May 2, 2019, at The Venetian hotel? It’s a great opportunity to learn about the latest...

Linux Kernel Development

Towards A More Secure QEMU Hypervisor, Part 3 of 3

In this blog, the third in a series of three, Oracle Linux developer Jag Raman analyzes the performance of the disaggregated QEMU. Performance of Separated LSI device It is essential to check how the Separated LSI device performs in comparison with the LSI device built into QEMU. For this purpose, we ran CloudHarmony block-storage benchmark on both. We ran this benchmark on a BareMetal instance in Oracle Cloud. The results are summarized below. CloudHarmony results   For detailed CloudHarmony report, see the following performance reports:please follow the links below: Performance of Built-in LSI device (pdf) Performance of Separated LSI device (pdf) Built-in LSI vs. Separated LSI Analysis of Performance The Separated LSI device performs very similarly to the Built-in LSI device. There are some cases where there is a gap between them. We are working on improving our understanding of why this is the case, and have detailed proposals available to bridge the gap. Following is a technical discussion of the performance problem and plans to fix it. Message passing overhead The current model for multi-process QEMU uses a communication channel with Unix sockets to transfer messages between QEMU & the Separated process. Since MMIO read/write is also passed as a message, there is a significant overhead associated with the syscall used to move the MMIO request to the Separated device. We believe that this overhead adds up, especially in the cases where the IOPS are large, resulting in a noticeable performance drop. The following proposal tries to minimize this overhead. MMIO acceleration proposal The majority of data transfer between the VM & Separated process happens over DMA (which has no overhead). However, MMIO writes are used to initiate these transfers, and MMIO reads are used to monitor the status/completion of IO requests. We think that in some cases, these MMIO accesses could contribute to the IO performance. Even small overhead per MMIO could cumulatively result in a performance drop, especially in the case of high IOPS devices. As a result, it is essential to reduce the amount of this overhead, as much as possible. We are working on the following proposal to accelerate MMIO access. The proposal is to bypass QEMU and forward all the MMIOs trapped by Kernel/KVM directly to the Separated process. Secondly, a shared ring buffer would be used to send messages to the Separated process, instead of using Unix sockets. These two changes are expected to reduce the overhead associated with MMIO access, thereby improving performance.

In this blog, the third in a series of three, Oracle Linux developer Jag Raman analyzes the performance of the disaggregated QEMU. Performance of Separated LSI device It is essential to check how the...

Announcements

Announcing the Oracle Cloud Developer Image for Oracle Cloud Infrastructure

We are pleased to introduce the Oracle Cloud Developer Image, an Oracle Linux 7 based, ready-to-run image that provides a comprehensive out-of-the-box development platform on Oracle Cloud Infrastructure. The Oracle Cloud Developer Image enables you to rapidly pre-install, and automatically configure and launch a comprehensive development environment on Oracle Cloud Infrastructure that includes the latest tools, choice of popular development languages, Oracle Cloud Infrastructure Software Development Kits (SDKs), and database connectors.  The Oracle Cloud Developer Image for Oracle Cloud Infrastructure provides you with easy access to all the tools needed throughout the development lifecycle at your fingertips. You can use command line and GUI tools to write, debug, and run code in a variety of languages, and develop modern applications on Oracle Cloud Infrastructure. The introductory release of the Oracle Cloud Developer Image includes the following tools and packages: Latest Oracle Linux 7 image for Oracle Cloud Infrastructure Languages and Oracle Database Connectors Java Platform, Standard Edition (Java SE) 8 Python 3.6 cx_Oracle 7 Python module for Python 2.7 Node.js 10 and node-oracledb Go 1.12 Oracle Instant Client 18.5 Oracle Cloud Infrastructure Command Line Interface (CLI), Software Development Kits (SDKs) and Tools Oracle Cloud Infrastructure CLI Python, Java, Go, and Ruby Oracle Cloud Infrastructure SDKs Terraform and Oracle Cloud Infrastructure Terraform Provider Oracle Cloud Infrastructure Utilities Other Oracle Container Runtime for Docker Extra Packages for Enterprise Linux (EPEL) via Yum GUI Desktop with access via VNC Server More tools and packages will be included with the Oracle Cloud Developer Image in upcoming releases. Here are some examples of use cases where you can take advantage of the out-of-the-box tools included with Oracle Cloud Developer Image: Easily access a VNC client or SSH to connect to a desktop environment Use Oracle Cloud Infrastructure CLI and SDKs Create an Autonomous Transaction Processing Database and connect to it using Python, Java, PHP, and Node.js Use Terraform scripts and templates to configure and build the cloud application infrastructure Run Docker containers To get started, simply log into your Oracle Cloud Infrastructure console, and deploy the image from the Marketplace by selecting Marketplace under the main navigation menu under Solutions, Platform and Edge. Search for and select ‘Oracle Cloud Developer Image’. Follow the click-through instructions to launch the Oracle Cloud Developer Image instance. The Oracle Cloud Developer Image is available at no additional cost to Oracle Cloud Infrastructure subscribers. If you do not already have an Oracle Cloud Infrastructure account, register for one here. You can try out the Oracle Cloud Developer Image today with available free subscription credits on Oracle Cloud Infrastructure. We welcome your feedback on the Oracle Cloud Developer Image.  Please send your comments and questions to oraclelinux-info_ww_grp@oracle.com or post them on the Oracle Linux for Infrastructure Community. For more information, visit the following links: Oracle Linux Oracle Linux 7 Documentation Oracle Linux for Oracle Cloud Infrastructure Blog: Click to Launch Images by Using the Marketplace in Oracle Cloud Infrastructure Oracle Linux Blog Oracle Linux for Oracle Cloud Infrastructure Community Pages Oracle Linux for Oracle Cloud Infrastructure Training    

We are pleased to introduce the Oracle Cloud Developer Image, an Oracle Linux 7 based, ready-to-run image that provides a comprehensive out-of-the-box development platform on Oracle Cloud...

Linux

New Oracle Validated Configurations on Lenovo ThinkSystem Servers and Storage

Check out the latest Oracle Validated Configurations on Lenovo, published on the Oracle Validated Configurations website. These configurations use Lenovo ThinkSystem SR650/SR850/SR950 Servers with ThinkSystem Storage DM5000F.     Through Oracle Validated Configurations and the Hardware Certification List (HCL), Lenovo has performed thorough testing of its hardware in real-world configurations with Oracle Linux and Oracle VM. This helps assure mutual customers that Lenovo hardware is qualified on Oracle Linux and Oracle VM and the combined solution can provide optimal performance and reliability, with faster, lower-cost implementations. Additionally, the validated configurations can help minimize risk for enterprises by reducing deployment testing and validation efforts. The three latest validated configurations are qualified on Oracle Linux 7 and Oracle VM. These pre-tested, validated reference architectures - including software, hardware, storage, and network components are: Lenovo ThinkServer SR950 with ThinkSystem DM5000F storage array Lenovo ThinkServer SR850 with ThinkSystem DM5000F storage array Lenovo ThinkServer SR650 with ThinkSystem DM5000F storage array Lenovo ThinkSystem SR950 Server The Lenovo ThinkSystem SR950 is a 4U Rack server supports up to 8 processors and 96 DIMMs. It is designed for your most demanding, mission-critical workloads, such as Oracle in-memory databases, large transactional databases, batch and real-time analytics, ERP, CRM, and virtualized server workloads. Lenovo ThinkSystem SR850 Server Lenovo ThinkSystem SR850 is a 4-socket server that features a streamlined 2U rack design that is optimized for price and performance, with best-in-class flexibility and expandability. Built for workloads like general business applications, server consolidation, and accelerating transactional databases and analytics. Lenovo ThinkSystem SR650 Server Lenovo ThinkSystem SR650 is an ideal 2-socket server for small businesses up to large enterprises that need industry-leading reliability, management, and security, as well as the ability maximize performance and flexibility for future growth. The SR630 server is designed to handle a wide range of workloads, such as databases, virtualization, and cloud computing. Lenovo ThinkSystem DM5000F storage array Lenovo ThinkSystem DM5000F is a unified, all flash entry-level storage system that is designed to provide performance, simplicity, capacity, security, and high availability for medium to large businesses. Powered by the ONTAP software, ThinkSystem DM5000F delivers enterprise-class storage management capabilities with a wide choice of host connectivity options and enhanced data management features. The ThinkSystem DM5000F can handle a wide range of enterprise workloads, including big data and analytics, artificial intelligence, engineering and design, enterprise applications, and other storage I/O-intensive applications. Validated Configuration Summary:  Two Lenovo Think System SR650/SR850/SR950  Lenovo Think System Storage DM5000F  Lenovo Rackswitch G8272  Lenovo Think System Storage switch 32 GB FC SAN Switch DB620S  Intel Quad 10 GbE SFP+ adapter  QLogic 32 GB FC Dual-port HBA Oracle Linux 7 Update 6 with the Unbreakable Enterprise Kernel Release 4 Oracle Database 12c Release 2 These tested configurations, along with the benefits of reliability, availability, and serviceability (RAS) features from Lenovo Think System Server and Storage, are an excellent choice for business-critical Oracle deployments. These Oracle Validated Configuration -- from 2 Socket SR650 to 8 Socket SR950 -- provide flexibility for enterprises to choose the configuration that suits their enterprise workload demands. To learn more about the benefits of Lenovo Think System Servers and Storage, visit: Lenovo Servers for Mission Critical Workloads.

Check out the latest Oracle Validated Configurations on Lenovo, published on the Oracle Validated Configurations website. These configurations use Lenovo ThinkSystem SR650/SR850/SR950 Servers with...

Announcements

Announcing Oracle VirtIO Drivers 1.1.3 for Microsoft Windows

We are pleased to announce Oracle VirtIO Drivers for Microsoft Windows release 1.1.3. The Oracle VirtIO Drivers for Microsoft Windows are paravirtualized (PV) drivers for Microsoft Windows guests that are running on Oracle Linux KVM. The Oracle VirtIO Drivers for Microsoft Windows improve performance for network and block (disk) devices on Microsoft Windows guests and resolve common issues. What's New The Oracle VirtIO Drivers for Microsoft Windows 1.1.3 provides a new “Custom” installation option that facilitates the migration of guest VMs to run in PV mode on Oracle Cloud Infrastructure (OCI). This enables you to run existing Microsoft Windows images as PV instances on OCI. The “Default” option installs the Oracle VirtIO Drivers on the Microsoft Windows guest running on Oracle Linux KVM. Oracle VirtIO Drivers 1.1.3 is built on the 1.1.2 release of VirtIO Drivers that have been certified by Microsoft. The update (from 1.1.2 to 1.1.3) is due to a new custom installation option. Existing customers using Oracle VirtIO Drivers 1.1.2 do not need to upgrade to the 1.1.3 release. The new "Custom" installation, executed on a Microsoft Windows virtual machine in "Oracle Cloud Infrastructure - Classic (OCI-C)" or on premises in an Oracle VM virtual machine, adds and activates the Oracle VirtIO drivers required to run paravirtualized mode on Oracle Cloud Infrastructure. Oracle VirtIO Drivers 1.1.3 supports the KVM hypervisor with Oracle Linux 7 on premises and on Oracle Cloud Infrastructure. The following guest Microsoft Windows operating systems are supported:   Guest OS 64-bit 32-bit Microsoft Windows Server 2016 Yes Not Available Microsoft Windows Server 2012 R2 Yes Not Available Microsoft Windows Server 2012 Yes Not available Microsoft Windows Server 2008 R2 SP1 Yes Not Available Microsoft Windows Server 2008 SP2 Yes Yes Microsoft Windows Server 2003 R2 SP2 Yes Yes Microsoft Windows 10 Yes Yes Microsoft Windows 8.1 Yes Yes Microsoft Windows 7 SP1 Yes Yes Microsoft Windows Vista SP2 Yes Yes   For further details related to support and certifications, refer to the Oracle Linux 7 Administrator's Guide. Additional information on the Oracle VirtIO Drivers 1.1.2 certifications can be found in the Windows Server Catalog.   Downloading Oracle VirtIO Drivers Oracle VirtIO Drivers release 1.1.3 is available on the Oracle Software Delivery Cloud by searching on "Oracle Linux" Click on the "Add to Cart" button and then click on "Checkout" in the right upper corner. On the following window, select "x86-64" and click on the "Continue" button: Click on "V981734-01.zip - Oracle VirtIO Drivers Version for Microsoft Windows 1.1.3" to download the drivers:   The Oracle VirtIO Drivers release 1.1.3 is also available on My Oracle Support under the patch number 27637937. Oracle Linux Resources Documentation Oracle Linux Administrator's Guide for Release 7 - Virtualization Oracle VirtIO Drivers for Microsoft Windows Blogs Oracle Linux Blog Oracle Virtualization Blog Community Pages Oracle Linux Product Training and Education Oracle Linux Administration - Training and Certification Data Sheets, White Papers, Videos, Training, Support & more Oracle Linux Social Media Oracle Linux on YouTube Oracle Linux on Facebook Oracle Linux on Twitter

We are pleased to announce Oracle VirtIO Drivers for Microsoft Windows release 1.1.3. The Oracle VirtIO Drivers for Microsoft Windows are paravirtualized (PV) drivers for Microsoft Windows guests that...

Announcements

Registration is Open for Oracle OpenWorld and Oracle Code One San Francisco 2019

Register now for Oracle OpenWorld and Oracle Code One San Francisco. These concurrent events are happening September 16-19, 2019 at Moscone Center. By registering now, you can take advantage of the Super Saver rate before it expires on April 20, 2019.  This year at Oracle OpenWorld San Francisco, you’ll learn how to do more with your applications, adopt new technologies, and network with product experts and peers.    Don’t miss the opportunity to experience: Future technology firsthand such as Oracle Autonomous Database, blockchain, and artificial intelligence New connections by meeting some of the brightest technologists from some of the world’s most compelling companies Technical superiority by taking home new skills and getting an insider’s look at the latest Oracle technology Lasting memories while experiencing all that Oracle has to offer, including many opportunities to unwind and have some fun   At Oracle Code One, the most inclusive developer conference on the planet, come learn, experiment, and build with us. You can participate in discussions on Linux, Java, Go, Rust, Python, JavaScript, SQL, R, and more. See how you can shape the future and break new ground. Join deep-dive sessions and hands-on labs covering leading-edge technology such as blockchain, chatbots, microservices, and AI. Experience cloud development technology in the Groundbreakers Hub, featuring workshops and other live, interactive experiences and demos. Register Now and Save! Now is the best time to register for these popular conferences and take us up on the Super Saver rate. Then be sure to check back in early May, 2019 for the full content catalog where you will see the breadth and depth of our sessions. You can also signup to be notified when the content catalog goes live. Register now for Oracle OpenWorld San Francisco 2019 Register now for Oracle Code One San Francisco 2019 We look forward to seeing you in September!  

Register now for Oracle OpenWorld and Oracle Code One San Francisco. These concurrent events are happening September 16-19, 2019 at Moscone Center. By registering now, you can take advantage of the...

Linux Kernel Development

Towards A More Secure QEMU Hypervisor, Part 2 of 3

In this blog, the second in a series of three, Oracle Linux kernel developer Elena Ufimtseva demonstrates how to configure and build our disaggregated QEMU. Configure and build multi-process QEMU To build the system that supports multi-process device emulation in QEMU, the build system was modified to add new objects. To get the latest development tree with multi-process support clone it from the git repository and branch multi-process-qemu-v0.1: git clone -b multi-process-qemu-v0.1 https://github.com/oracle/qemu.git Run configure with –enable-mpqemu to enable multi-process qemu and run make: ./configure --disable-xen --disable-tcg --disable-tcg-interpreter --target-list=x86_64-softmmu --enable-guest-agent --enable-mpqemu make all make install Notes on Xen: If no support of Xen on the system is needed, --disable-xen should be used. On OL7 --disable-xen should be used. There are few executable files, some of which are the remote programs. Depending on the options used while configuring Qemu, one may need to add the location of those remote programs to the PATH environment variable. In current version the program name is “qemu-scsi-dev”. configure script can be used with option –install= to specify the installation directory. Running multi-process QEMU To run qemu device emulation in a separate process, there are following options that are different from the original qemu: rdevice; rdrive; These options are similar to the ones in original qemu and can be used in the same way. For example, to run disk attached to LSI SCSI controller in remote process, the following command line can be used: /usr/local/bin/qemu-system-x86_64 -name vm -m 6G -drive file=/root/ol7.qcow2,format=raw -enable-kvm -machine q35,accel=kvm -rdevice lsi53c895a,rid=0,id=scsi0,command=qemu-scsi-dev -rdevice scsi-hd,rid=0,drive=drive0,bus=scsi0.0,scsi-id=0 -rdrive id=drive0,rid=0,file=/root/cirros-0.4.0-x86_64-disk.img,format=qcow2 -object memory-backend-file,id=mem,mem-path=/dev/shm/,size=6G,share=on -numa node,memdev=mem -display none -vnc :0 -monitor stdio -device e1000,netdev=net0 -netdev user,id=net0,hostfwd=tcp::5555-:22 Required options are: remote device options:-rdevice lsi53c895a,rid=0,id=scsi0,command=qemu-scsi-dev -rdevice scsi-hd,rid=0,drive=drive0,bus=scsi0.0,scsi-id=0 -rdrive id=drive0,rid=0,file=/root/cirros-0.4.0-x86_64-disk.img,format=qcow2 memory object to support file descriptor based memory synchronization between remote process and qemu: -object memory-backend-file,id=mem,mem-path=/dev/shm/,size=6G,share=on -numa node,memdev=mem The result of running multi-process qemu with one remote process: There are two processes listed here, one is the main qemu and the second is the qemu-scsi-dev remote process. Debugging and troubleshooting There are additional options to provide more diagnostics for debugging. To enable logging for multi process qemu, -D option can be specified with mask “rdebug”: -D /tmp/qemu.log -d rdebug To enable Qemu debugging with gdb, it can be configured with --enable-debug-info to include debug symbols. Since multi-process qemu has additional processes that are spawned during the execution, to use gdb to debug child processes the following settings can be used to launch gdb: set detach-on-fork off set follow-exec-mode new set follow-fork-mode child set print inferior-events on This will allow debug of the child process automatically. Below is the example of such a debug session: [root@localhost ~]# gdb /usr/local/bin/qemu-system-x86_64 GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-114.el7 Copyright (C) 2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later http://gnu.org/licenses/gpl.html This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-redhat-linux-gnu". For bug reporting instructions, please see: http://www.gnu.org/software/gdb/bugs/... Reading symbols from /usr/local/bin/qemu-system-x86_64...done. (gdb) r -enable-kvm -machine q35 -smp 4 -m 8000M -vnc :0 -net nic -net user,hostfwd=tcp::5022-:22 -drive file=/root/ol7.qcow2,format=raw -rdevice lsi53c895a,rid=0,id=scsi0 -rdevice scsi-hd,rid=0,drive=drive0,bus=scsi0.0,scsi-id=0 -rdrive id=drive0,rid=0,file=/root/cirros-0.4.0-x86_64-disk.img -object memory-backend-file,id=mem,mem-path=/dev/shm/,size=8000M,share=on -numa node,memdev=mem Starting program: /usr/local/bin/qemu-system-x86_64 -enable-kvm -machine q35 -smp 4 -m 8000M -vnc :0 -net nic -net user,hostfwd=tcp::5022-:22 -drive file=/root/ol7.qcow2,format=raw -rdevice lsi53c895a,rid=0,id=scsi0 -rdevice scsi-hd,rid=0,drive=drive0,bus=scsi0.0,scsi-id=0 -rdrive id=drive0,rid=0,file=/root/cirros-0.4.0-x86_64-disk.img -object memory-backend-file,id=mem,mem-path=/dev/shm/,size=8000M,share=on -numa node,memdev=mem [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib64/libthread_db.so.1". [New Thread 0x7fffef5fe700 (LWP 14001)] [New Thread 0x7ffdfac1a700 (LWP 14003)] [New Thread 0x7ffdfa419700 (LWP 14005)] [New Thread 0x7ffdf9c18700 (LWP 14006)] [New Thread 0x7ffdf9417700 (LWP 14007)] [New Thread 0x7ffdebfff700 (LWP 14009)] [New inferior 14010] [New process 14010] [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib64/libthread_db.so.1". Thread 0x7ffff7fc5c00 (LWP 14010) is executing new program: /usr/local/bin/qemu-scsi-dev [New inferior 14010] (gdb) info inferior Num Description Executable 3 process 14010 /usr/local/bin/qemu-scsi-dev 2 <null> /usr/local/bin/qemu-system-x86_64 1 process 13997 /usr/local/bin/qemu-system-x86_64

In this blog, the second in a series of three, Oracle Linux kernel developer Elena Ufimtseva demonstrates how to configure and build our disaggregated QEMU. Configure and build multi-process QEMU To...

Linux Kernel Development

Towards A More Secure QEMU Hypervisor, Part 1 of 3

In this blog, the first in a series of three, Oracle Linux kernel developer John Johnson introduces Oracle’s work towards a more secure QEMU based hypervisor. Disaggregating QEMU QEMU is often used as the hypervisor for virtual machines running in the Oracle cloud. Since one of the advantages of cloud computing is the ability to run many VMs from different tenants in the same cloud infrastructure, a guest that compromised its hypervisor could potentially use the hypervisor’s access privileges to access data it is not authorized to. QEMU can be susceptible to security attack because it is a large, monolithic program that provides many services to the VMs it controls. Many of these services can be configured out of QEMU, but even a reduced configuration QEMU has a large amount of code a guest can potentially attack in order to gain additional privileges. QEMU services QEMU can be broadly described as providing three types of services. One is a VM control point, where VMs can be created, migrated, re-configured, and destroyed. A second service emulates the CPU instructions within the VM, usually accelerated by HW virtualization features such as Intel’s VT extensions. Finally, it provides IO services to the VM by emulating HW IO devices, such as disk and network devices. All these services exist within a single, monolithic QEMU process:   A disaggregated QEMU A disaggregated QEMU involves separating these services into multiple host processes. Having these services in separate processes allows us to use SELinux mandatory access controls to constrain the processes to only the files needed to provide its service, e.g., a disk emulation process would be given access to only the the disk images it provides; and not be allowed to access other host files, or any network devices. An attacker who compromised such a disk emulation process would not be able to exploit it beyond the host files the process has been granted access to. A QEMU control process would remain, but in disaggregated mode, it would be a control point that executes the processes needed to support the VM being created and sets up the communication paths between them. But the QEMU control process would have no direct interfaces to the VM, although it would still provide the user interface to control the VM, such as hot-plugging devices or live migrating the VM. Disaggregating IO services A first step in creating a disaggregated QEMU is to separate IO services from the main QEMU program. The main QEMU process would continue to provide CPU emulation as well as being the VM control point. In a later phase, CPU emulation could be separated from the control process. Disaggregating IO services is a good place to begin QEMU disaggregating for a couple of reasons. One is the sheer number of IO devices QEMU can emulate provides a large surface of interfaces which could potentially be exploited. Another is the modular nature of QEMU device emulation code provides interface points where the QEMU functions that perform device emulation can be separated from the QEMU functions that manage the emulation of guest CPU instructions.   Disaggregated CPU emulation After IO services have been disaggregated, a second phase would be to separate a process to handle CPU instruction emulation from the main QEMU control function. There are few existing object separation points for this code, so the first task would be to create interfaces between the control plane functions and functions that manage guest CPUs.   Progress to date We’ve separated our first device from the the main QEMU process: an LSI 895 SCSI disk controller. Future blogs posts on this topic will cover the design of the project, its performance, as well as where the source code can be found and how to use it. To see part 2 in this blog series, go to: https://blogs.oracle.com/linux/towards-a-more-secure-qemu-hypervisor%2c-part-2-of-3

In this blog, the first in a series of three, Oracle Linux kernel developer John Johnson introduces Oracle’s work towards a more secure QEMU based hypervisor. Disaggregating QEMU QEMU is often used as...

Linux

libresource - It is time for version 2

In this blog post, Oracle Linux kernel developer Rahul Yadav discusses a few details about version 2 of his libresource project. As discussed in my previous blog[1] on libresource, we are working on a library which provides APIs to get system resource information for user-land applications. The system resource information includes information related to memory, networking, devices and various other statistics. Currently an application developer needs to read this information mostly from procfs and sysfs. The developer needs to open a file, read the desired information, parse that information and then close the file. libresource provides simple APIs to do away with all these steps and allow the application to get the information via one call. In version 1 of libresource we delivered the following: Basic infrastructure so adding new resource information is straightforward We added a lot of memory and networking related system resource information All the user application facing APIs are done I presented the current status at Linux Plumbers Conference 2018[2] and discussed with the community on what we should be doing next in libresource version 2. The following things came out of that discussion: We need to add more system resource information in the library. A large application like a database or web servers need a lot of system related information to take decisions, and it will be good for them to get all system resource information from one library. We are planning to add the following: table { border-collapse: collapse; width: 80%; } td, th { border: 1px solid #dddddd; padding: 8px; } Resource Id Description NET_TCPSENDBUFSIZE Send buffer sizes for TCP NET_TCPRECVBUFSIZ recv buffer sizes for TCP NET_GLOBALSENDBUFSIZE Send buffer sizes for global NET_GLOBALRECVBUFSIZE Global recv buffer sizes NET_BUFSIZEINFOALL Send/recv buffer sizes for global and TCP MMAP_PROC_HEAPINFO Heap address and heap size for pid MMAP_PROC_STACKINFO Stack address and stack size for pid FS_AIONR Running total of the number of events specified on the io_setup system call for all currently active aio contexts FS_AIOMAXNR MAX AIONR possible. If aio-nr reaches aio-max-nr then io_setup will fail with EAGAIN FS_FILENR Number of allocated file handles, the number of allocated but unused file handles, and the maximum number of file handles FS_FILEMAXNR Maximum number of file-handles that the Linux kernel will allocate. CPU_CORECOUNT Core count CPU_THREADCOUNT Total thread count (CPU count) PROCSET_NUMCPU Get current number of CPUs in caller's processor set CPU_ARCHINFOALL Struct which has socket,core and thread count MEM_HUGEPAGESIZE Size of a huge page MEM_HUGEPAGEALL Struct with all information about huge pages VMSTAT_PAGEIN Number of page in since last boot VMSTAT_PAGEOUT Number of page out since last boot VMSTAT_SWAPIN Number of swapin since last boot VMSTAT_SWAPOUT Number of swapout since last boot VMSTAT_PGMAJFAULT Number of major page faults per sec. VMSTAT_INFOALL All information related to VMSTAT. LOADAVG_INFO All information related to load average; CPU and IO utilization of the last one, five, and 10 minute periods. It also shows the number of currently running processes and the total number of processes.   We need to start thinking about how we can virtualize the information provided by the library. Currently all the information which is provided is not virtualized because they are fetched from /proc which itself is not virtualized. This means if an application is running in a containerized environment then the information provided by the library may not necessarily be for the container itself, it might be information of the host system. One suggestion was to read this information using LXCfs which is a file system that can be bind mounted over /proc to provide cgroup aware information. But this seems to be pretty heavy because it uses FUSE to get cgroup aware container information. Another suggestion was to read this information for cgroup files and provide them to application. This seems more efficient and an ideal solution for the problem. libresource internally reads the information from procfs or sysfs itself, so currently it does not provide any performance improvement over reading that information directly from procfs or sysfs. We need to figure out ways to get the information in a more efficient manner. Various efforts have been made to add a system call or similar interface to provide this information, but none have been accepted by the community so far. There was a suggestion to use netlink to get some of the kernel information, especially networking related information. I had tried that while working on networking resources in first version of the library, but I did not see any performance improvement in comparison to getting the information from procfs. This is because we still need to open a socket and read information from it, parse the information and close the socket. If in the future we provide APIs to read system resource information continuously, then this might be useful. We can keep the socket open and read the information continuously. There was a suggestion to standardize the make/install processes. Currently the library has a simple Makefile which does the work. We are working on this in next version. I am working on a lot of these suggestions for the next version of libresource and they should be out for review and later for use soon. Meanwhile you can get the library from github[3] and start using it. If you have a request or a question, please use the issues[4] page on the github repository. [1] https://blogs.oracle.com/linux/getting-system-resource-information-with-a-standard-api [2] https://www.linuxplumbersconf.org/event/2/contributions/211/ [3] https://github.com/lxc/libresource [4] https://github.com/lxc/libresource/issues

In this blog post, Oracle Linux kernel developer Rahul Yadav discusses a few details about version 2 of his libresource project. As discussed in my previous blog[1] on libresource, we are working on a...

Linux

How to Install Node.js 10 with node-oracledb and Connect it to Oracle Database

This post was updated on 20 March, 2019 to reflect changes in the way yum configuration works.   A few months ago we added dedicated repositories for Node.js to the Oracle Linux yum server. These repos also include an RPM with the Oracle Database driver for Node.js, node-oracledb, so you can connect your Node.js application to the Oracle Database. In this post I describe the steps to install Node.js 10 and node-oracledb Node.js to Oracle Database. If you are in a rush or want to try this out in a non-destructive way, I recommend you use the latest Oracle Linux 7 Vagrant box . Configure Yum with Node.js and Oracle Instant Client Repositories To set up your system to access Node.js and Oracle Instant Client repos on Oracle Linux yum server, install the oracle-nodejs-release-el7 and oracle-release-el7 RPMs. As of this writing, the Node.js 10 repo will be enabled by default when you install the Oracle Node.js repelase RPM $ sudo yum -y oracle-node-release-el7 oracle-release-el7 Next, install Node.js 10 and the compatible node-oracledb, making sure to temporarily disable the EPEL repository to prevent the wrong version of Node.js getting installed. $ sudo yum -y install --disablerepo=ol7_developer_EPEL nodejs node-oracledb-node10 Connecting to Oracle Database For my testing I used Oracle Database 18c Express Edition (XE). You can download it here. Quick Start instructions are here. About Oracle Instant Client node-oracledb depends on Oracle Instant Client. During OpenWorld 2018 we released Oracle Instant Client 18.3 RPMs on Oracle Linux yum server in the ol7_oracle_instantclient and ol6_oracle_instantclient repositories, making installation a breeze. Assuming you have enabled the repository for Oracle Instant Client appropriate for your Oracle Linux release, it will be installed as a dependency. As of release 3.0, node-oracledb is built with Oracle Client 18.3, which connects to Oracle Database 11.2 and greater. Older releases of Oracle Instant Client are available on OTN. Add the Oracle Instant Client to the runtime link path. $ sudo sh -c "echo /usr/lib/oracle/18.3/client64/lib > /etc/ld.so.conf.d/oracle-instantclient.conf" $ sudo ldconfig A Quick Node.js Test Program Connecting to Oracle Database I copied this file from the examples in the node-oracledb Github repo. Running this will tell us whether Node.js can connect to the database. Copy this code into a file called connect.js. The file below comes from the same GitHub repo. Copy the code into a file called dbconfig.js and edit it to include your Database username, password and connect string. Run connect.js with node Before running connect.js, make sure NODE_PATH is set so that the node-oracledb module can be found. $ export NODE_PATH=`npm root -g` $ node connect.js Connection was successful!

This post was updated on 20 March, 2019 to reflect changes in the way yum configuration works.   A few months ago we added dedicated repositories for Node.js to the Oracle Linux yum server....

Technologies

Kata Containers: An Important Cloud Native Development Trend

Introduction One of Oracle’s top 10 predictions for developers in 2019 was that a hybrid model that falls between virtual machines and containers will rise in popularity for deploying applications. Kata Containers are a relatively new technology that combine the speed of development and deployment of (Docker) containers with the isolation of virtual machines. In the Oracle Linux and virtualization team we have been investigating Kata Containers and have recently released Oracle Container Runtime for Kata on Oracle Linux yum server for anyone to experiment with. In this post, I describe what Kata containers are as well as some of the history behind this significant development in the cloud native landscape. For now, I will limit the discussion to Kata as containers in a container engine. Stay tuned for a future post on the topic of Kata Containers running in Kubernetes. History of Containerization in Linux The history of isolation, sharing of resources and virtualization in Linux and in computing in general is rich and deep. I will skip over much of this history to focus on some of the key landmarks on the way there. Two Linux kernel features are instrumental building blocks for the Docker Containers we’ve become so familiar with: namespaces and cgroups. Linux namespaces are a way to partition kernel resources such that two different processes have their own view of resources such as process IDs, file names or network devices. Namespaces determine what system resources you can see. Control Groups or cgroups are a kernel feature that enable processes to be grouped hierarchically such that their use of subsystem resources (memory, CPU, I/O, etc) can be monitored and limited. Cgroups determine what system resources your can use. One of the earliest containerization features available in Linux combine both namespaces and cgroups was Linux Containers (LXC). LXC offered a userspace interface to make the Linux kernel containment features easy to use and enabled the creation of system or application containers. Using LXC, you could run, for example, CentOS 6 and Oracle Linux 7, two completely different operating systems with different userspace libraries and versions on the same Linux kernel. Docker expanded on this idea of lightweight containers by adding packagaging, versioning and component reuse features. Docker Containers have become widely used because they appealed to developers. They shortened the build-test-deploy cycle because they made it easier to package and distribute an application or service as a self-contained unit, together with all the libraries needed to run it. Their popularity also stems from the fact that they appeal to developers and operators alike. Essentially, Docker Containers bridge the gap between dev and ops and shorten the cycle from development to deployment. Because containers —both LXC and Docker-based— share the same underlying kernel, it’s not inconceivable that an exploit able to escape a container could access kernel resources or even other containers. Especially in multi-tenant environments, this is something you want to avoid. Projects like Intel® Clear Containers Hyper runV took a different approach to parceling out system resources: their goal was to combine the strong isolation of VMs with the speed and density (the number of containers you can pack onto a server) of containers. Rather than relying on namespaces and cgroups, they used a hypervisor to run a container image. Intel® Clear Linux OS Containers and Hyper runV came together in Kata Containers, an open source project and community, which saw its first release in March of 2018. Kata Containers: Best of Both Worlds The fact that Kata Containers are lightweight VMs means that, unlike traditional Linux containers or Docker Containers, Kata Containers don’t share the same underlying Linux kernel. Kata Containers fit into the existing container ecosystem because developers and operators interact with them through a container runtime that adheres to the Open Container Initiative (OCI)specification. Creating, starting, stopping and deleting containers works just the way it does for Docker Containers. Image by OpenStack Foundation licensed under CC BY-ND 4.0 In summary, Kata Containers: Run their own lightweight OS and a dedicated kernel, offering memory, I/O and network isolation Can use hardware virtualization extensions (VT) for additional isolation Comply with the OCI (Open Container Initiative) specification as well as CRI (Container Runtime Interface) for Kubernetes Installing Oracle Container Runtime for Kata As I mentioned earlier, we’ve been researching Kata Containers here in the Oracle Linux team and as part of that effort we have released software for customers to expermiment with. The packages are available on Oracle Linux yum server and its mirrors in Oracle Cloud Infrastructure (OCI). Specifically, we’ve released a kata-runtime and related compontents, as well an optimized Oracle Linux guest kernel and guest image used to boot the virtual machine that will run a container. Oracle Container Runtime for Kata relies on QEMU and KVM as the hypervisor to launch VMs. To install Oracle Container Runtime for Kata on a bare metal compute instance on OCI: Install QEMU Qemu is available in the ol7_kvm_utils repo. Enable that repo and install qemu sudo yum-config-manager --enable ol7_kvm_utils sudo yum install qemu Install and Enable Docker Next, install and enable Docker. sudo yum install docker-engine sudo systemctl start docker sudo systemctl enable docker Install kata-runtime and Configure Docker to Use It First, configure yum for access to the Oracle Linux Cloud Native Environment - Developer Preview yum repository by installing the oracle-olcne-release-el7 RPM: sudo yum install oracle-olcne-release-el7 Now, install kata-runtime: sudo yum install kata-runtime To make the kata-runtime an available runtime in Docker, modify Docker settings in /etc/sysconfig/docker. Make sure SELinux is not enabled. The line that starts with OPTIONS should look like this: $ grep OPTIONS /etc/sysconfig/docker OPTIONS='-D --add-runtime kata-runtime=/usr/bin/kata-runtime' Next, restart Docker: sudo systemctl daemon-reload sudo systemctl restart docker Run a Container Using Oracle Container Runtime for Kata Now you can use the usual docker command to run a container with the --runtime option to indictate you want to use kata-runtime. For example: sudo docker run --rm --runtime=kata-runtime oraclelinux:7 uname -r Unable to find image 'oraclelinux:7' locally Trying to pull repository docker.io/library/oraclelinux ... 7: Pulling from docker.io/library/oraclelinux 73d3caa7e48d: Pull complete Digest: sha256:be6367907d913b4c9837aa76fe373fa4bc234da70e793c5eddb621f42cd0d4e1 Status: Downloaded newer image for oraclelinux:7 4.14.35-1909.1.2.el7.container To review what happened here. Docker, via the kata-runtime instructed KVM and QMEU to start a VM based on a special purpose kernel and minimized OS image. Inside the VM a container was created, which ran the uname -r command. You can see from the kernel version that a “special” kernel is running. Running a container this way, takes more time than a traditional container based on namespaces and cgroups, but if you consider the fact that a whole VM is launched, it’s quite impressive. Let’s compare: # time docker run --rm --runtime=kata-runtime oraclelinux:7 echo 'Hello, World!' Hello, World! real 0m2.480s user 0m0.048s sys 0m0.026s # time docker run --rm oraclelinux:7 echo 'Hello, World!' Hello, World! real 0m0.623s user 0m0.050s sys 0m0.023s That’s about 2.5 seconds to launch a Kata Container versus 0.6 seconds to launch a traditional container. Conclusion Kata Containers represent an important phenomenon in the evolution of cloud native technologies. They address both the need for security through virtual machine isolation as well as speed of development through seamless integration into the existing container ecosystem without compromising on computing density. In this blog post I’ve described some of the history that brought us Kata Containers as well as showed how you can experiment with them yourself with packages using Oracle Container Runtime for Kata.

Introduction One of Oracle’s top 10 predictions for developers in 2019 was that a hybrid model that falls between virtual machines and containers will rise in popularity for deploying applications. Kata...

Announcements

Announcing Gluster Storage Release 4.1 for Oracle Linux 7

The Oracle Linux and Virtualization team is pleased to announce the release of Gluster Storage Release 4.1 for Oracle Linux 7. Gluster Storage is a runtime component of the Oracle Linux Cloud Native Environment. Gluster Storage is an open source, POSIX compatible file system capable of supporting thousands of clients while using commodity hardware. Gluster provides a scalable, distributed file system that aggregates disk storage resources from multiple servers into a single global namespace. Gluster provides built-in optimization for different workloads and can be accessed using either an optimized Gluster FUSE client or standard protocols including SMB/CIFS. Gluster can be configured to enable both distribution and replication of content with quota support, snapshots, and bit-rot detection for self-healing. Gluster 4.1 for Oracle Linux 7 introduces support for: Either the Unbreakable Enterprise Kernel (Release 4 and higher) and the Red Hat Compatible Kernel x86_64 and aarch64 architectures Upgrades from an existing Gluster 3.12 configuration NFS-Ganesha, which provides NFSv3, v4, v4.1, and pNFS server support for Gluster volumes This release also includes a technology preview of Heketi, which provides a RESTful management interface to manage the lifecycle of GlusterFS volumes. Notable enhancement and new features: Management Samba volumes can be made inaccessible to clients without stopping the same smb.conf. This enhancement can also preserve changes to smb.conf, when configured externally GlusterD2 brings initial support for rebalancing, snapshots, intelligent volume provisioning (This is a technology preview and still experimental) Monitoring GlusterFS 4 offers a lightweight method to access internal information and avoids the performance penalty and complexities of previous approaches GlusterFS 4.1 introduces additional metrics to help determine the effectiveness of the xlator in various workloads Performance Gluster FUSE mounts now support FUSE extension to leverage the kernel "write-back cache" Improved performance when there are frequent metadata updates in the workload, typically seen with shared volumes Processing FUSE read requests can be done in parallel Better workload distribution on reads for replicate-based volumes Standalone Utime feature enables Gluster to maintain consistent change and modification time stamps on files and directories across bricks Thin Arbiter volumes in Gluster (part of the GlusterD2 technology preview) Automatically configure backup volfile servers in clients (part of the GlusterD2 technology preview) Installation Gluster Storage is available on the Unbreakable Linux Network (ULN) and the Oracle Linux yum server. It is currently available for the x86_64 and aarch64 architectures and can be installed on any Oracle Linux 7 server running either the Red Hat Compatible Kernel (RHCK) or the Unbreakable Enterprise Kernel (UEK) Release 4 or 5.  For more information on hardware requirements and how to install and configure Gluster, please review the Gluster Storage for Oracle Linux Release 4.1 documentation. Support Support for Gluster Storage is available to customers with an Oracle Linux Premier support subscription. Refer to Oracle Linux 7 License Information User Manual for information about Oracle Linux support levels. Oracle Linux Resources: Documentation Oracle Linux Software Download Oracle Linux Oracle Container Registry Blogs Oracle Linux Blog Community Pages Oracle Linux Social Media Oracle Linux on YouTube Oracle Linux on Facebook Oracle Linux on Twitter Data Sheets, White Papers, Videos, Training, Support & more Oracle Linux Product Training and Education Oracle Linux For community-based support, please visit the Oracle Linux space on the Oracle Developer Community.

The Oracle Linux and Virtualization team is pleased to announce the release of Gluster Storage Release 4.1 for Oracle Linux 7. Gluster Storage is a runtime component of the Oracle Linux Cloud...

Events

Join the Oracle Linux and Virtualization Team at Oracle OpenWorld Asia

Singapore is the next stop on our world tour! Join us for Oracle OpenWorld Asia, March 26-27, at the Marina Bay Sands. At Oracle OpenWorld Asia, you can gain enterprise expertise and start-up ingenuity directly from experts across retail, manufacturing, financial services, technology, the public sector, and more. Join innovators as they challenge assumptions, design for better outcomes, and leverage transformational technologies to create future possibilities now. Oracle OpenWorld Asia speakers are the innovators, disruptors and thought leaders of tomorrow. From a pioneer in the mobile and data analytics industries, authors, futurists and many more. Discover your tomorrow, today. Register now, and be sure to attend these sessions: Oracle Linux and Virtualization Sessions Wednesday, March 27, Marina Bay Sands, Singapore Session Speaker Time & Location Jumpstart Your Development with Oracle Linux and Oracle Cloud [SOL1993-SIN] Wim Coekaerts, Senior Vice President, Operating Systems and Virtualization Engineering, Oracle 09:00 AM - 09:45 AM | Arena 8 (Level 3)  How Oracle Linux Cloud Native Environment and VirtualBox Can Make Developers Life Easier [SES2155-SIN] Avi Miller, Director of Product Management, Oracle 10:25 AM - 11:10 AM | Arena 8 (Level 3)  Build a Cloud Native Environment with Oracle Linux [SES2223-SIN] Robert Shimp, Product Management Group Vice President, Oracle Linux and Virtualization, Oracle 3:30 PM - 4:05 PM | Arena 5 (Level 3) The Exchange: a Showcase for Attendees to Connect, Discover and Learn Oracle Linux and Oracle Virtualization experts will be at The Exchange to answer your questions, update you on the latest product enhancements, and demo the latest software releases. Let us know about your experience -- #OOWSIN #OracleLinux @OracleLinux Enjoy the conference!

Singapore is the next stop on our world tour! Join us for Oracle OpenWorld Asia, March 26-27, at the Marina Bay Sands. At Oracle OpenWorld Asia, you can gain enterprise expertise and start-up ingenuity...

Linux

Making Code More Secure with GCC - Part 2

This blog entry was contributed by Maxim Kartashev In the previous post I focused on the static analysis capabilities of the gcc 7.3 compiler. Warnings issued at compile time can point to the place in a program where an error at run time might occur, thus enabling the programmer to fix the program even before it is run. Not all run time errors can be predicted at compile time, though, and there are good and bad reasons why. For instance, there might be many annoying false positive warnings that get routinely ignored (and sometimes rightly so), until that time when one of them points to the actual problem, but gets silenced together with the rest. Or the programmer invokes undefined behavior, which in many cases is impossible to diagnose at compile time because there are simply no provisions for that in the programming language. The GNU toolchain continues to help the programmer even past compile time with the help of code instrumentation and additional features baked into the glibc library. In this post I am going to describe the necessary steps to utilize these capabilities. Apart from flaws in the program that make it work incorrectly even on correct data, an attacker will attempt to create input unforeseen by the programmer in order to take control over the program. And again, gcc can help to strengthen the code it generates by structuring it differently and providing additional checks. This post list several most useful techniques that gcc 7.3 implements. Finding Bugs At Run Time Some compiler warnings can be legitimately - from the point of view of the language - suppressed. One example is shown below: an explicit type cast spelled out in the code makes the compiler believe that you know what you are doing and not complain. a.c int global; int main() { int* p = &global; long* lp = p; long l1 = *lp; // warning: initialization from incompatible // pointer type [-Wincompatible-pointer-types] long l2 = *(long*)p; // same as above, but no warning } $ gcc -fsanitize=undefined a.c a.c: In function ´main´: a.c:5:16: warning: initialization from incompatible pointer type [-Wincompatible-pointer-types] long* lp = p; ^ These kinds of tricks place the program into the undefined behavior territory meaning that it is no longer predictable what the program will do. It is often tempting to dismiss the severity of the undefined behavior; in fact, not many situations really lead to unpredictable results at low optimization levels. The danger increases tenfold with the high -O settings because the undefined behavior starts to break compiler's understanding of the program and, guessing incorrectly, the compiler can generate code that does peculiar things. As an example, see how undefined behavior can erase your hard disk. Fortunately, the gcc compiler can still help to find at least some kinds of undefined behavior situations. It can be asked to instrument the generated code with additional instructions that would perform various checks before actual user code gets executed. To enable this instrumentation, use the -fsanitize=undefined option when compiling and linking your program. When executed, the program will report problems spotted as "runtime errors". See, for instance, how the GNU toolchain detects two bugs in the above code at run time: $ ./a.out a.c:9:10: runtime error: load of misaligned address 0x0000006010dc for type 'long int', which requires 8 byte alignment 0x0000006010dc: note: pointer points here 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ^ a.c:9:10: runtime error: load of address 0x0000006010dc with insufficient space for an object of type 'int' 0x0000006010dc: note: pointer points here 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 The -fsanitize option has many sub-options. If you are interested in finding out which specific situation can be detected by the version of the GNU toolchain you are using, check the Program Instrumentation Options section of its documentation. By default, the first error aborts the program giving you an opportunity to debug the core file, but it is also possible to attempt to continue execution in order to catch more error at once. This is what the -fsanitize-recover=undefined compiler option does; remember, though, that errors can cascade and all but the first one may not be very useful. Memory Corruption Mitigation Memory corruption is perhaps the most common source of subtle bugs and vulnerabilities. Unsurprisingly, many tools exist to help the programmer to find the origin of the problem (memcheck, discover, etc, etc). The GNU toolchain has not one but two such technologies: run-time program instrumentation ("AddressSanitizer") and, independent from it, built-in checks of the glibc dynamic memory allocator. AddressSanitizer The gcc compiler can instrument memory access instructions so that out-of-bounds and use-after-free bugs can be detected. This method requires recompilation with the -fsanitize=address option and obviously produces code that runs slower than without instrumentation (expect ~x2 slowdown). When compiling with optimization, the -fno-omit-frame-pointer is recommended since the sanitizer runtime uses fast and simple frame-based stack unwinder that requires the frame pointer register to serve its primary function. At run time, a detailed error message will be issued to stderr complete with the stack traces at the time of the invalid access and allocation of the memory block (if it was in the heap). Many find it helpful to not abort on first error; the -fsanitize-recover=address option enables this. Here's an example of the sanitizer output from this code: a.c // ... char* p = malloc(2); p[2] = 0; // writes past the allocated buffer // ... $ gcc -fsanitize=address a.c $ ./a.out ================================================================= ==27056==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x619000000480 at pc 0x000000400726 bp 0x7fffffffd910 WRITE of size 1 at 0x619000000480 thread T0 #0 0x400725 in main (/tmp/a.out+0x400725) #1 0x7ffff6a7d3d4 in __libc_start_main (/lib64/libc.so.6+0x223d4) #2 0x400618 (/tmp/a.out+0x400618) 0x619000000480 is located 0 bytes to the right of 1024-byte region [0x619000000080,0x619000000480) allocated by thread T0 here: #0 0x7ffff6f01900 in __interceptor_malloc /.../asan_malloc_linux.cc:62 #1 0x4006d8 in main (/tmp/a.out+0x4006d8) #2 0x7ffff6a7d3d4 in __libc_start_main (/lib64/libc.so.6+0x223d4) SUMMARY: AddressSanitizer: heap-buffer-overflow (/tmp/a.out+0x400725) in main Shadow bytes around the buggy address: ... 0x0c327fff8080: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 =>0x0c327fff8090:[fa]fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa ... This method works not only on dynamically allocated memory, but on stack (local, automatic) variables and global statically allocated data. Many aspects of the address sanitizer's work are controlled with the ASAN_OPTIONS environment variable, including what to check and what to report. For example, specifying ASAN_OPTIONS=log_path=memerr.log will redirect all output to the file named memerr.log.<pid> instead of stderr. See the complete option reference. Dynamic Memory Checks by glibc The glibc dynamic memory allocator can perform heap consistency checks and report problems to stderr supplied with the stack trace and memory map at the time of error, if requested. To utilize this capability, set the MALLOC_CHECK_ environment variable (values control what to do on error and can be found in mallopt(3)) prior to running the program. You can also insert explicit heap checks by either linking with -lmcheck option or calling the mcheck(3) function before the first call to malloc(3). All the specifics can be found in the mcheck(3) man page. This is an example of this facility: a.c char* p = malloc(n); // ... if ( argc == 1 ) { free(p); } // ... free(p); No additional compilation options are required: $ gcc a.c $ MALLOC_CHECK_=3 ./a.out *** Error in `./a.out': free(): invalid pointer: 0x0000000000602010 *** ======= Backtrace: ========= /lib64/libc.so.6(+0x8362e)[0x7ffff7a9162e] ./a.out[0x40058b] ... Aborted (core dumped) The types of problems found by these checks are limited to heap metadata corruption (heap buffer overruns) and things like double free. Still, the method requires neither changes to the code nor recompilation, has lower performance impact than AddressSanitizer described above, and can be used to abort the program to ease debugging, all of which make it a useful tool in keeping your program clear from dynamic memory corruption. Options to Increase Code Security The GNU compiler implements several techniques to harden the program against possible attacks. They work by inserting small bits of code and/or by adding checks to some standard functions (strcat(3), for instance) that verify the integrity of the vital data at run time and abort the program if the data get damaged, which may be the result of a programming error or attempted attack. All these options are aimed at being enabled for production builds. The -fstack-protector option adds protection against stack smashing attacks by placing a few guarding bytes to the vulnerable (see below) function's stack and verifying that those bytes haven't been changed before returning from the function. If they have, an error is printed and the program aborts: *** stack smashing detected ***: ./a.out terminated ======= Backtrace: ========= /lib64/libc.so.6(__fortify_fail+0x37)[0x7ffff7b26677] /lib64/libc.so.6(+0x118632)[0x7ffff7b26632] ./a.out[0x400589] ./a.out[0x400599] ... By default, only functions with call alloca(3) and functions with buffers larger than 8 bytes are so protected by the option. There are several choices as to which functions to consider vulnerable and protect: -fstack-protector-strong protects also those that have local array definitions or have references to local frame addresses, -fstack-protector-all protects all functions, and -fstack-protector-explicit only protects those with the stack_protect attribute, which you need to add manually. Another compiler option that helps to protect against the stack-tampering attacks is -fstack-check. When a single-threaded program goes beyond its stack boundaries, the OS generates a signal (typically SIGSEGV) that terminates the program. With multi-threaded - and, therefore, multi-stack - programs, such situation is not so easily detectable because one thread's stack's bottom might be another stack's top and the gap between them (protected by the OS) is small enough so that it can be "jumped" over. The -fstack-check option will help to mitigate that and make sure the OS knows when a stack is being extended and by how many pages even if the attacker makes it so that the program doesn't touch every page of the newly extended stack. The result is the OS-guarded canary between different thread's stacks is guaranteed to get touched and the multi-threaded program receives the same neat terminating signal as with an offending single-threaded program. The next code hardening technique gets activated by defining the _FORTIFY_SOURCE macro to 1 (check without changing semantics) or 2 (more checking, but conforming programs might fail) and provides protection against silent buffer overruns by functions that manipulate strings or memory such as memset(3) or strcpy(3). Precise information for your version of the toolchain can be found in the feature_test_macros(3) man page. As I have mentioned in my previous post, many compiler checks benefit from an increased level of optimization that allows gcc to collect more data about the program. The use of _FORTIFY_SOURCE macro requires the optimization level of -O1 or above. Potential errors are detected both at run and compile time when possible. Consider this example: a.c #include <string.h> int main(int argc, char* argv[]) { char s[2]; strcpy(s, "a.out"); // buffer overrun here return 0; } Compiling it with the usual flags doesn't spot any problems, even though obviously the "a.out" string doesn't fit into the two bytes available in the local variable s: $ gcc -O2 -Wall -Wextra -Wno-unused a.c Even running the problem gives no hints to possible troubles: $ ./a.out $ echo $? 0 Let's add the _FORTIFY_SOURCE macro: $ gcc -D_FORTIFY_SOURCE=1 -O2 -Wall -Wextra -Wno-unused a.c In file included from /usr/include/string.h:638:0, from a.c:1: In function ´strcpy´, inlined from ´main´ at a.c:6:5: /usr/include/bits/string3.h:104:10: warning: ´__builtin___strcpy_chk´ writing 6 bytes into a region of size 2 overflows the destination [-Wstringop-overflow=] return __builtin___strcpy_chk (__dest, __src, __bos (__dest)); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ And we immediately get a warning from the compiler. Now let's see what happens if the source string being copied is not a compile-time constant: a.c #include <string.h> int main(int argc, char* argv[]) { char s[2]; strcpy(s, argv[0]); // buffer overrun here as argv[0] will be "./a.out" return 0; } Notice that this time there are no warnings: $ gcc -D_FORTIFY_SOURCE=1 -O2 -Wall -Wextra -Wno-unused a.c At run time, however, the support library has detected the buffer overrun and immediately aborted execution of the program. $ ./a.out *** buffer overflow detected ***: ./a.out terminated ======= Backtrace: ========= /lib64/libc.so.6(__fortify_fail+0x37)[0x7ffff7b26677] /lib64/libc.so.6(+0x1167f2)[0x7ffff7b247f2] ./a.out[0x40052d] ... Aborted (core dumped) Key Take-Aways The GNU toolchain can be utilized to find bugs and vulnerabilities at run time: Compile your program with the -fsanitize=undefined gcc option and run your tests. This will exercise a lot of additional checks that will help to ensure the program actually behaves as intended and doesn't do so simply by accident. Both suspected and unsuspected problems with the heap can often be detected by setting the MALLOC_CHECK_ environment variable prior to running your program (see mallopt(3) for more info). No re-compilation required! If recompiling is possible, all kinds of memory access problems can be detected by AddressSanitizer: compile with -fsanitize=address (adding -O -fno-omit-frame-pointer to reduce the negative performance impact and, possibly, -fsanitize-recover=address to not abort on first error). The GNU toolchain can also harden your program against certain kinds of attacks: The -fstack-protector option adds stack integrity checks to certain vulnerable functions. You can control which functions to protect with sub-options. Use -fstack-check for multi-threaded programs to prevent one thread from silently extending its stack on top of another. Add -D_FORTIFY_SOURCE=1 -O2 to your compilation flags to catch buffer overruns by certain standard memory manipulation functions both at run and compile time. See feature_test_macros(3) for more info. References List of gcc options for program instrumentation (-fsanitize= and friends). The complete list of gcc options with descriptions. glibc built-in heap consistency checks.

This blog entry was contributed by Maxim Kartashev In the previous post I focused on the static analysis capabilities of the gcc 7.3 compiler. Warnings issued at compile time can point to the place in...

Linux

Short Cuts to Better Solutions with the Oracle Linux ISV Catalog

Whether you’re an Oracle customer or partner, there are many reasons to look for solutions certified for use with Oracle Linux and Oracle VM – on-premises or in the cloud. There are many applications, tools, plug-ins, and more, that you may need to consider for your projects. Narrowing down the options and gathering all the necessary information can be a time-consuming task, so we’d like to offer some short cuts to the right solution for you. Oracle Software For Oracle customers, you’ll want to check out our support portal. Here you will find all Oracle software that runs on Oracle Linux and Oracle VM. You’ll find which versions have been tested and work together to help you jump start your project. You’ll also find a handy tool. In less than 10 minutes, this Getting Started with Certifications video provides a wealth of information on the various ways to search for tested software combinations. And, for customers with a support subscription, help is just one call away. Oracle Support provides technical assistance for Oracle Database, Oracle Applications, and all other Oracle software. With Oracle Linux and Oracle VM, the software is free to download, use, and distribute. You can purchase a support subscription, which is available in different support levels, to meet your needs. Third-Party Software Likewise, visit our ISV Catalog for third-party software that has been certified with Oracle Linux and Oracle VM. We work closely with ISVs to help them test their software with Oracle Linux and Oracle VM, so that mutual customers are confident that the software combinations that they deploy – on premises or in the cloud – have been tested and work well together. If you're an ISV and your software isn’t in our catalog – let’s fix that! You’re missing a great opportunity to reach customers who may be looking for your software to run on Oracle Linux – one of the top enterprise Linux distributions. Contact us to learn more about the certification process. We welcome the opportunity to work with you. Oracle Linux has a very rich set of certified solutions, comparable to other Linux distributions. These short cuts should help you find just the right solution for you.      

Whether you’re an Oracle customer or partner, there are many reasons to look for solutions certified for use with Oracle Linux and Oracle VM – on-premises or in the cloud. There are many applications,...

Linux Kernel Development

Writing kernel tests with the new Kernel Test Framework (KTF)

In this blog, Oracle Linux kernel developers Alan Maguire and Knut Omang explain how to write Kernel Test Framework tests. KTF is available as a standalone git repository, but we are also working to offer it as a patch set for integration into the kernel. Read more about KTF in our introductory blog post, here: https://blogs.oracle.com/linux/oracles-new-kernel-test-framework-for-linux-v2  Writing new KTF (Kernel Test Framework) tests Here we're going to try and describe how we can use KTF to write some tests. The neat thing about KTF is it allows us to test kernel code in kernel context directly. This means the environment we're running our tests in affords a lot of control. Here we're going to try and write some tests for a key abstraction in Linux kernel networking, the "struct sk_buff". The sk_buff (socket buffer) is the structure used to store packet data as it moves through the networking stack. For an excellent introduction, see http://vger.kernel.org/~davem/skb_data.html In fact we're going to base our tests around some of the descriptions there, by creating/manipulating/freeing skbs and asking questions like what is the state of an sk_buff when it is first allocated? what about when we reserve space for new packet headers, or add tailroom? ...etc. My hope is that we can show that adding tests is in fact a great way to understand an API. If we can formalize the guarantees of the API such that we can write tests to validate them, we've come a long way in understanding it. Brief Introduction to KTF KTF allows us to test both exported and un-exported kernel interfaces in test cases which are added in a dedicated test module. We can make assertions about state during these test cases and the results are communicated to userspace via netlink sockets. The googletest framework is used in conjunction with this framework. While KTF supports hybrid user- and kernel-mode tests, here we will focus on kernel-only tests. Creating our project First let's grab a copy of KTF and build it. We use separate source and build trees, and because KTF builds modules we need kernel-specific builds. Because we are building kernel modules we will also need the kernel-uek-devel package. We build googletest from source. Note: these instructions are for Oracle Linux; some package names etc may differ for other distros. Full instructions can be found in the doc/installation.txt file in KTF. We use Knut's version of googletest as it includes assertion counting and better test case naming. Building googletest # yum install cmake3 # cd ~ # mkdir -p src build/`uname -r` # cd src # git clone https://github.com/knuto/googletest.git # cd ~/build/`uname -r` # mkdir googletest # cd googletest # cmake3 ~/src/googletest/ -DBUILD_SHARED_LIBS=ON # make # sudo make install Building KTF We need kernel-uek-devel and cpp packages to build. Finally once we have built ktf, we insert the kernel module. # sudo yum install kernel-uek-devel cpp libnl3-devel # cd ~/src # git clone https://github.com/oracle/ktf # cd ktf # autoreconf # cd ~/build/`uname -r` # mkdir ktf # cd ktf # PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig ~/src/ktf/configure KVER=`uname -r` # make # sudo make install # sudo insmod kernel/ktf.ko Creating our new test suite Getting started here is easy; Knut created a "ktfnew" program to populate a new suite: # ~/src/ktf/scripts/ktfnew -p ~/src skbtest Creating a new project under ~/src/skbtest Let's see what we got! # ls ~/src/skbtest ac autom4te.cache configure.ac m4 Makefile.in aclocal.m4 configure kernel Makefile.am The kernel subdir is where we will add tests to our "skbtest" module, and it has already been populated with a file: # ls ~/src/skbtest/kernel Makefile.in skbtest.c skbtest.c is a simple module with one test "t1" in test set "simple" which evaluates a true expression via the EXPECT_TRUE() macro. The module init function adds the test via the ADD_TEST(name) macro. ASSERT_() and EXPECT_() macros are used to test conditions, and if they fail the test fails. We can clean up by using the ASSERT_*_GOTO() variants which we can pass a label to jump to on failure. ASSERTs are fatal to a test case execution. We will see more examples of this later on. #include <linux/module.h> #include "ktf.h" MODULE_LICENSE("GPL"); KTF_INIT(); TEST(simple, t1) { EXPECT_TRUE(true); } static void add_tests(void) { ADD_TEST(t1); } static int __init skbtest_init(void) { add_tests(); return 0; } static void __exit skbtest_exit(void) { KTF_CLEANUP(); } module_init(skbtest_init); module_exit(skbtest_exit); So we're ready to start adding our tests! Before we do anything else, let's ensure we track our progress with git. We remove "configure" as we don't want to track it via git, we create it with "autoreconf". # cd ~/src/skbtest # rm configure # git init . # git add ac aclocal.m4 configure.ac kernel/ m4 Makefile.* # git commit -a -m "initial commit" The first thing we need to do is ensure that our tests have access to the skb interfaces. We need to add #include <linux/skbuff.h> Next, let's add a simple test that makes assertions about skb state after allocation. /** * alloc_skb_sizes() * * ensure initial skb state is as expected for allocations of various sizes. * - head == data * - end >= tail + size * - len == data_len == 0 * - nr_frags == 0 * **/ TEST(skb, alloc_skb_sizes) { unsigned int i, sizes[] = { 127, 260, 320, 550, 1028, 2059 }; struct sk_buff *skb = NULL; for (i = 0; i < ARRAY_SIZE(sizes); i++) { skb = alloc_skb(sizes[i], GFP_KERNEL); ASSERT_ADDR_NE_GOTO(skb, 0, done); ASSERT_ADDR_EQ_GOTO(skb->head, skb->data, done); /* * skb->end will be aligned and include overhead of shared * info. */ ASSERT_TRUE_GOTO(skb->end >= skb->tail + sizes[i], done); ASSERT_TRUE_GOTO(skb->tail == skb->data - skb->head, done); ASSERT_TRUE_GOTO(skb->len == 0, done); ASSERT_TRUE_GOTO(skb->data_len == 0, done); ASSERT_TRUE_GOTO(skb_shinfo(skb)->nr_frags == 0, done); kfree_skb(skb); skb = NULL; } done: kfree_skb(skb); } static void add_tests(void) { ADD_TEST(alloc_skb_sizes); } If one of our ASSERT_ macros fails, we will goto "done", and we clean up there by freeing the skb. Ensuring tests tidy up after themselves is important as we don't want our tests to induce memory leaks! Now we build and run our test. Building and running our test Here we build our test kernel module. Since we installed ktf/googletest in /usr/local, we need to tell configure to look there. # cd ~/src/skbtest # autoreconf # cd ~/build/`uname -r` # mkdir skbtest # cd skbtest # ~/src/skbtest/configure KVER=`uname -r` --prefix=/usr/local --libdir=/usr/local/lib64 --with-ktf=/usr/local # make # sudo make install Now let's load our test module (we loaded ktf above) and run the tests: # sudo insmod kernel/skbtest.ko # sudo LD_LIBRARY_PATH=/usr/local/lib64 /usr/local/bin/ktfrun [==========] Running 1 test from 1 test case. [----------] Global test environment set-up. [----------] 1 test from skb [ RUN ] skb.alloc_skb_sizes [ OK ] skb.alloc_skb_sizes, 42 assertions (0 ms) [----------] 1 test from skb (0 ms total) [----------] Global test environment tear-down [==========] 1 test from 1 test case ran. (0 ms total) [ PASSED ] 1 test. Error injection Now the above admittedly looks pretty dull. However it's worth emphasizing something before we move on. This code actually ran in-kernel! With a lot of pain, it would be possible to hack up a user-space equivalent test, but it would require adding definitions for kmalloc, kmem_cache_alloc etc. Here we test the code in the same environment in which it is run, with no caveats or special-purpose environments. This makes KTF execution pretty unique; no need for extensive stubbing, we're testing the code as-is. Next we're going to try and inject an error and see how skb allocation behaves in low-memory conditions. KTF allows us to catch function execution and return and mess with the results via kprobes; or specifically kretprobes. To catch a return value we declare: KTF_RETURN_PROBE(function_name, function_handler) { void *retval = (void *)KTF_RETURN_VALUE(); ... KTF_SET_RETURN_VALUE(newvalue); return 0; } We get the intended return value witl KTF_RETURN_VALUE(), and we can set our own via KTF_SET_RETURN_VALUE(). Note that the return value that the above function returns should always be 0 - the value that the functionw we're probing actually returns is set by KTF_SET_RETURN_VALUE(). For neatness, if it's a memory allocation we should free it, otherwise we'll be inducing a memory leak with our test! However we face a few problems with this sort of error injection. First, the kmem_cache used - skbuff_head_cache - is not exported as a symbol, so how do we access it in order to kmem_cache_free() our skb memory? Luckily, ktf has a handy function for cases like this - ktf_find_symbol(). We pass in the module name (NULL in this case because it's a core kernel variable) and the symbol name, and we get back the address of the symbol. Remember though that this is essentially &skbuff_head_cache, so we need to dereference it before use. Second, we don't want to fail skb allocations for everyone as that will kill our network access etc. So by recording the task_struct * for the test in alloc_skb_nomem_task, we can limit the damage to our test thread. Here's what the test looks like in full: struct task_struct *alloc_skb_nomem_task; KTF_RETURN_PROBE(kmem_cache_alloc_node, kmem_cache_alloc_nodehandler) { struct sk_buff *retval = (void *)KTF_RETURN_VALUE(); struct kmem_cache **cache; /* We only want alloc failures for this task! */ if (alloc_skb_nomem_task != current) return 0; /* skbuf_head_cache is private to skbuff.c */ cache = ktf_find_symbol(NULL, "skbuff_head_cache"); if (!cache || !*cache || !retval) return 0; kmem_cache_free(*cache, retval); KTF_SET_RETURN_VALUE(0); return 0; } /** * alloc_skb_nomem() * * Ensure that in the face of allocation failures (kmem cache alloc of the * skb) alloc_skb() behaves sensibly and returns NULL. **/ TEST(skb, alloc_skb_nomem) { struct sk_buff *skb = NULL; alloc_skb_nomem_task = current; ASSERT_INT_EQ_GOTO(KTF_REGISTER_RETURN_PROBE(kmem_cache_alloc_node, kmem_cache_alloc_nodehandler), 0, done); skb = alloc_skb(128, GFP_KERNEL); ASSERT_ADDR_EQ_GOTO(skb, 0, done); alloc_skb_nomem_task = NULL; done: KTF_UNREGISTER_RETURN_PROBE(kmem_cache_alloc_node, kmem_cache_alloc_nodehandler); kfree_skb(skb); } static void add_tests(void) { ADD_TEST(alloc_skb_sizes); ADD_TEST(alloc_skb_nomem); } Let's run it! # sudo LD_LIBRARY_PATH=/usr/local/lib64 /usr/local/bin/ktfrun [==========] Running 2 tests from 1 test case. [----------] Global test environment set-up. [----------] 2 tests from skb [ RUN ] skb.alloc_skb_nomem [ OK ] skb.alloc_skb_nomem, 2 assertions (27 ms) [ RUN ] skb.alloc_skb_sizes [ OK ] skb.alloc_skb_sizes, 42 assertions (0 ms) [----------] 2 tests from skb (27 ms total) [----------] Global test environment tear-down [==========] 2 tests from 1 test case ran. (27 ms total) [ PASSED ] 2 tests. Neat! Our error injection must have worked since alloc_skb() returned NULL, and we also cleaned up the memory that was really allocated but we pretended wasn't. alloc_skb and bad skb sizes Next we might wonder; given the arguments, can we see what happens when we provide an invalid size? But what is an invalid size? 0? UINT_MAX? Let's try a test where we pass in 0 and UINT_MAX and expect alloc_skb() to fail: TEST(skb, alloc_skb_invalid_sizes) { unsigned int i, sizes[] = { 0, UINT_MAX }; struct sk_buff *skb = NULL; for (i = 0; i < ARRAY_SIZE(sizes); i++) { skb = alloc_skb(sizes[i], GFP_KERNEL); ASSERT_ADDR_EQ_GOTO(skb, 0, done); } done: kfree_skb(skb); } Build again, and let's see what happens: # sudo LD_LIBRARY_PATH=/usr/local/lib64 ktfrun [==========] Running 3 tests from 1 test case. [----------] Global test environment set-up. [----------] 3 tests from skb [ RUN ] skb.alloc_skb_invalid_sizes /var/tmp/build/4.14.35+/skbtest/kernel/skbtest.c:113: Failure Assertion '(u64)(skb)==(u64)(0)' failed: (u64)(skb)==0xffffa07b53ca6c00, (u64)(0)==0x0 [ FAILED ] skb.alloc_skb_invalid_sizes, where GetParam() = "alloc_skb_invalid_sizes" (19 ms) [ RUN ] skb.alloc_skb_nomem [ OK ] skb.alloc_skb_nomem, 2 assertions (23 ms) [ RUN ] skb.alloc_skb_sizes [ OK ] skb.alloc_skb_sizes, 2 assertions (0 ms) [----------] 3 tests from skb (42 ms total) [----------] Global test environment tear-down [==========] 3 tests from 1 test case ran. (42 ms total) [ PASSED ] 2 tests. [ FAILED ] 1 test, listed below: [ FAILED ] skb.alloc_skb_invalid_sizes, where GetParam() = "alloc_skb_invalid_sizes" 1 FAILED TEST Okay so that failed, which means our allocation succeeded; why? Taking a closer look at alloc_skb(), there's no bar on 0 values. What about UINT_MAX, that shouldn't work, right? Actually it does! If we look at the code however, the size value that gets passed in gets the sizeof(struct skb_shared_info) etc added to it. So we just overflow the value, but what's interesting about that is we'll end up with an skb that invalidates the initial state expectations. Let's demonstrate that by add UINT_MAX to our "sizes" array in our valid skb alloc test "alloc_skb_sizes": unsigned int i, sizes[] = { 0, 127, 260, 320, 550, 1028, 2059, UINT_MAX }; Rebuilding and running we see this: # sudo LD_LIBRARY_PATH=/usr/local/lib64 ktfrun [==========] Running 3 tests from 1 test case. [----------] Global test environment set-up. [----------] 3 tests from skb [ RUN ] skb.alloc_skb_invalid_sizes [ OK ] skb.alloc_skb_invalid_sizes, 2 assertions (0 ms) [ RUN ] skb.alloc_skb_nomem [ OK ] skb.alloc_skb_nomem, 2 assertions (23 ms) [ RUN ] skb.alloc_skb_sizes /var/tmp/build/4.14.35+/skbtest/kernel/skbtest.c:45: Failure Failure '(skb->end >= skb->tail + sizes[i])' occurred [ FAILED ] skb.alloc_skb_sizes, where GetParam() = "alloc_skb_sizes" (15 ms) [----------] 3 tests from skb (38 ms total) So if we pass UINT_MAX to alloc_skb() we end up with a broken skb, in that skb->end isn't pointing where it should be. Seems like there could be some range checking here, but alloc_skb() is such a hot codepath it's likely the pragmatic argument that "no-one should allocate dumb-sized skbs" wins. We can modify our test to use "safer" bad sizes for now: TEST(skb, alloc_skb_invalid_sizes) { /* We cannot just use UINT_MAX here as the "size" argument passed in * has sizeof(struct skb_shared_info) etc added to it; let's settle for * UINT_MAX >> 1, UINT_MAX >> 2, etc. */ unsigned int i, sizes[] = { UINT_MAX >> 1, UINT_MAX >> 2}; struct sk_buff *skb = NULL; for (i = 0; i < ARRAY_SIZE(sizes); i++) { skb = alloc_skb(sizes[i], GFP_KERNEL); ASSERT_ADDR_EQ_GOTO(skb, 0, done); } done: kfree_skb(skb); } In general the skb interfaces assume the data they are provided is sensible, but we've just learned what can happen when it isn't! Writing tests is a great way to learn about an API.

In this blog, Oracle Linux kernel developers Alan Maguire and Knut Omang explain how to write Kernel Test Framework tests. KTF is available as a standalone git repository, but we are also working to...

Announcements

Oracle OpenWorld and Oracle Code One San Francisco 2019 – Call for Speakers is Open!

This year, Oracle OpenWorld and Oracle Code One San Francisco 2019 are taking place Sunday, September 15 – Thursday, September 19, 2019. The Call for Speakers is now open, and the deadline is coming up fast! Oracle customers and partners are encouraged to submit proposals to present at either or both of the conferences. The deadline to submit a proposal has been extended to 4pm ET on Friday, March 22, 2019. Whether you’re focused on securing your enterprise, operating in a hybrid cloud environment, finding ways to optimize cloud native or DevOps solutions, using Oracle Infrastructure Technologies, these conferences are ideal for sharing best practices, case studies, lessons learned, how-to’s, and deep-dives. We’re excited to have you join us, to make these the ultimate cloud and developer learning conferences of 2019. Don’t wait! Submit your proposal by 4pm ET on Friday, March 22. Details and submission guidelines are available on the Oracle OpenWorld and Oracle Code One websites below. Important Links Oracle OpenWorld Conference website Call for Speakers – proposal deadline: March 22, 2019 Oracle Code One Conference website Call for Speakers – proposal deadline: March 22, 2019

This year, Oracle OpenWorld and Oracle Code One San Francisco 2019 are taking place Sunday, September 15 – Thursday, September 19, 2019. The Call for Speakers is now open, and the deadline is coming...

Linux Kernel Development

Reboot faster with kexec

Oracle Linux kernel developer Steve Sistare contributes this article on speeding up kernel reboots for development and for production systems. Fast reboot with kexec The kexec command loads a new kernel and jumps directly to it, bypassing firmware and grub. It is most often used as the first step in generating a crash dump, but it can also be used to perform an administrative reboot. The time saved by skipping firmware is substantial on a server with large memory, many CPUS, and many devices. This is particularly useful during kernel development when you frequently rebuild and reboot the kernel. The kexec options are a bit arcane, so I wrote a script to make it easier to use for basic reboot. You specify the new or old kernel, and new or old or additional kernel command-line parameters. The script loads the new kernel and initramfs using kexec -l, then gracefully stops systemd services and jumps to the new kernel using systemctl kexec. It could save a few more seconds by abruptly killing processes with kexec -e, but I choose the graceful route to mimic a normal reboot as closely as possible. The dramatic time savings come from skipping firmware, rather than skipping systemd shutdown. Here is the bash script, which I call kboot: #!/bin/sh [[ "$1" != '-' ]] && kernel="$1" shift if [[ "$1" == '-' ]]; then reuse=--reuse-cmdline shift fi [[ $# == 0 ]] && reuse=--reuse-cmdline kernel="${kernel:-$(uname -r)}" kargs="/boot/vmlinuz-$kernel --initrd=/boot/initramfs-$kernel.img" kexec -l -t bzImage $kargs $reuse --append="$*" && \ systemctl kexec   Usage: kboot kboot <kernel> [<params>] ... The first arg (if any) specifies the kernel, where a '-' means use the current kernel. If the 2nd arg is '-' or is omitted, then the existing kernel parameters are appended. Any remaining args are also appended to the kernel parameters.   Examples:   Reboot to the same (possibly updated) kernel with same kernel command line. # kboot Reboot to a different kernel with the same kernel command line. # kboot 4.20.0-rc5 Reboot to the same kernel with same kernel command line plus additional parameters: # kboot - - log_buf_len=16M enforcing=0 Reboot to a different kernel with the same kernel command line plus additional parameters # kboot 4.20.0-rc5 - log_buf_len=16M enforcing=0 Reboot to the same kernel with a new command line. Add single quotes around the parameters if they contain shell meta characters. # kboot - 'root=/dev/mapper/vg00-lv_root ro crashkernel=auto rd.lvm.lv=vg00/lv_root rd.lvm.lv=vg00/lv_swap console=ttyS0,115200 systemd.log_level=debug' On an X6-2 test system with 2 sockets * 22 cores and 448 GB of RAM, running Oracle Linux 7.5 with UEK5, a normal reboot takes 184 seconds, as measured from typing reboot to the availability of the sshd port for logging in. kboot takes 30 seconds, a 6X speedup. For my kernel projects, kexec reboot has made the edit-compile-debug cycle a pleasure rather than a punishment!

Oracle Linux kernel developer Steve Sistare contributes this article on speeding up kernel reboots for development and for production systems. Fast reboot with kexec The kexec command loads a new kernel...

Linux

Easy Compute Instance Metadata Access with OCI Utils

About OCI Utilities Instances created in Oracle Cloud Infrastructure using Oracle-Provided Images based on Oracle Linux include a pre-installed set of utilities that are designed to make it easier to work with Oracle Linux images. This is a quick blog post to demonstrate how the oci-metadata command included in OCI Utilities make quick work of accessing instance metadata. Update - March 4th, 2019: This post was updated to include the --value-only option As of this writing, the following components are included. You can read more about each of the utilities in the OCI Utilities documentation. ocid oci-growfs oci-iscsi-config oci-metadata oci-network-config oci-network-inspector oci-network-inspector oci-public-ip Working With Instance Metadata Using oci-metadata Display all instance metadata To display all metadata in human-readable format, simply run oci-metadata $ oci-metadata Instance details: Display Name: autonomous blog Region: iad - us-ashburn-1 (Ashburn, VA, USA) Canonical Region Name: us-ashburn-1 Availability Domain: PDkt:US-ASHBURN-AD-3 Fault domain: FAULT-DOMAIN-2 OCID: ocid1.instance.oc1.iad.abuwcl.................7crrhz2g......aq Compartment OCID: ocid1.tenancy.oc1..aaaaaaaa5............qok3lunzc6.....jw7q Instance shape: VM.Standard2.1 Image ID: ocid1.image.oc1.iad.aaaaaaaawuf..............zjc7klojix6vmk42va Created at: 1548877740674 state: Running Instance Metadata: user_data: dW5kZWZpbmVk ssh_authorized_keys: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAxxxxxxxxxxVMheESQgRukanNBmLxaXA0kZw4DxaCispcEjTgAmBmHpUWQBsG7Y/s3zVQDUZ5irMKr2Rtc5DAkH+y6SsNw+xxxxxx+Zix85RClbmu3vl6Mf1++15VoxxxxxEP16mPZl+Cfk/T9LVIlMtV+brph8AQACxFxxxxxxWSNTj1tE8DTml2QnSA6F6MtP6OvOQ0KzQViNm1kN9MaarGOoNxxxxxxNyJGayh8YA6+n8Y07A3fr870H bmc Networking details: VNIC OCID: ocid1.vnic.oc1.iad.abuwcljsrul..............................hioysuicdmzcq VLAN Tag: 804 MAC address: 02:00:17:01:78:09 Subnet CIDR block: 10.0.2.0/24 Virtual router IP address: 10.0.2.1 Private IP address: 10.0.2.3   To display all metadata in JSON format: $ oci-metadata -j oci-metadata -j { "instance": { "compartmentId": "ocid1.tenancy.oc1..aaaaaaaa5............qok3lunzc6.....jw7q", "displayName": "autonomous blog", "timeCreated": 1548877740674, "state": "Running", "image": "ocid1.image.oc1.iad.aaaaaaaawufnve5jxze4xf7orejupw5iq3pms6cuadzjc7klojix6vmk42va", "canonicalRegionName": "us-ashburn-1", "metadata": { ... Display a specific metadata key value The following command displays the value of the canonicalRegionName key, trimming the path to the last component only using the --trim option. $ oci-metadata -g canonicalRegionName --trim Canonical Region Name: us-ashburn-1 Exporting metadata values as environment variables Using eval To set an environment with the name and value from instance metadata: $ eval $(oci-metadata --get compartmentId --export) $ echo $compartmentId ocid1.tenancy.oc1..aaaaaaaa5............qok3lunzc6.....jw7q Using the --value-only option The --value-only option, as the name implies, outputs only the key value without a label. For example: $ oci-metadata -g "CanonicalRegionName" --value-only us-phoenix-1 Or, to assign the compartment ID to an environment variable: $ export MYCOMPARTMENT=`oci-metadata -g "compartmentID" --value-only` $ echo MYCOMPARTMENT ocid1.tenancy.oc1..aaaaaaaa5............qok3lunzc6.....jw7q Using jq To set an environment variable you name yourself, you can extract the raw value of a key using the jq JSON processor: $ export MYCOMPARTMENT=`oci-metadata -j --trim -g /instance/compartmentID | jq -r .[]` $ echo MYCOMPARTMENT ocid1.tenancy.oc1..aaaaaaaa5............qok3lunzc6.....jw7q Display the Instance's Public IP Address To display the instance's public IP address $ oci-public-ip Public IP address: 129.xxx.yyy.175   And to extract just the IP address: oci-public-ip -j | jq -r .[] 129.xxx.yyy.175

About OCI Utilities Instances created in Oracle Cloud Infrastructure using Oracle-Provided Images based on Oracle Linux include a pre-installed set of utilities that are designed to make it easier to...

Linux Kernel Development

Introducing SPDK for Oracle Linux

Oracle Linux Kernel developer Lance Hartmann contributes this blog post on using SPDK, the Storage Performance Development Kit. Introducing the SPDK Slated to arrive soon in the developer yum channel via ULN, the Storage Performance Development Kit SPDK is an open-source project providing user space tools and libraries for writing high performance, scalable storage applications built largely but not solely around a user space NVMe driver. Harnessing the power of multi-core CPUs and the multi-queue architecture of NVMe, SPDK applications can easily achieve the maximum bandwidth that a NVMe drive supports and enjoy low latency by polling for I/O completions instead of using interrupts. Under the Hood Zero-copy I/O is managed through the use of hugepages whose physical pages are always pinned for the data buffers and the I/O queues. A single thread per NVMe queue which both dispatches I/Os and checks for completions enables a lockless I/O path. For those NVMe controllers designated for use by the SPDK, the default Linux kernel nvme driver is unbound from them and replaced with a binding to either the uio_pci_generic or vfio-pci kernel drivers. Using the SPDK API, applications then gain access, via mmap(), to the NVMe controller's register set enabling them to perform admin actions and trigger I/Os. In addition to providing I/O to locally (PCIe) attached NVMe drives, the SPDK also ships with a NVMe over Fabric target application. The RDMA transport for Infiniband and RoCE has been supported in the SPDK for a while, and the TCP transport was just recently added. A set of patches for supporting the Fibre Channel (FC) transport have been proposed. Configuration of the target is facilitated with either a configuration file, or may be dynamically managed via RPC calls provided by SPDK Python scripts. The growth and active development of the SPDK has yielded additional functionality. A user space block layer also exists and provides a highly modular architecture enabling the development of "bdevs" which may be used alone or stacked atop one another enabling complex I/O pipelines. Existing bdev modules today include NVMe, RAM disk, Linux AIO, RAID (level-0/striping), iSCSI and more all of which may be configured as targets to the SPDK's target applications. Common features of the block layer include mechanisms for enumerating SPDK block devices and exposing their supported I/O operations, queueing I/Os in the case of the underlying device's queue is full, support of hotplug remove notification, obtaining I/O statistics which may be used for quality-of-service (QoS) throttling, timeout and reset handling, and more. Traditionally, the SPDK has relied on portions of the Data Plane Development Kit DPDK to provide lower level functionality which is referred to as the run time environment. This includes things like thread and co-process management, memory management, virtual to physical address translation, lockless data structures like rings, and PCI enumeration and mmap()'d I/O. Over time it was realized that a number of consumers of the SPDK already had much of such functionality in place, and moreover, that their implementation was highly tailored to their types of workloads. Hence, an abstraction layer was created in the SPDK enabling consumers to employ their own run time environment if preferred over the default DPDK. Packaging The SPDK is currently in use in a number of production environments around the world, though to date has yet to appear via packages. Instead, consumers of the SPDK have been downloading source and building the SPDK from scratch to enable integration with their applications. Coming soon, SPDK rpm packages "spdk", "spdk-tools" and "spdk-devel" will make their inaugural debut for Oracle Linux. The aim is to offer users the ability to experiment with some example SPDK applications and provide the include files and libraries to build their own SPDK applications saving them the need to locate, download and build the SPDK themselves. Both static and their shared library equivalents are available though note that ABI versioning it not yet in place but planned in a future release.

Oracle Linux Kernel developer Lance Hartmann contributes this blog post on using SPDK, the Storage Performance Development Kit. Introducing the SPDK Slated to arrive soon in the developer yum channel...

Announcements

10 Leaders Share Their Infrastructure Transformation Stories

The detailed use cases in this paper are of the 2018 Winners of the Oracle Excellence Awards “Leadership In Infrastructure Transformation” category. In these 10 individual stories, you'll learn how IT leaders accelerated innovation and drove business transformation.  Each of these leaders ultimately delivered value to their organizations through the use of multiple Oracle technologies which have resulted in reduced cost of IT operations, improved time to deployment, and performance and end user productivity gains. Each story includes the use of at least one, if not a combination of several, of the below:   •    Oracle Linux •    Oracle Virtualization (VM, VirtualBox) •    Oracle Private Cloud Appliance •    Oracle SuperCluster •    Oracle SPARC •    Oracle Solaris •    Oracle Storage, Tape/Disk The stories feature Michael Polepchuk, Deputy Chief Information Officer, BCS Global Markets; Brian Young, Vice President, Cerner, Brian Bream, CTO, Collier IT; Rudolf Rotheneder, CEO, cons4u GmbH; Heidi Ratini, Senior Director of Engineering, IT Convergence; Philip Adams, Chief Technology Officer, Lawrence Livermore National Labs; JK Pareek, Vice President, Global IT and CIO, Nidec Americas Holding Corporation; Baris Findik, CIO, Pegasus Airlines; Michael Myhrén, Senior DBA Senior Systems Engineer and Charles Mongeon, Vice President Data Center Solutions and Services (TELUS Corporation). Learn more here. 

The detailed use cases in this paper are of the 2018 Winners of the Oracle Excellence Awards “Leadership In Infrastructure Transformation” category. In these 10 individual stories, you'll learn how IT...

Announcements

Oracle Linux 7 Completes Common Criteria Evaluation

Oracle is pleased to announce that Oracle Linux 7 received Common Criteria Certification which was performed against the National Information Assurance Partnership (NIAP) General Purpose Operating System v4.1 and additionally at Evaluation Assurance Level (EAL) 1. Common Criteria is an international framework (ISO/IEC 15408) which defines a common approach for evaluating security features and capabilities of Information Technology security products. A certified product is one that a recognized Certification Body asserts as having been evaluated by a qualified, accredited, and independent evaluation laboratory competent in the field of IT security evaluation to the requirements of the Common Criteria and Common Methodology for Information Technology Security Evaluation. Security evaluation is a process by which independent but accredited organizations provide assurance in the security of IT products and systems to commercial, government, and military institutions. Such evaluations, and the criteria upon which they are based, are designed to help establish an acceptable level of confidence for IT purchasers and vendors alike. Furthermore, security evaluation criteria and ratings can be used as concise expressions of IT security requirements. The completed evaluation for Oracle Linux 7 update 3 was performed by atsec information security AB, in accordance with the requirements of Common Criteria, version 3.1, release 5, and the Common Methodology for IT Security Evaluation, version 3.1, release 5. The evaluation was performed at the evaluation assurance level Evaluation Activities for OSPP (Protection Profile for General Purpose Operating Systems v4.1) and SSH-EP (Extended Package for Secure Shell) as well as at the evaluation assurance level EAL 1, augmented by ALC_FLR.3 Flaw Remediation reporting procedures. The evaluation platform was Oracle Server X7-2 with both the Unbreakable Enterprise Kernel (UEK) and Red Hat Compatible Kernel (RHCK). Oracle Linux is engineered for open cloud infrastructure. It delivers leading performance, scalability, reliability, and security for enterprise SaaS and PaaS workloads as well as traditional enterprise applications. Oracle Linux Support offers access to award-winning Oracle support resources and Linux support specialists, zero-downtime updates using Ksplice, additional management tools such as Oracle Enterprise Manager and lifetime support, all at a low cost. Unlike many other commercial Linux distributions, Oracle Linux is easy to download and completely free to use, distribute, and update. For a matrix of Oracle security evaluations currently in progress as well as those completed, please refer to the Oracle Security Evaluations. Visit Oracle Linux Security to learn how Oracle Linux can help keep your systems secure and improve the speed and stability of your operations.

Oracle is pleased to announce that Oracle Linux 7 received Common Criteria Certification which was performed against the National Information Assurance Partnership (NIAP) General Purpose Operating...

Announcements

Announcing Oracle Container Services 1.1.12 for use with Kubernetes

Oracle is pleased to announce the general availability of Oracle Container Services 1.1.12 for use with Kubernetes which is based on Kubernetes version 1.12.5, as released upstream. It is available for Oracle Linux 7 and is designed to integrate with the Oracle Container Runtime for Docker, provided and supported by Oracle. Oracle Container Services for use with Kubernetes runs in a series of Docker containers which are available from the Oracle Container Registry.  This release maintains Oracle's commitment to conformance with the upstream project and is Certified Kubernetes by the Cloud Native Computing Foundation (CNCF). New features in this release: Support for high availability multi-master clusters kubeadm-ha-setup provides a setup and configuration tool to lessen the administrative burden in the creation of  "high availability" clusters.   Replacement of KubeDNS with CoreDNS CoreDNS is introduced and functions as the cluster DNS service. CoreDNS is installed by default on all new clusters, and support for KubeDNS is deprecated. Note that CoreDNS support requires the Unbreakable Enterprise Kernel Release 5 for Oracle Linux 7 or later. Although Oracle makes KubeDNS and support for the Unbreakable Enterprise Kernel Release 4 for Oracle Linux 7 available for users upgrading from earlier versions, the KubeDNS configuration is deprecated and future upgrades from this combination may not be possible.   Flexvolume driver for Oracle Cloud Infrastructure The flexvolume driver enables you to add block storage volumes hosted on Oracle Cloud Infrastructure to your Kubernetes cluster.  In this release, flexvolume driver for Oracle Cloud Infrastructure is a technical preview, you can read more at https://github.com/oracle/oci-flexvolume-driver Additional features in this release of Oracle Container Services for use with Kubernetes include upstream Kubernetes 1.12.5 software packaged for Oracle Linux, improved setup and configuration utilities, updated Kubernetes Dashboard software, improved cluster backup and restore tools, and integration testing for use with Oracle Cloud Infrastructure. For more information about these and other new features, please review the Oracle Container Services for Use with Kubernetes User Guide. The guide also contains documentation on how to use the new setup and configuration utility to install a multi-master cluster as well as upgrade existing clusters. Note that Oracle does not support upgrading an existing single-master cluster to a high availability cluster. Installation and Update Oracle Container Services 1.1.12 for use with Kubernetes is free to download from the Oracle Linux yum server. Customers are encouraged to use the latest updates for Oracle Container Services for use with Kubernetes that are released on the Oracle Linux yum server and on Oracle's Unbreakable Linux Network (ULN). You can use the standard yum update command to perform an upgrade. For more information about how to install and configure Oracle Container Services for use with Kubernetes, please review the Oracle Container Services for use with Kubernetes User's Guide. Oracle does not support Kubernetes on systems where the ol7_preview, ol7_developer, or ol7_developer_EPEL yum repositories or ULN channels are enabled, or where software from these repositories, or channels, is currently installed on the systems where Kubernetes runs.  Support This release of Oracle Container Services for use with Kubernetes is made available for Oracle Linux 7 and is designed to integrate with Oracle Container Runtime for Docker. Support is available to customers having an Oracle Linux Premier Support subscription and is restricted to the combination of Oracle Container Services for Kubernetes and Oracle Container Runtime for Docker on Oracle Linux 7. Refer to Oracle Linux 7 License Information User Manual for information about Oracle Linux support levels. Kubernetes® is a registered trademark of The Linux Foundation in the United States and other countries, and is used pursuant to a license from The Linux Foundation. Resources – Oracle Linux Documentation Oracle Linux Software Download Oracle Linux Oracle Container Registry Blogs Oracle Linux  Social Media Oracle Linux on YouTube Oracle Linux on Facebook Oracle Linux on Twitter Data Sheets, White Papers, Videos, Training, Support & more Oracle Linux Product Training and Education Oracle Linux - http://oracle.com/education/linux For community-based support, please visit the Oracle Linux space on the Oracle Technology Network Community.

Oracle is pleased to announce the general availability of Oracle Container Services 1.1.12 for use with Kubernetes which is based on Kubernetes version 1.12.5, as released upstream. It is available...

Announcements

Click to Launch Oracle Linux KVM and Oracle Linux Storage Appliance using the Oracle Cloud Marketplace

We are pleased to announce the availability of the Oracle Linux KVM Image and the Oracle Linux Storage Appliance application on Oracle Cloud Marketplace.  Oracle Cloud Infrastructure (OCI) now provides ready access to these images for fast and easy deployment using the embedded Marketplace in Oracle Cloud Infrastructure. You can launch these applications directly from the Marketplace on your OCI Compute instance.  With a few clicks, you can get your Oracle Linux KVM and Oracle Linux Storage Appliance instances up and running. To access the Marketplace from the OCI Console, click the navigation menu. Then, under Solutions, Platform and Edge, go to Marketplace. To demonstrate how easy it is to deploy Oracle Linux KVM with a few clicks, simply select the Oracle Linux KVM application from the Marketplace. This will take you to overview details about the application and provides useful links to documentation and resources, and usage information on how to access the KVM instance on OCI.  After clicking on the Launch Instance button, you will need to select the version of the image and the compartment in which you wish to deploy the image, and accept the terms of usage.  Clicking Launch Instance then will take you directly to the Create Compute Instance window with the pre-populated KVM image source and instance configuration details. You may modify instance configuration details here, and clicking on Create Instance will immediately deploy your instance.  This is how easy it is to deploy the Oracle Linux KVM Image on OCI. Deploying the Oracle Linux Storage Appliance is just as easy using the Marketplace in OCI.  You can also find the Oracle Linux KVM Image and Oracle Linux Storage Appliance on the public Oracle Cloud Marketplace at https://cloudmarketplace.oracle.com. Navigating from the public Marketplace will also allow you to deploy these images quickly from within the OCI console. By simplifying how software development teams access and deploy Oracle Linux solutions on OCI, customers can innovate and respond quickly to changing business needs. Experience for yourself how easy it is to deploy Oracle Linux solutions on Oracle Cloud Infrastructure. If you are not subscribed to Oracle Cloud Infrastructure, you can try it out by creating a free account with available free credits. For more information, visit: Oracle Linux for Oracle Cloud Infrastructure Oracle Linux KVM Image for Oracle Cloud Infrastructure Getting Started: Oracle Linux KVM for Oracle Cloud Infrastructure Oracle Linux Storage Appliance Blog: Click to Launch Images by Using the Marketplace in Oracle Cloud Infrastructure

We are pleased to announce the availability of the Oracle Linux KVM Image and the Oracle Linux Storage Appliance application on Oracle Cloud Marketplace.  Oracle Cloud Infrastructure (OCI) now...

Announcements

Announcing Oracle Container Runtime for Docker Release 18.09

Oracle is pleased to announce the release of Oracle Container Runtime for Docker version 18.09. Oracle Container Runtime allows you to create and distribute applications across Oracle Linux systems and other operating systems that support Docker. Oracle Container Runtime for Docker consists of the Docker Engine, which packages and runs the applications, and integrates with the Docker Hub, Docker Store and Oracle Container Registry to share the applications in a Software-as-a-Service (SaaS) cloud. Notable Updates Oracle has implemented multi-registry support that makes it possible to run the daemon with the --default-registry flag, which can be used to change the default registry to point to a registry other than the standard Docker Hub registry. More flexibility is provided with the --add-registry option which defines alternate registries to be used in case the default registry is not available. Other functionality available in this feature includes the --block-registry flag which can be used to prevent access to a particular Docker registry. Registry lists help ensure that images are prefixed with their source registry automatically, so that a listing of Docker images indicates the source registry from which an image was pulled.   This release of Docker introduces an integrated SSH connection helper that allows a Docker client to connect to a remote Docker engine securely over SSH.   The Docker client application can now be installed as an independent package, docker-cli, so that the Docker engine daemon does not need to be installed on a system that may be used to manage a remote Docker daemon instance.   Docker 18.09 uses a new version of containerd, version 1.2.0. This version of containerd includes many enhancements for greater compatibility with the most recent Kubernetes release. This release has integrated additional improvements and security fixes, including the fix to CVE-2019-5736.   Upgrading To learn how to upgrade from a previously supported version of Oracle Container Runtime for Docker, please review the Upgrading Oracle Container Runtime for Docker chapter of the documentation. Note that upgrading from a developer preview release is not supported by Oracle. Support Support for the Oracle Container Runtime for Docker is available to customers with an Oracle Linux support subscription. Refer to Oracle Linux 7 License Information User Manual for information about Oracle Linux support levels. Oracle Linux Resources: Documentation Oracle Container Runtime for Docker User's Guide Oracle Container Services for use with Kubernetes User's Guide Oracle Linux Software Download Oracle Linux Oracle Container Registry Blogs Oracle Linux Blog Community Pages Oracle Linux Social Media Oracle Linux on YouTube Oracle Linux on Facebook Oracle Linux on Twitter Data Sheets, White Papers, Videos, Training, Support & more Oracle Linux Product Training and Education Oracle Linux - education.oracle.com/linux For community-based support, please visit the Oracle Linux space on the Oracle Developer Community.

Oracle is pleased to announce the release of Oracle Container Runtime for Docker version 18.09. Oracle Container Runtime allows you to create and distribute applications across Oracle Linux systems...

Linux

Making Code More Secure with GCC - Part 1

This blog entry was contributed by Maxim Kartashev In today's world, programming securely is the default option for any project. A program that doesn't validate its input, contains buffer overruns or uninitialized variables, uses obsolete interfaces, etc. quickly becomes a liability. Standards, best practices, and tools that help find security-related bugs and prevent them from creeping into code are in no short supply. There are, for instance, SEI CERT secure coding standards designed to be statically verifiable. And a multitude of static checkers such as Fortify, Coverity, Parfait, to name a few. They all help to make the code more secure, each at its own cost to developers, but inevitably involve tools that are generally foreign to the development process. The effort required to start using that software in your project varies and is never zero. Authors of Coverity, a popular static program analyzer, formulated two laws of bug finding: "Law #1: You can't check code you don't see. Law #2: You can't check code you can't parse". From the tool developer's perspective, this means that the code analyzer must mimic the toolchain (compiler, linker, support libraries) that is used to build the program as closely as possible. Or, risk missing bugs and seeing what's not there, which may result in false positives that so frequently throw us all off. On the other hand, the toolchain itself has many qualities of a program checker: the compiler can flag potential errors in the code, often at no additional cost to the user, the linker can help to find inconsistencies in inter-module calls and warn about the use of insecure and outdated interfaces, the run-time support libraries can do additional bookkeeping and help to locate accidental interface misuse. This post starts a short series, in which I am going to explore the capabilities of the GNU 7.3 toolchain in the area of secure programming. I'll focus on the power of the compiler as a static analyzer in this post. GCC Static Analysis Options Before generating executable code, the compiler has to perform a great deal of checks in order to make sure the program conforms to syntactic and semantic constraints of the language it is written in. For example, direct initialization of a 1-byte variable with an integer constant that doesn't fit in it is an error in C++11 and, quite naturally, the error will be reported: char c{0xFFFF}; // error: narrowing conversion of `65535` from `int` to `char` inside { } [-Wnarrowing] Some of those checks aren't strictly required, but help to bring potential problems to the programmer's attention. For example, using a different kind of initialization of the same variable with the same value is technically allowed, but still has the same chance of being an error on the programmer's part. This is where compiler warnings come in: char c(0xFFFF); // warning: overflow in implicit constant conversion [-Woverflow] gcc 7.3 has almost 150 distinct options that control warnings. Some are useful because they indicate unintended user errors, even if the language rules say nothing in that situation. Some are there to help to enforce certain guidelines that may or may not be employed by your project (for instance, -Weffc++). Fortunately, very few of those options need to be mentioned by name thanks to several "macro" options that enable many warnings at once. These are -Wall and -Wextra. Together, the two options control 50+ warnings, all which are useful, so it is a sensible default for any build. Despite the name, -Wall doesn't turn on all the warnings; neither does -Wextra. While they give diagnostics worth paying attention to, there could be an overwhelming amount of "unused variable" warnings at first. Those rarely indicate real problems in the code (but see below), so it might be a good idea to add -Wno-unused until all the other warnings have been dealt with. The proper solution to silencing the "unused" warnings is to add __attribute__((unused)) to those variables that are intentionally unused. Note Sometimes the warning about an unused variable hints at the real problem, so don't turn them off forever. For example, in the following code, the "unused" warning indirectly points to the fact that the constructor's parameter was used instead of the class member, which was obviously intended to be initialized in the constructor. This is the result of naming the constructor parameter the same as the class's data member (may compilers be merciful to those adventurous souls who do such a thing). struct A { int field; A(int field) // warning: parameter `field` set but not used [-Wunused-but-set-parameter] { field = 42; // meant to initialize the data member, but set constructor's parameter instead } }; Additional Help The -Wall -Wextra warnings do not fully unleash the potential of gcc's static analysis capabilities. To narrow the compiler's focus on the program security, consider adding these options as well: -Wformat-security -Wduplicated-cond -Wfloat-equal -Wshadow -Wconversion -Wjump-misses-init -Wlogical-not-parentheses -Wnull-dereference   Here is why I consider those useful:   Options Example -Wformat-security or -Wformat=2 Help to catch all kinds of format-string-related security holes. It always makes sense to keep either option on the command line. void foo(const char* s) { printf(s); // warning: format not a string literal and no format arguments [-Wformat-security] } -Wduplicated-cond Seems to always indicate a bug; for example, a misspelled comparison operator. if ( p == 42 ) { return 1; } else if ( 42 == p ) { // warning: duplicated `if` condition [-Wduplicated-cond] return 2; } -Wfloat-equal The result of comparing floating point numbers for equality is rarely predictable and therefore indicate a possible bug in the code. Consult this 1991 article titled "What Every Computer Scientist Should Know About Floating-Point Arithmetic" for an in-depth explanation of the reasons. double d = 3; return d == 3; // warning: comparing floating point with == or != is unsafe [-Wfloat-equal] -Wshadow This option helps to catch accidental misuse of variables from different scopes and is highly recommended. int global = 42; int main() { char global = 'a'; // warning: declaration of 'global' shadows a global declaration [-Wshadow] // ... many lines later ... return global; // refers to the char variable, not ::global } -Wconversion The rules of adjusting the value when changing its type are complex and sometimes counter-intuitive. This option helps to spot unintended value adjustments. unsigned u = -1; // warning: negative integer implicitly converted // to unsigned type [-Wsign-conversion] -Wjump-misses-init Unlike in C++, jumping past variable initialization is not an error in C, but is nevertheless dangerous. switch(i) { case 10: foo(); int j = 42; case 11: // warning: switch jumps over variable initialization [-Wjump-misses-init] return j; default: return 42; } -Wlogical-not-parentheses This option helps to find questionable - from the readability point of view - conditions that may or may not indicate a bug in the code. if ( ! a > 1 ) // warning: logical not is only applied to the left hand // side of comparison [-Wlogical-not-parentheses] -Wnon-virtual-dtor This option is specific to C++ and usually indicates a problem in the code, but is not sophisticated enough to guarantee the absence of false positives. struct A // warning: `struct A` has virtual functions and non-virtual destructor { virtual void foo(); ~A(); }; void foo(A* a) { delete a; // warning: deleting object of polymorphic class type `A` which has // non-virtual destructor might cause undefined behavior [-Wdelete-non-virtual-dtor] } -Wnull-dereference This is a very useful warning with little to no false positives, but it requires the-fdelete-null-pointer-checks option, which is enabled by optimizations for most targets. void foo(int* p) { *p = 1; // warning: null pointer dereference [-Wnull-dereference] } int main() { int *p = 0; foo(p); }   Higher Optimization Means Better Analysis In order to be helpful with some of those warnings (like, for example, -Wnull-dereference and -Wstringop-overflow), the compiler needs to collect and analyze various kinds of information about the program. Some types of analysis are only performed at higher optimization levels, which is why it is advisable to compile at least with -O1 to get better diagnostics. For example: #include int main(int argc, char *argv[]) { char buf[4]; const char *s = argc > 10 ? argv[0] : "adbc"; // "s" may require 5 or more bytes strcpy(buf, s); // there's only room for 3 characters and the terminating 0 byte in buf } With the default optimization level - implying no optimization at all - you get no warnings: $ gcc -Wall -Wextra a.c But with -O1, the problem gets spotted: $ gcc -Wall -Wextra -O1 a.c a.c: In function ‘main’: a.c:8:5: |*warning*|: ‘strcpy’ writing 5 bytes into a region of size 4 overflows the destination [-Wstringop-overflow=] strcpy(buf, s); ^~~~~~~~~~~~~~ Inter-module Checks Even the highest optimization level cannot compensate for lack of information: the compiler is usually given one compilation unit (CU) at a time, making cross-checks between CUs impossible. There's a solution, though: the -flto option. It works with the linker's help and can spot otherwise very hard-to-find bugs. In this example, a function is defined as char foo(int) in one file, but declared int foo(int) in another: a.c char foo(int i) { /* ... */ } b.c extern int foo(int); typedef int (*FUNC)(int); int main() { FUNC fp = &foo; int i = fp(1); // foo() actually only returns 1 byte, while we read sizeof(int) here return i; // may return garbage } Notice the difference in the size of return types; when this function is called by the CU that only sees the latter declaration, it can end up reading uninitialized memory (3 bytes more than the function actually returns). Only the final link step with -flto can help to catch this: $ gcc -flto -c a.c b.c # no warnings $ gcc -flto a.o b.o b.c:3:12: |*warning*|: type of ‘foo’ does not match original declaration [-Wlto-type-mismatch] extern int foo(int); ^ a.c:1:6: note: return value type mismatch char foo(int i) ^ a.c:1:6: note: type ‘char’ should match type ‘int’ a.c:1:6: note: ‘foo’ was previously declared here As you can see, -flto has enabled gcc to compare declaration and definition of the function and find that they aren't really compatible. Key Take-Aways To make your gcc-compiled program more secure: Always add -Wall -Wextra to the gcc command line to get an ever-expanding set of useful diagnostics about your program. Add -Wno-unused if the amount of messages regarding unused variables is overwhelming; consider using __attribute__((unused)) later. Don't forget these additional options help to make the code even more secure: -Wformat-security -Wduplicated-cond -Wfloat-equal -Wshadow -Wconversion -Wjump-misses-init -Wlogical-not-parentheses -Wnull-dereference Compile with optimization (-O1 or higher) to enable the compiler to issue better diagnostics and help to find real bugs in the code. Use the latest possible gcc; each new major version adds dozens of new checks and improves existing ones. What's Next Static program analysis is always the result of a trade-off between the quality of real bugs it finds and quantity of false positives. In other words, not all true bugs are found and reported at compile time. Which is why keeping your eyes open at run time is also important and the GNU compiler can help with that, too. gcc is capable of adding checks to the code that it generates ("sanitizing" it), thus enabling automatic bug detection at run time. This compiler feature can help to find bugs that completely escape static analysis. I also plan to look at the built-in debugging capabilities of support libraries the GNU toolchain provides. References SEI CERT Coding Standards for C, C++, Java, and Perl. A Few Billion Lines of Code Later: Using Static Analysis to Find Bugs in the Real World - an article from the creators of Coverity. A complete list of gcc 7.3 options with description. Difference in gcc options between versions that shows the amount of new kinds of analysis each new gcc version adds. Parfait - Oracle Labs static program analysis tool.

This blog entry was contributed by Maxim Kartashev In today's world, programming securely is the default option for any project. A program that doesn't validate its input, contains buffer overruns or...

Linux Kernel Development

Talk of Huge Pages at Linux Plumbers Conference 2018

Oracle Linux kernel developer Mike Kravetz, who is also the hugetlbfs maintainer, attended Linux Plumbers Conference 2018 and shares some of his thought about the conference especially around huge pages in this blog post.   Huge Pages and Contiguous Allocations at LPC 2018 At the 2018 Linux Plumbers Conference, Huge Page utilization was discussed during the Performance and Scalability microconf, and the topic of Contiguous Allocations was discussed during the RDMA microconf. Christoph Lameter and myself gave brief presentations and led discussions on these topics. Neither of these topics are new to Linux and are often discussed at conferences and other developer gatherings. One reason for frequent discussion is that the issues are somewhat complicated and difficult to implement to everyone’s satisfaction. As a result, discussions tend to rehash old ideas, talk about any progress made and look for new ideas. Below are some of my observations from this year’s discussions. Huge Pages One may think that there is little to talk about in the realm of huge pages. After all, they have been available in Linux via hugetlbfs for over 15 years. When Transparent Huge Pages (THP) were added, huge pages could be used without all the required hugetlbfs application changes and sysadmin support. While hugetlbfs functionality is mostly settled, new features have recently been added to THP: notably work by Kirill Shutemov and others to add THP support in shm and tmpfs. Kirill has even proposed patches that add THP support to ext4. In addition to hugetlbfs and THP, DAX (Persistent Memory) defaults to using huge pages for suitably sized mappings. Ongoing Xarray work by Matthew Wilcox will make page cache management of multiple page sizes much easier. On systems with very large memory sizes people would ideally like to scale up the base page size. The well known default base page size is 4K on x86 and most other architectures. However, it is possible to change the base page size on some architectures such as arm64 and powerpc. There is interest in exploring ways to increase the base page size on x86. However, jumping to the next size supported by the MMU (2M) would be wasteful in most cases. But, for really really big memory systems (think multi- TB) it may be worth exploring. Contiguous Allocation This discussion was a follow up on the LPC 2017 presentation that formally introduced the a new contiguous allocation request. The use case from 2017 was the need for a RDMA driver to have physically contiguous areas for optimal performance. Ideally, these areas would be allocated by and passed in from user space. The ideal size for this driver would be 2G. Two things make this use case especially difficult. First, there is no interface capable of obtaining a physically contiguous area of such a large size. The in kernel memory allocators are based on the buddy allocator and have a maximum allocation size of MAX_ORDER-1 pages (4M default on x86). CMA (Contiguous Memory Allocator) can allocate such large areas, but it requires administrative overhead and coordination. Secondly, is the general problem of memory fragmentation. After the system is up and running for a while, it becomes less and less likely to find large physically contiguous areas. Memory migration is used to try and create large contiguous areas. However, some pages become locked and can not be moved which prevents their migration. In a separate presentation, work in the area of fragmentation avoidance was presented by Vlastmil Babka: The hard work behind large physical allocations in the kernel. In addition, Mel Gorman has been working on a patch series to help address this issue. Christoph Lameter suggested an idea to protect large order pages from being broken up so that they would be available for contiguous allocations. However, he admits this is a controversial hack that will likely not be accepted due to the “memory reservation” aspect of the approach. Even though the likelihood of actually obtaining large contiguous allocations is only slowly moving forward, an in kernel interface to obtain contiguous pages has been proposed. alloc_contig_pages() would search for and return an arbitrary number contiguous pages if possible. There is similar special case code in the kernel today to allocate gigantic huge pages. The idea is to use this new interface for gigantic huge pages as well as other use cases.

Oracle Linux kernel developer Mike Kravetz, who is also the hugetlbfs maintainer, attended Linux Plumbers Conference 2018 and shares some of his thought about the conference especially around huge...

Linux Kernel Development

BPF: Using BPF to do Packet Transformation

Notes on BPF (6) - BPF packet transformation using tc Oracle Linux kernel developer Alan Maguire presents this six-part series on BPF, wherein he presents an in depth look at the kernel's "Berkeley Packet Filter" -- a useful and extensible kernel function for much more than packet filtering. In earlier blog entries, we've tried to run through some of the concepts in BPF and hopefully now we're ready to try writing some BPF programs. One of the great use cases for BPF is in network packet handling. Here we will try and do some magic using BPF; we're going to turn IPv4 packets we receive on the wire into IPv6 packets for the receiving Linux networking stack, so that the receiving TCP/IP stack only sees IPv6 traffic, and then we will reverse the trick on outbound. So our system running BPF will only see IPv6 in the networking stack, while IPv4 traffic will be what's seen on the wire. Specifically we'll do this for an ICMP echo request (ping), converting an inbound ping into an IPv6 echo request. Then we will take the IPv6 echo reply and convert it into IPv4. So the remote ping application thinks it's talking to an IPv4 endpoint, while the local Linux TCP/IP stack thinks it's talking to an remote IPv6 ping client! So on inbound, what happens is this: +----> 3. IPv6 packet is processed by TCP/IP stack | +-----> 2. BPF ingress (inbound) filter transforms it into IPv6 | 1. IPv4 inbound packet arrives Similarly for outbound packets: +----- 1. IPv6 packet is sent by TCP/IP stack V +-------2. BPF egress (outbound) filter transforms it into IPv4 | 3. IPv4 outbound packet is sent on wire. Why do this? Mostly because it's a non-trivial example of using BPF to do packet transformation, and I couldn't find any existing examples that do IPv4 -> IPv6 transformation. As a reminder though, the samples/bpf directory in the kernel tree has a bunch of different examples that are useful if you're trying to learn how to write BPF programs. If you want to see the fully worked example, check out https://github.com/alan-maguire/bpf-test/blob/master/bpf/test_bpf_helper_bpf_skb_change_proto_kern.c It's part of a repo which does unit tests of various bpf helpers. This one covers the bpf_skb_change_proto() helper function which allows us to turn an IPv4 packet into IPv6 and vice versa. The test converts IPv4 ICMP echo requests (pings) into IPv6 echo requests on ingress, and takes IPv6 echo replies on egress and converts them into IPv4 echo replies. So the remote system pings an IPv4 address and BPF translates things so that the echo request is processed an IPv6 ping. Doing all this allows us to test that the protocol change helper works. Converting IPv4 to IPv6 - a quick primer To convert between the protocols, we need to remind ourselves what the differences are between IPv4 and IPv6. As always, consult the RFCs for full details, but to summarize the key details we need to care about: IPv6 does not utilize a checksum while IPv4 checksums the IPv4 header IPv6 headers are 40 bytes in size while IPv4 are 20 bytes, largely because... IPv6 addresses are 128 bits in size rather than 32 for IPv4. IPv6 uses extension headers, while IPv4 uses options which are tacked on the end of the header. Note that for higher-level protocols, we also need to consider the concept of a pseudo-header. When checksumming TCP, UDP and ICMPv6, we checksum the TCP, UDP and ICMPv6 packet content, but also add a pseudo-header consisting of the source/destination addresses, payload length and protocol type. Again consult the RFCs for full details, but the consequences for BPF are this: if moving from IPv4 to IPv6, we need to modify layer 4 checksums also because in changing the IP addresses (from v4 to v6 or vice versa), we also change the pseudo-header and thus the checksum calculation. Another pain point is that IPCMPv6 != ICMP; types and codes are different, even for simple packet data like ping echo requests/replies. So if we're converting ICMPv4 to ICMPv6 we will need to modify these fields too. And ICMPv4 does not use a pseudo-header, so we need to take that into account in checksum calculations. All seems kind of daunting, but the great news is BPF provides helpers to do checksum calculations, convert IPv4 to IPv6 and vice versa and so on. Choosing our BPF program type When we initially described the various program types in BPF, we talked about when the BPF program associated with the program type is run. For this case, we have two requirements: We need to be able to run it on ingress for inbound traffic and for egress for outbound traffic. It needs to process the packet on ingress prior to handing it off to the TCP/IP networking stack, and on egress prior to handing it to the driver for transmission. There are a few options for us to choose from, but a "tc" bpf program makes most sense. tc supports symmetric (ingress and egress) program attach, and the advantage of using XDP - not having to allocate packet metadata - doesn't really buy us much here, since we want to pass our packet upstream to the Linux TCP/IP stack. If we were doing some form of firewalling or DDoS mitigation where we were dropping a lot of the received packets, doing that without the overhead of skbuff packet metadata allocation in XDP is ideal. Userspace interactions? In the real world, you'd likely want to restrict such conversions to a specific IP address or port, so you could store those in a BPF hash map. In the case of our tests, we use a BPF array map to store test status for each test; this allows us to mark a test case failed from within our BPF program and to be able to pick that up in the userspace program that launches the test. Beware of offload functionality! If you are doing anything involving tunnel encapsulation/de-encapsulation, it can be difficult to get that functionality working with generic send offload/generice receive offload functionality. As a reminder, GSO allows us to send a large packet down to the device which segments it into individual under-MTU-sized packets for transmission. If we are pre-pending tunnel headers etc we may need to switch off such functionality as we want each packet to have the tunnel header pre-pended. I haven't had much luck with getting these offload features to work with BPF so I generally turn them off with ethtool, but your experience may be different. Direct packet access versus bpf_skb_load/store_bytes Initially the way to read write packet data in BPF was to use bpf_skb_load_bytes() and bpf_skb_store_bytes(). These interfaces were useful because they handled cases where the packet is what is known as non-linear. This means that the buffers storing packet data are not contiguous. In general packet headers are in the linear portion of an sk_buff, but I've come across cases (in heavily encapsulated traffic for VMs) where header data falls into non-linear parts of packet data. For a review of how sk_buff data structures work, see David Miller's "How SKBs work": http://vger.kernel.org/~davem/skb_data.html Later direct packet access was added to BPF, which meant we could use the __sk_buff "data" pointer to access packet data like a normal pointer. However for safety BPF requires we first test we have not reached the end of the linear portion of the packet (data_end). So most packet accesses have to be prefixed with checks for this condition. If we fall off the end of the packet we can explicitly call bpf_skb_pull_data() to request that the desired amount of data be in the linear portion. Writing our ingress filter Our goal is to process an IPv4 inbound ICMPv4 echo request packet and convert it into ICMPv6. I've chosen ICMP because it's harder to do than TCP or UDP - for those protocols, L4 checksum modification is done for the changed IP addresses only. For ICMPv4->ICMPv6 we also need to change ICMP type and take into account the fact that ICMPv6 has a pseudo header whereas ICMPv4 does not. So to adapt this example to TCP/UDP, you will just need to modify the checksum computations and the checksum offset. Verify our packet is IPv4/ICMP We define our ingress ELF section, and we use direct packet access (hence the initial checks) to ensure we've got an IPv4 (ETH_P_IP) packet, and moreover that it's an ICMP echo requests (ICMP_ECHO). Note we could do an explicit bpf_skb_pull_data() for these cases, but since it's unlikely that the first few bytes of the packet are non-linear we just pass such packets up to Linux intact (by returning TC_ACT_OK). SEC("ipv4toipv6_ingress") int ipv4toipv6_ingress(struct __sk_buff *skb) { /* We use an icmp hdr for icmp6 because we only want type/code/check */ struct icmphdr *icmph, icmp6h = { 0 }; void *data_end = (void *)(long)skb->data_end; void *data = (void *)(long)skb->data; struct eth_hdr *eth = data, eth_copy; struct icmphdr *icmph; sruct iphdr *iph; if (data + sizeof(*eth) > data_end) return TC_ACT_OK; if (bpf_ntohs(eth->h_proto) != ETH_P_IP) return TC_ACT_OK; if (data + sizeof(*eth) + sizeof(*iph) > data_end) return TC_ACT_OK; iph = data + sizeof(*eth); if (iph->protocol != IPPROTO_ICMP) return TC_ACT_OK; if (data + sizeof(*eth) + sizeof(*iph) + sizeof(*icmph) > data_end) return TC_ACT_OK; icmph = data + sizeof(*eth) + sizeof(*iph); if (icmph->type != ICMP_ECHO) return TC_ACT_OK; Also note that if IP options were present, we'd need to adjust offsets accordingly, but we will keep things simple here. Copy our ethernet header, extract needed info from IP header When we convert from IPv4 to IPv6, we need 20 bytes extra space for the IPv6 header. The bpf helper bpf_skb_change_proto() will reserve extra headroom in the sk_buff for us to do this, but at the cost of overwriting the existing ethernet header. So let's copy that out and modify the protocol to ETH_P_IPV6. /* Copy original ethernet header, as it must be moved. */ ret = bpf_skb_load_bytes(skb, 0, &eth_copy, sizeof(eth_copy)); if (ret) { bpf_debug("bpf_skb_load_bytes returned %d\n", ret); return TC_ACT_OK; } eth_copy.h_proto = bpf_htons(ETH_P_IPV6); /* IPv6 payload len does not include header len. */ payload_len = bpf_ntohs(iph->tot_len) - (iph->ihl << 2); Construct our ICMPv6, IPv6 headers. Here we use hardcoded IPv6 addresses along with a simple __always_inline function to set 4 32-bit values comprising an IPv6 address: static __always_inline void ipv6_addr_set(struct in6_addr *addr, __be32 w1, __be32 w2, __be32 w3, __be32 w4) { addr->in6_u.u6_addr32[0] = w1; addr->in6_u.u6_addr32[1] = w2; addr->in6_u.u6_addr32[2] = w3; addr->in6_u.u6_addr32[3] = w4; } The "__always_inline" is needed to ensure the function gets into our ingress ELF section. Back to our ingress handler: /* Time to construct ICMPv6 header. */ icmp6h.type = ICMPV6_ECHO_REQUEST; icmp6h.code = icmph->code; /* Time to construct IPv6 header and copy it. */ __builtin_memset(&ip6h, 0, sizeof(ip6h)); ip6h.version = 6; ip6h.payload_len = bpf_htons(payload_len); ip6h.nexthdr = IPPROTO_ICMPV6; ip6h.hop_limit = 8; ipv6_addr_set(&ip6h.saddr, BPF_HELPER_IPV6_PREFIX, 0, 0, BPF_HELPER_IPV6_REMOTE_SUFFIX); ipv6_addr_set(&ip6h.daddr, BPF_HELPER_IPV6_PREFIX, 0, 0, BPF_HELPER_IPV6_LOCAL_SUFFIX); Calculate value for ICMPv6 checksum Internet checksums have some really nice mathematical properties; one key property is if the field of a header changes, we can recalcuate the checksum without traversing the whole header if we know the old and new values. We take advantage of that behaviour here, because in moving from IPv4 ICMP to IPv6 ICMPv6 - we need to add a pseudo-header to our ICMPv6 checksum - to do so we need to sum over the IPv6 addresses, the payload length and the protocol (IPPROTO_ICMPV6) - we also need to take into account the difference between the old ICMP type (ICMP_ECHO) and the ICMPv6 equivalent (ICMPV6_ECHO_REQUEST). We need a function to generate the sum of 16-bit values; so we use Clang's loop-unrolling feature to define sum16(): static __always_inline __u32 sum16(__u16 *addr, __u8 len) { __u32 sum = 0; int i; #pragma clang loop unroll(full) for (i = 0; i < len; i++) sum += *addr++; return sum; } ...and then use it to sum up the checksum value changes in adding the pseudo-header and modifying the ICMP type values: /* Fix up our checksum. Source/destination addresses have changed, and * so has ICMP type. Note that ICMPv6 also has a pseudo-header, so * we also need to add payload length and ICMPv6 protocol to newsum, * but do not add IPv4 equivalents to oldsum because ICMPv4 does not * use a pseudo-header in checksum calculation. Only thing that changes * for oldsum is ICMP type. */ oldsum = icmph->type; newsum = sum16((__u16 *)&ip6h.saddr, sizeof(ip6h.saddr) >> 1); newsum += sum16((__u16 *)&ip6h.daddr, sizeof(ip6h.daddr) >> 1); newsum += icmp6h.type + bpf_htons(payload_len) + bpf_htons(IPPROTO_ICMPV6); Later we will use these values to modify the checksum. Change from IPv4 -> IPv6 and store our new ethernet, IPv6 and ICMPv6 data We also update the checksum via bpf_l4_csum_replace(), specifying our oldsum and newsum values from above: /* Convert skb to IPv6 and adjust headroom to allow for space for * IPv6 header. */ ret = bpf_skb_change_proto(skb, bpf_htons(ETH_P_IPV6), 0); if (ret) { bpf_debug("bpf_skb_change_proto returned %d\n", ret); return TC_ACT_OK; } /* Store our copied ethernet header at new start of packet. */ ret = bpf_skb_store_bytes(skb, 0, &eth_copy, sizeof(eth_copy), 0); if (ret) { bpf_debug("bpf_skb_store_bytes returned %d\n", ret); return TC_ACT_SHOT; } /* Store our IPv6 header after the copied ether header */ ret = bpf_skb_store_bytes(skb, sizeof(eth), &ip6h, sizeof(ip6h), 0); if (ret) { bpf_debug("bpf_skb_store_bytes returned %d\n", ret); return TC_ACT_SHOT; } /* Only two bytes type/code change */ ret = bpf_skb_store_bytes(skb, sizeof(eth) + sizeof(ip6h), &icmp6h, 2, 0); if (ret) { bpf_debug("bpf_skb_store_bytes returned %d\n", ret); return TC_ACT_SHOT; } /* Lastly, recompute L4 checksum. */ ret = bpf_l4_csum_replace(skb, sizeof(eth) + sizeof(ip6h) + offsetof(struct icmphdr, checksum), oldsum, newsum, BPF_F_PSEUDO_HDR | sizeof(newsum)); if (ret) { bpf_debug("bpf_l4_csum_replace returned %d\n", ret); return TC_ACT_SHOT; } Note that in failure cases, we return TC_ACT_SHOT since we've modified the packet in bpf_skb_change_proto() such that it's not in a proper state if something goes wrong. Writing our egress filter This is mostly reversing the above, with the caveat that we need to calcuate the IPv4 checksum. Again see the referenced example for a fully-worked out version: https://github.com/alan-maguire/bpf-test/blob/master/bpf/test_bpf_helper_bpf_skb_change_proto_kern.c Conclusion BPF is an extremely flexible environment in which to do packet processing. We didn't touch on encapsulation/de-enapsulation here, but we can handle cases like that with the helper bpf_skb_adjust_room() to add/remove headroom in a packet. Hopefully the above demonstrates that we can do some interesting things in BPF! Be sure to visit the previous installments of this series on BPF, here, and stay tuned for our next blog posts! 1. BPF program types 2. BPF helper functions for those programs 3. BPF userspace communication 4. BPF program build environment 5. BPF bytecodes and verifier 6. BPF Packet Transformation

Notes on BPF (6) - BPF packet transformation using tc Oracle Linux kernel developer Alan Maguire presents this six-part series on BPF, wherein he presents an in depth look at the kernel's "Berkeley...

Linux Kernel Development

BPF In Depth: The BPF Bytecode and the BPF Verifier

Notes on BPF (5) - BPF bytecodes and the BPF verifier Oracle Linux kernel developer Alan Maguire presents this six-part series on BPF, wherein he presents an in depth look at the kernel's "Berkeley Packet Filter" -- a useful and extensible kernel function for much more than packet filtering. Previously, we've described what sorts of BPF programs can be used; the BPF helper functions those programs can call the ways BPF programs can communicate with userpace how to set up a BPF build environment. Now we've got one more topic to cover before we're ready to start writing BPF programs. How does BPF ensure that programs are safe? When working with BPF, the first wall you are likely to hit - after compiling your program and trying to load it - is a BPF verifier complaint such as this one I came across recently when loading a BPF-based tc classifier: from 1545 to 1615: R0=inv0 R6=inv2 R7=ctx(id=0,off=0,imm=0) R8=inv(id=0,umin_value=28,umax_value=1048,var_off=(0x0; 0x7fc)) R9=inv(id=0,umax_value=1020,var_off=(0x0; 0x3fc)) R10=fp0 fp-248=inv fp-232=map_value 1615: (61) r1 = *(u32 *)(r7 +76) 1616: (79) r2 = *(u64 *)(r10 -152) 1617: (0f) r1 += r2 math between pkt pointer and register with unbounded min value is not allowed To understand what all this means, we need to describe the BPF instruction set and what the verifier does. BPF instruction set As mentioned previously, the eBPF instruction set extended the set of bytecodes available, moved to 64-bit registers and in general created an instruction set that looks quite like x86_64.This isn't a coincidence; the aim was to support just-in-time (JIT) compilation as a speedier alternative to interpreting bytecodes. JIT compilation can be enabled via # sysctl net/core/bpf_jit_enable=1 The instruction set is documented at https://www.kernel.org/doc/Documentation/networking/filter.txt ...but be sure to look at the "BPF kernel internals" section and later, as above that is a description of "classic" BPF, the initial instruction set used for packet filtering. Classic BPF is translated in-kernel to support existing filtering mechanisms in wireshark, tcpdump etc. BPF Registers Register Function x86_64 equiv R0 return value from in-kernel function/exit value for prog rax R1 first arg to in-kernel function/scratch variable rdi R2 second arg to in-kernel function/scratch variable rsi R3 third arg to in-kernel function/scratch variable rdx R4 fourth arg to in-kernel function/scratch variable rcx R5 fifth arg to in-kernel function/scratch variable r8 R6 callee saved registers that in-kernel function preserves rbx R7 callee saved registers that in-kernel function preserves r13 R8 callee saved registers that in-kernel function preserves r14 R9 callee saved registers that in-kernel function preserves r15 R10 read-only frame pointer to access stack rbp As we can see, the maximum number of function register arguments BPF can use is 5 (x86_64 supports more). So just-in-time compilation can simply use the x86_64 equivalents when creating a mapping from BPF instructions to the x86_64 ISA. The x86_64 implementation of JIT compilation for 4.14 is found at https://github.com/oracle/linux-uek/blob/uek5/master/arch/x86/net/bpf_jit_comp.c bpf_int_jit_compile() makes multiple passes over the bytecodes, shrinking the image each time until no more shrinking occurs. do_jit() carries out the mapping, cycling through the instructions in a big switch() statement. There is no great need to describe the various supported BPF opcodes, as the output from the verifier is rendered in a quite human-readable form. Returning to our verifier complaint, it showed us a few snippets of our program: 1615: (61) r1 = *(u32 *)(r7 +76) 1616: (79) r2 = *(u64 *)(r10 -152) 1617: (0f) r1 += r2 From the above, we know that r1 and r2 are registers used to pass arguments to BPF functions. So on 1615, we are setting r1 to the u32 value pointed at by (r7 + 76). And on 1616, we are setting r2 to an offset from the frame pointer, i.e. a local variable on the stack. Finally we add both together. The last piece of the puzzle is to describe what the verifier context information "from 1545 to 1615: R0=inv0 R6=inv2 R7=ctx(id=0,off=0,imm=0) R8=inv(id=0,umin_value=28,umax_value=1048,var_off=(0x0; 0x7fc)) R9=inv(id=0,umax_value=1020,var_off=(0x0; 0x3fc)) R10=fp0 fp-248=inv fp-232=map_value" and error "math between pkt pointer and register with unbounded min value is not allowed" ...mean. To describe that, we need a bit more information on what the verifier does. The BPF verifier What does the verifier do? At a high-level, the BPF verifier ensures that BPF programs are safe - i.e. they will not crash the system, access invalid memory addresses, etc. The verifier code is pretty well commented; I'd recommend starting with https://github.com/oracle/linux-uek/blob/uek5/master/kernel/bpf/verifier.c : Here's what it says bpf_check() is a static code analyzer that walks eBPF program instruction by instruction and updates register/stack state. All paths of conditional branches are analyzed until 'bpf_exit' insn. The first pass is depth-first-search to check that the program is a DAG. It rejects the following programs: - larger than BPF_MAXINSNS insns - if loop is present (detected via back-edge) - unreachable insns exist (shouldn't be a forest. program = one function) - out of bounds or malformed jumps The second pass is all possible path descent from the 1st insn. Since it's analyzing all pathes through the program, the length of the analysis is limited to 64k insn, which may be hit even if total number of insn is less then 4K, but there are too many branches that change stack/regs. Number of 'branches to be analyzed' is limited to 1k DAG is a "directed acyclic graph" - we want to ensure our program has no backward branches. It is a directed graph because we always branch forwards. However, multiple places in the code can branch forward to the same destination, so it's not a tree. First pass verifier complaints So from the above, when we considering verifier errors, we have a few different classes of problem. In the first pass we can get verifier errors if we pass in programs that are too big (larger than BPF_MAXINSNS instructions). In Linux 4.14 BPF_MAXINSNS is set to 4096. programs with loops. Note that we can unroll simple loops in clang via "#pragma clang loop unroll(full)", but such loops should be simple as unrolling can fail. In particular loops which are bounded by a variable value (such as a value retrieved from a packet header) are risky. In addiition, adding complex predicates within a loop body can be problematic also. programs which call other functions (that are not BPF helpers or defined as __always_inline). unreachable instructions. Hard to see how this could happen in a restricted C environment, using raw BPF it could be a risk of course. Most of these problems are reasonably easy to eliminate. Second pass verifier complaints The second pass is trickier. The verifier will try all paths, tracking types of registers used as input to instructions, and updating resulting type via register state values. For example, PTR_TO_PACKET + SCALAR_VALUE → PTR_TO_PACKET. Certain operations are forbidden, e.g. adding two pointer values together gives an invalid value. The bpf verifier explores all paths of the program. For conditional jumps, a stack is used, so one path is explored while the instruction for the other path is pushed onto the stack. So we do a depth-first search of the instruction set. When we arrive at an instruction with a state equivalent to an earlier instruction state analysis (see the states_equal() function for how this is determined), we can prune the search. If we reach bpf_exit() without any complaints and a valid R0 value (the return value of the BPF program), a state is marked safe. We then backtrack to the first pushed instruction and repeat the cycle until the stack is empty and we're done. In my experience, the verifier can find quite subtle issues in code, and while you will spend a considerable amount of time tracking them down, it is usually a genuine bug! There are cases where compiler optimizations can confuse the verifier, so it's always best to run "llvm-objdump" (see below) to examine your program. So the "math between pkt pointer and register with unbounded min value is not allowed" error we saw above is essentially the verifier figuring out the set of actions in your program can lead to a situation where it is possible to run off the start of the packet by subtracting a value from the packet pointer. It is important to ensure values we add to packet pointers are unsigned, e.g. __u16. Also watch out for overflows when bit-shifting, adding, subtracting or multiplying. Ensure same for accesses on stack - for that we would get a similar error but it would mention the fp (frame pointer) instead. So what about "from 1545 to 1615: R0=inv0 R6=inv2 R7=ctx(id=0,off=0,imm=0) R8=inv(id=0,umin_value=28,umax_value=1048,var_off=(0x0; 0x7fc)) R9=inv(id=0,umax_value=1020,var_off=(0x0; 0x3fc)) R10=fp0 fp-248=inv fp-232=map_value" ? With the above info, we can see that this is the output of the verifier analysis, and it is telling us the state of the registers as per the verifier when processing a given chunk of instructions. Direct packet access, non-linear SKBs and verifier complaints For BPF programs which support sk_buff access, there are two modes with which we can retrieve/store information from/to a packet. The first is to use bpf_skb_load|store_bytes(). The advantage of this interface is that it works for linear and non-linear sk_buffs. Packet data is stored in the sk_buff structure, and it can hold that data in an initial "linear" section from skb→data to skb→data + skb→end (If this all sounds confusing, I'd recommend reading "How SKBs work" by David Miller). However, additional packet data can also be stored in fragments associated with the packet. These are referenced via the skb_shared_info structure. In BPF, we get a modified version of the skb, "struct __sk_buff" which contains pointers "data" and "data_end" which point at the start and end of the linear portion of the packet. We can directly read and write packet data using these pointers, but the BPF verifier requires that we first ensure that the packet data we wish to read/write is between "data" and "data_end". So a lot of BPF code which uses direct packet access looks like this: struct eth_hdr *eth; if (data + sizeof(*eth) > data_end) return TC_ACT_OK; eth = data; if (bpf_ntohs(eth→h_proto) == ETH_P_IP) { ... This leads naturally to a question - what if some of our packet data falls into the non-linear portion? I've encountered situations - particulary in VMs which use multiple layers of packet encapsulation - where some packet header data falls into the non-linear part of the skb. The best approach is to test for the condition where additional packet data is present and not in the linear portion. If that is the case, we can call bpf_skb_pull_data(skb, data_len) to ensure that data_len bytes will be in the linear portion.David Miller writes about direct packet access here. However, you may get a bunch more verifier warnings if you do this. Why? Well, many BPF functions such as bpf_skb_store_bytes(), bpf_skb_pull_data(), bpf_skb_adjust_room() etc will invalidate the data/data_end pointers and any checks done on them. So when using direct packet access, we need to retrieve data/data_end from the skb again and ensure that we verify the data we read/write falls between them. Examining your program with llvm-objdump If you get verifier errors, you will want to figure out where they occur in your restricted C code. We can dump our BPF program with annotated source if we run # llvm-objdump -S -no-show-raw-insn program.o Ensure the original program was compiled with -g to get source annotations. The result will look something like this: program.o: file format ELF64-BPF Disassembly of section program_handle_egress: program_handle_egress: ; { 0: r7 = r1 ; { 1: r6 = 0 ; void *data_end = (void *)(long)skb->data_end; 2: r2 = *(u32 *)(r7 + 80) ; void *data = (void *)(long)skb->data; 3: r1 = *(u32 *)(r7 + 76) ; if (data + sizeof(*eth) > data_end) 4: r3 = r1 5: r3 += 14 6: if r3 > r2 goto 570 You can see the source code interspersed with the BPF program, so it's a neat way to figure out what's happening around wherever the BPF is complaining about. Learning more about BPF Thanks for reading this installment of our series on BPF. We hope you found it educational and useful. Questions or comments? Use the comments field below! Stay tuned for the final installment in this series, BPF Packet Transformation. Be sure to visit the previous installments of this series on BPF, here, and stay tuned for our next blog posts! 1. BPF program types 2. BPF helper functions for those programs 3. BPF userspace communication 4. BPF program build environment 5. BPF bytecodes and verifier

Notes on BPF (5) - BPF bytecodes and the BPF verifier Oracle Linux kernel developer Alan Maguire presents this six-part series on BPF, wherein he presents an in depth look at the kernel's "Berkeley...

Linux Kernel Development

BPF In Depth: Building BPF Programs

Notes on BPF (4) - Setting up your environment to build BPF programs Oracle Linux kernel developer Alan Maguire presents this six-part series on BPF, wherein he presents an in depth look at the kernel's "Berkeley Packet Filter" -- a useful and extensible kernel function for much more than packet filtering. Here I'm going to describe how I set up my programming environment to build BPF programs. The advice is mostly based around using Linux UEK5, which is based on a 4.14 Linux kernel, so a bit of adjustment will be needed for other distros. Note - I'm not going to talk about BCC (the BPF Compiler Collection) here; for UEK5 that extra step involves building BCC from source. BCC isn't required to build BPF programs - clang/LLVM support a BPF target, so what we're aiming for here is to compile and use BPF programs. BCC however is a great resource for programs and provides python bindings and much more. Install dependencies First, verify the kernel you are working with has the following configuration options enabled: CONFIG_BPF=y CONFIG_BPF_SYSCALL=y CONFIG_NET_CLS_BPF=m CONFIG_NET_ACT_BPF=m CONFIG_BPF_JIT=y CONFIG_HAVE_BPF_JIT=y CONFIG_BPF_EVENTS=y All of these are enabled for our latest release based on Linux kernel 4.14, UEK5. To check these values for your running kernel: # grep BPF /boot/config-`uname -r` To build BPF programs, add LLVM and clang packages. clang is used to compile C programs to BPF bytecodes, and to ensure your version supports bpf, run "llc --version"; BPF should be listed as a registered target. To support BPF compilation, clang should be > version, 3.4.0 LLVM > version 3.7.1, according to http://prototype-kernel.readthedocs.io/en/latest/networking/XDP/end-user/build_environment.html . For UEK5, you can install them from the developer EPEL yum repository. Note; to use the latest LLVM/clang, "scl enable rh-dotnet20 bash" must be run. For UEK5 # yum install -y yum-utils # yum-config-manager --add-repo=http://yum.oracle.com/public-yum-ol7.repo # yum-config-manager --enable ol7_developer --enable ol7_developer_EPEL # yum install -y rh-dotnet20-clang rh-dotnet20-llvm # scl enable rh-dotnet20 bash # llc --version |grep bpf If you are using tc to build classifiers/actions via BPF, or want to use BPF to manage lightweight tunnel encapsulation for routes, you will need up-to-date versions of iproute and tc; i.e. 4.14-based versions, which support interaction with BPF programs. Follow those links for the UEK5 packages; for other distros you can also build these from source if needs be. # yum-config-manager --enable ol7_UEKR5 # yum install -y iproute iproute-tc Finally, to build BPF programs, you will need an up-to-date kernel development package to compile against, e.g. the UEK5 kernel-uek-devel or kernel-uek-headers package, since the headers shipped with UEK5 in the kernel-headers do not contain the 4.14 definitions for the BPF syscall etc. # yum install -y kernel-uek-devel Warning - installing kernel-uek-headers installs updated headers in /usr/include and can cause compatibility issues, so it is often best avoided in production environments. For an alternative approach to updating the header files in /usr/include using kernel-uek-devel, read on. The kernel-uek-devel package provides kernel headers and makefiles sufficient to build modules against the kernel package, and has nearly everything we need to build BPF programs; the below shows us how to use it and add the extra pieces. Building BPF programs outside the kernel tree This is mostly specific to my needs, but if you want to build BPF programs outside of the kernel tree while having them compatible with samples/bpf (so hopefully you can push them upstream later!), read on... Once the above dependencies have been installed, you are ready to start building BPF programs. However, it's important to ensure they are compiled against the right headers with all the latest BPF definitions. The approach I use is to point compilation at the kernel-uek-devel headers from /usr/src/kernels/, and we can pick up the up-to-date BPF headers, even if out-of-date headers are still installed in /usr/include (which they often are for backwards compatibility).The only complication with doing this is that the kernel-uek-devel package does not include a few files that are needed for compilation to succeed on the kernel side, and on the user-space side there are some convenience functions etc implemented which we would like to use in our programs. Here I'll describe how I've tackled this; again this may not make sense for your situation, but there may be aspects of the Makefiles that you can re-use. For BPF projects, I use a directory structure as follows: bpf/ include/ Makefile user/ I like to mirror the samples/bpf functionality - in particular I want to be able to use bpf.c/bpf_load.c as these simplify BPF interactions by providing code to scan a BPF program and load ELF sections as maps and programs. Loading BPF programs - when not using tc or iproute for configuring lightweight tunnels, which both have BPF integration - is a pain. Explaining each subdirectory: The "bpf" directory contains the code to be compiled into BPF programs "include" contains headers used to build - bpf_endian.h, bpf_ and linux/types.h (the latter is needed for u64, u32 definitions etc.), along with any common headers needed by the user and bpf subdirectories. "user" contains the BPF user-space code that load BPF program in the kernel and interacts with them, and uses copies of bpf_load.c/bpf_load.h, and bpf.c/bpf.h from the kernel tree to do this. This approach minimizes dependencies by providing local copies of some of the samples and tools .c and .h files ; we provide our own because kernel-uek-devel does not deliver these files. Then we point compilation at the kernel headers from /usr/src/kernels/, and we can pick up the up-to-date BPF headers even if out-of-date headers are installed in /usr/include. Thus we can build BPF programs without having to install up-to-date kernel-uek-headers which, when installed, could cause breakage elsewhere. Building BPF programs - kernel The "bpf" subdirectory is where BPF programs are built with LLVM/clang, and to simplify the build process I add local copies of bpf_helpers.h and bpf_endian.h to the include/ directory. Also added here is linux/types.h; a copy of tools/include/linux/types.h. Here is the full bpf/Makefile:I use; in this case we are building one object; socket_filter_kernel.o; more can be added to OBJS as needed. # SPDX-License-Identifier: GPL-2.0 # # Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 # as published by the Free Software Foundation. # # Build bpf code (kernel) out-of-tree by referencing local copies of # bpf .h files along with headers from kernel source tree. # Creates similar environment to that used by samples/bpf by adding # ../include/[bpf_endian.h,bpf_helpers.h,linux/types.h]. The latter is # used to get definitions for u64, u32 etc which are needed by other kernel # headers. # # - ../include/bpf_helpers.h is a copy of tools/testing/selftest/bpf/bpf_helpers.h # - ../include/bpf_endian.h is a copy of tools/testing/selftest/bpf/bpf_endian.h # - ../include/linux/types.h is a copy of tools/include/linux/types.h # # # Assumptions: # # - kernel-uek-devel package or equivalent has installed (partial) source # tree in /usr/src/kernels/`uname -r` # # - llc/clang are available and support "bpf" target; check with "llc --verison" # OBJS = socket_filter_kernel.o LLC ?= llc CLANG ?= clang INC_FLAGS = -nostdinc -isystem `$(CLANG) -print-file-name=include` EXTRA_CFLAGS ?= -O2 -emit-llvm # In case up-to-date headers are not installed locally in /usr/include, # use source build. linuxhdrs ?= /usr/src/kernels/`uname -r` LINUXINCLUDE = -I$(linuxhdrs)/arch/x86/include/uapi \ -I$(linuxhdrs)/arch/x86/include/generated/uapi \ -I$(linuxhdrs)/include/generated/uapi \ -I$(linuxhdrs)/include/uapi \ -I$(linuxhdrs)/include prefix ?= /usr/local INSTALLPATH = $(prefix)/lib/bpf install_PROGRAM = install install_DIR = install -dv all: $(OBJS) .PHONY: clean clean: rm -f $(OBJS) INC_FLAGS = -nostdinc -isystem `$(CLANG) -print-file-name=include` $(OBJS): %.o:%.c $(CLANG) $(INC_FLAGS) \ -D__KERNEL__ -D__ASM_SYSREG_H \ -Wno-unused-value -Wno-pointer-sign \ -Wno-compare-distinct-pointer-types \ -Wno-gnu-variable-sized-type-not-at-end \ -Wno-address-of-packed-member -Wno-tautological-compare \ -Wno-unknown-warning-option \ -I../include $(LINUXINCLUDE) \ $(EXTRA_CFLAGS) -c $< -o -| $(LLC) -march=bpf -filetype=obj -o $@ install: $(OBJS) $(install_DIR) -d $(INSTALLPATH) ; \ $(install_PROGRAM) $^ -t $(INSTALLPATH) uninstall: $(OBJS) rm -rf $(INSTALLPATH) Building BPF programs - user-space In the user/ subdirectory I add local copies of bpf.[ch], bpf_load.[ch], bpf_util.h and perf-sys.h. Here is the Makefile: # SPDX-License-Identifier: GPL-2.0 # # Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 # as published by the Free Software Foundation. # # Build bpf userspace code out-of-tree by referencing local copies of # bpf .c and .h files. # # - bpf.[ch] are copies of tools/lib/bpf/bpf.[ch] # - bpf_load.[ch] are copies are samples/bpf/bpf_load.[ch], with references # to #include the unneeded libbpf.h removed, replaced by references to bpf.h # - bpf_util.h is a copy of tools/testing/selftests/bpf/bpf_util.h # - perf-sys.h is a copy of tools/perf/perf-sys.h # COMMONOBJS = bpf.o bpf_load.o SOCKETFILTERPROG = socket_filter_user SOCKETFILTEROBJ = $(SOCKETFILTERPROG).o PROGS= $(SOCKETFILTERPROG) OBJS= $(COMMONOBJS) $(SOCKETFILTEROBJ) linuxhdrs ?= /usr/src/kernels/`uname -r` LINUXINCLUDE = -I$(linuxhdrs)/arch/x86/include/uapi \ -I$(linuxhdrs)/arch/x86/include/generated/uapi \ -I$(linuxhdrs)/include/generated/uapi \ -I$(linuxhdrs)/include/uapi \ -I$(linuxhdrs)/include prefix ?= /usr/local INSTALLPATH = $(prefix)/bin install_PROGRAM = install install_DIR = install -d LDLIBS = -lelf all: $(SOCKETFILTERPROG) .PHONY: clean clean: rm -f $(OBJS) $(PROGS) %.o: %.c $(CC) -g -Wno-unused-variable -I../include $(LINUXINCLUDE) -c -o $@ $< $(CFLAGS) $(PROGS): $(OBJS) $(CC) -g -o $@ $(@).o $(COMMONOBJS) $(CFLAGS) $(LDLIBS) install: $(PROGS) $(install_DIR) -d $(INSTALLPATH) ; \ $(install_PROGRAM) $^ -t $(INSTALLPATH) uninstall: $(PROGS) cd $(INSTALLPATH); rm -f $^ Example [Check back for a link to the example code.] Summary So we've seen how to install dependencies and how to set things up to build BPF programs. From here you might want to build some BPF programs of your own, or install BCC and play around with it. Anyway hopefully some of this has been useful. Learning more about BPF Thanks for reading this installment of our six part series on BPF. We hope you found it educational and useful. Questions or comments? Use the comments field below! Stay tuned for the next installment in this series, The BPF Bytecode Verifier. Be sure to visit the previous installments of this series on BPF, here, and stay tuned for our next blog posts! 1. BPF program types 2. BPF helper functions for those programs 3. BPF userspace communication 4. BPF program build environment

Notes on BPF (4) - Setting up your environment to build BPF programs Oracle Linux kernel developer Alan Maguire presents this six-part series on BPF, wherein he presents an in depth look at...

Linux

DTrace a Docker Container

Content for this blog entry was provided by Tomas Jedlicka and Eugene Loh Software containers have standardized how software is shipped, making it simpler to run an application with its expected dependencies on a wide variety of platforms. Here, we illustrate use of DTrace on a host system to observe activity within a Docker container, running on Oracle Linux using runC.  The central idea is that DTrace predicates can limit tracing on the host system to children of the Docker container process. Note that a runC-like container runtime shares a single kernel instance across all containers.  Some other container implementations would not work with this same DTrace script.  An example is Clear Containers, which creates lightweight virtual machines with their own kernel instances. System Setup 1.  Install DTrace:     # yum install dtrace-utils 2. Install and start Docker: Make sure that the ol7_addons repo is enabled, for example by making sure in /etc/yum.repos.d/public-yum-ol7.repo that [ol7_addons] has enabled=1.  Then:     # yum install docker-engine     [...]     Complete!     # systemctl start docker     # systemctl enable docker     Created symlink [...]     # systemctl status docker       docker.service - Docker Application Container Engine     [...]     Hint: Some lines were ellipsized, use -l to show in full. 3. Get an image: In this example, we use the Oracle Container Registry. You might first have to log into the website at https://container-registry.oracle.com to accept license agreements.      # docker login container-registry.oracle.com     Username: myname     Password:     Login Succeeded     # docker pull container-registry.oracle.com/os/oraclelinux     Using default tag: latest     [...]   Running in a container We run our container, using -it to allocate a pseudo-TTY, creating an interactive bash shell:    # docker run --rm -it container-registry.oracle.com/os/oraclelinux From the host system, we can get the container ID and thereby also the process ID (PID) of the bash shell running in the container.     # docker ps -q     4c80fafde812     # docker ps -q | xargs docker inspect --format "{{.State.Pid}}"     12345     # ps -p 12345 -o pid,ppid,command       PID  PPID COMMAND     12345 12340 /bin/bash     # ps -p 12340 -o pid,cmd       PID  CMD     12340  docker-containerd-shim -namespace moby -workdir /var/lib/docker/cont     # The bash command has pid 12345 and its parent is docker-containerd-shim, whose pid is 12340.   Using DTrace to observe activities in the container While we manually execute commands in the container's bash shell, we can observe those activities from the host system. The key is that DTrace allows predicates to filter tracing, and progenyof() allows us to trace only processes that are progeny (children, grandchildren, etc.) of the pid of interest. Consider the D script syscalls.d:     #!/usr/sbin/dtrace -s     syscall:::                              /* trace system calls */     / progenyof($1) /                       /* only progeny of specified pid */     {                                       /* count occurrences */       @[pid, execname, probefunc] = count();     } We can run this script on the host system, specifying the pid on the command line, to study system calls in the container, aggregating results that are reported when the script is terminated.     # ./syscalls.d 12345 As with many DTrace scripts, which are short though powerful, we could just run a one-liner.     # dtrace -n 'syscall::: /progenyof($1)/ {@[pid,execname,probefunc]=count()}' 12345 Here is the example output:     dtrace: script './syscalls.d' matched 638 probes     ^C         [...]         13012  ls       close              26         13012  ls       read               28         13012  ls       mprotect           36         13012  ls       newlstat           38         13012  ls       open               42         13012  bash     rt_sigaction       44         12345  bash     rt_sigaction       48         13012  ls       mmap               54         12345  bash     rt_sigprocmask     58         13012  ls       rt_sigaction       76 We can also look exclusively at read and write system calls.  Since argument 2 to these calls is the size of the I/O operation, we can form histograms of these sizes:     #!/usr/sbin/dtrace -s     syscall::read:entry,             /* trace read and write system calls */     syscall::write:entry     /progenyof($1) && arg2 > 1024/   /* only progeny of the specified pid */     {       @[probefunc] = quantize(arg2);     } This script filters not only on progeny of the specified pid, but also on large (> 1 Kbyte) transfers. While this script is running on the host, we execute the following copy in the container:     [root@4c80fafde812 /]# dd if=/dev/zero of=/dev/null bs=1M count=10     10+0 records in     10+0 records out     10485760 bytes (10 MB) copied, 0.00237154 s, 4.4 GB/s     [root@4c80fafde812 /]# Upon completion, we can terminate the script on the host:     # ./large_rw.d 12345     dtrace: script './large_rw.d' matched 2 probes     ^C       read                                                              value  ------------- Distribution ------------- count                   524288 |                                         0                      1048576 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10                     2097152 |                                         0               write                                                             value  ------------- Distribution ------------- count                   524288 |                                         0                      1048576 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10                     2097152 |                                         0      DTrace confirms that there were ten 1-Mbyte read and write transfers in the container. Conclusions DTrace is a simple-yet-powerful tracing tool.  Using a progenyof() predicate, it can focus exclusively on processes running within a Docker container.  Using D syntax, the tracing can be filtered, and data can be selected, aggregated, and otherwise manipulated. Docker documentation can be found at https://docs.docker.com The Oracle Container Registry is at https://container-registry.oracle.com An earlier post https://blogs.oracle.com/linux/dtrace-on-linux%3a-an-update discussed the port of DTrace to Linux.

Content for this blog entry was provided by Tomas Jedlicka and Eugene Loh Software containers have standardized how software is shipped, making it simpler to run an application with its...

Linux Kernel Development

BPF In Depth: Communicating with Userspace

Notes on BPF (3) - How BPF communicates with userspace - BPF maps, perf events, bpf_trace_printk Oracle Linux kernel developer Alan Maguire presents this six-part series on BPF, wherein he presents an in depth look at the kernel's "Berkeley Packet Filter" -- a useful and extensible kernel function for much more than packet filtering. We've seen how userspace sets up BPF programs, but once a program is attached and running, how do we gather information from it? There are three ways to do do this; using BPF maps, perf events and bpf_trace_printk. 1. BPF maps When should I use maps? BPF maps are useful for gathering information during BPF programs to share with other running BPF programs, or with userspace programs which can also see the map data. How can I use it? The set of map types is described in include/linux/uapi/bpf.h. In our UEK5 release - based on Linux 4.14 - the enumerated bpf_map_type looks like this: enum bpf_map_type { BPF_MAP_TYPE_UNSPEC, BPF_MAP_TYPE_HASH, BPF_MAP_TYPE_ARRAY, BPF_MAP_TYPE_PROG_ARRAY, BPF_MAP_TYPE_PERCPU_HASH, BPF_MAP_TYPE_PERCPU_ARRAY, BPF_MAP_TYPE_STACK_TRACE, BPF_MAP_TYPE_CGROUP_ARRAY, BPF_MAP_TYPE_LRU_HASH, BPF_MAP_TYPE_LRU_PERCPU_HASH, BPF_MAP_TYPE_LPM_TRIE, BPF_MAP_TYPE_ARRAY_OF_MAPS, BPF_MAP_TYPE_HASH_OF_MAPS, BPF_MAP_TYPE_DEVMAP, BPF_MAP_TYPE_SOCKMAP, }; Map actions We can create/update, delete and lookup map information, both in BPF programs and in user-space. User-space map interactions are done via the BPF syscall. Their function signatures are slightly different to those of their in-kernel BPF program equivalents. In tools/lib/bpf/bpf.c wrappers for these actions are present: int bpf_create_map(enum bpf_map_type map_type, int key_size, int value_size, int max_entries, __u32 map_flags); Description Create BPF map of specified type, with key/value size, of max_entries size with map flags specified. Returns File descriptor for map on success, negative error on failure. int bpf_create_map_node(enum bpf_map_type map_type, int key_size, int value_size, int max_entries, __u32 map_flags, int node); Description NUMA node-specific creation of BPF map. Returns File descriptor for map on success, negative error on failure. int bpf_create_map_in_map(enum bpf_map_type map_type, int key_size, int inner_map_fd, int max_entries, __u32 map_flags); Description Create map of specified type, passing in fd of inner map as representative Returns File descriptor for map on success, negative error on failure. int bpf_create_map_in_map_node(enum bpf_map_type map_type, int key_size, int inner_map_fd, int max_entries, __u32 map_flags, int node); Description NUMA node-specific creation of BPF map-in-map. Returns File descriptor for map on success, negative error on failure. int bpf_map_update_elem(int fd, const void *key, const void *value, __u64 flags); Description Update element with specified key with new value. A few flag values are supported. BPF_NOEXIST The entry for key must not exist in the map. BPF_EXIST The entry for key must already exist in the map. BPF_ANY No condition on the existence of the entry for key Flag value BPF_NOEXIST cannot be used for maps of types _ARRAY (all elements always exist), the helper would return an error. Returns 0 on success, negative errno on failure. int bpf_map_lookup_elem(int fd, const void *key, void *value); Description Look up value associated with specific key. If successful value will point to retrieved value. The value will be copied if necessary. Returns 0 on success, negative errno on failure. int bpf_map_delete_elem(int fd, const void *key); Description Delete element with specified key. Delete is not supported for array values. Returns 0 on success, negative errno on failure. int bpf_map_get_next_key(int fd, const void *key, void *next_key); Description On success, next_key will point at next key after specified *key. Returns 0 on success, negative error on failure or when no more keys are available. int bpf_map_get_next_id(__u32 start_id, __u32 *next_id); Description Get id of next map given start id. Returns 0 on success, negative error on failure or when no more ids are available. Defining a map in a BPF program Under samples/bpf, maps are defined in a kernel BPF program in a dedicated section as a type "struct bpf_map_def" which bpf_load.h defines as: struct bpf_map_def { unsigned int type; unsigned int key_size; unsigned int value_size; unsigned int max_entries; unsigned int map_flags; unsigned int inner_map_idx; unsigned int numa_node; }; An example of a definition using this structure is in samples/bpf/lathist_kern.c : struct bpf_map_def SEC("maps") my_map = { .type = BPF_MAP_TYPE_ARRAY, .key_size = sizeof(int), .value_size = sizeof(u64), .max_entries = MAX_CPU, }; Once bpf_load.c has scanned the ELF headers, it calls bpf_create_map_node() or bpf_create_map_in_map_node() which are implemented in tools/lib/bpf/bpf.c as wrappers to the BPF_MAP_CREATE command for the SYS_BPF syscall. Unless you are writing tc or lightweight tunnel BPF programs - which, since they implement BPF program loading themselves have their own map loading mechanisms - I'd recommend re-using this code rather than re-inventing the wheel. We can see it's generally a case of defining a map type, key/value sizes and a maximum number of entries. Programs which use "tc"/"ip route" for loading can utilize a data structure like this (from tc_l2_redirect_kern.c): #define PIN_GLOBAL_NS 2 struct bpf_elf_map { __u32 type; __u32 size_key; __u32 size_value; __u32 max_elem; __u32 flags; __u32 id; __u32 pinning; }; struct bpf_elf_map SEC("maps") tun_iface = { .type = BPF_MAP_TYPE_ARRAY, .size_key = sizeof(int), .size_value = sizeof(int), .pinning = PIN_GLOBAL_NS, .max_elem = 1, }; The bpf_elf_map data structure mirrors that defined in https://git.kernel.org/pub/scm/network/iproute2/iproute2.git/tree/include/bpf_elf.h?h=v4.14.1. Map pinning In that file, we can see that there are a few options for pinning a map: /* Object pinning settings */ #define PIN_NONE 0 #define PIN_OBJECT_NS 1 #define PIN_GLOBAL_NS 2 Pinning options determine how the map's file descriptor is exported via the filesystem. Outside of tc etc, we can pin a map fd to a file via libbpf's bpf_obj_pin(fd, path). Then other programs etc can retrieve the fd via bpf_obj_get(). The PIN_* options for iproute determine that path - for example maps which specify PIN_GLOBAL_NS are found in /sys/fs/bpf/tc/globals/ , so to retrieve the map fd one simply runs mapfd = bpf_obj_get(pinned_file); ...where "pinned_file" is the filename. From looking at the iproute code it appears a custom pinning path can also be used (by specifying a value > PIN_GLOBAL_NS). Map operation definitions Examining include/linux/bpf_types.h, we see that the various map types have associated sets of operations; for example: BPF_MAP_TYPE(BPF_MAP_TYPE_ARRAY, array_map_ops) BPF_MAP_TYPE(BPF_MAP_TYPE_PERCPU_ARRAY, percpu_array_map_ops) etc. The functions in the various ops variables define how the map allocates, frees, looks up data and much more. For example, as you might imagine the key for the lookup function for a BPF_MAP_TYPE_ARRAY is simply an index into the array. We see in kernel/bpf/arraymap.c: /* Called from syscall or from eBPF program */ static void *array_map_lookup_elem(struct bpf_map *map, void *key) { struct bpf_array *array = container_of(map, struct bpf_array, map); u32 index = *(u32 *)key; if (unlikely(index >= array->map.max_entries)) return NULL; return array->value + array->elem_size * (index & array->index_mask); } Array Maps Array maps are implemented in kernel/bpf/arraymap.c . All arrays restrict key size to 4 bytes (64 bits), and delete of values is not supported. BPF_MAP_TYPE_ARRAY: Simple array. Key is the array index, and elements cannot be deleted. BPF_MAP_TYPE_PERCPU_ARRAY: As above, but kernel programs implicitly write to a per-CPU allocated array which minimizes lock contention in BPF program context. When bpf_map_lookup_elem() is called, it retrieves NR_CPUS values. For example, if we are summing a stat across CPUs, we would do something like this: long values[nr_cpus]; ... ret = bpf_map_lookup_elem(map_fd, &next_key, values); if (ret) { perror("Error looking up stat"); continue; } for (i = 0; i < nr_cpus; i++) { sum += values[i]; } Use of a per-cpu data structure is to be preferred in codepaths which are frequently executed, since we will likely be aggregating the results across CPUs in user-space much less frequently than writing updates. BPF_MAP_TYPE_PROG_ARRAY: An array of BPF programs used as a jump table by bpf_tail_call(). See samples/bpf/sockex3_kern.c for an example. BPF_MAP_TYPE_PERF_EVENT_ARRAY: Array map which is used by the kernel in bpf_perf_event_output() to associate tracing output with a specific key. User-space programs associate fds with each key, and can poll() those fds to receive notification that data has been traced. See "Perf Events" section below for more details. BPF_MAP_TYPE_CGROUP_ARRAY: Array map used to store cgroup fds in user-space for later use in BPF programs which call bpf_skb_under_cgroup() to check if skb is associated with the cgroup in the cgroup array at the specified index. BPF_MAP_TYPE_ARRAY_OF_MAPS: Allows map-in-map definition where the values are the fds for the inner maps. Only two levels of map are supported, i.e. a map containing maps, not a map containing maps containing maps. BPF_MAP_TYPE_PROG_ARRAY does not support map-in-map functionality as it would make tail call verification harder. See https://www.mail-archive.com/netdev@vger.kernel.org/msg159387.html. for more. Hash Maps Hash maps are implemented in kernel/bpf/hashmap.c . Hash keys do not appear to be limited in size but must be > 0 for obvious reasons. Hash lookup matches the key to the appropriate value via a hashing function rather than an indexed lookup. Unlike the array case, values can be deleted from a hashmap. Hash maps are ideal when using a value such as an IP address for storage/retrieval. BPF_MAP_TYPE_HASH: simple hash map. Continually adding new elements can fail with E2BIG - if this is likely to be an issue, an LRU (least recently used) hash is recommended as it will recycle old entries out of buckets. BPF_MAP_TYPE_PERCPU_HASH: same as above, but kernel programs implicitly write to the CPU-specific hash. Retrieval works as described above. BPF_MAP_TYPE_LRU_HASH: Each hash maintains an LRU (least recently used) list for each bucket to inform delete when the hash bucket fills up. BPF_MAP_TYPE_HASH_OF_MAPS: Similar to ARRAY_OF_MAPS for for hash. See https://www.mail-archive.com/netdev@vger.kernel.org/msg159383.html for more. Other BPF_MAP_TYPE_STACK_TRACE: defined in kernel/bpf/stackmap.c. Kernel programs can store stacks via the bpf_get_stackid() helper. The idea is we store stacks based on an identifier which appears to correspond to a 32-bit hash of the instruction pointer addresses that comprise the stack for the current context. The common use case is to get stack id in kernel, and use it as key to update another map. So for example we could profile specific stack traces by counting their occurence, or associate a specific stack trace with the current pid as key. See samples/bpf/offwaketime_kern.c for an example of the latter. In user-space we can look up the symbols associated with the stackmap to unwind the stack (see samples/bpf/offwaketime_user.c). BPF_MAP_TYPE_LPM_TRIE: Map supporting efficient longest-prefix matching. Useful for storage/retrieval of IP routes for example. BPF_MAP_TYPE_SOCKMAP: sockmaps are used primarily for socket redirection, where sockets added to a socket map and referenced by a key which dictates redirection when bpf_sockmap_redirect() is called. BPF_MAP_TYPE_DEVMAP: does a similar job to sockmap, with netdevices for XDP and bpf_redirect(). 2. Perf Events As well as using maps, perf events can be used to gather information from BPF in user-space. Perf events allow BPF programs to store data in mmap()ed shared memory accessible by user-space programs. When should I use perf events? If you are gathering kernel data that is not amenable to map storage (such as variable-length chunks of memory) and does not need to be shared with other BPF programs. How can I use it? To see an example of how to set this up on the user-space side, see samples/bpf/trace_output_user.c and samples/bpf/trace_output_kern.c. User-space First we may need to up the rlimit (resource limit) of how much memory we can lock in RAM (RLIMIT_MEMLOCK) - we need to lock memory for maps. See setrlimit(2)/getrlimit(2) Create a map of type BPF_MAP_TYPE_PERF_EVENT_ARRAY. It can be keyed by CPU, and in that case the associated value for each key will be the fd associated with the perf event opened for that CPU. For each CPU, run perf_event_open() with a perf event with attributes of type PERF_TYPE_SOFTWARE, config PERF_COUNT_SW_BPF_OUTPUT, sample_type PERF_SAMPLE_RAW Update the BPF_MAP_TYPE_PERF_EVENT_ARRAY for the current CPU with the fd retrieved from the perf_event_open(). See test_bpf_perf_event() Run PERF_EVENT_IOC_ENABLE ioctl() for perf event fd mmap() read/write shared memory for the perf event fd. See perf_event_mmap(). This will store struct perf_event_mmap_page * containing the data. Add the perf event fd to the set of fds used in poll() so we can poll on events from the set of fds for each CPU to catch events. Now we are ready to run poll(), and handle events enqueued (see perf_event_read()) Kernel The program needs to define BPF_MAP_TYPE_PERF_EVENT_ARRAY to share with userspace. Program should run bpf_perf_event_output(ctx, &map, index, &data, sizeof(data)) . The index is the key of the BPF_MAP_TYPE_PERF_EVENT_ARRAY map, so if we're keying per-cpu it should be a CPU id. As we saw previously, bpf_perf_event_output() is supported for tc, XDP, lightweight tunnel, and kprobe, tracepoint and perf events program types. The context passed in is the relevant context for each of those program types. 3. bpf_trace_printk When should I use it? This option is more for debugging and should not be used in production BPF code. All BPF program types support bpf_trace_printk() and it is useful for debugging. How can I use it? Simply add a bpf_trace_printk() to your program. Messages can be retrieved via # cat /sys/kernel/debug/tracing/trace_pipe One gotcha here; you need to pre-define the format string otherwise the BPF verifier will complain. I usually use the following approach: define a general error message format, and have it add specifics with a particular string. For example: char errmsg[] = "egress: got unexpected error (%s) %x\n"; char store_fail[] = "could not store ipv6 hdr"; bpf_trace_printk(errmsg, sizeof(errmsg), store_fail, ret); One approach to consider is to have a config option BPF map shared between your program and user-space and if the config debug option is set, emit bpf_trace_printk()s. Summary We've seen that BPF maps are a good fit for communicating between different BPF programs and user-space. More customized data handling requires using perf events, and for debug logging bpf_trace_printk() is really useful. # Learning more about BPF Thanks for reading this installment of our six part series on BPF. We hope you found it educational and useful. Questions or comments? Use the comments field below! Stay tuned for the next installment in this series, Building BPF Programs. Previously: BPF program types BPF helper functions for those programs BPF userspace communication

Notes on BPF (3) - How BPF communicates with userspace - BPF maps, perf events, bpf_trace_printk Oracle Linux kernel developer Alan Maguire presents this six-part series on BPF, wherein he presents an...

Linux Kernel Development

Dealing with Realtime Processes in Linux User Namespaces

Linux kernel developer Prakash Sangappa works closely with the Oracle Database team to ensure that the database runs best on Oracle Linux. As the Oracle Database team brings new capabilities to a release, Prakash ensures that any necessary support is in Oracle Linux. This is always exciting when Prakash and the team are delivering new features to the Linux operating system. In this blog post, Prakash talks about the challenges of trying to run a process with real time priority in a user namespace. Realtime (RT) Processes Inside User Namespace User namespaces provide user id and group id isolation. With use of user namespaces, an unprivileged user can be mapped to the root user(uid 0) inside a user namespace. That unprivileged user gains full privileges and capabilities to perform operations within the user namespace. This includes the ability to create other namespaces which is useful. Oracle Multitenant, the architecture for the next-generation database cloud, will be using namespaces to create and isolate database instances on a system. Though uid 0 in user namespace gets all capabilities, some of the capabilities are ineffective (e.g. CAP_SYS_NICE, CAP_IPC_LOCK, CAP_SYS_TIME) as they would allow modifying global resources, like setting RT priority, locking memory and setting system time respectively. This restriction is problematic for Oracle Multitenant, especially the capability CAP_SYS_NICE, which is required to set RT priority on some of its critical processes. Below is a brief description of the architecture and the use case. Oracle Multitenant Architecture Oracle Multitenant helps simplify consolidation, provisioning, management and more. This new architecture allows a container database (CDB) to hold zero or more customer databases called pluggable databases (PDBs). It helps to manage many databases as one. An existing database can be adaptoped without change as a pluggable database. You can find more information about Oracle Multitenant here. For security and isolation, Oracle Multitenant will use Linux namespaces including user namespaces to sandbox PDBs which are nested inside the CDB. Namespaces will also be used to isolate many CDBs on the system. Within a CDB, there are critical processes like the log writer that has to run at a higher priority. It needs to be scheduled on a CPU immediately as soon as it is ready to run. For this reason, these critical processes are assigned RT priority. However, with use of user namespaces, setting RT priority from within the user namespace is not possible. One way to handle this limitation would be to use a helper process running as root in the init namespace. This process could set RT priority for the critical processes within the user namespace on request. However, this is not convenient. Possible Approaches As RT priority is not a resource that can be namespace'd by introducing a new namespace type, the following approaches could address the requirement. The main concern would be runaway processes running with RT priority that render the system unresponsive. Allow root user(uid 0) from init namespace, when mapped inside a user namespace to set RT priority. If a user namespace were to be tagged or indicated in some way, permit CAP_SYS_NICE capability to take affect and be able to set RT priority. With use of cgroups bandwidth control, allow root user(uid 0) inside user namespace to be able to set RT priority. Add a scheduler option to run processes at a fixed high priority above all user priority, like a new scheduling class. This topic was presented at Linux Plumbers Conference 2018. From the discussion that ensued after the presentation, opinion seems to be leaning towards some solution based on cgroups bandwidth control to allow setting RT priority inside user namespace. We plan to further explore this approach.

Linux kernel developer Prakash Sangappa works closely with the Oracle Database team to ensure that the database runs best on Oracle Linux. As the Oracle Database team brings new capabilities to a...

Events

Join us at Oracle OpenWorld Europe

2019 is off to a great start with Oracle OpenWorld going global. The first stop is London, January 16-17. Join us for insights from leading experts, informative sessions and demos, and opportunities to connect with your peers. Discover how to stay competitive with today’s transformational technology. Highlights to include on your schedule: Featured Speakers Oracle OpenWorld Europe’s featured speakers are the innovators, disruptors and thought leaders of tomorrow. From a former number two at United Nations, digital anthropologist, a pioneer in the mobile and data analytics industries, authors, futurists and many more. Oracle Linux and Virtualization Sessions Wednesday, January 16 9:45 a.m.–10:20 a.m. | Arena 4 (Level 3) - ExCeL London [SES1793] Build a Cloud Native Environment with Oracle Linux Speaker: Karen Sigman, Vice President, Product and Partner Marketing, Product Channel Marketing Oracle Linux offers an open, integrated operating environment with application development tools, management tools, containers, and orchestration capabilities, which enable DevOps teams to efficiently build reliable, secure cloud native applications. In this session learn how Oracle Linux can help you enhance productivity. 10:30 a.m.–11:15 a.m. | Arena 8 (Level 3) - ExCeL London [SES1792] How Oracle Linux Cloud Native Environment and VirtualBox can Make a Developer's Life Easier Speaker: Simon Coter, Product Management Director, Oracle Linux and Virtualization, Oracle Tried, tested, and tuned for enterprise workloads, Oracle Linux is used by developers worldwide. Oracle Linux yum server and Oracle Container Registry provide easy access to Linux developer preview software, including the latest Oracle Linux Cloud Native Environment software. Thousands of EPEL packages also have been built and signed by Oracle for security and compliance. Software Collections include recent versions of Python, PHP, Node.js, nginx, and more. In addition, Oracle Cloud developer tools such as Terraform, SDKs, and CLI are available for an improved experience. Use Oracle VM VirtualBox to run Oracle Linux with cloud native software on your desktop and easily deploy to the cloud. Come to this session to learn more about speeding up your development and move to the cloud.   The Exchange: a Showcase for Attendees to Connect, Discover and Learn Oracle Linux and Oracle Virtualization experts will be at The Exchange to answer your questions, update you on the latest product enhancements, and demo the latest software releases. Let us know about your experience -- #OOWLON #OracleLinux @OracleLinux Enjoy the conference!

2019 is off to a great start with Oracle OpenWorld going global. The first stop is London, January 16-17. Join us for insights from leading experts, informative sessions and demos, and...

Linux Kernel Development

BPF In Depth: BPF Helper Functions

Notes on BPF (2) - BPF helper functions Oracle Linux kernel developer Alan Maguire presents this six-part series on BPF, wherein he presents an in depth look at the kernel's "Berkeley Packet Filter" -- a useful and extensible kernel function for much more than packet filtering. Now that we have a list of program types, what can we do within programs we attach? A good place to start with writing BPF programs is to see what helper functions the various BPF program types have available to them. To see some of this, check out https://github.com/oracle/linux-uek/blob/uek5/master/net/core/filter.c It contains a set of data structures used by the bpf verifier - struct bpf_verifier_ops. Here's an example for sk_filter programs: const struct bpf_verifier_ops sk_filter_prog_ops = { .get_func_proto = sk_filter_func_proto, .is_valid_access = sk_filter_is_valid_access, .convert_ctx_access = bpf_convert_ctx_access, }; "get_func_proto" defines the set of functions supported by the program. The "is_valid_access" function checks if the read/write access for the memory offset is valid. The "convert_ctx_access" function converts accesses from bpf-specific (e.g. struct __sk_buff) structures into real access to the "struct sk_buff". This is all so the verifier can ensure your BPF program is calling valid functions and accessing valid data for the given instrumentation point. Back to the function prototypes. Firstly, there are a base set of functions available, the prototypes of which are returned by bpf_base_func_proto(). The following descriptions come from Quentin's more recent bpf-next changes which document helpers in include/uapi/linux/bpf.h - https://lwn.net/Articles/751527/ - here we're simply organizing them by the program type(s) that can use them. void *bpf_map_lookup_elem(struct bpf_map *map, const void *key) Description Perform a lookup in map for an entry associated to key. Return Map value associated to key, or NULL if no entry was found. int bpf_map_update_elem(struct bpf_map *map, const void *key, const void *value, u64 flags) Description Add or update the value of the entry associated to key in map with value. flags is one of: BPF_NOEXIST The entry for key must not exist in the map. BPF_EXIST The entry for key must already exist in the map. BPF_ANY No condition on the existence of the entry for key. Flag value BPF_NOEXIST cannot be used for maps of types BPF_MAP_TYPE_ARRAY or BPF_MAP_TYPE_PERCPU_ARRAY (all elements always exist), the helper would return an error. Return 0 on success, or a negative error in case of failure. int bpf_map_delete_elem(struct bpf_map *map, const void *key) Description Delete entry with key from map. Return 0 on success, or a negative error in case of failure. u32 bpf_get_prandom_u32(void) Description Get a pseudo-random number. From a security point of view, this helper uses its own pseudo-random internal state, and cannot be used to infer the seed of other random functions in the kernel. However, it is essential to note that the generator used by the helper is not cryptographically secure. Return A random 32-bit unsigned value. u32 bpf_get_smp_processor_id(void) Description Get the SMP (symmetric multiprocessing) processor id. Note that all programs run with preemption disabled, which means that the SMP processor id is stable during all the execution of the program. Return The SMP id of the processor running the program. int bpf_get_numa_node_id(void) Description Return the id of the current NUMA node. Return The id of current NUMA node. int bpf_tail_call(void *ctx, struct bpf_map *prog_array_map, u32 index) Description This special helper is used to trigger a "tail call", or in other words, to jump into another eBPF program. The same stack frame is used (but values on stack and in registers for the caller are not accessible to the callee). This mechanism allows for program chaining, either for raising the maximum number of available eBPF instructions, or to execute given programs in conditional blocks. For security reasons, there is an upper limit to the number of successive tail calls that can be performed. Upon call of this helper, the program attempts to jump into a program referenced at index in prog_array_map, a special map of type BPF_MAP_TYPE_PROG_ARRAY, and passes ctx, a pointer to the context. If the call succeeds, the kernel immediately runs the first instruction of the new program. This is not a function call, and it never returns to the previous program. If the call fails, then the helper has no effect, and the caller continues to run its subsequent instructions. A call can fail if the destination program for the jump does not exist (i.e. index is higher than the number of entries in prog_array_map), or if the maximum number of tail calls has been reached for this chain of programs. This limit is defined in the kernel by the macro MAX_TAIL_CALL_CNT (not accessible to user space), which is currently set to 32. Return 0 on success, or a negative error in case of failure. u64 bpf_ktime_get_ns(void) Description Return the time elapsed since system boot, in nanoseconds. Return Current *ktime*. int bpf_trace_printk(const char *fmt, u32 fmt_size, ...) Description This helper is a "printk()-like" facility for debugging. It prints a message defined by format fmt (of size fmt_size) to file /sys/kernel/debug/tracing/trace from DebugFS, if available. It can take up to three additional u64 arguments (as in eBPF helpers, the total number of arguments is limited to five). Each time the helper is called, it appends a line to the trace. The format of the trace is customizable, and the exact output one will get depends on the options set in /sys/kernel/debug/tracing/trace_options (see also the README file under the same directory). However, it usually defaults to something like: telnet-470 [001] .N.. 419421.045894: 0x00000001: <formatted msg> In the above: * ``telnet`` is the name of the current task. * ``470`` is the PID of the current task. * ``001`` is the CPU number on which the task is running * In ``.N..``, each character refers to a set of options (whether irqs are enabled, scheduling options, whether hard/softirqs are running, level of preempt_disabled respectively). N means that TIF_NEED_RESCHED and PREEMPT_NEED_RESCHED are set. * ``419421.045894`` is a timestamp. * ``0x00000001`` is a fake value used by BPF for the instruction pointer register. * ``<formatted msg>`` is the message formatted with fmt The conversion specifiers supported by fmt are similar, but more limited than for printk(). They are %d, %i, %u, %x, %ld, %li, %lu, %lx, %lld, %lli, %llu, %llx, %p, %s. No modifier (size of field, padding with zeroes, etc.) is available, and the helper will return -EINVAL (but print nothing) if it encounters an unknown specifier. Also, note that bpf_trace_printk() is slow, and should only be used for debugging purposes. For this reason, a notice block (spanning several lines) is printed to kernel logs and states that the helper should not be used "for production use" the first time this helper is used (or more precisely when the trace_printk () buffers are allocated). For passing values to user space, perf events should be preferred. Return The number of bytes written to the buffer, or a negative error in case of failure. Additionally, for each class of instrumentation target we see a _func_proto() function which enumerates the additional functions available, along with the base set. We will describe these functions, grouped by the program types that support them. 1. socket-related program functions Socket-related BPF programs support the generic set of operations above, and a set of program-specific functions. 1.1 sk_filter programs int bpf_skb_load_bytes(const struct sk_buff *skb, u32 offset, void *to, u32 len) Description This helper was provided as an easy way to load data from a packet. It can be used to load len bytes from offset from the packet associated to skb, into the buffer pointed to by to. Since Linux 4.7, usage of this helper has mostly been replaced by "direct packet access", enabling packet data to be manipulated with skb->data and skb→data_end pointing respectively to the first byte of packet data and to the byte after the last byte of packet data. However, it remains useful if one wishes to read large quantities of data at once from a packet into the eBPF stack. Return 0 on success, or a negative error in case of failure. u64 bpf_get_socket_cookie(struct sk_buff *skb) Description If the struct sk_buff * pointed by skb has a known socket, retrieve the cookie (generated by the kernel) of this socket. If no cookie has been set yet, generate a new cookie. Once generated, the socket cookie remains stable for the life of the socket. This helper can be useful for monitoring per socket networking traffic statistics as it provides a unique socket identifier per namespace. Return A 8-byte long non-decreasing number on success, or 0 if the socket field is missing inside skb. u32 bpf_get_socket_uid(struct sk_buff *skb) Return The owner UID of the socket associated to skb. If the socket is NULL, or if it is not a full socket (i.e. if it is a time-wait or a request socket instead), overflowuid value is returned (note that overflowuid might also be the actual UID value for the socket). 1.2 sock_ops programs int bpf_setsockopt(struct bpf_sock_ops *bpf_socket, int level, int optname, char *optval, int optlen) Description Emulate a call to setsockopt() on the socket associated to bpf_socket, which must be a full socket. The level at which the option resides and the name optname of the option must be specified, see setsockopt(2) for more information. The option value of length optlen is pointed by optval. This helper actually implements a subset of setsockopt(). It supports the following levels: * SOL_SOCKET, which supports the following optnames: SO_RCVBUF, SO_SNDBUF, SO_MAX_PACING_RATE, SO_PRIORITY, SO_RCVLOWAT, SO_MARK. * IPPROTO_TCP, which supports the following optnames: TCP_CONGESTION, TCP_BPF_IW, TCP_BPF_SNDCWND_CLAMP. * IPPROTO_IP, which supports optname IP_TOS. * IPPROTO_IPV6, which supports optname IPV6_TCLASS. Return 0 on success, or a negative error in case of failure. int bpf_sock_map_update(struct bpf_sock_ops *skops, struct bpf_map *map, void *key, u64 flags) Description Add an entry to, or update a map referencing sockets. The skops is used as a new value for the entry associated to key. flags is one of: BPF_NOEXIST The entry for key must not exist in the map. BPF_EXIST The entry for key must already exist in the map. BPF_ANY No condition on the existence of the entry for key. If the map has eBPF programs (parser and verdict), those will be inherited by the socket being added. If the socket is already attached to eBPF programs, this results in an error. Return 0 on success, or a negative error in case of failure. 1.3 sk_skb programs In addition to the base set, the following are supported: int bpf_skb_store_bytes(struct sk_buff *skb, u32 offset, const void *from, u32 len, u64 flags) Description Store len bytes from address from into the packet associated to skb, at offset. flags are a combination of BPF_F_RECOMPUTE_CSUM (automatically recompute the checksum for the packet after storing the bytes) and BPF_F_INVALIDATE_HASH (set skb->hash, skb->swhash and skb->l4hash to 0). A call to this helper is susceptible to change the underlaying packet buffer. Therefore, at load time, all checks on pointers previously done by the verifier are invalidated and must be performed again, if the helper is used in combination with direct packet access. Return 0 on success, or a negative error in case of failure. int bpf_skb_pull_data(struct sk_buff *skb, u32 len) Description Pull in non-linear data in case the skb is non-linear and not all of len are part of the linear section. Make len bytes from skb readable and writable. If a zero value is passed for len, then the whole length of the skb is pulled. This helper is only needed for reading and writing with direct packet access. For direct packet access, testing that offsets to access are within packet boundaries (test on skb->data_end) is susceptible to fail if offsets are invalid, or if the requested data is in non-linear parts of the skb. On failure the program can just bail out, or in the case of a non-linear buffer, use a helper to make the data available. The bpf_skb_load_bytes() helper is a first solution to access the data. Another one consists in using bpf_skb_pull_data to pull in once the non-linear parts, then retesting and eventually access the data. At the same time, this also makes sure the skb is uncloned, which is a necessary condition for direct write. As this needs to be an invariant for the write part only, the verifier detects writes and adds a prologue that is calling bpf_skb_pull_data() to effectively unclone the skb from the very beginning in case it is indeed cloned. A call to this helper is susceptible to change the underlaying packet buffer. Therefore, at load time, all checks on pointers previously done by the verifier are invalidated and must be performed again, if the helper is used in combination with direct packet access. Return 0 on success, or a negative error in case of failure. int bpf_skb_change_tail(struct sk_buff *skb, u32 len, u64 flags) Description Resize (trim or grow) the packet associated to skb to the new len. The flags are reserved for future usage, and must be left at zero. The basic idea is that the helper performs the needed work to change the size of the packet, then the eBPF program rewrites the rest via helpers like bpf_skb_store_bytes(), bpf_l3_csum_replace(), and others. This helper is a slow path utility intended for replies with control messages. And because it is targeted for slow path, the helper itself can afford to be slow: it implicitly linearizes, unclones and drops offloads from the skb.. A call to this helper is susceptible to change the underlaying packet buffer. Therefore, at load time, all checks on pointers previously done by the verifier are invalidated and must be performed again, if the helper is used in combination with direct packet access. Return 0 on success, or a negative error in case of failure. int bpf_skb_change_head(struct sk_buff *skb, u32 len, u64 flags) Description Grows headroom of packet associated to skb and adjusts the offset of the MAC header accordingly, adding len bytes of space. It automatically extends and reallocates memory as required. This helper can be used on a layer 3 *skb* to push a MAC header for redirection into a layer 2 device. All values for flags are reserved for future usage, and must be left at zero. A call to this helper is susceptible to change the underlaying packet buffer. Therefore, at load time, all checks on pointers previously done by the verifier are invalidated and must be performed again, if the helper is used in combination with direct packet access. Return 0 on success, or a negative error in case of failure. int bpf_sk_redirect_map(struct bpf_map *map, u32 key, u64 flags) Description Redirect the packet to the socket referenced by map (of type BPF_MAP_TYPE_SOCKMAP) at index key. Both ingress and egress interfaces can be used for redirection. The BPF_F_INGRESS value in flags is used to make the distinction (ingress path is selected if the flag is present, egress path otherwise). This is the only flag supported for now. Return SK_PASS on success, or SK_DROP on error. bpf_skb_load_bytes, bpf_get_socket_cookie, bpf_get_socket_uid are also supported. See above for descriptions of these. 2. tc (traffic control) subsystem program functions In addition to the base function set, the following are supported: s64 bpf_csum_diff(__be32 *from, u32 from_size, __be32 *to, u32 to_size, __wsum seed) Description Compute a checksum difference, from the raw buffer pointed by from, of length from_size (that must be a multiple of 4), towards the raw buffer pointed by to, of size to_size (same remark). An optional seed can be added to the value (this can be cascaded, the seed may come from a previous call to the helper). This is flexible enough to be used in several ways: * With from_size == 0, to_size > 0 and seed set to checksum, it can be used when pushing new data. * With from_size > 0, *to_size* == 0 and seed set to checksum, it can be used when removing data from a packet. * With from_size > 0, to_size > 0 and seed set to 0, it can be used to compute a diff. Note that from_size and to_size do not need to be equal. This helper can be used in combination with bpf_l3_csum_replace() and bpf_l4_csum_replace(), to which one can feed in the difference computed with bpf_csum_diff(). Return The checksum result, or a negative error code in case of failure. s64 bpf_csum_update(struct sk_buff *skb, __wsum csum) Description Add the checksum csum into skb->csum in case the driver has supplied a checksum for the entire packet into that field. Return an error otherwise. This helper is intended to be used in combination with bpf_csum_diff(), in particular when the checksum needs to be updated after data has been written into the packet through direct packet access. Return The checksum on success, or a negative error code in case of failure. int bpf_l3_csum_replace(struct sk_buff *skb, u32 offset, u64 from, u64 to, u64 size) Description Recompute the layer 3 (e.g. IP) checksum for the packet associated to skb. Computation is incremental, so the helper must know the former value of the header field that was modified (from), the new value of this field (to), and the number of bytes (2 or 4) for this field, stored in size. Alternatively, it is possible to store the difference between the previous and the new values of the header field in to, by setting from and size to 0. For both methods, offset indicates the location of the IP checksum within the packet. This helper works in combination with bpf_csum_diff(), which does not update the checksum in-place, but offers more flexibility and can handle sizes larger than 2 or 4 for the checksum to update. A call to this helper is susceptible to change the underlaying packet buffer. Therefore, at load time, all checks on pointers previously done by the verifier are invalidated and must be performed again, if the helper is used in combination with direct packet access. Return 0 on success, or a negative error in case of failure. int bpf_l4_csum_replace(struct sk_buff *skb, u32 offset, u64 from, u64 to, u64 flags) Description Recompute the layer 4 (e.g. TCP, UDP or ICMP) checksum for the packet associated to skb. Computation is incremental, so the helper must know the former value of the header field that was modified (from), the new value of this field (to), and the number of bytes (2 or 4) for this field, stored on the lowest four bits of flags. Alternatively, it is possible to store the difference between the previous and the new values of the header field in to, by setting from and the four lowest bits of flags to 0. For both methods, offset indicates the location of the IP checksum within the packet. In addition to the size of the field, flags can be added (bitwise OR) actual flags. With BPF_F_MARK_MANGLED_0, a null checksum is left untouched (unless BPF_F_MARK_ENFORCE is added as well), and for updates resulting in a null checksum the value is set to CSUM_MANGLED_0 instead. Flag BPF_F_PSEUDO_HDR indicates the checksum is to be computed against a pseudo-header. This helper works in combination with bpf_csum_diff(), which does not update the checksum in-place, but offers more flexibility and can handle sizes larger than 2 or 4 for the checksum to update. A call to this helper is susceptible to change the underlaying packet buffer. Therefore, at load time, all checks on pointers previously done by the verifier are invalidated and must be performed again, if the helper is used in combination with direct packet access. Return 0 on success, or a negative error in case of failure. int bpf_clone_redirect(struct sk_buff *skb, u32 ifindex, u64 flags) Description Clone and redirect the packet associated to skb to another net device of index ifindex. Both ingress and egress interfaces can be used for redirection. The BPF_F_INGRESS value in flags is used to make the distinction (ingress path is selected if the flag is present, egress path otherwise). This is the only flag supported for now. In comparison with bpf_redirect() helper, bpf_clone_redirect() has the associated cost of duplicating the packet buffer, but this can be executed out of the eBPF program. Conversely, bpf_redirect() is more efficient, but it is handled through an action code where the redirection happens only after the eBPF program has returned. A call to this helper is susceptible to change the underlaying packet buffer. Therefore, at load time, all checks on pointers previously done by the verifier are invalidated and must be performed again, if the helper is used in combination with direct packet access. Return 0 on success, or a negative error in case of failure. int bpf_redirect(u32 ifindex, u64 flags) Description Redirect the packet to another net device of index ifindex. This helper is somewhat similar to bpf_clone_redirect(), except that the packet is not cloned, which provides increased performance. Except for XDP, both ingress and egress interfaces can be used for redirection. The BPF_F_INGRESS value in flags is used to make the distinction (ingress path is selected if the flag is present, egress path otherwise). Currently, XDP only supports redirection to the egress interface, and accepts no flag at all. The same effect can be attained with the more generic bpf_redirect_map(), which requires specific maps to be used but offers better performance. Return For XDP, the helper returns XDP_REDIRECT on success or XDP_ABORTED on error. For other program types, the values are TC_ACT_REDIRECT on success or TC_ACT_SHOT on error. u32 bpf_get_cgroup_classid(struct sk_buff *skb) Description Retrieve the classid for the current task, i.e. for the net_cls cgroup to which skb belongs. This helper can be used on TC egress path, but not on ingress. The net_cls cgroup provides an interface to tag network packets based on a user-provided identifier for all traffic coming from the tasks belonging to the related cgroup. See also the related kernel documentation, available from the Linux sources in file Documentation/cgroup-v1/net_cls.txt. The Linux kernel has two versions for cgroups: there are cgroups v1 and cgroups v2. Both are available to users, who can use a mixture of them, but note that the net_cls cgroup is for cgroup v1 only. This makes it incompatible with BPF programs run on cgroups, which is a cgroup-v2-only feature (a socket can only hold data for one version of cgroups at a time). This helper is only available is the kernel was compiled with the CONFIG_CGROUP_NET_CLASSID configuration option set to "y" or to "m". Return The classid, or 0 for the default unconfigured classid. int bpf_skb_under_cgroup(struct sk_buff *skb, struct bpf_map *map, u32 index) Description Check whether skb is a descendant of the cgroup2 held by map of type BPF_MAP_TYPE_CGROUP_ARRAY, at index. Return The return value depends on the result of the test, and can be: * 0, if the skb failed the cgroup2 descendant test. * 1, if the skb succeeded the cgroup2 descendant test. * A negative error code, if an error occurred. int bpf_skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci) Description Push a vlan_tci (VLAN tag control information) of protocol vlan_proto to the packet associated to skb, then update the checksum. Note that if vlan_proto is different from ETH_P_8021Q and ETH_P_8021AD, it is considered to be ETH_P_8021Q. A call to this helper is susceptible to change the underlaying packet buffer. Therefore, at load time, all checks on pointers previously done by the verifier are invalidated and must be performed again, if the helper is used in combination with direct packet access. Return 0 on success, or a negative error in case of failure. int bpf_skb_vlan_pop(struct sk_buff *skb) Description Pop a VLAN header from the packet associated to skb. A call to this helper is susceptible to change the underlaying packet buffer. Therefore, at load time, all checks on pointers previously done by the verifier are invalidated and must be performed again, if the helper is used in combination with direct packet access. Return 0 on success, or a negative error in case of failure. int bpf_skb_change_proto(struct sk_buff *skb, __be16 proto, u64 flags) Description Change the protocol of the skb to proto. Currently supported are transition from IPv4 to IPv6, and from IPv6 to IPv4. The helper takes care of the groundwork for the transition, including resizing the socket buffer. The eBPF program is expected to fill the new headers, if any, via skb_store_bytes() and to recompute the checksums with bpf_l3_csum_replace() and bpf_l4_csum_replace(). The main case for this helper is to perform NAT64 operations out of an eBPF program. Internally, the GSO type is marked as dodgy so that headers are checked and segments are recalculated by the GSO/GRO engine. The size for GSO target is adapted as well. All values for *flags* are reserved for future usage, and must be left at zero. A call to this helper is susceptible to change the underlaying packet buffer. Therefore, at load time, all checks on pointers previously done by the verifier are invalidated and must be performed again, if the helper is used in combination with direct packet access. Return 0 on success, or a negative error in case of failure. int bpf_skb_change_type(struct sk_buff *skb, u32 type) Description Change the packet type for the packet associated to skb. This comes down to setting skb->pkt_type to type, except the eBPF program does not have a write access to skb→pkt_type beside this helper. Using a helper here allows for graceful handling of errors. The major use case is to change incoming skbs to PACKET_HOST in a programmatic way instead of having to recirculate via redirect(..., BPF_F_INGRESS), for example. Note that type only allows certain values. At this time, they are: PACKET_HOST Packet is for us. PACKET_BROADCAST Send packet to all. PACKET_MULTICAST Send packet to group. PACKET_OTHERHOST Send packet to someone else. Return 0 on success, or a negative error in case of failure. int bpf_skb_get_tunnel_key(struct sk_buff *skb, struct bpf_tunnel_key *key, u32 size, u64 flags) Description Get tunnel metadata. This helper takes a pointer key to an empty struct bpf_tunnel_key of size, that will be filled with tunnel metadata for the packet associated to skb. The flags can be set to BPF_F_TUNINFO_IPV6, which indicates that the tunnel is based on IPv6 protocol instead of IPv4. The struct bpf_tunnel_key is an object that generalizes the principal parameters used by various tunneling protocols into a single struct. This way, it can be used to easily make a decision based on the contents of the encapsulation header, "summarized" in this struct. In particular, it holds the IP address of the remote end (IPv4 or IPv6, depending on the case) in key->remote_ipv4 or key->remote_ipv6. Also, this struct exposes the key->tunnel_id, which is generally mapped to a VNI (Virtual Network Identifier), making it programmable together with the bpf_skb_set_tunnel_key() helper. Let's imagine that the following code is part of a program attached to the TC ingress interface, on one end of a GRE tunnel, and is supposed to filter out all messages coming from remote ends with IPv4 address other than 10.0.0.1: int ret; struct bpf_tunnel_key key = {}; ret = bpf_skb_get_tunnel_key(skb, &key, sizeof(key), 0); if (ret < 0) return TC_ACT_SHOT; // drop packet if (key.remote_ipv4 != 0x0a000001) return TC_ACT_SHOT; // drop packet return TC_ACT_OK; // accept packet This interface can also be used with all encapsulation devices that can operate in "collect metadata" mode: instead of having one network device per specific configuration, the "collect metadata" mode only requires a single device where the configuration can be extracted from this helper. This can be used together with various tunnels such as VXLan, Geneve, GRE or IP in IP (IPIP). Return 0 on success, or a negative error in case of failure. int bpf_skb_set_tunnel_key(struct sk_buff *skb, struct bpf_tunnel_key *key, u32 size, u64 flags) Description Populate tunnel metadata for packet associated to skb. The tunnel metadata is set to the contents of key, of size. The flags can be set to a combination of the following values: BPF_F_TUNINFO_IPV6 Indicate that the tunnel is based on IPv6 protocol instead of IPv4. BPF_F_ZERO_CSUM_TX For IPv4 packets, add a flag to tunnel metadata indicating that checksum computation should be skipped and checksum set to zeroes. BPF_F_DONT_FRAGMENT Add a flag to tunnel metadata indicating that the packet should not be fragmented. BPF_F_SEQ_NUMBER Add a flag to tunnel metadata indicating that a sequence number should be added to tunnel header before sending the packet. This flag was added for GRE encapsulation, but might be used with other protocols as well in the future. Here is a typical usage on the transmit path: struct bpf_tunnel_key key; populate key ... bpf_skb_set_tunnel_key(skb, &key, sizeof(key), 0); bpf_clone_redirect(skb, vxlan_dev_ifindex, 0); See also the description of the bpf_skb_get_tunnel_key() helper for additional information. Return 0 on success, or a negative error in case of failure. int bpf_skb_get_tunnel_opt(struct sk_buff *skb, u8 *opt, u32 size) Description Retrieve tunnel options metadata for the packet associated to skb, and store the raw tunnel option data to the buffer opt of size. This helper can be used with encapsulation devices that can operate in "collect metadata" mode (please refer to the related note in the description of bpf_skb_get_tunnel_key() for more details). A particular example where this can be used is in combination with the Geneve encapsulation protocol, where it allows for pushing (with bpf_skb_get_tunnel_opt() helper) and retrieving arbitrary TLVs (Type-Length-Value headers) from the eBPF program. This allows for full customization of these headers. Return The size of the option data retrieved. int bpf_skb_set_tunnel_opt(struct sk_buff *skb, u8 *opt, u32 size) Description Set tunnel options metadata for the packet associated to skb to the option data contained in the raw buffer opt of size. See also the description of the bpf_skb_get_tunnel_opt() helper for additional information. Return 0 on success, or a negative error in case of failure. u32 bpf_get_route_realm(struct sk_buff *skb) Description Retrieve the realm or the route, that is to say the tclassid field of the destination for the skb. The indentifier retrieved is a user-provided tag, similar to the one used with the net_cls cgroup (see description for bpf_get_cgroup_classid() helper), but here this tag is held by a route (a destination entry), not by a task. Retrieving this identifier works with the clsact TC egress hook (see also tc-bpf(8)), or alternatively on conventional classful egress qdiscs, but not on TC ingress path. In case of clsact TC egress hook, this has the advantage that, internally, the destination entry has not been dropped yet in the transmit path. Therefore, the destination entry does not need to be artificially held via netif_keep_dst() for a classful qdisc until the skb is freed. This helper is available only if the kernel was compiled with CONFIG_IP_ROUTE_CLASSID configuration option. Return The realm of the route for the packet associated to skb, or 0 if none was found. u32 bpf_get_hash_recalc(struct sk_buff *skb) Description Retrieve the hash of the packet, skb->hash. If it is not set, in particular if the hash was cleared due to mangling, recompute this hash. Later accesses to the hash can be done directly with skb->hash. Calling bpf_set_hash_invalid(), changing a packet prototype with bpf_skb_change_proto(), or calling bpf_skb_store_bytes() with the BPF_F_INVALIDATE_HASH are actions susceptible to clear the hash and to trigger a new computation for the next call to bpf_get_hash_recalc(). Return The 32-bit hash. void bpf_set_hash_invalid(struct sk_buff *skb) Description Invalidate the current skb->hash. It can be used after mangling on headers through direct packet access, in order to indicate that the hash is outdated and to trigger a recalculation the next time the kernel tries to access this hash or when the **bpf_get_hash_recalc**\ () helper is called. u32 bpf_set_hash(struct sk_buff *skb, u32 hash) Description Set the full hash for skb (set the field skb→hash) to value hash. Return 0 int bpf_perf_event_output(struct pt_reg *ctx, struct bpf_map *map, u64 flags, void *data, u64 size) Description Write raw data blob into a special BPF perf event held by map of type BPF_MAP_TYPE_PERF_EVENT_ARRAY. This perf event must have the following attributes: PERF_SAMPLE_RAW as sample_type, PERF_TYPE_SOFTWARE as type, and PERF_COUNT_SW_BPF_OUTPUT as config. The flags are used to indicate the index in map for which the value must be put, masked with BPF_F_INDEX_MASK. Alternatively, flags can be set to BPF_F_CURRENT_CPU to indicate that the index of the current CPU core should be used. The value to write, of size, is passed through eBPF stack and pointed by data. The context of the program ctx needs also be passed to the helper. On user space, a program willing to read the values needs to call perf_event_open() on the perf event (either for one or for all CPUs) and to store the file descriptor into the map. This must be done before the eBPF program can send data into it. An example is available in file samples/bpf/trace_output_user.c in the Linux kernel source tree (the eBPF program counterpart is in samples/bpf/trace_output_kern.c). bpf_perf_event_output() achieves better performance than bpf_trace_printk() for sharing data with user space, and is much better suitable for streaming data from eBPF programs. Note that this helper is not restricted to tracing use cases and can be used with programs attached to TC or XDP as well, where it allows for passing data to user space listeners. Data can be: * Only custom structs, * Only the packet payload, or * A combination of both. Return 0 on success, or a negative error in case of failure. bpf_skb_store_bytes,: bpf_skb_load_bytes, bpf_skb_pull_data, bpf_skb_change_tail, bpf_get_socket_cookie, bpf_get_socket_uid:are also supported. See above for descriptions. 3. xdp : Xpress Data Path program functions In addition to the base set, bpf_perf_event_output, bpf_get_smp_processor_id, bpf_redirect and bpf_redirect_map are all supported as described above. int bpf_xdp_adjust_head(struct xdp_buff *xdp_md, int delta) Description Adjust (move) xdp_md->data by delta bytes. Note that it is possible to use a negative value for delta. This helper can be used to prepare the packet for pushing or popping headers. A call to this helper is susceptible to change the underlaying packet buffer. Therefore, at load time, all checks on pointers previously done by the verifier are invalidated and must be performed again, if the helper is used in combination with direct packet access. Return 0 on success, or a negative error in case of failure. 4. kprobes, tracepoints and perf events program functions To figure out which helper functions are supported for these program types, we need to look at kernel/trace/bpf_trace.c. Here a common set of verifier ops valid for all these program types is defined in tracing_func_proto(). This is the equivalent of the base function prototype in filter.c. The base set of functions for for BPF filters are supported here too; bpf_map_lookup_elem, bpf_map_update_elem, bpf_map_delete_elem, bpf_ktime_get_ns, bpf_tail_call, bpf_trace_printk, bpf_get_smp_processor_id, bpf_get_numa_node_id. bpf_get_prandom_u32. In addition bpf_perf_event_read, bpf_perf_event_output are all valid, and defined above. Other functions (not previously described) are : int bpf_get_stackid(struct pt_reg *ctx, struct bpf_map *map, u64 flags) Description Walk a user or a kernel stack and return its id. To achieve this, the helper needs ctx, which is a pointer to the context on which the tracing program is executed, and a pointer to a map of type BPF_MAP_TYPE_STACK_TRACE. The last argument, flags, holds the number of stack frames to skip (from 0 to 255), masked with BPF_F_SKIP_FIELD_MASK. The next bits can be used to set a combination of the following flags: BPF_F_USER_STACK Collect a user space stack instead of a kernel stack. BPF_F_FAST_STACK_CMP Compare stacks by hash only. BPF_F_REUSE_STACKID If two different stacks hash into the same *stackid*, discard the old one. The stack id retrieved is a 32 bit long integer handle which can be further combined with other data (including other stack ids) and used as a key into maps. This can be useful for generating a variety of graphs (such as flame graphs or off-cpu graphs). For walking a stack, this helper is an improvement over bpf_probe_read(), which can be used with unrolled loops but is not efficient and consumes a lot of eBPF instructions. Instead, bpf_get_stackid() can collect up to PERF_MAX_STACK_DEPTH both kernel and user frames. Note that this limit can be controlled with the sysctl program, and that it should be manually increased in order to profile long user stacks (such as stacks for Java programs). To do so, use: # sysctl kernel.perf_event_max_stack=<new value> Return The positive or null stack id on success, or a negative error in case of failure. int bpf_probe_read(void *dst, u32 size, const void *src) Description For tracing programs, safely attempt to read size bytes from address src and store the data in dst. Return 0 on success, or a negative error in case of failure. u64 bpf_get_current_pid_tgid(void) Return A 64-bit integer containing the current tgid and pid, and created as such: current_task->tgid << 32 | current_task->pid. u64 bpf_get_current_uid_gid(void) Return A 64-bit integer containing the current GID and UID, and created as such: current_gid << 32 | current_uid. int bpf_get_current_comm(char *buf, u32 size_of_buf) Description Copy the comm attribute of the current task into buf of size_of_buf. The comm attribute contains the name of the executable (excluding the path) for the current task. The size_of_buf must be strictly positive. On success, the helper makes sure that the buf is NUL-terminated. On failure, it is filled with zeroes. Return 0 on success, or a negative error in case of failure. u64 bpf_get_current_task(void) Return A pointer to the current task struct. int bpf_probe_write_user(void *dst, const void *src, u32 len) Description Attempt in a safe way to write len bytes from the buffer src to dst in memory. It only works for threads that are in user context, and dst must be a valid user space address. This helper should not be used to implement any kind of security mechanism because of TOC-TOU attacks, but rather to debug, divert, and manipulate execution of semi-cooperative processes. Keep in mind that this feature is meant for experiments, and it has a risk of crashing the system and running programs. Therefore, when an eBPF program using this helper is attached, a warning including PID and process name is printed to kernel logs. Return 0 on success, or a negative error in case of failure. int bpf_current_task_under_cgroup(struct bpf_map *map, u32 index) Description Check whether the probe is being run is the context of a given subset of the cgroup2 hierarchy. The cgroup2 to test is held by map of type BPF_MAP_TYPE_CGROUP_ARRAY, at index. Return The return value depends on the result of the test, and can be: * 0, if the skb task belongs to the cgroup2. * 1, if the skb task does not belong to the cgroup2. * A negative error code, if an error occurred. . int bpf_probe_read_str(void *dst, int size, const void *unsafe_ptr) Description Copy a NUL terminated string from an unsafe address unsafe_ptr to dst. The size should include the terminating NUL byte. In case the string length is smaller than size, the target is not padded with further NUL bytes. If the string length is larger than *size*, just *size*-1 bytes are copied and the last byte is set to NUL. On success, the length of the copied string is returned. This makes this helper useful in tracing programs for reading strings, and more importantly to get its length at runtime. See the following snippet: SEC("kprobe/sys_open") void bpf_sys_open(struct pt_regs *ctx) { char buf[PATHLEN]; // PATHLEN is defined to 256 int res = bpf_probe_read_str(buf, sizeof(buf), ctx->di); // Consume buf, for example push it to // userspace via bpf_perf_event_output(); we // can use res (the string length) as event // size, after checking its boundaries. } In comparison, using bpf_probe_read() helper here instead to read the string would require to estimate the length at compile time, and would often result in copying more memory than necessary. Another useful use case is when parsing individual process arguments or individual environment variables navigating current->mm->arg_start and current->mm->env_start using this helper and the return value, one can quickly iterate at the right offset of the memory area. Return On success, the strictly positive length of the string, including the trailing NUL character. On error, a negative value. 5. cgroups-related program functions For cgroup sock/skb programs, in addition to the base set, one additional function is supported: bpf_get_current_uid_gid:is supported, and defined above. 6. Lightweight tunnel program functions For Lightweight tunnel in/out/xmit, in addition to the base set of functions, bpf_skb_load_bytes:, bpf_skb_pull_data, bpf_csum_diff, bpf_get_cgroup_classid: bpf_perf_event_output, bpf_get_route_realm, bpf_get_hash_recalc, bpf_perf_event_output, bpf_get_smp_processor_id, bpf_skb_under_cgroup: are all supported, and defined above. For Lightweight tunnel xmit only: bpf_skb_get_tunnel_key, bpf_skb_set_tunnel_key, bpf_skb_get_tunnel_opt, bpf_skb_set_tunnel_opt, bpf_redirect, bpf_clone_redirect, bpf_skb_change_tail, bpf_skb_change_head, bpf_skb_store_bytes, bpf_csum_update, bpf_l3_csum_replace, bpf_l4_csum_replace, bpf_set_hash_invalid are all supported and defined above. Summary We've described the various program types, and the functions they support. However before we can start writing BPF programs, we need to talk about BPF maps - a key data structure for sharing information that can be used (among other things) to share information between BPF programs and user-space. Learning more about BPF Thanks for reading this installment of our series on BPF. We hope you found it educational and useful. Questions or comments? Use the comments field below! Stay tuned for the next installment in this series, BPF and Userspace. Previously: BPF program types

Notes on BPF (2) - BPF helper functions Oracle Linux kernel developer Alan Maguire presents this six-part series on BPF, wherein he presents an in depth look at the kernel's "Berkeley Packet Filter" --...

Linux Kernel Development

BPF: A Tour of Program Types

Notes on BPF (1) - A Tour of Progam Types Oracle Linux kernel developer Alan Maguire presents this six-part series on BPF, wherein he presents an in depth look at the kernel's "Berkeley Packet Filter" -- a useful and extensible kernel function for much more than packet filtering. If you follow Linux kernel development discussions and blog posts, you've probably heard BPF mentioned a lot lately. It's being used for high-performance load-balancing, DDoS mitigation and firewalling, safe instrumentation of kernel and user-space code and much more! BPF does this by supporting a safe flexible programming environment in many different contexts; networking datapaths, kernel probes, perf events and more. Safety is key - in most environments, adding a kernel module introduces significant risk. BPF programs however are verified at program load time to ensure no out-of-bounds accesses occur etc. In addition BPF supports just-in-time compilation of its bytecode to the native instructions set, so BPF programs are also fast. If you're interested in topics like fast packet processing and observability, learning BPF should definitely be on your to-do list. Here we try to give a guide to BPF, covering a range of topics which will hopefully help developers trying to get to grips with writing BPF programs. This guide is based on Linux 4.14 (which is the kernel for Oracle Linux UEK5), so do bear that in mind as there have been a bunch of changes in BPF since, and some package names etc may differ for other distributions. Because BPF in Linux is such a fast-moving target, I'm going to try and point you at relevant places in the kernel codebase that may help you get a sense for what the technology can do. The samples/bpf directory is a great place to look to see what others have done, but here we'll also dig into the implementation as reference, as it may give you some ideas how to create new BPF programs. The aim here isn't to give a deep dive into BPF internals, but rather to give a few pointers to areas in the code which reveal BPF functionality. The source tree I'm using for reference is our UEK5 release, based on Linux 4.14.35. See https://github.com/oracle/linux-uek/tree/uek5/master . Most of the functionality described can be found in any recent kernel. The bpf-next tree (where BPF kernel development happens) can be found at https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git An important caveat; again, what is below describes the state as per the 4.14 kernel. A lot has changed since; but hopefully with the pointers into the code, you'll be better equipped to figure out what some of these changes are! The aim here is to be able to get to the point of working on interesting problems with BPF. However before we get there, let's look at the various pieces and how they fit together. The first question to ask is what can we do with BPF? What kinds of programs can we write? To get a sense for this, let's examine the enumerated type definition from include/uapi/linux/bpf.h https://github.com/oracle/linux-uek/blob/uek5/master/include/uapi/linux/bpf.h#L117 enum bpf_prog_type { BPF_PROG_TYPE_UNSPEC, BPF_PROG_TYPE_SOCKET_FILTER, BPF_PROG_TYPE_KPROBE, BPF_PROG_TYPE_SCHED_CLS, BPF_PROG_TYPE_SCHED_ACT, BPF_PROG_TYPE_TRACEPOINT, BPF_PROG_TYPE_XDP, BPF_PROG_TYPE_PERF_EVENT, BPF_PROG_TYPE_CGROUP_SKB, BPF_PROG_TYPE_CGROUP_SOCK, BPF_PROG_TYPE_LWT_IN, BPF_PROG_TYPE_LWT_OUT, BPF_PROG_TYPE_LWT_XMIT, BPF_PROG_TYPE_SOCK_OPS, BPF_PROG_TYPE_SK_SKB, }; What are all of these program types? To understand this, we will ask the same set of questions for each program type: what do I do with this program type? how do I attach my BPF program for this program type? what context is provided to my program? By this we mean what argument(s) and data are provided for us to work with. when does the attached program get run? It's important to understand this, as it gives a sense of where for example in the network stack a filter is applied. We won't worry about how you create the programs for now; that side of things is relatively uniform across the various program types. 1. socket-related program types - SOCKET_FILTER, SK_SKB, SOCK_OPS First, let's consider the socket-related program types which allow us to filter, redirect socket data and monitor socket events. The filtering use case relates to the origins of BPF. When observing the network we want to see only a portion of network traffic, for example all traffic from a troublesome system. Filters are used to describe the traffic we want to see, and ideally we want it to be fast, and we want to give users an open-ended set of filtering options. But we have a problem; we want to throw away unneeded data as early as possible, and to do that we need to filter in kernel context. Consider the alternative to an in-kernel solution - incurring the cost of copying packets to user-space and filtering there. That would be very expensive, especially if we only want to see a portion of the network traffic and throw away the rest.To achieve this, a safe mini-language was invented to translate high-level filters into a bytecode program that the kernel can use (termed classic BPF, cBPF). The aim of the language was to support a flexible set of filtering options while being fast and safe. Filters written in this assembly-like language could be pushed by userspace programs such as tcpdump to accomplish filtering in-kernel. See https://www.tcpdump.org/papers/bpf-usenix93.pdf ...for the classic paper describing this work. Modern eBPF took these concepts, expanded the register and instruction set, added data structures called maps, hugely expanded the kinds of events we can attach to, and much more! For socket filtering, the common case is to attach to a raw socket (SOCK_RAW), and in fact you'll notice most programs that do socket filtering have a line like this: s = socket(AF_PACKET,SOCK_RAW,htons(ETH_P_ALL)); Creating such a socket, we specify the domain (AF_PACKET), socket type (SOCK_RAW) and protocol (all packet types). In the Linux kernel, receive of raw packets is implemented by the raw_local_deliver() function. It is called called by ip_local_deliver_finish(), just prior to calling the relevant IP protocol's handler, which is where the packet is passed to TCP, UDP, ICMP etc. So at this point the traffic has not been associated with a specific socket; that happens later, when the IP stack figures out the mapping from packet to layer 4 protocol, and then to the relevant socket (if any). You can see the cBPF bytecodes generated by tcpdump by using the -d option. Here I want to run tcpdump on the wlp4s0 interface, filtering TCP traffic only: # tcpdump -i wlp4s0 -d 'tcp' (000) ldh [12] (001) jeq #0x86dd jt 2 jf 7 (002) ldb [20] (003) jeq #0x6 jt 10 jf 4 (004) jeq #0x2c jt 5 jf 11 (005) ldb [54] (006) jeq #0x6 jt 10 jf 11 (007) jeq #0x800 jt 8 jf 11 (008) ldb [23] (009) jeq #0x6 jt 10 jf 11 (010) ret #65535 (011) ret #0 Without much deep knowledge we can get a feel for what's happening here. On line 000 we load the offset of the ether header + 12 ; the ether header protocol type. On line 001, we jump to 002 if it matches ETH_P_IPv6 (0x86dd) (jt 2), otherwise jump to 007 if false (jf 7) (handle the IPv4 case). Let's look at the IPv6 case first. On line 003 we jump to 010 - success - if the IPv6 protocol (offset + 20) is 6 (IPPROTO_TCP) - line 010 returns 65535 which is the max length so we're accepting the packet. Otherwise we jump to 004. Here we compare to 0x2c, which indicates there's an IPv6 fragment header. If that's true we check if the fragment header (offset 54) specifies a next protocol value as IPPROTO_TCP, and if so we jump to 10 (success) or 11 (failure). Returning 0 means dropping the packet for filtering purposes. Handling IPv4 is simpler; on 007 (arrived at via "jf" on 001), we check for ETH_P_IPV4 and, if found, we verify that the IPPROTO is TCP. And we're done! Remember though this is cBPF; eBPF has an extended instruction/op set similar to x86_64 and additional registers. One other thing to note - socket filtering is distinct from netfilter-based filtering. Netfilter defines its own set of hooks with NF_HOOK() definitions, which netfilter-based technologies such as ipfilter can use to filter traffic also. You might think - couldn't we use eBPF there too? And you'd be right! bpfilter is replacing ipfilter in more recent Linux kernels. So with all that in mind, let's return to examining the socket-related program types. 1.1 BPF_PROG_TYPE_SOCKET_FILTER What do I do with it? The filtering actions include dropping packets (if the program returns 0) or trimming packets (if the program returns a length less than the original). See sk_filter_trim_cap() and its call to bpf_prog_run_save_cb(). Note that we're not trimming or dropping the original packet which would still reach the intended socket intact; we're working with a copy of the packet metadata which raw sockets can access for observability. In addition to filtering packet flow to our socket, we can also do things that have side-effects; for example collecting statistics in BPF maps. How do I attach my program? BPF programs can be attached to sockets via the SO_ATTACH_BPF setsockopt(), which passes in a file descriptor to the program. What context is provided? A pointer to the struct __sk_buff containing packet metadata/data. This structure is defined in include/linux/bpf.h, and includes key fields from the real sk_buff. The bpf verifier converts access to valid __sk_buff fields into offsets into the "real" sk_buff, see https://lwn.net/Articles/636647/ for more details. When does it run? Socket filters run for receive in sock_queue_rcv_skb() which is called by various protocols (TCP, UDP, ICMP, raw sockets etc) and can be used to filter inbound traffic. To give a sense for what programs look like, here we will create a filter that trims packet data we filter on the basis of protocol type; for IPv4 TCP, let's grab the IPv4 + TCP header only, while for UDP, we'll take the IPv4 and UDP header only. We won't deal with IPv4 options as it's a simple example, so in all other cases we return 0 (drop packet). #include <linux/bpf.h> #include <linux/in.h> #include <linux/types.h> #include <linux/string.h> #include <linux/if_ether.h> #include <linux/if_packet.h> #include <linux/ip.h> #include <linux/tcp.h> #include <linux/udp.h> #include "bpf_helpers.h" #ifndef offsetof #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) #endif /* * We are only interested in TCP/UDP headers, so drop every other protocol * and trim packets after the TCP/UDP header by returning length of * ether header + IPv4 header + TCP/UDP header. */ SEC("socket") int bpf_prog1(struct __sk_buff *skb) { int proto = load_byte(skb, ETH_HLEN + offsetof(struct iphdr, protocol)); int size = ETH_HLEN + sizeof(struct iphdr); switch (proto) { case IPPROTO_TCP: size += sizeof(struct tcphdr); break; case IPPROTO_UDP: size += sizeof(struct udphdr); break; default: size = 0; break; } return size; } char _license[] SEC("license") = "GPL"; This program can be compiled into BPF bytecodes using LLVM/clang by specifying arch of "bpf" , and once that is done it will contain an object with an ELF section called "socket". That is our program. The next step is to use the BPF system call to assign a file descriptor to the program, then attach it to the socket. In samples/bpf , you can see that bpf_load.c scans the ELF sections, and sections with name prefixed by "socket" are recognized as BPF_PROG_TYPE_SOCKET_FILTER programs. If you're adding a sample I'd recommend including bpf_load.h so you can just call load_bpf_file() on your BPF program. For example, in samples/bpf/sockex1_user.c we take the filename of our program (sockex1) and load sockex1_kern.o ; the associated BPF program. Then we open a raw socket to loopback (lo) and attach the program there: snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]); if (load_bpf_file(filename)) { printf("%s", bpf_log_buf); return 1; } sock = open_raw_sock("lo"); assert(setsockopt(sock, SOL_SOCKET, SO_ATTACH_BPF, prog_fd, sizeof(prog_fd[0])) == 0); 1.2 BPF_PROG_TYPE_SOCK_OPS What do I do with it? Attach a BPF program to catch socket operations such as connection establishment, retransmit timeout etc. Once caught options can also be set via bpf_setsockopt(), so for example on passive establishment of a connection from a system not on the same subnet, we could lower the MTU so we won't have to worry about intermediate routers fragmenting packets. Programs can return success (0) or failure (a negative value) and a reply value can be set to indicate the desired value for a socket option (e.g. TCP rwnd). See https://lwn.net/Articles/727189/ for full details, and look for tcp_call_bpf()s inline definition in include/net/tcp.h to see how TCP handles execution of such programs. Another use case is for sockmap updates in combination with BPF_PROG_TYPE_SK_SKB programs; the bpf_sock_ops struct pointer passed into the BPF_PROG_TYPE_SOCK_OPS program is used to update the sockmap, associating a value for that socket. Later sk_skb programs can reference those values to specify which socket to redirect to via bpf_sk_redirect_map() calls. If this sounds confusing, I'd recommend taking a look at the code in samples/sockmap. How do I attach my program? It is attached to a cgroup file descriptor using BPF_CGROUP_SOCK_OPS attach type. What context is provided? Argument provided is the context, struct bpf_sock_ops *.. Op field specifies the operatiion, BPF_SOCK_OPS_RWND_INIT, BPF_SOCK_OPS_TCP_CONNECT_CB etc. The reply field can be used to indicate to the caller a new value for a parameter set. /* User bpf_sock_ops struct to access socket values and specify request ops * and their replies. * Some of this fields are in network (bigendian) byte order and may need * to be converted before use (bpf_ntohl() defined in samples/bpf/bpf_endian.h). * New fields can only be added at the end of this structure */ struct bpf_sock_ops { __u32 op; union { __u32 reply; __u32 replylong[4]; }; __u32 family; __u32 remote_ip4; /* Stored in network byte order */ __u32 local_ip4; /* Stored in network byte order */ __u32 remote_ip6[4]; /* Stored in network byte order */ __u32 local_ip6[4]; /* Stored in network byte order */ __u32 remote_port; /* Stored in network byte order */ __u32 local_port; /* stored in host byte order */ }; When does it run? As per the above article, unlike other BPF program types that expect to be called at a particular place in the codebase, SOCK_OPS program can be called at different places and use an "op" field to indicate that context. See include/uapi/linux/bpf.h for the enumerated BPF_SOCK_OPS_* definitions, but they include events like retransmit timeout, connection establishment etc. 1.3 BPF_PROG_TYPE_SK_SKB What do I do with it? Allows users to access skb and socket details such as port and IP address with a view to supporting redirect of skbs between sockets. See https://lwn.net/Articles/731133/ . This functionality is used in conjunction with a sockmap - a special-purpose BPF map that contains references to socket structures and associated values. sockmaps are used to support redirection. The program is attached and the bpf_sk_redirect_map() helper can be used to carry out the redirection. The general approach we catch socket creation events with sock_ops BPF programs, associate values with the sockmap for these, and then use data at the sk_skb instrumentation points to inform socket redirection - this is termed the verdict, and the program for this is attached to the sockmap via BPF_SK_SKB_STREAM_VERDICT. The verdict can be __SK_DROP, __SK_PASS, or __SK_REDIRECT. Another use case for this program type is in the strparser framework (https://www.kernel.org/doc/Documentation/networking/strparser.txt). BPF programs can be used to parse message streams via callbacks for read operations, verdict and read completion. TLS and KCM use stream parsing. How do I attach my program? A redirection progaram is attached to a sockmap as BPF_SK_SKB_STREAM_VERDICT; it should return the result of bpf_sk_redirect_map(). A strparser program is attached via BPF_SK_SKB_STREAM_PARSER and should return the length of data parsed. What context is provided? A pointer to the struct __sk_buff containing packet metadata/data. However more fields are accessible to the sk_skb program type. The extra set of fields available are documented in include/linux/bpf.h like so: /* Accessed by BPF_PROG_TYPE_sk_skb types from here to ... */ __u32 family; __u32 remote_ip4; /* Stored in network byte order */ __u32 local_ip4; /* Stored in network byte order */ __u32 remote_ip6[4]; /* Stored in network byte order */ __u32 local_ip6[4]; /* Stored in network byte order */ __u32 remote_port; /* Stored in network byte order */ __u32 local_port; /* stored in host byte order */ /* ... here. */ So from the above alone we can see we can gather information about the socket, since the above represents the key information that identifies the socket uniquely (protocol is already available in the globally-accessible portion of the struct __sk_buff). When does it run? A stream parser can be attached to a socket via BPF_SK_SKB_STREAM_PARSER attachment to a sockmap, and the parser runs on socket receive via smap_parse_func_strparser() in kernel/bpf/sockmap.c . BPF_SK_SKB_STREAM_VERDICT also attaches to the sockmap, and is run via smap_verdict_func(). 2. tc (traffic control) subsystem programs Next let's examine the program type related to the TC kernel packet scheduling subsystem. See the tc(8) manpage for a general introduction, and tc-bpf(8) for BPF specifics. 2.1 tc_cls_act : qdisc classifier What do I do with it? tc_cls_act allows us to use BPF programs as classifiers and actions in tc, the Linux QoS subsystem. What's even better is the tc(8) command has eBPF support also, so we can directly load BPF programs as classifiers and actions for inbound (ingress) and outbound (egress) traffic. See http://man7.org/linux/man-pages/man8/tc-bpf.8.html for a description of how to use tc's BPF functionality. tc programs can classify, modify, redirect or drop packets. How do I attach my program? tc(8) can be used; see tc-bpf(8) for details. The basics are we create a "clsact" qdisc for a network device, and add ingress and egress classifiers/actoins by specifying the BPF object and relevant ELF section. Example, to add an ingress classifier to eth0 in ELF section my_elf_sec from myprog_kernel.o (a bpf-bytecode-compiled object file): # tc qdisc add dev eth0 clsact # tc filter add dev eth0 ingress bpf da obj myprog_kernel.o sec my_elf_sec What context is provided? A pointer to struct __sk_buff packet metadata/data. When does it get run? As mentioned above, classifier qdisc must be added, and once it is we can attach BPF programs to classify inbound and outbound traffic. Implementation-wise, act_bpf.c and cls_bpf.c implement action/classifier modules. On ingress/gress sch_handle_ingress()/egress() call tcf_classify(). In the case of ingress, we do classification via the core network interface receive function, so we are getting the packet after the driver has processed it but before IP etc see it. On egress, the filtering is done prior to submitting to the device queue for transmit. 3. xdp : the Xpress Data Path. The key design goal for XDP is to introduce programmability in the network datapath. The aim is to provide the XDP hooks as close to the device as possible (before the OS has created sk_buff metadata) to maximize performace while supporting a common infrastructure across devices. To support XDP like this requires driver changes. For an example see drivers/net/ethernet/broadcom/bnxt/bnxt_xdp.c. A bpf net device op (ndo_bpf) is added. For bnxt it supports XDP_SETUP_PROG and XDP_QUERY_PROG actions; the former configures the device for XDP, reserving rings and setting the program as active. The latter returns the BPF program id. BPF-specific transmit and receive functions are provided and called by the real send/receive functions if needed. 3.1 BPF_PROG_TYPE_XDP What do I do with it? XDP allows access to packet data as early as possible, before packet metadata (struct sk_buff) has been assigned. Thus it is a useful place to do DDoS mitigation or load balancing since such activities can often avoid the expensive overhead of sk_buff allocation. XDP is all about supporting run-time programming of the kernel in via BPF hooks, but by working in concert with the kernel itself; i.e. not a kernel bypass mechanism. Actions supported include XDP_PASS (pass into network processing as usual), XDP_DROP (drop), XDP_TX (transmit) and XDP_REDIRECT. See include/uapi/linux/bpf.h for the "enum xdp_action". How do I attach my program? Via netlink socket message. A netlink socket - socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE) - is created and bound, and then we send a netlink message of type NLA_F_NESTED | 43 ; this specifies XDP message. The message contains the BPF fd, the interface index (ifindex). See samples/bpf/bpf_load.c for an example. What context is provided? An xdp metadata pointer; struct xdp_md * . XDP metadata is deliberately lightweight; from include/uapi/linux/bpf.h: /* user accessible metadata for XDP packet hook * new fields must be added to the end of this structure */ struct xdp_md { __u32 data; __u32 data_end; }; When does it get run? "Real" XDP is implemented at the driver level, and transmit/receive ring resources are set aside for XDP usage. For cases where drivers do not support XDP, there is the option of using "generic" XDP, which is implemented in net/core/dev.c. The downside of this is we do not bypass skb allocation, it just allows us to use XDP for such devices also. 4. kprobes, tracepoints and perf events kprobes, tracepoints and perf events all provide kernel instrumentation. kprobes - https://www.kernel.org/doc/Documentation/kprobes.txt - allow instrumentation of specific functions - entry of a function can be monitored via a kprobe, along with most instructions within a function, or entry/return can be instrumented via a kretprobe. When one of these probes is enabled, the code at the enable point is saved, and replaced with a breakpoint instruction. When this breakpoint is hit a trap instruction is generated, registers are saved and we branch to the relevant instrumentation handler. For example, kprobes are handled by kprobe_dispatcher() which gets the address of the kprobe and register context as arguments. kretprobes are implemented via kprobes; a kprobe fires on entry and modifies the return address, saving the original and replacing it with the location of the instrumentation handler. Tracepoints - https://www.kernel.org/doc/Documentation/trace/tracepoints.rst - are similar, but ratther than being enabled at particular instructions, they are explicitly marked at sites in code, and if enabled can be used to collect debugging information at those sites of interest. The same tracepoint can be declared in multiple places; for example trace_drv_return_int() is called in multiple places in net/mac80211/driver-ops.c . Perf events - https://perf.wiki.kernel.org/index.php/Main_Page - are the basis for eBPF support for these program types. BPF essentially piggy-backs on the existing infrastructure for event sampling, allowing us to attach programs to perf events of interest, which include kprobes, uprobes, tracepoints etc as well has other software events, and indeed hardware events can be monitored too. These instrumentation points are what gives BPF the capability to be a general-purpose tracing tool as well as a means for supporting the original networking-centric use cases like socket filtering. 4.1 BPF_PROG_TYPE_KPROBE What do I do with it? instrument code in any kernel function (bar a few exceptions) via kprobe, or instrument entry/return via kretprobe. k[ret]probe_perf_func() executes a BPF program attached to the probe point. Note that this program type can also be used to attach to u[ret]probes - see https://www.kernel.org/doc/Documentation/trace/uprobetracer.txt for details How do I attach my program? When the kprobe is created via sysfs, it has an id associated with it, stored in /sys/kernel/debug/tracing/events/[uk]probe//id , /sys/kernel/debug/tracing/events/[uk]retprobe/probename/id . https://www.kernel.org/doc/Documentation/trace/kprobetrace.txt contains details on how to create a kprobe using sysfs.For example, to create a probe called "myprobe" on entry to tcp_retransmit_skb() and retrieve its id: # echo 'p:myprobe tcp_retransmit_skb' > /sys/kernel/debug/tracing/kprobe_events # cat /sys/kernel/debug/tracing/events/kprobes/myprobe/id 2266 We can use that probe id to open a perf event, enable it, and set the BPF program for that perf event to be our program. See samples/bpf/bpf_load.c in the load_and_attach() function for how this can be done for k[ret]probes. The code might look something like this: struct perf_event_attr attr; int eventfd, programfd; int probeid; /* Load BPF program and assign programfd to it; and get probeid of probe from sysfs */ attr.type = PERF_TYPE_TRACEPOINT; attr.sample_type = PERF_SAMPLE_RAW; attr.sample_period = 1; attr.wakeup_events = 1; attr.config = probeid; eventfd = sys_perf_event_open(&attr, -1, 0, programfd, 0); if (eventfd < 0) return -errno; if (ioctl(eventfd, PERF_EVENT_IOC_ENABLE, 0)) { close(eventfd); return -errno; } if (ioctl(eventfd, PERF_EVENT_IOC_SET_BPF, programfd)) { close(eventfd); return -errno; } What context is provided? A struct pt_regs *ctx , from which the registers can be accessed. Much of this is platform-specific, but some general-purpose functions exist such as regs_return_value(regs), which returns the value of the register than holds the function return value (regs→ax on x86). When does it get run? When the probe is enabled and breakpoint is hit, k[ret]probe_perf_func() executes a BPF program attached to the probe point via trace_call_bpf(). Similar story for u[ret]probe_perf_func(). 4.2 BPF_PROG_TYPE_TRACEPOINT What do I do with it? Instrument tracepoints in kernel code. Tracepoints can be enabled via sysfs as is the case with kprobes, and in a similar way. The list of trace events can be seen under /sys/kernel/debug/tracing/events. How do I attach my program? As we saw above, when the tracepoint is created via sysfs, it has an id associated with it. We can use that probe id to open a perf event, enable it, and set the BPF program for that perf event to be our program. See samples/bpf/bpf_load.c in the load_and_attach() function for how this can be done for tracepoints; the above code snippet for kprobes works for tracepoints also. As an example showing how tracepoints are enabled, here we enable the net/net_dev_xmit tracepoint as "myprobe2" and retrieve its id: # echo 'p:myprobe2 trace:net/net_dev_xmit' > /sys/kernel/debug/tracing/kprobe_events # cat /sys/kernel/debug/tracing/events/kprobes/myprobe2/id 2270 What context is provided? The context provided by the specific tracepoint; arguments and data types are associated with the tracepoint definition. When does it get run? When the tracepoint is enabled and hit, perf_trace_() (see definition in include/trace/perf.h) calls perf_trace_run_bpf_submit() which will invoke the bpf program via trace_call_bpf(). 4.3 BPF_PROG_TYPE_PERF_EVENT What do I do with it? Instrument software and hardware perf events. These include events like syscalls, timer expiry, sampling of hardware events, etc. Hardware events include PMU events (processor monitoring unit) which tell us things like how many instructions completed etc. Perf event monitoring can be targeted at a specific process or group, processor, and a sample period can be specified for profiling. How do I attach my program? A similar model as per the above; we call perf_event_open() with an attribute set, enable the perf event via PERF_EVENT_IOC_ENABLE ioctl(), and set the bpf program via PERF_EVENT_IOC_SET_BPF ioctl(). For PMU (processor monitoring unit) perf event example, see these snippets from samples/bpf/sampleip_user.c: ... struct perf_event_attr pe_sample_attr = { .type = PERF_TYPE_SOFTWARE, .freq = 1, .sample_period = freq, .config = PERF_COUNT_SW_CPU_CLOCK, .inherit = 1, }; ... pmu_fd[i] = sys_perf_event_open(&pe_sample_attr, -1 /* pid */, i, -1 /* group_fd */, 0 /* flags */); if (pmu_fd[i] < 0) { fprintf(stderr, "ERROR: Initializing perf sampling\n"); return 1; } assert(ioctl(pmu_fd[i], PERF_EVENT_IOC_SET_BPF, prog_fd[0]) == 0); assert(ioctl(pmu_fd[i], PERF_EVENT_IOC_ENABLE, 0) == 0); ... What context is provided? A struct bpf_perf_event_data *, which looks like this: struct bpf_perf_event_data { struct pt_regs regs; __u64 sample_period; }; When does it get run? Depends on the perf event firing and the sample rate chosen, specified by freq and sample_period fields in the perf event attribute structure. 5. cgroups-related program types CGroups are used to handle resource allocation, allowing or denying access to system resources such as CPU, network bandwidth etc for groups of processes. One key use case for cgroups is containers; a container's resource access is limited via cgroups while its activities are isolated by the various classes of namespace (network namespace, process ID namespace etc). In the BPF context, we can create eBPF programs that allow or deny access. In include/linux/bpf-cgroup.h we can see definitions for execution of socket/skb programs, where __cgroup_bpf_run_filter_skb is called wrapped in a check that cgroup BPF is enabled: #define BPF_CGROUP_RUN_PROG_INET_INGRESS(sk, skb) \ ({ \ int __ret = 0; \ if (cgroup_bpf_enabled) \ __ret = __cgroup_bpf_run_filter_skb(sk, skb, \ BPF_CGROUP_INET_INGRESS); \ \ __ret; \ }) #define BPF_CGROUP_RUN_SK_PROG(sk, type) \ ({ \ int __ret = 0; \ if (cgroup_bpf_enabled) { \ __ret = __cgroup_bpf_run_filter_sk(sk, type); \ } \ __ret; \ }) If cgroups are enabled, we attach our program to the cgroup and it will be executed at the relevant hook points. To get an idea of the full list of hooks, consult include/uapi/linux/bpf.h and examine the enumerated type "bpf_attach_type" for BPF_CGROUP_* definitions. 5.1 BPF_PROG_TYPE_CGROUP_SKB What do I do with it? Allow or deny network access on IP egress/ingress (BPF_CGROUP_INET_INGRESS/BPF_CGROUP_INET_EGRESS). BPF programs should return 1 to allow access. Any other value results in the function __cgroup_bpf_run_filter_skb() returning -EPERM, which will be propagated to the caller such that the packet is dropped. How do I attach my program? The program is attached to a specific cgroup's file descriptor. What context is provided? The relevant skb. When does it get run? For inet ingress, sk_filter_trim_cap() (see above) contains a call to BPF_CGROUP_RUN_PROG_INET_INGRESS(sk, skb); if a non-zero value is returned, the error is propogated to the caller (e.g. __sk_receive_skb()) and the packet is discarded and freed. A similar approach is taken on egress, but in ip[6]_finish_output(). 5.2 BPF_PROG_TYPE_CGROUP_SOCK What do I do with it? Allow or deny network access at various socket-related events (BPF_CGROUP_INET_SOCK_CREATE, BPF_CGROUP_SOCK_OPS). As above, BPF programs should return 1 to allow access. Any other value results in the function __cgroup_bpf_run_filter_sk() returning -EPERM, which will be propagated to the caller such that the packet is dropped. How do I attach my program? The program is attached to a specific cgroup's file descriptor. What context is provided? The relevant socket (sk). When does it get run? At socket creation time, in inet_create() we call BPF_CGROUP_RUN_PROG_INET_SOCK() with the socket as argument, and if that function fails, the socket is released. 6. Lightweight tunnel program types. Lightweight tunnels - https://lwn.net/Articles/650778/ - are a simple way to do tunneling by attaching encapsulation instructions to routes. The examples in the patch description make things clearer: iproute examples (without BPF): VXLAN: ip route add 40.1.1.1/32 encap vxlan id 10 dst 50.1.1.2 dev vxlan0 MPLS: ip route add 10.1.1.0/30 encap mpls 200 via inet 10.1.1.1 dev swp1 So we're telling Linux for example that for traffic to 40.1.1.1/32 addresses, we want to encapsulate with a a VXLAN ID of 10 and destination IPv4 address of 50.1.1.2. BPF programs can do the encapsulation on outbound/transmit (inbound packets are readonly). See https://lwn.net/Articles/705609/ for more details. Similarly to tc, iproute eBPF support allows us to attach the eBPF program ELF section directly: ip route add 192.168.253.2/32 \ encap bpf out obj lwt_len_hist_kern.o section len_hist \ dev veth0 6.1 BPF_PROG_TYPE_LWT_IN What do I do with it? Examine inbound packets for lightweight tunnel de-encapsulation. How do I attach my program? Via "ip route add". # ip route add <route+prefix> encap bpf in obj <bpf object file.o> section <ELF section> dev <device> What context is provided? Pointer to the sk_buff. When does it get run? Via lwtunnel_input() ; that function supports a number of encapsulation types including BPF. The BPF case runs bpf_input in net/core/lwt_bpf.c with redirection disallowed. 6.2 BPF_PROG_TYPE_LWT_OUT What do I do with it? Implement encapsulation for lightweight tunnels for specific destination routes on outbound. Encapsulation is forbidden How do I attach my program? Via "ip route add": # ip route add <route+prefix> encap bpf out obj <bpf object file.o> section <ELF section> dev <device> What context is provided? Pointer to the struct __sk_buff When does it get run? Via lwtunnel_output(). 6.3 BPF_PROG_TYPE_LWT_XMIT What do I do with it? Implement encapsulation/redirection for lightweight tunnels on transmit. How do I attach my program? Via "ip route add" # ip route add <route+prefix> encap bpf xmit obj <bpf object file.o> section <ELF section> dev <device> What context is provided? Pointer to the struct __sk_buff When does it get run? Via lwtunnel_xmit(). Summary So hopefully this roundup of program types was useful. We can see that BPF's safe in-kernel programmable environment can be used in all sorts of interesting ways! The next thing we will talk about is what BPF helper functions are available within the varoius program types. Learning more about BPF Thanks for reading this installment of our series on BPF. We hope you found it educational and useful. Questions or comments? Use the comments field below! Stay tuned for the next installment in this series, BPF Helper Functions.

Notes on BPF (1) - A Tour of Progam Types Oracle Linux kernel developer Alan Maguire presents this six-part series on BPF, wherein he presents an in depth look at the kernel's "Berkeley Packet Filter"...

Linux Kernel Development

Linux Plumbers Conference 2018 Report

Dhaval Giani, an Oracle Linux kernel developer and development manager, shares some of his thoughts and insights from Linux Plumbers Conference 2018. This is my report from LPC 2018 held in Vancouver, BC on November 13-15, 2018. Oracle had a strong presence at LPC this year. I counted at least 20 of us (so ~4% of the conference attendees). Like last year, I organized the Testing and Fuzzing microconference. It was a popular microconference (I counted over 100 attendees at peak times). Highlights of the testing microconference: The Automated Testing Summit (ATS) this year was co-located with ELCE. Kevin Hilman provided a report about events at the summit. There was a push to standardize testing procedures, starting with how testing is done, to defining various terms. There was a strong embedded presence this year but the summit organizers would like to expand it to include more distributions and server folks. A big goal going forward is to unify all the secret sauces which various companies have. LWN has covered this talk, and I highly recommend reading about it here. KernelCI was another important topic. The goal of this project is to test non-x86 platforms. The original success criteria used to be a successful compile on the platform. Now, we have reached a point where more often than not, we have a successful boot. This is great work by the kernel community, and kernelCI is only going to get more and more important as we reach a point where we will actually be able to run test suites for more than a few references platforms. KernelCI will soon be a Linux Foundation project. LWN has covered this as well. Our own Knut Omang talked about his new make runchecks which helps to improve code quality by running a bunch of automated checks (such as checkpatch, smatch, sparse, checkdoc, Coccinelle). The tool aims to categorize errors so that users can filter on them. The talk was quite well received, with a lot of "this is a cool idea" being heard around the room. Dmitry Vyukov from Google talked about syzkaller and syzbot. These projects are working very well to automate a lot of kernel fuzzing and reporting a number of issues (some of them having security implications). Around 70% of the bugs reported by syzkaller/syzbot are getting fixed upstream. There is also a lot of future automation being worked on. Matthew Wilcox from Oracle talked about his kernel testing in userspace. Matthew has extracted some kernel code into a library which can then be built into a user space test suite, but also be run as part of kernel test suites. At this point, it only works for Matthew but if he gets some collaborators, he believes it can be made more generic. Steven Rostedt implemented an ftrace probe filter to inject allocation failures during this talk. This was an enjoyable discussion. Finally Dan Carpenter, also from Oracle, talked about smatch. Smatch had quite some success in finding issues in the kernel with many of them having security implications. It was a great talk on how smatch worked and what new features were coming. One notable moment was Dan's work with detecting spectre v1 issues, and confirming if something was a real issue or not. Matthew Wilcox stated that the issue Dan highlighted was real and even created a patch for it. This was an excellent session, and I loved the interaction we had. There was talk about expanding ATS next year to get more coverage. Stay tuned to hear more about it. I also attended an old favourite of mine, Real Time Scheduling microconference. That was also a fantastic microconference. I have been following the PREEMPT_RT project for many years now, and it is getting close to being all in mainline. Talks have shifted from, when will we get to mainline, to what do we do after it is mainline (more testing seemed to the theme). Oracle's Prakash Sangappa talked about real-time inside namespaces, which led to a spirited discussion. Once missing bandwidth inheritance comes into place, we will be able to allow real-time inside namespaces which would make namespaces (and by extension containers) very useful. Daniel Jordan from Oracle organized the Scalability microconference. This was another exciting microconference, with a lot of great problems being discussed. Steven Sistare and Subhra Mazumdar from Oracle talked about improving the scheduler's load balancer. One of the key issues coming up now is, does the scheduler scale well on both the higher end (big iron) as well as the lower end (embedded and mobile) at the same time. Is it time to start bringing in tunables. Oracle is currently one of the very few participants looking to improve the high end performance. We will be keeping a close eye to maintain and improve performance characteristics of Linux in general and the scheduler in particular. There was talk about how to improve hugepages by Mike Kravetz, an Oracle kernel developer (along with Christoph Lameter) , and on ktask by Daniel Jordan. This was also a very interactive microconference that I enjoyed greatly. The rest of my time at the conference was spent in the hallway track, meeting old friends and discussing crazy ideas. We talked about how it is time now for cgroups v3 (just kidding!), and in general about the various other problems people are trying to solve across the stack. The Linux Plumbers Conference 2018 website located here has a link for the detailed conference schedule which has clickable links for each session. This year sessions were video taped so you can watch the presentations as well as the discussions that occurred. Also, the etherpads have all the notes from each session available. Finally, no report of LPC is complete without a mention of the social events. We got to meet a lot of old friends and made new ones. One key takeaway I had was that our push to get patches accepted upstream, and increasing participation is getting noticed. It is good to see Oracle's contribution to Linux and open source being acknowledged by other developers. I would like to thank Oracle for sponsoring my travel and the LPC organizing committee for organizing another great edition of the conference.

Dhaval Giani, an Oracle Linux kernel developer and development manager, shares some of his thoughts and insights from Linux Plumbers Conference 2018. This is my report from LPC 2018 held in Vancouver,...

Linux Kernel Development

Can better task stealing make Linux faster?

Load balancing via scalable task stealing Oracle Linux kernel developer Steve Sistare contributes this discussion on kernel scheduler improvements. The Linux task scheduler balances load across a system by pushing waking tasks to idle CPUs, and by pulling tasks from busy CPUs when a CPU becomes idle. Efficient scaling is a challenge on both the push and pull sides on large systems. For pulls, the scheduler searches all CPUs in successively larger domains until an overloaded CPU is found, and pulls a task from the busiest group. This is very expensive, costing 10's to 100's of microseconds on large systems, so search time is limited by the average idle time, and some domains are not searched. Balance is not always achieved, and idle CPUs go unused. I have implemented an alternate mechanism that is invoked after the existing search in idle_balance() limits itself and finds nothing. I maintain a bitmap of overloaded CPUs, where a CPU sets its bit when its runnable CFS task count exceeds 1. The bitmap is sparse, with a limited number of significant bits per cacheline. This reduces cache contention when many threads concurrently set, clear, and visit elements. There is a bitmap per last-level cache. When a CPU becomes idle, it searches the bitmap to find the first overloaded CPU with a migratable task, and steals it. This simple stealing yields a higher CPU utilization than idle_balance() alone, because the search is cheap, costing 1 to 2 microseconds, so it may be called every time the CPU is about to go idle. Stealing does not offload the globally busiest queue, but it is much better than running nothing at all. Results Stealing improves utilization with only a modest CPU overhead in scheduler code. In the following experiment, hackbench is run with varying numbers of groups (40 tasks per group), and the delta in /proc/schedstat is shown for each run, averaged per CPU, augmented with these non-standard stats: %find - percent of time spent in old and new functions that search for idle CPUs and tasks to steal and set the overloaded CPUs bitmap. steal - number of times a task is stolen from another CPU. X6-2: 1 socket * 10 cores * 2 hyperthreads = 20 CPUs Intel(R) Xeon(R) CPU E5-2630 v4 @ 2.20GHz hackbench process 100000 sched_wakeup_granularity_ns=15000000 baseline grps time %busy slice sched idle wake %find steal 1 8.084 75.02 0.10 105476 46291 59183 0.31 0 2 13.892 85.33 0.10 190225 70958 119264 0.45 0 3 19.668 89.04 0.10 263896 87047 176850 0.49 0 4 25.279 91.28 0.10 322171 94691 227474 0.51 0 8 47.832 94.86 0.09 630636 144141 486322 0.56 0 new grps time %busy slice sched idle wake %find steal %speedup 1 5.938 96.80 0.24 31255 7190 24061 0.63 7433 36.1 2 11.491 99.23 0.16 74097 4578 69512 0.84 19463 20.9 3 16.987 99.66 0.15 115824 1985 113826 0.77 24707 15.8 4 22.504 99.80 0.14 167188 2385 164786 0.75 29353 12.3 8 44.441 99.86 0.11 389153 1616 387401 0.67 38190 7.6 Elapsed time improves by 8 to 36%, costing at most 0.4% more find time. CPU busy utilization is close to 100% for the new kernel, as shown by the green curve in the following graph, versus the orange curve for the baseline kernel: Stealing improves Oracle database OLTP performance by up to 9% depending on load, and we have seen some nice improvements for mysql, pgsql, gcc, java, and networking. In general, stealing is most helpful for workloads with a high context switch rate. The code As of this writing, this work is not yet upstream, but the latest patch series is at https://lkml.org/lkml/2018/12/6/1253. If your kernel is built with CONFIG_SCHED_DEBUG=y, you can verify that it contains the stealing optimization using # grep -q STEAL /sys/kernel/debug/sched_features && echo Yes Yes If you try it, note that stealing is disabled for systems with more than 2 NUMA nodes, because hackbench regresses on such systems, as I explain in https://lkml.org/lkml/2018/12/6/1250 . However, I suspect this effect is specific to hackbench and that stealing will help other workloads on many-node systems. To try it, reboot with kernel parameter sched_steal_node_limit = 8 (or larger). Future work After the basic stealing algorithm is pushed upstream, I am considering the following enhancements: If stealing within the last-level cache does not find a candidate, steal across LLC's and NUMA nodes. Maintain a sparse bitmap to identify stealing candidates in the RT scheduling class. Currently pull_rt_task() searches all run queues. Remove the core and socket levels from idle_balance(), as stealing handles those levels. Remove idle_balance() entirely when stealing across LLC is supported. Maintain a bitmap to identify idle cores and idle CPUs, for push balancing.

Load balancing via scalable task stealing Oracle Linux kernel developer Steve Sistare contributes this discussion on kernel scheduler improvements. The Linux task scheduler balances load across a system...

Announcements

Announcing Software Collection Library 3.2 for Oracle Linux

We are pleased to announce the release of the Software Collection Library 3.2 to the Unbreakable Linux Network and the Oracle Linux yum server. Software collections are primarily intended for development environments which require access to the latest features of software components such as Perl, PHP, or Python. For these environments, you need to minimize the disruption of system processes that rely on the versions of these components. The Software Collections library allows you to install and use several versions of the same software on a system, simultaneously, and without disruption. You use the software collection library utility (scl) to run the developer tools from the software collections that you have installed. The scl utility isolates the effects of running these tools from other versions of the same software utilities that you have installed. Additions and Updates for Oracle Linux 7 The following collections have been added in the 3.2 release of the Software Collection Library: devtoolset-8 rh-git218 rh-haproxy18 rh-nginx114 rh-nodejs10 rh-perl526 rh-php72 rh-ruby25 rh-varnish5 rh-varnish6 The following collections have been updated in the 3.2 release of the Software Collection Library: devtoolset-7 httpd24 rh-git29 rh-nodejs6 rh-nodejs8 rh-php70 Software Collections Libraries Available for Oracle Linux 7 (aarch64) Oracle only provides the latest versions and additions to the software collection library for the Arm (aarch64) platform and these are only supported for the latest update level of Oracle Linux 7. A subset of the complete software collection library, as available for the x86_64 platform, is available for aarch64. The following collections are currently available for Oracle Linux 7 (aarch64): devtoolset-6 devtoolset-7 devtoolset-8 httpd24 oracle-armtoolset-1 python27 rh-git218 rh-git29 rh-maven35 rh-nginx112 rh-nginx114 rh-nodejs10 rh-nodejs6 rh-nodejs8 rh-perl526 rh-php70 rh-php71 rh-php72 rh-python36 rh-ruby25 rh-varnish5 rh-varnish6 The Oracle Linux 7 (aarch64) release of the software collection library, additionally includes oracle-armtoolset-1 which provides a solid developer toolset to build code for 64-bit Arm platforms and to compile modules against the provided kernel. This includes the version 7.3 of the gcc compiler that is used to build the aarch64 version of UEK R5. Oracle Linux 7 users can find more information in the Software Collection Library 3.2 for Oracle Linux 7 Release Notes in the Oracle Linux 7 documentation library. Additions and Updates for Oracle Linux 6 The following collections for Oracle Linux 6 have been added in the 3.2 release of the Software Collection Library: devtoolset-8 The following collections have been updated in the 3.2 release of the Software Collection Library: devtoolset-7 httpd24 rh-git29 rh-nodejs6 rh-php70 Oracle Linux 6 users can find more information in the Software Collection Library 3.2 for Oracle Linux 6 Release Notes in the Oracle Linux 6 documentation library. Support Support for the Software Collection Library is provided at no extra cost to customers with an Oracle Linux Premier Support subscription. If you do not have paid support, you can get peer support via the Oracle Community forums at https://community.oracle.com. Resources – Oracle Linux Documentation Oracle Linux Software Download Oracle Linux Blogs Oracle Linux Blog Community Pages Oracle Linux Social Media Oracle Linux on YouTube Oracle Linux on Facebook Oracle Linux on Twitter Data Sheets, White Papers, Videos, Training, Support & more Oracle Linux Product Training and Education Oracle Linux - http://oracle.com/education/linux

We are pleased to announce the release of the Software Collection Library 3.2 to the Unbreakable Linux Network and the Oracle Linux yum server. Software collections are primarily intended for...

Announcements

Announcing the general availability of the Unbreakable Enterprise Kernel Release 5 Update 1

The Oracle Linux operating system is engineered for an open cloud infrastructure. It delivers leading performance, scalability and reliability for enterprise SaaS and PaaS workloads as well as traditional enterprise applications. Oracle Linux Support offers access to award-winning Oracle support resources and Linux support specialists; zero-downtime updates using Ksplice; additional management tools such as Oracle Enterprise Manager and Spacewalk; and lifetime support, all at a low cost. And unlike many other commercial Linux distributions, Oracle Linux is easy to download, completely free to use, distribute, and update. What's New? The Unbreakable Enterprise Kernel Release (UEK) 5 Update 1 is based on the mainline kernel version 4.14.35 and includes several new features, added functionality and bug fixes across a range of subsystems. Notable changes Improved support for 64-bit Arm (aarch64) architecture. Oracle continues to deliver kernel modifications to improve support for 64-bit Arm (aarch64) architecture. These changes are built and tested against existing Arm hardware and provide support for Oracle Linux for Arm. Cgroup v2 CPU controller backported to support kABI. The update includes changes to the code that handles cgroup resource usage statistics and improves performance when handling frequent reads where there are many cgroups that are not active. Improved scheduler scalability for fast path. This release includes scheduler scalability improvements for fast path. In addition, a new scheduler feature, SIS_CORE, is introduced to improve performance for certain workloads such as Oracle Database OLTP. DTrace has been enhanced to include additional runtime options on both the x86_64 and Arm architectures. In addition, DTrace has been enhanced to include the implementation of ustack() along with the implementation of SDT probes, FBT entry probes, and FBT return probes on the Arm architecture. libnvdimm subsystem updated for PMEM and DAX. The libnvdimm kernel subsystem, which is responsible for the detection, configuration, and management of Non-Volatile Dual Inline Memory Modules (NVDIMMs) is updated in UEK R5U1 to take advantage a large number of upstream patches, bug fixes and backports. Notably, these include fixes to /proc/smaps to reflect the actual PMEM page size and some work to improve Address Range Scrub (ARS). Also included is support for direct access (DAX) page operations on Non-Volatile Dual Inline Memory Modules (NVDIMMs) using either the ext4 or XFS file systems. For more details on these and other new features and changes, please consult the Release Notes for the Unbreakable Enterprise Kernel Release 5 Update 1. Security (CVE) Fixes A full list of CVEs fixed in this release can be found in the Release Notes for the UEK R5 Update 1. Supported upgrade path Customers can upgrade existing Oracle Linux 7 Update 5 (and later) servers using the Unbreakable Linux Network or the Oracle Linux yum server. Software Download Oracle Linux can be downloaded, used, and distributed free of charge and all updates and errata are freely available. This allows you to decide which of your systems require a support subscription and makes Oracle Linux an ideal choice for your development, testing and production systems. You decide which support coverage is the best for each of your systems individually, while keeping all of your systems up-to-date and secure. For customers with Oracle Linux Premier Support, you also receive access to zero-downtime kernel updates using Oracle Ksplice and support for Oracle OpenStack. Compatibility UEK R5 Update 1 is fully compatible with the UEK R5 GA release. The kernel ABI for UEK R5 remains unchanged in all subsequent updates to the initial release. In this release, there are changes to the kernel ABI relative to UEK R4 that require recompilation of third-party kernel modules on the system. Before installing UEK R5, verify its support status with your application vendor. Resources – Oracle Linux Documentation Oracle Linux Software Download Oracle Linux Blogs Oracle Linux Blog Community Pages Oracle Linux Social Media Oracle Linux on YouTube Oracle Linux on Facebook Oracle Linux on Twitter Data Sheets, White Papers, Videos, Training, Support & more Oracle Linux Product Training and Education Oracle Linux - http://oracle.com/education/linux

The Oracle Linux operating system is engineered for an open cloud infrastructure. It delivers leading performance, scalability and reliability for enterprise SaaS and PaaS workloads as well...

Linux Kernel Development

Seccomp: Safe and Secure and Slow No More

Linux kernel developer Tom Hromatka has been working in the area of seccomp looking to improve performance of large seccomp filters. Background Seccomp is a critical component to safely isolate and secure containers by restricting the syscalls that a container is allowed to invoke. In a nod to the many security threats that have arisen lately, current seccomp best practices are to create a (typically large) whitelist of allowed syscalls. This is safer than a small blacklist because new syscalls are occasionally added to the Linux kernel. If a blacklist is used and the seccomp filter and a new kernel are not updated together, malicious code could call this new syscall and use it as an attack vector to harm the system. But libseccomp isn't equipped to manage large whitelists at present. In its current form, it generates a series of sequential if syscall == n statements. Thus, a large seccomp filter can consist of hundreds of classic Berkeley Packet Filter (cBPF) instructions. The kernel must execute every if syscall == n cBPF instruction until the if statement matching the syscall being processed is found. For syscalls near the end of the filter, it can take milliseconds to process the cBPF instructions.   Hope (and better seccomp performance) is on the way! At Oracle, we are working on significantly improving seccomp performance when running large filters. We have proposed changes to libseccomp to utilize a binary tree which will reduce the cBPF computation time from O(n) down to O(log n). For a seccomp filter with 300 syscalls, this will drastically decrease the number of cBPF instructions executed from 300+ down to as little as 9 instructions.   An Example We created a simple test program using Docker's default libseccomp filter. In this test program, we call getppid() (a very fast syscall) millions of times and record how quickly it is executed. By modifying libseccomp and the cBPF instructions it generates, we're able to identify the impact of large syscall filters and their effect on performance. The results are even better than we hoped:     The performance of the current libseccomp implementation degrades linearly as the syscall falls later in the filter. Conversely, the performance of the binary tree remains consistent regardless of the location of the syscall within the filter. It is nearly as fast as the best case of the current filter. Expect to see this feature in libseccomp in 2019! Resources The binary tree RFC for libseccomp is available here:   https://github.com/seccomp/libseccomp/issues/116 Tom presented this topic at  Linux Plumbers Conference 2018. The video of that talk and presentation can be found here:   https://www.linuxplumbersconf.org/event/2/contributions/213/  

Linux kernel developer Tom Hromatka has been working in the area of seccomp looking to improve performance of large seccomp filters. Background Seccomp is a critical component to safely isolate and...

Linux Kernel Development

New Concepts in Scalability and Performance

Scalability and Performance Microconference at LPC 2018 This year at the Linux Plumbers Conference, Oracle Linux developer Daniel Jordan co-organized the performance and scalability microconference along with Pasha Tatashin from Microsoft and Ying Huang from Intel. The event had nine speakers, about half of whom were from Oracle, so this was a nice opportunity for our team to raise its concerns with the community. Daniel contributes this writeup on the challenges and opportunities they discussed. This was a good year for Oracle at the 2018 Linux Plumbers Conference with several of the attendees telling me that they noticed the heavy representation from Oracle, both in talks and the hallway. Plumbers was most useful for having small, focused discussions that would never happen on mailing lists. You can end up going deeper and finding more common ground with extended face time. Tim Chen from Intel spoke about a bottleneck in TPC-C with scheduler task accounting for cgroups on multi-socket systems. (Oracle's Unbreakable Enterprise Kernel 5 is configured with the same scheduler options he used in the runs.) An atomic operation to track the aggregate load average in a task group (load_avg in struct task_group) was showing up at the top of his profiles. Rik van Riel pointed out that this wasn't just a problem on multisocket boxes, they were also seeing this on single-socket systems at Facebook. Peter Zijlstra suggested that Tim revive some old patches that broke this counter up across NUMA nodes, and after further discussion, it was agreed to split along Last-Level Cache (LLC) boundaries instead because systems have grown larger since the patches were last posted. We're hopeful to see good results from these changes soon! Pasha Tatashin from Microsoft spoke about seamlessly updating a host OS while minimizing downtime of guest VMs, presenting two high-level strategies for the audience to consider. First, kexec a new host kernel and transfer control between the old and new host kernel as the transition between the two kernels is happening, and second, boot a new host OS inside a VM, migrate the guests into this VM (relying on nested virtualization), and kexec into it, fixing EPT translations before transferring control. There was some concern about how to support SR-IOV devices in the second solution, but in the end, Pasha decided to experiment with the second option. Steve Sistare and Subhra Mazumdar spoke about scheduler scalability work they've been involved in. Steve's blog post is coming in January; read Subhra's blog post here. Mike Kravetz and Christoph Lameter led a session on huge page issues in the kernel. Here's an excerpt about the session from Mike: During this MC, Christoph Lameter and myself talked about promoting huge page usage. This was mostly a rehash of material previously presented and discussed. The 'hope' was to spark discussion and possibly new ideas. During this session, one really good suggestion was made. Align mmap addresses for THP. I sent out a similar RFC to align for pmd sharing a couple years back (https://lkml.org/lkml/2016/3/28/478) but did not follow through. Will add both to my todo list. Boqun Feng held a discussion about an issue he had seen with workqueues and CPU hotplug that had come up when optimizing an RCU (Read-Copy-Update lock) path. According to a comment above its definition, queue_work_on requires callers to ensure the requested CPU for the work item can't go offline before the queueing is finished, and the problem was the RCU code path doesn't follow this requirement. Boqun wanted to disable preemption around the queue_work_on call, effectively preventing CPU hotplug, but Thomas Gleixner opposed this, saying that disabling preemption prevents CPU hotplug only by accident and that there was no semantic guarantee for it. Paul McKenney and Thomas went back and forth about what to do, but to make a long story short, in the hallway afterward it was discovered that the workqueue comment giving the requirement about CPU hotplug was stale. The workqueue splats Boqun Feng saw had some other cause, pending investigation. I spoke about ktask, an interface for parallelizing CPU-intensive kernel work, with the goal of discussing a few of the open problems in this work. The audience had a different idea, and we spent the session fielding questions about how ktask worked and where else it might be used. For example, Junaid Shahid from Google had a use case for ktask to multithread kvm dirty page tracking during live migration, but was concerned about threads having different amounts of work to do in their assigned memory regions such that the load may not be equally shared between them. My new plan, post-conference, will be to alleviate this by splitting up the ranges to be tracked into small pieces interleaved across threads to minimize the chance that one thread would get stuck with a busy range. Finally, Yang Shi led a discussion on mmap_sem, a perennial bottleneck in the kernel that often serializes updates to a process's address space, including its rbtree of VMAs and various fields in mm_struct. This discussion is hard to summarize since there were so many comments: To Yang Shi's suggestion about a per-VMA lock, Davidlohr Bueso said it wouldn't help alleviate contention when multiple threads update the same VMA. Vlastimil Babka suggested splitting large VMAs into many smaller ones, even if they shared the same flags, to make per-VMA locks work better. Rik van Riel was skeptical about this, since application threads may not have an even access pattern across the process's virtual address space. On a different topic, Waiman Long warned that a strategy used in one of the recent mmap_sem fixes for alleviating contention, downgrading the holder from writer to reader, may not benefit sometimes because readers don't optimistically spin the way writers do. Matthew Wilcox mentioned a planned experiment to use an RCU-safe B-tree (aka the Maple Tree) to avoid taking mmap_sem for read. Steve Sistare said the problem with the range locks is you have to traverse a tree of ranges to find which range to operate on, which creates a bottleneck in itself, and suggested potentially using a hashed array of locks, which is parallelizable but can suffer when the VA region to operate on is very large. Davidlohr Bueso mentioned that a range locking primitive exists already upstream. An rwsem will always outperform it because of optimistic spinning, but the worst case scenario described in the range locking series isn't that much worse than rwsem. He believes the main question right now is how to serialize threads operating on the same VMA. Laurent Dufour said the problem with the VMA is that there are so many ways to get to it: mm_struct's rbtree, mm_struct's VMA list, and anon_vma lists. Matthew Wilcox agreed, and said the kernel doesn't differentiate the case where the whole address space needs protecting and the case where an individual VMA does. Laurent and Matthew agreed on the need for a per-VMA lock. Matthew hopes for a per-process spinlock for the entire address space and a semaphore for each VMA. Thanks to Paul McKenney, Davidlohr Bueso, Dave Hansen, and Dhaval Giani, who provided helpful advice in the process of organizing this microconference Other Talks Here are a few recommended talks from LPC. Videos and slides are posted on the talk pages, linked from here . Mike Kravetz's and Christoph Lameter's "Very large Contiguous regions in userspace" for its useful and very interactive discussion about how to proceed with a common problem between different kernel communities. "RDMA and get_user_pages" from Matthew Wilcox, Dan Williams, Jan Kara, and John Hubbard for the great audience interaction, problem solving, and interesting technical content. Vlastimil Babka's "The hard work behind large physical allocations in the kernel" because of how well it laid out current issues in this area. The slide deck is very readable on its own, for those who prefer reading to watching but become frustrated at following powerpoints. "Concurrency with tools/memory-model" from Andrea Parri and Paul McKenney. If your work involves memory barriers, this is a good one to watch to learn about the expectations of the maintainers of the LKMM (Linux Kernel Memory Model). It turns out they filter for upstream postings containing barriers (e.g. smp_mb) and review the changes to make sure they're correct, and follow the expected commenting style for paired barriers. Concluding Thoughts Thanks to everyone who helped organize this event: it is a massive undertaking to make a conference this large happen. Excited for next year!

Scalability and Performance Microconference at LPC 2018 This year at the Linux Plumbers Conference, Oracle Linux developer Daniel Jordan co-organized the performance and scalability microconference...