Linux framebuffer что это

Linux.yaroslavl.ru

Скажите, кто из вас не делал этого? Наверняка почти все. Мне просто захотелось все это обобщить и рассмотреть различные варианты настройки. Буду рад всем вашим дополнениям. И наконец — появится первая статья :). Все желающие могут использовать материал данной статьи, но только при наличии ссылки на первоисточник. В статье использован материал с сайта http://kmxb.narod.ru/index.html

Для осуществления сабжа вам будет необходимо несколько вещей:

  • не кривые руки (надо хотя бы иметь опыт компиляции ядра),
  • ОС Linux,
  • ведро линукс больше >=2.4.5 (уточните — не помню когда появился fb). Насчет всего сказанного относительно 2.6 прошу не пинать — сам не проверял.

О чем базар?

Framebuffer — это такая классная штука, которая позволяет нам в текстовом режиме увидеть больше символов чем 80×25, да еще посмотреть картинки и фильмы поверх текста — виндузятники просто помирают от зависти. В дословном переводе означает «кадровый буфер». Когда мы включаем свой компьютер, мы в большинстве своем видим при загрузке как lilo обращается через BIOS к нашей видюхе, а затем и ядро (уже напрямую) выдает на консоль все в том же режиме 80х25. Возникает вопрос — почему же мы владельцы наикрутейших видеокарт с поддержкой vesa 2.0 (с s3tri64v2) и vesa 3.0 (начиная вроде с ривы) должны пользоваться этим наследием доисторических времен, когда компьютеры были большими а программы — маленькими?

Первым делом, первым делом — самолеты.

Наипростейшим решением узнать поддерживает ли ваша карта vesa >=2.0 было бы написать простенькую программку, которая загружается с дискеты и инициализирует vesa, считывая при этом инфу. Но некоторым кажется проще найти какой-нибудь виндозный софт типа sandra-soft- че-то-там или AIDA32. На самом деле это уже ваши проблемы. Могу только заверить, что если у вас agp-карта то она vesa 2.0 точно поддерживает.

Так вот о чем это я.
Заходим в консоли под root’ом в /usr/src/linux
пишем make menuconfig
ставим галку

«Code maturity level options>Prompt for development and/or incomplete code/drivers»

«Console drivers>Frame-buffer support»

все это компилим.
Дальше смотрим в /usr/src/linux/Documentation/fb/vesafb.txt
И что же мы видим?

640×480 800×600 1024×768 1280×1024
256 0x301 0x303 0x305 0x307
32k 0x310 0x313 0x316 0x319
64k 0x311 0x314 0x317 0x31A
16M 0x312 0x315 0x318 0x31B

Это список нужных нам режимов. Т.к. vesa 2.0 не поддерживает смену частоты развертки все режимы на частоте 60Hz. В следующей версии этой статьи будет как этот досадный факт исправить Открываем /etc/lilo.conf (если у вас в качестве загрузщика lilo) и добавляем(. ) вместе с новым ядром строчку типа vga=. вы думаете это число из таблицы? А нифига — берите калькулятор и пересчитывайте все в десятичную систему счисления. Именно добавляем а не исправляем. Не спрашивайте почему. image = /boot/vmlinuz
root = /dev/hda2
label = Linux-fb
read-only
vga=[режим]

После этого пишем lilo и reboot.
После перезагрузки вы должны увидеть мир линукс другими глазами.
Если вывалилось сообщение типа incorrect vga mode press space or enter и т.д то значит на вашей карточке vesafb работать не будет как не старайся. Все вопросы к Gerd Knorr
Это не баг — это фича.
Дополнительно можно проставить параметры модулю vesafb написав в lilo.conf
append=vesa:opt[,opt1[,opt2. ]]

  • ypan — скроллинг работает быстрее за счет того что экран не перерисовывается, а просто изменяется адрес окна в памяти.
  • ywrap — тоже самое, только уже при достижении конца памяти указатель перемещается в начало. Быстрее, чем ypan
  • redraw — самый медленный вариант — перерисовка
  • vgapal и pmipal — при изменении палитры использовать либо стандартные регистры либо через защищенный режим.
  • mtrr — включить использование MemoryTypeRangeRegisters — в кратце это должно ускорить работу. (только на PII и выше)

