iTranslated by AI
System Programming in Go: Learning from lls and cachectl
YAPC::Kyoto 2023 presentation materials
Self-introduction
- Real name: Tatsuya Kaneko
- CTO and Head of Engineering at PR TIMES, Inc.
- Joined April 2021
- We are Gold Sponsors for this YAPC
- Please reach out if you want to hear more about the company!
- Co-author of "Expert Web Performance Tuning: Practical Optimization Learned from ISUCON" (Gijutsu-Hyoron-sha) (commonly known as the "ISUCON Book")
- Organizer for ISUCON9 Qualifiers and ISUCON6 Finals
- Active on various social media with the ID: catatsuy
- Often called "catatsuy"
Introduction
- The Perl CPAN module Sys::PageCache has been used to adjust the page cache on Linux.
- Sys::PageCache is implemented using XS (a mechanism for calling C code from Perl), so it is not a pure Perl implementation.
- It calls system calls via C.
- cubicdaiya/cachectl is a Go tool with similar functionality to Sys::PageCache.
- It was originally a cgo implementation, but I rewrote it as a pure Go implementation.
- Go does not need to use C to call system calls.
- My own tool, lls, is also implemented in pure Go by calling system calls directly from Go.
- Since the method of doing system programming in Go doesn't seem to be widely known, I'll introduce it here.
Target Audience
- Understand the basic syntax of Go
- Have experience building applications with Go
- Have a certain level of understanding regarding Go's standard library and compiler
- Interested in Linux system programming
References
C and System Calls
System calls are the entry point to system programming.
(Linux System Programming 1.1.1.1 Issuing System Calls)
- Linux system programming involves programs that execute Linux system calls.
- User-space applications cannot directly perform operations such as reading or writing files for security and reliability reasons.
- When a user application needs to perform an operation permitted only to the kernel, it invokes a system call to let the kernel do it on its behalf.
- The method for invoking system calls is defined by the kernel and varies depending on the architecture.
- A unique number is assigned to each system call.
- C is the primary language used to execute system calls.
- Since the method for calling system calls differs by OS and architecture, they are usually called via libc (described later).
While the procedure for issuing system calls differs across other architectures, the essence remains the same. System programmers typically do not need to know how the kernel accepts system calls. This procedure is determined by the architecture and handled automatically by the compiler and C library.
(Linux System Programming 1.1.1.1 Issuing System Calls)
Column: How to use man
| Section | Content |
|---|---|
| 1 | Commands executable by users on Linux |
| 2 | System calls |
| 3 | Libraries implemented in C |
-
manallows you to specify the section number shown above. - If you want to read the documentation for the
opensystem call, runman 2 open.
About libc
The C library (libc) is the heart of Unix applications. Even when programming in languages other than C, the C library is used to access core services and system calls, though it may be hidden by higher-level libraries. The C library on Linux systems is GNU libc, abbreviated as glibc.
(Linux System Programming 1.1.2 C Library)
- Linux typically uses GNU libc (glibc), but Alpine Linux uses musl libc as its libc.
- musl libc is said to have simpler source code, so it is recommended to look at musl libc if you want to examine libc source code.
- The system call number for
openis often 5, but it varies by architecture (see below). - libc absorbs these differences between architectures.
- The system call number for
arch/arm/bits/syscall.h.in:#define __NR_open 5
arch/i386/bits/syscall.h.in:#define __NR_open 5
arch/m68k/bits/syscall.h.in:#define __NR_open 5
arch/microblaze/bits/syscall.h.in:#define __NR_open 5
arch/mips/bits/syscall.h.in:#define __NR_open 4005
arch/mips64/bits/syscall.h.in:#define __NR_open 5002
arch/mipsn32/bits/syscall.h.in:#define __NR_open 6002
arch/powerpc/bits/syscall.h.in:#define __NR_open 5
arch/powerpc64/bits/syscall.h.in:#define __NR_open 5
arch/s390x/bits/syscall.h.in:#define __NR_open 5
arch/sh/bits/syscall.h.in:#define __NR_open 5
arch/x32/bits/syscall.h.in:#define __NR_open (0x40000000 + 2)
arch/x86_64/bits/syscall.h.in:#define __NR_open 2
System Programming in Go
Go is a general-purpose language designed with systems programming in mind
The Go Programming Language Specification
- Go can invoke system calls without relying on C.
- While it has its pros and cons, it is quite convenient for creating tools that run on Linux.
- Since Go has a feature called cgo that can call C libraries and functions, you can invoke system calls via cgo.
- However, using cgo makes cross-compilation difficult.
- It has significant drawbacks, such as performance overhead due to memory copying between C and Go, and the fact that it falls outside the scope of garbage collection (GC).
- What I am introducing here is a method to implement this using only Go, without using cgo.
- There is a maxim in the Go Proverbs that says "Cgo is not Go.", and cgo should be avoided.
- In Go, you don't need to use cgo just to call system calls; you can use the
syscallpackage orgolang.org/x/sys/unix.- It is actually a language that makes system programming quite easy.
- However, since you will be directly using parts that the Go standard library usually hides, many things differ from typical Go practices.
- Naturally, system calls that only exist in Linux have functions and constants that only exist for Linux, so on a Mac, they will be treated as calling non-existent functions.
- Depending on your editor settings, this may show as an error in the editor, but you just have to ignore it.
- Naturally, you cannot compile it on a Mac (though you can cross-compile a binary for Linux).
Go and libc
- Go does not use libc.
- Go itself needs to absorb the differences between architectures.
- Go has a build tag specification, which allows the compiler to decide whether to include a specific file at build time based on the OS, architecture, Go version, etc.
- Nowadays, the new
//go:buildsyntax is available, allowing you to write conditional expressions.- For OS:Linux and Arch:amd64, you use
//go:build amd64 && linux.
- For OS:Linux and Arch:amd64, you use
- For example, constants used for the
opensystem call numbers are defined in separate files (see below).
- Nowadays, the new
- System call invocations are defined for each OS in the standard library's
syscallpackage.- Go can invoke system calls without using the power of C.
- However, the policy is not to add any more features to the
syscallpackage; new features are added togolang.org/x/sys/unix. - https://golang.org/s/go1.4-syscall
syscall/zsysnum_darwin_amd64.go: SYS_OPEN = 5
syscall/zsysnum_darwin_arm64.go: SYS_OPEN = 5
syscall/zsysnum_dragonfly_amd64.go: SYS_OPEN = 5
syscall/zsysnum_freebsd_386.go: SYS_OPEN = 5
syscall/zsysnum_freebsd_amd64.go: SYS_OPEN = 5
syscall/zsysnum_freebsd_arm.go: SYS_OPEN = 5
syscall/zsysnum_freebsd_arm64.go: SYS_OPEN = 5
syscall/zsysnum_freebsd_riscv64.go: SYS_OPEN = 5
syscall/zsysnum_linux_386.go: SYS_OPEN = 5
syscall/zsysnum_linux_amd64.go: SYS_OPEN = 2
syscall/zsysnum_linux_arm.go: SYS_OPEN = 5
syscall/zsysnum_linux_mips.go: SYS_OPEN = 4005
syscall/zsysnum_linux_mips64.go: SYS_OPEN = 5002
syscall/zsysnum_linux_mips64le.go: SYS_OPEN = 5002
syscall/zsysnum_linux_mipsle.go: SYS_OPEN = 4005
syscall/zsysnum_linux_ppc64.go: SYS_OPEN = 5
syscall/zsysnum_linux_ppc64le.go: SYS_OPEN = 5
syscall/zsysnum_linux_s390x.go: SYS_OPEN = 5
syscall/zsysnum_netbsd_386.go: SYS_OPEN = 5
syscall/zsysnum_netbsd_amd64.go: SYS_OPEN = 5
syscall/zsysnum_netbsd_arm.go: SYS_OPEN = 5
syscall/zsysnum_netbsd_arm64.go: SYS_OPEN = 5
syscall/zsysnum_openbsd_386.go: SYS_OPEN = 5
syscall/zsysnum_openbsd_amd64.go: SYS_OPEN = 5
syscall/zsysnum_openbsd_arm.go: SYS_OPEN = 5
syscall/zsysnum_openbsd_arm64.go: SYS_OPEN = 5
syscall/zsysnum_openbsd_mips64.go: SYS_OPEN = 5
syscall/zsysnum_plan9.go: SYS_OPEN = 14
Column: Go Bootstrap Problem
- The Go compiler was written in C until version 1.4, and has been written in Go since version 1.5.
- self-hosting
- Since pre-built Go binaries are distributed, you usually just download the pre-built binary.
- If you want to build Go 1.19 or lower yourself, you can obtain it by: compiling Go 1.4 with a C compiler → using Go 1.4 to compile the latest Go.
- Since Go 1.20 adopted Go 1.17 as the bootstrap toolchain, Go 1.20 can be obtained by: compiling Go 1.4 with a C compiler → using Go 1.4 to compile Go 1.17 → using Go 1.17 to compile Go 1.20.
- Go has a release cycle of twice a year. Currently, there is a proposal to annually update the Go version used as the bootstrap toolchain to the version released one year prior. It is proposed to update the bootstrap toolchain to Go 1.20 in Go 1.22.
- If this is realized, the use of generics may become more widespread.
- The reason for choosing Go 1.17 was to fully introduce the new
//go:buildbuild tag syntax introduced in Go 1.17, and because Go 1.18 was the first version where generics were introduced, which involved many changes and a high possibility of bugs.
Go Arrays and Slices
Refer to Go Slices: usage and internals - The Go Programming Language and Chapter 4 of "The Go Programming Language".
- I will explain arrays and slices here because this knowledge will be required later.
- In Go, an array's size is part of its type.
-
[3]intand[4]intare different types.
-
- Go arrays are values; for instance, if passed as a function argument, they are copied.
- In C, passing an array name results in a pointer to the first element, which is different from Go.
- A slice contains a pointer to an element of an underlying array, a length (
len), and a capacity (cap).- Since it holds a pointer to an array element, a slice is essentially a reference type.
- The pointer to the array element does not have to be the first element of the array.
The Go Standard Library and Arrays
- In Go, slices are typically used instead of arrays.
- Some standard libraries return arrays, but otherwise, you can basically forget about them.
- For example,
crypto/md5.Sum(data []byte)returns a[16]byte.
- For example,
- Passing a large array to a function causes a copy, so using arrays is likely unfavorable for performance.
- Arrays have a fixed size and lack flexibility; moreover, because the size is part of the type, you can only create functions for specific sizes.
- In current Go, you cannot pass array sizes even with generics (there is a proposal), and using slices is much easier.
- proposal: Go 2: spec: generic parameterization of array sizes · Issue #44253 · golang/go
From here, I will introduce actual programs!
About lls
- You cannot use
lson a directory containing a massive number of files.- Running
lsmight cause it to freeze or terminate abnormally. - One reason is that it sorts the results, so a well-known technique is to disable sorting.
- However, there are (and were) cases where even that isn't enough.
- Running
- The cause is that the buffer size used internally by libc's
readdiris fixed, so if there are too many files, a large number of system calls must be executed.- Since there is no way to change the buffer size, the only option is to directly call the
getdents64system call yourself.
- Since there is no way to change the buffer size, the only option is to directly call the
- At PR TIMES, we eventually succeeded in outputting a list of approximately 31 million files.
Usage examples of lls
lls can be used as an alternative to ls suitable for handling large numbers of files.
# Basically the same as ls, but since a massive list of files will likely be output, it is better to redirect the output to a file.
lls > output.txt
# Of course, you can also specify a directory.
lls / > output.txt
lls Implementation (Excerpt)
Go's syscall/ztypes_linux_amd64.go:
package syscall
type Dirent struct {
Ino uint64
Off int64
Reclen uint16
Type uint8
Name [256]int8
Pad_cgo_0 [5]byte
}
Equivalent to the following libc implementation:
struct dirent {
ino_t d_ino; /* Inode number */
off_t d_off; /* Not an offset; see below */
unsigned short d_reclen; /* Length of this record */
unsigned char d_type; /* Type of file; not supported
by all filesystem types */
char d_name[256]; /* Null-terminated filename */
};
lls implementation:
// Create a buffer to pass to getdents64
buf := make([]byte, bufSize)
// getdents64 can be executed multiple times to retrieve the remaining file list, so execute until the end
for {
// Execute getdents64 by passing the created buffer
// Return values are the number of bytes in the buffer and an error
n, err := syscall.Getdents(int(f.Fd()), buf)
if err != nil {
fmt.Fprintln(c.errStream, err)
return ExitCodeFail
}
// If 0, all files have been retrieved, so terminate the for loop
if n == 0 {
break
}
// The buffer contains multiple pieces of data from the C structure (struct dirent)
// Map them one by one to the Go structure
for bufp := 0; bufp < n; {
// Cast the C structure to the Go structure
dirent := (*syscall.Dirent)(unsafe.Pointer(&buf[bufp]))
// Reclen contains the byte size of this structure, so advance by that number of bytes
bufp += int(dirent.Reclen)
// Ino is the Inode number; 0 means the file entity does not exist -> deleted file
// The Inode number represents the file entity
if dirent.Ino == 0 {
continue
}
// Name contains the filename
// In C it's char[256], corresponding to [256]int8 in Go, but since we want to convert it to a string, cast it to [256]byte first
// In Go, type byte = uint8, so they are not the same and require casting
// The maximum length of a Linux filename is 255 bytes because this is char[256] and the last character is a NULL character
bb := (*[256]byte)(unsafe.Pointer(&dirent.Name))
// The [n:m] notation can be used on arrays, but it returns a slice
// It needs to be a []byte to cast it to a string
// Since this is a C string terminated with a NULL character, passing a []byte up to the index of the NULL character will result in a string
name := string(bb[0:blen(*bb)])
// Every directory contains the two directories . and .., so remove them
if name == "." || name == ".." {
// ignore
continue
}
fmt.Fprintln(c.outStream, name)
}
}
// Function that returns the position of the NULL character
func blen(b [256]byte) int {
for i := 0; i < len(b); i++ {
// The NULL character is the same as 0
if b[i] == 0 {
return i
}
}
// Ideally, we should never reach this point
return len(b)
}
Column: getdents and getdents64
man 2 getdents
getdents64()
The original Linux getdents() system call did not handle large filesystems and large file offsets. Consequently, Linux 2.4 added dents64(), with wider types for the d_ino and d_off
fields. In addition, getdents64() supports an explicit d_type field.
The getdents64() system call is like getdents(), except that its second argument is a pointer to a buffer containing structures of the lowing type:
struct linux_dirent64 {
ino64_t d_ino; /* 64-bit inode number */
off64_t d_off; /* 64-bit offset to next structure */
unsigned short d_reclen; /* Size of this dirent */
unsigned char d_type; /* File type */
char d_name[]; /* Filename (null-terminated) */
};
- There is no advantage to using
getdentsas it is an old mechanism.- You should simply use
getdents64without hesitation.
- You should simply use
- In Go, depending on the architecture, both
SYS_GETDENTSandSYS_GETDENTS64are defined in thesyscallpackage.- However, a wrapper function (like the
syscall.Getdentsused this time) is only provided forSYS_GETDENTS64. If you absolutely must callSYS_GETDENTS, you have to invoke it yourself using something likesyscall.Syscall.
- However, a wrapper function (like the
Column: musl libc's readdir implementation
- The
readdirfunction calls thegetdents64system call internally, but the buffer size is fixed.
struct dirent *readdir(DIR *dir)
{
struct dirent *de;
if (dir->buf_pos >= dir->buf_end) {
int len = __syscall(SYS_getdents, dir->fd, dir->buf, sizeof dir->buf);
if (len <= 0) {
if (len < 0 && len != -ENOENT) errno = -len;
return 0;
}
dir->buf_end = len;
dir->buf_pos = 0;
}
de = (void *)(dir->buf + dir->buf_pos);
dir->buf_pos += de->d_reclen;
dir->tell = de->d_off;
return de;
}
struct __dirstream
{
off_t tell;
int fd;
int buf_pos;
int buf_end;
volatile int lock[1];
/* Any changes to this struct must preserve the property:
* offsetof(struct __dirent, buf) % sizeof(off_t) == 0 */
char buf[2048];
};
typedef struct __dirstream DIR;
Column: About unsafe.String
- From Go 1.20, the
unsafe.Stringfunction was added to perform casting from[]bytetostringat high speed.- Converting to a
stringtakes almost no time.
- Converting to a
- In the
llsuse case, it seemed it would only result in a speedup of about 30ns in my environment, which would only total about 1s for 30 million files.- In the case of
lls, since a large number of files are placed on the disk, the HDD read speed is the bottleneck. - For
lls, there doesn't seem to be enough benefit to outweigh the loss in readability.
- In the case of
use unsafe.String to optimize for speed by catatsuy · Pull Request #28 · catatsuy/lls
About cachectl
-
cubicdaiya/cachectl originally executed system calls via C using cgo.
- I rewrote it into a pure Go implementation.
- It can basically do the same things as the CPAN module
Sys::PageCache.- It allows you to check the page cache usage of files on Linux and purge them from the page cache.
- There is also a
cachectldthat can be started as a daemon, but I won't introduce it this time.
Usage examples of cachectl
cachectl can be used to adjust the page cache on Linux.
# Check page cache status
cachectl -f /var/log/access_log
# Purge specified file from page cache
cachectl -op purge -f /var/log/access_log
# Ratio can be specified with -r
cachectl -op purge -f /var/log/access_log -r 0.9
cachectl Implementation (Excerpt)
- In the original C implementation, error handling for closing files was managed with
goto error, but in Go,deferis sufficient.
import (
"fmt"
"log"
"os"
"golang.org/x/sys/unix"
)
// Purge process
func purgePages(fpath string, fsize int64, rate float64) error {
if rate < 0.0 || rate > 1.0 {
return fmt.Errorf("%.1f: rate should be over 0.0 and less than 1.0\\n", rate)
}
f, err := os.Open(fpath)
if err != nil {
return err
}
defer f.Close()
// Equivalent to the following C code
// l = (off_t)(st.st_size * r)
// posix_fadvise(fd, 0, l, POSIX_FADV_DONTNEED)
// Pre-declare access patterns for file data
// POSIX_FADV_DONTNEED declares that the specified data will not be accessed in the near future
err = unix.Fadvise(int(f.Fd()), 0, int64(float64(fsize)*rate), unix.FADV_DONTNEED)
if err != nil {
return fmt.Errorf("failed to purge page cache for %s", fpath)
}
return nil
}
import (
"os"
"unsafe"
"golang.org/x/sys/unix"
)
// Get page cache status
func activePages(path string) (int, error) {
f, err := os.Open(path)
if err != nil {
return 0, err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return 0, err
}
fsize := fi.Size()
if fsize == 0 {
return 0, nil
}
// Equivalent to the following C code
// m = mmap(NULL, st.st_size, PROT_NONE, MAP_SHARED, fd, 0);
// Note that the order of arguments is different
mmap, err := unix.Mmap(int(f.Fd()), 0, int(fsize), unix.PROT_NONE, unix.MAP_SHARED)
if err != nil {
return 0, err
}
// Equivalent to the following C code
// munmap(m, st.st_size);
defer unix.Munmap(mmap)
pagesize := int64(os.Getpagesize())
pages := (fsize + pagesize - 1) / pagesize
pageinfo := make([]byte, pages)
mmapPtr := uintptr(unsafe.Pointer(&mmap[0]))
sizePtr := uintptr(fsize)
pageinfoPtr := uintptr(unsafe.Pointer(&pageinfo[0]))
// Determine if the page is in memory
// Equivalent to the following C code
// mincore(m, st.st_size, pageinfo)
// Only the constant is defined and no function is provided, so call it yourself using unix.Syscall
// Returns 0 on success, -1 on error
// Passing a pointer to the first element of the byte slice variable pageinfo; necessary information will be assigned to pageinfo
ret, _, err := unix.Syscall(unix.SYS_MINCORE, mmapPtr, sizePtr, pageinfoPtr)
if ret != 0 {
return 0, err
}
result := 0
for _, p := range pageinfo {
// Determined if the file exists in memory based on whether the least significant bit is set
// Other bits are currently undefined but are bitwise-operated because they may be added in the future
if p&1 == 1 {
result++
}
}
return result, nil
}
Comparison of C and Go
- Since Go allows the use of
defer, you won't forget processes that must always be executed at the end of a function.- Such as closing files.
- C cannot return multiple values, so in most cases, when a libc function or system call results in an error, it returns -1 (though this varies by function) and sets an error variable in the global variable
errno.- In Go, you only need to check the
err.
- In Go, you only need to check the
- The Go side generally lacks documentation, so you need to read the libc or system call documentation.
- Since you're essentially just calling them as they are, you can manage by reading those.
- System calls are fundamentally in the world of C, so you need to keep that in mind even when handling them in Go.
- The returned values might be C structures or arrays, and the rules for return values may differ from Go's rules.
- Apart from the code introduced this time, everything else is familiar Go, so you can leverage your Go knowledge for everything except the specific functions shown here.
- By hiding the details of system calls as much as possible within the functions that call them, you can make the program feel like a natural Go program.
- As long as you handle the system call invocation part, the rest is just normal Go, making it actually quite easy to write.
- Go's standard packages hide these tedious parts, so it feels like doing for yourself what the standard packages usually do for you.
Finally
- "Linux System Programming" and "The Go Programming Language" are must-reads.
- Doing system programming in Go is fun, so I highly recommend it.
Discussion