Showing posts with label kernel. Show all posts
Showing posts with label kernel. Show all posts

Nov 19, 2014

User mode Linux

User mode Linux (UML, Линукс пользовательского режима) — вариант ядра Linux, который позволяет запустить несколько виртуализованных Линукс-систем (guests) в качестве обычных приложений в основной Linux‐системе (host).

http://uml.devloop.org.uk/howto.html
http://uml.devloop.org.uk/faq.html
http://user-mode-linux.sourceforge.net/index.html

Запуск

Скачать ядро, скомпилировать:
make defconfig ARCH=um
make ARCH=um

Скачать root_fs, например Debian-Wheezy

Запустить:
host% mkdir /tmp/uml
host% TMPDIR=/tmp/uml ./linux ubda=Debian-Wheezy-AMD64-root_fs mem=1024m
Остановить:
guest% halt

Настройка сети

http://user-mode-linux.sourceforge.net/network.html
host% sudo aptitude install uml-utilities
Добавить пользователя в группу uml-net:
host% sudo vi /etc/group
newgrp uml-net  # login to group

hot-plug it into a running UML:
pCtikQ - umlid, можно найти в папке ~/.uml
uml_console
tuntap - TUN and TAP are virtual-network kernel devices. Being network devices supported entirely in software, they differ from ordinary network devices which are backed up by hardware network adapters
host% uml_mconsole pCtikQ config eth0=tuntap,,,192.168.0.254
# or do it via bash command
host% uml_mconsole `ls -1t ~/.uml | head -n1` config eth0=tuntap,,,192.168.0.254
Enable the device within UML:
guest% ifconfig eth0 192.168.0.253 up
guest% route add default gw 192.168.0.254
Set up NAT on the host in order to communicate with the outside Internet:
host% sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

Запуск в gdb

http://web2.clarkson.edu/class/cs644/kernel/setup/uml/gdb_uml.html
host% TMPDIR=/tmp/uml gdb ./linux
(gdb) handle SIGSEGV pass nostop noprint
(gdb) handle SIGUSR1 pass nostop noprint
(gdb) break netlink_create
(gdb) run ubda=Debian-Wheezy-AMD64-root_fs mem=512m
handle SIGSEGV pass nostop noprint
handle SIGUSR1 pass nostop noprint
r ubda=Debian-Wheezy-AMD64-root_fs mem=512m

Tips on debugging optimized code

The Linux kernel and all kernel modules are always built with optimization on. This is not just for performance reasons: the kernel code requires and assumes that it is optimized and does not function otherwise.

Tips on debugging optimized code

Jun 24, 2014

gcc dumpspecs

gcc -dumpspecs
# ...
# *startfile:
# %{!mandroid|tno-android-ld:%{!shared: %{pg|p|profile:gcrt1.o%s;pie:Scrt1.o%s;:crt1.o%s}}    crti.o%s # %{static:crtbeginT.o%s;shared|pie:crtbeginS.o%s;:crtbegin.o%s};:%{shared: crtbegin_so%O%s;:  %{static: crtbegin_static%O%s;: crtbegin_dynamic%O%s}}}
# ...
http://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Spec-Files.html#Spec-Files

ld --verbose
#...
# OUTPUT_ARCH(i386:x86-64)
# ENTRY(_start)
# SEARCH_DIR("/usr/x86_64-linux-gnu/lib64"); SEARCH_DIR("=/usr/local/lib/x86_64-linux-gnu"); SEARCH_DIR("=/usr/local/lib64"); SEARCH_DIR("=/lib/x86_64-linux-gnu"); SEARCH_DIR("=/lib64"); SEARCH_DIR("=/usr/lib/x86_64-linux-gnu"); SEARCH_DIR("=/usr/lib64"); SEARCH_DIR("=/usr/local/lib"); SEARCH_DIR("=/lib"); # SEARCH_DIR("=/usr/lib");
SECTIONS
# ...
https://sourceware.org/binutils/docs/ld/

May 30, 2014

Kgdb, Kdb

Using kgdb, kdb and the kernel debugger internals

Kgdb is a debug stub that allows another machine to connect a source-level debugger over a serial link.

kdb reuses kgdb's breakpoint and polled I/O infrastructure in order to implement a machine-level kernel debugger that runs entirely on the machine being debugged.

May 19, 2014

Kernel. Misc