А теперь поговорим о счастливых (или несчастных) владельцах видеокарт от nVIDIA. Спешл для вас есть модуль rivafb, который мы и попытаемся использовать по-назначению.
Сразу оговорюсь — в X Window вам придется пожертвовать деревами от nvidia(т.е. и ускорением GLX) и поставить nv, иначе все что вы добъетесь — повесившаяся консоль и даже SysRq иногда не спасает.
Для нормальной настройки вам еще понадобится пакет fbset.
По умолчанию при загрузке модуля rivafb инициализируется режим 640×480/8-60Hz Это естественно нас не устраивает и тогда мы при помощи пакета fbset это исправим. Если Вы скомпилили rivafb как модуль, то потрудитесь прописать его загрузку где-нить в одном из скриптов в /etc/rc.d, который исполняется как можно раньше.
Например у меня это /etc/rc.d/rc.sysinit
modprobe rivafb
где-то там можно еще и прописать строку
fbset -a -x .
Не буду перечислять параметры fbset — это не входит в цели данного документа так что RTFM.
Вместо этого опишу файл /etc/fb.modes. В нем находится самое интересное — различные разрешения экрана для fbset.
Чтобы добавить свое любимое разрешение из X достаточно запустить под ним xvidtune и нажать кнопку show. Мы получим т.н. Modeline, который нам теперь предстоит преоброзовать в формат понятный fbset.
Например у меня.

Для этого запускаем /usr/sbin/modeline2fb и пишем в него (например просто вставив все мышкой)

Получаем описание режима и сохраняем его где-нибудь в /etc/fb.modes под другим именем. Глубину цвета указываем в строчке geometry в качестве последнего параметра. Идеальный вариант — 15 бит/пиксель
Все теперь прописываем fbset в скриптах с названием этого режима в качестве параметра.
fbset -x -a 1024×768-70 .

Если вы не сделали такой же ошибки как и я и не стали компилировать rivafb как модуль, а встроили его в ядро то можно забить на fbset и обратиться к /etc/lilo.conf

Параметры из /etc/fb.modes.

теперь мы поимели консоль с нужной нам частотой развертки, но это еще не все. Теперь мы можем запускать mplayer -vo fbdev. Это так к слову. Работает все значительно быстрее чем с vesafb.

Источник

The Frame Buffer DeviceВ¶

Last revised: May 10, 2001

0. IntroductionВ¶

The frame buffer device provides an abstraction for the graphics hardware. It represents the frame buffer of some video hardware and allows application software to access the graphics hardware through a well-defined interface, so the software doesn’t need to know anything about the low-level (hardware register) stuff.

The device is accessed through special device nodes, usually located in the /dev directory, i.e. /dev/fb*.

1. User’s View of /dev/fb*¶

From the user’s point of view, the frame buffer device looks just like any other device in /dev. It’s a character device using major 29; the minor specifies the frame buffer number.

By convention, the following device nodes are used (numbers indicate the device minor numbers):

For backwards compatibility, you may want to create the following symbolic links:

The frame buffer devices are also normal memory devices, this means, you can read and write their contents. You can, for example, make a screen snapshot by:

There also can be more than one frame buffer at a time, e.g. if you have a graphics card in addition to the built-in hardware. The corresponding frame buffer devices (/dev/fb0 and /dev/fb1 etc.) work independently.

Application software that uses the frame buffer device (e.g. the X server) will use /dev/fb0 by default (older software uses /dev/fb0current). You can specify an alternative frame buffer device by setting the environment variable $FRAMEBUFFER to the path name of a frame buffer device, e.g. (for sh/bash users):

or (for csh users):

After this the X server will use the second frame buffer.

2. Programmer’s View of /dev/fb*¶

As you already know, a frame buffer device is a memory device like /dev/mem and it has the same features. You can read it, write it, seek to some location in it and mmap() it (the main usage). The difference is just that the memory that appears in the special file is not the whole memory, but the frame buffer of some video hardware.

/dev/fb* also allows several ioctls on it, by which lots of information about the hardware can be queried and set. The color map handling works via ioctls, too. Look into
for more information on what ioctls exist and on which data structures they work. Here’s just a brief overview:

You can request unchangeable information about the hardware, like name, organization of the screen memory (planes, packed pixels, …) and address and length of the screen memory.

You can request and change variable information about the hardware, like visible and virtual geometry, depth, color map format, timing, and so on. If you try to change that information, the driver maybe will round up some values to meet the hardware’s capabilities (or return EINVAL if that isn’t possible).

You can get and set parts of the color map. Communication is done with 16 bits per color part (red, green, blue, transparency) to support all existing hardware. The driver does all the computations needed to apply it to the hardware (round it down to less bits, maybe throw away transparency).

All this hardware abstraction makes the implementation of application programs easier and more portable. E.g. the X server works completely on /dev/fb* and thus doesn’t need to know, for example, how the color registers of the concrete hardware are organized. XF68_FBDev is a general X server for bitmapped, unaccelerated video hardware. The only thing that has to be built into application programs is the screen organization (bitplanes or chunky pixels etc.), because it works on the frame buffer image data directly.

For the future it is planned that frame buffer drivers for graphics cards and the like can be implemented as kernel modules that are loaded at runtime. Such a driver just has to call register_framebuffer() and supply some functions. Writing and distributing such drivers independently from the kernel will save much trouble…

3. Frame Buffer Resolution MaintenanceВ¶