# Options
sudo sysctl -a
less /usr/include/linux/sysctl.h

ulimit -a # Sets or reports user resource limits.

cat /proc/sys/kernel/ostype
cat /proc/sys/kernel/osrelease

ls /lib/modules/$(uname -r)/kernel/fs
List open files
lsof -p

File
stat text.txt
file arch.tar.xz
fuser -v server.sock

Inode
ls -i
df -i

Port
fuser -v -n tcp 11100

Interrupts


Timing

Page and buffer cache fadvise, madvise, readahead
pdflush

Apr 27, 2014

The Linux Graphics Stack


The Direct Rendering Manager (DRM) is a device-independent kernel-level device driver that provides support for the Direct Rendering Infrastructure.

Direct Rendering Infrastructure (DRI) is an interface and a free software implementation inside the kernel used by the X Window System/Wayland to securely allow user applications to access the video hardware without requiring data to be passed through the display server. Its primary application is to provide hardware acceleration for the Mesa implementation of OpenGL, which is the core of the DRI OpenGL drivers. Without DRI, programs have to use the CPU while rendering (indirect rendering), which degrades overall performance. DRI has also been adapted to provide OpenGL acceleration on a framebuffer console without a display server running.

Mode setting (KMS) is a software operation that activates a display mode (screen resolution, color depth, and refresh rate) for a computer's display adapter.

Wayland is a protocol that specifies the communication between the display server (called Wayland compositor) and its clients. It was initially designed as a replacement for the X Window System. In stark contrast to the latter, Wayland clients will render without detour directly into their own buffer located in the graphics memory, through the use of EGL with some additional Wayland-specific extensions to EGL.
The display manager is to do the compositing, hence it will incorporate a big chunk of the functionality of current-day compositing window managers. It will composite those buffers to form the on-screen display of application windows. The Wayland protocol is essentially only about input handling and buffer management. The handling of the input hardware relies on evdev in Linux, and similar components in other operating systems.

EGL is an interface between Khronos rendering APIs (such as OpenGL, OpenGL ES or OpenVG) and the underlying native platform windowing system. EGL handles graphics context management, surface/buffer binding, rendering synchronization, and enables "high-performance, accelerated, mixed-mode 2D and 3D rendering using other Khronos APIs." EGL is managed by the non-profit technology consortium Khronos Group.

evdev (for event device) is a component of the Linux kernel for handling input (from keyboards, mice, joysticks, etc.) and a closely related input driver for both the X.Org Server and Wayland compositors. The kernel component is glue code which translates input events from peripheral-specific drivers into a generic structure which the input driver can easily translate into X11 events. Thus every input device with a Linux driver is compatible with the X.Org input driver, making X.Org much easier to configure.

Mesa is a collection of free and open-source libraries that implement OpenGL and several other APIs related to hardware-accelerated 3D rendering, 3D computer graphics and GPGPU.

Mar 19, 2014

Kernel. Power management

cat /sys/module/cpuidle/parameters/off

cd /sys/devices/system/cpu/cpu0/cpuidle
cat */power
cat */usage

C-State
powertop

The cpuidle subsystem

Feb 15, 2014

Kernel. Networking

struct sk_buff

struct net_device
devices: eth ppp asdn atm
rx recieve
tz transmit

Explicit Congestion Notification (ECN) — (Явное Уведомление о Перегруженности)
ls -l /sys/class/net

cat /proc/net/sockstat
cat /proc/net/dev
cat /proc/net/tcp  # ports
cat /proc/net/udp
cat /proc/net/unix
Nearly all cards support DMA mode

IPv4
IPv6

UDP
TCP

mtu maximum transmission unit
ARP address resolution protocol
NAT network address translation; masquerading
transparent proxy
netfilter; iptables
finite state machine конечный автомат
tcpdump witeshark
tshark -V -2 -R 'ip.addr==208.118.235.148'

# http://stackoverflow.com/questions/5907527/application-control-of-tcp-retransmission-on-linux
/proc/sys/net/ipv4/tcp_retries2

man 5 socketckall

man 3 netlink
man 5 netlink
/proc/net/netlink

Feb 3, 2014

Extended file attributes, ACL

Does file system support?
sudo tune2fs -l /dev/sda1 | grep "Default mount options:"
# Default mount options:    user_xattr acl
Extended file attributes