Frame buffer resolutions are maintained using the utility fbset . It can change the video mode properties of a frame buffer device. Its main usage is to change the current video mode, e.g. during boot up in one of your /etc/rc.* or /etc/init.d/* files.

Fbset uses a video mode database stored in a configuration file, so you can easily add your own modes and refer to them with a simple identifier.

4. The X ServerВ¶

The X server (XF68_FBDev) is the most notable application program for the frame buffer device. Starting with XFree86 release 3.2, the X server is part of XFree86 and has 2 modes:

If the Display subsection for the fbdev driver in the /etc/XF86Config file contains a:

line, the X server will use the scheme discussed above, i.e. it will start up in the resolution determined by /dev/fb0 (or $FRAMEBUFFER, if set). You still have to specify the color depth (using the Depth keyword) and virtual resolution (using the Virtual keyword) though. This is the default for the configuration file supplied with XFree86. It’s the most simple configuration, but it has some limitations.

Therefore it’s also possible to specify resolutions in the /etc/XF86Config file. This allows for on-the-fly resolution switching while retaining the same virtual desktop size. The frame buffer device that’s used is still /dev/fb0current (or $FRAMEBUFFER), but the available resolutions are defined by /etc/XF86Config now. The disadvantage is that you have to specify the timings in a different format (but fbset -x may help).

To tune a video mode, you can use fbset or xvidtune. Note that xvidtune doesn’t work 100% with XF68_FBDev: the reported clock values are always incorrect.

5. Video Mode TimingsВ¶

A monitor draws an image on the screen by using an electron beam (3 electron beams for color models, 1 electron beam for monochrome monitors). The front of the screen is covered by a pattern of colored phosphors (pixels). If a phosphor is hit by an electron, it emits a photon and thus becomes visible.

The electron beam draws horizontal lines (scanlines) from left to right, and from the top to the bottom of the screen. By modifying the intensity of the electron beam, pixels with various colors and intensities can be shown.

After each scanline the electron beam has to move back to the left side of the screen and to the next line: this is called the horizontal retrace. After the whole screen (frame) was painted, the beam moves back to the upper left corner: this is called the vertical retrace. During both the horizontal and vertical retrace, the electron beam is turned off (blanked).

The speed at which the electron beam paints the pixels is determined by the dotclock in the graphics board. For a dotclock of e.g. 28.37516 MHz (millions of cycles per second), each pixel is 35242 ps (picoseconds) long:

If the screen resolution is 640×480, it will take:

to paint the 640 (xres) pixels on one scanline. But the horizontal retrace also takes time (e.g. 272 pixels ), so a full scanline takes:

We’ll say that the horizontal scanrate is about 31 kHz:

A full screen counts 480 (yres) lines, but we have to consider the vertical retrace too (e.g. 49 lines ). So a full screen will take:

The vertical scanrate is about 59 Hz:

This means the screen data is refreshed about 59 times per second. To have a stable picture without visible flicker, VESA recommends a vertical scanrate of at least 72 Hz. But the perceived flicker is very human dependent: some people can use 50 Hz without any trouble, while I’ll notice if it’s less than 80 Hz.

Since the monitor doesn’t know when a new scanline starts, the graphics board will supply a synchronization pulse (horizontal sync or hsync) for each scanline. Similarly it supplies a synchronization pulse (vertical sync or vsync) for each new frame. The position of the image on the screen is influenced by the moments at which the synchronization pulses occur.

The following picture summarizes all timings. The horizontal retrace time is the sum of the left margin, the right margin and the hsync length, while the vertical retrace time is the sum of the upper margin, the lower margin and the vsync length:

The frame buffer device expects all horizontal timings in number of dotclocks (in picoseconds, 1E-12 s), and vertical timings in number of scanlines.

6. Converting XFree86 timing values info frame buffer device timingsВ¶

An XFree86 mode line consists of the following fields:

The frame buffer device uses the following fields:

pixclock: pixel clock in ps (pico seconds)

left_margin: time from sync to picture

right_margin: time from picture to sync

upper_margin: time from sync to picture

lower_margin: time from picture to sync

hsync_len: length of horizontal sync

vsync_len: length of vertical sync

fb: in picoseconds (ps)

pixclock = 1000000 / DCF

left_margin = HFL — SH2

right_margin = SH1 — HR

hsync_len = SH2 — SH1

upper_margin = VFL — SV2

lower_margin = SV1 — VR

vsync_len = SV2 — SV1

Good examples for VESA timings can be found in the XFree86 source tree, under “xc/programs/Xserver/hw/xfree86/doc/modeDB.txt”.

7. ReferencesВ¶

For more specific information about the frame buffer device and its applications, please refer to the Linux-fbdev website:

and to the following documentation:

The manual pages for fbset: fbset(8), fb.modes(5)

The manual pages for XFree86: XF68_FBDev(1), XF86Config(4/5)

Источник

Читайте также:  Windows флешка реестр удалить
Оцените статью