Extended attributes: the good, the not so good, the bad.
On Linux and FreeBSD, cp will only preserve xattrs if given the option --preserve=xattr, also implied by the -a option. cp will not duplicate attributes by default, which is a reasonable default choice, even if it will be wrong in some situations (where you will have to use the options).

Extended Attributes – lsattr and chattr
  • a : append only 
  • c : compressed 
  • d : no dump 
  • e : extent format 
  • i : immutable 
  • j : data journalling 
  • s : secure deletion 
  • t : no tail-merging 
  • u : undeletable 
  • A : no atime updates 
  • C : no copy on write 
  • D : synchronous directory updates 
  • S : synchronous updates 
  • T : top of directory hierarchy
lsattr test.txt
chattr -a test.txt
SELinux (англ. Security-Enhanced Linux — Linux с улучшенной безопасностью) — реализация системы принудительного контроля доступа, которая может работать параллельно с классической дискреционной системой контроля доступа. Входит в стандартное ядро Linux. Также для функционирования SELinux требуются модифицированные версии некоторых утилит (ps, ls, и тд), которые обеспечивают поддержку новых функций ядра, и поддержка со стороны файловой системы.
setfattr -n user.comment -v "this is a comment" testfile
getfattr testfile
# user.comment
getfattr -n user.comment testfile
# user.comment="this is a comment"

POSIX Access Control Lists on Linux
DAC model
man 5 acl
getfacl dir
setfacl -m user:joe:rwx dir
man chacl

Jan 23, 2014

Kernel. Modules, program exec, syscalls, elf

man 2 syscalls
system_call()
strace -e trace=open date
strace -c date

ltrace -T -S rmdir t
ltrace -c -S rmdir t
ldd `which python`
Elf
# view headers, section...
readelf -a a.out
readelf --sections=vmlinux a.out
readelf --dynamic a.out

# disassembly
objdump -M intel -S a.out

# list symbols from object files
nm a.out

# dependencies resolved from this list
cat /proc/kallsyms | grep printk

cat /boot/System.map-3.13.0 | grep printk

stat a.out
file a.out
Modules
# list modules
lsmod

# Modules dependencies
cat /lib/modules/3.12.7/modules.dep | grep vboxdrv
man depmod

# info
modinfo vboxdrv

# view system device information
systool -v -m vboxdrv
struct module
sys_init_module() -> load_module()
sys_delete_module()
request_module()
hello world module
man 2 init_module
man 2 delete_module

# which module loader
cat /proc/sys/kernel/modprobe
sudo sysctl -a | grep modprobe

man modprobe
man insmod
man rmmod

ll /sbin/udevd

udevadm monitor
cat /proc/sys/kernel/taintined
dmesg | grep taint

Linux kernel. Devices and drivers

cat /proc/partitions
cat /proc/devices

tmpfs
df -h # tmpfs and subfolders v
udev
ps aux | grep [u]dev  # demons
udevadm monitor  # new devices

struct gendisk
add_disk()

struct block_device
struct block_device_operations
struct request_queue
struct request

sumit_bio()
generic_make_request

Linux I/O Scheduler
struct elevator_ops
vfs_ioctl() - call filesystem specific ioctl methods
man 2 ioctl # control device

I/O ports and I/O memmory vs DMA
IOMMU
cat /proc/ioports
cat /proc/mem
struct device
struct bus_type
bus_register()

sysfs vs Kernfs introduced in 3.14
ll /sys/block
ll /sys/bus/pci/

ISA, PCI, PCI Express

struct pci_bus
struct pci_dev
struct pci_driver




Vfs
struct inode
struct inode_operations
dmesg|grep Inode
#[    0.001283] Inode-cache hash table entries: 262144 (order: 9, 2097152 bytes)

struct file_struct - opened by process

struct file
struct file_operations

RCU

struct dentry
struct dentry_operations

NFS, AFS, SMB (CIFS)

struct super_block

mount
ll /dev/disk/by-*

ramfs, tmpfs, sysfs, procfs, debugfs CONFIG_DEBUG_FS
cat /proc/filesystems
ll /proc/buddyinfo
cat /proc/buddyinfo
cat /proc/slabinfo
sudo cat /proc/slabinfo
cat /proc/vmstat
cat /proc/kallsyms
ll /proc/kcore  # + gdb, ddd
cat /proc/interrupts

sys_open() - adds fd to current->fs
ACL
Ext2 reservation window


Ext3
writeback, ordered, journal

Jan 21, 2014

Arch

OpenRISC — открытый микропроцессор архитектуры RISC с открытым исходным кодом на языке описания аппаратного обеспечения Verilog. Проект создан сообществом OpenCores и распространяется по лицензии GNU LGPL. OpenRISC воплощён аппаратно и успешно производится в виде интегральных микросхем и ПЛИС (PLD).

SPARC - SPARC (Scalable Processor ARChitecture — масштабируемая архитектура процессора) — архитектура RISC-микропроцессоров, первоначально разработанная в 1985 году компанией Sun Microsystems.
МЦСТ R1000 (NUMA)

ARM (Advanced RISC Machine, Acorn RISC Machine, усовершенствованная RISC-машина) — семейство лицензируемых 32-битных и 64-битных микропроцессорных ядер разработки компании ARM Limited.

MIPS (англ. Microprocessor without Interlocked Pipeline Stages) — микропроцессор, разработанный компанией MIPS Computer Systems (в настоящее время MIPS Technologies) в соответствии с концепцией проектирования процессоров RISC (то есть для процессоров с сокращенным набором команд).

DEC Alpha (также известный как Alpha AXP) — 64-разрядный RISC микропроцессор, первоначально разработанный и произведённый компанией DEC, которая использовала его в собственной линейке рабочих станций и серверов.

PowerPC (или сокращённо PPC) — микропроцессорная RISC-архитектура, созданная в 1991 году альянсом компаний Apple, IBM и Motorola, известным как AIM.

IA-64 (also called Intel Itanium architecture) is the architecture of the Itanium family of 64-bit of Intel microprocessors. The architecture originated at Hewlett-Packard (HP), and was later jointly developed by HP and Intel.
The Itanium architecture is based on explicit instruction-level parallelism, in which the compiler decides which instructions to execute in parallel. This contrasts with other superscalar architectures, which depend on the processor to manage instruction dependencies at runtime. In all Itanium models, up to and including Tukwila, cores execute up to six instructions per clock cycle. The first Itanium processor, codenamed Merced, was released in 2001.

IA-32 (i386) (Intel Architecture, 32-bit, sometimes called i386 through metonymy) is the title of the third generation of x86 architecture, first implemented in the Intel 80386 microprocessors in 1985. It was the first incarnation of x86 to support 32-bit computing. As such, "IA-32" may be used as a metonym to refer to all x86 versions that supported 32-bit computing.

x86-64 (x64) — 64-битная аппаратная платформа (чипсет и архитектура набора команд), разработанная компанией AMD для выполнения 64-разрядных приложений.
Это расширение архитектуры x86 с почти полной обратной совместимостью.

List of Linux supported architectures
Modern Microprocessors. A 90 Minute Guide!

Jan 17, 2014

Kernel and Hardware Abbriviations


ASMP - Asymmetric multiprocessing
SMP - Symmetric Multiprocessing
Регистр процессора
OOO - Внеочередное исполнение (англ. Out-of-order execution) likely, unlikely
Кэш процессора
Алгоритмы кэширования: LRU - Least Recently Used; MRU - Most Recently Used
Выравнивание данных


UMA - Uniform Memory Access
NUMA - Non-Uniform Memory Access

BIOS  SLIC - Software Licensing Description Table
UEFI, EFI Extensible Firmware Interface (англ. Расширяемый интерфейс прошивки) — интерфейс между операционной системой и микропрограммами, управляющими низкоуровневыми функциями оборудования, его основное предназначение: корректно инициализировать оборудование при включении системы и передать управление загрузчику операционной системы. EFI предназначен для замены BIOS — интерфейса, который традиционно используется всеми IBM PC-совместимыми персональными компьютерами.
ACPI - Advanced Configuration and Power Interface — усовершенствованный интерфейс управления конфигурацией и питанием. Suspend, Hibernate
e820 - Функция прерывания 15H BIOS персонального компьютера, использующаяся для получения информации о распределении адресного пространства, имеющейся оперативной памяти и зарезервированных адресах.
DMI - (Desktop Management Interface) — интерфейс программирования приложений (API), позволяющий программному обеспечению собирать данные о характеристиках компьютера. dmidecode
RAM
ROM - Постоянное запоминающее устройство (ПЗУ)

MMU - Блок управления памятью или устройство управления памятью (англ. memory management unit)
PAE - Physical Address Extension — режим работы встроенного блока управления памятью x86-совместимых процессоров, в котором используются 64-битные элементы таблиц страниц, c помощью которых процессор может адресовать 64 ГБ физической памяти (вместо 4 ГБ, адресуемых при использовании 32-разрядных таблиц), хотя каждая задача (программа) всё равно может адресовать максимум до 4 ГБ виртуальной памяти. Также, в новых моделях процессоров в PAE-режиме старший бит элемента таблицы страниц отвечает за запрет исполнения кода в странице, что затрудняет атаку по методу переполнения буфера.
NX bit - No eXecute Bit
PSE - Page Size Extension (PSE) — режим работы встроенного блока управления памятью x86-совместимых процессоров, в котором используются страницы размером в 4 (32-битные таблицы страниц) или 2 мегабайта (PAE/AMD64, 64-битные таблицы), в дополнение к обычным страницам x86 архитектуры в 4 килобайта.
DMA - Прямой доступ к памяти
TLB - Буфер ассоциативной трансляции (англ. Translation lookaside buffer, TLB) — это специализированный кэш центрального процессора, используемый для ускорения трансляции адреса виртуальной памяти в адрес физической памяти.
PGD - Global
PUD - Upper
PMD - Middle
PTE- Page Table entry

Slab Slub Slob
ASLR Address space layout randomization — технология, применяемая в операционных системах, при использовании которой случайным образом изменяется расположение в адресном пространстве процесса важных структур, а именно: образа исполняемого файла, подгружаемых библиотек, кучи и стека.


Completely Fair Scheduler
Round robin scheduling
FIFO - First In, First Out /usr/include/x86_64-linux-gnu/sys/queue.h

Jan 3, 2014

Linux kernel. Scheduler

priority to load weight
load balancing, kmigrate

run queues, sched entities:
cat /proc/sched_debug
# Sched Debug Version: v0.11, 3.13.6 #4
# ktime                                   : 11620320.261793
# sched_clk                               : 11629180.728702
# cpu_clk                                 : 11629180.728834
# jiffies                                 : 4297797377
# sched_clock_stable                      : 1
# 
# cpu#0, 3077.541 MHz
#   .nr_running                    : 0
#   .load                          : 0
#   .nr_switches                   : 10802526
#   .nr_load_updates               : 1998334
#   .nr_uninterruptible            : -2228
#   .next_balance                  : 4297.797394
# .....
# rt_rq[0]:/
#   .rt_nr_running                 : 0
#   .rt_throttled                  : 0
#   .rt_time                       : 0.011064
#   .rt_runtime                    : 950.000000
# 
# runnable tasks:
#             task   PID         tree-key  switches  prio     exec-runtime ...
# ------------------------------------------------------------------------ ...
#      ksoftirqd/0     3    875652.689495     83449   120    875652.689495 ...
#     kworker/0:0H     5      3837.050667         6   100      3837.050667 ...
#        rcu_sched     7    875652.806577    388480   120    875652.806577 ...
sudo cat /proc/schedstat
cat /proc/PID/sched
cat /proc/PID/limits
ls /proc/sys/kernel | grep sched
sudo sysctl -A | grep sched
Real time policy (priority 90):
sudo chrt -r -p 90 22336
SCHED_RR implements a round robin method
SCHED_FIFO uses a first in, first out mechanism
schedtool -h

struct thread_info
struct task_struct
struct nsproxy

do_fork()
do_execve()
kernel_thread()

struct sched_class
struct rq
struct sched_entity
scheduler_tick()
context_switch()

struct sched_class fair_sched_class
check_preempt_tick()

struct sched_class rt_sched_class
task_tick_rt()

New in 3.14
Earliest deadline first scheduling
struct sched_class dl_sched_class
task_tick_dl()

find_busiest_queue() compares rqs load weights

Dec 19, 2013

kernel man 9

make mandocs
make installmandocs

Dec 14, 2013

Dec 5, 2013

Linux I/O Scheduler

Selecting a Linux I/O Scheduler
How do I change I/O scheduler?

cat /sys/block/sda/queue/scheduler
echo noop > /sys/block/sda/queue/scheduler
In /etc/default/grub change
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
to
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash elevator=noop"
Then run
sudo update-grub2
and restart.