diff --git a/documentation/content/de/books/handbook/config/_index.adoc b/documentation/content/de/books/handbook/config/_index.adoc index c3ca5b53f3..3bfdc51759 100644 --- a/documentation/content/de/books/handbook/config/_index.adoc +++ b/documentation/content/de/books/handbook/config/_index.adoc @@ -1,1527 +1,1527 @@ --- title: Kapitel 11. Konfiguration und Tuning part: Teil III. Systemadministration prev: books/handbook/partiii next: books/handbook/boot showBookMenu: true weight: 15 path: "/books/handbook/" --- [[config-tuning]] = Konfiguration und Tuning :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 11 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/config/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[config-synopsis]] == Übersicht Die richtige Systemkonfiguration ist einer der wichtigsten Aspekte unter FreeBSD. Dieses Kapitel beschreibt die Konfiguration von FreeBSD sowie Maßnahmen zur Leistungssteigerung von FreeBSD-Systemen. Nachdem Sie dieses Kapitel durchgearbeitet haben, werden Sie Folgendes wissen: * Die Grundlagen der Konfiguration von [.filename]#rc.conf# und die Skripte zum Starten von Anwendungen in [.filename]#/usr/local/etc/rc.d#. * Wie Sie Netzwerkkarten konfigurieren und testen. * Wie Sie virtuelle Hosts und Netzwerkgeräte konfigurieren. * Wie Sie die verschiedenen Konfigurationsdateien in [.filename]#/etc# benutzen. * Wie Sie mit FreeBSD mit man:sysctl[8]-Variablen einstellen können. * Wie Sie die Platten-Performance einstellen und Kernel-Parameter modifizieren können. Bevor Sie dieses Kapitel lesen, sollten Sie * die Grundlagen von UNIX(R) und FreeBSD (crossref:basics[basics,Grundlagen des FreeBSD Betriebssystems]) verstehen. * Damit vertraut sein, wie Sie einen Kernel konfigurieren und kompilieren (crossref:kernelconfig[kernelconfig,Konfiguration des FreeBSD-Kernels]). [[configtuning-starting-services]] == Start von Diensten Viele Benutzer installieren Software Dritter auf FreeBSD mithilfe der Ports-Sammlung. Häufig soll die Software bei einem Systemstart mitgestartet werden. Beispielsweise sollen die Dienste package:mail/postfix[] oder package:www/apache22[] nach einem Systemstart laufen. Dieser Abschnitt stellt die Startprozeduren für Software Dritter vor. Unter FreeBSD werden die meisten der im System enthaltenen Dienste wie man:cron[8] mithilfe von Systemskripten gestartet. === Dienste über das [.filename]#rc.d#-System starten Mit [.filename]#rc.d# lässt sich der Start von Anwendungen besser steuern und es sind mehr Funktionen verfügbar. Mit den in <> besprochenen Schlüsselwörtern können Anwendungen in einer bestimmten Reihenfolge gestartet werden und Optionen können in [.filename]#rc.conf# statt fest im Startskript der Anwendung festgelegt werden. Ein einfaches Startskript sieht wie folgt aus: [.programlisting] .... #!/bin/sh # # PROVIDE: utility # REQUIRE: DAEMON # KEYWORD: shutdown . /etc/rc.subr name=utility rcvar=utility_enable command="/usr/local/sbin/utility" load_rc_config $name # # DO NOT CHANGE THESE DEFAULT VALUES HERE # SET THEM IN THE /etc/rc.conf FILE # utility_enable=${utility_enable-"NO"} pidfile=${utility_pidfile-"/var/run/utility.pid"} run_rc_command "$1" .... Dieses Skript stellt sicher, dass `utility` nach den `DAEMON`-Pseudodiensten gestartet wird. Es stellt auch eine Methode bereit, die Prozess-ID (PID) der Anwendung in einer Datei zu speichern. In [.filename]#/etc/rc.conf# könnte für diese Anwendung die folgende Zeile stehen: [.programlisting] .... utility_enable="YES" .... Die Methode erleichtert den Umgang mit Kommandozeilenargumenten, bindet Funktionen aus [.filename]#/etc/rc.subr# ein, ist kompatibel zu man:rcorder[8] und lässt sich über [.filename]#rc.conf# leichter konfigurieren. === Andere Arten, um Dienste zu starten Andere Dienste können über man:inetd[8] gestartet werden. Die Konfiguration von man:inetd[8] wird in crossref:network-servers[network-inetd,“Der inetd Super-Server”] ausführlich beschrieben. Systemdienste können auch mit man:cron[8] gestartet werden. Dieser Ansatz hat einige Vorteile; nicht zuletzt, weil man:cron[8] die Prozesse unter dem Eigentümer der [.filename]#crontab# startet, ist es möglich, dass Dienste von normalen Benutzern gestartet und gepflegt werden können. Für die Zeitangabe in man:cron[8] kann `@reboot` eingesetzt werden. Damit wird das Kommando gestartet, wenn man:cron[8] kurz nach dem Systemboot gestartet wird. [[configtuning-cron]] == man:cron[8] konfigurieren Ein sehr nützliches Werkzeug von FreeBSD ist cron. Dieses Programm läuft im Hintergrund und überprüft fortlaufend [.filename]#/etc/crontab# und [.filename]#/var/cron/tabs#. In diesen Dateien wird festgelegt, welche Programme zu welchem Zeitpunkt von cron ausgeführt werden sollen. Jede Zeile in diesen Dateien definiert eine auszuführende Aufgabe, die auch als _Cronjob_ bezeichnet wird. Das Werkzeug verwendet zwei verschiedene Konfigurationsdateien: die System-crontab, welche nicht verändert werden sollte und die Benutzer-crontabs, die nach Bedarf erstellt und geändert werden können. Das Format, dass von diesen beiden Dateien verwendet wird, ist in man:crontab[5] dokumentiert. Das Format der System-crontab in [.filename]#/etc/crontab# enthält das Feld `who`, das in der Benutzer-crontab nicht existiert. Dieses Feld gibt den Benutzer an, mit dem die Aufgabe ausgeführt wird. Die Aufgaben in den Benutzer-crontabs laufen unter dem Benutzer, der die crontab erstellt hat. Benutzer-crontabs erlauben es den Benutzern, ihre eigenen Aufgaben zu planen. Der Benutzer `root` kann auch seine eigene Benutzer-crontab haben, um Aufgaben zu planen, die nicht in der System-crontab existieren. Hier ist ein Beispieleintrag aus der System-crontab, [.filename]#/etc/crontab#: [.programlisting] .... # /etc/crontab - root's crontab for FreeBSD # # $FreeBSD$ # <.> SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin <.> # #minute hour mday month wday who command <.> # */5 * * * * root /usr/libexec/atrun <.> .... <.> Das Zeichen `#` am Zeilenanfang leitet einen Kommentar ein. Benutzen Sie Kommentare, um die Funktion eines Eintrags zu erläutern. Kommentare müssen in einer extra Zeile stehen. Sie können nicht in derselben Zeile wie ein Kommando stehen, da sie sonst Teil des Kommandos wären. Leerzeilen in dieser Datei werden ignoriert. <.> Umgebungsvariablen werden mit dem Gleichheits-Zeichen (`=`) festgelegt. Im Beispiel werden die Variablen `SHELL`, `PATH` und `HOME` definiert. Wenn die Variable `SHELL` nicht definiert wird, benutzt cron die Bourne Shell. Wird die Variable `PATH` nicht gesetzt, müssen alle Pfadangaben absolut sein, da es keinen Vorgabewert für `PATH` gibt. <.> In dieser Zeile werden sieben Felder der System-crontab beschrieben: `minute`, `hour`, `mday`, `month`, `wday`, `who` und `command`. Das Feld `minute` legt die Minute fest in der die Aufgabe ausgeführt wird, das Feld `hour` die Stunde, das Feld `mday` den Tag des Monats. Im Feld `month` wird der Monat und im Feld `wday` der Wochentag festgelegt. Alle Felder müssen numerische Werte enthalten und die Zeitangaben sind im 24-Stunden-Format. Das Zeichen `*` repräsentiert dabei alle möglichen Werte für dieses Feld. Das Feld `who` gibt es nur in der System-crontab und gibt den Account an, unter dem das Kommando laufen soll. Im letzten Feld wird schließlich das auszuführende Kommando angegeben. <.> Diese Zeile definiert die Werte für den Cronjob. Die Zeichenfolge `\*/5` gefolgt von mehreren `*`-Zeichen bedeutet, dass `/usr/libexec/atrun` von `root` alle fünf Minuten aufgerufen wird.Bei den Kommandos können beliebig viele Optionen angegeben werden. Wenn das Kommando zu lang ist und auf der nächsten Zeile fortgesetzt werden soll, muss am Ende der Zeile das Fortsetzungszeichen (`\`) angegeben werden. [[configtuning-installcrontab]] === Eine Benutzer-crontab erstellen Rufen Sie `crontab` im Editor-Modus auf, um eine Benutzer-crontab zu erstellen: [source,shell] .... % crontab -e .... Dies wird die crontab des Benutzers mit dem voreingestellten Editor öffnen. Wenn der Benutzer diesen Befehl zum ersten Mal ausführt, wird eine leere Datei geöffnet. Nachdem der Benutzer eine crontab erstellt hat, wird die Datei mit diesem Kommando zur Bearbeitung geöffnet. Es empfiehlt sich, die folgenden Zeilen an den Anfang der crontab-Datei hinzuzufügen, um die Umgebungsvariablen zu setzen und die einzelnen Felder zu beschreiben: [.programlisting] .... SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin # Order of crontab fields # minute hour mday month wday command .... Fügen Sie dann für jedes Kommando oder Skript eine Zeile hinzu, mit der Angabe wann das Kommando ausgeführt werden soll. In diesem Beispiel wird ein Bourne Shell Skript täglich um 14:00 Uhr ausgeführt. Da der Pfad zum Skript nicht in `PATH` enthalten ist, wird der vollständige Pfad zum Skript angegeben: [.programlisting] .... 0 14 * * * /usr/home/dru/bin/mycustomscript.sh .... [TIP] ==== Bevor Sie ein eigenes Skript verwenden, stellen Sie sicher, dass es ausführbar ist und dass es mit den wenigen Umgebungsvariablen von cron funktioniert. Um die Umgebung nachzubilden, die der obige cron-Eintrag bei der Ausführung verwenden würde, benutzen Sie dieses Kommando: [source,shell] .... % env -i SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin HOME=/home/dru LOGNAME=dru /usr/home/dru/bin/mycustomscript.sh .... Die Umgebung von cron wird in man:crontab[5] beschrieben. Es ist wichtig, dass sichergestellt wird, dass die Skripte in der Umgebung von cron korrekt arbeiten, besonders wenn Befehle enthalten sind, welche Dateien mit Wildcards löschen. ==== Wenn Sie mit der Bearbeitung der crontab fertig sind, speichern Sie die Datei. Sie wird automatisch installiert und cron wird die darin enthalten Cronjobs zu den angegebenen Zeiten ausführen. Um die Cronjobs in einer crontab aufzulisten, verwenden Sie diesen Befehl: [source,shell] .... % crontab -l 0 14 * * * /usr/home/dru/bin/mycustomscript.sh .... Um alle Cronjobs einer Benutzer-crontab zu löschen, verwenden Sie diesen Befehl: [source,shell] .... % crontab -r remove crontab for dru? y .... [[configtuning-rcd]] == Dienste unter FreeBSD verwalten FreeBSD verwendet die vom man:rc[8]-System bereit gestellten Startskripten beim Systemstart und für die Verwaltung von Diensten. Die Skripte sind in [.filename]#/etc/rc.d# abgelegt und bieten grundlegende Dienste an, die über die Optionen `start`, `stop` und `restart` des man:service[8] Kommandos kontrolliert werden können. Beispielsweise kann man:sshd[8] mit dem nachstehenden Kommando neu gestartet werden: [source,shell] .... # service sshd restart .... Analog können Sie andere Dienste starten und stoppen. Normalerweise werden die Dienste beim Systemstart über Einträge in der Datei man:rc.conf[5] automatisch gestartet. man:natd[8] wird zum Beispiel mit dem folgenden Eintrag in [.filename]#/etc/rc.conf# aktiviert: [.programlisting] .... natd_enable="YES" .... Wenn dort bereits die Zeile `natd_enable="NO"` existiert, ändern Sie `NO` in `YES`. Die man:rc[8]-Skripten starten, wie unten beschrieben, auch abhängige Dienste. Da das man:rc[8]-System primär zum automatischen Starten und Stoppen von Systemdiensten dient, funktionieren die Optionen `start`, `stop` und `restart` nur, wenn die entsprechenden Variablen in [.filename]#/etc/rc.conf# gesetzt sind. Beispielsweise funktioniert `sshd restart` nur dann, wenn in [.filename]#/etc/rc.conf# die Variable `sshd_enable` auf `YES` gesetzt wurde. Wenn Sie die Optionen `start`, `stop` oder `restart` unabhängig von den Einstellungen in [.filename]#/etc/rc.conf# benutzen wollen, müssen Sie den Optionen mit dem Präfix "one" verwenden. Um beispielsweise `sshd` unabhängig von den Einstellungen in [.filename]#/etc/rc.conf# neu zu starten, benutzen Sie das nachstehende Kommando: [source,shell] .... # service sshd onerestart .... Ob ein Dienst in [.filename]#/etc/rc.conf# aktiviert ist, können Sie herausfinden, indem Sie das entsprechende man:rc[8]-Skript mit der Option `rcvar` aufrufen. Dieses Beispiel prüft, ob der `sshd`-Dienst in [.filename]#/etc/rc.conf# aktiviert ist: [source,shell] .... # service sshd rcvar # sshd # sshd_enable="YES" # (default: "") .... [NOTE] ==== Die Zeile `# sshd` wird von dem Kommando ausgegeben; sie kennzeichnet nicht die Eingabeaufforderung von `root`. ==== Ob ein Dienst läuft, kann mit `status` abgefragt werden. Das folgende Kommando überprüft, ob `sshd` auch wirklich gestartet wurde: [source,shell] .... # service sshd status sshd is running as pid 433. .... Einige Dienste können über die Option `reload` neu initialisiert werden. Dazu wird dem Dienst über ein Signal mitgeteilt, dass er seine Konfigurationsdateien neu einlesen soll. Oft wird dazu das Signal `SIGHUP` verwendet. Beachten Sie aber, dass nicht alle Dienste diese Option unterstützen. Die meisten Systemdienste werden beim Systemstart vom man:rc[8]-System gestartet. Zum Beispiel aktiviert das Skript [.filename]#/etc/rc.d/bgfsck# die Prüfung von Dateisystemen im Hintergrund. Das Skript gibt die folgende Meldung aus, wenn es gestartet wird: [source,shell] .... Starting background file system checks in 60 seconds. .... Dieses Skript wird während des Systemstarts ausgeführt und führt eine Überprüfung der Dateisysteme im Hintergrund durch. Viele Systemdienste hängen von anderen Diensten ab. man:yp[8] und andere RPC-basierende Systeme hängen beispielsweise von dem `rpcbind`-Dienst ab. Im Kopf der Startskripten befinden sich die Informationen über Abhängigkeiten von anderen Diensten und weitere Metadaten. Mithilfe dieser Daten bestimmt das Programm man:rcorder[8] beim Systemstart die Startreihenfolge der Dienste. Folgende Schlüsselwörter müssen im Kopf aller Startskripten verwendet werden, da sie von man:rc.subr[8] zum "Aktivieren" des Startskripts benötigt werden: * `PROVIDE`: Gibt die Namen der Dienste an, die mit dieser Datei zur Verfügung gestellt werden. Die folgenden Schlüsselwörter können im Kopf des Startskripts angegeben werden. Sie sind zwar nicht unbedingt notwendig, sind aber hilfreich beim Umgang mit man:rcorder[8]: * `REQUIRE`: Gibt die Namen der Dienste an, von denen dieser Dienst abhängt. Ein Skript, das dieses Schlüsselwort enthält wird _nach_ den angegebenen Diensten ausgeführt. * `BEFORE`: Zählt Dienste auf, die auf diesen Dienst angewiesen sind. Ein Skript, dass dieses Schlüsselwort enthält wird _vor_ den angegebenen Diensten ausgeführt. Durch das Verwenden dieser Schlüsselwörter kann ein Administrator die Startreihenfolge von Systemdiensten feingranuliert steuern, ohne mit den Schwierigkeiten des "runlevel"-Systems anderer UNIX(R) Systeme kämpfen zu müssen. Weitere Informationen über das man:rc[8]-System finden Sie in man:rc[8] und man:rc.subr[8]. Wenn Sie eigene [.filename]#rc.d#-Skripte schreiben wollen, sollten Sie extref:{rc-scripting}[diesen Artikel] lesen. [[configtuning-core-configuration]] === Systemspezifische Konfiguration Informationen zur Systemkonfiguration sind hauptsächlich in [.filename]#/etc/rc.conf#, die meist beim Start des Systems verwendet wird, abgelegt. Sie enthält die Konfigurationen für die [.filename]#rc*# Dateien. In [.filename]#rc.conf# werden die Vorgabewerte aus [.filename]#/etc/defaults/rc.conf# überschrieben. Die Vorgabedatei sollte nicht editiert werden. Stattdessen sollten alle systemspezifischen Änderungen in [.filename]#rc.conf# vorgenommen werden. Um den administrativen Aufwand gering zu halten, existieren in geclusterten Anwendungen mehrere Strategien, globale Konfigurationen von systemspezifischen Konfigurationen zu trennen. Der empfohlene Weg hält die globale Konfiguration in einer separaten Datei z.B. [.filename]#/etc/rc.conf.local#. Zum Beispiel so: * [.filename]#/etc/rc.conf#: + [.programlisting] .... sshd_enable="YES" keyrate="fast" defaultrouter="10.1.1.254" .... * [.filename]#/etc/rc.conf.local#: + [.programlisting] .... hostname="node1.example.org" ifconfig_fxp0="inet 10.1.1.1/8" .... [.filename]#/etc/rc.conf# kann dann auf jedes System mit rsync oder puppet verteilt werden, während [.filename]#/etc/rc.conf.local# dabei systemspezifisch bleibt. Bei einem Upgrade des Systems wird [.filename]#/etc/rc.conf# nicht überschrieben, so dass die Systemkonfiguration erhalten bleibt. [TIP] ==== [.filename]#/etc/rc.conf# und [.filename]#/etc/rc.conf.local# werden von man:sh[1] gelesen. Dies erlaubt es dem Systemadministrator, komplexe Konfigurationsszenarien zu erstellen. Lesen Sie man:rc.conf[5], um weitere Informationen zu diesem Thema zu erhalten. ==== [[config-network-setup]] == Einrichten von Netzwerkkarten Die Konfiguration einer Netzwerkkarte gehört zu den alltäglichen Aufgaben eines FreeBSD Administrators. === Bestimmen des richtigen Treibers Ermitteln Sie zunächst das Modell der Netzwerkkarte und den darin verwendeten Chip. FreeBSD unterstützt eine Vielzahl von Netzwerkkarten. Prüfen Sie die Hardware-Kompatibilitätsliste für das FreeBSD Release, um zu sehen ob die Karte unterstützt wird. Wenn die Karte unterstützt wird, müssen Sie den Treiber für die Karte bestimmen. [.filename]#/usr/src/sys/conf/NOTES# und [.filename]#/usr/src/sys/arch/conf/NOTES# enthalten eine Liste der verfügbaren Treiber mit Informationen zu den unterstützten Chipsätzen. Wenn Sie sich nicht sicher sind, ob Sie den richtigen Treiber ausgewählt haben, lesen Sie die Hilfeseite des Treibers. Sie enthält weitere Informationen über die unterstützten Geräte und bekannte Einschränkungen des Treibers. Die Treiber für gebräuchliche Netzwerkkarten sind schon im [.filename]#GENERIC#-Kernel enthalten, so dass die Karte während des Systemstarts erkannt werden sollte. Die Systemmeldungen können Sie sich mit `more /var/run/dmesg.boot` ansehen. Mit der Leertaste können Sie durch den Text blättern. In diesem Beispiel findet das System zwei Karten, die den man:dc[4]-Treiber benutzen: [source,shell] .... dc0: <82c169 PNIC 10/100BaseTX> port 0xa000-0xa0ff mem 0xd3800000-0xd38 000ff irq 15 at device 11.0 on pci0 miibus0: on dc0 bmtphy0: PHY 1 on miibus0 bmtphy0: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc0: Ethernet address: 00:a0:cc:da:da:da dc0: [ITHREAD] dc1: <82c169 PNIC 10/100BaseTX> port 0x9800-0x98ff mem 0xd3000000-0xd30 000ff irq 11 at device 12.0 on pci0 miibus1: on dc1 bmtphy1: PHY 1 on miibus1 bmtphy1: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc1: Ethernet address: 00:a0:cc:da:da:db dc1: [ITHREAD] .... Ist der Treiber für die Netzwerkkarte nicht in [.filename]#GENERIC# enthalten, muss zunächst ein Treiber geladen werden, um die Karte konfigurieren und benutzen zu können. Dafür gibt es zwei Methoden: * Am einfachsten ist es, das Kernelmodul für die Karte mit man:kldload[8] zu laden. Um den Treiber automatisch beim Systemstart zu laden, fügen Sie die entsprechende Zeile in [.filename]#/boot/loader.conf# ein. Es gibt nicht für alle Karten Kernelmodule. * Alternativ kann der Treiber für die Karte fest in den Kernel eingebunden werden. Lesen Sie dazu [.filename]#/usr/src/sys/conf/NOTES#, [.filename]#/usr/src/sys/arch/conf/NOTES# und die Hilfeseite des Treibers, den Sie in den Kernel einbinden möchten, an. Die Übersetzung des Kernels wird in crossref:kernelconfig[kernelconfig,Konfiguration des FreeBSD-Kernels] beschrieben. Wenn die Karte während des Systemstarts vom Kernel erkannt wurde, muss der Kernel nicht neu übersetzt werden. [[config-network-ndis]] ==== Windows(R)-NDIS-Treiber einsetzen Leider stellen nach wie vor viele Unternehmen die Spezifikationen ihrer Treiber der Open Source Gemeinde nicht zur Verfügung, weil sie diese Informationen als Geschäftsgeheimnisse betrachten. Daher haben die Entwickler von FreeBSD und anderen Betriebssystemen nur zwei Möglichkeiten. Entweder versuchen sie in einem aufwändigen Prozess den Treiber durch Reverse Engineering nachzubauen, oder sie versuchen, die vorhandenen Binärtreiber der Microsoft(R) Windows(R)-Plattform zu verwenden. FreeBSD bietet "native" Unterstützung für die Network Driver Interface Specification (NDIS). man:ndisgen[8] wird benutzt, um einen Windows(R) XP-Treiber in ein Format zu konvertieren, das von FreeBSD verwendet werden kann. Da der man:ndis[4]-Treiber einen Windows(R) XP-Binärtreiber nutzt, kann er nur auf i386(TM)- und amd64-Systemen verwendet werden. Unterstützt werden PCI, CardBus, PCMCIA und USB-Geräte. Um den NDISulator zu verwenden, benötigen Sie drei Dinge: . Die FreeBSD Kernelquellen . Den Windows(R) XP-Binärtreiber mit der Erweiterung [.filename]#.SYS# . Die Konfigurationsdatei des Windows(R) XP-Treibers mit der Erweiterung [.filename]#.INF# Laden Sie die [.filename]#.SYS#- und [.filename]#.INF#-Dateien für die Karte. Diese befinden sich meistens auf einer beigelegten CD-ROM, oder können von der Internetseite des Herstellers heruntergeladen werden. In den folgenden Beispielen werden die Dateien [.filename]#W32DRIVER.SYS# und [.filename]#W32DRIVER.INF# verwendet. Die Architektur des Treibers muss zur jeweiligen Version von FreeBSD passen. Benutzen Sie einen Windows(R) 32-bit Treiber für FreeBSD/i386. Für FreeBSD/amd64 wird ein Windows(R) 64-bit Treiber benötigt. Als Nächstes kompilieren Sie den binären Treiber, um ein Kernelmodul zu erzeugen. Dazu rufen Sie als `root` man:ndisgen[8] auf: [source,shell] .... # ndisgen /path/to/W32DRIVER.INF /path/to/W32DRIVER.SYS .... Dieses Kommando arbeitet interaktiv, benötigt es weitere Informationen, so fragt es Sie danach. Das Ergebnis ist ein neu erzeugtes Kernelmodul im aktuellen Verzeichnis. Benutzen Sie man:kldload[8] um das neue Modul zu laden: [source,shell] .... # kldload ./W32DRIVER.ko .... Neben dem erzeugten Kernelmodul müssen auch die Kernelmodule [.filename]#ndis.ko# und [.filename]#if_ndis.ko# geladen werden. Dies passiert automatisch, wenn Sie ein von man:ndis[4] abhängiges Modul laden. Andernfalls können die Module mit den folgenden Kommandos manuell geladen werden: [source,shell] .... # kldload ndis # kldload if_ndis .... Der erste Befehl lädt den man:ndis[4]-Miniport-Treiber, der zweite das tatsächliche Netzwerkgerät. Überprüfen Sie die Ausgabe von man:dmesg[8] auf eventuelle Fehler während des Ladevorgangs. Gab es dabei keine Probleme, sollte die Ausgabe wie folgt aussehen: [source,shell] .... ndis0: mem 0xf4100000-0xf4101fff irq 3 at device 8.0 on pci1 ndis0: NDIS API version: 5.0 ndis0: Ethernet address: 0a:b1:2c:d3:4e:f5 ndis0: 11b rates: 1Mbps 2Mbps 5.5Mbps 11Mbps ndis0: 11g rates: 6Mbps 9Mbps 12Mbps 18Mbps 36Mbps 48Mbps 54Mbps .... Ab jetzt kann das Gerät [.filename]#ndis0# wie jede andere Netzwerkkarte konfiguriert werden. Um die man:ndis[4]-Module automatisch beim Systemstart zu laden, kopieren Sie das erzeugte Modul [.filename]#W32DRIVER_SYS.ko# nach [.filename]#/boot/modules#. Danach fügen Sie die folgende Zeile in [.filename]#/boot/loader.conf# ein: [.programlisting] .... W32DRIVER_SYS_load="YES" .... === Konfiguration von Netzwerkkarten Nachdem der richtige Treiber für die Karte geladen ist, muss die Karte konfiguriert werden. Unter Umständen ist die Karte schon während der Installation mit man:bsdinstall[8] konfiguriert worden. Das nachstehende Kommando zeigt die Konfiguration der Netzwerkkarten an: [source,shell] .... % ifconfig dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da inet 192.168.1.3 netmask 0xffffff00 broadcast 192.168.1.255 media: Ethernet autoselect (100baseTX ) status: active dc1: flags=8802 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:db inet 10.0.0.1 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet 10baseT/UTP status: no carrier lo0: flags=8049 metric 0 mtu 16384 options=3 inet6 fe80::1%lo0 prefixlen 64 scopeid 0x4 inet6 ::1 prefixlen 128 inet 127.0.0.1 netmask 0xff000000 nd6 options=3 .... Im Beispiel werden Informationen zu den folgenden Geräten angezeigt: * [.filename]#dc0#: Der erste Ethernet-Adapter. * [.filename]#dc1#: Der zweite Ethernet-Adapter. * [.filename]#lo0#: Das Loopback-Gerät. Der Name der Netzwerkkarte wird aus dem Namen des Treibers und einer Zahl zusammengesetzt. Die Zahl gibt die Reihenfolge an, in der die Geräte beim Systemstart erkannt wurden. Die dritte Karte, die den man:sis[4] Treiber benutzt, würde beispielsweise [.filename]#sis2# heißen. Der Adapter [.filename]#dc0# aus dem Beispiel ist aktiv. Sie erkennen das an den folgenden Hinweisen: . `UP` bedeutet, dass die Karte konfiguriert und aktiv ist. . Der Karte wurde die Internet-Adresse (`inet`) `192.168.1.3` zugewiesen. . Die Subnetzmaske ist richtig (`0xffffff00` entspricht `255.255.255.0`). . Die Broadcast-Adresse `192.168.1.255` ist richtig. . Die MAC-Adresse der Karte (`ether`) lautet `00:a0:cc:da:da:da`. . Die automatische Medienerkennung ist aktiviert (`media: Ethernet autoselect (100baseTX )`). Der Adapter [.filename]#dc1# benutzt das Medium `10baseT/UTP`. Weitere Informationen über die einstellbaren Medien entnehmen Sie der Hilfeseite des Treibers. . Der Verbindungsstatus (`status`) ist `active`, das heißt es wurde ein Trägersignal entdeckt. Für [.filename]#dc1# wird `status: no carrier` angezeigt. Das ist normal, wenn kein Kabel an der Karte angeschlossen ist. Wäre die Karte nicht konfiguriert, würde die Ausgabe von man:ifconfig[8] so aussehen: [source,shell] .... dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da media: Ethernet autoselect (100baseTX ) status: active .... Die Karte muss als Benutzer `root` konfiguriert werden. Die Konfiguration kann auf der Kommandozeile mit man:ifconfig[8] erfolgen. Allerdings gehen diese Informationen bei einem Neustart verloren. Tragen Sie stattdessen die Konfiguration in [.filename]#/etc/rc.conf# ein. Wenn es im LAN einen DHCP-Server gibt, fügen Sie einfach folgende Zeile hinzu: [.programlisting] .... ifconfig_dc0="DHCP" .... Ersetzen Sie _>dc0_ durch die richtigen Werte für das System. Nachdem Sie die Zeile hinzugefügt haben, folgen Sie den Anweisungen in <>. [NOTE] ==== Wenn das Netzwerk während der Installation konfiguriert wurde, existieren vielleicht schon Einträge für die Netzwerkkarte(n). Überprüfen Sie [.filename]#/etc/rc.conf# bevor Sie weitere Zeilen hinzufügen. ==== Falls kein DHCP-Server zur Verfügung steht, müssen die Netzwerkkarten manuell konfiguriert werden. Fügen Sie für jede Karte im System eine Zeile hinzu, wie in diesem Beispiel zu sehen: [.programlisting] .... ifconfig_dc0="inet 192.168.1.3 netmask 255.255.255.0" ifconfig_dc1="inet 10.0.0.1 netmask 255.255.255.0 media 10baseT/UTP" .... Ersetzen Sie [.filename]#dc0# und [.filename]#dc1# und die IP-Adressen durch die richtigen Werte für das System. Die Manualpages des Treibers, man:ifconfig[8] und man:rc.conf[5] enthalten weitere Einzelheiten über verfügbare Optionen und die Syntax von [.filename]#/etc/rc.conf#. Wenn das Netzwerk kein DNS benutzt, können Sie in [.filename]#/etc/hosts# die Namen und IP-Adressen der Rechner des LANs eintragen. Weitere Informationen entnehmen Sie man:hosts[5] und [.filename]#/usr/shared/examples/etc/hosts#. [NOTE] ==== Falls kein DHCP-Server zur Verfügung steht, Sie aber Zugang zum Internet benötigen, müssen Sie das Standard-Gateway und die Nameserver manuell konfigurieren: [source,shell] .... # echo 'defaultrouter="Ihr_Default_Gateway"' >> /etc/rc.conf # echo 'nameserver Ihr_DNS_Server' >> /etc/resolv.conf .... ==== [[config-network-testing]] === Test und Fehlersuche Nachdem die notwendigen Änderungen in [.filename]#/etc/rc.conf# gespeichert wurden, kann das System neu gestartet werden, um die Konfiguration zu testen und zu überprüfen, ob das System ohne Fehler neu gestartet wurde. Alternativ können Sie mit folgenden Befehl die Netzwerkeinstellungen neu initialisieren: [source,shell] .... # service netif restart .... [NOTE] ==== Falls in [.filename]#/etc/rc.conf# ein Default-Gateway definiert wurde, müssen Sie auch den folgenden Befehl ausführen: [source,shell] .... # service routing restart .... ==== Wenn das System gestartet ist, sollten Sie die Netzwerkkarten testen. ==== Test der Ethernet-Karte Um zu prüfen, ob die Ethernet-Karte richtig konfiguriert ist, testen Sie zunächst mit man:ping[8] den Adapter selbst und sprechen Sie dann eine andere Maschine im LAN an. Zuerst, der Test des Adapters: [source,shell] .... % ping -c5 192.168.1.3 PING 192.168.1.3 (192.168.1.3): 56 data bytes 64 bytes from 192.168.1.3: icmp_seq=0 ttl=64 time=0.082 ms 64 bytes from 192.168.1.3: icmp_seq=1 ttl=64 time=0.074 ms 64 bytes from 192.168.1.3: icmp_seq=2 ttl=64 time=0.076 ms 64 bytes from 192.168.1.3: icmp_seq=3 ttl=64 time=0.108 ms 64 bytes from 192.168.1.3: icmp_seq=4 ttl=64 time=0.076 ms --- 192.168.1.3 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.074/0.083/0.108/0.013 ms .... [source,shell] .... % ping -c5 192.168.1.2 PING 192.168.1.2 (192.168.1.2): 56 data bytes 64 bytes from 192.168.1.2: icmp_seq=0 ttl=64 time=0.726 ms 64 bytes from 192.168.1.2: icmp_seq=1 ttl=64 time=0.766 ms 64 bytes from 192.168.1.2: icmp_seq=2 ttl=64 time=0.700 ms 64 bytes from 192.168.1.2: icmp_seq=3 ttl=64 time=0.747 ms 64 bytes from 192.168.1.2: icmp_seq=4 ttl=64 time=0.704 ms --- 192.168.1.2 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.700/0.729/0.766/0.025 ms .... Um die Namensauflösung zu testen, verwenden Sie den Namen der Maschine anstelle der IP-Adresse. Wenn kein DNS-Server im Netzwerk vorhanden ist, muss [.filename]#/etc/hosts# entsprechend eingerichtet sein. Fügen Sie dazu die Namen und IP-Adressen der Rechner im LAN in [.filename]#/etc/hosts# hinzu, falls sie nicht bereits vorhanden sind. Weitere Informationen finden Sie in man:hosts[5] und [.filename]#/usr/shared/examples/etc/hosts#. ==== Fehlersuche Fehler zu beheben, ist immer sehr mühsam. Indem Sie die einfachen Sachen zuerst prüfen, erleichtern Sie sich die Aufgabe. Steckt das Netzwerkkabel? Sind die Netzwerkdienste richtig konfiguriert? Funktioniert die Firewall? Wird die Netzwerkkarte von FreeBSD unterstützt? Lesen Sie immer die Hardware-Informationen des Releases, bevor Sie einen Fehlerbericht einsenden. Aktualisieren Sie die FreeBSD-Version auf die neueste -STABLE Version. Suchen Sie in den Archiven der Mailinglisten und im Internet nach bekannten Lösungen. Wenn die Karte funktioniert, die Verbindungen aber zu langsam sind, sollten Sie man:tuning[7] lesen. Prüfen Sie auch die Netzwerkkonfiguration, da falsche Einstellungen die Ursache für langsame Verbindungen sein können. Wenn Sie viele `device timeout` Meldungen in den Systemprotokollen finden, prüfen Sie, dass es keinen Konflikt zwischen der Netzwerkkarte und anderen Geräten des Systems gibt. Überprüfen Sie nochmals die Verkabelung. Unter Umständen benötigen Sie eine andere Netzwerkkarte. Bei `watchdog timeout` Fehlermeldungen, kontrollieren Sie zuerst die Verkabelung. Überprüfen Sie dann, ob der PCI-Steckplatz der Karte Bus Mastering unterstützt. Auf einigen älteren Motherboards ist das nur für einen Steckplatz (meistens Steckplatz 0) der Fall. Lesen Sie in der Dokumentation der Karte und des Motherboards nach, ob das vielleicht die Ursache des Problems sein könnte. Die Meldung `No route to host` erscheint, wenn das System ein Paket nicht zustellen kann. Das kann vorkommen weil beispielsweise keine Default-Route gesetzt wurde oder das Netzwerkkabel nicht richtig steckt. Schauen Sie in der Ausgabe von `netstat -rn` nach, ob eine gültige Route zu dem Zielsystem existiert. Wenn nicht, lesen Sie crossref:advanced-networking[network-routing,“Gateways und Routen”]. Die Meldung `ping: sendto: Permission denied` wird oft von einer falsch konfigurierten Firewall verursacht. Wenn keine Regeln definiert wurden, blockiert eine aktivierte Firewall alle Pakete, selbst einfache man:ping[8]-Pakete. Weitere Informationen erhalten Sie in crossref:firewalls[firewalls,Firewalls]. Falls die Leistung der Karte schlecht ist, setzen Sie die Medienerkennung von `autoselect` (automatisch) auf das richtige Medium. In vielen Fällen löst diese Maßnahme Leistungsprobleme. Wenn nicht, prüfen Sie nochmal die Netzwerkeinstellungen und lesen Sie man:tuning[7]. [[configtuning-virtual-hosts]] == Virtual Hosts Ein gebräuchlicher Zweck von FreeBSD ist das virtuelle Hosting, bei dem ein Server im Netzwerk wie mehrere Server aussieht. Dies wird dadurch erreicht, dass einem Netzwerkinterface mehrere Netzwerk-Adressen zugewiesen werden. Ein Netzwerkinterface hat eine "echte" Adresse und kann beliebig viele "alias" Adressen haben. Die Aliase werden durch entsprechende alias Einträge in [.filename]#/etc/rc.conf# festgelegt, wie in diesem Beispiel zu sehen ist: [.programlisting] .... ifconfig_fxp0_alias0="inet xxx.xxx.xxx.xxx netmask xxx.xxx.xxx.xxx" .... Beachten Sie, dass die Alias-Einträge mit `alias_0_` anfangen müssen und weiter hochgezählt werden, das heißt `alias1`, `alias2`, und so weiter. Die Konfiguration der Aliase hört bei der ersten fehlenden Zahl auf. Die Berechnung der Alias-Netzwerkmasken ist wichtig. Für jedes Interface muss es eine Adresse geben, die die Netzwerkmaske des Netzwerkes richtig beschreibt. Alle anderen Adressen in diesem Netzwerk haben dann eine Netzwerkmaske, die mit `1` gefüllt ist, also `255.255.255.255` oder hexadezimal `0xffffffff`. Als Beispiel betrachten wir den Fall, in dem [.filename]#fxp0# mit zwei Netzwerken verbunden ist: dem Netzwerk `10.1.1.0` mit der Netzwerkmaske `255.255.255.0` und dem Netzwerk `202.0.75.16` mit der Netzwerkmaske `255.255.255.240`. Das System soll die Adressen `10.1.1.1` bis `10.1.1.5` und `202.0.75.17` bis `202.0.75.20` belegen. Nur die erste Adresse in einem Netzwerk sollte die richtige Netzwerkmaske haben. Alle anderen Adressen (`10.1.1.2` bis `10.1.1.5` und `202.0.75.18` bis `202.0.75.20`) müssen die Maske `255.255.255.255` erhalten. Die folgenden Einträge in [.filename]#/etc/rc.conf# konfigurieren den Adapter entsprechend dem Beispiel: [.programlisting] .... ifconfig_fxp0="inet 10.1.1.1 netmask 255.255.255.0" ifconfig_fxp0_alias0="inet 10.1.1.2 netmask 255.255.255.255" ifconfig_fxp0_alias1="inet 10.1.1.3 netmask 255.255.255.255" ifconfig_fxp0_alias2="inet 10.1.1.4 netmask 255.255.255.255" ifconfig_fxp0_alias3="inet 10.1.1.5 netmask 255.255.255.255" ifconfig_fxp0_alias4="inet 202.0.75.17 netmask 255.255.255.240" ifconfig_fxp0_alias5="inet 202.0.75.18 netmask 255.255.255.255" ifconfig_fxp0_alias6="inet 202.0.75.19 netmask 255.255.255.255" ifconfig_fxp0_alias7="inet 202.0.75.20 netmask 255.255.255.255" .... Dies kann mit einer durch Leerzeichen getrennten Liste von IP-Adressbereichen auch einfacher ausgedrückt werden. Die erste Adresse hat wieder die angegebene Netzwerkmaske und die zusätzlichen Adressen haben die Netzwerkmaske `255.255.255.255`. [.programlisting] .... ifconfig_fxp0_aliases="inet 10.1.1.1-5/24 inet 202.0.75.17-20/28" .... [[configtuning-syslog]] == Konfiguration der Systemprotokollierung Die Aufzeichnung und Kontrolle von Log-Meldungen ist ein wichtiger Aspekt der Systemadministration. Die Informationen werden nicht nur verwendet um Hard- und Softwarefehler ausfindig zu machen, auch zur Überwachung der Sicherheit und der Reaktion bei einem Zwischenfall spielen diese Aufzeichnungen eine wichtige Rolle. Die meisten Systemdienste und Anwendungen erzeugen Log-Meldungen. FreeBSD stellt mit syslogd ein Werkzeug zur Verwaltung von Protokollen bereit. In der Voreinstellung wird syslogd beim Booten automatisch gestartet. Dieses Verhalten wird über die Variable `syslogd_enable` in [.filename]#/etc/rc.conf# gesteuert. Dazu gibt es noch zahlreiche Argumente, die in der Variable `syslogd_flags` in [.filename]#/etc/rc.conf# gesetzt werden können. Lesen Sie man:syslogd[8] für weitere Informationen über die verfügbaren Argumente. Dieser Abschnitt beschreibt die Konfiguration und Verwendung des FreeBSD Protokollservers, und diskutiert auch die Log-Rotation und das Management von Logdateien. === Konfiguration der lokalen Protokollierung Die Konfigurationsdatei [.filename]#/etc/syslog.conf# steuert, was syslogd mit Log-Meldungen macht, sobald sie empfangen werden. Es gibt verschiedene Parameter, die das Verhalten bei eingehenden Ereignissen kontrollieren. facility beschreibt das Subsystem, welches das Ereignis generiert hat. Beispielsweise der Kernel, oder ein Daemon. level hingegen beschreibt den Schweregrad des aufgetretenen Ereignisses. Dies macht es möglich, Meldungen in verschiedenen Logdateien zu protokollieren, oder Meldungen zu verwerfen, je nach Konfiguration von facility und level. Ebenfalls besteht die Möglichkeit auf Meldungen zu reagieren, die von einer bestimmten Anwendung stammen, oder von einem spezifischen Host erzeugt wurden. Die Konfigurationsdatei von man:syslogd[8] enthält für jede Aktion eine Zeile. Die Syntax besteht aus einem Auswahlfeld, gefolgt von einem Aktionsfeld. Die Syntax für das Auswahlfeld ist _facility.level_. Dies entspricht Log-Meldungen von _facility_ mit einem Level von _level_ oder höher. Um noch präziser festzulegen was protokolliert wird, kann dem Level optional ein Vergleichsflag vorangestellt werden. Mehrere Auswahlen können, durch Semikolon (`;`) getrennt, für die gleiche Aktion verwendet werden. `*` wählt dabei alles aus. Das Aktionsfeld definiert, wohin die Log-Meldungen gesendet werden, beispielsweise in eine Datei oder zu einem entfernten Log-Server. Als Beispiel dient hier [.filename]#/etc/syslog.conf# aus FreeBSD: [.programlisting] .... # $FreeBSD$ # # Spaces ARE valid field separators in this file. However, # other *nix-like systems still insist on using tabs as field # separators. If you are sharing this file between systems, you$ # may want to use only tabs as field separators here. # Consult the syslog.conf(5) manpage. *.err;kern.warning;auth.notice;mail.crit /dev/console *.notice;authpriv.none;kern.debug;lpr.info;mail.crit;news.err /var/log/messages security.* /var/log/security auth.info;authpriv.info /var/log/auth.log mail.info /var/log/maillog lpr.info /var/log/lpd-errs ftp.info /var/log/xferlog cron.* /var/log/cron !-devd *.=debug /var/log/debug.log *.emerg * # uncomment this to log all writes to /dev/console to /var/log/console.log #console.info /var/log/console.log # uncomment this to enable logging of all log messages to /var/log/all.log # touch /var/log/all.log and chmod it to mode 600 before it will work #*.* /var/log/all.log # uncomment this to enable logging to a remote loghost named loghost #*.* @loghost # uncomment these if you're running inn # news.crit /var/log/news/news.crit # news.err /var/log/news/news.err # news.notice /var/log/news/news.notice # Uncomment this if you wish to see messages produced by devd # !devd # *.>=info !ppp *.* /var/log/ppp.log !* .... In diesem Beispiel: * Zeile 8 selektiert alle Meldungen vom Level `err`, sowie `kern.warning`, `auth.notice` und `mail.crit` und schickt diese zur Konsole ([.filename]#/dev/console#). * Zeile 12 selektiert alle Meldungen von `mail` ab dem Level `info` oder höher und schreibt diese in [.filename]#/var/log/maillog#. * Zeile 17 benutzt ein Vergleichsflag (`=`), um nur Meldungen vom Level `debug` zu selektieren und schreibt diese in [.filename]#/var/log/debug.log#. * Zeile 33 zeigt ein Beispiel für die Nutzung einer Programmspezifikation. Die nachfolgenden Regeln sind dann nur für Programme gültig, welche der Programmspezifikation stehen. In diesem Fall werden alle Meldungen von ppp (und keinem anderen Programm) in [.filename]#/var/log/ppp.log# geschrieben. Die verfügbaren level, beginnend mit den höchst kritischen, hin zu den weniger kritischen, sind: `emerg`, `alert`, `crit`, `err`, `warning`, `notice`, `info` und `debug`. Die facilities, in beliebiger Reihenfolge, sind: `auth`, `authpriv`, `console`, `cron`, `daemon`, `ftp`, `kern`, `lpr`, `mail`, `mark`, `news`, `security`, `syslog`, `user`, `uucp`, sowie `local0` bis `local7`. Beachten Sie, dass andere Betriebssysteme hiervon abweichende facilities haben können. Um alle Meldungen vom Level `notice` und höher in [.filename]#/var/log/daemon.log# zu protokollieren, fügen Sie folgenden Eintrag hinzu: [.programlisting] .... daemon.notice /var/log/daemon.log .... Für weitere Informationen zu verschiedenen Level und faclilities, lesen Sie man:syslog[3] und man:syslogd[8]. Weitere Informationen zu [.filename]#/etc/syslog.conf#, dessen Syntax und erweiterten Anwendungsbeispielen, finden Sie in man:syslog.conf[5]. === Management und Rotation von Logdateien Logdateien können schnell wachsen und viel Speicherplatz belegen, was es schwieriger macht, nützliche Informationen zu finden. Log-Management versucht, diesen Effekt zu mildern. FreeBSD verwendet newsyslog für die Verwaltung von Logdateien. Dieses in FreeBSD integrierte Programm rotiert und komprimiert in regelmäßigen Abständen Logdateien. Optional kann es auch fehlende Logdateien erstellen und Programme benachrichtigen, wenn Logdateien verschoben wurden. Die Logdateien können von syslogd oder einem anderen Programm generiert werden. Obwohl newsyslog normalerweise von man:cron[8] aufgerufen wird, ist es kein Systemdämon. In der Standardkonfiguration wird dieser Job jede Stunde ausgeführt. Um zu wissen, welche Maßnahmen zu ergreifen sind, liest newsyslog seine Konfigurationsdatei [.filename]#/etc/newsyslog.conf#. Diese Konfigurationsdatei enthält eine Zeile für jede Datei, die von newsyslog verwaltet wird. Jede Zeile enthält Informationen über den Besitzer der Datei, die Dateiberechtigungen, wann die Datei rotiert wird, optionale Flags, welche die Log-Rotation beeinflussen (bspw. Komprimierung) und Programme, denen ein Signal geschickt wird, wenn Logdateien rotiert werden. Hier folgt die Standardkonfiguration in FreeBSD: [.programlisting] .... # configuration file for newsyslog # $FreeBSD$ # # Entries which do not specify the '/pid_file' field will cause the # syslogd process to be signalled when that log file is rotated. This # action is only appropriate for log files which are written to by the # syslogd process (ie, files listed in /etc/syslog.conf). If there # is no process which needs to be signalled when a given log file is # rotated, then the entry for that file should include the 'N' flag. # # The 'flags' field is one or more of the letters: BCDGJNUXZ or a '-'. # # Note: some sites will want to select more restrictive protections than the # defaults. In particular, it may be desirable to switch many of the 644 # entries to 640 or 600. For example, some sites will consider the # contents of maillog, messages, and lpd-errs to be confidential. In the # future, these defaults may change to more conservative ones. # # logfilename [owner:group] mode count size when flags [/pid_file] [sig_num] /var/log/all.log 600 7 * @T00 J /var/log/amd.log 644 7 100 * J /var/log/auth.log 600 7 100 @0101T JC /var/log/console.log 600 5 100 * J /var/log/cron 600 3 100 * JC /var/log/daily.log 640 7 * @T00 JN /var/log/debug.log 600 7 100 * JC /var/log/kerberos.log 600 7 100 * J /var/log/lpd-errs 644 7 100 * JC /var/log/maillog 640 7 * @T00 JC /var/log/messages 644 5 100 @0101T JC /var/log/monthly.log 640 12 * $M1D0 JN /var/log/pflog 600 3 100 * JB /var/run/pflogd.pid /var/log/ppp.log root:network 640 3 100 * JC /var/log/devd.log 644 3 100 * JC /var/log/security 600 10 100 * JC /var/log/sendmail.st 640 10 * 168 B /var/log/utx.log 644 3 * @01T05 B /var/log/weekly.log 640 5 1 $W6D0 JN /var/log/xferlog 600 7 100 * JC .... Jede Zeile beginnt mit dem Namen der Protokolldatei, die rotiert werden soll, optional gefolgt von Besitzer und Gruppe für rotierende, als auch für neu erstellte Dateien. Das Feld `mode` definiert die Zugriffsrechte der Datei. `count` gibt an, wie viele rotierte Dateien aufbewahrt werden sollen. Anhand der `size`- und `when`-Flags erkennt newsyslog, wann die Datei rotiert werden muss. Eine Logdatei wird rotiert, wenn ihre Größe den Wert von `size` überschreitet, oder wenn die Zeit im `when`-Feld abgelaufen ist. Ein `*` bedeutet, dass dieses Feld ignoriert wird. Das _flags_-Feld gibt newsyslog weitere Instruktionen, zum Beispiel wie eine Datei zu rotieren ist, oder eine Datei zu erstellen falls diese nicht existiert. Die letzten beiden Felder sind optional und bestimmen die PID-Datei und wann die Datei rotiert wird. Weitere Informationen zu allen Feldern, gültigen Flags und wie Sie die Rotationszeit angeben können, finden Sie in man:newsyslog.conf[5]. Denken Sie daran, dass newsyslog von man:cron[8] aufgerufen wird und somit Dateien auch nur dann rotiert, wenn es von man:cron[8] aufgerufen wird, und nicht häufiger. [[network-syslogd]] === Protokollierung von anderen Hosts Die Überwachung der Protokolldateien kann bei steigender Anzahl von Rechnern sehr unhandlich werden. Eine zentrale Protokollierung kann manche administrativen Belastungen bei der Verwaltung von Protokolldateien reduzieren. Die Aggregation, Zusammenführung und Rotation von Protokolldateien kann in FreeBSD mit syslogd und newsyslog konfiguriert werden. In der folgenden Beispielkonfiguration sammelt Host `A`, genannt `logserv.example.com`, Protokollinformationen für das lokale Netzwerk. Host `B`, genannt `logclient.example.com` wird seine Protokollinformationen an den Server weiterleiten. ==== Konfiguration des Protokollservers Ein Protokollserver ist ein System, welches Protokollinformationen von anderen Hosts akzeptiert. Bevor Sie diesen Server konfigurieren, prüfen Sie folgendes: * Falls eine Firewall zwischen dem Protokollserver und den -Clients steht, muss das Regelwerk der Firewall UDP auf Port 514 sowohl auf Client- als auch auf Serverseite freigegeben werden. * Der `syslogd`-Server und alle Clientrechner müssen gültige Einträge für sowohl Vorwärts- als auch Umkehr-DNS besitzen. Falls im Netzwerk kein DNS-Server vorhanden ist, muss auf jedem System die Datei [.filename]#/etc/hosts# mit den richtigen Einträgen gepflegt werden. Eine funktionierende Namensauflösung ist zwingend erforderlich, ansonsten würde der Server die Protokollnachrichten ablehnen. Bearbeiten Sie [.filename]#/etc/syslog.conf# auf dem Server. Tragen Sie den Namen des Clients ein, den Verbindungsweg und den Namen der Protokolldatei. Dieses Beispiel verwendet den Rechnernamen `B`, alle Verbindungswege, und die Protokolle werden in [.filename]#/var/log/logclient.log# gespeichert. .Einfache Server Konfiguration [example] ==== [.programlisting] .... +logclient.example.com *.* /var/log/logclient.log .... ==== Fügen Sie für jeden Client zwei Zeilen hinzu, falls Sie mehrere Clients in diese Datei aufnehmen. Weitere Informationen über die verfügbaren Verbindungswege finden Sie in man:syslog.conf[5]. Konfigurieren Sie als nächstes [.filename]#/etc/rc.conf#: [.programlisting] .... syslogd_enable="YES" syslogd_flags="-a logclient.example.com -v -v" .... Der erste Eintrag startet `syslogd` während des Bootens. Der zweite Eintrag erlaubt es, Daten von dem spezifizierten Client auf diesem Server zu akzeptieren. Die Verwendung von `-v -v` erhöht die Anzahl von Protokollnachrichten. Dies ist hilfreich für die Feineinstellung der Verbindungswege, da Administratoren auf diese Weise erkennen, welche Arten von Nachrichten von welchen Verbindungswegen protokolliert werden. Mehrere `-a`-Optionen können angegeben werden, um die Protokollierung von mehreren Clients zu erlauben. IP-Adressen und ganze Netzblöcke können ebenfalls spezifiziert werden. Eine vollständige Liste der Optionen finden Sie in man:syslogd[8]. Zum Schluss muss die Protokolldatei erstellt werden: [source,shell] .... # touch /var/log/logclient.log .... Zu diesem Zeitpunkt sollte `syslogd` neu gestartet und überprüft werden: [source,shell] .... # service syslogd restart # pgrep syslog .... Wenn eine PID zurückgegeben wird, wurde der Server erfolgreich neu gestartet und die Clientkonfiguration kann beginnen. Wenn der Server nicht neu gestartet wurde, suchen Sie in [.filename]#/var/log/messages# nach dem Fehler. ==== Konfiguration des Protokollclients Ein Protokollclient sendet Protokollinformationen an einen Protokollserver. Zusätzlich behält er eine lokale Kopie seiner eigenen Protokolle. Sobald der Server konfiguriert ist, bearbeiten Sie [.filename]#/etc/rc.conf# auf dem Client: [.programlisting] .... syslogd_enable="YES" syslogd_flags="-s -v -v" .... Der erste Eintrag aktiviert den `syslogd`-Dienst während des Systemstarts. Der zweite Eintrag erhöht die Anzahl der Protokollnachrichten. Die Option `-s` verhindert, dass dieser Client Protokolle von anderen Hosts akzeptiert. Als nächstes muss der Protokollserver in der [.filename]#/etc/syslog.conf# des Clients eingetragen werden. In diesem Beispiel wird das `@`-Symbol benutzt, um sämtliche Protokolldaten an einen bestimmten Server zu senden: [.programlisting] .... *.* @logserv.example.com .... Nachdem die Änderungs gespeichert wurden, muss `syslogd` neu gestartet werden, damit die Änderungen wirksam werden: [source,shell] .... # service syslogd restart .... Um zu testen, ob Protokollnachrichten über das Netzwerk gesendet werden, kann man:logger[1] auf dem Client benutzt werden, um eine Nachricht an syslogd zu schicken: [source,shell] .... # logger "Test message from logclient" .... Diese Nachricht sollte jetzt sowohl in [.filename]#/var/log/messages# auf dem Client, als auch in [.filename]#/var/log/logclient.log# auf dem Server vorhanden sein. ==== Fehlerbehebung beim Protokollserver Wenn der Server keine Nachrichten empfängt, ist die Ursache wahrscheinlich ein Netzwerkproblem, ein Problem bei der Namensauflösung oder ein Tippfehler in einer Konfigurationsdatei. Um die Ursache zu isolieren, müssen Sie sicherstellen, dass sich Server und Client über den in [.filename]#/etc/rc.conf# konfigurierten Hostnamen mit `ping` erreichen lässt. Falls dies nicht gelingt sollten Sie die Netzwerkverkabelung überprüfen, außerdem Firewallregeln sowie die Einträge für Hosts im DNS und [.filename]#/etc/hosts#. Überprüfen Sie diese Dinge auf dem Server und dem Client, bis der `ping` von beiden Hosts erfolgreich ist. Wenn sich die Hosts gegenseitig mit `ping` erreichen können, der Server aber immer noch keine Nachrichten empfängt, können Sie vorübergehend die Ausführlichkeit der Protokollierung erhöhen, um die Ursache für das Problem weiter einzugrenzen. In dem folgenden Beispiel ist auf dem Server die Datei [.filename]#/var/log/logclient.log# leer und in der Datei [.filename]#/var/log/messages# auf dem Client ist keine Ursache für das Problem erkennbar. Um nun die Ausführlichkeit der Protokollierung zu erhöhen, passen Sie auf dem Server den Eintrag `syslogd_flags` an. Anschließend starten Sie den Dienst neu: [.programlisting] .... syslogd_flags="-d -a logclient.example.com -v -v" .... [source,shell] .... # service syslogd restart .... Informationen wie diese werden sofort nach dem Neustart auf der Konsole erscheinen: [source,shell] .... logmsg: pri 56, flags 4, from logserv.example.com, msg syslogd: restart syslogd: restarted logmsg: pri 6, flags 4, from logserv.example.com, msg syslogd: kernel boot file is /boot/kernel/kernel Logging to FILE /var/log/messages syslogd: kernel boot file is /boot/kernel/kernel cvthname(192.168.1.10) validate: dgram from IP 192.168.1.10, port 514, name logclient.example.com; rejected in rule 0 due to name mismatch. .... In diesem Beispiel werden die Nachrichten aufgrund eines fehlerhaften Namens abgewiesen. Der Hostname sollte `logclient` und nicht `logclien` sein. Beheben Sie den Tippfehler, starten Sie den Dienst neu und überprüfen Sie das Ergebnis: [source,shell] .... # service syslogd restart logmsg: pri 56, flags 4, from logserv.example.com, msg syslogd: restart syslogd: restarted logmsg: pri 6, flags 4, from logserv.example.com, msg syslogd: kernel boot file is /boot/kernel/kernel syslogd: kernel boot file is /boot/kernel/kernel logmsg: pri 166, flags 17, from logserv.example.com, msg Dec 10 20:55:02 logserv.example.com syslogd: exiting on signal 2 cvthname(192.168.1.10) validate: dgram from IP 192.168.1.10, port 514, name logclient.example.com; accepted in rule 0. logmsg: pri 15, flags 0, from logclient.example.com, msg Dec 11 02:01:28 trhodes: Test message 2 Logging to FILE /var/log/logclient.log Logging to FILE /var/log/messages .... Zu diesem Zeitpunkt werden die Nachrichten korrekt empfangen und in die richtige Datei geschrieben. ==== Sicherheitsbedenken Wie mit jedem Netzwerkdienst, müssen Sicherheitsanforderungen in Betracht gezogen werden, bevor ein Protokollserver eingesetzt wird. Manchmal enthalten Protokolldateien sensitive Daten über aktivierte Dienste auf dem lokalen Rechner, Benutzerkonten und Konfigurationsdaten. Daten, die vom Client an den Server geschickt werden, sind weder verschlüsselt noch mit einem Passwort geschützt. Wenn ein Bedarf für Verschlüsselung besteht, ist es möglich package:security/stunnel[] zu verwenden, welches die Protokolldateien über einen verschlüsselten Tunnel versendet. Lokale Sicherheit ist ebenfalls ein Thema. Protokolldateien sind während der Verwendung oder nach ihrer Rotation nicht verschlüsselt. Lokale Benutzer versuchen vielleicht, auf diese Dateien zuzugreifen, um zusätzliche Einsichten in die Systemkonfiguration zu erlangen. Es ist absolut notwendig, die richtigen Berechtigungen auf diesen Dateien zu setzen. Das Werkzeug newsyslog unterstützt das Setzen von Berechtigungen auf gerade erstellte oder rotierte Protokolldateien. Protokolldateien mit Zugriffsmodus `600` sollten verhindern, dass lokale Benutzer darin herumschnüffeln. Zusätzliche Informationen finden Sie in man:newsyslog.conf[5]. [[configtuning-configfiles]] == Konfigurationsdateien === [.filename]#/etc# Layout Konfigurationsdateien finden sich in einigen Verzeichnissen unter anderem in: [.informaltable] [cols="1,1", frame="none"] |=== |[.filename]#/etc# |Enthält generelle systemspezifische Konfigurationsinformationen. |[.filename]#/etc/defaults# |Default Versionen der Konfigurationsdateien. |[.filename]#/etc/mail# |Enthält die man:sendmail[8] Konfiguration und weitere MTA Konfigurationsdateien. |[.filename]#/etc/ppp# |Hier findet sich die Konfiguration für die User- und Kernel-ppp Programme. |[.filename]#/usr/local/etc# |Installierte Anwendungen legen hier ihre Konfigurationsdateien ab. Dieses Verzeichnis kann Unterverzeichnisse für bestimmte Anwendungen enthalten. |[.filename]#/usr/local/etc/rc.d# |man:rc[8]-Skripten installierter Anwendungen. |[.filename]#/var/db# |Automatisch generierte systemspezifische Datenbanken, wie die Paket-Datenbank oder die man:locate[1]-Datenbank. |=== === Hostnamen ==== [.filename]#/etc/resolv.conf# Wie ein FreeBSD-System auf das Internet Domain Name System (DNS) zugreift, wird in [.filename]#/etc/resolv.conf# festgelegt. Die gebräuchlichsten Einträge in [.filename]#/etc/resolv.conf# sind: [.informaltable] [cols="1,1", frame="none"] |=== |`nameserver` |Die IP-Adresse eines Nameservers, den der Resolver abfragen soll. Bis zu drei Server werden in der Reihenfolge, in der sie aufgezählt sind, abgefragt. |`search` |Suchliste mit Domain-Namen zum Auflösen von Hostnamen. Die Liste wird normalerweise durch den Domain-Teil des lokalen Hostnamens festgelegt. |`domain` |Der lokale Domain-Name. |=== Beispiel für eine typische [.filename]#/etc/resolv.conf#: [.programlisting] .... search example.com nameserver 147.11.1.11 nameserver 147.11.100.30 .... [NOTE] ==== Nur eine der Anweisungen `search` oder `domain` sollte benutzt werden. ==== Wenn Sie DHCP benutzen, überschreibt man:dhclient[8] für gewöhnlich [.filename]#/etc/resolv.conf# mit den Informationen vom DHCP-Server. ==== [.filename]#/etc/hosts# [.filename]#/etc/hosts# ist eine einfache textbasierte Datenbank. Zusammen mit DNS und NIS stellt sie eine Abbildung zwischen Namen und IP-Adressen zur Verfügung. Anstatt man:named[8] zu konfigurieren, können hier lokale Rechner, die über ein LAN verbunden sind, eingetragen werden. Lokale Einträge für gebräuchliche Internet-Adressen in [.filename]#/etc/hosts# verhindern die Abfrage eines externen Servers und beschleunigen die Namensauflösung. [.programlisting] .... # $FreeBSD$ # # # Host Database # # This file should contain the addresses and aliases for local hosts that # share this file. Replace 'my.domain' below with the domainname of your # machine. # # In the presence of the domain name service or NIS, this file may # not be consulted at all; see /etc/nsswitch.conf for the resolution order. # # ::1 localhost localhost.my.domain 127.0.0.1 localhost localhost.my.domain # # Imaginary network. #10.0.0.2 myname.my.domain myname #10.0.0.3 myfriend.my.domain myfriend # # According to RFC 1918, you can use the following IP networks for # private nets which will never be connected to the Internet: # # 10.0.0.0 - 10.255.255.255 # 172.16.0.0 - 172.31.255.255 # 192.168.0.0 - 192.168.255.255 # # In case you want to be able to connect to the Internet, you need # real official assigned numbers. Do not try to invent your own network # numbers but instead get one from your network provider (if any) or # from your regional registry (ARIN, APNIC, LACNIC, RIPE NCC, or AfriNIC.) # .... [.filename]#/etc/hosts# hat das folgende Format: [.programlisting] .... [Internet Adresse] [Offizieller Hostname] [Alias1] [Alias2] ... .... Zum Beispiel: [.programlisting] .... 10.0.0.1 myRealHostname.example.com myRealHostname foobar1 foobar2 .... Weitere Informationen entnehmen Sie bitte man:hosts[5]. [[configtuning-sysctl]] == Einstellungen mit man:sysctl[8] Mit man:sysctl[8] können Sie Änderungen an einem laufenden FreeBSD-System vornehmen. Unter anderem können Optionen des TCP/IP-Stacks oder des virtuellen Speichermanagements verändert werden. Unter der Hand eines erfahrenen Systemadministrators kann dies die Systemperformance erheblich verbessern. Über 500 Variablen können mit man:sysctl[8] gelesen und gesetzt werden. Der Hauptzweck von man:sysctl[8] besteht darin, Systemeinstellungen zu lesen und zu verändern. Alle auslesbaren Variablen werden wie folgt angezeigt: [source,shell] .... % sysctl -a .... Um eine spezielle Variable zu lesen, geben Sie den Namen an: [source,shell] .... % sysctl kern.maxproc kern.maxproc: 1044 .... Um eine Variable zu setzen, benutzen Sie die Syntax _Variable_= _Wert_: [source,shell] .... # sysctl kern.maxfiles=5000 kern.maxfiles: 2088 -> 5000 .... Mit sysctl können Strings, Zahlen oder Boolean-Werte gesetzt werden. Bei Boolean-Werten steht `1` für wahr und `0` für falsch. Um die Variablen automatisch während des Systemstarts zu setzen, fügen Sie sie in [.filename]#/etc/sysctl.conf# ein. Weitere Informationen finden Sie in der Hilfeseite man:sysctl.conf[5] und in <>. [[configtuning-sysctlconf]] === [.filename]#sysctl.conf# [.filename]#/etc/sysctl.conf# sieht ähnlich wie [.filename]#/etc/rc.conf# aus. Werte werden in der Form `Variable=Wert` gesetzt. Die angegebenen Werte werden gesetzt, nachdem sich das System bereits im Mehrbenutzermodus befindet. Allerdings lassen sich im Mehrbenutzermodus nicht alle Werte setzen. Um das Protokollieren von fatalen Signalen abzustellen und Benutzer daran zu hindern, von anderen Benutzern gestartete Prozesse zu sehen, können Sie in [.filename]#/etc/sysctl.conf# die folgenden Variablen setzen: [.programlisting] .... # Do not log fatal signal exits (e.g. sig 11) kern.logsigexit=0 # Prevent users from seeing information about processes that # are being run under another UID. security.bsd.see_other_uids=0 .... [[sysctl-readonly]] === Schreibgeschützte Variablen Wenn schreibgeschützte man:sysctl[8]-Variablen verändert werden, ist ein Neustart des Systems erforderlich. Beispielsweise hat man:cardbus[4] auf einigen Laptops Schwierigkeiten, Speicherbereiche zu erkennen. Es treten dann Fehlermeldungen wie die folgende auf: [source,shell] .... cbb0: Could not map register memory device_probe_and_attach: cbb0 attach returned 12 .... Um dieses Problem zu lösen, muss eine schreibgeschützte man:sysctl[8]-Variable verändert werden. Fügen Sie `hw.pci.allow_unsupported_io_range=1` in [.filename]#/boot/loader.conf# hinzu und starten Sie das System neu. Danach sollte man:cardbus[4] fehlerfrei funktionieren. [[configtuning-disk]] == Tuning von Laufwerken Der folgende Abschnitt beschreibt die verschiedenen Methoden zur Feinabstimmung der Laufwerke. Oft sind mechanische Teile in Laufwerken, wie SCSI-Laufwerke, verbaut. Diese können einen Flaschenhals bei der Gesamtleistung des Systems darstellen. Sie können zwar auch ein Laufwerk ohne mechanische Teile einbauen, wie z.B. ein Solid-State-Drive, aber Laufwerke mit mechanischen Teilen werden auch in naher Zukunft nicht vom Markt verschwinden. Bei der Feinabstimmung ist es ratsam, die Funktionen von man:iostat[8] zu verwenden, um verschiedene Änderungen zu testen und um nützliche IO-Informationen des Systems zu erhalten. === Sysctl Variablen ==== `vfs.vmiodirenable` Die man:sysctl[8]-Variable `vfs.vmiodirenable` besitzt in der Voreinstellung den Wert `1`. Die Variable kann auf den Wert `0` (deaktiviert) oder `1` (aktiviert) gesetzt werden. Sie steuert, wie Verzeichnisse vom System zwischengespeichert werden. Die meisten Verzeichnisse sind klein und benutzen nur ein einzelnes Fragment, typischerweise 1 kB, im Dateisystem und 512 Bytes im Buffer-Cache. Ist die Variable deaktiviert, wird der Buffer-Cache nur eine limitierte Anzahl Verzeichnisse zwischenspeichern, auch wenn das System über sehr viel Speicher verfügt. Ist die Variable aktiviert, kann der Buffer-Cache den VM-Page-Cache benutzen, um Verzeichnisse zwischenzuspeichern. Der ganze Speicher steht damit zum Zwischenspeichern von Verzeichnissen zur Verfügung. Der Nachteil bei dieser Vorgehensweise ist, dass zum Zwischenspeichern eines Verzeichnisses mindestens eine physikalische Seite im Speicher, die normalerweise 4 kB groß ist, anstelle von 512 Bytes gebraucht wird. Es wird empfohlen, diese Option aktiviert zu lassen, wenn Sie Dienste zur Verfügung stellen, die viele Dateien manipulieren. Beispiele für solche Dienste sind Web-Caches, große Mail-Systeme oder Netnews. Die aktivierte Variable vermindert, trotz des verschwendeten Speichers, in aller Regel nicht die Leistung des Systems, obwohl Sie das nachprüfen sollten. ==== `vfs.write_behind` In der Voreinstellung besitzt die man:sysctl[8]-Variable `vfs.write_behind` den Wert `1` (aktiviert). Mit dieser Einstellung schreibt das Dateisystem anfallende vollständige Cluster, die besonders beim sequentiellen Schreiben großer Dateien auftreten, direkt auf das Medium aus. Dies verhindert, dass sich im Buffer-Cache veränderte Puffer (dirty buffers) ansammeln, die die I/O-Verarbeitung nicht mehr beschleunigen würden. Unter bestimmten Umständen blockiert diese Funktion allerdings Prozesse. Setzen Sie in diesem Fall die Variable `vfs.write_behind` auf den Wert `0`. ==== `vfs.hirunningspace` Die man:sysctl[8]-Variable `vfs.hirunningspace` bestimmt systemweit die Menge ausstehender Schreiboperationen, die dem Platten-Controller zu jedem beliebigen Zeitpunkt übergeben werden können. Normalerweise können Sie den Vorgabewert verwenden. Auf Systemen mit vielen Platten kann der Wert aber auf 4 bis 5 _Megabyte_ erhöht werden. Ein zu hoher Wert (größer als der Schreib-Schwellwert des Buffer-Caches) kann zu Leistungsverlusten führen. Setzen Sie den Wert daher nicht zu hoch! Hohe Werte können auch Leseoperationen verzögern, die gleichzeitig mit Schreiboperationen ausgeführt werden. Es gibt weitere man:sysctl[8]-Variablen, mit denen Sie den Buffer-Cache und den VM-Page-Cache beeinflussen können. Es wird nicht empfohlen, diese Variablen zu verändern, da das VM-System den virtuellen Speicher selbst sehr gut verwaltet. ==== `vm.swap_idle_enabled` Die man:sysctl[8]-Variable `vm.swap_idle_enabled` ist für große Mehrbenutzer-Systeme gedacht, auf denen sich viele Benutzer an- und abmelden und auf denen es viele Prozesse im Leerlauf (idle) gibt. Solche Systeme fragen kontinuierlich freien Speicher an. Wenn Sie die Variable `vm.swap_idle_enabled` aktivieren, können Sie die Auslagerungs-Hysterese von Seiten mit den Variablen `vm.swap_idle_threshold1` und `vm.swap_idle_threshold2` einstellen. Die Schwellwerte beider Variablen geben die Zeit in Sekunden an, in denen sich ein Prozess im Leerlauf befinden muss. Wenn die Werte so eingestellt sind, dass Seiten früher als nach dem normalen Algorithmus ausgelagert werden, verschafft das dem Auslagerungs-Prozess mehr Luft. Aktivieren Sie diese Funktion nur, wenn Sie sie wirklich benötigen: Die Speicherseiten werden eher früher als später ausgelagert. Der Platz im Swap-Bereich wird dadurch schneller verbraucht und die Plattenaktivitäten steigen an. Auf kleinen Systemen hat diese Funktion spürbare Auswirkungen. Auf großen Systemen, die sowieso schon Seiten auslagern müssen, können ganze Prozesse leichter in den Speicher geladen oder ausgelagert werden. ==== `hw.ata.wc` Obwohl das Abstellen des IDE-Schreib-Zwischenspeichers die Bandbreite zum Schreiben auf die IDE-Festplatte verringert, kann es aus Gründen der Datenkonsistenz als notwendig angesehen werden. Das Problem ist, dass IDE-Platten keine zuverlässige Aussage über das Ende eines Schreibvorgangs treffen. Wenn der Schreib-Zwischenspeicher aktiviert ist, werden die Daten nicht in der Reihenfolge ihres Eintreffens geschrieben. Es kann sogar passieren, dass das Schreiben mancher Blöcke im Fall von starker Plattenaktivität auf unbefristete Zeit verzögert wird. Ein Absturz oder Stromausfall zu dieser Zeit kann die Dateisysteme erheblich beschädigen. Sie sollten den Wert der man:sysctl[8]-Variable `hw.ata.wc` auf dem System überprüfen. Wenn der Schreib-Zwischenspeicher abgestellt ist, können Sie ihn beim Systemstart aktivieren, indem Sie die Variable in [.filename]#/boot/loader.conf# auf den Wert `1` setzen. Weitere Informationen finden Sie in man:ata[4]. ==== `SCSI_DELAY` (`kern.cam.scsi_delay`) Mit der Kerneloption `SCSI_DELAY` kann die Dauer des Systemstarts verringert werden. Der Vorgabewert ist recht hoch und er verzögert den Systemstart um `15` oder mehr Sekunden. Normalerweise kann dieser Wert, insbesondere mit modernen Laufwerken, mit der man:sysctl[8]-Variable `kern.cam.scsi_delay` auf `5` Sekunden heruntergesetzt werden. Die Variable sowie die Kerneloption verwenden für die Zeitangabe Millisekunden und _nicht_ Sekunden. [[soft-updates]] === Soft Updates Mit man:tunefs[8] lassen sich Feineinstellungen an Dateisystemen vornehmen. Das Programm hat verschiedene Optionen. Soft Updates werden wie folgt ein- und ausgeschaltet: [source,shell] .... # tunefs -n enable /filesystem # tunefs -n disable /filesystem .... Ein eingehängtes Dateisystem kann nicht mit man:tunefs[8] modifiziert werden. Soft Updates werden am besten im Single-User Modus aktiviert, bevor Partitionen eingehangen sind. Durch Einsatz eines Zwischenspeichers wird die Performance im Bereich der Metadaten, vorwiegend beim Anlegen und Löschen von Dateien, gesteigert. Es wird empfohlen, Soft Updates auf allen UFS-Dateisystemen zu aktivieren. Allerdings sollten Sie sich über die zwei Nachteile von Soft Updates bewusst sein: Erstens garantieren Soft Updates zwar die Konsistenz der Daten im Fall eines Absturzes, aber es kann passieren, dass das Dateisystem über mehrere Sekunden oder gar eine Minute nicht synchronisiert wurde. Nicht geschriebene Daten gehen dann vielleicht verloren. Zweitens verzögern Soft Updates die Freigabe von Datenblöcken. Eine größere Aktualisierung eines fast vollen Dateisystems, wie dem Root-Dateisystem, z.B. während eines `make installworld`, kann das Dateisystem vollaufen lassen. Dadurch würde die Aktualisierung fehlschlagen. ==== Details über Soft Updates Bei einem Metadaten-Update werden die Inodes und Verzeichniseinträge aktualisiert auf die Platte zurückgeschrieben. Es gibt zwei klassische Ansätze, um die Metadaten des Dateisystems auf die Platte zu schreiben. Das historisch übliche Verfahren waren synchrone Updates der Metadaten, d. h. wenn eine Änderung an einem Verzeichnis nötig war, wurde anschließend gewartet, bis diese Änderung tatsächlich auf die Platte zurückgeschrieben worden war. Der _Inhalt_ der Dateien wurde im "Buffer Cache" zwischengespeichert und später asynchron auf die Platte geschrieben. Der Vorteil dieser Implementierung ist, dass sie sicher funktioniert. Wenn während eines Updates ein Ausfall erfolgt, haben die Metadaten immer einen konsistenten Zustand. Eine Datei ist entweder komplett angelegt oder gar nicht. Wenn die Datenblöcke einer Datei im Fall eines Absturzes noch nicht den Weg aus dem "Buffer Cache" auf die Platte gefunden haben, kann man:fsck[8] das Dateisystem reparieren, indem es die Dateilänge einfach auf `0` setzt. Außerdem ist die Implementierung einfach und überschaubar. Der Nachteil ist, dass Änderungen der Metadaten sehr langsam vor sich gehen. Ein `rm -r` beispielsweise fasst alle Dateien eines Verzeichnisses der Reihe nach an, aber jede dieser Änderungen am Verzeichnis (Löschen einer Datei) wird einzeln synchron auf die Platte geschrieben. Gleiches beim Auspacken großer Hierarchien mit `tar -x`. Der zweite Ansatz sind asynchrone Metadaten-Updates. Das ist der Standard, wenn UFS-Dateisysteme mit `mount -o async` eingehängt werden. Man schickt die Updates der Metadaten einfach auch noch über den "Buffer Cache", sie werden also zwischen die Updates der normalen Daten eingeschoben. Vorteil ist, dass man nun nicht mehr auf jeden Update warten muss, Operationen, die zahlreiche Metadaten ändern, werden also viel schneller. Auch hier ist die Implementierung sehr einfach und wenig anfällig für Fehler. Nachteil ist, dass keinerlei Konsistenz des Dateisystems mehr gesichert ist. Wenn mitten in einer Operation, die viele Metadaten ändert, ein Ausfall erfolgt (Stromausfall, drücken des Reset-Schalters), dann ist das Dateisystem anschließend in einem unbestimmten Zustand. Niemand kann genau sagen, was noch geschrieben worden ist und was nicht mehr; die Datenblöcke einer Datei können schon auf der Platte stehen, während die inode Tabelle oder das zugehörige Verzeichnis nicht mehr aktualisiert worden ist. Man kann praktisch kein man:fsck[8] mehr implementieren, das diesen Zustand wieder reparieren kann, da die dazu nötigen Informationen einfach auf der Platte fehlen. Wenn ein Dateisystem irreparabel beschädigt wurde, hat man nur noch die Möglichkeit es neu zu erzeugen und die Daten vom Backup zurückspielen. Der Ausweg aus diesem Dilemma ist ein _dirty region logging_, was auch als _Journalling_ bezeichnet wird. Man schreibt die Metadaten-Updates zwar synchron, aber nur in einen kleinen Plattenbereich, die _logging area_. Von da aus werden sie dann asynchron auf ihre eigentlichen Bereiche verteilt. Da die _logging area_ ein kleines zusammenhängendes Stückchen ist, haben die Schreibköpfe der Platte bei massiven Operationen auf Metadaten keine allzu großen Wege zurückzulegen, so dass alles ein ganzes Stück schneller geht als bei klassischen synchronen Updates. Die Komplexität der Implementierung hält sich ebenfalls in Grenzen, somit auch die Anfälligkeit für Fehler. Als Nachteil ergibt sich, dass Metadaten zweimal auf die Platte geschrieben werden müssen (einmal in die _logging area_, einmal an die richtige Stelle), so dass das im Falle regulärer Arbeit (also keine gehäuften Metadatenoperationen) eine "Pessimisierung" des Falls der synchronen Updates eintritt, es wird alles langsamer. Dafür hat man als Vorteil, dass im Falle eines Absturzes der konsistente Zustand dadurch erzielbar ist, dass die angefangenen Operationen aus dem _dirty region log_ entweder zu Ende ausgeführt oder komplett verworfen werden, wodurch das Dateisystem schnell wieder zur Verfügung steht. Die Lösung von Kirk McKusick, dem Schöpfer von Berkeley FFS, waren _Soft Updates_: die notwendigen Updates der Metadaten werden im Speicher gehalten und dann sortiert auf die Platte geschrieben ("ordered metadata updates"). Dadurch hat man den Effekt, dass im Falle massiver Metadaten-Änderungen spätere Operationen die vorhergehenden, noch nicht auf die Platte geschriebenen Updates desselben Elements im Speicher "einholen". Alle Operationen, auf ein Verzeichnis beispielsweise, werden also in der Regel noch im Speicher abgewickelt, bevor der Update überhaupt auf die Platte geschrieben wird (die dazugehörigen Datenblöcke werden natürlich auch so sortiert, dass sie nicht vor ihren Metadaten auf der Platte sind). Im Fall eines Absturzes hat man ein implizites "log rewind": alle Operationen, die noch nicht den Weg auf die Platte gefunden haben, sehen danach so aus, als hätten sie nie stattgefunden. Man hat so also den konsistenten Zustand von ca. 30 bis 60 Sekunden früher sichergestellt. Der verwendete Algorithmus garantiert dabei, dass alle tatsächlich benutzten Ressourcen auch in den entsprechenden Bitmaps (Block- und inode Tabellen) als belegt markiert sind. Der einzige Fehler, der auftreten kann, ist, dass Ressourcen noch als "belegt" markiert sind, die tatsächlich "frei" sind. man:fsck[8] erkennt dies und korrigiert diese nicht mehr belegten Ressourcen. Die Notwendigkeit eines Dateisystem-Checks darf aus diesem Grunde auch ignoriert und das Dateisystem mittels `mount -f` zwangsweise eingebunden werden. Um noch allozierte Ressourcen freizugeben muss später ein man:fsck[8] nachgeholt werden. Das ist dann auch die Idee des _background fsck_: beim Starten des Systems wird lediglich ein _Schnappschuss_ des Dateisystems gemacht, mit dem man:fsck[8] dann später arbeiten kann. Alle Dateisysteme dürfen "unsauber" eingebunden werden und das System kann sofort in den Multiuser-Modus gehen. Danach wird ein Hintergrund-man:fsck[8] für die Dateisysteme gestartet, die dies benötigen, um möglicherweise irrtümlich belegte Ressourcen freizugeben. Dateisysteme ohne _Soft Updates_ benötigen natürlich immer noch den üblichen Vordergrund-man:fsck[8], bevor sie eingebunden werden können. Der Vorteil ist, dass die Metadaten-Operationen beinahe so schnell ablaufen wie im asynchronen Fall, also auch schneller als beim _logging_, das die Metadaten immer zweimal schreiben muss. Als Nachteil stehen dem die Komplexität des Codes, ein erhöhter Speicherverbrauch und einige spezielle Eigenheiten entgegen. Nach einem Absturz ist ein etwas "älterer" Stand auf der Platte - statt einer leeren, aber bereits angelegten Datei, wie nach einem herkömmlichen man:fsck[8] Lauf, ist auf einem Dateisystem mit _Soft Updates_ keine Spur der entsprechenden Datei mehr zu sehen, da weder die Metadaten noch der Dateiinhalt je auf die Platte geschrieben wurden. Weiterhin kann der Platz nach einem man:rm[1] nicht sofort wieder als verfügbar markiert werden, sondern erst dann, wenn der Update auch auf die Platte vermittelt worden ist. Dies kann besonders dann Probleme bereiten, wenn große Datenmengen in einem Dateisystem installiert werden, das nicht genügend Platz hat, um alle Dateien zweimal unterzubringen. [[configtuning-kernel-limits]] == Einstellungen von Kernel Limits [[file-process-limits]] === Datei und Prozeß Limits [[kern-maxfiles]] ==== `kern.maxfiles` Abhängig von den Anforderungen an das System kann die man:sysctl[8]-Variable `kern.maxfiles` erhöht oder gesenkt werden. Die Variable legt die maximale Anzahl von Dateideskriptoren auf dem System fest. Wenn die Dateideskriptoren aufgebraucht sind, werden Sie die Meldung `file: table is full` wiederholt im Puffer für Systemmeldungen sehen. Den Inhalt des Puffers können Sie sich mit man:dmesg[8] anzeigen lassen. Jede offene Datei, jedes Socket und jede FIFO verbraucht einen Dateideskriptor. Auf "dicken" Produktionsservern können leicht Tausende Dateideskriptoren benötigt werden, abhängig von der Art und Anzahl der gleichzeitig laufenden Dienste. In älteren FreeBSD-Versionen wurde die Voreinstellung von `kern.maxfile` aus der Kernelkonfigurationsoption `maxusers` bestimmt. `kern.maxfiles` wächst proportional mit dem Wert von `maxusers`. Wenn Sie einen angepassten Kernel kompilieren, empfiehlt es sich diese Option entsprechend der maximalen Benutzerzahl des Systems einzustellen. Obwohl auf einer Produktionsmaschine vielleicht nicht 256 Benutzer gleichzeitig angemeldet sind, können die benötigten Ressourcen ähnlich hoch wie bei einem großen Webserver sein. Die nur lesbare man:sysctl[8]-Variable `kern.maxusers` wird beim Systemstart automatisch aus dem zur Verfügung stehenden Hauptspeicher bestimmt. Im laufenden Betrieb kann dieser Wert aus `kern.maxusers` ermittelt werden. Einige Systeme benötigen für diese Variable einen anderen Wert, wobei `64`, `128` und `256` gewöhnliche Werte darstellen. Es wird nicht empfohlen, die Anzahl der Dateideskriptoren auf einen Wert größer `256` zu setzen, es sei denn, Sie benötigen wirklich eine riesige Anzahl von ihnen. Viele der von `kern.maxusers` auf einen Standardwert gesetzten Parameter können beim Systemstart oder im laufenden Betrieb in [.filename]#/boot/loader.conf# angepasst werden. In man:loader.conf[5] und [.filename]#/boot/defaults/loader.conf# finden Sie weitere Details und Hinweise. Ältere FreeBSD-Versionen setzen diesen Wert selbst, wenn Sie in der Konfigurationsdatei den Wert `0` angeben. Wenn Sie den Wert selbst bestimmen wollen, sollten Sie `maxusers` mindestens auf `4` setzen. Dies gilt insbesondere dann, wenn Sie beabsichtigen, Xorg zu benutzen oder Software zu kompilieren. Der wichtigste Wert, der durch `maxusers` bestimmt wird, die maximale Anzahl an Prozessen ist, die auf `20 + 16 * maxusers` gesetzt wird. Wird `maxusers` auf `1` setzen, können gleichzeitig nur `36` Prozesse laufen, von denen ungefähr `18` schon beim Booten des Systems gestartet werden. Dazu kommen nochmals etwa `15` Prozesse beim Start von Xorg. Selbst eine einfache Aufgabe wie das Lesen einer Manualpage benötigt neun Prozesse zum Filtern, Dekomprimieren und Betrachten der Datei. Für die meisten Benutzer sollte es ausreichen, `maxusers` auf `64` zu setzen, womit `1044` gleichzeitige Prozesse zur Verfügung stehen. Wenn Sie allerdings den Fehler beim Start eines Programms oder auf einem Server mit einer großen Benutzerzahl sehen, dann sollten Sie den Wert nochmals erhöhen und den Kernel neu bauen. [NOTE] ==== Die Anzahl der Benutzer, die sich auf einem Rechner anmelden kann, wird durch `maxusers` _nicht_ begrenzt. Der Wert dieser Variablen legt neben der möglichen Anzahl der Prozesse eines Benutzers weitere sinnvolle Größen für bestimmte Systemtabellen fest. ==== ==== `kern.ipc.soacceptqueue` Die man:sysctl[8]-Variable `kern.ipc.soacceptqueue` beschränkt die Größe der Warteschlange (Listen-Queue) für neue TCP-Verbindungen. Der Vorgabewert von `128` ist normalerweise zu klein, um neue Verbindungen auf einem stark ausgelasteten Webserver zuverlässig zu handhaben. Auf solchen Servern sollte der Wert auf `1024` oder höher gesetzt werden. Dienste wie man:sendmail[8] oder Apache können die Größe der Queue selbst einschränken. Oft gibt es die Möglichkeit, die Größe der Listen-Queue in einer Konfigurationsdatei einzustellen. Eine große Listen-Queue übersteht vielleicht auch einen Denial of Service Angriff (). [[nmbclusters]] === Netzwerk Limits Die Kerneloption `NMBCLUSTERS` schreibt die Anzahl der Netzwerkpuffer (Mbufs) fest, die das System besitzt. Eine zu geringe Anzahl Mbufs auf einem Server mit viel Netzwerkverkehr verringert die Leistung von FreeBSD. Jeder Mbuf-Cluster nimmt ungefähr 2 kB Speicher in Anspruch, so dass ein Wert von `1024` insgesamt 2 Megabyte Speicher für Netzwerkpuffer im System reserviert. Wie viele Cluster benötigt werden, lässt sich durch eine einfache Berechnung herausfinden. Ein Webserver, der maximal `1000` gleichzeitige Verbindungen servieren soll, wobei jede der Verbindungen einen 6 kB großen Sendepuffer und einen 16 kB großen Empfangspuffer benötigt, braucht ungefähr 32 MB Speicher für Netzwerkpuffer. Als Daumenregel verdoppeln Sie diese Zahl, so dass sich für `NMBCLUSTERS` der Wert 2x32 MB / 2 kB= 64 MB / 2 kB= `32768` ergibt. Für Maschinen mit viel Speicher werden Werte zwischen `4096` und `32768` empfohlen. Unter keinen Umständen sollten Sie diesen Wert willkürlich erhöhen, da dies zu einem Absturz beim Systemstart führen kann. Verwenden Sie man:netstat[1] mit `-m` um den Gebrauch der Netzwerkpuffer zu kontrollieren. Die Netzwerkpuffer können beim Systemstart mit der Loader-Variablen `kern.ipc.nmbclusters` eingestellt werden. Nur auf älteren FreeBSD-Systemen müssen Sie die Kerneloption `NMBCLUSTERS` verwenden. Die Anzahl der man:sendfile[2] Puffer muss auf ausgelasteten Servern, die den Systemaufruf man:sendfile[2] oft verwenden, vielleicht erhöht werden. Dazu können Sie die Kerneloption `NSFBUFS` verwenden oder die Anzahl der Puffer in [.filename]#/boot/loader.conf# (siehe man:loader[8]) setzen. Die Puffer sollten erhöht werden, wenn Sie Prozesse im Zustand `sfbufa` sehen. Die schreibgeschützte man:sysctl[8]-Variable `kern.ipc.nsfbufs` zeigt die Anzahl eingerichteten Puffer im Kernel. Der Wert dieser Variablen wird normalerweise von `kern.maxusers` bestimmt. Manchmal muss die Pufferanzahl jedoch manuell eingestellt werden. [IMPORTANT] ==== Auch wenn ein Socket nicht blockierend angelegt wurde, kann der Aufruf von man:sendfile[2] blockieren, um auf freie `struct sf_buf` Puffer zu warten. ==== ==== `net.inet.ip.portrange.*` Die man:sysctl[8]-Variable `net.inet.ip.portrange.*` legt die Portnummern für TCP- und UDP-Sockets fest. Es gibt drei Bereiche: den niedrigen Bereich, den normalen Bereich und den hohen Bereich. Die meisten Netzprogramme benutzen den normalen Bereich. Dieser Bereich umfasst in der Voreinstellung die Portnummern `1024` bis `5000` und wird durch die Variablen `net.inet.ip.portrange.first` und `net.inet.ip.portrange.last` festgelegt. Die festgelegten Bereiche für Portnummern werden von ausgehenden Verbindungen benutzt. Unter bestimmten Umständen, beispielsweise auf stark ausgelasteten Proxy-Servern, sind alle Portnummern für ausgehende Verbindungen belegt. Bereiche für Portnummern spielen auf Servern keine Rolle, die hauptsächlich eingehende Verbindungen verarbeiten (wie ein normaler Webserver) oder nur eine begrenzte Anzahl ausgehender Verbindungen öffnen (beispielsweise ein Mail-Relay). Wenn keine freien Portnummern mehr vorhanden sind, sollte die Variable `net.inet.ip.portrange.last` langsam erhöht werden. Ein Wert von `10000`, `20000` oder `30000` ist angemessen. Beachten Sie auch eine vorhandene Firewall, wenn Sie die Bereiche für Portnummern ändern. Einige Firewalls sperren große Bereiche (normalerweise aus den kleinen Portnummern) und erwarten, dass hohe Portnummern für ausgehende Verbindungen verwendet werden. Daher kann es erforderlich sein, den Wert von `net.inet.ip.portrange.first` zu erhöhen. ==== `TCP` Bandwidth Delay Product Begrenzung Die `TCP` Bandwidth Delay Product Begrenzung wird aktiviert, indem die man:sysctl[8]-Variable `net.inet.tcp.inflight.enable` auf den Wert `1` gesetzt wird. Das System wird dadurch angewiesen, für jede Verbindung, das Produkt aus der Übertragungsrate und der Verzögerungszeit zu bestimmen. Dieses Produkt begrenzt die Datenmenge, die für einen optimalen Durchsatz zwischengespeichert werden muss. Diese Begrenzung ist nützlich, wenn Sie Daten über Verbindungen mit einem hohen Produkt aus Übertragungsrate und Verzögerungszeit wie Modems, Gigabit-Ethernet oder schnellen WANs, zur Verfügung stellen. Insbesondere wirkt sich die Begrenzung aus, wenn die Verbindung die Option Window-scaling verwendet oder große Sende-Fenster (send window) benutzt. Schalten Sie die Debug-Meldungen aus, wenn Sie die Begrenzung aktiviert haben. Dazu setzen Sie die Variable `net.inet.tcp.inflight.debug` auf `0`. Auf Produktions-Systemen sollten Sie zudem die Variable `net.inet.tcp.inflight.min` mindestens auf den Wert `6144` setzen. Allerdings kann ein zu hoher Wert, abhängig von der Verbindung, die Begrenzungsfunktion unwirksam machen. Die Begrenzung reduziert die Datenmenge in den Queues von Routern und Switches, sowie die Datenmenge in der Queue der lokalen Netzwerkkarte. Die Verzögerungszeit (Round Trip Time) für interaktive Anwendungen sinkt, da weniger Pakete zwischengespeichert werden. Dies gilt besonders für Verbindungen über langsame Modems. Die Begrenzung wirkt sich allerdings nur auf das Versenden von Daten aus (Uploads, Server). Auf den Empfang von Daten (Downloads) hat die Begrenzung keine Auswirkungen. Die Variable `net.inet.tcp.inflight.stab` sollte _nicht_ angepasst werden. Der Vorgabewert der Variablen beträgt `20`, das heißt es werden maximal zwei Pakete zu dem Produkt aus Übertragungsrate und Verzögerungszeit addiert. Dies stabilisiert den Algorithmus und verbessert die Reaktionszeit auf Veränderungen. Bei langsamen Verbindungen können sich aber die Laufzeiten der Pakete erhöhen (ohne diesen Algorithmus wären sie allerdings noch höher). In solchen Fällen können Sie versuchen, den Wert der Variablen auf `15`, `10` oder `5` herabzusetzen. Gleichzeitig müssen Sie vielleicht auch `net.inet.tcp.inflight.min` auf einen kleineren Wert (beispielsweise `3500`) setzen. Ändern Sie diese Variablen nur ab, wenn Sie keine anderen Möglichkeiten mehr haben. === Virtueller Speicher (Virtual Memory) ==== `kern.maxvnodes` Ein vnode ist die interne Darstellung einer Datei oder eines Verzeichnisses. Die Erhöhung der Anzahl der für das Betriebssystem verfügbaren vnodes verringert also die Schreib- und Lesezugriffe auf der Festplatte. vnodes werden im Normalfall vom Betriebssystem automatisch vergeben und müssen nicht manuell angepasst werden. In einigen Fällen stellt der Zugriff auf eine Platte allerdings einen Flaschenhals dar, daher sollten Sie in diesem Fall die Anzahl der möglichen vnodes erhöhen, um dieses Problem zu beheben. Beachten Sie dabei aber die Größe des inaktiven und freien Hauptspeichers. Um die Anzahl der derzeit verwendeten vnodes zu sehen, geben Sie Folgendes ein: [source,shell] .... # sysctl vfs.numvnodes vfs.numvnodes: 91349 .... Die maximal mögliche Anzahl der vnodes erhalten Sie durch die Eingabe von: [source,shell] .... # sysctl kern.maxvnodes kern.maxvnodes: 100000 .... Wenn sich die Anzahl der genutzten vnodes dem maximal möglichen Wert nähert, sollten Sie den Wert `kern.maxvnodes` zuerst um etwa `1000` erhöhen. Beobachten Sie danach die Anzahl der vom System genutzten `vfs.numvnodes`. Nähert sich der Wert wiederum dem definierten Maximum, müssen Sie `kern.maxvnodes` nochmals erhöhen. Sie sollten nun eine Änderung des Speicherverbrauches über man:top[1] registrieren können und über mehr aktiven Speicher verfügen. [[adding-swap-space]] == Hinzufügen von Swap-Bereichen Manchmal benötigt ein System mehr Swap-Bereiche. Dieser Abschnitt beschreibt zwei Methoden, um Swap-Bereiche hinzuzufügen: auf einer bestehenden Partition oder auf einem neuen Laufwerk, und das Hinzufügen einer Swap-Datei auf einer existierenden Partition. Für Informationen zur Verschlüsselung von Swap-Partitionen, zu den dabei möglichen Optionen sowie zu den Gründen für eine Verschlüsselung des Auslagerungsspeichers lesen Sie crossref:disks[swap-encrypting,“Den Auslagerungsspeicher verschlüsseln”]. [[new-drive-swap]] === Swap auf einer neuen Festplatte oder einer existierenden Partition Das Hinzufügen einer neuen Festplatte für den Swap-Bereich bietet eine bessere Leistung, als die Verwendung einer Partition auf einem vorhandenem Laufwerk. Die Einrichtung von Partitionen und Laufwerken wird in crossref:disks[disks-adding,“Hinzufügen von Laufwerken“] beschrieben. crossref:bsdinstall[configtuning-initial,“Ein Partitionslayout entwerfen“] diskutiert Aspekte über die Anordnung und Größe von Swap-Bereichen. Benutzen Sie `swapon` um eine Swap-Partition zum System hinzuzufügen. Zum Beispiel: [source,shell] .... # swapon /dev/ada1s1b .... [WARNING] ==== Sie können jede Partition verwenden, sofern sie nicht schon eingehangen ist. Das gilt auch dann, wenn die Partition bereits Daten enthält. Wird `swapon` auf einer Partition ausgeführt die Daten enthält, werden die vorhandenen Daten überschrieben und sind unweigerlich verloren. Stellen Sie sicher, dass die Partition, die Sie als Swap-Bereich hinzufügen möchten, wirklich die gewünschte Partition ist, bevor Sie `swapon` ausführen. ==== Um diese Swap-Partition automatisch beim Systemstart hinzuzufügen, fügen Sie einen Eintrag in [.filename]#/etc/fstab# hinzu: [.programlisting] .... /dev/ada1s1b none swap sw 0 0 .... Die einzelnen Einträge von [.filename]#/etc/fstab# werden in man:fstab[5] erläutert. Weitere Informationen zu `swapon` finden Sie in man:swapon[8]. [[create-swapfile]] === Swap-Dateien erstellen Anstatt eine Partition zu verwenden, erstellen diese Beispiele eine 512 MB große Swap-Datei mit dem Namen [.filename]#/usr/swap0#. Die Verwendung von Swap-Dateien macht es erforderlich, dass das Modul man:md[4] entweder im Kernel vorhanden oder geladen wird, bevor Swap aktiviert ist. crossref:kernelconfig[kernelconfig,Konfiguration des FreeBSD-Kernels] enthält Informationen zum Bau eines angepassten Kernels. [[swapfile-10-and-later]] .Erstellen einer Swap-Datei [example] ==== [.procedure] . Erstellen Sie die Swap-Datei: + [source,shell] .... # dd if=/dev/zero of=/usr/swap0 bs=1024k count=512 .... . Setzen Sie die richtigen Berechtigungen für die neue Datei: + [source,shell] .... # chmod 0600 /usr/swap0 .... . Fügen Sie einen Eintrag in [.filename]#/etc/fstab# hinzu: + [.programlisting] .... md99 none swap sw,file=/usr/swap0,late 0 0 .... + Das man:md[4] Gerät [.filename]#md99# wird verwendet, damit die niedrigeren Gerätenummer für die interaktive Benutzung frei bleiben. . Der Swap-Speicher wird nun automatisch beim Systemstart hinzugefügt. Benutzen Sie man:swapon[8] um den Swap-Speicher direkt zu aktivieren: + [source,shell] .... # swapon -aL .... ==== [[acpi-overview]] == Energie- und Ressourcenverwaltung Es ist wichtig, Hardware effizient einzusetzen. Energie- und Ressourcenverwaltung ermöglicht es dem System auf verschiedene Ereignisse, beispielsweise einen unerwarteten Temperaturanstieg, reagieren zu können. Eine frühe Spezifikation für die Energieverwaltung war das Advanced Power Management (APM). APM steuert den Energieverbrauch eines Systems auf Basis der Systemaktivität. Ursprünglich konnten Stromverbrauch und Wärmeabgabe eines Systems nur schlecht von Betriebssystemen gesteuert werden. Die Hardware wurde vom BIOS gesteuert, was die Kontrolle der Energieverwaltung für den Anwender erschwerte. Das APM-BIOS wird von dem Hersteller des Systems zur Verfügung gestellt und ist auf die spezielle Hardware angepasst. Der APM-Treiber des Betriebssystems greift auf das _APM Software Interface_ zu, das den Energieverbrauch regelt. APM hat hauptsächlich vier Probleme. Erstens läuft die Energieverwaltung unabhängig vom Betriebssystem in einem herstellerspezifischen BIOS. Beispielsweise kann das APM-BIOS die Festplatten nach einer konfigurierbaren Zeit ohne die Zustimmung des Betriebssystems herunterfahren. Zweitens befindet sich die ganze APM-Logik im BIOS; das Betriebssystem hat gar keine APM-Komponenten. Bei Problemen mit dem APM-BIOS muss das Flash-ROM aktualisiert werden. Diese Prozedur ist gefährlich, da sie im Fehlerfall das System unbrauchbar machen kann. Zum Dritten ist APM eine Technik, die herstellerspezifisch ist und nicht koordiniert wird. Fehler im BIOS eines Herstellers werden nicht unbedingt im BIOS anderer Hersteller korrigiert. Das letzte Problem ist, dass im APM-BIOS nicht genügend Platz vorhanden ist, um eine durchdachte oder eine auf den Zweck der Maschine zugeschnittene Energieverwaltung zu implementieren. Das _Plug and Play BIOS (PNPBIOS)_ war in vielen Situationen ebenfalls unzureichend. Das PNPBIOS verwendet eine 16-Bit-Technik. Damit das Betriebssystem das PNPBIOS ansprechen kann, muss es in einer 16-Bit-Emulation laufen. FreeBSD stellt einen APM-Treiber zur Verfügung, welcher für Systeme benutzt werden sollte, die vor dem Jahr 2000 hergestellt wurden. Der Treiber wird in man:apm[4] beschrieben. Der Nachfolger von APM ist das _Advanced Configuration and Power Interface_ (ACPI). ACPI ist ein Standard verschiedener Hersteller, welcher die Verwaltung von Hardware und Energiesparfunktionen festlegt. Die ACPI-Funktionen, die mehr Kontrolle und Flexibilität bieten, können vom Betriebssystem gesteuert werden. Dieser Abschnitt zeigt die Konfiguration von ACPI unter FreeBSD. Zudem werden einige Tipps zur Fehlersuche vorgestellt und wie Sie Problemberichte einreichen können, sodass Entwickler ACPI-Probleme erfassen und beheben können. [[acpi-config]] === Konfiguration des ACPI Der man:acpi[4]-Treiber wird standardmäßig beim Systemstart vom man:loader[8] geladen und sollte daher _nicht_ fest in den Kernel eingebunden werden. Der Treiber kann im laufenden Betrieb nicht entfernt werden, da er zur Kommunikation mit der Hardware verwendet wird. Falls jedoch Probleme auftreten, kann ACPI auch komplett deaktiviert werden. Dazu muss `hint.acpi.0.disabled="1"` in [.filename]#/boot/loader.conf# gesetzt und anschließend das System neu gestartet werden. Alternativ können Sie diese Variable auch am man:loader[8]-Prompt eingeben, wie in crossref:boot[boot-loader,“Phase Drei”] beschrieben. [NOTE] ==== ACPI und APM können nicht zusammen verwendet werden. Das zuletzt geladene Modul beendet sich, sobald es bemerkt, dass das andere Modul geladen ist. ==== Mit `acpiconf` können Sie das System in einen Ruhemodus (sleep mode) versetzen. Es gibt verschiedene Modi (von `1` bis `5`), die Sie auf der Kommandozeile mit `-s` angeben können. Für die meisten Anwender sind die Modi `1` und `3` völlig ausreichend. Der Modus `5` schaltet das System aus (Soft-off) und entspricht dem Befehl `halt -p`. Verschiedene Optionen können mit `sysctl` gesetzt werden. Lesen Sie dazu man:acpi[4] sowie man:acpiconf[8]. [[ACPI-comprob]] === Häufige Probleme ACPI gibt es in allen modernen Rechnern der ia32- (x86) und amd64- (AMD) Architektur. Der vollständige Standard bietet Funktionen zur Steuerung und Verwaltung der CPU-Leistung, der Stromversorgung, von Wärmebereichen, Batterien, eingebetteten Controllern und Bussen. Auf den meisten Systemen wird nicht der vollständige Standard implementiert. Arbeitsplatzrechner besitzen meist nur Funktionen zur Verwaltung der Busse, während Notebooks Funktionen zur Temperaturkontrolle und Ruhezustände besitzen. Ein ACPI konformes System besitzt verschiedene Komponenten. Die BIOS- und Chipsatz-Hersteller stellen mehrere statische Tabellen bereit, zum Beispiel die Fixed-ACPI-Description-Table (FADT). Die Tabellen enthalten beispielsweise die mit SMP-Systemen benutzte APIC-Map, Konfigurationsregister und einfache Konfigurationen. Zusätzlich gibt es die _Differentiated-System-Description-Table_ (DSDT), die Bytecode enthält. Die Tabelle ordnet Geräte und Methoden in einem baumartigen Namensraum an. Ein ACPI-Treiber muss die statischen Tabellen einlesen, einen Interpreter für den Bytecode bereitstellen und die Gerätetreiber im Kernel so modifizieren, dass sie mit dem ACPI-Subsystem kommunizieren. Für FreeBSD, Linux(R) und NetBSD hat Intel(R) den Interpreter ACPI-CA, zur Verfügung gestellt. Der Quelltext zu ACPI-CA befindet sich im Verzeichnis [.filename]#src/sys/contrib/dev/acpica#. Die Schnittstelle von ACPI-CA zu FreeBSD befindet sich unter [.filename]#src/sys/dev/acpica/Osd#. Treiber, die verschiedene ACPI-Geräte implementieren, befinden sich im Verzeichnis [.filename]#src/sys/dev/acpica#. Damit ACPI richtig funktioniert, müssen alle Teile funktionieren. Im Folgenden finden Sie eine Liste mit Problemen und möglichen Abhilfen oder Korrekturen. Die Liste ist nach der Häufigkeit, mit der die Probleme auftreten, sortiert. Wenn eine Korrektur das Problem nicht behebt, finden Sie in <> Anweisungen, wie Sie einen Problembericht einreichen können. ==== Mausprobleme Es kann vorkommen, dass die Maus nicht mehr funktioniert, wenn Sie nach einem Suspend weiterarbeiten wollen. Ist dies bei Ihnen der Fall, reicht es meistens aus, den Eintrag `hint.psm.0.flags="0x3000"` in [.filename]#/boot/loader.conf# aufzunehmen. ==== Suspend/Resume ACPI kennt drei Suspend-to-RAM-Zustände (STR), `S1`-`S3` sowie einen Suspend-to-Disk-Zustand (STD) `S4`. STD kann auf zwei Arten implementiert werden: ``S4``BIOS und ``S4``OS. Im ersten Fall wird der Suspend-to-Disk-Zustand durch das BIOS hergestellt im zweiten Fall alleine durch das Betriebssystem. Der Zustand `S5` wird "Soft off" genannt. In diesem Zustand befindet sich ein Rechner, wenn die Stromversorgung angeschlossen ist, der Rechner aber nicht hochgefahren ist. Benutzen Sie `sysctl hw.acpi` um die Suspend-Zustände zu ermitteln. Diese Beispielausgabe stammt von einem Thinkpad: [source,shell] .... hw.acpi.supported_sleep_state: S3 S4 S5 hw.acpi.s4bios: 0 .... Diese Ausgabe besagt, dass mit dem Befehl `acpiconf -s` die Zustände `S3`, `S4` und `S5` eingestellt werden können. Hätte `s4bios` den Wert `1`, gäbe es den Zustand ``S4``BIOS anstelle von `S4`. Wenn Sie die Suspend- und Resume-Funktionen testen, fangen Sie mit dem `S1`-Zustand an, wenn er angeboten wird. Dieser Zustand wird am ehesten funktionieren, da der Zustand wenig Treiber-Unterstützung benötigt. Der Zustand `S2` ist ähnlich wie `S1`, allerdings hat ihn noch niemand implementiert. Als nächstes sollten Sie den Zustand `S3` ausprobieren. Dies ist der tiefste STR-Schlafzustand. Dieser Zustand ist auf massive Treiber-Unterstützung angewiesen, um die Geräte wieder richtig zu initialisieren. Ein häufiges Problem mit Suspend/Resume ist, dass viele Gerätetreiber ihre Firmware, Register und Gerätespeicher nicht korrekt speichern, wiederherstellen und/oder reinitialisieren. Um dieses Problem zu lösen, sollten Sie zuerst die folgenden Befehle ausführen: [source,shell] .... # sysctl debug.bootverbose=1 # sysctl debug.acpi.suspend_bounce=1 # acpiconf -s 3 .... Dieser Test emuliert einen Suspend/Resume-Zyklus für alle Geräte (ohne dass diese dabei wirklich in den Status `S3` wechseln). In vielen Fällen reicht dies bereits aus, um Probleme (beispielsweise verlorener Firmware-Status, Timeouts, hängende Geräte) zu entdecken. Beachten Sie dabei, dass das Gerät bei diesem Test nicht wirklich in den Status `S3` wechseln. Es kann also vorkommen, dass manche Geräte weiterhin mit Strom versorgt werden (dies wäre bei einem wirklichen Wechsel in den Status `S3` NICHT möglich. Andere Geräte werden normal weiterarbeiten, weil sie über keine Suspend/Resume-Funktionen verfügen. Schwierigere Fälle können den Einsatz zusätzlicher Hardware (beispielsweise serielle Ports/Kabel für die Verbindung über eine serielle Konsole oder Firewire-Ports/Kabel für man:dcons[4]) sowie Kenntnisse im Bereich Kerneldebugging erforderlich machen. Um das Problem einzugrenzen, entladen Sie soviele Treiber wie möglich. Wenn das funktioniert, laden Sie einen Treiber nach dem anderen, bis der Fehler wieder auftritt. Typischerweise verursachen binäre Treiber wie [.filename]#nvidia.ko#, Grafiktreiber und USB-Treiber die meisten Fehler, hingegen laufen Ethernet-Treiber für gewöhnlich sehr zuverlässig. Wenn ein Treiber zuverlässig geladen und entfernt werden kann, können Sie den Vorgang automatisieren, indem Sie die entsprechenden Kommandos in [.filename]#/etc/rc.suspend# und [.filename]#/etc/rc.resume# einfügen. In den Dateien finden Sie ein deaktiviertes Beispiel, das einen Treiber lädt und wieder entfernt. Ist die Bildschirmanzeige bei der Wiederaufnahme des Betriebs gestört, setzen Sie die Variable `hw.acpi.reset_video` auf `1`. Versuchen Sie auch, die Variable `hw.acpi.sleep_delay` auf kürzere Zeitspannen zu setzen. Die Suspend- und Resume-Funktionen können Sie auch auf einer neuen Linux(R)-Distribution mit ACPI testen. Wenn es mit Linux(R) funktioniert, liegt das Problem wahrscheinlich bei einem FreeBSD-Treiber. Es hilft uns, das Problem zu lösen, wenn Sie feststellen können, welcher Treiber das Problem verursacht. Beachten Sie bitte, dass die ACPI-Entwickler normalerweise keine anderen Treiber pflegen (beispielsweise Sound- oder ATA-Treiber). Es ist wohl das beste, die Ergebnisse der Fehlersuche an die Mailingliste {freebsd-current} und den Entwickler des Treibers zu schicken. Erfahrene Benutzer können versuchen, den Fehler in der Resume-Funktion zu finden, indem sie einige man:printf[3]-Anweisungen in den Code des fehlerhaften Treibers einfügen. Schließlich können Sie ACPI noch abschalten und stattdessen APM verwenden. Wenn die Suspend- und Resume-Funktionen mit APM funktionieren, sollten Sie besser APM verwenden (insbesondere mit alter Hardware von vor dem Jahr 2000). Die Hersteller benötigten einige Zeit, um ACPI korrekt zu implementieren, daher gibt es mit älterer Hardware oft ACPI-Probleme. ==== Systemhänger Die meisten Systemhänger entstehen durch verlorene Interrupts oder einen Interrupt-Sturm. Probleme werden verursacht durch die Art, in der das BIOS Interrupts vor dem Systemstart konfiguriert, durch eine fehlerhafte APIC-Tabelle und durch die Zustellung des System-Control-Interrupts (SCI). Anhand der Ausgabe des Befehls `vmstat -i` können Sie verlorene Interrupts von einem Interrupt-Sturm unterscheiden. Untersuchen Sie die Ausgabezeile, die `acpi0` enthält. Ein Interrupt-Sturm liegt vor, wenn der Zähler öfter als ein paar Mal pro Sekunde hochgezählt wird. Wenn sich das System aufgehangen hat, versuchen Sie mit der Tastenkombination kbd:[Ctrl+Alt+Esc] in den Debugger DDB zu gelangen. Geben Sie dort den Befehl `show interrupts` ein. Wenn Sie Interrupt-Probleme haben, ist es vorerst wohl am besten, APIC zu deaktivieren. Tragen Sie dazu die Zeile `hint.apic.0.disabled="1"` in [.filename]#/boot/loader.conf# ein. ==== Abstürze (Panics) Panics werden so schnell wie möglich behoben; mit ACPI kommt es aber selten dazu. Zuerst sollten Sie die Panic reproduzieren und dann versuchen einen backtrace (eine Rückverfolgung der Funktionsaufrufe) zu erstellen. Richten Sie dazu den DDB über die serielle Schnittstelle (siehe crossref:serialcomms[serialconsole-ddb,“DDB Debugger über die serielle Schnittstelle”]) oder eine gesonderte man:dump[8]-Partition ein. In DDB können Sie den backtrace mit dem Kommando `tr` erstellen. Falls Sie den backtrace vom Bildschirm abschreiben müssen, schreiben Sie bitte mindestens die fünf ersten und die fünf letzten Zeile der Ausgabe auf. Versuchen Sie anschließend, das Problem durch einen Neustart ohne ACPI zu beseitigen. Wenn das funktioniert hat, können Sie versuchen, das verantwortliche ACPI-Subsystem durch Setzen der Variablen `debug.acpi.disable` herauszufinden. Die Hilfeseite man:acpi[4] enthält dazu einige Beispiele. ==== Nach einem Suspend oder einem Stopp startet das System wieder Setzen Sie zuerst `hw.acpi.disable_on_poweroff="0"` in [.filename]#/boot/loader.conf#. Damit wird verhindert, dass ACPI während des Systemabschlusses die Bearbeitung verschiedener Ereignisse deaktiviert. Auf manchen Systemen muss die Variable den Wert `1` besitzen (die Voreinstellung). Normalerweise wird der unerwünschte Neustart des Systems durch Setzen dieser Variablen behoben. [[ACPI-aslanddump]] ==== BIOS mit fehlerhaftem Bytecode Einige BIOS-Hersteller liefern einen fehlerhaften Bytecode aus. Dies erkennen Sie an Kernelmeldungen wie diesen: [source,shell] .... ACPI-1287: *** Error: Method execution failed [\\_SB_.PCI0.LPC0.FIGD._STA] \\ (Node 0xc3f6d160), AE_NOT_FOUND .... Oft können Sie das Problem dadurch lösen, dass Sie eine aktuelle BIOS-Version einspielen. Die meisten Meldungen auf der Konsole sind harmlos, wenn aber beispielsweise der Batteriestatus falsch angezeigt wird, können Sie in den Meldungen nach Problemen suchen. === Die voreingestellte ASL überschreiben Der BIOS-Bytecode, bekannt als ACPI Maschine Language (AML) wird aus der Sprache namens ACPI Source Language (ASL) übersetzt. Die AML ist in einer Tabelle, bekannt als Differentiated System Description Table (DSDT), abgelegt. Es ist das Ziel von FreeBSD, dass ACPI ohne Eingriffe des Benutzers läuft. Zurzeit werden allerdings noch Abhilfen für Fehler der BIOS-Hersteller entwickelt. Der Microsoft(R)-Interpreter ([.filename]#acpi.sys# und [.filename]#acpiec.sys#) prüft die ASL nicht streng gegen den Standard. Daher reparieren BIOS-Hersteller, die ACPI nur unter Windows(R) testen, ihre ASL nicht. Die FreeBSD Entwickler hoffen, dass sie das vom Standard abweichende Verhalten des Microsoft(R)-Interpreters dokumentieren und in FreeBSD replizieren können. Dadurch müssen Benutzer ihre ASL nicht selbst reparieren. Um bei der Fehlersuche zu helfen und das Problem möglicherweise zu beheben, kann eine Kopie der ASL gemacht werden. Dazu nutzen Sie `acpidump` zusammen mit `-t`, um den Inhalt der Tabelle anzuzeigen und `-d`, um die AML zu zerlegen: [source,shell] .... # acpidump -td > my.asl .... Einige AMLs gehen davon aus, dass der Anwender eine Windows(R)-Versionen benutzt. Versuchen Sie das Betriebssystem, das Sie in der ASL finden, in [.filename]#/boot/loader.conf# anzugeben: `hw.acpi.osname=_"Windows 2009"_`. Manche Abhilfen erfordern eine Anpassung von [.filename]#my.asl#. Wenn diese Datei bearbeitet wird, erstellen Sie die neue ASL mit dem folgenden Befehl. Warnung können meistens ignoriert werden, aber Fehler verhindern die ordnungsgemäße Funktion von ACPI. [source,shell] .... # iasl -f my.asl .... Die Option `-f` erzwingt das Erstellen der AML auch dann, wenn während der Übersetzung Fehler auftreten. Einige Fehler, wie fehlende Return-Anweisungen, werden automatisch vom FreeBSD Interpreter umgangen. Die voreingestellte Ausgabedatei von `iasl` ist [.filename]#DSDT.aml#. Wenn Sie diese Datei anstelle der fehlerhaften Kopie des BIOS laden wollen, editieren Sie [.filename]#/boot/loader.conf# wie folgt: [.programlisting] .... acpi_dsdt_load="YES" acpi_dsdt_name="/boot/DSDT.aml" .... Stellen Sie bitte sicher, dass sich [.filename]#DSDT.aml# in [.filename]#/boot# befindet und starten Sie das System neu. Wenn dadurch das Problem behoben wird, schicken Sie einen man:diff[1] der alten und der neuen ASL an {freebsd-acpi}, damit die Entwickler das Problem in [.filename]#acpica# umgehen können. [[ACPI-submitdebug]] === Abrufen und Einreichen von Informationen zur Fehlersuche Der ACPI-Treiber besitzt flexible Möglichkeiten zur Fehlersuche. Sie können sowohl die zu untersuchenden Subsysteme als auch die zu erzeugenden Ausgaben festlegen. Die zu untersuchenden Subsysteme werden als "layer" angegeben und in Komponenten (`ACPI_ALL_COMPONENTS`) und ACPI-Hardware (`ACPI_ALL_DRIVERS`) aufgeteilt. Welche Meldungen ausgegeben werden, wird über "level" gesteuert. Die Level reichen von von `ACPI_LV_ERROR` (es werden nur Fehler ausgegeben) bis zu `ACPI_LV_VERBOSE` (alles wird ausgegeben). Das Level ist eine Bitmaske, sodass verschiedene Stufen auf einmal (durch Leerzeichen getrennt) angegeben werden können. Die erzeugte Ausgabemenge passt vielleicht nicht in den Konsolenpuffer. In diesem Fall sollte die Ausgabe mithilfe einer seriellen Konsole gesichert werden. Die möglichen Werte für "layers" und "level" werden in man:acpi[4] beschrieben. Die Ausgaben zur Fehlersuche sind in der Voreinstellung nicht aktiviert. Wenn ACPI im Kernel enthalten ist, fügen Sie `options ACPI_DEBUG` zur Kernelkonfigurationsdatei hinzu. Sie können die Ausgaben zur Fehlersuche global aktivieren, indem Sie in der Datei [.filename]#/etc/make.conf# die Zeile `ACPI_DEBUG=1` einfügen. Das Modul [.filename]#acpi.ko# können Sie wie folgt neu übersetzen: [source,shell] .... # cd /sys/modules/acpi/acpi && make clean && make ACPI_DEBUG=1 .... Kopieren Sie anschließend [.filename]#acpi.ko# ins Verzeichnis [.filename]#/boot/kernel#. In [.filename]#/boot/loader.conf# stellen Sie "level" und "layer" ein. Das folgende Beispiel aktiviert die Ausgabe von Fehlern für alle ACPI-Komponenten und alle Hardwaretreiber: [.programlisting] .... debug.acpi.layer="ACPI_ALL_COMPONENTS ACPI_ALL_DRIVERS" debug.acpi.level="ACPI_LV_ERROR" .... Wenn ein Problem durch ein bestimmtes Ereignis, beispielsweise den Start nach einem Ruhezustand, hervorgerufen wird, können Sie die Einstellungen für "level" und "layer" auch mit dem Kommando `sysctl` vornehmen. In diesem Fall müssen Sie [.filename]#/boot/loader.conf# nicht editieren. Auf der Kommandozeile geben Sie über `sysctl` dieselben Variablennamen wie in [.filename]#/boot/loader.conf# an. Sobald Sie die Fehlerinformationen gesammelt haben, schicken Sie diese an {freebsd-acpi}, sodass die Betreuer des FreeBSD-ACPI-Subsystems diese Informationen zur Analyse und für die Entwicklung einer Lösung verwenden können. [NOTE] ==== Bevor Sie einen Fehlerbericht an diese Mailingliste einreichen, stellen Sie bitte sicher, dass das BIOS und die Firmware des Controllers aktuell sind. ==== Wenn Sie einen Fehlerbericht einsenden, fügen Sie bitte die folgenden Informationen ein: * Beschreiben Sie den Fehler und alle Umstände, unter denen der Fehler auftritt. Geben Sie ebenfalls den Typ und das Modell Ihres Systems an. Wenn Sie einen neuen Fehler entdeckt haben, versuchen Sie möglichst genau zu beschreiben, wann der Fehler das erste Mal aufgetreten ist. * Die Ausgabe von `dmesg` nach der Eingabe von `boot -v`. Geben Sie auch alle Fehlermeldungen an, die erscheinen, wenn Sie den Fehler provozieren. * Die Ausgabe von `dmesg` nach der Eingabe von `boot -v` und mit deaktiviertem ACPI, wenn das Problem ohne ACPI nicht auftritt. * Die Ausgabe von `sysctl hw.acpi`. Dieses Kommando zeigt die vom System unterstützten ACPI-Funktionen an. * Die URL, unter der die ASL liegt. Schicken Sie bitte _nicht_ die ASL an die Mailingliste, da die ASL sehr groß sein kann. Eine Kopie der ASL erstellen Sie mit dem nachstehenden Befehl: + [source,shell] .... # acpidump -td > name-system.asl .... + Setzen Sie für _name_ den Namen des Kontos und für _system_ den Hersteller und das Modell des Systems ein. Zum Beispiel: [.filename]#njl-FooCo6000.asl#. Obwohl die meisten Entwickler die Mailingliste {freebsd-current} lesen, sollten Sie Fehlerberichte an die Liste {freebsd-acpi} schicken. Seien Sie bitte geduldig; wir haben alle Arbeit außerhalb des Projekts. Wenn der Fehler nicht offensichtlich ist, bitten wir Sie vielleicht, einen offiziellen Fehlerbericht (PR) einzusenden. Geben Sie im Fehlerbericht bitte dieselben Informationen wie oben an. Mithilfe der PRs verfolgen und lösen wir Probleme. Senden Sie bitte keinen PR ein, ohne vorher den Fehlerbericht an die Liste {freebsd-acpi} zu senden. Es kann sein, dass der Fehler schon von jemand anderem gemeldet wurde. [[ACPI-References]] === Referenzen Weitere Informationen über ACPI finden Sie hier: * Die FreeBSD ACPI Mailingliste (https://lists.freebsd.org/pipermail/freebsd-acpi/[https://lists.freebsd.org/pipermail/freebsd-acpi/]) -* Die ACPI 2.0 Spezifikation (http://acpi.info/spec.htm[http://acpi.info/spec.htm]) +* Die https://uefi.org/specifications#ACPI[ACPI Spezifikation] * man:acpi[4], man:acpi_thermal[4], man:acpidump[8], man:iasl[8] und man:acpidb[8] diff --git a/documentation/content/el/books/handbook/config/_index.adoc b/documentation/content/el/books/handbook/config/_index.adoc index 3460bb661d..6449b7545f 100644 --- a/documentation/content/el/books/handbook/config/_index.adoc +++ b/documentation/content/el/books/handbook/config/_index.adoc @@ -1,1374 +1,1374 @@ --- title: Κεφάλαιο 12. Ρύθμιση και Βελτιστοποίηση part: Μέρος III. Διαχείριση Συστήματος prev: books/handbook/partiii next: books/handbook/boot showBookMenu: true weight: 16 path: "/books/handbook/" --- [[config-tuning]] = Ρύθμιση και Βελτιστοποίηση :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 12 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/config/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[config-synopsis]] == Σύνοψη Ένα από τα σημαντικά χαρακτηριστικά του FreeBSD είναι η δυνατότητα ρύθμισης του συστήματος. Με τις σωστές ρυθμίσεις συστήματος είναι εύκολο να αποφευχθούν πολλά προβλήματα κατά τη διάρκεια μελλοντικών αναβαθμίσεων. Το κεφάλαιο αυτό θα εξηγήσει μεγάλο μέρος της διαδικασίας ρύθμισης του FreeBSD, συμπεριλαμβανομένων και κάποιων παραμέτρων που μπορούν να ρυθμιστούν για την βελτιστοποίηση της απόδοσης του συστήματος. Αφού διαβάσετε αυτό το κεφάλαιο, θα ξέρετε: * Πως να δουλέψετε αποδοτικά με συστήματα αρχείων και κατατμήσεις swap. * Τα βασικά των συστημάτων ρύθμισης και εκκίνησης [.filename]#rc.conf# και [.filename]#/usr/local/etc/rc.d#. * Πως να ρυθμίσετε και να δοκιμάσετε μια κάρτα δικτύου. * Πως να ρυθμίσετε virtual hosts στις δικτυακές σας συσκευές. * Πως να χρησιμοποιήσετε τα διάφορα αρχεία ρυθμίσεων στον κατάλογο [.filename]#/etc#. * Πως να βελτιστοποιήσετε το FreeBSD χρησιμοποιώντας μεταβλητές `sysctl`. * Πως να βελτιστοποιήσετε την απόδοση του δίσκου και να αλλάξετε τους περιορισμούς του πυρήνα. Πριν διαβάσετε αυτό το κεφάλαιο, θα πρέπει: * Να κατανοείτε βασικές έννοιες του UNIX(R) και του FreeBSD (crossref:basics[basics,Βασικές Έννοιες στο UNIX(R)]). * Να είστε εξοικειωμένοι με τα βασικά της ρύθμισης και της μεταγλώττισης του πυρήνα (crossref:kernelconfig[kernelconfig,Ρυθμίζοντας τον Πυρήνα του FreeBSD]). [[configtuning-initial]] == Αρχική Ρύθμιση === Διάταξη Κατατμήσεων ==== Βασικές Κατατμήσεις Όταν δημιουργείτε συστήματα αρχείων με το man:bsdlabel[8] ή το man:sysinstall[8], θυμηθείτε ότι οι σκληροί δίσκοι μεταφέρουν δεδομένα γρηγορότερα απο τα εξωτερικά μέροι τους στα εσωτερικά. Έτσι μικρότερα και περισσότερο προσβάσιμα συστήματα αρχείων πρέπει να είναι πλησιέστερα στο εξωτερικό του δίσκου, ενώ μεγαλύτερες κατατμήσεις όπως το [.filename]#/usr# πρέπει να τοποθετούνται πιο κοντά στο εσωτερικό του δίσκου. Είναι καλή ιδέα να δημιουργείτε κατατμήσεις με παρόμοια σειρά με αυτήν: root, swap, [.filename]#/var#, [.filename]#/usr#. Το μέγεθος του [.filename]#/var# αντανακλά την επιδιωκούμενη χρήση του μηχανήματος. Το [.filename]#/var# χρησιμοποιείτε για την αποθήκευση των γραμματοκιβωτίων, των αρχείων καταγραφής και του spooler του εκτυπωτή. Τα γραμματοκιβώτια και τα αρχεία καταγραφής μπορούν να μεγαλώσουν σε απροσδόκητα μεγέθη ανάλογα με τον αριθμό των χρηστών του συστήματος και το χρονικό διάστημα που κρατούνται τα αρχεία καταγραφής. Σπάνια χρειάζεται το [.filename]#/var/tmp# να έχει πάνω από ένα gigabyte χώρο, αλλά καλό είναι να έχετε κατά νου ότι πρέπει να είναι αρκετά μεγάλο για να κρατάει τα πακέτα που θέλετε να εγκαταστήσετε. Η κατάτμηση [.filename]#/usr# περιέχει τα περισσότερα αρχεία που απαιτούνται για την υποστήριξη του συστήματος, τη συλλογή των man:ports[7] (προτείνεται) και τον πηγαίο κώδικα (προαιρετικό). Και τα δύο αυτά είναι προαιρετικά κατα την εγκατάσταση. Τουλάχιστον 2 gigabytes προτείνονται για αυτή την κατάτμηση. Όταν επιλέγετε μέγεθος για τις κατατμήσεις, να έχετε υπόψιν σας τις απαιτήσεις σε χώρο. Μπορεί να είναι λίγο πρόβλημα το να μείνετε χωρίς χώρο σε μια κατάτμηση ενώ χρησιμοποιείτε ελάχιστα μια άλλη. [NOTE] ==== Μερικές φορές η επιλογή `Auto-defaults` του κατατμητή του man:sysinstall[8] μπορεί να επιλέξει πολύ μικρό μέγεθος για τις κατατμήσεις [.filename]#/var# και [.filename]#/#. Προσπαθείστε να επιλέξετε έξυπνα και γενναιόδωρα μεγέθη για τις κατατμήσεις σας. ==== [[swap-design]] ==== Swap Κατάτμηση Ένας εμπειρικός κανόνας για να επιλέξετε μέγεθος για την κατάτμηση swap είναι: πρέπει να είναι περίπου διπλή απο το μέγεθος της μνήμης (RAM) του συστήματος. Για παράδειγμα, αν το μηχάνημα έχει 128 megabytes μνήμης, η κατάτμηση swap πρέπει να είναι 256 megabytes. Συστήματα με λιγότερη μνήμη μπορούν να αποδίδουν καλύτερα με περισσότερο swap. Λιγότερο απο 256 megabytes swap δεν προτείνεται και πρέπει να εξεταστεί η επέκταση της μνήμης. Οι αλγόριθμοι VM paging του πυρήνα είναι έτσι φτιαγμένοι ώστε να αποδίδουν καλύτερα όταν η κατάτμηση swap είναι τουλάχιστον δύο φορές το μέγεθος της κεντρικής μνήμης. Αν ρυθμίσετε πολύ μικρό swap, μπορεί να έχουν μειωμένη απόδοση οι αλγόριθμοι σάρωσης σελίδων του υποσυστήματος VM και μπορεί αργότερα να δημιουργηθούν προβλήματα αν προστεθεί περισσότερη φυσική μνήμη. Σε μεγαλύτερα συστήματα με πολλαπλούς SCSI δίσκους (ή πολλαπλούς IDE δίσκους σε διαφορετικούς ελεγκτές), είναι προτιμότερο το swap να είναι ρυθμισμένο σε κάθε δίσκο (μέχρι τέσσερις δίσκους). Οι ξεχωριστές κατατμήσεις swap καλό είναι να έχουν περίπου το ίδιο μέγεθος. Ο πυρήνας μπορεί να χειριστεί αυθαίρετα μεγέθη swap, αλλά οι εσωτερικές δομές δεδομένων ρυθμίζονται με βάση το μέγεθος της μεγαλύτερης κατάτμησης swap. Κρατώντας την κατάτμηση swap σχεδόν στο ίδιο μέγεθος θα επιτρέψει στον πυρήνα να βελτιστοποιήσει την χρήση του swap, μοιράζοντας πιο καλά το φόρτο σε κάθε δίσκο. Δεν πειράζει να έχετε μεγάλο μέγεθος swap, ακόμα και αν δε χρησιμοποιείται αρκετά. Μπορεί να είναι ευκολότερη η ανάκαμψη απο ένα εκτός ελέγχου πρόγραμμα προτού χρειαστεί να επανεκκινήσετε το σύστημα. ==== Γιατί να φτιάξετε κατατμήσεις; Αρκετοί χρήστες νομίζουν ότι μία μεγάλη κατάτμηση θα είναι εντάξει, αλλά υπάρχουν αρκετοί λόγοι γιατί αυτό είναι κακή ιδέα. Καταρχήν, κάθε κατάτμηση έχει διαφορετικά λειτουργικά χαρακτηριστικά, οπότε ξεχωρίζοντας τις κατατμήσεις επιτρέπουμε στο σύστημα αρχείων να εναρμονίζεται ανάλογα. Για παράδειγμα, οι root και [.filename]#/usr# κατατμήσεις είναι κυρίως για ανάγνωση, χωρίς πολλές εγγραφές. Αντίθετα, γίνονται πολλές αναγνώσεις και εγγραφές στις [.filename]#/var# και [.filename]#/var/tmp#. Κάνοντας σωστή κατάτμηση σε ένα σύστημα, ο κατακερματισμός που συμβαίνει σε μικρότερες και περισσότερο εγγράψιμες κατατμήσεις δεν θα διαρρεύσει στις κατατμήσεις που διαβάζονται πιο συχνά από ότι γράφονται. Κρατώντας τις περισσότερο εγγράψιμες κατατμήσεις πιο κοντά στην άκρη του δίσκου, θα αυξηθεί η I/O απόδοση στις κατατμήσεις όπου και χρειάζεται πιο συχνά. Τώρα ενώ η απόδοση I/O χρειάζεται στις μεγαλύτερες κατατμήσεις, αλλάζοντας αυτές πιο κοντά στην άκρη του δίσκου δεν θα οδηγήσει σε σημαντική αύξηση της απόδοσης όσο το να μετακινήσετε την [.filename]#/var# στην άκρη. Τέλος, υπάρχει και θέμα ασφάλειας. Μία μικρή, προσεγμένη root κατάτμηση η οποία είναι διαβάζεται πιο συχνά από ότι γράφεται έχει μεγαλύτερη πιθανότητα να επιζήσει ενός άσχημου χτυπήματος. [[configtuning-core-configuration]] == Κύρια Ρύθμιση Η κύρια τοποθεσία των πληροφοριών για την ρύθμιση του συστήματος βρίσκεται μέσα στο [.filename]#/etc/rc.conf#. Αυτό το αρχείο περιέχει ένα ευρύ φάσμα ρυθμίσεων, κυρίως χρησιμοποιούμενες στην εκκίνηση του συστήματος για την ρύθμιση του συστήματος. Το όνομα του απευθείας συνεπάγεται αυτό; είναι ρυθμίσεις για τα αρχεία [.filename]#rc*#. Ένας διαχειριστής πρέπει να δημιουργήσει εγγραφές μέσα στο αρχείο [.filename]#rc.conf# ώστε να αντικαταστήσει τις προεπιλεγμένες ρυθμίσεις απο το αρχείο [.filename]#/etc/defaults/rc.conf#. Το αρχείο προεπιλογών δεν πρέπει να αντιγραφεί αυτολεξεί στο [.filename]#/etc# - αυτό περιέχει προεπιλεγμένες τιμές, όχι παραδείγματα. Όλες οι αλλαγές που αφορούν το σύστημα πρέπει να γίνουν στο αρχείο [.filename]#rc.conf# αποκλειστικά. Ένας αριθμός στρατηγικών μπορεί να εφαρμοστεί σε ένα σύνολο εφαρμογών για να ξεχωρίσουμε ρυθμίσεις του ευρύ συνόλου απο τις ρυθμίσεις επικεντρωμένες για ένα σύστημα για να κρατήσουμε τον φόρτο διαχείρισης χαμηλά. Η προτεινόμενη προσέγγιση είναι να τοποθετούμε τις ρυθμίσεις ευρύ συνόλου σε ένα διαφορετικό αρχείο, όπως το [.filename]#/etc/rc.conf.site#, και τότε να συμπεριλάβουμε το αρχείο αυτό στο [.filename]#/etc/rc.conf#, το οποίο θα περιέχει πληροφορίες επικεντρωμένες για ένα σύστημα. Μιάς και το [.filename]#rc.conf# διαβάζεται απο το man:sh[1] είναι εύκολο να το επιτύχουμε αυτό. Για παράδειγμα: * rc.conf: + [.programlisting] .... . /etc/rc.conf.site hostname="node15.example.com" network_interfaces="fxp0 lo0" ifconfig_fxp0="inet 10.1.1.1" .... * rc.conf.site: + [.programlisting] .... defaultrouter="10.1.1.254" saver="daemon" blanktime="100" .... Το αρχείο [.filename]#rc.conf.site# μπορεί έπειτα να διανεμηθεί σε κάθε σύστημα χρησιμοποιώντας το `rsync` ή κάποιο παρόμοιο πρόγραμμα, ενώ το αρχείο [.filename]#rc.conf# παραμένει μοναδικό. Αναβαθμίζοντας το σύστημα χρησιμοποιώντας man:sysinstall[8] ή `make world` δεν θα αντικαταστήσει το αρχείο [.filename]#rc.conf#, έτσι οι ρυθμίσεις δεν θα χαθούν. [[configtuning-appconfig]] == Ρύθμιση Εφαρμογών Τυπικά, οι εγκατεστημένες εφαρμογές έχουν τα δικά τους αρχεία ρυθμίσεων, με το δικό τους τρόπο σύνταξης, κτλπ. Είναι σημαντικό αυτά τα αρχεία να κρατούνται ξεχωριστά απο το βασικό σύστημα, έτσι ώστε να είναι εύκολα εντοπίσιμα και διαχειρίσιμα απο τα εργαλεία διαχείρισης πακέτων. Τυπικά, αυτά τα αρχεία είναι εγκατεστημένα στο [.filename]#/usr/local/etc#. Σε αυτή την περίπτωση όταν μία εφαρμογή έχει μεγάλο αριθμό αρχείων ρυθμίσεων, ένας υποκατάλογος δημιουργείται για να τα αποθηκεύσει. Κανονικά, όταν ένα port ή ένα package εγκαθιστάτε, παραδείγματα αρχείων ρυθμίσεων εγκαθιστάνται επίσης. Αυτά είναι συνήθως αναγνωρίσιμα απο την [.filename]#.default# κατάληξη τους. Αν δεν υπάρχουν αρχεία ρυθμίσεων για την εφαρμογή, τότε θα δημιουργηθούν κάνοντας αντιγραφή τα [.filename]#.default# αρχεία. Για παράδειγμα, έχετε υπόψη σας τα περιεχόμενα του καταλόγου [.filename]#/usr/local/etc/apache#: .... -rw-r--r-- 1 root wheel 2184 May 20 1998 access.conf -rw-r--r-- 1 root wheel 2184 May 20 1998 access.conf.default -rw-r--r-- 1 root wheel 9555 May 20 1998 httpd.conf -rw-r--r-- 1 root wheel 9555 May 20 1998 httpd.conf.default -rw-r--r-- 1 root wheel 12205 May 20 1998 magic -rw-r--r-- 1 root wheel 12205 May 20 1998 magic.default -rw-r--r-- 1 root wheel 2700 May 20 1998 mime.types -rw-r--r-- 1 root wheel 2700 May 20 1998 mime.types.default -rw-r--r-- 1 root wheel 7980 May 20 1998 srm.conf -rw-r--r-- 1 root wheel 7933 May 20 1998 srm.conf.default .... Τα μεγέθοι των αρχείων δείχνουν ότι μόνο το αρχείο [.filename]#srm.conf# έχει αλλάξει. Μία μετέπειτα αναβάθμιση του port της εφαρμογής Apache δεν θα αντικαταστήσει το αλλαγμένο αρχείο. [[configtuning-starting-services]] == Eκκινώντας Υπηρεσίες Πολλοί χρήστες επιλέγουν να εγκαταστήσουν λογισμικό απο τρίτους κατασκευαστές στο FreeBSD απο την συλλογή των Ports. Σε πολλές απο αυτές τις περιπτώσεις μπορεί να είναι απαραίτητο να ρυθμίσουν το λογισμικό με τέτοιο τρόπο ώστε να μπορεί να επιτραπεί η εκκίνηση του κατα την εκκίνηση του συστήματος. Υπηρεσίες, όπως το package:mail/postfix[] ή το package:www/apache13[] είναι μόνο δύο απο τα πολλά πακέτα λογισμικού που μπορεί να χρειάζονται να εκκινηθούν κατά την εκκίνηση του συστήματος. Το μέρος αυτό θα εξηγήσει τις διαθέσιμες διαδικασίες για την εκκίνηση λογισμικού προερχόμενο απο τρίτους κατασκευαστές. Στο FreeBSD, οι περισσότερες περιεχόμενες υπηρεσίες, όπως το man:cron[8], είναι εκκινήσιμες μέσα από τα σενάρια εκκίνησης του συστήματος. Τα σενάρια αυτά μπορεί να διαφέρουν ανάλογα το FreeBSD ή την έκδοση του κατασκευαστή; ωστόσο, η πιο σημαντική πτυχή που πρέπει να εξεταστεί είναι ότι οι ρυθμίσεις εκκίνησης τους μπορούν να χειριστούν μέσα απο ένα απλό σενάριο εκκίνησης. Πριν την έλευση του [.filename]#rc.d#, οι εφαρμογές μπορούσαν να τοποθετήσουν ένα απλό σενάριο εκκίνησης μέσα στον κατάλογο [.filename]#/usr/local/etc/rc.d# ο οποίος μπορούσε να διαβαστεί απο τα σενάρια εκκίνησης του συστήματος. Αυτά τα σενάρια μπορούσαν να εκτελεστούν κατα τα μετέπειτα στάδια εκκίνησης του συστήματος. Ενώ πολλοί ιδιώτες ξόδευαν χρόνο προσπαθώντας να συνχωνεύσουν το παλιό στυλ ρυθμίσεων με το νέο στυλ, παραμένει γεγονός ότι μερικά προγράμματα ακόμα απαιτούν ένα σενάριο να τοποθετηθεί μέσα στον προαναφερθέντα κατάλογο. Οι λεπτές διαφορές ανάμεσα στα σενάρια εξαρτώνται από το αν ή όχι ο [.filename]#rc.d# χρησιμοποιείτε. Προγενέστερα του FreeBSD 5.1 το παλιό στυλ ρυθμίσεων χρησιμοποιούνταν και σχεδόν σε όλες τις περιπτώσεις ένα νέου στυλ σενάριο θα είναι συμβατό. Ενώ κάθε σενάριο πρέπει να τηρεί ορισμένες ελάχιστες απαιτήσεις, τις περισσότερες φορές αυτές οι απαιτήσεις είναι ανεξάρτητες της έκδοσης του FreeBSD. Κάθε σενάριο πρέπει να έχει μια [.filename]#.sh# επέκταση προσαρτημένη στο τέλος του και κάθε σενάριο πρέπει να είναι εκτελέσιμο απο το σύστημα. Το δεύτερο μπορεί να επιτευχθεί χρησιμοποιώντας την `chmod` εντολή και ρυθμίζοντας την άδεια `755`. Εκεί πρέπει να υπάρχει, τουλάχιστον, μια επιλογή `start` και μία επιλογή `stop` για την εφαρμογή. Το πιο απλό σενάριο εκκίνησης πιθανότατα να μοιάζει με το παρακάτω: [.programlisting] .... #!/bin/sh echo -n ' utility' case "$1" in start) /usr/local/bin/utility ;; stop) kill -9 `cat /var/run/utility.pid` ;; *) echo "Usage: `basename $0` {start|stop}" >&2 exit 64 ;; esac exit 0 .... Το σενάριο αυτό παρέχει μια `stop` και μια `start` επιλογή για την εφαρμογή όπου στο παράδειγμα εδώ αναφέρεται σαν `utility`. Μπορεί να εκκινηθεί χειρωνακτικά κάνοντας: [source,shell] .... # /usr/local/etc/rc.d/utility.sh start .... Παρόλο που δεν απαιτούν όλες οι εφαρμογές να προστεθεί μία εγγραφή στο [.filename]#rc.conf#, σχεδόν καθημερινά και ένα νέο port θα τροποποιήτε για να δέχεται αυτή την ρύθμιση. Ελέγξετε την τελική έξοδο της εγκατάστασης για περισσότερες πληροφορίες πάνω στην συγκεκριμένη εφαρμογή. Μερικές εφαρμογές απο τρίτους κατασκευαστές παρέχουν σενάρια εκκίνησης τα οποία επιτρέπουν στην εφαρμογή να χρησιμοποιηθεί με το [.filename]#rc.d#, παρόλα αυτα, αυτό θα συζητηθεί στο επόμενο μέρος. === Εκτεταμένη Ρύθμιση Εφαρμογών Πλέον το FreeBSD περιέχει το [.filename]#rc.d#, η ρύθμιση της εκκίνησης των εφαρμογών έχει γίνει ευκολότερη, και πιο πλούσια σε χαρακτηρικά. Χρησιμοποιώντας λέξεις κλειδία μέσα στον κατάλογο <>, οι εφαρμογές μπορούν πλέον να εκκινούν έπειτα απο συγκεκριμένες υπηρεσίες για παράδειγμα την DNS, μπορεί να επιτραπεί η εισαγωγή επιπλέον παραμέτρων μέσα απο το [.filename]#rc.conf# στην θέση των ήδη υπάρχoντον παραμέτρων απο τα σενάρια εκκινήσης, κτλπ. Ένα βασικό σενάριο μπορεί να μοιάζει με το ακόλουθο: [.programlisting] .... #!/bin/sh # # PROVIDE: utility # REQUIRE: DAEMON # KEYWORD: shutdown . /etc/rc.subr name=utility rcvar=utility_enable command="/usr/local/sbin/utility" load_rc_config $name # # DO NOT CHANGE THESE DEFAULT VALUES HERE # SET THEM IN THE /etc/rc.conf FILE # utility_enable=${utility_enable-"NO"} pidfile=${utility_pidfile-"/var/run/utility.pid"} run_rc_command "$1" .... Το σενάριο αυτό θα εξασφαλίσει ότι το πρόγραμμα utility θα εκκινηθεί μετά απο την `daemon` υπηρεσία. Θα εξασφαλίσει επιπλέον έναν τρόπο για την ρύθμιση και τον εντοπισμό του PID, ή του αρχείου του ID της διεργασίας. Η εφαρμογή μπορεί πλέον να έχει την παρακάτω γραμμή τοποθετημένη στο [.filename]#/etc/rc.conf#: [.programlisting] .... utility_enable="YES" .... Ο νέος αυτός τρόπος επιτρέπει επιπλέον τον ευκολότερο χειρισμό των παραμέτρων της γραμμής εντολών, σε συνδυασμό με τις προυπάρχουσες λειτουργίες παρεχόμενες απο το [.filename]#/etc/rc.subr#, τη συμβατότητα με το βοηθητικό πρόγραμμα man:rcorder[8] και επιπλέον την ευκολότερη ρύθμιση μέσω του [.filename]#rc.conf# αρχείου. === Χρησιμοποιώντας Υπηρεσίες Για Την Εκκίνηση Υπηρεσιών Άλλες υπηρεσίες, όπως ο δαίμονας του εξυπηρετή POP3, IMAP, κτλπ. μπορούν να εκκινηθούν χρησιμοποιώντας το man:inetd[8]. Αυτό απαιτεί την εγκατάσταση του βοηθητικού προγράμματος υπηρεσιών απο την Ports συλλογή και μια γραμμή ρυθμίσεων προσαρτημένη στο αρχείο [.filename]#/etc/inetd.conf#, ή αποχαρακτηρίζοντας μια απο τις ήδη υπάρχουσες γραμμές ρυθμίσεων. Δουλεύοντας με το inetd και τις ρυθμίσεις του περιγράφεται αναλυτικά στο μέρος crossref:network-servers[network-inetd,inetd]. Σε πολλές περιπτώσεις, είναι εύλογο να χρησιμοποιείτε ο δαίμονας man:cron[8] για την εκκίνηση των υπηρεσιών του συστήματος. Η προσέγγιση αυτή έχει έναν αριθμό πλεονεκτημάτων γιατί το `cron` τρέχει τις διεργασίες σαν ιδιοκτήτης του [.filename]#crontab# αρχείου. Αυτό επιτρέπει στους κανονικούς χρήστες να εκκινούν και να διαχειρίζονται μερικές εφαρμογές. Το βοηθητικό πρόγραμμα `cron` παρέχει ένα μοναδικό χαρακτηριστικό, το `@reboot`, το οποίο μπορεί να χρησιμοποιηθεί στην θέση του χρονικού ορισμού. Αυτό θα κάνει την εργασία να τρέξει όταν το man:cron[8] εκκινηθεί, συνήθως κατά την εκκίνηση του συστήματος. [[configtuning-cron]] == Ρυθμίζοντας Το Πρόγραμμα `cron` Ένα απο τα πιο χρήσιμα βοηθητικά προγράμματα στο FreeBSD είναι το man:cron[8]. Το πρόγραμμα `cron` τρέχει στο παρασκήνιο και συνεχώς ελέγχει το αρχείο [.filename]#/etc/crontab#. Το `cron` ελέγχει επίσης τον κατάλογο [.filename]#/var/cron/tabs#, αναζητώντας καινούργια αρχεία [.filename]#crontab#. Τα αρχεία [.filename]#crontab# έχουν αποθηκευμένες πληροφορίες για συγκεκριμένες διαδικασίες τις οποίες το `cron` πρέπει να εκτελέσει σε συγκεκριμένο χρόνο. Το `cron` χρησιμοποιεί δύο διαφορετικούς τύπους αρχείων ρυθμίσεων, το crontab του συστήματος και το crontab των χρηστών. Η μόνη διαφορά ανάμεσα στους δύο αυτούς τύπους είναι το έκτο πεδίο. Στο crontab του συστήματος, το έκτο πεδίο είναι το όνομα του χρήστη με του οποίου θα εκτελεστεί η εντολή. Αυτό δίνει την δυνατότητα στο crontab του συστήματος να εκτελεί εντολές σαν οποιοδήποτε χρήστης. Στο crontab των χρηστών, το έκτο πεδίο είναι η εντολή που πρέπει να εκτελεστεί, και όλες οι εντολές εκτελούνται στο όνομα του χρήστη που δημιούργησε το crontab; αυτό είναι ένα σημαντικό χαρακτηριστικό ασφαλείας. [NOTE] ==== Τα crontabs των χρηστών επιτρέπουν σε μεμονωμένους χρήστες να προγραμματίσουν εργρασίες χωρίς την ανάγκη `root` δικαιωμάτον. Οι εντολές μέσα στο crontab ενός χρήστη τρέχουν με τα δικαιώματα του χρήστη του οποίου ανήκει το crontab. Ο χρήστης `root` μπορεί να έχει ένα crontab χρήστη ακριβώς όπως κάθε χρήστης. Αυτό είναι διαφορετικό απο το [.filename]#/etc/crontab# (το crontab του συστήματος). Λόγο του crontab του συστήματος, δεν υπάρχει συνήθως καμία ανάγκη για την δημιουργία ενός ξεχωριστού crontab για τον χρήστη `root`. ==== Ας ρίξουμε μια ματία στο αρχείο [.filename]#/etc/crontab# (το crontab του συστήματος): [.programlisting] .... # /etc/crontab - root's crontab for FreeBSD # # $FreeBSD: src/etc/crontab,v 1.32 2002/11/22 16:13:39 tom Exp $ ## <.> # SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin <.> HOME=/var/log # # #minute hour mday month wday who command <.> # # */5 * * * * root /usr/libexec/atrun <.> .... <.> Όπως στα περισσότερα αρχεία ρυθμίσεων στο FreeBSD, ο χαρακτήρας `#` παριστάνει ένα σχόλιο. Ένα σχόλιο μπορεί να τοποθετηθεί μέσα στο αρχείο σαν υπενθύμιση για το τι πραγματοποιεί και γιατί μία ενέργεια. Τα σχόλια δεν μπορούν να είναι στην ίδια γραμμή με μία εντολή γιατί αλλιώς θα ερμηνευτούν σαν κομμάτι της εντολής; πρέπει να είναι σε μία νέα γραμμή. Οι κενές γραμμές αγνοούνται. <.> Καταρχήν, πρέπει να καθοριστεί το περιβάλλον. Ο χαρακτήρας ίσον (`=`) χρησιμοποιείτε για να καθορίσει τις ρυθμίσεις του περιβάλλοντος, όπως σε αυτό το παράδειγμα που χρησιμοποιούνται οι μεταβλητές `SHELL`, `PATH`, και `HOME`. Αν η γραμμή του κέλυφους παραμεληθεί, το `cron` θα χρησιμοποιήσει την προεπιλεγμένη, οι οποία είναι η `sh`. Αν η μεταβλητή `PATH` παραμεληθεί, δεν θα χρησιμοποιηθεί προεπιλεγμένη και η τοποθεσίες των αρχείων θα πρέπει να καθοριστούν με ακρίβεια. Αν η `HOME` παραμεληθεί, το `cron` θα χρησιμοποιήσει τον κεντρικό κατάλογο των εκάστοτε χρηστών. <.> Η γραμμή αυτή καθορίζει συνολικά επτά πεδία. Τα πεδία αυτά είναι τα `minute`, `hour`, `mday`, `month`, `wday`, `who`, και `command`. Αυτά είναι απο μόνα τους επεξηγηματικά. Το πεδίο `minute` είναι ο χρόνος σε λεπτά τον οποίον η εντολή θα εκτελεστεί. Το πεδίο `hour` είναι παρόμοιο με το πεδίο `minute`, απλά είναι σε ώρες. Το πεδίο `mday` καθορίζει την ημέρα του μήνα. Το πεδίο `month` είναι παρόμοιο με το πεδίο `hour` και το πεδίο `minute`, υποδεικνύοντας τον μήνα. Το πεδίο `wday` καθορίζει την ημέρα της εβδομάδας. Όλα αυτά τα πεδία πρέπει να έχουν αριθμητικές τιμές, και να ακολουθούν το είκοσι-τετράωρο ρολόι. Το πεδίο `who` είναι ιδιαίτερο, και υπάρχει μόνο μέσα στο αρχείο [.filename]#/etc/crontab#. Το πεδίο αυτό καθορίζει σαν ποιός χρήστης θα τρέξει την εντολή. Όταν ένας χρήστης εγκαθιστά το [.filename]#crontab# αρχείο του, δεν θα έχει το πεδίο αυτό διαθέσιμο. Τέλος, θα ακολουθήσει η επιλογή `command`. Αυτό είναι το τελευταίο πεδίο, έτσι και λογικά υποδεικνύει την εντολή που θα εκτελεστεί. <.> Η τελευταία αυτή γραμμή θα καθορίσει τα μεγέθοι που συζητήθηκαν παραπάνω. Προσέξτε εδώ ότι έχουμε έναν ορισμό `\*/5`, ακολουθούμενο απο αρκετούς χαρακτήρες `*`. Οι χαρακτήρες `*` σημαίνουν "πρώτο-τελευταίο", και μπορούν να ερμηνευθούν σαν _κάθε_ φορά. Έτσι, κρίνοντας απο αυτή την γραμμή, είναι προφανές ότι η εντολή `atrun` επικαλείται απο τον χρήστη `root` κάθε πέντε λεπτά ανεξάρτητα απο την ημέρα και τον μήνα. Για περισσότερες πληροφορίες σχετικά με την εντολή `atrun`, κοιτάξτε την σελίδα βοηθείας man:atrun[8].Οι εντολές μπορούν να έχουν απεριόριστο αριθμό παραμέτρων, ωστόσο, οι εντολές με εκτεταμένο αριθμό γραμμών πρέπει να διασπαστούν με τον χαρακτήρα συνέχειας αντίθετης καθέτου "\". Αυτές είναι οι βασικές ρυθμίσεις για κάθε αρχείο [.filename]#crontab#, ωστόσο υπάρχει και κάτι διαφορετικό. Το πεδίο έξι, όπου και καθορίζουμε το όνομα χρήστη, υπάρχει μόνο στο αρχείο του συστήματος [.filename]#/etc/crontab#. Το πεδίο αυτό πρέπει να παραλειφθεί για κάθε [.filename]#crontab# αρχείο χρήστη. [[configtuning-installcrontab]] === Εγκαθιστώντας Ένα Crontab [IMPORTANT] ==== Δεν θα πρέπει να χρησιμοποιήσετε την διαδικασία που περιγράφεται εδώ για την διόρθωση/εγκατάσταση του crontab του συστήματος. Απλά χρησιμοποιήστε τον αγαπημένο σας κειμενογράφο: το `cron` θα εντοπίσει ότι το αρχείο έχει τροποποιηθεί και θα αρχίσει άμεσα να χρησιμοποιεί την ανανεωμένη έκδοση του. Δείτε extref:{faq}[αυτή την εγγραφή του FAQ, ROOT-NOT-FOUND-CRON-ERRORS] για περισσότερες πληροφορίες. ==== Για να εγκαταστήσετε ένα νέο [.filename]#crontab# χρήστη, πρώτα χρησιμοποιήστε τον αγαπημένο σας κειμενογράφο για να δημιουργήσετε ένα αρχείο με το απαιτούμενο τύπο, και τότε χρησιμοποιήστε το `crontab`. Η πιο κοινή χρήση του είναι: [source,shell] .... % crontab crontab-file .... Στο παράδειγμα αυτό, το αρχείο [.filename]#crontab-file# είναι το όνομα του αρχείου [.filename]#crontab# που είχε δημιουργηθεί προηγουμένως. Υπάρχει επίσης μία επιλογή για να απαριθμήσετε τα εγκατεστημένα αρχεία [.filename]#crontab#: απλά εισάγετε την επιλογή `-l` στην εντολή `crontab` και ελέγξτε το αποτέλεσμα. Για τους χρήστες που θέλουν να αρχίσουν το crontab αρχείο τους απο την αρχή, χωρίς την χρήση προτύπου, μπορούν να χρησιμοποιήσουν την εντολή `crontab -e`. Αυτή η εντολή θα ξεκινήσει τον κειμενογράφο με ένα κενό αρχείο. Όταν το αρχείο αποθηκευθεί, θα εγκατασταθεί αυτόματα απο την εντολή `crontab`. Αν αργότερα θέλετε να διαγράψετε το [.filename]#crontab# αρχείο χρήστη τελείως, χρησιμοποιήστε την εντολή `crontab` μαζί με την επιλογή `-r`. [[configtuning-rcd]] == Χρησιμοποιώντας Το Σύστημα rc Στο FreeBSD Το 2002 το FreeBSD ενσωμάτωσε το σύστημα [.filename]#rc.d# του NetBSD για την εκκίνηση του συστήματος. Οι χρήστες θα πρέπει να έχουν αντιληφθεί τα αρχεία που βρίσκονται στον κατάλογο [.filename]#/etc/rc.d#. Πολλά απο αυτά τα αρχεία είναι για τις βασικές υπηρεσίες και μπορούν να ελεγθούν με τις επιλογές `start`, `stop`, και `restart`. Για παράδειγμα, το man:sshd[8] μπορεί να ελεγθεί χρησιμοποιώντας την εξής εντολή: [source,shell] .... # /etc/rc.d/sshd restart .... Η διαδικασία αυτή είναι παρόμοια και για τις υπόλοιπες υπηρεσίες. Φυσικά, οι υπηρεσίες αυτές είναι συνήθως αυτόματα εκκινήσιμες κατα την εκκίνηση του συστήματος όπως και καθορίζεται στο man:rc.conf[5]. Για παράδειγμα, ενεργοποιώντας τον δαίμονα Network Address Translation στην εκκίνηση είναι τόσο απλό όσο κάνοντας προσθήκη της ακόλουθης γραμμής στο [.filename]#/etc/rc.conf#: [.programlisting] .... natd_enable="YES" .... Αν η επιλογή `natd_enable="NO"` είναι ήδη παρούσα, τότε απλά αλλάζετε την επιλογή `NO` σε `YES`. Τα σενάρια rc θα φορτώσουν αυτόματα οποιαδήποτε εξαρτώμενη υπηρεσία κατά την διάρκεια της επόμενης εκκίνησης, όπως και περιγράφεται παρακάτω. Μιας και το σύστημα [.filename]#rc.d# είναι κυρίως για την εκκίνηση και τον τερματισμό υπηρεσιών κατα την εκκίνηση και τον τερματισμό του συστήματος αντίστοιχα, οι προκαθορισμένες επιλογές `start`, `stop` και `restart` θα πραγματοποιήσουν τις αντίστοιχες ενέργειες αν η κατάλληλες μεταβλητές είναι καθορισμένες στο [.filename]#/etc/rc.conf#. Για παράδειγμα η παραπάνω εντολή `sshd restart` θα δουλέψει μόνο αν η μεταβλητή `sshd_enable` έχει τεθεί σε `YES` μέσα στο [.filename]#/etc/rc.conf#. Για να εκτελέσετε τις επιλογές `start`, `stop` ή `restart` μιας υπηρεσίας ανεξάρτητα απο τις ρυθμίσεις της στο [.filename]#/etc/rc.conf#, η εντολή πρέπει να έχει χαρακτηριστεί με "one". Για παράδειγμα για την επανεκκίνηση του `sshd` ανεξάρτητα απο τις τρέχουσες ρυθμίσεις στο [.filename]#/etc/rc.conf#, εκτελείτε την ακόλουθη εντολή: [source,shell] .... # /etc/rc.d/sshd onerestart .... Είναι εύκολο να ελέγξετε αν η υπηρεσία είναι ενεργοποιημένη στο [.filename]#/etc/rc.conf# τρέχοντας το κατάλληλο σενάριο [.filename]#rc.d# με την παράμετρο `rcvar`. Κατά συνέπεια, ένας διαχειριστής μπορεί να ελέγξει αν το `sshd` είναι όντως ενεργοποιημένο στο [.filename]#/etc/rc.conf# εκτελώντας: [source,shell] .... # /etc/rc.d/sshd rcvar # sshd $sshd_enable=YES .... [NOTE] ==== Η δεύτερη γραμμή (`# sshd`) είναι η έξοδος της εντολής `sshd`, και όχι η κονσολά του χρήστη `root`. ==== Για να ελέγξετε αν μια υπηρεσία τρέχει, η επιλογή `status` είναι διαθέσιμη. Για παράδειγμα για να επιβεβαιώστε ότι η υπηρεσία `sshd` τρέχει: [source,shell] .... # /etc/rc.d/sshd status sshd is running as pid 433. .... Σε πολλές περιπτώσεις είναι δυνατόν το `reload` μίας υπηρεσίας. Αυτό θα στείλει ένα σήμα στην υπηρεσία, επιβάλλοντας της να ξαναφορτώσει τα αρχεία ρυθμίσεων της. Στην πραγματικότητα αυτό σημαίνει ότι θα στείλει ένα σήμα `SIGHUP` στην υπηρεσία. Η υποστήριξη για αυτό το χαρακτηριστικό δεν παρέχεται σε κάθε υπηρεσία. Το σύστημα [.filename]#rc.d# δεν χρησιμοποιείτε μόνο για τις υπηρεσίες δικτύου, αλλά επίσης συμβάλει και κατα την εκκίνηση του συστήματος. Για παράδειγμα, σκεφτείτε το αρχείο [.filename]#bgfsck#. Όταν ένα σενάριο εκτελείτε, θα εκτυπώνει το ακόλουθο μήνυμα: [source,shell] .... Starting background file system checks in 60 seconds. .... Επομένος το αρχείο αυτό χρησιμοποιείτε στο παρασκήνιο για τον έλεγχο του συστήματος αρχείων, ο οποίος και συμβαίνει κατα στην εκκίνηση του συστήματος. Πολλές υπηρεσίες εξαρτώνται από άλλες υπηρεσίες για να τα καταφέρουν να λειτουργήσουν σωστά. Για παράδειγμα, η υπηρεσία NIS και άλλες βασισμένες στο RPC υπηρεσίες θα αποτύχουν να εκκινηθούν αν η υπηρεσία `rpcbind` (portmapper) δεν έχει ήδη εκκινηθεί. Για να λύθει το πρόβλημα αυτό, υπάρχουν πληροφορίες για τις εξαρτήσεις και άλλα μετα-δεδομένα μέσα στα σχόλια στην αρχή κάθε σεναρίου. Το πρόγραμμα man:rcorder[8] χρησιμοποιείτε για την ανάλυση των σχολίων αυτών κατά την εκκίνηση του συστήματος για να καθορίστει με ποιά σειρά θα πρέπει να εκκινηθούν οι υπηρεσίες ώστε να εκπληρωθούν οι εξαρτήσεις. Οι επόμενες προτάσεις μπορούν να περιληφθούν μέσα σε κάθε αρχείο εκκίνησης: * `PROVIDE`: Καθόριζει την υπηρεσία που παρέχει το αρχείο αυτό. * `REQUIRE`: Απαριθμεί τις υπηρεσίες που απαιτούνται για την την υπηρεσία αυτή. Το αρχείο αυτό θα εκτελεστεί _μετά_ απο την καθορισμένη υπηρεσία. * `BEFORE`: Απαριθμεί τις υπηρεσίες οι οποίες εξαρτώνται απο την υπηρεσία αυτή. Το αρχείο αυτό θα εκτελεστεί _πρίν_ τις καθορισμένες υπηρεσίες. Χρησιμοποιώντας την μέθοδο αυτή, οι διαχειριστές μπορούν εύκολα να ελέγξουν τις υπηρεσίες του συστήματος χωρίς τα δυσνόητα "runlevels" όπως σε μερικά άλλα λειτουργικά συστήματα UNIX(R). Επιπλέον πληροφορίες για το σύστημα [.filename]#rc.d# μπορούν να βρεθούν στις σελίδες βοηθείας man:rc[8] και man:rc.subr[8]. Αν ενδιαφέρεστε για την εγγραφή δικών σας σεναρίων [.filename]#rc.d# ή για την βελτίωση των ήδη υπάρχοντων, θα βρείτε extref:{rc-scripting}[τον σύνδεσμο αυτόν] αρκετά χρήσιμο. [[config-network-setup]] == Ρυθμίζοντας Τις Κάρτες Δικτύου Την σήμερον εποχή δεν μπορούμε να σκεφτούμε έναν υπολογιστή χωρίς να σκεφτούμε και μία σύνδεση δικτύου. Προσθέτοντας και ρυθμίζοντας μια κάρτα δικτύου είναι μία συνηθισμένη εργασία για έναν οποιοδήποτε διαχειριστή του FreeBSD. === Εντοπίζοντας Τον Σωστό Οδηγό Πριν αρχίσετε, θα πρέπει να γνωρίζετε το μοντέλο της κάρτας που έχετε, ποιό chip χρησιμοποιεί, και αν είναι PCI ή ISA κάρτα. Το FreeBSD υποστηρίζει ένα μεγάλο εύρος καρτών PCI και ISA. Ελέγξτε την Λίστα Συμβατότητας Υλικού για την έκδοση σας για να δείτε αν η κάρτα σας υποστηρίζεται. Εφόσον είστε πλέον σίγουρος ότι η κάρτα σας υποστηρίζεται, θα χρειαστεί να καθορίσετε τον κατάλληλο οδηγό για την κάρτα σας. Το αρχείο [.filename]#/usr/src/sys/conf/NOTES# και το αρχείο [.filename]#/usr/src/sys/arch/conf/NOTES# θα σας δώσουν μια λίστα με κάρτες δικτύου και μερικές πληροφορίες για τα υποστηριζόμενα chipsets και τις υποστηριζόμενες κάρτες. Αν έχετε αμφιβολίες για το ποιός οδηγός είναι ο σωστός, διαβάστε την σελίδα βοηθείας του οδηγού. Η σελίδα βοηθείας θα σας δώσει περισσότερες πληροφορίες σχετικά με το υποστηριζόμενο υλικό και ακόμα και για τα πιθανά προβλήματα που μπορεί να προκύψουν. Αν έχετε μια συνηθισμένη κάρτα, κατα πάσα πιθανότητα δεν θα χρειαστεί να ψάξετε πολύ για τον οδηγό. Οι οδηγοί για τις συνηθισμένες κάρτες δικτύου υπάρχουν στον πυρήνα [.filename]#GENERIC#, έτσι ώστε και θα εμφανιστεί κατα την διάρκεια της εκκίνησης, για παράδειγμα: [source,shell] .... dc0: <82c169 PNIC 10/100BaseTX> port 0xa000-0xa0ff mem 0xd3800000-0xd38 000ff irq 15 at device 11.0 on pci0 dc0: Ethernet address: 00:a0:cc:da:da:da miibus0: on dc0 ukphy0: on miibus0 ukphy0: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc1: <82c169 PNIC 10/100BaseTX> port 0x9800-0x98ff mem 0xd3000000-0xd30 000ff irq 11 at device 12.0 on pci0 dc1: Ethernet address: 00:a0:cc:da:da:db miibus1: on dc1 ukphy1: on miibus1 ukphy1: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto .... Στο παράδειγμα αυτό, βλέπουμε ότι δύο κάρτες που χρησιμοποιούν τον οδηγό man:dc[4] έχουν εντοπιστεί στο σύστημα. Αν ο οδηγός της NIC σας δεν είναι παρόν στον [.filename]#GENERIC#, θα πρέπει να φορτώσετε τον κατάλληλο οδηγό για να χρησιμοποιήσετε την NIC σας. Αυτό μπορεί να επιτευχθεί με έναν απο τους δύο αυτούς τρόπους: * Ο ποιό εύκολο τρόπος είναι απλά να φορτώσετε ένα άρθρωμα του πυρήνα για την κάρτα δικτύου σας με το man:kldload[8], ή αυτόματα κατα την εκκίνηση προσθέτοντας την κατάλληλη γραμμή στο αρχείο [.filename]#/boot/loader.conf#. Δεν είναι όλοι οι οδηγοί NIC διαθέσιμοι σαν αρθρώματα, χαρακτηριστικά παραδείγματα είναι τα αρθρώματα για συσκευές ISA. * Εναλλακτικά, μπορείτε να μεταγλώττισετε στατικά την υποστήριξη για την κάρτα σας στον πυρήνα. Ελέγξετε το αρχείο [.filename]#/usr/src/sys/conf/NOTES#, το [.filename]#/usr/src/sys/arch/conf/NOTES# και την σελίδα βοηθείας του οδηγού για να μάθετε τι πρέπει να προσθέσετε στο αρχείο ρυθμίσεων του πυρήνα. Για περισσότερες πληροφορίες για το πως να μεταγλωττίσετε τον πυρήνα, παρακαλώ διαβάστε το crossref:kernelconfig[kernelconfig,Ρυθμίζοντας τον Πυρήνα του FreeBSD]. Αν η κάρτα σας εντοπιστεί κατα την εκκίνηση απο τον πυρήνα ([.filename]#GENERIC#) δεν χρειάζετε να μεταγλώττισετε έναν νέο πυρήνα. [[config-network-ndis]] ==== Χρησιμοποιώντας Οδηγούς Windows(R) Με Το NDIS Δυστυχώς, υπάρχουν ακόμα πολλοί κατασκευαστές που δεν παρέχουν τεχνικές προδιαγραφές για τους οδηγούς τους στην κοινότητα του ανοικτού λογισμικού γιατί αντιμετωπίζουν τέτοιες πληροφορίες σαν μυστικά του εμπορίου. Συνεπώς, οι υπεύθυνοι για την ανάπτυξη του FreeBSD και άλλων λειτουργικών συστημάτων μένουν με δύο επιλογές: να αναπτύξουν οδηγούς με την μακρά και επίπονη διαδικασία της αντίστροφης μηχανικής ή να χρησιμοποιήσουν ήδη υπάρχοντες οδηγούς σε δυαδική μορφή διαθέσιμους για την πλατφόρμα Microsoft(R) Windows(R). Οι περισσότεροι υπεύθυνοι για την ανάπτυξη, μεταξύ τους και αυτοί που εμπλέκονται με το FreeBSD, έχουν επιλέξει την δεύτερη προσέγγιση. Χάρη την προσφορά του Bill Paul (wpaul), μιάς και απο το FreeBSD 5.3-RELEASE υπάρχει "γηγενής" υποστήριξη για το Network Driver Interface Specification (NDIS). Το έργο FreeBSD NDISulator (διαφορετικά γνωστό σας Project Evil) παίρνει έναν οδηγό Windows(R) σε δυαδική μορφή και στην ουσία τον εξαπατά ώστε να νομίζει ότι τρέχει σε Windows(R). Λόγο του ότι ο οδηγός man:ndis[4] χρησιμοποιεί μία Windows(R) δυαδική μορφή, μπορεί να χρησιμοποιηθεί μόνο σε i386(TM) και amd64 συστήματα. [NOTE] ==== Ο οδηγός man:ndis[4] είναι σχεδιασμένος ώστε να υποστηρίζει κυρίως συσκευές PCI, CardBus και PCMCIA, οι συσκευές USB δεν υποστηρίζονται ακόμα. ==== Για να χρησιμοποιήσετε τον NDISulator, θα χρειαστείτε τρία πράγματα: . Τον πηγαίο κώδικα του πυρήνα . Την Windows(R) XP δυαδική μορφή του οδηγού ([.filename]#.SYS# επέκταση) . Το Windows(R) XP αρχείο ρυθμίσεων του οδηγού ([.filename]#.INF# επέκταση) Εντοπίστε τα αρχεία αυτά για την κάρτα σας. Γενικά, αυτά μπορούν να βρεθούν στα παρεχόμενα CDs ή στους ιστότοπους των κατασκευαστών. Στα ακόλουθα παραδείγματα, θα χρησιμοποιήσουμε τα αρχεία [.filename]#W32DRIVER.SYS# και [.filename]#W32DRIVER.INF#. [NOTE] ==== Δεν μπορείτε να χρησιμοποιήσετε οδηγούς Windows(R)/i386 σε συστήματα FreeBSD/amd64, θα πρέπει να βρείτε οδηγούς Windows(R)/amd64 για να δουλέψουν σωστά. ==== Το επόμενο βήμα είναι να μεταγλωττίσετε τον δυαδικό οδηγό μέσα σε ένα φορτώσιμο άρθρωμα του πυρήνα. Για να το επιτύχετε αυτό, θα πρέπει σαν `root`, να χρησιμοποιήσετε το man:ndisgen[8]: [source,shell] .... # ndisgen /path/to/W32DRIVER.INF /path/to/W32DRIVER.SYS .... Το βοηθητικό πρόγραμμα man:ndisgen[8] είναι διαδραστικό και θα σας ενημερώσει για οποιαδήποτε επιπλέον πληροφορία μπορεί να χρειαστεί; θα παράγει ένα άρθρωμα του πυρήνα στον τρέχωντα κατάλογο και μπορεί να φορτωθεί ως εξής: [source,shell] .... # kldload ./W32DRIVER.ko .... Επιπλέον του παραχθέντος αρθρώματος, θα πρέπει να φορτώσετε τα αρθρώματα [.filename]#ndis.ko# και [.filename]#if_ndis.ko#. Αυτό θα πρέπει να γίνει αυτόματα όταν φορτώνετε οποιαδήποτε εξαρτάται απο το man:ndis[4]. Αν θέλετε να το κάνετε χειρωνακτικά, θα πρέπει να χρησιμοποιήσετε τις ακόλουθες εντολές: [source,shell] .... # kldload ndis # kldload if_ndis .... Η πρώτη εντολή φορτώνει τον οδηγό NDIS miniport wrapper, ενώ η δεύτερη φορτώνει την πραγματική κάρτα δικτύου. Τώρα, ελέγξτε το man:dmesg[8] για να δείτε αν υπάρχουν σφάλματα κατα την φόρτωση. Αν όλα πήγαν καλά, θα πρέπει να δείτε μια παρόμοια έξοδο με την επόμενη: [source,shell] .... ndis0: mem 0xf4100000-0xf4101fff irq 3 at device 8.0 on pci1 ndis0: NDIS API version: 5.0 ndis0: Ethernet address: 0a:b1:2c:d3:4e:f5 ndis0: 11b rates: 1Mbps 2Mbps 5.5Mbps 11Mbps ndis0: 11g rates: 6Mbps 9Mbps 12Mbps 18Mbps 36Mbps 48Mbps 54Mbps .... Απο εδώ και πέρα μπορείτε να χειριστείτε την συσκευή [.filename]#ndis0# σαν μια οποιαδήποτε κάρτα δικτύου (π.χ., [.filename]#dc0#). Μπορείτε να ρυθμίσετε το σύστημα να φορτώνει τα NDIS αρθρώματα κατα την εκκίνηση με τον ίδιο τρόπο με τα όπως με οποιαδήποτε άλλα αρθρώματα. Πρώτα, αντιγράψτε το παραχθείσα άρθρωμα, [.filename]#W32DRIVER.ko#, στον κατάλογο [.filename]#/boot/modules#. Τότε, προσθέστε την ακόλουθη γραμμή στο [.filename]#/boot/loader.conf#: [.programlisting] .... W32DRIVER_load="YES" .... === Ρυθμίζοντας Την Κάρτα Δικτύου Μόλις ο κατάλληλος οδηγός φορτωθεί για την κάρτα δικτύου, χρειάζεται να ρυθμιστεί. Όπως πολλά άλλα πράγματα, η κάρτα δικτύου είχε ρυθμιστεί κατα την στιγμή της εγκατάστασης με το sysinstall. Για να εμφανίσετε τις κάρτες δικτύου που έχετε στο σύστημα σας, πληκτρολογήστε την ακόλουθη εντολή: [source,shell] .... % ifconfig dc0: flags=8843 mtu 1500 inet 192.168.1.3 netmask 0xffffff00 broadcast 192.168.1.255 ether 00:a0:cc:da:da:da media: Ethernet autoselect (100baseTX ) status: active dc1: flags=8843 mtu 1500 inet 10.0.0.1 netmask 0xffffff00 broadcast 10.0.0.255 ether 00:a0:cc:da:da:db media: Ethernet 10baseT/UTP status: no carrier lp0: flags=8810 mtu 1500 lo0: flags=8049 mtu 16384 inet 127.0.0.1 netmask 0xff000000 tun0: flags=8010 mtu 1500 .... [NOTE] ==== Παλαιότερες εκδόσεις του FreeBSD μπορεί να χρειάζονται την παράμετρο `-a` ακολουθούμενη στην man:ifconfig[8], για περισσότερες λεπτομέρειες σχετικά με την σωστή σύνταξη του man:ifconfig[8], παρακαλώ ανατρέξτε στην σελίδα βοηθείας. Σημειώστε επίσης ότι οι εγγραφές που αφορούν το IPv6 (`inet6` κτλπ.) έχουν παραμεληθεί σε αυτό το παράδειγμα. ==== Σε αυτό το παράδειγμα, οι ακόλουθες συσκευές έχουν εμφανιστεί: * [.filename]#dc0#: Η πρώτη Ethernet κάρτα δικτύου * [.filename]#dc1#: Η δεύτερη Ethernet κάρτα δικτύου * [.filename]#lp0#: Η παράλληλη πόρτα * [.filename]#lo0#: Η συσκευή loopback * [.filename]#tun0#: Η συσκευή tunnel χρησιμοποιούμενη απο το πρόγραμμα ppp Το FreeBSD χρησιμοποιεί τα ονόματα των οδηγών με την σειρά κατα την οποία εντοπίστηκαν οι αντίστοιχες κάρτες κατα την εκκίνηση. Για παράδειγμα η συσκευή [.filename]#sis2# θα είναι η τρίτη κάρτα δικτύου που χρησιμοποιεί τον οδηγό man:sis[4]. Στο παράδειγμα αυτό, η συσκευή [.filename]#dc0# είναι πάνω και τρέχει. Οι λέξεις κλειδία είναι: . `UP` σημαίνει ότι η κάρτα είναι ρυθμισμένη και έτοιμη. . Η κάρτα έχει μία Internet διεύθυνση (`inet`) ρυθμισμένη (σε αυτή την περίπτωση `192.168.1.3`). . Έχει μία έγκυρη μάσκα υποδικτύου (`netmask`; `0xffffff00` είναι το ίδιο με το `255.255.255.0`). . Έχει μία έγκυρη broadcast διεύθυνση (σε αυτή την περίπτωση, `192.168.1.255`). . Η διεύθυνση MAC της κάρτας (`ether`) είναι `00:a0:cc:da:da:da` . Η επιλογή του φυσικού μέσου είναι σε κατάσταση autoselection (`media: Ethernet autoselect (100baseTX )`). Παρατηρούμε ότι η [.filename]#dc1# έχει ρυθμιστεί να τρέχει σαν `10baseT/UTP` μέσο. Για περισσότερες πληροφορίες για τους τύπους των μέσων ενός οδηγού, παρακαλώ ανατρέξτε στην σελίδα βοηθείας. . Η κατάσταση της σύνδεσης (`status`) είναι `active`, δηλ. έχει εντοπιστεί σήμα μεταφοράς. Στην [.filename]#dc1#, παρατηρούμε `status: no carrier`. Αυτό είναι λογικό αφού το καλώδιο Ethernet δεν έχει συνδεθεί με την κάρτα. Αν το man:ifconfig[8] εμφανίζει κάτι παρόμοιο με αυτό: [source,shell] .... dc0: flags=8843 mtu 1500 ether 00:a0:cc:da:da:da .... σημαίνει ότι η κάρτα δεν έχει ρυθμιστεί. Για να ρυθμίσετε την κάρτα σας, θα χρειαστείτε προνόμια `root`. Η ρύθμιση της κάρτας δικτύου μπορεί να γίνει απο την γραμμή εντολών με το man:ifconfig[8] αλλά θα πρέπει να το επαναλάβετε σε κάθε επανεκκίνηση του συστήματος. Το αρχείο [.filename]#/etc/rc.conf# είναι εκεί όπου πρέπει να προσθέσετε τις ρύθμισεις της κάρτας δικτύου. Ανοίξτε το αρχείο [.filename]#/etc/rc.conf# με τον αγαπημένο σας κειμενογράφο. Θα χρειαστεί να προσθέσετε μία γραμμή για κάθε κάρτα δικτύου που υπάρχει στο σύστημα σας, για παράδειγμα στην περίπτωση μας, θα πρέπει να προσθέσετε τι εξής γραμμές: [.programlisting] .... ifconfig_dc0="inet 192.168.1.3 netmask 255.255.255.0" ifconfig_dc1="inet 10.0.0.1 netmask 255.255.255.0 media 10baseT/UTP" .... Θα πρέπει να αντικαταστήσετε το [.filename]#dc0#, [.filename]#dc1#, και ούτω κάθε εξής, με τις σωστές συσκευές των καρτών σας, και τις σωστές διευθύνσεις. Θα πρέπει να διαβάσετε την σελίδα βοηθείας του οδηγού και του man:ifconfig[8] για περισσότερες λεπτομέριες σχετικά με τις επιτρεπόμενες παραμέτρους και επίσης την σελίδα βοηθείας του man:rc.conf[5] για περισσότερες λεπτομέριες σχετικά με την σύνταξη του [.filename]#/etc/rc.conf#. Αν ρυθμίσατε το δίκτυο σας κατα την εγκατάσταση, μερικές γραμμές σχετικές με την/τις κάρτα/κάρτες δικτύου θα υπάρχουν ήδη. Ελέγξτε διπλά το [.filename]#/etc/rc.conf# προτού προσθέστε επιπλέον γραμμές. Θα πρέπει επίσης να διορθώσετε το αρχείο [.filename]#/etc/hosts# ώστε να προσθέσετε τα ονόματα και τις IP διεύθυνσεις απο τα διάφορα μηχανήματα στο LAN σας, αν δεν είναι ήδη ρυθμισμένα. Για περισσότερες πληροφορίες ανατρέξτε στην σελίδα βοηθείας του man:hosts[5] και του [.filename]#/usr/shared/examples/etc/hosts#. === Δοκιμές Και Επίλυση Προβλημάτων Μόλις κάνετε τις βασικές αλλαγές στο [.filename]#/etc/rc.conf#, θα πρέπει να επανεκκινήσετε το σύστημα σας. Αυτό θα επιτρέψει σε πιθανές αλλαγές στις κάρτες να εφαρμοστούν, και να επιβεβαιώσετε ότι το σύστημα επανεκκινεί χωρίς κανένα λάθος στις ρυθμίσεις. Μόλις το σύστημα επανεκκινηθεί, θα πρέπει να δοκιμάσετε τις κάρτες δικτύου. ==== Δοκιμάζοντας Μια Ethernet Κάρτα Για να επιβεβαιώσετε ότι η Ethernet κάρτα λειτουργεί σωστά, θα πρέπει να κάνετε δύο πράγματα. Πρώτα, κάντε ping την κάρτα την ίδια, και μετά κάντε ping ένα άλλο μηχάνημα στο LAN. Πρώτα δοκιμάστε στην τοπική κάρτα: [source,shell] .... % ping -c5 192.168.1.3 PING 192.168.1.3 (192.168.1.3): 56 data bytes 64 bytes from 192.168.1.3: icmp_seq=0 ttl=64 time=0.082 ms 64 bytes from 192.168.1.3: icmp_seq=1 ttl=64 time=0.074 ms 64 bytes from 192.168.1.3: icmp_seq=2 ttl=64 time=0.076 ms 64 bytes from 192.168.1.3: icmp_seq=3 ttl=64 time=0.108 ms 64 bytes from 192.168.1.3: icmp_seq=4 ttl=64 time=0.076 ms --- 192.168.1.3 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.074/0.083/0.108/0.013 ms .... Τώρα δοκιμάστε σε ένα άλλο μηχάνημα στο LAN: [source,shell] .... % ping -c5 192.168.1.2 PING 192.168.1.2 (192.168.1.2): 56 data bytes 64 bytes from 192.168.1.2: icmp_seq=0 ttl=64 time=0.726 ms 64 bytes from 192.168.1.2: icmp_seq=1 ttl=64 time=0.766 ms 64 bytes from 192.168.1.2: icmp_seq=2 ttl=64 time=0.700 ms 64 bytes from 192.168.1.2: icmp_seq=3 ttl=64 time=0.747 ms 64 bytes from 192.168.1.2: icmp_seq=4 ttl=64 time=0.704 ms --- 192.168.1.2 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.700/0.729/0.766/0.025 ms .... Μπορείτε να χρησιμοποιήσετε και το όνομα το μηχανήματος αντί της διεύθυνσης `192.168.1.2` αν έχετε ρυθμίσει το αρχείο [.filename]#/etc/hosts#. ==== Επίλυση Προβλημάτων Η επίλυση προβλημάτων υλικού και λογισμικού είναι πάντοτε επίπονη, ένας πόνος ο οποιός μπορεί να ανακουφιστεί ελέγχοντας μερικά απλά πράγματα πρώτα. Είναι το καλώδιο του δικτύου συνδεδεμένο; Έχετε ρυθμίσει σωστά τις υπηρεσίες δικτύου; Έχετε ρυθμίσει σωστά το πύρινο τείχος; Έχει πράγματι το FreeBSD υποστήριξη για αυτή την κάρτα δικτύου; Πρέπει πάντα να ελέγχετε τις σημειώσεις του υλικού πριν στείλε μία αναφορά για ένα πρόβλημα. Αναβαθμίστε την έκδοση του FreeBSD στην τελευταία ΣΤΑΘΕΡΗ έκδοση. Ελέγξτε τα αρχεία των λιστών μηνυμάτων, ή ψάξτε στο Internet. Αν η κάρτα δουλεύει, αλλά με χαμηλή απόδοση, θα άξιζε να διαβάσετε την σελίδα βοηθείας man:tuning[7]. Μπορείτε επίσης να ελέγξετε οι αν λανθασμένες ρυθμίσεις του δικτύου προκαλούν τις αργές συνδέσεις. Μερικοί χρήστες αντιμετωπίζουν ένα ή δύο μηνύματα `device timeout`, τα οποία είναι φυσιολογικά για μερικές κάρτες. Αν συνεχιστούν, ή γίνουν ενοχλητικά, θα πρέπει να ελέγξετε μήπως και κάποιες συσκευές παρεμποδίζουν η μία την άλλη. Ελέγξτε διπλά τις συνδέσεις των καλωδίων. Ίσως θα πρέπει να αποκτήσετε μία άλλη κάρτα. Μερικές φορές, οι χρήστες παρατηρούν μερικά μηνύματα λάθους `watchdog timeout`. Το πρώτο πράγμα που πρέπει να κάνετε είναι να ελέγξετε το καλώδιο του δικτύου. Αρκέτες κάρτες χρειάζονται μία θέση PCI που να υποστηρίζει Bus Mastering. Σε μερικές παλιές μητρικές κάρτες. μόνο μία θέση PCI το υποστήριζε (συνήθως η θέση 0). Ελέγξτε την κάρτα δικτύου και την τεκμηρίωση της μητρικής κάρτας για να διαπιστώσετε αν εκεί είναι το πρόβλημα. Το μήνυμα `No route to host` εμφανίζεται αν το σύστημα αδυνατεί να δρομολογήσει τα πακέτα στον προορισμό τους. Αυτό συμβαίνει αν δεν έχει καθοριστεί προεπιλεγμένη διεύθυνση δρομολόγησης, ή αν ένα καλώδιο έχει ξεσυνδεθεί. Ελέγξτε την έξοδο τις εντολής `netstat -rn` και σιγουρευτείτε ότι η διεύθυνση δρομολόγησης είναι έγκυρη. Αν δεν έχει καθοριστεί, διαβάστε το crossref:advanced-networking[advanced-networking,Προχωρημένα Θέματα Δικτύωσης] για περισσότερες πληροφορίες. Το μήνυμα λάθους `ping: sendto: Permission denied` συμβαίνει κυρίως λόγο κάποιας λάθος ρύθμισης στο πύρινο τείχος. Αν το `ipfw` είναι ενεργοποιημένο στον πυρήνα αλλά δεν έχουν καθοριστεί κανόνες, τότε η προεπιλεγμένη πολιτική είναι η απαγόρευση όλης της κίνησης, ακόμα και των αιτημάτων ping! Διαβάστε το crossref:firewalls[firewalls,Firewalls] για περισσότερες πληροφορίες. Μερικές φορές η απόδοση της κάρτας μπορεί να είναι φτωχή, ή κάτω του μέσου όρου. Σε αυτές τις περιπτώσεις το καλύτερο είναι να ρυθμίσετε την κατάσταση του μέσου απο `autoselect` στην κατάλληλη κατάσταση. Ενώ συνήθως αυτό φαίνετε να δουλεύει στα περισσότερα υλικά, μπορεί να μην λύσει το πρόβλημα στον καθέναν. Και πάλι, ελέγξτε όλες τις ρυθμίσεις του δικτύου, και ξαναδιαβάστε πάλι την σελίδα βοηθείας man:tuning[7]. [[configtuning-virtual-hosts]] == Εικονικά Hosts Μία αρκετά συνηθισμένη χρήση του FreeBSD είναι η εικονική φιλοξενία ιστοχώρων, όπου και ένας εξυπηρετητής εμφανίζεται στο δίκτυο σαν περισσότερο απο ένας. Αυτό επιτυγχάνεται αναθέτοντας πολλαπλές δικτυακές διευθύνσεις σε μία και μόνο συσκευή. Μία κάρτα δικτύου έχει μία "πραγματική" διεύθυνση, και απεριόριστο αριθμό "εικονικών" διευθύνσεων. Οι εικονικές αυτές διεύθυνσεις προσθέτονται με την μορφή εγγραφών στο αρχείο [.filename]#/etc/rc.conf#. Μία εγγραφή εικονικής διεύθυνσης για την κάρτα δικτύου [.filename]#fxp0# μοιάζει ως εξής: [.programlisting] .... ifconfig_fxp0_alias0="inet xxx.xxx.xxx.xxx netmask xxx.xxx.xxx.xxx" .... Σημειώστε ότι οι εγγραφές αυτές πρέπει να ξεκινούν με `alias0` και να συνεχίζουν πρός τα πάνω σε σειρά, (για παράδειγμα, `_alias1`, `_alias2`, και ούτω κάθε εξής). Η διαδικασία ρύθμισης θα σταματήσει στον πρώτο αριθμό που λείπει. Ο υπολογισμός της μάσκας δικτύου είναι σημαντικός, αλλά ευτυχώς και εύκολος. Για κάθε κάρτα, πρέπει να υπάρχει μία διεύθυνση η οποία αντιπροσωπεύει σωστά την μάσκα του δικτύου. Οποιαδήποτε άλλη διεύθυνση που συμπίπτει στο ίδιο δίκτυο πρέπει να έχει μάσκα δικτύου ``1``s (εκφρασμένη είτε σαν `255.255.255.255` είτε σαν `0xffffffff`). Για παράδειγμα, εξετάστε την περίπτωση όπου η κάρτα δικτύου [.filename]#fxp0# είναι συνδεδεμένη σε δύο δίκτυα, το δίκτυο `10.1.1.0` με μάσκα δικτύου `255.255.255.0` και το δίκτυο `202.0.75.16` με μάσκα δικτύου `255.255.255.240`. Θέλουμε το σύστημα να πάρει τις διευθύνσεις από `10.1.1.1` μέχρι `10.1.1.5` και τις `202.0.75.17` μέχρι `202.0.75.20`. Όπως σημειώθηκε παραπάνω, μόνο η πρώτες διευθύνσεις (στην περίπτωση αυτή, η `10.0.1.1` και η `202.0.75.17`) πρέπει να έχουν πραγματικές μάσκες δικτύου. Όλες οι υπόλοιπες, από (`10.1.1.2` μέχρι `10.1.1.5` και `202.0.75.18` μέχρι `202.0.75.20`) πρέπει να ρυθμιστούν με μάσκα δικτύου `255.255.255.255`. Η ακόλουθες εγγραφές στο αρχείο [.filename]#/etc/rc.conf# θα ρυθμίσουν την κάρτα όπως πρέπει για το παράδειγμα: [.programlisting] .... ifconfig_fxp0="inet 10.1.1.1 netmask 255.255.255.0" ifconfig_fxp0_alias0="inet 10.1.1.2 netmask 255.255.255.255" ifconfig_fxp0_alias1="inet 10.1.1.3 netmask 255.255.255.255" ifconfig_fxp0_alias2="inet 10.1.1.4 netmask 255.255.255.255" ifconfig_fxp0_alias3="inet 10.1.1.5 netmask 255.255.255.255" ifconfig_fxp0_alias4="inet 202.0.75.17 netmask 255.255.255.240" ifconfig_fxp0_alias5="inet 202.0.75.18 netmask 255.255.255.255" ifconfig_fxp0_alias6="inet 202.0.75.19 netmask 255.255.255.255" ifconfig_fxp0_alias7="inet 202.0.75.20 netmask 255.255.255.255" .... [[configtuning-configfiles]] == Αρχεία Ρυθμίσεων === Ο κατάλογος [.filename]#/etc# Τα αρχεία ρυθμίσεων αποθηκεύονται σε καταλόγους. Μερικοί απο αυτούς είναι: [.informaltable] [cols="1,1", frame="none"] |=== |[.filename]#/etc# |Γενικές ρυθμίσεις του συστήματος, data here is system-specific. |[.filename]#/etc/defaults# |Default versions of system configuration files. |[.filename]#/etc/mail# |Extra man:sendmail[8] configuration, other MTA configuration files. |[.filename]#/etc/ppp# |Configuration for both user- and kernel-ppp programs. |[.filename]#/etc/namedb# |Default location for man:named[8] data. Normally [.filename]#named.conf# and zone files are stored here. |[.filename]#/usr/local/etc# |Configuration files for installed applications. May contain per-application subdirectories. |[.filename]#/usr/local/etc/rc.d# |Start/stop scripts for installed applications. |[.filename]#/var/db# |Automatically generated system-specific database files, such as the package database, the locate database, and so on |=== === Hostnames ==== [.filename]#/etc/resolv.conf# [.filename]#/etc/resolv.conf# dictates how FreeBSD's resolver accesses the Internet Domain Name System (DNS). The most common entries to [.filename]#resolv.conf# are: [.informaltable] [cols="1,1", frame="none"] |=== |`nameserver` |The IP address of a name server the resolver should query. The servers are queried in the order listed with a maximum of three. |`search` |Search list for hostname lookup. This is normally determined by the domain of the local hostname. |`domain` |The local domain name. |=== A typical [.filename]#resolv.conf#: [.programlisting] .... search example.com nameserver 147.11.1.11 nameserver 147.11.100.30 .... [NOTE] ==== Only one of the `search` and `domain` options should be used. ==== If you are using DHCP, man:dhclient[8] usually rewrites [.filename]#resolv.conf# with information received from the DHCP server. ==== [.filename]#/etc/hosts# [.filename]#/etc/hosts# is a simple text database reminiscent of the old Internet. It works in conjunction with DNS and NIS providing name to IP address mappings. Local computers connected via a LAN can be placed in here for simplistic naming purposes instead of setting up a man:named[8] server. Additionally, [.filename]#/etc/hosts# can be used to provide a local record of Internet names, reducing the need to query externally for commonly accessed names. [.programlisting] .... # $FreeBSD$ # # Host Database # This file should contain the addresses and aliases # for local hosts that share this file. # In the presence of the domain name service or NIS, this file may # not be consulted at all; see /etc/nsswitch.conf for the resolution order. # # ::1 localhost localhost.my.domain myname.my.domain 127.0.0.1 localhost localhost.my.domain myname.my.domain # # Imaginary network. #10.0.0.2 myname.my.domain myname #10.0.0.3 myfriend.my.domain myfriend # # According to RFC 1918, you can use the following IP networks for # private nets which will never be connected to the Internet: # # 10.0.0.0 - 10.255.255.255 # 172.16.0.0 - 172.31.255.255 # 192.168.0.0 - 192.168.255.255 # # In case you want to be able to connect to the Internet, you need # real official assigned numbers. PLEASE PLEASE PLEASE do not try # to invent your own network numbers but instead get one from your # network provider (if any) or from the Internet Registry (ftp to # rs.internic.net, directory `/templates'). # .... [.filename]#/etc/hosts# takes on the simple format of: [.programlisting] .... [Internet address] [official hostname] [alias1] [alias2] ... .... For example: [.programlisting] .... 10.0.0.1 myRealHostname.example.com myRealHostname foobar1 foobar2 .... Consult man:hosts[5] for more information. === Log File Configuration ==== [.filename]#syslog.conf# [.filename]#syslog.conf# is the configuration file for the man:syslogd[8] program. It indicates which types of `syslog` messages are logged to particular log files. [.programlisting] .... # $FreeBSD$ # # Spaces ARE valid field separators in this file. However, # other *nix-like systems still insist on using tabs as field # separators. If you are sharing this file between systems, you # may want to use only tabs as field separators here. # Consult the syslog.conf(5) manual page. *.err;kern.debug;auth.notice;mail.crit /dev/console *.notice;kern.debug;lpr.info;mail.crit;news.err /var/log/messages security.* /var/log/security mail.info /var/log/maillog lpr.info /var/log/lpd-errs cron.* /var/log/cron *.err root *.notice;news.err root *.alert root *.emerg * # uncomment this to log all writes to /dev/console to /var/log/console.log #console.info /var/log/console.log # uncomment this to enable logging of all log messages to /var/log/all.log #*.* /var/log/all.log # uncomment this to enable logging to a remote log host named loghost #*.* @loghost # uncomment these if you're running inn # news.crit /var/log/news/news.crit # news.err /var/log/news/news.err # news.notice /var/log/news/news.notice !startslip *.* /var/log/slip.log !ppp *.* /var/log/ppp.log .... Consult the man:syslog.conf[5] manual page for more information. ==== [.filename]#newsyslog.conf# [.filename]#newsyslog.conf# is the configuration file for man:newsyslog[8], a program that is normally scheduled to run by man:cron[8]. man:newsyslog[8] determines when log files require archiving or rearranging. [.filename]#logfile# is moved to [.filename]#logfile.0#, [.filename]#logfile.0# is moved to [.filename]#logfile.1#, and so on. Alternatively, the log files may be archived in man:gzip[1] format causing them to be named: [.filename]#logfile.0.gz#, [.filename]#logfile.1.gz#, and so on. [.filename]#newsyslog.conf# indicates which log files are to be managed, how many are to be kept, and when they are to be touched. Log files can be rearranged and/or archived when they have either reached a certain size, or at a certain periodic time/date. [.programlisting] .... # configuration file for newsyslog # $FreeBSD$ # # filename [owner:group] mode count size when [ZB] [/pid_file] [sig_num] /var/log/cron 600 3 100 * Z /var/log/amd.log 644 7 100 * Z /var/log/kerberos.log 644 7 100 * Z /var/log/lpd-errs 644 7 100 * Z /var/log/maillog 644 7 * @T00 Z /var/log/sendmail.st 644 10 * 168 B /var/log/messages 644 5 100 * Z /var/log/all.log 600 7 * @T00 Z /var/log/slip.log 600 3 100 * Z /var/log/ppp.log 600 3 100 * Z /var/log/security 600 10 100 * Z /var/log/wtmp 644 3 * @01T05 B /var/log/daily.log 640 7 * @T00 Z /var/log/weekly.log 640 5 1 $W6D0 Z /var/log/monthly.log 640 12 * $M1D0 Z /var/log/console.log 640 5 100 * Z .... Consult the man:newsyslog[8] manual page for more information. [[configtuning-sysctlconf]] === [.filename]#sysctl.conf# [.filename]#sysctl.conf# looks much like [.filename]#rc.conf#. Values are set in a `variable=value` form. The specified values are set after the system goes into multi-user mode. Not all variables are settable in this mode. To turn off logging of fatal signal exits and prevent users from seeing processes started from other users, the following tunables can be set in [.filename]#sysctl.conf#: [.programlisting] .... # Do not log fatal signal exits (e.g. sig 11) kern.logsigexit=0 # Prevent users from seeing information about processes that # are being run under another UID. security.bsd.see_other_uids=0 .... [[configtuning-sysctl]] == Tuning with sysctl man:sysctl[8] is an interface that allows you to make changes to a running FreeBSD system. This includes many advanced options of the TCP/IP stack and virtual memory system that can dramatically improve performance for an experienced system administrator. Over five hundred system variables can be read and set using man:sysctl[8]. At its core, man:sysctl[8] serves two functions: to read and to modify system settings. To view all readable variables: [source,shell] .... % sysctl -a .... To read a particular variable, for example, `kern.maxproc`: [source,shell] .... % sysctl kern.maxproc kern.maxproc: 1044 .... To set a particular variable, use the intuitive _variable_=_value_ syntax: [source,shell] .... # sysctl kern.maxfiles=5000 kern.maxfiles: 2088 -> 5000 .... Settings of sysctl variables are usually either strings, numbers, or booleans (a boolean being `1` for yes or a `0` for no). If you want to set automatically some variables each time the machine boots, add them to the [.filename]#/etc/sysctl.conf# file. For more information see the man:sysctl.conf[5] manual page and the <>. [[sysctl-readonly]] === man:sysctl[8] Read-only In some cases it may be desirable to modify read-only man:sysctl[8] values. While this is sometimes unavoidable, it can only be done on (re)boot. For instance on some laptop models the man:cardbus[4] device will not probe memory ranges, and fail with errors which look similar to: [source,shell] .... cbb0: Could not map register memory device_probe_and_attach: cbb0 attach returned 12 .... Cases like the one above usually require the modification of some default man:sysctl[8] settings which are set read only. To overcome these situations a user can put man:sysctl[8] "OIDs" in their local [.filename]#/boot/loader.conf#. Default settings are located in the [.filename]#/boot/defaults/loader.conf# file. Fixing the problem mentioned above would require a user to set `hw.pci.allow_unsupported_io_range=1` in the aforementioned file. Now man:cardbus[4] will work properly. [[configtuning-disk]] == Tuning Disks === Sysctl Variables ==== `vfs.vmiodirenable` The `vfs.vmiodirenable` sysctl variable may be set to either 0 (off) or 1 (on); it is 1 by default. This variable controls how directories are cached by the system. Most directories are small, using just a single fragment (typically 1 K) in the file system and less (typically 512 bytes) in the buffer cache. With this variable turned off (to 0), the buffer cache will only cache a fixed number of directories even if you have a huge amount of memory. When turned on (to 1), this sysctl allows the buffer cache to use the VM Page Cache to cache the directories, making all the memory available for caching directories. However, the minimum in-core memory used to cache a directory is the physical page size (typically 4 K) rather than 512 bytes. We recommend keeping this option on if you are running any services which manipulate large numbers of files. Such services can include web caches, large mail systems, and news systems. Keeping this option on will generally not reduce performance even with the wasted memory but you should experiment to find out. ==== `vfs.write_behind` The `vfs.write_behind` sysctl variable defaults to `1` (on). This tells the file system to issue media writes as full clusters are collected, which typically occurs when writing large sequential files. The idea is to avoid saturating the buffer cache with dirty buffers when it would not benefit I/O performance. However, this may stall processes and under certain circumstances you may wish to turn it off. ==== `vfs.hirunningspace` The `vfs.hirunningspace` sysctl variable determines how much outstanding write I/O may be queued to disk controllers system-wide at any given instance. The default is usually sufficient but on machines with lots of disks you may want to bump it up to four or five _megabytes_. Note that setting too high a value (exceeding the buffer cache's write threshold) can lead to extremely bad clustering performance. Do not set this value arbitrarily high! Higher write values may add latency to reads occurring at the same time. There are various other buffer-cache and VM page cache related sysctls. We do not recommend modifying these values, the VM system does an extremely good job of automatically tuning itself. ==== `vm.swap_idle_enabled` The `vm.swap_idle_enabled` sysctl variable is useful in large multi-user systems where you have lots of users entering and leaving the system and lots of idle processes. Such systems tend to generate a great deal of continuous pressure on free memory reserves. Turning this feature on and tweaking the swapout hysteresis (in idle seconds) via `vm.swap_idle_threshold1` and `vm.swap_idle_threshold2` allows you to depress the priority of memory pages associated with idle processes more quickly then the normal pageout algorithm. This gives a helping hand to the pageout daemon. Do not turn this option on unless you need it, because the tradeoff you are making is essentially pre-page memory sooner rather than later; thus eating more swap and disk bandwidth. In a small system this option will have a determinable effect but in a large system that is already doing moderate paging this option allows the VM system to stage whole processes into and out of memory easily. ==== `hw.ata.wc` FreeBSD 4.3 flirted with turning off IDE write caching. This reduced write bandwidth to IDE disks but was considered necessary due to serious data consistency issues introduced by hard drive vendors. The problem is that IDE drives lie about when a write completes. With IDE write caching turned on, IDE hard drives not only write data to disk out of order, but will sometimes delay writing some blocks indefinitely when under heavy disk loads. A crash or power failure may cause serious file system corruption. FreeBSD's default was changed to be safe. Unfortunately, the result was such a huge performance loss that we changed write caching back to on by default after the release. You should check the default on your system by observing the `hw.ata.wc` sysctl variable. If IDE write caching is turned off, you can turn it back on by setting the kernel variable back to 1. This must be done from the boot loader at boot time. Attempting to do it after the kernel boots will have no effect. For more information, please see man:ata[4]. ==== `SCSI_DELAY` (`kern.cam.scsi_delay`) The `SCSI_DELAY` kernel config may be used to reduce system boot times. The defaults are fairly high and can be responsible for `15` seconds of delay in the boot process. Reducing it to `5` seconds usually works (especially with modern drives). Newer versions of FreeBSD (5.0 and higher) should use the `kern.cam.scsi_delay` boot time tunable. The tunable, and kernel config option accept values in terms of _milliseconds_ and _not seconds_. [[soft-updates]] === Soft Updates The man:tunefs[8] program can be used to fine-tune a file system. This program has many different options, but for now we are only concerned with toggling Soft Updates on and off, which is done by: [source,shell] .... # tunefs -n enable /filesystem # tunefs -n disable /filesystem .... A filesystem cannot be modified with man:tunefs[8] while it is mounted. A good time to enable Soft Updates is before any partitions have been mounted, in single-user mode. Soft Updates drastically improves meta-data performance, mainly file creation and deletion, through the use of a memory cache. We recommend to use Soft Updates on all of your file systems. There are two downsides to Soft Updates that you should be aware of: First, Soft Updates guarantees filesystem consistency in the case of a crash but could very easily be several seconds (even a minute!) behind updating the physical disk. If your system crashes you may lose more work than otherwise. Secondly, Soft Updates delays the freeing of filesystem blocks. If you have a filesystem (such as the root filesystem) which is almost full, performing a major update, such as `make installworld`, can cause the filesystem to run out of space and the update to fail. ==== More Details about Soft Updates There are two traditional approaches to writing a file systems meta-data back to disk. (Meta-data updates are updates to non-content data like inodes or directories.) Historically, the default behavior was to write out meta-data updates synchronously. If a directory had been changed, the system waited until the change was actually written to disk. The file data buffers (file contents) were passed through the buffer cache and backed up to disk later on asynchronously. The advantage of this implementation is that it operates safely. If there is a failure during an update, the meta-data are always in a consistent state. A file is either created completely or not at all. If the data blocks of a file did not find their way out of the buffer cache onto the disk by the time of the crash, man:fsck[8] is able to recognize this and repair the filesystem by setting the file length to 0. Additionally, the implementation is clear and simple. The disadvantage is that meta-data changes are slow. An `rm -r`, for instance, touches all the files in a directory sequentially, but each directory change (deletion of a file) will be written synchronously to the disk. This includes updates to the directory itself, to the inode table, and possibly to indirect blocks allocated by the file. Similar considerations apply for unrolling large hierarchies (`tar -x`). The second case is asynchronous meta-data updates. This is the default for Linux/ext2fs and `mount -o async` for *BSD ufs. All meta-data updates are simply being passed through the buffer cache too, that is, they will be intermixed with the updates of the file content data. The advantage of this implementation is there is no need to wait until each meta-data update has been written to disk, so all operations which cause huge amounts of meta-data updates work much faster than in the synchronous case. Also, the implementation is still clear and simple, so there is a low risk for bugs creeping into the code. The disadvantage is that there is no guarantee at all for a consistent state of the filesystem. If there is a failure during an operation that updated large amounts of meta-data (like a power failure, or someone pressing the reset button), the filesystem will be left in an unpredictable state. There is no opportunity to examine the state of the filesystem when the system comes up again; the data blocks of a file could already have been written to the disk while the updates of the inode table or the associated directory were not. It is actually impossible to implement a `fsck` which is able to clean up the resulting chaos (because the necessary information is not available on the disk). If the filesystem has been damaged beyond repair, the only choice is to use man:newfs[8] on it and restore it from backup. The usual solution for this problem was to implement _dirty region logging_, which is also referred to as _journaling_, although that term is not used consistently and is occasionally applied to other forms of transaction logging as well. Meta-data updates are still written synchronously, but only into a small region of the disk. Later on they will be moved to their proper location. Because the logging area is a small, contiguous region on the disk, there are no long distances for the disk heads to move, even during heavy operations, so these operations are quicker than synchronous updates. Additionally the complexity of the implementation is fairly limited, so the risk of bugs being present is low. A disadvantage is that all meta-data are written twice (once into the logging region and once to the proper location) so for normal work, a performance "pessimization" might result. On the other hand, in case of a crash, all pending meta-data operations can be quickly either rolled-back or completed from the logging area after the system comes up again, resulting in a fast filesystem startup. Kirk McKusick, the developer of Berkeley FFS, solved this problem with Soft Updates: all pending meta-data updates are kept in memory and written out to disk in a sorted sequence ("ordered meta-data updates"). This has the effect that, in case of heavy meta-data operations, later updates to an item "catch" the earlier ones if the earlier ones are still in memory and have not already been written to disk. So all operations on, say, a directory are generally performed in memory before the update is written to disk (the data blocks are sorted according to their position so that they will not be on the disk ahead of their meta-data). If the system crashes, this causes an implicit "log rewind": all operations which did not find their way to the disk appear as if they had never happened. A consistent filesystem state is maintained that appears to be the one of 30 to 60 seconds earlier. The algorithm used guarantees that all resources in use are marked as such in their appropriate bitmaps: blocks and inodes. After a crash, the only resource allocation error that occurs is that resources are marked as "used" which are actually "free". man:fsck[8] recognizes this situation, and frees the resources that are no longer used. It is safe to ignore the dirty state of the filesystem after a crash by forcibly mounting it with `mount -f`. In order to free resources that may be unused, man:fsck[8] needs to be run at a later time. This is the idea behind the _background fsck_: at system startup time, only a _snapshot_ of the filesystem is recorded. The `fsck` can be run later on. All file systems can then be mounted "dirty", so the system startup proceeds in multiuser mode. Then, background ``fsck``s will be scheduled for all file systems where this is required, to free resources that may be unused. (File systems that do not use Soft Updates still need the usual foreground `fsck` though.) The advantage is that meta-data operations are nearly as fast as asynchronous updates (i.e. faster than with _logging_, which has to write the meta-data twice). The disadvantages are the complexity of the code (implying a higher risk for bugs in an area that is highly sensitive regarding loss of user data), and a higher memory consumption. Additionally there are some idiosyncrasies one has to get used to. After a crash, the state of the filesystem appears to be somewhat "older". In situations where the standard synchronous approach would have caused some zero-length files to remain after the `fsck`, these files do not exist at all with a Soft Updates filesystem because neither the meta-data nor the file contents have ever been written to disk. Disk space is not released until the updates have been written to disk, which may take place some time after running `rm`. This may cause problems when installing large amounts of data on a filesystem that does not have enough free space to hold all the files twice. [[configtuning-kernel-limits]] == Tuning Kernel Limits [[file-process-limits]] === File/Process Limits [[kern-maxfiles]] ==== `kern.maxfiles` `kern.maxfiles` can be raised or lowered based upon your system requirements. This variable indicates the maximum number of file descriptors on your system. When the file descriptor table is full, `file: table is full` will show up repeatedly in the system message buffer, which can be viewed with the `dmesg` command. Each open file, socket, or fifo uses one file descriptor. A large-scale production server may easily require many thousands of file descriptors, depending on the kind and number of services running concurrently. In older FreeBSD releases, the default value of `kern.maxfiles` is derived from the `maxusers` option in your kernel configuration file. `kern.maxfiles` grows proportionally to the value of `maxusers`. When compiling a custom kernel, it is a good idea to set this kernel configuration option according to the uses of your system. From this number, the kernel is given most of its pre-defined limits. Even though a production machine may not actually have 256 users connected at once, the resources needed may be similar to a high-scale web server. As of FreeBSD 4.5, `kern.maxusers` is automatically sized at boot based on the amount of memory available in the system, and may be determined at run-time by inspecting the value of the read-only `kern.maxusers` sysctl. Some sites will require larger or smaller values of `kern.maxusers` and may set it as a loader tunable; values of 64, 128, and 256 are not uncommon. We do not recommend going above 256 unless you need a huge number of file descriptors; many of the tunable values set to their defaults by `kern.maxusers` may be individually overridden at boot-time or run-time in [.filename]#/boot/loader.conf# (see the man:loader.conf[5] man page or the [.filename]#/boot/defaults/loader.conf# file for some hints) or as described elsewhere in this document. Systems older than FreeBSD 4.4 must set this value via the kernel man:config[8] option `maxusers` instead. In older releases, the system will auto-tune `maxusers` for you if you explicitly set it to `0`. When setting this option, you will want to set `maxusers` to at least 4, especially if you are using the X Window System or compiling software. The reason is that the most important table set by `maxusers` is the maximum number of processes, which is set to `20 + 16 * maxusers`, so if you set `maxusers` to 1, then you can only have 36 simultaneous processes, including the 18 or so that the system starts up at boot time and the 15 or so you will probably create when you start the X Window System. Even a simple task like reading a manual page will start up nine processes to filter, decompress, and view it. Setting `maxusers` to 64 will allow you to have up to 1044 simultaneous processes, which should be enough for nearly all uses. If, however, you see the dreaded error when trying to start another program, or are running a server with a large number of simultaneous users (like `ftp.FreeBSD.org`), you can always increase the number and rebuild. [NOTE] ==== `maxusers` does _not_ limit the number of users which can log into your machine. It simply sets various table sizes to reasonable values considering the maximum number of users you will likely have on your system and how many processes each of them will be running. One keyword which _does_ limit the number of simultaneous remote logins and X terminal windows is crossref:kernelconfig[kernelconfig-ptys,`pseudo-device pty 16`]. With FreeBSD 5.X, you do not have to worry about this number since the man:pty[4] driver is "auto-cloning"; you simply use the line `device pty` in your configuration file. ==== ==== `kern.ipc.somaxconn` The `kern.ipc.somaxconn` sysctl variable limits the size of the listen queue for accepting new TCP connections. The default value of `128` is typically too low for robust handling of new connections in a heavily loaded web server environment. For such environments, it is recommended to increase this value to `1024` or higher. The service daemon may itself limit the listen queue size (e.g. man:sendmail[8], or Apache) but will often have a directive in its configuration file to adjust the queue size. Large listen queues also do a better job of avoiding Denial of Service () attacks. [[nmbclusters]] === Network Limits The `NMBCLUSTERS` kernel configuration option dictates the amount of network Mbufs available to the system. A heavily-trafficked server with a low number of Mbufs will hinder FreeBSD's ability. Each cluster represents approximately 2 K of memory, so a value of 1024 represents 2 megabytes of kernel memory reserved for network buffers. A simple calculation can be done to figure out how many are needed. If you have a web server which maxes out at 1000 simultaneous connections, and each connection eats a 16 K receive and 16 K send buffer, you need approximately 32 MB worth of network buffers to cover the web server. A good rule of thumb is to multiply by 2, so 2x32 MB / 2 KB = 64 MB / 2 kB = 32768. We recommend values between 4096 and 32768 for machines with greater amounts of memory. Under no circumstances should you specify an arbitrarily high value for this parameter as it could lead to a boot time crash. The `-m` option to man:netstat[1] may be used to observe network cluster use. `kern.ipc.nmbclusters` loader tunable should be used to tune this at boot time. Only older versions of FreeBSD will require you to use the `NMBCLUSTERS` kernel man:config[8] option. For busy servers that make extensive use of the man:sendfile[2] system call, it may be necessary to increase the number of man:sendfile[2] buffers via the `NSFBUFS` kernel configuration option or by setting its value in [.filename]#/boot/loader.conf# (see man:loader[8] for details). A common indicator that this parameter needs to be adjusted is when processes are seen in the `sfbufa` state. The sysctl variable `kern.ipc.nsfbufs` is a read-only glimpse at the kernel configured variable. This parameter nominally scales with `kern.maxusers`, however it may be necessary to tune accordingly. [IMPORTANT] ==== Even though a socket has been marked as non-blocking, calling man:sendfile[2] on the non-blocking socket may result in the man:sendfile[2] call blocking until enough ``struct sf_buf``'s are made available. ==== ==== `net.inet.ip.portrange.*` The `net.inet.ip.portrange.*` sysctl variables control the port number ranges automatically bound to TCP and UDP sockets. There are three ranges: a low range, a default range, and a high range. Most network programs use the default range which is controlled by the `net.inet.ip.portrange.first` and `net.inet.ip.portrange.last`, which default to 1024 and 5000, respectively. Bound port ranges are used for outgoing connections, and it is possible to run the system out of ports under certain circumstances. This most commonly occurs when you are running a heavily loaded web proxy. The port range is not an issue when running servers which handle mainly incoming connections, such as a normal web server, or has a limited number of outgoing connections, such as a mail relay. For situations where you may run yourself out of ports, it is recommended to increase `net.inet.ip.portrange.last` modestly. A value of `10000`, `20000` or `30000` may be reasonable. You should also consider firewall effects when changing the port range. Some firewalls may block large ranges of ports (usually low-numbered ports) and expect systems to use higher ranges of ports for outgoing connections - for this reason it is not recommended that `net.inet.ip.portrange.first` be lowered. ==== TCP Bandwidth Delay Product The TCP Bandwidth Delay Product Limiting is similar to TCP/Vegas in NetBSD. It can be enabled by setting `net.inet.tcp.inflight.enable` sysctl variable to `1`. The system will attempt to calculate the bandwidth delay product for each connection and limit the amount of data queued to the network to just the amount required to maintain optimum throughput. This feature is useful if you are serving data over modems, Gigabit Ethernet, or even high speed WAN links (or any other link with a high bandwidth delay product), especially if you are also using window scaling or have configured a large send window. If you enable this option, you should also be sure to set `net.inet.tcp.inflight.debug` to `0` (disable debugging), and for production use setting `net.inet.tcp.inflight.min` to at least `6144` may be beneficial. However, note that setting high minimums may effectively disable bandwidth limiting depending on the link. The limiting feature reduces the amount of data built up in intermediate route and switch packet queues as well as reduces the amount of data built up in the local host's interface queue. With fewer packets queued up, interactive connections, especially over slow modems, will also be able to operate with lower _Round Trip Times_. However, note that this feature only effects data transmission (uploading / server side). It has no effect on data reception (downloading). Adjusting `net.inet.tcp.inflight.stab` is _not_ recommended. This parameter defaults to 20, representing 2 maximal packets added to the bandwidth delay product window calculation. The additional window is required to stabilize the algorithm and improve responsiveness to changing conditions, but it can also result in higher ping times over slow links (though still much lower than you would get without the inflight algorithm). In such cases, you may wish to try reducing this parameter to 15, 10, or 5; and may also have to reduce `net.inet.tcp.inflight.min` (for example, to 3500) to get the desired effect. Reducing these parameters should be done as a last resort only. === Virtual Memory ==== `kern.maxvnodes` A vnode is the internal representation of a file or directory. So increasing the number of vnodes available to the operating system cuts down on disk I/O. Normally this is handled by the operating system and does not need to be changed. In some cases where disk I/O is a bottleneck and the system is running out of vnodes, this setting will need to be increased. The amount of inactive and free RAM will need to be taken into account. To see the current number of vnodes in use: [.programlisting] .... # sysctl vfs.numvnodes vfs.numvnodes: 91349 .... To see the maximum vnodes: [.programlisting] .... # sysctl kern.maxvnodes kern.maxvnodes: 100000 .... If the current vnode usage is near the maximum, increasing `kern.maxvnodes` by a value of 1,000 is probably a good idea. Keep an eye on the number of `vfs.numvnodes`. If it climbs up to the maximum again, `kern.maxvnodes` will need to be increased further. A shift in your memory usage as reported by man:top[1] should be visible. More memory should be active. [[adding-swap-space]] == Adding Swap Space No matter how well you plan, sometimes a system does not run as you expect. If you find you need more swap space, it is simple enough to add. You have three ways to increase swap space: adding a new hard drive, enabling swap over NFS, and creating a swap file on an existing partition. For information on how to encrypt swap space, what options for this task exist and why it should be done, please refer to crossref:disks[swap-encrypting,Encrypting Swap Space] of the Handbook. [[new-drive-swap]] === Swap on a New Hard Drive The best way to add swap, of course, is to use this as an excuse to add another hard drive. You can always use another hard drive, after all. If you can do this, go reread the discussion of swap space in <> of the Handbook for some suggestions on how to best arrange your swap. [[nfs-swap]] === Swapping over NFS Swapping over NFS is only recommended if you do not have a local hard disk to swap to; NFS swapping will be limited by the available network bandwidth and puts an additional burden on the NFS server. [[create-swapfile]] === Swapfiles You can create a file of a specified size to use as a swap file. In our example here we will use a 64MB file called [.filename]#/usr/swap0#. You can use any name you want, of course. .Creating a Swapfile on FreeBSD [example] ==== . Be certain that your kernel configuration includes the memory disk driver (man:md[4]). It is default in [.filename]#GENERIC# kernel. + [.programlisting] .... device md # Memory "disks" .... . Create a swapfile ([.filename]#/usr/swap0#): + [source,shell] .... # dd if=/dev/zero of=/usr/swap0 bs=1024k count=64 .... . Set proper permissions on ([.filename]#/usr/swap0#): + [source,shell] .... # chmod 0600 /usr/swap0 .... . Enable the swap file in [.filename]#/etc/rc.conf#: + [.programlisting] .... swapfile="/usr/swap0" # Set to name of swapfile if aux swapfile desired. .... . Reboot the machine or to enable the swap file immediately, type: + [source,shell] .... # mdconfig -a -t vnode -f /usr/swap0 -u 0 && swapon /dev/md0 .... ==== [[acpi-overview]] == Power and Resource Management It is important to utilize hardware resources in an efficient manner. Before ACPI was introduced, it was difficult and inflexible for operating systems to manage the power usage and thermal properties of a system. The hardware was managed by the BIOS and thus the user had less control and visibility into the power management settings. Some limited configurability was available via _Advanced Power Management (APM)_. Power and resource management is one of the key components of a modern operating system. For example, you may want an operating system to monitor system limits (and possibly alert you) in case your system temperature increased unexpectedly. In this section of the FreeBSD Handbook, we will provide comprehensive information about ACPI. References will be provided for further reading at the end. [[acpi-intro]] === What Is ACPI? Advanced Configuration and Power Interface (ACPI) is a standard written by an alliance of vendors to provide a standard interface for hardware resources and power management (hence the name). It is a key element in _Operating System-directed configuration and Power Management_, i.e.: it provides more control and flexibility to the operating system (OS). Modern systems "stretched" the limits of the current Plug and Play interfaces prior to the introduction of ACPI. ACPI is the direct successor to APM (Advanced Power Management). [[acpi-old-spec]] === Shortcomings of Advanced Power Management (APM) The _Advanced Power Management (APM)_ facility controls the power usage of a system based on its activity. The APM BIOS is supplied by the (system) vendor and it is specific to the hardware platform. An APM driver in the OS mediates access to the _APM Software Interface_, which allows management of power levels. APM should still be used for systems manufactured at or before the year 2000. There are four major problems in APM. Firstly, power management is done by the (vendor-specific) BIOS, and the OS does not have any knowledge of it. One example of this, is when the user sets idle-time values for a hard drive in the APM BIOS, that when exceeded, it (BIOS) would spin down the hard drive, without the consent of the OS. Secondly, the APM logic is embedded in the BIOS, and it operates outside the scope of the OS. This means users can only fix problems in their APM BIOS by flashing a new one into the ROM; which is a very dangerous procedure with the potential to leave the system in an unrecoverable state if it fails. Thirdly, APM is a vendor-specific technology, which means that there is a lot of parity (duplication of efforts) and bugs found in one vendor's BIOS, may not be solved in others. Last but not the least, the APM BIOS did not have enough room to implement a sophisticated power policy, or one that can adapt very well to the purpose of the machine. _Plug and Play BIOS (PNPBIOS)_ was unreliable in many situations. PNPBIOS is 16-bit technology, so the OS has to use 16-bit emulation in order to "interface" with PNPBIOS methods. The FreeBSD APM driver is documented in the man:apm[4] manual page. [[acpi-config]] === Configuring ACPI The [.filename]#acpi.ko# driver is loaded by default at start up by the man:loader[8] and should _not_ be compiled into the kernel. The reasoning behind this is that modules are easier to work with, say if switching to another [.filename]#acpi.ko# without doing a kernel rebuild. This has the advantage of making testing easier. Another reason is that starting ACPI after a system has been brought up often doesn't work well. If you are experiencing problems, you can disable ACPI altogether. This driver should not and can not be unloaded because the system bus uses it for various hardware interactions. ACPI can be disabled by setting `hint.acpi.0.disabled="1"` in [.filename]#/boot/loader.conf# or at the man:loader[8] prompt. [NOTE] ==== ACPI and APM cannot coexist and should be used separately. The last one to load will terminate if the driver notices the other running. ==== ACPI can be used to put the system into a sleep mode with man:acpiconf[8], the `-s` flag, and a `1-5` option. Most users will only need `1` or `3` (suspend to RAM). Option `5` will do a soft-off which is the same action as: [source,shell] .... # halt -p .... Other options are available via man:sysctl[8]. Check out the man:acpi[4] and man:acpiconf[8] manual pages for more information. [[ACPI-debug]] == Using and Debugging FreeBSD ACPI ACPI is a fundamentally new way of discovering devices, managing power usage, and providing standardized access to various hardware previously managed by the BIOS. Progress is being made toward ACPI working on all systems, but bugs in some motherboards' _ACPI Machine Language_ (AML) bytecode, incompleteness in FreeBSD's kernel subsystems, and bugs in the Intel(R) ACPI-CA interpreter continue to appear. This document is intended to help you assist the FreeBSD ACPI maintainers in identifying the root cause of problems you observe and debugging and developing a solution. Thanks for reading this and we hope we can solve your system's problems. [[ACPI-submitdebug]] === Submitting Debugging Information [NOTE] ==== Before submitting a problem, be sure you are running the latest BIOS version and, if available, embedded controller firmware version. ==== For those of you that want to submit a problem right away, please send the following information to link:mailto:freebsd-acpi@FreeBSD.org[ freebsd-acpi@FreeBSD.org]: * Description of the buggy behavior, including system type and model and anything that causes the bug to appear. Also, please note as accurately as possible when the bug began occurring if it is new for you. * The man:dmesg[8] output after `boot -v`, including any error messages generated by you exercising the bug. * The man:dmesg[8] output from `boot -v` with ACPI disabled, if disabling it helps fix the problem. * Output from `sysctl hw.acpi`. This is also a good way of figuring out what features your system offers. * URL where your _ACPI Source Language_ (ASL) can be found. Do _not_ send the ASL directly to the list as it can be very large. Generate a copy of your ASL by running this command: + [source,shell] .... # acpidump -dt > name-system.asl .... + (Substitute your login name for _name_ and manufacturer/model for _system_. Example: [.filename]#njl-FooCo6000.asl#) Most of the developers watch the {freebsd-current} but please submit problems to {freebsd-acpi} to be sure it is seen. Please be patient, all of us have full-time jobs elsewhere. If your bug is not immediately apparent, we will probably ask you to submit a PR via man:send-pr[1]. When entering a PR, please include the same information as requested above. This will help us track the problem and resolve it. Do not send a PR without emailing {freebsd-acpi} first as we use PRs as reminders of existing problems, not a reporting mechanism. It is likely that your problem has been reported by someone before. [[ACPI-background]] === Background ACPI is present in all modern computers that conform to the ia32 (x86), ia64 (Itanium), and amd64 (AMD) architectures. The full standard has many features including CPU performance management, power planes control, thermal zones, various battery systems, embedded controllers, and bus enumeration. Most systems implement less than the full standard. For instance, a desktop system usually only implements the bus enumeration parts while a laptop might have cooling and battery management support as well. Laptops also have suspend and resume, with their own associated complexity. An ACPI-compliant system has various components. The BIOS and chipset vendors provide various fixed tables (e.g., FADT) in memory that specify things like the APIC map (used for SMP), config registers, and simple configuration values. Additionally, a table of bytecode (the _Differentiated System Description Table_ DSDT) is provided that specifies a tree-like name space of devices and methods. The ACPI driver must parse the fixed tables, implement an interpreter for the bytecode, and modify device drivers and the kernel to accept information from the ACPI subsystem. For FreeBSD, Intel(R) has provided an interpreter (ACPI-CA) that is shared with Linux and NetBSD. The path to the ACPI-CA source code is [.filename]#src/sys/contrib/dev/acpica#. The glue code that allows ACPI-CA to work on FreeBSD is in [.filename]#src/sys/dev/acpica/Osd#. Finally, drivers that implement various ACPI devices are found in [.filename]#src/sys/dev/acpica#. [[ACPI-comprob]] === Common Problems For ACPI to work correctly, all the parts have to work correctly. Here are some common problems, in order of frequency of appearance, and some possible workarounds or fixes. ==== Mouse Issues In some cases, resuming from a suspend operation will cause the mouse to fail. A known work around is to add `hint.psm.0.flags="0x3000"` to the [.filename]#/boot/loader.conf# file. If this does not work then please consider sending a bug report as described above. ==== Suspend/Resume ACPI has three suspend to RAM (STR) states, `S1`-`S3`, and one suspend to disk state (`STD`), called `S4`. `S5` is "soft off" and is the normal state your system is in when plugged in but not powered up. `S4` can actually be implemented two separate ways. ``S4``BIOS is a BIOS-assisted suspend to disk. ``S4``OS is implemented entirely by the operating system. Start by checking `sysctl hw.acpi` for the suspend-related items. Here are the results for a Thinkpad: [source,shell] .... hw.acpi.supported_sleep_state: S3 S4 S5 hw.acpi.s4bios: 0 .... This means that we can use `acpiconf -s` to test `S3`, ``S4``OS, and `S5`. If `s4bios` was one (`1`), we would have ``S4``BIOS support instead of ``S4``OS. When testing suspend/resume, start with `S1`, if supported. This state is most likely to work since it does not require much driver support. No one has implemented `S2` but if you have it, it is similar to `S1`. The next thing to try is `S3`. This is the deepest STR state and requires a lot of driver support to properly reinitialize your hardware. If you have problems resuming, feel free to email the {freebsd-acpi} list but do not expect the problem to be resolved since there are a lot of drivers/hardware that need more testing and work. To help isolate the problem, remove as many drivers from your kernel as possible. If it works, you can narrow down which driver is the problem by loading drivers until it fails again. Typically binary drivers like [.filename]#nvidia.ko#, X11 display drivers, and USB will have the most problems while Ethernet interfaces usually work fine. If you can properly load/unload the drivers, you can automate this by putting the appropriate commands in [.filename]#/etc/rc.suspend# and [.filename]#/etc/rc.resume#. There is a commented-out example for unloading and loading a driver. Try setting `hw.acpi.reset_video` to zero (`0`) if your display is messed up after resume. Try setting longer or shorter values for `hw.acpi.sleep_delay` to see if that helps. Another thing to try is load a recent Linux distribution with ACPI support and test their suspend/resume support on the same hardware. If it works on Linux, it is likely a FreeBSD driver problem and narrowing down which driver causes the problems will help us fix the problem. Note that the ACPI maintainers do not usually maintain other drivers (e.g sound, ATA, etc.) so any work done on tracking down a driver problem should probably eventually be posted to the {freebsd-current} list and mailed to the driver maintainer. If you are feeling adventurous, go ahead and start putting some debugging man:printf[3]s in a problematic driver to track down where in its resume function it hangs. Finally, try disabling ACPI and enabling APM instead. If suspend/resume works with APM, you may be better off sticking with APM, especially on older hardware (pre-2000). It took vendors a while to get ACPI support correct and older hardware is more likely to have BIOS problems with ACPI. ==== System Hangs (temporary or permanent) Most system hangs are a result of lost interrupts or an interrupt storm. Chipsets have a lot of problems based on how the BIOS configures interrupts before boot, correctness of the APIC (MADT) table, and routing of the _System Control Interrupt_ (SCI). Interrupt storms can be distinguished from lost interrupts by checking the output of `vmstat -i` and looking at the line that has `acpi0`. If the counter is increasing at more than a couple per second, you have an interrupt storm. If the system appears hung, try breaking to DDB (kbd:[CTRL+ALT+ESC] on console) and type `show interrupts`. Your best hope when dealing with interrupt problems is to try disabling APIC support with `hint.apic.0.disabled="1"` in [.filename]#loader.conf#. ==== Panics Panics are relatively rare for ACPI and are the top priority to be fixed. The first step is to isolate the steps to reproduce the panic (if possible) and get a backtrace. Follow the advice for enabling `options DDB` and setting up a serial console (see crossref:serialcomms:[serialconsole-ddb,Είσοδος στον DDB Debugger Μέσω της Σειριακής Γραμμής]) or setting up a man:dump[8] partition. You can get a backtrace in DDB with `tr`. If you have to handwrite the backtrace, be sure to at least get the lowest five (5) and top five (5) lines in the trace. Then, try to isolate the problem by booting with ACPI disabled. If that works, you can isolate the ACPI subsystem by using various values of `debug.acpi.disable`. See the man:acpi[4] manual page for some examples. ==== System Powers Up After Suspend or Shutdown First, try setting `hw.acpi.disable_on_poweroff="0"` in man:loader.conf[5]. This keeps ACPI from disabling various events during the shutdown process. Some systems need this value set to `1` (the default) for the same reason. This usually fixes the problem of a system powering up spontaneously after a suspend or poweroff. ==== Other Problems If you have other problems with ACPI (working with a docking station, devices not detected, etc.), please email a description to the mailing list as well; however, some of these issues may be related to unfinished parts of the ACPI subsystem so they might take a while to be implemented. Please be patient and prepared to test patches we may send you. [[ACPI-aslanddump]] === ASL, `acpidump`, and IASL The most common problem is the BIOS vendors providing incorrect (or outright buggy!) bytecode. This is usually manifested by kernel console messages like this: [source,shell] .... ACPI-1287: *** Error: Method execution failed [\\_SB_.PCI0.LPC0.FIGD._STA] \\ (Node 0xc3f6d160), AE_NOT_FOUND .... Often, you can resolve these problems by updating your BIOS to the latest revision. Most console messages are harmless but if you have other problems like battery status not working, they are a good place to start looking for problems in the AML. The bytecode, known as AML, is compiled from a source language called ASL. The AML is found in the table known as the DSDT. To get a copy of your ASL, use man:acpidump[8]. You should use both the `-t` (show contents of the fixed tables) and `-d` (disassemble AML to ASL) options. See the <> section for an example syntax. The simplest first check you can do is to recompile your ASL to check for errors. Warnings can usually be ignored but errors are bugs that will usually prevent ACPI from working correctly. To recompile your ASL, issue the following command: [source,shell] .... # iasl your.asl .... [[ACPI-fixasl]] === Fixing Your ASL In the long run, our goal is for almost everyone to have ACPI work without any user intervention. At this point, however, we are still developing workarounds for common mistakes made by the BIOS vendors. The Microsoft(R) interpreter ([.filename]#acpi.sys# and [.filename]#acpiec.sys#) does not strictly check for adherence to the standard, and thus many BIOS vendors who only test ACPI under Windows(R) never fix their ASL. We hope to continue to identify and document exactly what non-standard behavior is allowed by Microsoft(R)'s interpreter and replicate it so FreeBSD can work without forcing users to fix the ASL. As a workaround and to help us identify behavior, you can fix the ASL manually. If this works for you, please send a man:diff[1] of the old and new ASL so we can possibly work around the buggy behavior in ACPI-CA and thus make your fix unnecessary. Here is a list of common error messages, their cause, and how to fix them: ==== _OS dependencies Some AML assumes the world consists of various Windows(R) versions. You can tell FreeBSD to claim it is any OS to see if this fixes problems you may have. An easy way to override this is to set `hw.acpi.osname="Windows 2001"` in [.filename]#/boot/loader.conf# or other similar strings you find in the ASL. ==== Missing Return statements Some methods do not explicitly return a value as the standard requires. While ACPI-CA does not handle this, FreeBSD has a workaround that allows it to return the value implicitly. You can also add explicit Return statements where required if you know what value should be returned. To force `iasl` to compile the ASL, use the `-f` flag. ==== Overriding the Default AML After you customize [.filename]#your.asl#, you will want to compile it, run: [source,shell] .... # iasl your.asl .... You can add the `-f` flag to force creation of the AML, even if there are errors during compilation. Remember that some errors (e.g., missing Return statements) are automatically worked around by the interpreter. [.filename]#DSDT.aml# is the default output filename for `iasl`. You can load this instead of your BIOS's buggy copy (which is still present in flash memory) by editing [.filename]#/boot/loader.conf# as follows: [.programlisting] .... acpi_dsdt_load="YES" acpi_dsdt_name="/boot/DSDT.aml" .... Be sure to copy your [.filename]#DSDT.aml# to the [.filename]#/boot# directory. [[ACPI-debugoutput]] === Getting Debugging Output From ACPI The ACPI driver has a very flexible debugging facility. It allows you to specify a set of subsystems as well as the level of verbosity. The subsystems you wish to debug are specified as "layers" and are broken down into ACPI-CA components (ACPI_ALL_COMPONENTS) and ACPI hardware support (ACPI_ALL_DRIVERS). The verbosity of debugging output is specified as the "level" and ranges from ACPI_LV_ERROR (just report errors) to ACPI_LV_VERBOSE (everything). The "level" is a bitmask so multiple options can be set at once, separated by spaces. In practice, you will want to use a serial console to log the output if it is so long it flushes the console message buffer. A full list of the individual layers and levels is found in the man:acpi[4] manual page. Debugging output is not enabled by default. To enable it, add `options ACPI_DEBUG` to your kernel configuration file if ACPI is compiled into the kernel. You can add `ACPI_DEBUG=1` to your [.filename]#/etc/make.conf# to enable it globally. If it is a module, you can recompile just your [.filename]#acpi.ko# module as follows: [source,shell] .... # cd /sys/modules/acpi/acpi && make clean && make ACPI_DEBUG=1 .... Install [.filename]#acpi.ko# in [.filename]#/boot/kernel# and add your desired level and layer to [.filename]#loader.conf#. This example enables debug messages for all ACPI-CA components and all ACPI hardware drivers (CPU, LID, etc.). It will only output error messages, the least verbose level. [.programlisting] .... debug.acpi.layer="ACPI_ALL_COMPONENTS ACPI_ALL_DRIVERS" debug.acpi.level="ACPI_LV_ERROR" .... If the information you want is triggered by a specific event (say, a suspend and then resume), you can leave out changes to [.filename]#loader.conf# and instead use `sysctl` to specify the layer and level after booting and preparing your system for the specific event. The ``sysctl``s are named the same as the tunables in [.filename]#loader.conf#. [[ACPI-References]] === References More information about ACPI may be found in the following locations: * The {freebsd-acpi} * The ACPI Mailing List Archives http://lists.freebsd.org/pipermail/freebsd-acpi/[http://lists.freebsd.org/pipermail/freebsd-acpi/] * The old ACPI Mailing List Archives http://home.jp.FreeBSD.org/mail-list/acpi-jp/[http://home.jp.FreeBSD.org/mail-list/acpi-jp/] -* The ACPI 2.0 Specification http://acpi.info/spec.htm[http://acpi.info/spec.htm] +* The https://uefi.org/specifications#ACPI[ACPI Specification] * FreeBSD Manual pages: man:acpi[4], man:acpi_thermal[4], man:acpidump[8], man:iasl[8], man:acpidb[8] * http://www.cpqlinux.com/acpi-howto.html#fix_broken_dsdt[DSDT debugging resource]. (Uses Compaq as an example but generally useful.) diff --git a/documentation/content/en/books/handbook/config/_index.adoc b/documentation/content/en/books/handbook/config/_index.adoc index f157c3c897..f14ca70e6d 100644 --- a/documentation/content/en/books/handbook/config/_index.adoc +++ b/documentation/content/en/books/handbook/config/_index.adoc @@ -1,1985 +1,1985 @@ --- title: Chapter 13. Configuration and Tuning part: Part III. System Administration prev: books/handbook/partiii next: books/handbook/boot description: This chapter explains much of the FreeBSD configuration process, including some of the parameters which can be set to tune a FreeBSD system. tags: ["configuration", "tuning", "services", "cron", "virtual hosts", "logging", "configuration files", "sysctl", "tuning disks", "kernel limits", "swap", "power management"] showBookMenu: true weight: 17 path: "/books/handbook/" --- [[config-tuning]] = Configuration and Tuning :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 13 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/config/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[config-synopsis]] == Synopsis One of the important aspects of FreeBSD is proper system configuration. This chapter explains much of the FreeBSD configuration process, including some of the parameters which can be set to tune a FreeBSD system. After reading this chapter, you will know: * The basics of [.filename]#rc.conf# configuration and [.filename]#/usr/local/etc/rc.d# startup scripts. * How to configure and test a network card. * How to configure virtual hosts on network devices. * How to use the various configuration files in [.filename]#/etc#. * How to tune FreeBSD using man:sysctl[8] variables. * How to tune disk performance and modify kernel limitations. Before reading this chapter, you should: * Understand UNIX(R) and FreeBSD basics (crossref:basics[basics,FreeBSD Basics]). * Be familiar with the basics of kernel configuration and compilation (crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]). [[configtuning-starting-services]] == Starting Services Many users install third party software on FreeBSD from the Ports Collection and require the installed services to be started upon system initialization. Services, such as package:mail/postfix[] or package:www/apache22[] are just two of the many software packages which may be started during system initialization. This section explains the procedures available for starting third party software. In FreeBSD, most included services, such as man:cron[8], are started through the system startup scripts. === Extended Application Configuration Now that FreeBSD includes [.filename]#rc.d#, configuration of application startup is easier and provides more features. Using the key words discussed in <>, applications can be set to start after certain other services and extra flags can be passed through [.filename]#/etc/rc.conf# in place of hard coded flags in the startup script. A basic script may look similar to the following: [.programlisting] .... #!/bin/sh # # PROVIDE: utility # REQUIRE: DAEMON # KEYWORD: shutdown . /etc/rc.subr name=utility rcvar=utility_enable command="/usr/local/sbin/utility" load_rc_config $name # # DO NOT CHANGE THESE DEFAULT VALUES HERE # SET THEM IN THE /etc/rc.conf FILE # utility_enable=${utility_enable-"NO"} pidfile=${utility_pidfile-"/var/run/utility.pid"} run_rc_command "$1" .... This script will ensure that the provided `utility` will be started after the `DAEMON` pseudo-service. It also provides a method for setting and tracking the process ID (PID). This application could then have the following line placed in [.filename]#/etc/rc.conf#: [.programlisting] .... utility_enable="YES" .... This method allows for easier manipulation of command line arguments, inclusion of the default functions provided in [.filename]#/etc/rc.subr#, compatibility with man:rcorder[8], and provides for easier configuration via [.filename]#rc.conf#. === Using Services to Start Services Other services can be started using man:inetd[8]. Working with man:inetd[8] and its configuration is described in depth in crossref:network-servers[network-inetd,“The inetd Super-Server”]. In some cases, it may make more sense to use man:cron[8] to start system services. This approach has a number of advantages as man:cron[8] runs these processes as the owner of the man:crontab[5]. This allows regular users to start and maintain their own applications. The `@reboot` feature of man:cron[8], may be used in place of the time specification. This causes the job to run when man:cron[8] is started, normally during system initialization. [[configtuning-cron]] == Configuring man:cron[8] One of the most useful utilities in FreeBSD is cron. This utility runs in the background and regularly checks [.filename]#/etc/crontab# for tasks to execute and searches [.filename]#/var/cron/tabs# for custom crontab files. These files are used to schedule tasks which cron runs at the specified times. Each entry in a crontab defines a task to run and is known as a _cron job_. Two different types of configuration files are used: the system crontab, which should not be modified, and user crontabs, which can be created and edited as needed. The format used by these files is documented in man:crontab[5]. The format of the system crontab, [.filename]#/etc/crontab# includes a `who` column which does not exist in user crontabs. In the system crontab, cron runs the command as the user specified in this column. In a user crontab, all commands run as the user who created the crontab. User crontabs allow individual users to schedule their own tasks. The `root` user can also have a user [.filename]#crontab# which can be used to schedule tasks that do not exist in the system [.filename]#crontab#. Here is a sample entry from the system crontab, [.filename]#/etc/crontab#: [.programlisting] .... # /etc/crontab - root's crontab for FreeBSD # # $FreeBSD$ # <.> SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin <.> # #minute hour mday month wday who command <.> # */5 * * * * root /usr/libexec/atrun <.> .... <.> Lines that begin with the `+#+` character are comments. A comment can be placed in the file as a reminder of what and why a desired action is performed. Comments cannot be on the same line as a command or else they will be interpreted as part of the command; they must be on a new line. Blank lines are ignored. <.> The equals (`=`) character is used to define any environment settings. In this example, it is used to define the `SHELL` and `PATH`. If the `SHELL` is omitted, cron will use the default Bourne shell. If the `PATH` is omitted, the full path must be given to the command or script to run. <.> This line defines the seven fields used in a system crontab: `minute`, `hour`, `mday`, `month`, `wday`, `who`, and `command`. The `minute` field is the time in minutes when the specified command will be run, the `hour` is the hour when the specified command will be run, the `mday` is the day of the month, `month` is the month, and `wday` is the day of the week. These fields must be numeric values, representing the twenty-four hour clock, or a `*`, representing all values for that field. The `who` field only exists in the system crontab and specifies which user the command should be run as. The last field is the command to be executed. <.> This entry defines the values for this cron job. The `\*/5`, followed by several more `*` characters, specifies that `/usr/libexec/atrun` is invoked by `root` every five minutes of every hour, of every day and day of the week, of every month.Commands can include any number of switches. However, commands which extend to multiple lines need to be broken with the backslash "\" continuation character. [[configtuning-installcrontab]] === Creating a User Crontab To create a user crontab, invoke `crontab` in editor mode: [source,shell] .... % crontab -e .... This will open the user's crontab using the default text editor. The first time a user runs this command, it will open an empty file. Once a user creates a crontab, this command will open that file for editing. It is useful to add these lines to the top of the crontab file in order to set the environment variables and to remember the meanings of the fields in the crontab: [.programlisting] .... SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin # Order of crontab fields # minute hour mday month wday command .... Then add a line for each command or script to run, specifying the time to run the command. This example runs the specified custom Bourne shell script every day at two in the afternoon. Since the path to the script is not specified in `PATH`, the full path to the script is given: [.programlisting] .... 0 14 * * * /usr/home/dru/bin/mycustomscript.sh .... [TIP] ==== Before using a custom script, make sure it is executable and test it with the limited set of environment variables set by cron. To replicate the environment that would be used to run the above cron entry, use: [.programlisting] .... env -i SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin HOME=/home/dru LOGNAME=dru /usr/home/dru/bin/mycustomscript.sh .... The environment set by cron is discussed in man:crontab[5]. Checking that scripts operate correctly in a cron environment is especially important if they include any commands that delete files using wildcards. ==== When finished editing the crontab, save the file. It will automatically be installed and cron will read the crontab and run its cron jobs at their specified times. To list the cron jobs in a crontab, use this command: [source,shell] .... % crontab -l 0 14 * * * /usr/home/dru/bin/mycustomscript.sh .... To remove all of the cron jobs in a user crontab: [source,shell] .... % crontab -r remove crontab for dru? y .... [[configtuning-rcd]] == Managing Services in FreeBSD FreeBSD uses the man:rc[8] system of startup scripts during system initialization and for managing services. The scripts listed in [.filename]#/etc/rc.d# provide basic services which can be controlled with the `start`, `stop`, and `restart` options to man:service[8]. For instance, man:sshd[8] can be restarted with the following command: [source,shell] .... # service sshd restart .... This procedure can be used to start services on a running system. Services will be started automatically at boot time as specified in man:rc.conf[5]. For example, to enable man:natd[8] at system startup, add the following line to [.filename]#/etc/rc.conf#: [.programlisting] .... natd_enable="YES" .... If a `natd_enable="NO"` line is already present, change the `NO` to `YES`. The man:rc[8] scripts will automatically load any dependent services during the next boot, as described below. Since the man:rc[8] system is primarily intended to start and stop services at system startup and shutdown time, the `start`, `stop` and `restart` options will only perform their action if the appropriate [.filename]#/etc/rc.conf# variable is set. For instance, `sshd restart` will only work if `sshd_enable` is set to `YES` in [.filename]#/etc/rc.conf#. To `start`, `stop` or `restart` a service regardless of the settings in [.filename]#/etc/rc.conf#, these commands should be prefixed with "one". For instance, to restart man:sshd[8] regardless of the current [.filename]#/etc/rc.conf# setting, execute the following command: [source,shell] .... # service sshd onerestart .... To check if a service is enabled in [.filename]#/etc/rc.conf#, run the appropriate man:rc[8] script with `rcvar`. This example checks to see if man:sshd[8] is enabled in [.filename]#/etc/rc.conf#: [source,shell] .... # service sshd rcvar # sshd # sshd_enable="YES" # (default: "") .... [NOTE] ==== The `# sshd` line is output from the above command, not a `root` console. ==== To determine whether or not a service is running, use `status`. For instance, to verify that man:sshd[8] is running: [source,shell] .... # service sshd status sshd is running as pid 433. .... In some cases, it is also possible to `reload` a service. This attempts to send a signal to an individual service, forcing the service to reload its configuration files. In most cases, this means sending the service a `SIGHUP` signal. Support for this feature is not included for every service. The man:rc[8] system is used for network services and it also contributes to most of the system initialization. For instance, when the [.filename]#/etc/rc.d/bgfsck# script is executed, it prints out the following message: [source,shell] .... Starting background file system checks in 60 seconds. .... This script is used for background file system checks, which occur only during system initialization. Many system services depend on other services to function properly. For example, man:yp[8] and other RPC-based services may fail to start until after the man:rpcbind[8] service has started. To resolve this issue, information about dependencies and other meta-data is included in the comments at the top of each startup script. The man:rcorder[8] program is used to parse these comments during system initialization to determine the order in which system services should be invoked to satisfy the dependencies. The following key word must be included in all startup scripts as it is required by man:rc.subr[8] to "enable" the startup script: * `PROVIDE`: Specifies the services this file provides. The following key words may be included at the top of each startup script. They are not strictly necessary, but are useful as hints to man:rcorder[8]: * `REQUIRE`: Lists services which are required for this service. The script containing this key word will run _after_ the specified services. * `BEFORE`: Lists services which depend on this service. The script containing this key word will run _before_ the specified services. By carefully setting these keywords for each startup script, an administrator has a fine-grained level of control of the startup order of the scripts, without the need for "runlevels" used by some UNIX(R) operating systems. Additional information can be found in man:rc[8] and man:rc.subr[8]. Refer to extref:{rc-scripting}[this article] for instructions on how to create custom man:rc[8] scripts. [[configtuning-core-configuration]] === Managing System-Specific Configuration The principal location for system configuration information is [.filename]#/etc/rc.conf#. This file contains a wide range of configuration information and it is read at system startup to configure the system. It provides the configuration information for the [.filename]#rc*# files. The entries in [.filename]#/etc/rc.conf# override the default settings in [.filename]#/etc/defaults/rc.conf#. The file containing the default settings should not be edited. Instead, all system-specific changes should be made to [.filename]#/etc/rc.conf#. A number of strategies may be applied in clustered applications to separate site-wide configuration from system-specific configuration in order to reduce administration overhead. The recommended approach is to place system-specific configuration into [.filename]#/etc/rc.conf.local#. For example, these entries in [.filename]#/etc/rc.conf# apply to all systems: [.programlisting] .... sshd_enable="YES" keyrate="fast" defaultrouter="10.1.1.254" .... Whereas these entries in [.filename]#/etc/rc.conf.local# apply to this system only: [.programlisting] .... hostname="node1.example.org" ifconfig_fxp0="inet 10.1.1.1/8" .... Distribute [.filename]#/etc/rc.conf# to every system using an application such as rsync or puppet, while [.filename]#/etc/rc.conf.local# remains unique. Upgrading the system will not overwrite [.filename]#/etc/rc.conf#, so system configuration information will not be lost. [TIP] ==== Both [.filename]#/etc/rc.conf# and [.filename]#/etc/rc.conf.local# are parsed by man:sh[1]. This allows system operators to create complex configuration scenarios. Refer to man:rc.conf[5] for further information on this topic. ==== [[config-network-setup]] == Setting Up Network Interface Cards Adding and configuring a network interface card (NIC) is a common task for any FreeBSD administrator. === Locating the Correct Driver First, determine the model of the NIC and the chip it uses. FreeBSD supports a wide variety of NICs. Check the Hardware Compatibility List for the FreeBSD release to see if the NIC is supported. If the NIC is supported, determine the name of the FreeBSD driver for the NIC. Refer to [.filename]#/usr/src/sys/conf/NOTES# and [.filename]#/usr/src/sys/arch/conf/NOTES# for the list of NIC drivers with some information about the supported chipsets. When in doubt, read the manual page of the driver as it will provide more information about the supported hardware and any known limitations of the driver. The drivers for common NICs are already present in the [.filename]#GENERIC# kernel, meaning the NIC should be probed during boot. The system's boot messages can be viewed by typing `more /var/run/dmesg.boot` and using the spacebar to scroll through the text. In this example, two Ethernet NICs using the man:dc[4] driver are present on the system: [source,shell] .... dc0: <82c169 PNIC 10/100BaseTX> port 0xa000-0xa0ff mem 0xd3800000-0xd38 000ff irq 15 at device 11.0 on pci0 miibus0: on dc0 bmtphy0: PHY 1 on miibus0 bmtphy0: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc0: Ethernet address: 00:a0:cc:da:da:da dc0: [ITHREAD] dc1: <82c169 PNIC 10/100BaseTX> port 0x9800-0x98ff mem 0xd3000000-0xd30 000ff irq 11 at device 12.0 on pci0 miibus1: on dc1 bmtphy1: PHY 1 on miibus1 bmtphy1: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc1: Ethernet address: 00:a0:cc:da:da:db dc1: [ITHREAD] .... If the driver for the NIC is not present in [.filename]#GENERIC#, but a driver is available, the driver will need to be loaded before the NIC can be configured and used. This may be accomplished in one of two ways: * The easiest way is to load a kernel module for the NIC using man:kldload[8]. To also automatically load the driver at boot time, add the appropriate line to [.filename]#/boot/loader.conf#. Not all NIC drivers are available as modules. * Alternatively, statically compile support for the NIC into a custom kernel. Refer to [.filename]#/usr/src/sys/conf/NOTES#, [.filename]#/usr/src/sys/arch/conf/NOTES# and the manual page of the driver to determine which line to add to the custom kernel configuration file. For more information about recompiling the kernel, refer to crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]. If the NIC was detected at boot, the kernel does not need to be recompiled. [[config-network-ndis]] ==== Using Windows(R) NDIS Drivers Unfortunately, there are still many vendors that do not provide schematics for their drivers to the open source community because they regard such information as trade secrets. Consequently, the developers of FreeBSD and other operating systems are left with two choices: develop the drivers by a long and pain-staking process of reverse engineering or using the existing driver binaries available for Microsoft(R) Windows(R) platforms. FreeBSD provides "native" support for the Network Driver Interface Specification (NDIS). It includes man:ndisgen[8] which can be used to convert a Windows(R) XP driver into a format that can be used on FreeBSD. As the man:ndis[4] driver uses a Windows(R) XP binary, it only runs on i386(TM) and amd64 systems. PCI, CardBus, PCMCIA, and USB devices are supported. To use man:ndisgen[8], three things are needed: . FreeBSD kernel sources. . A Windows(R) XP driver binary with a [.filename]#.SYS# extension. . A Windows(R) XP driver configuration file with a [.filename]#.INF# extension. Download the [.filename]#.SYS# and [.filename]#.INF# files for the specific NIC. Generally, these can be found on the driver CD or at the vendor's website. The following examples use [.filename]#W32DRIVER.SYS# and [.filename]#W32DRIVER.INF#. The driver bit width must match the version of FreeBSD. For FreeBSD/i386, use a Windows(R) 32-bit driver. For FreeBSD/amd64, a Windows(R) 64-bit driver is needed. The next step is to compile the driver binary into a loadable kernel module. As `root`, use man:ndisgen[8]: [source,shell] .... # ndisgen /path/to/W32DRIVER.INF /path/to/W32DRIVER.SYS .... This command is interactive and prompts for any extra information it requires. A new kernel module will be generated in the current directory. Use man:kldload[8] to load the new module: [source,shell] .... # kldload ./W32DRIVER_SYS.ko .... In addition to the generated kernel module, the [.filename]#ndis.ko# and [.filename]#if_ndis.ko# modules must be loaded. This should happen automatically when any module that depends on man:ndis[4] is loaded. If not, load them manually, using the following commands: [source,shell] .... # kldload ndis # kldload if_ndis .... The first command loads the man:ndis[4] miniport driver wrapper and the second loads the generated NIC driver. Check man:dmesg[8] to see if there were any load errors. If all went well, the output should be similar to the following: [source,shell] .... ndis0: mem 0xf4100000-0xf4101fff irq 3 at device 8.0 on pci1 ndis0: NDIS API version: 5.0 ndis0: Ethernet address: 0a:b1:2c:d3:4e:f5 ndis0: 11b rates: 1Mbps 2Mbps 5.5Mbps 11Mbps ndis0: 11g rates: 6Mbps 9Mbps 12Mbps 18Mbps 36Mbps 48Mbps 54Mbps .... From here, [.filename]#ndis0# can be configured like any other NIC. To configure the system to load the man:ndis[4] modules at boot time, copy the generated module, [.filename]#W32DRIVER_SYS.ko#, to [.filename]#/boot/modules#. Then, add the following line to [.filename]#/boot/loader.conf#: [.programlisting] .... W32DRIVER_SYS_load="YES" .... === Configuring the Network Card Once the right driver is loaded for the NIC, the card needs to be configured. It may have been configured at installation time by man:bsdinstall[8]. To display the NIC configuration, enter the following command: [source,shell] .... % ifconfig dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da inet 192.168.1.3 netmask 0xffffff00 broadcast 192.168.1.255 media: Ethernet autoselect (100baseTX ) status: active dc1: flags=8802 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:db inet 10.0.0.1 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet 10baseT/UTP status: no carrier lo0: flags=8049 metric 0 mtu 16384 options=3 inet6 fe80::1%lo0 prefixlen 64 scopeid 0x4 inet6 ::1 prefixlen 128 inet 127.0.0.1 netmask 0xff000000 nd6 options=3 .... In this example, the following devices were displayed: * [.filename]#dc0#: The first Ethernet interface. * [.filename]#dc1#: The second Ethernet interface. * [.filename]#lo0#: The loopback device. FreeBSD uses the driver name followed by the order in which the card is detected at boot to name the NIC. For example, [.filename]#sis2# is the third NIC on the system using the man:sis[4] driver. In this example, [.filename]#dc0# is up and running. The key indicators are: . `UP` means that the card is configured and ready. . The card has an Internet (`inet`) address, `192.168.1.3`. . It has a valid subnet mask (`netmask`), where `0xffffff00` is the same as `255.255.255.0`. . It has a valid broadcast address, `192.168.1.255`. . The MAC address of the card (`ether`) is `00:a0:cc:da:da:da`. . The physical media selection is on autoselection mode (`media: Ethernet autoselect (100baseTX )`). In this example, [.filename]#dc1# is configured to run with `10baseT/UTP` media. For more information on available media types for a driver, refer to its manual page. . The status of the link (`status`) is `active`, indicating that the carrier signal is detected. For [.filename]#dc1#, the `status: no carrier` status is normal when an Ethernet cable is not plugged into the card. If the man:ifconfig[8] output had shown something similar to: [source,shell] .... dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da media: Ethernet autoselect (100baseTX ) status: active .... it would indicate the card has not been configured. The card must be configured as `root`. The NIC configuration can be performed from the command line with man:ifconfig[8] but will not persist after a reboot unless the configuration is also added to [.filename]#/etc/rc.conf#. If a DHCP server is present on the LAN, just add this line: [.programlisting] .... ifconfig_dc0="DHCP" .... Replace _dc0_ with the correct value for the system. The line added, then, follow the instructions given in <>. [NOTE] ==== If the network was configured during installation, some entries for the NIC(s) may be already present. Double check [.filename]#/etc/rc.conf# before adding any lines. ==== If there is no DHCP server, the NIC(s) must be configured manually. Add a line for each NIC present on the system, as seen in this example: [.programlisting] .... ifconfig_dc0="inet 192.168.1.3 netmask 255.255.255.0" ifconfig_dc1="inet 10.0.0.1 netmask 255.255.255.0 media 10baseT/UTP" .... Replace [.filename]#dc0# and [.filename]#dc1# and the IP address information with the correct values for the system. Refer to the man page for the driver, man:ifconfig[8], and man:rc.conf[5] for more details about the allowed options and the syntax of [.filename]#/etc/rc.conf#. If the network is not using DNS, edit [.filename]#/etc/hosts# to add the names and IP addresses of the hosts on the LAN, if they are not already there. For more information, refer to man:hosts[5] and to [.filename]#/usr/share/examples/etc/hosts#. [NOTE] ==== If there is no DHCP server and access to the Internet is needed, manually configure the default gateway and the nameserver: [source,shell] .... # sysrc defaultrouter="your_default_router" # echo 'nameserver your_DNS_server' >> /etc/resolv.conf .... ==== [[config-network-testing]] === Testing and Troubleshooting Once the necessary changes to [.filename]#/etc/rc.conf# are saved, a reboot can be used to test the network configuration and to verify that the system restarts without any configuration errors. Alternatively, apply the settings to the networking system with this command: [source,shell] .... # service netif restart .... [NOTE] ==== If a default gateway has been set in [.filename]#/etc/rc.conf#, also issue this command: [source,shell] .... # service routing restart .... ==== Once the networking system has been relaunched, test the NICs. ==== Testing the Ethernet Card To verify that an Ethernet card is configured correctly, man:ping[8] the interface itself, and then man:ping[8] another machine on the LAN: [source,shell] .... % ping -c5 192.168.1.3 PING 192.168.1.3 (192.168.1.3): 56 data bytes 64 bytes from 192.168.1.3: icmp_seq=0 ttl=64 time=0.082 ms 64 bytes from 192.168.1.3: icmp_seq=1 ttl=64 time=0.074 ms 64 bytes from 192.168.1.3: icmp_seq=2 ttl=64 time=0.076 ms 64 bytes from 192.168.1.3: icmp_seq=3 ttl=64 time=0.108 ms 64 bytes from 192.168.1.3: icmp_seq=4 ttl=64 time=0.076 ms --- 192.168.1.3 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.074/0.083/0.108/0.013 ms .... [source,shell] .... % ping -c5 192.168.1.2 PING 192.168.1.2 (192.168.1.2): 56 data bytes 64 bytes from 192.168.1.2: icmp_seq=0 ttl=64 time=0.726 ms 64 bytes from 192.168.1.2: icmp_seq=1 ttl=64 time=0.766 ms 64 bytes from 192.168.1.2: icmp_seq=2 ttl=64 time=0.700 ms 64 bytes from 192.168.1.2: icmp_seq=3 ttl=64 time=0.747 ms 64 bytes from 192.168.1.2: icmp_seq=4 ttl=64 time=0.704 ms --- 192.168.1.2 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.700/0.729/0.766/0.025 ms .... To test network resolution, use the host name instead of the IP address. If there is no DNS server on the network, [.filename]#/etc/hosts# must first be configured. To this purpose, edit [.filename]#/etc/hosts# to add the names and IP addresses of the hosts on the LAN, if they are not already there. For more information, refer to man:hosts[5] and to [.filename]#/usr/share/examples/etc/hosts#. ==== Troubleshooting When troubleshooting hardware and software configurations, check the simple things first. Is the network cable plugged in? Are the network services properly configured? Is the firewall configured correctly? Is the NIC supported by FreeBSD? Before sending a bug report, always check the Hardware Notes, update the version of FreeBSD to the latest STABLE version, check the mailing list archives, and search the Internet. If the card works, yet performance is poor, read through man:tuning[7]. Also, check the network configuration as incorrect network settings can cause slow connections. Some users experience one or two `device timeout` messages, which is normal for some cards. If they continue, or are bothersome, determine if the device is conflicting with another device. Double check the cable connections. Consider trying another card. To resolve `watchdog timeout` errors, first check the network cable. Many cards require a PCI slot which supports bus mastering. On some old motherboards, only one PCI slot allows it, usually slot 0. Check the NIC and the motherboard documentation to determine if that may be the problem. `No route to host` messages occur if the system is unable to route a packet to the destination host. This can happen if no default route is specified or if a cable is unplugged. Check the output of `netstat -rn` and make sure there is a valid route to the host. If there is not, read crossref:advanced-networking[network-routing,“Gateways and Routes”]. `ping: sendto: Permission denied` error messages are often caused by a misconfigured firewall. If a firewall is enabled on FreeBSD but no rules have been defined, the default policy is to deny all traffic, even man:ping[8]. Refer to crossref:firewalls[firewalls,Firewalls] for more information. Sometimes performance of the card is poor or below average. In these cases, try setting the media selection mode from `autoselect` to the correct media selection. While this works for most hardware, it may or may not resolve the issue. Again, check all the network settings, and refer to man:tuning[7]. [[configtuning-virtual-hosts]] == Virtual Hosts A common use of FreeBSD is virtual site hosting, where one server appears to the network as many servers. This is achieved by assigning multiple network addresses to a single interface. A given network interface has one "real" address, and may have any number of "alias" addresses. These aliases are normally added by placing alias entries in [.filename]#/etc/rc.conf#, as seen in this example: [.programlisting] .... ifconfig_fxp0_alias0="inet xxx.xxx.xxx.xxx netmask xxx.xxx.xxx.xxx" .... Alias entries must start with `alias__0__` using a sequential number such as `alias0`, `alias1`, and so on. The configuration process will stop at the first missing number. The calculation of alias netmasks is important. For a given interface, there must be one address which correctly represents the network's netmask. Any other addresses which fall within this network must have a netmask of all ``1``s, expressed as either `255.255.255.255` or `0xffffffff`. For example, consider the case where the [.filename]#fxp0# interface is connected to two networks: `10.1.1.0` with a netmask of `255.255.255.0` and `202.0.75.16` with a netmask of `255.255.255.240`. The system is to be configured to appear in the ranges `10.1.1.1` through `10.1.1.5` and `202.0.75.17` through `202.0.75.20`. Only the first address in a given network range should have a real netmask. All the rest (`10.1.1.2` through `10.1.1.5` and `202.0.75.18` through `202.0.75.20`) must be configured with a netmask of `255.255.255.255`. The following [.filename]#/etc/rc.conf# entries configure the adapter correctly for this scenario: [.programlisting] .... ifconfig_fxp0="inet 10.1.1.1 netmask 255.255.255.0" ifconfig_fxp0_alias0="inet 10.1.1.2 netmask 255.255.255.255" ifconfig_fxp0_alias1="inet 10.1.1.3 netmask 255.255.255.255" ifconfig_fxp0_alias2="inet 10.1.1.4 netmask 255.255.255.255" ifconfig_fxp0_alias3="inet 10.1.1.5 netmask 255.255.255.255" ifconfig_fxp0_alias4="inet 202.0.75.17 netmask 255.255.255.240" ifconfig_fxp0_alias5="inet 202.0.75.18 netmask 255.255.255.255" ifconfig_fxp0_alias6="inet 202.0.75.19 netmask 255.255.255.255" ifconfig_fxp0_alias7="inet 202.0.75.20 netmask 255.255.255.255" .... A simpler way to express this is with a space-separated list of IP address ranges. The first address will be given the indicated subnet mask and the additional addresses will have a subnet mask of `255.255.255.255`. [.programlisting] .... ifconfig_fxp0_aliases="inet 10.1.1.1-5/24 inet 202.0.75.17-20/28" .... [[configtuning-syslog]] == Configuring System Logging Generating and reading system logs is an important aspect of system administration. The information in system logs can be used to detect hardware and software issues as well as application and system configuration errors. This information also plays an important role in security auditing and incident response. Most system daemons and applications will generate log entries. FreeBSD provides a system logger, syslogd, to manage logging. By default, syslogd is started when the system boots. This is controlled by the variable `syslogd_enable` in [.filename]#/etc/rc.conf#. There are numerous application arguments that can be set using `syslogd_flags` in [.filename]#/etc/rc.conf#. Refer to man:syslogd[8] for more information on the available arguments. This section describes how to configure the FreeBSD system logger for both local and remote logging and how to perform log rotation and log management. === Configuring Local Logging The configuration file, [.filename]#/etc/syslog.conf#, controls what syslogd does with log entries as they are received. There are several parameters to control the handling of incoming events. The _facility_ describes which subsystem generated the message, such as the kernel or a daemon, and the _level_ describes the severity of the event that occurred. This makes it possible to configure if and where a log message is logged, depending on the facility and level. It is also possible to take action depending on the application that sent the message, and in the case of remote logging, the hostname of the machine generating the logging event. This configuration file contains one line per action, where the syntax for each line is a selector field followed by an action field. The syntax of the selector field is _facility.level_ which will match log messages from _facility_ at level _level_ or higher. It is also possible to add an optional comparison flag before the level to specify more precisely what is logged. Multiple selector fields can be used for the same action, and are separated with a semicolon (`;`). Using `*` will match everything. The action field denotes where to send the log message, such as to a file or remote log host. As an example, here is the default [.filename]#syslog.conf# from FreeBSD: [.programlisting] .... # $FreeBSD$ # # Spaces ARE valid field separators in this file. However, # other *nix-like systems still insist on using tabs as field # separators. If you are sharing this file between systems, you # may want to use only tabs as field separators here. # Consult the syslog.conf(5) manpage. *.err;kern.warning;auth.notice;mail.crit /dev/console *.notice;authpriv.none;kern.debug;lpr.info;mail.crit;news.err /var/log/messages security.* /var/log/security auth.info;authpriv.info /var/log/auth.log mail.info /var/log/maillog lpr.info /var/log/lpd-errs ftp.info /var/log/xferlog cron.* /var/log/cron !-devd *.=debug /var/log/debug.log *.emerg * # uncomment this to log all writes to /dev/console to /var/log/console.log #console.info /var/log/console.log # uncomment this to enable logging of all log messages to /var/log/all.log # touch /var/log/all.log and chmod it to mode 600 before it will work #*.* /var/log/all.log # uncomment this to enable logging to a remote loghost named loghost #*.* @loghost # uncomment these if you're running inn # news.crit /var/log/news/news.crit # news.err /var/log/news/news.err # news.notice /var/log/news/news.notice # Uncomment this if you wish to see messages produced by devd # !devd # *.>=info !ppp *.* /var/log/ppp.log !* .... In this example: * Line 8 matches all messages with a level of `err` or higher, as well as `kern.warning`, `auth.notice` and `mail.crit`, and sends these log messages to the console ([.filename]#/dev/console#). * Line 12 matches all messages from the `mail` facility at level `info` or above and logs the messages to [.filename]#/var/log/maillog#. * Line 17 uses a comparison flag (`=`) to only match messages at level `debug` and logs them to [.filename]#/var/log/debug.log#. * Line 33 is an example usage of a program specification. This makes the rules following it only valid for the specified program. In this case, only the messages generated by ppp are logged to [.filename]#/var/log/ppp.log#. The available levels, in order from most to least critical are `emerg`, `alert`, `crit`, `err`, `warning`, `notice`, `info`, and `debug`. The facilities, in no particular order, are `auth`, `authpriv`, `console`, `cron`, `daemon`, `ftp`, `kern`, `lpr`, `mail`, `mark`, `news`, `security`, `syslog`, `user`, `uucp`, and `local0` through `local7`. Be aware that other operating systems might have different facilities. To log everything of level `notice` and higher to [.filename]#/var/log/daemon.log#, add the following entry: [.programlisting] .... daemon.notice /var/log/daemon.log .... For more information about the different levels and facilities, refer to man:syslog[3] and man:syslogd[8]. For more information about [.filename]#/etc/syslog.conf#, its syntax, and more advanced usage examples, see man:syslog.conf[5]. === Log Management and Rotation Log files can grow quickly, taking up disk space and making it more difficult to locate useful information. Log management attempts to mitigate this. In FreeBSD, newsyslog is used to manage log files. This built-in program periodically rotates and compresses log files, and optionally creates missing log files and signals programs when log files are moved. The log files may be generated by syslogd or by any other program which generates log files. While newsyslog is normally run from man:cron[8], it is not a system daemon. In the default configuration, it runs every hour. To know which actions to take, newsyslog reads its configuration file, [.filename]#/etc/newsyslog.conf#. This file contains one line for each log file that newsyslog manages. Each line states the file owner, permissions, when to rotate that file, optional flags that affect log rotation, such as compression, and programs to signal when the log is rotated. Here is the default configuration in FreeBSD: [.programlisting] .... # configuration file for newsyslog # $FreeBSD$ # # Entries which do not specify the '/pid_file' field will cause the # syslogd process to be signalled when that log file is rotated. This # action is only appropriate for log files which are written to by the # syslogd process (ie, files listed in /etc/syslog.conf). If there # is no process which needs to be signalled when a given log file is # rotated, then the entry for that file should include the 'N' flag. # # The 'flags' field is one or more of the letters: BCDGJNUXZ or a '-'. # # Note: some sites will want to select more restrictive protections than the # defaults. In particular, it may be desirable to switch many of the 644 # entries to 640 or 600. For example, some sites will consider the # contents of maillog, messages, and lpd-errs to be confidential. In the # future, these defaults may change to more conservative ones. # # logfilename [owner:group] mode count size when flags [/pid_file] [sig_num] /var/log/all.log 600 7 * @T00 J /var/log/amd.log 644 7 100 * J /var/log/auth.log 600 7 100 @0101T JC /var/log/console.log 600 5 100 * J /var/log/cron 600 3 100 * JC /var/log/daily.log 640 7 * @T00 JN /var/log/debug.log 600 7 100 * JC /var/log/kerberos.log 600 7 100 * J /var/log/lpd-errs 644 7 100 * JC /var/log/maillog 640 7 * @T00 JC /var/log/messages 644 5 100 @0101T JC /var/log/monthly.log 640 12 * $M1D0 JN /var/log/pflog 600 3 100 * JB /var/run/pflogd.pid /var/log/ppp.log root:network 640 3 100 * JC /var/log/devd.log 644 3 100 * JC /var/log/security 600 10 100 * JC /var/log/sendmail.st 640 10 * 168 B /var/log/utx.log 644 3 * @01T05 B /var/log/weekly.log 640 5 1 $W6D0 JN /var/log/xferlog 600 7 100 * JC .... Each line starts with the name of the log to be rotated, optionally followed by an owner and group for both rotated and newly created files. The `mode` field sets the permissions on the log file and `count` denotes how many rotated log files should be kept. The `size` and `when` fields tell newsyslog when to rotate the file. A log file is rotated when either its size is larger than the `size` field or when the time in the `when` field has passed. An asterisk (`*`) means that this field is ignored. The _flags_ field gives further instructions, such as how to compress the rotated file or to create the log file if it is missing. The last two fields are optional and specify the name of the Process ID (PID) file of a process and a signal number to send to that process when the file is rotated. For more information on all fields, valid flags, and how to specify the rotation time, refer to man:newsyslog.conf[5]. Since newsyslog is run from man:cron[8], it cannot rotate files more often than it is scheduled to run from man:cron[8]. [[network-syslogd]] === Configuring Remote Logging Monitoring the log files of multiple hosts can become unwieldy as the number of systems increases. Configuring centralized logging can reduce some of the administrative burden of log file administration. In FreeBSD, centralized log file aggregation, merging, and rotation can be configured using syslogd and newsyslog. This section demonstrates an example configuration, where host `A`, named `logserv.example.com`, will collect logging information for the local network. Host `B`, named `logclient.example.com`, will be configured to pass logging information to the logging server. ==== Log Server Configuration A log server is a system that has been configured to accept logging information from other hosts. Before configuring a log server, check the following: * If there is a firewall between the logging server and any logging clients, ensure that the firewall ruleset allows UDP port 514 for both the clients and the server. * The logging server and all client machines must have forward and reverse entries in the local DNS. If the network does not have a DNS server, create entries in each system's [.filename]#/etc/hosts#. Proper name resolution is required so that log entries are not rejected by the logging server. On the log server, edit [.filename]#/etc/syslog.conf# to specify the name of the client to receive log entries from, the logging facility to be used, and the name of the log to store the host's log entries. This example adds the hostname of `B`, logs all facilities, and stores the log entries in [.filename]#/var/log/logclient.log#. .Sample Log Server Configuration [example] ==== [.programlisting] .... +logclient.example.com *.* /var/log/logclient.log .... ==== When adding multiple log clients, add a similar two-line entry for each client. More information about the available facilities may be found in man:syslog.conf[5]. Next, configure [.filename]#/etc/rc.conf#: [.programlisting] .... syslogd_enable="YES" syslogd_flags="-a logclient.example.com -v -v" .... The first entry starts syslogd at system boot. The second entry allows log entries from the specified client. The `-v -v` increases the verbosity of logged messages. This is useful for tweaking facilities as administrators are able to see what type of messages are being logged under each facility. Multiple `-a` options may be specified to allow logging from multiple clients. IP addresses and whole netblocks may also be specified. Refer to man:syslogd[8] for a full list of possible options. Finally, create the log file: [source,shell] .... # touch /var/log/logclient.log .... At this point, syslogd should be restarted and verified: [source,shell] .... # service syslogd restart # pgrep syslog .... If a PID is returned, the server restarted successfully, and client configuration can begin. If the server did not restart, consult [.filename]#/var/log/messages# for the error. ==== Log Client Configuration A logging client sends log entries to a logging server on the network. The client also keeps a local copy of its own logs. Once a logging server has been configured, edit [.filename]#/etc/rc.conf# on the logging client: [.programlisting] .... syslogd_enable="YES" syslogd_flags="-s -v -v" .... The first entry enables syslogd on boot up. The second entry prevents logs from being accepted by this client from other hosts (`-s`) and increases the verbosity of logged messages. Next, define the logging server in the client's [.filename]#/etc/syslog.conf#. In this example, all logged facilities are sent to a remote system, denoted by the `@` symbol, with the specified hostname: [.programlisting] .... *.* @logserv.example.com .... After saving the edit, restart syslogd for the changes to take effect: [source,shell] .... # service syslogd restart .... To test that log messages are being sent across the network, use man:logger[1] on the client to send a message to syslogd: [source,shell] .... # logger "Test message from logclient" .... This message should now exist both in [.filename]#/var/log/messages# on the client and [.filename]#/var/log/logclient.log# on the log server. ==== Debugging Log Servers If no messages are being received on the log server, the cause is most likely a network connectivity issue, a hostname resolution issue, or a typo in a configuration file. To isolate the cause, ensure that both the logging server and the logging client are able to `ping` each other using the hostname specified in their [.filename]#/etc/rc.conf#. If this fails, check the network cabling, the firewall ruleset, and the hostname entries in the DNS server or [.filename]#/etc/hosts# on both the logging server and clients. Repeat until the `ping` is successful from both hosts. If the `ping` succeeds on both hosts but log messages are still not being received, temporarily increase logging verbosity to narrow down the configuration issue. In the following example, [.filename]#/var/log/logclient.log# on the logging server is empty and [.filename]#/var/log/messages# on the logging client does not indicate a reason for the failure. To increase debugging output, edit the `syslogd_flags` entry on the logging server and issue a restart: [.programlisting] .... syslogd_flags="-d -a logclient.example.com -v -v" .... [source,shell] .... # service syslogd restart .... Debugging data similar to the following will flash on the console immediately after the restart: [source,shell] .... logmsg: pri 56, flags 4, from logserv.example.com, msg syslogd: restart syslogd: restarted logmsg: pri 6, flags 4, from logserv.example.com, msg syslogd: kernel boot file is /boot/kernel/kernel Logging to FILE /var/log/messages syslogd: kernel boot file is /boot/kernel/kernel cvthname(192.168.1.10) validate: dgram from IP 192.168.1.10, port 514, name logclient.example.com; rejected in rule 0 due to name mismatch. .... In this example, the log messages are being rejected due to a typo which results in a hostname mismatch. The client's hostname should be `logclient`, not `logclien`. Fix the typo, issue a restart, and verify the results: [source,shell] .... # service syslogd restart logmsg: pri 56, flags 4, from logserv.example.com, msg syslogd: restart syslogd: restarted logmsg: pri 6, flags 4, from logserv.example.com, msg syslogd: kernel boot file is /boot/kernel/kernel syslogd: kernel boot file is /boot/kernel/kernel logmsg: pri 166, flags 17, from logserv.example.com, msg Dec 10 20:55:02 logserv.example.com syslogd: exiting on signal 2 cvthname(192.168.1.10) validate: dgram from IP 192.168.1.10, port 514, name logclient.example.com; accepted in rule 0. logmsg: pri 15, flags 0, from logclient.example.com, msg Dec 11 02:01:28 trhodes: Test message 2 Logging to FILE /var/log/logclient.log Logging to FILE /var/log/messages .... At this point, the messages are being properly received and placed in the correct file. ==== Security Considerations As with any network service, security requirements should be considered before implementing a logging server. Log files may contain sensitive data about services enabled on the local host, user accounts, and configuration data. Network data sent from the client to the server will not be encrypted or password protected. If a need for encryption exists, consider using package:security/stunnel[], which will transmit the logging data over an encrypted tunnel. Local security is also an issue. Log files are not encrypted during use or after log rotation. Local users may access log files to gain additional insight into system configuration. Setting proper permissions on log files is critical. The built-in log rotator, newsyslog, supports setting permissions on newly created and rotated log files. Setting log files to mode `600` should prevent unwanted access by local users. Refer to man:newsyslog.conf[5] for additional information. [[configtuning-configfiles]] == Configuration Files === [.filename]#/etc# Layout There are a number of directories in which configuration information is kept. These include: [.informaltable] [cols="1,1", frame="none"] |=== |[.filename]#/etc# |Generic system-specific configuration information. |[.filename]#/etc/defaults# |Default versions of system configuration files. |[.filename]#/etc/mail# |Extra man:sendmail[8] configuration and other MTA configuration files. |[.filename]#/etc/ppp# |Configuration for both user- and kernel-ppp programs. |[.filename]#/usr/local/etc# |Configuration files for installed applications. May contain per-application subdirectories. |[.filename]#/usr/local/etc/rc.d# |man:rc[8] scripts for installed applications. |[.filename]#/var/db# |Automatically generated system-specific database files, such as the package database and the man:locate[1] database. |=== === Hostnames ==== [.filename]#/etc/resolv.conf# How a FreeBSD system accesses the Internet Domain Name System (DNS) is controlled by man:resolv.conf[5]. The most common entries to [.filename]#/etc/resolv.conf# are: [.informaltable] [cols="1,1", frame="none"] |=== |`nameserver` |The IP address of a name server the resolver should query. The servers are queried in the order listed with a maximum of three. |`search` |Search list for hostname lookup. This is normally determined by the domain of the local hostname. |`domain` |The local domain name. |=== A typical [.filename]#/etc/resolv.conf# looks like this: [.programlisting] .... search example.com nameserver 147.11.1.11 nameserver 147.11.100.30 .... [NOTE] ==== Only one of the `search` and `domain` options should be used. ==== When using DHCP, man:dhclient[8] usually rewrites [.filename]#/etc/resolv.conf# with information received from the DHCP server. ==== [.filename]#/etc/hosts# [.filename]#/etc/hosts# is a simple text database which works in conjunction with DNS and NIS to provide host name to IP address mappings. Entries for local computers connected via a LAN can be added to this file for simplistic naming purposes instead of setting up a man:named[8] server. Additionally, [.filename]#/etc/hosts# can be used to provide a local record of Internet names, reducing the need to query external DNS servers for commonly accessed names. [.programlisting] .... # $FreeBSD$ # # # Host Database # # This file should contain the addresses and aliases for local hosts that # share this file. Replace 'my.domain' below with the domainname of your # machine. # # In the presence of the domain name service or NIS, this file may # not be consulted at all; see /etc/nsswitch.conf for the resolution order. # # ::1 localhost localhost.my.domain 127.0.0.1 localhost localhost.my.domain # # Imaginary network. #10.0.0.2 myname.my.domain myname #10.0.0.3 myfriend.my.domain myfriend # # According to RFC 1918, you can use the following IP networks for # private nets which will never be connected to the Internet: # # 10.0.0.0 - 10.255.255.255 # 172.16.0.0 - 172.31.255.255 # 192.168.0.0 - 192.168.255.255 # # In case you want to be able to connect to the Internet, you need # real official assigned numbers. Do not try to invent your own network # numbers but instead get one from your network provider (if any) or # from your regional registry (ARIN, APNIC, LACNIC, RIPE NCC, or AfriNIC.) # .... The format of [.filename]#/etc/hosts# is as follows: [.programlisting] .... [Internet address] [official hostname] [alias1] [alias2] ... .... For example: [.programlisting] .... 10.0.0.1 myRealHostname.example.com myRealHostname foobar1 foobar2 .... Consult man:hosts[5] for more information. [[configtuning-sysctl]] == Tuning with man:sysctl[8] man:sysctl[8] is used to make changes to a running FreeBSD system. This includes many advanced options of the TCP/IP stack and virtual memory system that can dramatically improve performance for an experienced system administrator. Over five hundred system variables can be read and set using man:sysctl[8]. At its core, man:sysctl[8] serves two functions: to read and to modify system settings. To view all readable variables: [source,shell] .... % sysctl -a .... To read a particular variable, specify its name: [source,shell] .... % sysctl kern.maxproc kern.maxproc: 1044 .... To set a particular variable, use the _variable_=_value_ syntax: [source,shell] .... # sysctl kern.maxfiles=5000 kern.maxfiles: 2088 -> 5000 .... Settings of sysctl variables are usually either strings, numbers, or booleans, where a boolean is `1` for yes or `0` for no. To automatically set some variables each time the machine boots, add them to [.filename]#/etc/sysctl.conf#. For more information, refer to man:sysctl.conf[5] and <>. [[configtuning-sysctlconf]] === [.filename]#sysctl.conf# The configuration file for man:sysctl[8], [.filename]#/etc/sysctl.conf#, looks much like [.filename]#/etc/rc.conf#. Values are set in a `variable=value` form. The specified values are set after the system goes into multi-user mode. Not all variables are settable in this mode. For example, to turn off logging of fatal signal exits and prevent users from seeing processes started by other users, the following tunables can be set in [.filename]#/etc/sysctl.conf#: [.programlisting] .... # Do not log fatal signal exits (e.g., sig 11) kern.logsigexit=0 # Prevent users from seeing information about processes that # are being run under another UID. security.bsd.see_other_uids=0 .... [[sysctl-readonly]] === man:sysctl[8] Read-only In some cases it may be desirable to modify read-only man:sysctl[8] values, which will require a reboot of the system. For instance, on some laptop models the man:cardbus[4] device will not probe memory ranges and will fail with errors similar to: [source,shell] .... cbb0: Could not map register memory device_probe_and_attach: cbb0 attach returned 12 .... The fix requires the modification of a read-only man:sysctl[8] setting. Add `hw.pci.allow_unsupported_io_range=1` to [.filename]#/boot/loader.conf# and reboot. Now man:cardbus[4] should work properly. [[configtuning-disk]] == Tuning Disks The following section will discuss various tuning mechanisms and options which may be applied to disk devices. In many cases, disks with mechanical parts, such as SCSI drives, will be the bottleneck driving down the overall system performance. While a solution is to install a drive without mechanical parts, such as a solid state drive, mechanical drives are not going away anytime in the near future. When tuning disks, it is advisable to utilize the features of the man:iostat[8] command to test various changes to the system. This command will allow the user to obtain valuable information on system IO. === Sysctl Variables ==== `vfs.vmiodirenable` The `vfs.vmiodirenable` man:sysctl[8] variable may be set to either `0` (off) or `1` (on). It is set to `1` by default. This variable controls how directories are cached by the system. Most directories are small, using just a single fragment (typically 1 K) in the file system and typically 512 bytes in the buffer cache. With this variable turned off, the buffer cache will only cache a fixed number of directories, even if the system has a huge amount of memory. When turned on, this man:sysctl[8] allows the buffer cache to use the VM page cache to cache the directories, making all the memory available for caching directories. However, the minimum in-core memory used to cache a directory is the physical page size (typically 4 K) rather than 512 bytes. Keeping this option enabled is recommended if the system is running any services which manipulate large numbers of files. Such services can include web caches, large mail systems, and news systems. Keeping this option on will generally not reduce performance, even with the wasted memory, but one should experiment to find out. ==== `vfs.write_behind` The `vfs.write_behind` man:sysctl[8] variable defaults to `1` (on). This tells the file system to issue media writes as full clusters are collected, which typically occurs when writing large sequential files. This avoids saturating the buffer cache with dirty buffers when it would not benefit I/O performance. However, this may stall processes and under certain circumstances should be turned off. ==== `vfs.hirunningspace` The `vfs.hirunningspace` man:sysctl[8] variable determines how much outstanding write I/O may be queued to disk controllers system-wide at any given instance. The default is usually sufficient, but on machines with many disks, try bumping it up to four or five _megabytes_. Setting too high a value which exceeds the buffer cache's write threshold can lead to bad clustering performance. Do not set this value arbitrarily high as higher write values may add latency to reads occurring at the same time. There are various other buffer cache and VM page cache related man:sysctl[8] values. Modifying these values is not recommended as the VM system does a good job of automatically tuning itself. ==== `vm.swap_idle_enabled` The `vm.swap_idle_enabled` man:sysctl[8] variable is useful in large multi-user systems with many active login users and lots of idle processes. Such systems tend to generate continuous pressure on free memory reserves. Turning this feature on and tweaking the swapout hysteresis (in idle seconds) via `vm.swap_idle_threshold1` and `vm.swap_idle_threshold2` depresses the priority of memory pages associated with idle processes more quickly then the normal pageout algorithm. This gives a helping hand to the pageout daemon. Only turn this option on if needed, because the tradeoff is essentially pre-page memory sooner rather than later which eats more swap and disk bandwidth. In a small system this option will have a determinable effect, but in a large system that is already doing moderate paging, this option allows the VM system to stage whole processes into and out of memory easily. ==== `hw.ata.wc` Turning off IDE write caching reduces write bandwidth to IDE disks, but may sometimes be necessary due to data consistency issues introduced by hard drive vendors. The problem is that some IDE drives lie about when a write completes. With IDE write caching turned on, IDE hard drives write data to disk out of order and will sometimes delay writing some blocks indefinitely when under heavy disk load. A crash or power failure may cause serious file system corruption. Check the default on the system by observing the `hw.ata.wc` man:sysctl[8] variable. If IDE write caching is turned off, one can set this read-only variable to `1` in [.filename]#/boot/loader.conf# in order to enable it at boot time. For more information, refer to man:ata[4]. ==== `SCSI_DELAY` (`kern.cam.scsi_delay`) The `SCSI_DELAY` kernel configuration option may be used to reduce system boot times. The defaults are fairly high and can be responsible for `15` seconds of delay in the boot process. Reducing it to `5` seconds usually works with modern drives. The `kern.cam.scsi_delay` boot time tunable should be used. The tunable and kernel configuration option accept values in terms of _milliseconds_ and _not seconds_. [[soft-updates]] === Soft Updates To fine-tune a file system, use man:tunefs[8]. This program has many different options. To toggle Soft Updates on and off, use: [source,shell] .... # tunefs -n enable /filesystem # tunefs -n disable /filesystem .... A file system cannot be modified with man:tunefs[8] while it is mounted. A good time to enable Soft Updates is before any partitions have been mounted, in single-user mode. Soft Updates is recommended for UFS file systems as it drastically improves meta-data performance, mainly file creation and deletion, through the use of a memory cache. There are two downsides to Soft Updates to be aware of. First, Soft Updates guarantee file system consistency in the case of a crash, but could easily be several seconds or even a minute behind updating the physical disk. If the system crashes, unwritten data may be lost. Secondly, Soft Updates delay the freeing of file system blocks. If the root file system is almost full, performing a major update, such as `make installworld`, can cause the file system to run out of space and the update to fail. ==== More Details About Soft Updates Meta-data updates are updates to non-content data like inodes or directories. There are two traditional approaches to writing a file system's meta-data back to disk. Historically, the default behavior was to write out meta-data updates synchronously. If a directory changed, the system waited until the change was actually written to disk. The file data buffers (file contents) were passed through the buffer cache and backed up to disk later on asynchronously. The advantage of this implementation is that it operates safely. If there is a failure during an update, meta-data is always in a consistent state. A file is either created completely or not at all. If the data blocks of a file did not find their way out of the buffer cache onto the disk by the time of the crash, man:fsck[8] recognizes this and repairs the file system by setting the file length to `0`. Additionally, the implementation is clear and simple. The disadvantage is that meta-data changes are slow. For example, `rm -r` touches all the files in a directory sequentially, but each directory change will be written synchronously to the disk. This includes updates to the directory itself, to the inode table, and possibly to indirect blocks allocated by the file. Similar considerations apply for unrolling large hierarchies using `tar -x`. The second approach is to use asynchronous meta-data updates. This is the default for a UFS file system mounted with `mount -o async`. Since all meta-data updates are also passed through the buffer cache, they will be intermixed with the updates of the file content data. The advantage of this implementation is there is no need to wait until each meta-data update has been written to disk, so all operations which cause huge amounts of meta-data updates work much faster than in the synchronous case. This implementation is still clear and simple, so there is a low risk for bugs creeping into the code. The disadvantage is that there is no guarantee for a consistent state of the file system If there is a failure during an operation that updated large amounts of meta-data, like a power failure or someone pressing the reset button, the file system will be left in an unpredictable state. There is no opportunity to examine the state of the file system when the system comes up again as the data blocks of a file could already have been written to the disk while the updates of the inode table or the associated directory were not. It is impossible to implement a man:fsck[8] which is able to clean up the resulting chaos because the necessary information is not available on the disk. If the file system has been damaged beyond repair, the only choice is to reformat it and restore from backup. The usual solution for this problem is to implement _dirty region logging_, which is also referred to as _journaling_. Meta-data updates are still written synchronously, but only into a small region of the disk. Later on, they are moved to their proper location. Since the logging area is a small, contiguous region on the disk, there are no long distances for the disk heads to move, even during heavy operations, so these operations are quicker than synchronous updates. Additionally, the complexity of the implementation is limited, so the risk of bugs being present is low. A disadvantage is that all meta-data is written twice, once into the logging region and once to the proper location, so performance "pessimization" might result. On the other hand, in case of a crash, all pending meta-data operations can be either quickly rolled back or completed from the logging area after the system comes up again, resulting in a fast file system startup. Kirk McKusick, the developer of Berkeley FFS, solved this problem with Soft Updates. All pending meta-data updates are kept in memory and written out to disk in a sorted sequence ("ordered meta-data updates"). This has the effect that, in case of heavy meta-data operations, later updates to an item "catch" the earlier ones which are still in memory and have not already been written to disk. All operations are generally performed in memory before the update is written to disk and the data blocks are sorted according to their position so that they will not be on the disk ahead of their meta-data. If the system crashes, an implicit "log rewind" causes all operations which were not written to the disk appear as if they never happened. A consistent file system state is maintained that appears to be the one of 30 to 60 seconds earlier. The algorithm used guarantees that all resources in use are marked as such in their blocks and inodes. After a crash, the only resource allocation error that occurs is that resources are marked as "used" which are actually "free". man:fsck[8] recognizes this situation, and frees the resources that are no longer used. It is safe to ignore the dirty state of the file system after a crash by forcibly mounting it with `mount -f`. In order to free resources that may be unused, man:fsck[8] needs to be run at a later time. This is the idea behind the _background man:fsck[8]_: at system startup time, only a _snapshot_ of the file system is recorded and man:fsck[8] is run afterwards. All file systems can then be mounted "dirty", so the system startup proceeds in multi-user mode. Then, background man:fsck[8] is scheduled for all file systems where this is required, to free resources that may be unused. File systems that do not use Soft Updates still need the usual foreground man:fsck[8]. The advantage is that meta-data operations are nearly as fast as asynchronous updates and are faster than _logging_, which has to write the meta-data twice. The disadvantages are the complexity of the code, a higher memory consumption, and some idiosyncrasies. After a crash, the state of the file system appears to be somewhat "older". In situations where the standard synchronous approach would have caused some zero-length files to remain after the man:fsck[8], these files do not exist at all with Soft Updates because neither the meta-data nor the file contents have been written to disk. Disk space is not released until the updates have been written to disk, which may take place some time after running man:rm[1]. This may cause problems when installing large amounts of data on a file system that does not have enough free space to hold all the files twice. [[configtuning-kernel-limits]] == Tuning Kernel Limits [[file-process-limits]] === File/Process Limits [[kern-maxfiles]] ==== `kern.maxfiles` The `kern.maxfiles` man:sysctl[8] variable can be raised or lowered based upon system requirements. This variable indicates the maximum number of file descriptors on the system. When the file descriptor table is full, `file: table is full` will show up repeatedly in the system message buffer, which can be viewed using man:dmesg[8]. Each open file, socket, or fifo uses one file descriptor. A large-scale production server may easily require many thousands of file descriptors, depending on the kind and number of services running concurrently. In older FreeBSD releases, the default value of `kern.maxfiles` is derived from `maxusers` in the kernel configuration file. `kern.maxfiles` grows proportionally to the value of `maxusers`. When compiling a custom kernel, consider setting this kernel configuration option according to the use of the system. From this number, the kernel is given most of its pre-defined limits. Even though a production machine may not have 256 concurrent users, the resources needed may be similar to a high-scale web server. The read-only man:sysctl[8] variable `kern.maxusers` is automatically sized at boot based on the amount of memory available in the system, and may be determined at run-time by inspecting the value of `kern.maxusers`. Some systems require larger or smaller values of `kern.maxusers` and values of `64`, `128`, and `256` are not uncommon. Going above `256` is not recommended unless a huge number of file descriptors is needed. Many of the tunable values set to their defaults by `kern.maxusers` may be individually overridden at boot-time or run-time in [.filename]#/boot/loader.conf#. Refer to man:loader.conf[5] and [.filename]#/boot/defaults/loader.conf# for more details and some hints. In older releases, the system will auto-tune `maxusers` if it is set to `0`. footnote:[The auto-tuning algorithm sets maxusers equal to the amount of memory in the system, with a minimum of 32, and a maximum of 384.]. When setting this option, set `maxusers` to at least `4`, especially if the system runs Xorg or is used to compile software. The most important table set by `maxusers` is the maximum number of processes, which is set to `20 + 16 * maxusers`. If `maxusers` is set to `1`, there can only be `36` simultaneous processes, including the `18` or so that the system starts up at boot time and the `15` or so used by Xorg. Even a simple task like reading a manual page will start up nine processes to filter, decompress, and view it. Setting `maxusers` to `64` allows up to `1044` simultaneous processes, which should be enough for nearly all uses. If, however, the error is displayed when trying to start another program, or a server is running with a large number of simultaneous users, increase the number and rebuild. [NOTE] ==== `maxusers` does _not_ limit the number of users which can log into the machine. It instead sets various table sizes to reasonable values considering the maximum number of users on the system and how many processes each user will be running. ==== ==== `kern.ipc.soacceptqueue` The `kern.ipc.soacceptqueue` man:sysctl[8] variable limits the size of the listen queue for accepting new `TCP` connections. The default value of `128` is typically too low for robust handling of new connections on a heavily loaded web server. For such environments, it is recommended to increase this value to `1024` or higher. A service such as man:sendmail[8], or Apache may itself limit the listen queue size, but will often have a directive in its configuration file to adjust the queue size. Large listen queues do a better job of avoiding Denial of Service (DoS) attacks. [[nmbclusters]] === Network Limits The `NMBCLUSTERS` kernel configuration option dictates the amount of network Mbufs available to the system. A heavily-trafficked server with a low number of Mbufs will hinder performance. Each cluster represents approximately 2 K of memory, so a value of `1024` represents `2` megabytes of kernel memory reserved for network buffers. A simple calculation can be done to figure out how many are needed. A web server which maxes out at `1000` simultaneous connections where each connection uses a 6 K receive and 16 K send buffer, requires approximately 32 MB worth of network buffers to cover the web server. A good rule of thumb is to multiply by `2`, so 2x32 MB / 2 KB = 64 MB / 2 kB = `32768`. Values between `4096` and `32768` are recommended for machines with greater amounts of memory. Never specify an arbitrarily high value for this parameter as it could lead to a boot time crash. To observe network cluster usage, use `-m` with man:netstat[1]. The `kern.ipc.nmbclusters` loader tunable should be used to tune this at boot time. Only older versions of FreeBSD will require the use of the `NMBCLUSTERS` kernel man:config[8] option. For busy servers that make extensive use of the man:sendfile[2] system call, it may be necessary to increase the number of man:sendfile[2] buffers via the `NSFBUFS` kernel configuration option or by setting its value in [.filename]#/boot/loader.conf# (see man:loader[8] for details). A common indicator that this parameter needs to be adjusted is when processes are seen in the `sfbufa` state. The man:sysctl[8] variable `kern.ipc.nsfbufs` is read-only. This parameter nominally scales with `kern.maxusers`, however it may be necessary to tune accordingly. [IMPORTANT] ==== Even though a socket has been marked as non-blocking, calling man:sendfile[2] on the non-blocking socket may result in the man:sendfile[2] call blocking until enough ``struct sf_buf``'s are made available. ==== ==== `net.inet.ip.portrange.*` The `net.inet.ip.portrange.*` man:sysctl[8] variables control the port number ranges automatically bound to `TCP` and `UDP` sockets. There are three ranges: a low range, a default range, and a high range. Most network programs use the default range which is controlled by `net.inet.ip.portrange.first` and `net.inet.ip.portrange.last`, which default to `1024` and `5000`, respectively. Bound port ranges are used for outgoing connections and it is possible to run the system out of ports under certain circumstances. This most commonly occurs when running a heavily loaded web proxy. The port range is not an issue when running a server which handles mainly incoming connections, such as a web server, or has a limited number of outgoing connections, such as a mail relay. For situations where there is a shortage of ports, it is recommended to increase `net.inet.ip.portrange.last` modestly. A value of `10000`, `20000` or `30000` may be reasonable. Consider firewall effects when changing the port range. Some firewalls may block large ranges of ports, usually low-numbered ports, and expect systems to use higher ranges of ports for outgoing connections. For this reason, it is not recommended that the value of `net.inet.ip.portrange.first` be lowered. === Virtual Memory ==== `kern.maxvnodes` A vnode is the internal representation of a file or directory. Increasing the number of vnodes available to the operating system reduces disk I/O. Normally, this is handled by the operating system and does not need to be changed. In some cases where disk I/O is a bottleneck and the system is running out of vnodes, this setting needs to be increased. The amount of inactive and free RAM will need to be taken into account. To see the current number of vnodes in use: [source,shell] .... # sysctl vfs.numvnodes vfs.numvnodes: 91349 .... To see the maximum vnodes: [source,shell] .... # sysctl kern.maxvnodes kern.maxvnodes: 100000 .... If the current vnode usage is near the maximum, try increasing `kern.maxvnodes` by a value of `1000`. Keep an eye on the number of `vfs.numvnodes`. If it climbs up to the maximum again, `kern.maxvnodes` will need to be increased further. Otherwise, a shift in memory usage as reported by man:top[1] should be visible and more memory should be active. [[adding-swap-space]] == Adding Swap Space Sometimes a system requires more swap space. This section describes two methods to increase swap space: adding swap to an existing partition or new hard drive, and creating a swap file on an existing partition. For information on how to encrypt swap space, which options exist, and why it should be done, refer to crossref:disks[swap-encrypting,“Encrypting Swap”]. [[new-drive-swap]] === Swap on a New Hard Drive or Existing Partition Adding a new hard drive for swap gives better performance than using a partition on an existing drive. Setting up partitions and hard drives is explained in crossref:disks[disks-adding,“Adding Disks”] while crossref:bsdinstall[configtuning-initial,“Designing the Partition Layout”] discusses partition layouts and swap partition size considerations. Use `swapon` to add a swap partition to the system. For example: [source,shell] .... # swapon /dev/ada1s1b .... [WARNING] ==== It is possible to use any partition not currently mounted, even if it already contains data. Using `swapon` on a partition that contains data will overwrite and destroy that data. Make sure that the partition to be added as swap is really the intended partition before running `swapon`. ==== To automatically add this swap partition on boot, add an entry to [.filename]#/etc/fstab#: [.programlisting] .... /dev/ada1s1b none swap sw 0 0 .... See man:fstab[5] for an explanation of the entries in [.filename]#/etc/fstab#. More information about `swapon` can be found in man:swapon[8]. [[create-swapfile]] === Creating a Swap File These examples create a 512M swap file called [.filename]#/usr/swap0# instead of using a partition. Using swap files requires that the module needed by man:md[4] has either been built into the kernel or has been loaded before swap is enabled. See crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel] for information about building a custom kernel. [[swapfile-10-and-later]] .Creating a Swap File [example] ==== [.procedure] . Create the swap file: + [source,shell] .... # dd if=/dev/zero of=/usr/swap0 bs=1m count=512 .... . Set the proper permissions on the new file: + [source,shell] .... # chmod 0600 /usr/swap0 .... . Inform the system about the swap file by adding a line to [.filename]#/etc/fstab#: + [.programlisting] .... md none swap sw,file=/usr/swap0,late 0 0 .... + . Swap space will be added on system startup. To add swap space immediately, use man:swapon[8]: + [source,shell] .... # swapon -aL .... ==== [[acpi-overview]] == Power and Resource Management It is important to utilize hardware resources in an efficient manner. Power and resource management allows the operating system to monitor system limits and to possibly provide an alert if the system temperature increases unexpectedly. An early specification for providing power management was the Advanced Power Management (APM) facility. APM controls the power usage of a system based on its activity. However, it was difficult and inflexible for operating systems to manage the power usage and thermal properties of a system. The hardware was managed by the BIOS and the user had limited configurability and visibility into the power management settings. The APMBIOS is supplied by the vendor and is specific to the hardware platform. An APM driver in the operating system mediates access to the APM Software Interface, which allows management of power levels. There are four major problems in APM. First, power management is done by the vendor-specific BIOS, separate from the operating system. For example, the user can set idle-time values for a hard drive in the APMBIOS so that, when exceeded, the BIOS spins down the hard drive without the consent of the operating system. Second, the APM logic is embedded in the BIOS, and it operates outside the scope of the operating system. This means that users can only fix problems in the APMBIOS by flashing a new one into the ROM, which is a dangerous procedure with the potential to leave the system in an unrecoverable state if it fails. Third, APM is a vendor-specific technology, meaning that there is a lot of duplication of efforts and bugs found in one vendor's BIOS may not be solved in others. Lastly, the APMBIOS did not have enough room to implement a sophisticated power policy or one that can adapt well to the purpose of the machine. The Plug and Play BIOS (PNPBIOS) was unreliable in many situations. PNPBIOS is 16-bit technology, so the operating system has to use 16-bit emulation in order to interface with PNPBIOS methods. FreeBSD provides an APM driver as APM should still be used for systems manufactured at or before the year 2000. The driver is documented in man:apm[4]. The successor to APM is the Advanced Configuration and Power Interface (ACPI). ACPI is a standard written by an alliance of vendors to provide an interface for hardware resources and power management. It is a key element in _Operating System-directed configuration and Power Management_ as it provides more control and flexibility to the operating system. This chapter demonstrates how to configure ACPI on FreeBSD. It then offers some tips on how to debug ACPI and how to submit a problem report containing debugging information so that developers can diagnosis and fix ACPI issues. [[acpi-config]] === Configuring ACPI In FreeBSD the man:acpi[4] driver is loaded by default at system boot and should _not_ be compiled into the kernel. This driver cannot be unloaded after boot because the system bus uses it for various hardware interactions. However, if the system is experiencing problems, ACPI can be disabled altogether by rebooting after setting `hint.acpi.0.disabled="1"` in [.filename]#/boot/loader.conf# or by setting this variable at the loader prompt, as described in crossref:boot[boot-loader,“Stage Three”]. [NOTE] ==== ACPI and APM cannot coexist and should be used separately. The last one to load will terminate if the driver notices the other is running. ==== ACPI can be used to put the system into a sleep mode with `acpiconf`, the `-s` flag, and a number from `1` to `5`. Most users only need `1` (quick suspend to RAM) or `3` (suspend to RAM). Option `5` performs a soft-off which is the same as running `halt -p`. The man:acpi_video[4] driver uses link:https://uefi.org/specs/ACPI/6.4/Apx_B_Video_Extensions/Apx_B_Video_Extensions.html[ACPI Video Extensions] to control display switching and backlight brightness. It must be loaded after any of the DRM kernel modules. After loading the driver, the kbd:[Fn] brightness keys will change the brightness of the screen. It is possible to check the ACPI events by inspecting [.filename]#/var/run/devd.pipe#: [source,shell] ... # cat /var/run/devd.pipe !system=ACPI subsystem=Video type=brightness notify=62 !system=ACPI subsystem=Video type=brightness notify=63 !system=ACPI subsystem=Video type=brightness notify=64 ... Other options are available using `sysctl`. Refer to man:acpi[4] and man:acpiconf[8] for more information. [[ACPI-comprob]] === Common Problems ACPI is present in all modern computers that conform to the ia32 (x86) and amd64 (AMD) architectures. The full standard has many features including CPU performance management, power planes control, thermal zones, various battery systems, embedded controllers, and bus enumeration. Most systems implement less than the full standard. For instance, a desktop system usually only implements bus enumeration while a laptop might have cooling and battery management support as well. Laptops also have suspend and resume, with their own associated complexity. An ACPI-compliant system has various components. The BIOS and chipset vendors provide various fixed tables, such as FADT, in memory that specify things like the APIC map (used for SMP), config registers, and simple configuration values. Additionally, a bytecode table, the Differentiated System Description Table DSDT, specifies a tree-like name space of devices and methods. The ACPI driver must parse the fixed tables, implement an interpreter for the bytecode, and modify device drivers and the kernel to accept information from the ACPI subsystem. For FreeBSD, Intel(R) has provided an interpreter (ACPI-CA) that is shared with Linux(R) and NetBSD. The path to the ACPI-CA source code is [.filename]#src/sys/contrib/dev/acpica#. The glue code that allows ACPI-CA to work on FreeBSD is in [.filename]#src/sys/dev/acpica/Osd#. Finally, drivers that implement various ACPI devices are found in [.filename]#src/sys/dev/acpica#. For ACPI to work correctly, all the parts have to work correctly. Here are some common problems, in order of frequency of appearance, and some possible workarounds or fixes. If a fix does not resolve the issue, refer to <> for instructions on how to submit a bug report. ==== Mouse Issues In some cases, resuming from a suspend operation will cause the mouse to fail. A known work around is to add `hint.psm.0.flags="0x3000"` to [.filename]#/boot/loader.conf#. ==== Suspend/Resume ACPI has three suspend to RAM (STR) states, `S1`-`S3`, and one suspend to disk state (STD), called `S4`. STD can be implemented in two separate ways. The ``S4``BIOS is a BIOS-assisted suspend to disk and ``S4``OS is implemented entirely by the operating system. The normal state the system is in when plugged in but not powered up is "soft off" (`S5`). Use `sysctl hw.acpi` to check for the suspend-related items. These example results are from a Thinkpad: [source,shell] .... hw.acpi.supported_sleep_state: S3 S4 S5 hw.acpi.s4bios: 0 .... Use `acpiconf -s` to test `S3`, `S4`, and `S5`. An `s4bios` of one (`1`) indicates ``S4``BIOS support instead of `S4` operating system support. When testing suspend/resume, start with `S1`, if supported. This state is most likely to work since it does not require much driver support. No one has implemented `S2`, which is similar to `S1`. Next, try `S3`. This is the deepest STR state and requires a lot of driver support to properly reinitialize the hardware. A common problem with suspend/resume is that many device drivers do not save, restore, or reinitialize their firmware, registers, or device memory properly. As a first attempt at debugging the problem, try: [source,shell] .... # sysctl debug.bootverbose=1 # sysctl debug.acpi.suspend_bounce=1 # acpiconf -s 3 .... This test emulates the suspend/resume cycle of all device drivers without actually going into `S3` state. In some cases, problems such as losing firmware state, device watchdog time out, and retrying forever, can be captured with this method. Note that the system will not really enter `S3` state, which means devices may not lose power, and many will work fine even if suspend/resume methods are totally missing, unlike real `S3` state. If the previous test worked, on a laptop it is possible to configure the system to suspend into `S3` on lid close and resume when it is open back again: [source,shell] .... # sysctl hw.acpi.lid_switch_state=S3 .... This change can be made persistent across reboots: [source,shell] .... # echo 'hw.acpi.lid_switch_state=S3' >> /etc/sysctl.conf .... Harder cases require additional hardware, such as a serial port and cable for debugging through a serial console, a Firewire port and cable for using man:dcons[4], and kernel debugging skills. To help isolate the problem, unload as many drivers as possible. If it works, narrow down which driver is the problem by loading drivers until it fails again. Typically, binary drivers like [.filename]#nvidia.ko#, display drivers, and USB will have the most problems while Ethernet interfaces usually work fine. If drivers can be properly loaded and unloaded, automate this by putting the appropriate commands in [.filename]#/etc/rc.suspend# and [.filename]#/etc/rc.resume#. Try setting `hw.acpi.reset_video` to `1` if the display is messed up after resume. Try setting longer or shorter values for `hw.acpi.sleep_delay` to see if that helps. Try loading a recent Linux(R) distribution to see if suspend/resume works on the same hardware. If it works on Linux(R), it is likely a FreeBSD driver problem. Narrowing down which driver causes the problem will assist developers in fixing the problem. Since the ACPI maintainers rarely maintain other drivers, such as sound or ATA, any driver problems should also be posted to the {freebsd-current} and mailed to the driver maintainer. Advanced users can include debugging man:printf[3]s in a problematic driver to track down where in its resume function it hangs. Finally, try disabling ACPI and enabling APM instead. If suspend/resume works with APM, stick with APM, especially on older hardware (pre-2000). It took vendors a while to get ACPI support correct and older hardware is more likely to have BIOS problems with ACPI. ==== System Hangs Most system hangs are a result of lost interrupts or an interrupt storm. Chipsets may have problems based on boot, how the BIOS configures interrupts before correctness of the APIC (MADT) table, and routing of the System Control Interrupt (SCI). Interrupt storms can be distinguished from lost interrupts by checking the output of `vmstat -i` and looking at the line that has `acpi0`. If the counter is increasing at more than a couple per second, there is an interrupt storm. If the system appears hung, try breaking to DDB (kbd:[CTRL+ALT+ESC] on console) and type `show interrupts`. When dealing with interrupt problems, try disabling APIC support with `hint.apic.0.disabled="1"` in [.filename]#/boot/loader.conf#. ==== Panics Panics are relatively rare for ACPI and are the top priority to be fixed. The first step is to isolate the steps to reproduce the panic, if possible, and get a backtrace. Follow the advice for enabling `options DDB` and setting up a serial console in crossref:serialcomms[serialconsole-ddb,“Entering the DDB Debugger from the Serial Line”] or setting up a dump partition. To get a backtrace in DDB, use `tr`. When handwriting the backtrace, get at least the last five and the top five lines in the trace. Then, try to isolate the problem by booting with ACPI disabled. If that works, isolate the ACPI subsystem by using various values of `debug.acpi.disable`. See man:acpi[4] for some examples. ==== System Powers Up After Suspend or Shutdown First, try setting `hw.acpi.disable_on_poweroff="0"` in [.filename]#/boot/loader.conf#. This keeps ACPI from disabling various events during the shutdown process. Some systems need this value set to `1` (the default) for the same reason. This usually fixes the problem of a system powering up spontaneously after a suspend or poweroff. [[ACPI-aslanddump]] ==== BIOS Contains Buggy Bytecode Some BIOS vendors provide incorrect or buggy bytecode. This is usually manifested by kernel console messages like this: [source,shell] .... ACPI-1287: *** Error: Method execution failed [\\_SB_.PCI0.LPC0.FIGD._STA] \\ (Node 0xc3f6d160), AE_NOT_FOUND .... Often, these problems may be resolved by updating the BIOS to the latest revision. Most console messages are harmless, but if there are other problems, like the battery status is not working, these messages are a good place to start looking for problems. === Overriding the Default AML The BIOS bytecode, known as ACPI Machine Language (AML), is compiled from a source language called ACPI Source Language (ASL). The AML is found in the table known as the Differentiated System Description Table (DSDT). The goal of FreeBSD is for everyone to have working ACPI without any user intervention. Workarounds are still being developed for common mistakes made by BIOS vendors. The Microsoft(R) interpreter ([.filename]#acpi.sys# and [.filename]#acpiec.sys#) does not strictly check for adherence to the standard, and thus many BIOS vendors who only test ACPI under Windows(R) never fix their ASL. FreeBSD developers continue to identify and document which non-standard behavior is allowed by Microsoft(R)'s interpreter and replicate it so that FreeBSD can work without forcing users to fix the ASL. To help identify buggy behavior and possibly fix it manually, a copy can be made of the system's ASL. To copy the system's ASL to a specified file name, use `acpidump` with `-t`, to show the contents of the fixed tables, and `-d`, to disassemble the AML: [source,shell] .... # acpidump -td > my.asl .... Some AML versions assume the user is running Windows(R). To override this, set `hw.acpi.osname=_"Windows 2009"_` in [.filename]#/boot/loader.conf#, using the most recent Windows(R) version listed in the ASL. Other workarounds may require [.filename]#my.asl# to be customized. If this file is edited, compile the new ASL using the following command. Warnings can usually be ignored, but errors are bugs that will usually prevent ACPI from working correctly. [source,shell] .... # iasl -f my.asl .... Including `-f` forces creation of the AML, even if there are errors during compilation. Some errors, such as missing return statements, are automatically worked around by the FreeBSD interpreter. The default output filename for `iasl` is [.filename]#DSDT.aml#. Load this file instead of the BIOS's buggy copy, which is still present in flash memory, by editing [.filename]#/boot/loader.conf# as follows: [.programlisting] .... acpi_dsdt_load="YES" acpi_dsdt_name="/boot/DSDT.aml" .... Be sure to copy [.filename]#DSDT.aml# to [.filename]#/boot#, then reboot the system. If this fixes the problem, send a man:diff[1] of the old and new ASL to the {freebsd-acpi} so that developers can work around the buggy behavior in [.filename]#acpica#. [[ACPI-submitdebug]] === Getting and Submitting Debugging Info The ACPI driver has a flexible debugging facility. A set of subsystems and the level of verbosity can be specified. The subsystems to debug are specified as layers and are broken down into components (`ACPI_ALL_COMPONENTS`) and ACPI hardware support (`ACPI_ALL_DRIVERS`). The verbosity of debugging output is specified as the level and ranges from just report errors (`ACPI_LV_ERROR`) to everything (`ACPI_LV_VERBOSE`). The level is a bitmask so multiple options can be set at once, separated by spaces. In practice, a serial console should be used to log the output so it is not lost as the console message buffer flushes. A full list of the individual layers and levels is found in man:acpi[4]. Debugging output is not enabled by default. To enable it, add `options ACPI_DEBUG` to the custom kernel configuration file if ACPI is compiled into the kernel. Add `ACPI_DEBUG=1` to [.filename]#/etc/make.conf# to enable it globally. If a module is used instead of a custom kernel, recompile just the [.filename]#acpi.ko# module as follows: [source,shell] .... # cd /sys/modules/acpi/acpi && make clean && make ACPI_DEBUG=1 .... Copy the compiled [.filename]#acpi.ko# to [.filename]#/boot/kernel# and add the desired level and layer to [.filename]#/boot/loader.conf#. The entries in this example enable debug messages for all ACPI components and hardware drivers and output error messages at the least verbose level: [.programlisting] .... debug.acpi.layer="ACPI_ALL_COMPONENTS ACPI_ALL_DRIVERS" debug.acpi.level="ACPI_LV_ERROR" .... If the required information is triggered by a specific event, such as a suspend and then resume, do not modify [.filename]#/boot/loader.conf#. Instead, use `sysctl` to specify the layer and level after booting and preparing the system for the specific event. The variables which can be set using `sysctl` are named the same as the tunables in [.filename]#/boot/loader.conf#. Once the debugging information is gathered, it can be sent to the {freebsd-acpi} so that it can be used by the FreeBSD ACPI maintainers to identify the root cause of the problem and to develop a solution. [NOTE] ==== Before submitting debugging information to this mailing list, ensure the latest BIOS version is installed and, if available, the embedded controller firmware version. ==== When submitting a problem report, include the following information: * Description of the buggy behavior, including system type, model, and anything that causes the bug to appear. Note as accurately as possible when the bug began occurring if it is new. * The output of `dmesg` after running `boot -v`, including any error messages generated by the bug. * The `dmesg` output from `boot -v` with ACPI disabled, if disabling ACPI helps to fix the problem. * Output from `sysctl hw.acpi`. This lists which features the system offers. * The URL to a pasted version of the system's ASL. Do _not_ send the ASL directly to the list as it can be very large. Generate a copy of the ASL by running this command: + [source,shell] .... # acpidump -dt > name-system.asl .... + Substitute the login name for _name_ and manufacturer/model for _system_. For example, use [.filename]#njl-FooCo6000.asl#. Most FreeBSD developers watch the {freebsd-current}, but one should submit problems to the {freebsd-acpi} to be sure it is seen. Be patient when waiting for a response. If the bug is not immediately apparent, submit a bug report. When entering a PR, include the same information as requested above. This helps developers to track the problem and resolve it. Do not send a PR without emailing the {freebsd-acpi} first as it is likely that the problem has been reported before. [[ACPI-References]] === References More information about ACPI may be found in the following locations: * Archives at https://lists.freebsd.org/pipermail/freebsd-acpi/[] and more recent https://lists.freebsd.org/archives/freebsd-acpi/[] -* The ACPI 2.0 Specification (http://acpi.info/spec.htm[http://acpi.info/spec.htm]) +* The https://uefi.org/specifications#ACPI[ACPI Specification] * man:acpi[4], man:acpi_thermal[4], man:acpidump[8], man:iasl[8], and man:acpidb[8] diff --git a/documentation/content/en/books/handbook/config/_index.po b/documentation/content/en/books/handbook/config/_index.po index 5c5e7a167e..1ed5239be1 100644 --- a/documentation/content/en/books/handbook/config/_index.po +++ b/documentation/content/en/books/handbook/config/_index.po @@ -1,4026 +1,4025 @@ # SOME DESCRIPTIVE TITLE # Copyright (C) YEAR The FreeBSD Project # This file is distributed under the same license as the FreeBSD Documentation package. # FIRST AUTHOR , YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: FreeBSD Documentation VERSION\n" "POT-Creation-Date: 2023-04-20 20:56-0300\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #. type: YAML Front Matter: description #: documentation/content/en/books/handbook/config/_index.adoc:1 #, no-wrap msgid "This chapter explains much of the FreeBSD configuration process, including some of the parameters which can be set to tune a FreeBSD system." msgstr "" #. type: YAML Front Matter: part #: documentation/content/en/books/handbook/config/_index.adoc:1 #, no-wrap msgid "Part III. System Administration" msgstr "" #. type: YAML Front Matter: title #: documentation/content/en/books/handbook/config/_index.adoc:1 #, no-wrap msgid "Chapter 13. Configuration and Tuning" msgstr "" #. type: Title = #: documentation/content/en/books/handbook/config/_index.adoc:14 #, no-wrap msgid "Configuration and Tuning" msgstr "" #. type: Title == #: documentation/content/en/books/handbook/config/_index.adoc:52 #, no-wrap msgid "Synopsis" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:56 msgid "" "One of the important aspects of FreeBSD is proper system configuration. " "This chapter explains much of the FreeBSD configuration process, including " "some of the parameters which can be set to tune a FreeBSD system." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:58 msgid "After reading this chapter, you will know:" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:60 msgid "" "The basics of [.filename]#rc.conf# configuration and [.filename]#/usr/local/" "etc/rc.d# startup scripts." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:61 msgid "How to configure and test a network card." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:62 msgid "How to configure virtual hosts on network devices." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:63 msgid "How to use the various configuration files in [.filename]#/etc#." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:64 msgid "How to tune FreeBSD using man:sysctl[8] variables." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:65 msgid "How to tune disk performance and modify kernel limitations." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:67 msgid "Before reading this chapter, you should:" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:69 msgid "" "Understand UNIX(R) and FreeBSD basics (crossref:basics[basics,FreeBSD " "Basics])." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:70 msgid "" "Be familiar with the basics of kernel configuration and compilation " "(crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel])." msgstr "" #. type: Title == #: documentation/content/en/books/handbook/config/_index.adoc:72 #, no-wrap msgid "Starting Services" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:77 msgid "" "Many users install third party software on FreeBSD from the Ports Collection " "and require the installed services to be started upon system " "initialization. Services, such as package:mail/postfix[] or package:www/" "apache22[] are just two of the many software packages which may be started " "during system initialization. This section explains the procedures " "available for starting third party software." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:79 msgid "" "In FreeBSD, most included services, such as man:cron[8], are started through " "the system startup scripts." msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:80 #, no-wrap msgid "Extended Application Configuration" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:85 msgid "" "Now that FreeBSD includes [.filename]#rc.d#, configuration of application " "startup is easier and provides more features. Using the key words discussed " "in <>, applications can be set to start after certain " "other services and extra flags can be passed through [.filename]#/etc/rc." "conf# in place of hard coded flags in the startup script. A basic script " "may look similar to the following:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:93 #, no-wrap msgid "" "#!/bin/sh\n" "#\n" "# PROVIDE: utility\n" "# REQUIRE: DAEMON\n" "# KEYWORD: shutdown\n" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:95 #, no-wrap msgid ". /etc/rc.subr\n" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:98 #, no-wrap msgid "" "name=utility\n" "rcvar=utility_enable\n" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:100 #, no-wrap msgid "command=\"/usr/local/sbin/utility\"\n" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:102 #, no-wrap msgid "load_rc_config $name\n" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:109 #, no-wrap msgid "" "#\n" "# DO NOT CHANGE THESE DEFAULT VALUES HERE\n" "# SET THEM IN THE /etc/rc.conf FILE\n" "#\n" "utility_enable=${utility_enable-\"NO\"}\n" "pidfile=${utility_pidfile-\"/var/run/utility.pid\"}\n" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:111 #, no-wrap msgid "run_rc_command \"$1\"\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:115 msgid "" "This script will ensure that the provided `utility` will be started after " "the `DAEMON` pseudo-service. It also provides a method for setting and " "tracking the process ID (PID)." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:117 msgid "" "This application could then have the following line placed in [.filename]#/" "etc/rc.conf#:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:121 #, no-wrap msgid "utility_enable=\"YES\"\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:124 msgid "" "This method allows for easier manipulation of command line arguments, " "inclusion of the default functions provided in [.filename]#/etc/rc.subr#, " "compatibility with man:rcorder[8], and provides for easier configuration via " "[.filename]#rc.conf#." msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:125 #, no-wrap msgid "Using Services to Start Services" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:129 msgid "" "Other services can be started using man:inetd[8]. Working with man:inetd[8] " "and its configuration is described in depth in crossref:network-" "servers[network-inetd,“The inetd Super-Server”]." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:133 msgid "" "In some cases, it may make more sense to use man:cron[8] to start system " "services. This approach has a number of advantages as man:cron[8] runs " "these processes as the owner of the man:crontab[5]. This allows regular " "users to start and maintain their own applications." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:136 msgid "" "The `@reboot` feature of man:cron[8], may be used in place of the time " "specification. This causes the job to run when man:cron[8] is started, " "normally during system initialization." msgstr "" #. type: Title == #: documentation/content/en/books/handbook/config/_index.adoc:138 #, no-wrap msgid "Configuring man:cron[8]" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:144 msgid "" "One of the most useful utilities in FreeBSD is cron. This utility runs in " "the background and regularly checks [.filename]#/etc/crontab# for tasks to " "execute and searches [.filename]#/var/cron/tabs# for custom crontab files. " "These files are used to schedule tasks which cron runs at the specified " "times. Each entry in a crontab defines a task to run and is known as a " "_cron job_." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:150 msgid "" "Two different types of configuration files are used: the system crontab, " "which should not be modified, and user crontabs, which can be created and " "edited as needed. The format used by these files is documented in man:" "crontab[5]. The format of the system crontab, [.filename]#/etc/crontab# " "includes a `who` column which does not exist in user crontabs. In the " "system crontab, cron runs the command as the user specified in this column. " "In a user crontab, all commands run as the user who created the crontab." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:153 msgid "" "User crontabs allow individual users to schedule their own tasks. The " "`root` user can also have a user [.filename]#crontab# which can be used to " "schedule tasks that do not exist in the system [.filename]#crontab#." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:155 msgid "" "Here is a sample entry from the system crontab, [.filename]#/etc/crontab#:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:168 #, no-wrap msgid "" "# /etc/crontab - root's crontab for FreeBSD\n" "#\n" "# $FreeBSD$\n" "# <.>\n" "SHELL=/bin/sh\n" "PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin <.>\n" "#\n" "#minute\thour\tmday\tmonth\twday\twho\tcommand <.>\n" "#\n" "*/5\t*\t*\t*\t*\troot\t/usr/libexec/atrun <.>\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:171 msgid "" "Lines that begin with the `+#+` character are comments. A comment can be " "placed in the file as a reminder of what and why a desired action is " "performed. Comments cannot be on the same line as a command or else they " "will be interpreted as part of the command; they must be on a new line. " "Blank lines are ignored." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:173 msgid "" "The equals (`=`) character is used to define any environment settings. In " "this example, it is used to define the `SHELL` and `PATH`. If the `SHELL` is " "omitted, cron will use the default Bourne shell. If the `PATH` is omitted, " "the full path must be given to the command or script to run." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:175 msgid "" "This line defines the seven fields used in a system crontab: `minute`, " "`hour`, `mday`, `month`, `wday`, `who`, and `command`. The `minute` field is " "the time in minutes when the specified command will be run, the `hour` is " "the hour when the specified command will be run, the `mday` is the day of " "the month, `month` is the month, and `wday` is the day of the week. These " "fields must be numeric values, representing the twenty-four hour clock, or a " "`*`, representing all values for that field. The `who` field only exists in " "the system crontab and specifies which user the command should be run as. " "The last field is the command to be executed." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:177 msgid "" "This entry defines the values for this cron job. The `\\*/5`, followed by " "several more `*` characters, specifies that `/usr/libexec/atrun` is invoked " "by `root` every five minutes of every hour, of every day and day of the " "week, of every month.Commands can include any number of switches. However, " "commands which extend to multiple lines need to be broken with the backslash " "\"\\\" continuation character." msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:179 #, no-wrap msgid "Creating a User Crontab" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:182 msgid "To create a user crontab, invoke `crontab` in editor mode:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:186 #, no-wrap msgid "% crontab -e\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:191 msgid "" "This will open the user's crontab using the default text editor. The first " "time a user runs this command, it will open an empty file. Once a user " "creates a crontab, this command will open that file for editing." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:193 msgid "" "It is useful to add these lines to the top of the crontab file in order to " "set the environment variables and to remember the meanings of the fields in " "the crontab:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:200 #, no-wrap msgid "" "SHELL=/bin/sh\n" "PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin\n" "# Order of crontab fields\n" "# minute\thour\tmday\tmonth\twday\tcommand\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:205 msgid "" "Then add a line for each command or script to run, specifying the time to " "run the command. This example runs the specified custom Bourne shell script " "every day at two in the afternoon. Since the path to the script is not " "specified in `PATH`, the full path to the script is given:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:209 #, no-wrap msgid "0\t14\t*\t*\t*\t/usr/home/dru/bin/mycustomscript.sh\n" msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:216 msgid "" "Before using a custom script, make sure it is executable and test it with " "the limited set of environment variables set by cron. To replicate the " "environment that would be used to run the above cron entry, use:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:220 #, no-wrap msgid "env -i SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin HOME=/home/dru LOGNAME=dru /usr/home/dru/bin/mycustomscript.sh\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:224 msgid "" "The environment set by cron is discussed in man:crontab[5]. Checking that " "scripts operate correctly in a cron environment is especially important if " "they include any commands that delete files using wildcards." msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:229 msgid "" "When finished editing the crontab, save the file. It will automatically be " "installed and cron will read the crontab and run its cron jobs at their " "specified times. To list the cron jobs in a crontab, use this command:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:234 #, no-wrap msgid "" "% crontab -l\n" "0\t14\t*\t*\t*\t/usr/home/dru/bin/mycustomscript.sh\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:237 msgid "To remove all of the cron jobs in a user crontab:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:242 #, no-wrap msgid "" "% crontab -r\n" "remove crontab for dru? y\n" msgstr "" #. type: Title == #: documentation/content/en/books/handbook/config/_index.adoc:245 #, no-wrap msgid "Managing Services in FreeBSD" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:250 msgid "" "FreeBSD uses the man:rc[8] system of startup scripts during system " "initialization and for managing services. The scripts listed in [." "filename]#/etc/rc.d# provide basic services which can be controlled with the " "`start`, `stop`, and `restart` options to man:service[8]. For instance, man:" "sshd[8] can be restarted with the following command:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:254 #, no-wrap msgid "# service sshd restart\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:259 msgid "" "This procedure can be used to start services on a running system. Services " "will be started automatically at boot time as specified in man:rc.conf[5]. " "For example, to enable man:natd[8] at system startup, add the following line " "to [.filename]#/etc/rc.conf#:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:263 #, no-wrap msgid "natd_enable=\"YES\"\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:267 msgid "" "If a `natd_enable=\"NO\"` line is already present, change the `NO` to " "`YES`. The man:rc[8] scripts will automatically load any dependent services " "during the next boot, as described below." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:272 msgid "" "Since the man:rc[8] system is primarily intended to start and stop services " "at system startup and shutdown time, the `start`, `stop` and `restart` " "options will only perform their action if the appropriate [.filename]#/etc/" "rc.conf# variable is set. For instance, `sshd restart` will only work if " "`sshd_enable` is set to `YES` in [.filename]#/etc/rc.conf#. To `start`, " "`stop` or `restart` a service regardless of the settings in [.filename]#/etc/" "rc.conf#, these commands should be prefixed with \"one\". For instance, to " "restart man:sshd[8] regardless of the current [.filename]#/etc/rc.conf# " "setting, execute the following command:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:276 #, no-wrap msgid "# service sshd onerestart\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:280 msgid "" "To check if a service is enabled in [.filename]#/etc/rc.conf#, run the " "appropriate man:rc[8] script with `rcvar`. This example checks to see if " "man:sshd[8] is enabled in [.filename]#/etc/rc.conf#:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:288 #, no-wrap msgid "" "# service sshd rcvar\n" "# sshd\n" "#\n" "sshd_enable=\"YES\"\n" "# (default: \"\")\n" msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:293 msgid "" "The `# sshd` line is output from the above command, not a `root` console." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:297 msgid "" "To determine whether or not a service is running, use `status`. For " "instance, to verify that man:sshd[8] is running:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:302 #, no-wrap msgid "" "# service sshd status\n" "sshd is running as pid 433.\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:308 msgid "" "In some cases, it is also possible to `reload` a service. This attempts to " "send a signal to an individual service, forcing the service to reload its " "configuration files. In most cases, this means sending the service a " "`SIGHUP` signal. Support for this feature is not included for every service." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:311 msgid "" "The man:rc[8] system is used for network services and it also contributes to " "most of the system initialization. For instance, when the [.filename]#/etc/" "rc.d/bgfsck# script is executed, it prints out the following message:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:315 #, no-wrap msgid "Starting background file system checks in 60 seconds.\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:318 msgid "" "This script is used for background file system checks, which occur only " "during system initialization." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:323 msgid "" "Many system services depend on other services to function properly. For " "example, man:yp[8] and other RPC-based services may fail to start until " "after the man:rpcbind[8] service has started. To resolve this issue, " "information about dependencies and other meta-data is included in the " "comments at the top of each startup script. The man:rcorder[8] program is " "used to parse these comments during system initialization to determine the " "order in which system services should be invoked to satisfy the dependencies." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:325 msgid "" "The following key word must be included in all startup scripts as it is " "required by man:rc.subr[8] to \"enable\" the startup script:" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:327 msgid "`PROVIDE`: Specifies the services this file provides." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:330 msgid "" "The following key words may be included at the top of each startup script. " "They are not strictly necessary, but are useful as hints to man:rcorder[8]:" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:332 msgid "" "`REQUIRE`: Lists services which are required for this service. The script " "containing this key word will run _after_ the specified services." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:333 msgid "" "`BEFORE`: Lists services which depend on this service. The script containing " "this key word will run _before_ the specified services." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:335 msgid "" "By carefully setting these keywords for each startup script, an " "administrator has a fine-grained level of control of the startup order of " "the scripts, without the need for \"runlevels\" used by some UNIX(R) " "operating systems." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:338 msgid "" "Additional information can be found in man:rc[8] and man:rc.subr[8]. Refer " "to extref:{rc-scripting}[this article] for instructions on how to create " "custom man:rc[8] scripts." msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:340 #, no-wrap msgid "Managing System-Specific Configuration" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:345 msgid "" "The principal location for system configuration information is [.filename]#/" "etc/rc.conf#. This file contains a wide range of configuration information " "and it is read at system startup to configure the system. It provides the " "configuration information for the [.filename]#rc*# files." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:349 msgid "" "The entries in [.filename]#/etc/rc.conf# override the default settings in [." "filename]#/etc/defaults/rc.conf#. The file containing the default settings " "should not be edited. Instead, all system-specific changes should be made " "to [.filename]#/etc/rc.conf#." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:353 msgid "" "A number of strategies may be applied in clustered applications to separate " "site-wide configuration from system-specific configuration in order to " "reduce administration overhead. The recommended approach is to place system-" "specific configuration into [.filename]#/etc/rc.conf.local#. For example, " "these entries in [.filename]#/etc/rc.conf# apply to all systems:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:359 #, no-wrap msgid "" "sshd_enable=\"YES\"\n" "keyrate=\"fast\"\n" "defaultrouter=\"10.1.1.254\"\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:362 msgid "" "Whereas these entries in [.filename]#/etc/rc.conf.local# apply to this " "system only:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:367 #, no-wrap msgid "" "hostname=\"node1.example.org\"\n" "ifconfig_fxp0=\"inet 10.1.1.1/8\"\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:370 msgid "" "Distribute [.filename]#/etc/rc.conf# to every system using an application " "such as rsync or puppet, while [.filename]#/etc/rc.conf.local# remains " "unique." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:372 msgid "" "Upgrading the system will not overwrite [.filename]#/etc/rc.conf#, so system " "configuration information will not be lost." msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:379 msgid "" "Both [.filename]#/etc/rc.conf# and [.filename]#/etc/rc.conf.local# are " "parsed by man:sh[1]. This allows system operators to create complex " "configuration scenarios. Refer to man:rc.conf[5] for further information on " "this topic." msgstr "" #. type: Title == #: documentation/content/en/books/handbook/config/_index.adoc:382 #, no-wrap msgid "Setting Up Network Interface Cards" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:385 msgid "" "Adding and configuring a network interface card (NIC) is a common task for " "any FreeBSD administrator." msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:386 #, no-wrap msgid "Locating the Correct Driver" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:391 msgid "" "First, determine the model of the NIC and the chip it uses. FreeBSD " "supports a wide variety of NICs. Check the Hardware Compatibility List for " "the FreeBSD release to see if the NIC is supported." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:395 msgid "" "If the NIC is supported, determine the name of the FreeBSD driver for the " "NIC. Refer to [.filename]#/usr/src/sys/conf/NOTES# and [.filename]#/usr/src/" "sys/arch/conf/NOTES# for the list of NIC drivers with some information about " "the supported chipsets. When in doubt, read the manual page of the driver " "as it will provide more information about the supported hardware and any " "known limitations of the driver." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:399 msgid "" "The drivers for common NICs are already present in the [.filename]#GENERIC# " "kernel, meaning the NIC should be probed during boot. The system's boot " "messages can be viewed by typing `more /var/run/dmesg.boot` and using the " "spacebar to scroll through the text. In this example, two Ethernet NICs " "using the man:dc[4] driver are present on the system:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:416 #, no-wrap msgid "" "dc0: <82c169 PNIC 10/100BaseTX> port 0xa000-0xa0ff mem 0xd3800000-0xd38\n" "000ff irq 15 at device 11.0 on pci0\n" "miibus0: on dc0\n" "bmtphy0: PHY 1 on miibus0\n" "bmtphy0: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto\n" "dc0: Ethernet address: 00:a0:cc:da:da:da\n" "dc0: [ITHREAD]\n" "dc1: <82c169 PNIC 10/100BaseTX> port 0x9800-0x98ff mem 0xd3000000-0xd30\n" "000ff irq 11 at device 12.0 on pci0\n" "miibus1: on dc1\n" "bmtphy1: PHY 1 on miibus1\n" "bmtphy1: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto\n" "dc1: Ethernet address: 00:a0:cc:da:da:db\n" "dc1: [ITHREAD]\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:420 msgid "" "If the driver for the NIC is not present in [.filename]#GENERIC#, but a " "driver is available, the driver will need to be loaded before the NIC can be " "configured and used. This may be accomplished in one of two ways:" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:422 msgid "" "The easiest way is to load a kernel module for the NIC using man:kldload[8]. " "To also automatically load the driver at boot time, add the appropriate line " "to [.filename]#/boot/loader.conf#. Not all NIC drivers are available as " "modules." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:423 msgid "" "Alternatively, statically compile support for the NIC into a custom kernel. " "Refer to [.filename]#/usr/src/sys/conf/NOTES#, [.filename]#/usr/src/sys/arch/" "conf/NOTES# and the manual page of the driver to determine which line to add " "to the custom kernel configuration file. For more information about " "recompiling the kernel, refer to crossref:kernelconfig[kernelconfig," "Configuring the FreeBSD Kernel]. If the NIC was detected at boot, the kernel " "does not need to be recompiled." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:425 #, no-wrap msgid "Using Windows(R) NDIS Drivers" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:429 msgid "" "Unfortunately, there are still many vendors that do not provide schematics " "for their drivers to the open source community because they regard such " "information as trade secrets. Consequently, the developers of FreeBSD and " "other operating systems are left with two choices: develop the drivers by a " "long and pain-staking process of reverse engineering or using the existing " "driver binaries available for Microsoft(R) Windows(R) platforms." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:434 msgid "" "FreeBSD provides \"native\" support for the Network Driver Interface " "Specification (NDIS). It includes man:ndisgen[8] which can be used to " "convert a Windows(R) XP driver into a format that can be used on FreeBSD. " "As the man:ndis[4] driver uses a Windows(R) XP binary, it only runs on " "i386(TM) and amd64 systems. PCI, CardBus, PCMCIA, and USB devices are " "supported." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:436 msgid "To use man:ndisgen[8], three things are needed:" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:438 msgid "FreeBSD kernel sources." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:439 msgid "A Windows(R) XP driver binary with a [.filename]#.SYS# extension." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:440 msgid "" "A Windows(R) XP driver configuration file with a [.filename]#.INF# extension." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:444 msgid "" "Download the [.filename]#.SYS# and [.filename]#.INF# files for the specific " "NIC. Generally, these can be found on the driver CD or at the vendor's " "website. The following examples use [.filename]#W32DRIVER.SYS# and [." "filename]#W32DRIVER.INF#." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:448 msgid "" "The driver bit width must match the version of FreeBSD. For FreeBSD/i386, " "use a Windows(R) 32-bit driver. For FreeBSD/amd64, a Windows(R) 64-bit " "driver is needed." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:451 msgid "" "The next step is to compile the driver binary into a loadable kernel " "module. As `root`, use man:ndisgen[8]:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:455 #, no-wrap msgid "# ndisgen /path/to/W32DRIVER.INF /path/to/W32DRIVER.SYS\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:460 msgid "" "This command is interactive and prompts for any extra information it " "requires. A new kernel module will be generated in the current directory. " "Use man:kldload[8] to load the new module:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:464 #, no-wrap msgid "# kldload ./W32DRIVER_SYS.ko\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:469 msgid "" "In addition to the generated kernel module, the [.filename]#ndis.ko# and [." "filename]#if_ndis.ko# modules must be loaded. This should happen " "automatically when any module that depends on man:ndis[4] is loaded. If " "not, load them manually, using the following commands:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:474 #, no-wrap msgid "" "# kldload ndis\n" "# kldload if_ndis\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:477 msgid "" "The first command loads the man:ndis[4] miniport driver wrapper and the " "second loads the generated NIC driver." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:480 msgid "" "Check man:dmesg[8] to see if there were any load errors. If all went well, " "the output should be similar to the following:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:488 #, no-wrap msgid "" "ndis0: mem 0xf4100000-0xf4101fff irq 3 at device 8.0 on pci1\n" "ndis0: NDIS API version: 5.0\n" "ndis0: Ethernet address: 0a:b1:2c:d3:4e:f5\n" "ndis0: 11b rates: 1Mbps 2Mbps 5.5Mbps 11Mbps\n" "ndis0: 11g rates: 6Mbps 9Mbps 12Mbps 18Mbps 36Mbps 48Mbps 54Mbps\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:491 msgid "From here, [.filename]#ndis0# can be configured like any other NIC." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:494 msgid "" "To configure the system to load the man:ndis[4] modules at boot time, copy " "the generated module, [.filename]#W32DRIVER_SYS.ko#, to [.filename]#/boot/" "modules#. Then, add the following line to [.filename]#/boot/loader.conf#:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:498 #, no-wrap msgid "W32DRIVER_SYS_load=\"YES\"\n" msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:500 #, no-wrap msgid "Configuring the Network Card" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:504 msgid "" "Once the right driver is loaded for the NIC, the card needs to be " "configured. It may have been configured at installation time by man:" "bsdinstall[8]." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:506 msgid "To display the NIC configuration, enter the following command:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:528 #, no-wrap msgid "" "% ifconfig\n" "dc0: flags=8843 metric 0 mtu 1500\n" " options=80008\n" " ether 00:a0:cc:da:da:da\n" " inet 192.168.1.3 netmask 0xffffff00 broadcast 192.168.1.255\n" " media: Ethernet autoselect (100baseTX )\n" " status: active\n" "dc1: flags=8802 metric 0 mtu 1500\n" " options=80008\n" " ether 00:a0:cc:da:da:db\n" " inet 10.0.0.1 netmask 0xffffff00 broadcast 10.0.0.255\n" " media: Ethernet 10baseT/UTP\n" " status: no carrier\n" "lo0: flags=8049 metric 0 mtu 16384\n" " options=3\n" " inet6 fe80::1%lo0 prefixlen 64 scopeid 0x4\n" " inet6 ::1 prefixlen 128\n" " inet 127.0.0.1 netmask 0xff000000\n" " nd6 options=3\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:531 msgid "In this example, the following devices were displayed:" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:533 msgid "[.filename]#dc0#: The first Ethernet interface." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:534 msgid "[.filename]#dc1#: The second Ethernet interface." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:535 msgid "[.filename]#lo0#: The loopback device." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:538 msgid "" "FreeBSD uses the driver name followed by the order in which the card is " "detected at boot to name the NIC. For example, [.filename]#sis2# is the " "third NIC on the system using the man:sis[4] driver." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:541 msgid "" "In this example, [.filename]#dc0# is up and running. The key indicators are:" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:543 msgid "`UP` means that the card is configured and ready." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:544 msgid "The card has an Internet (`inet`) address, `192.168.1.3`." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:545 msgid "" "It has a valid subnet mask (`netmask`), where `0xffffff00` is the same as " "`255.255.255.0`." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:546 msgid "It has a valid broadcast address, `192.168.1.255`." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:547 msgid "The MAC address of the card (`ether`) is `00:a0:cc:da:da:da`." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:548 msgid "" "The physical media selection is on autoselection mode (`media: Ethernet " "autoselect (100baseTX )`). In this example, [.filename]#dc1# is " "configured to run with `10baseT/UTP` media. For more information on " "available media types for a driver, refer to its manual page." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:549 msgid "" "The status of the link (`status`) is `active`, indicating that the carrier " "signal is detected. For [.filename]#dc1#, the `status: no carrier` status is " "normal when an Ethernet cable is not plugged into the card." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:551 msgid "If the man:ifconfig[8] output had shown something similar to:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:559 #, no-wrap msgid "" "dc0: flags=8843 metric 0 mtu 1500\n" "\toptions=80008\n" "\tether 00:a0:cc:da:da:da\n" "\tmedia: Ethernet autoselect (100baseTX )\n" "\tstatus: active\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:562 msgid "it would indicate the card has not been configured." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:566 msgid "" "The card must be configured as `root`. The NIC configuration can be " "performed from the command line with man:ifconfig[8] but will not persist " "after a reboot unless the configuration is also added to [.filename]#/etc/rc." "conf#. If a DHCP server is present on the LAN, just add this line:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:570 #, no-wrap msgid "ifconfig_dc0=\"DHCP\"\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:573 msgid "Replace _dc0_ with the correct value for the system." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:575 msgid "" "The line added, then, follow the instructions given in <>." msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:580 msgid "" "If the network was configured during installation, some entries for the " "NIC(s) may be already present. Double check [.filename]#/etc/rc.conf# " "before adding any lines." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:584 msgid "" "If there is no DHCP server, the NIC(s) must be configured manually. Add a " "line for each NIC present on the system, as seen in this example:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:589 #, no-wrap msgid "" "ifconfig_dc0=\"inet 192.168.1.3 netmask 255.255.255.0\"\n" "ifconfig_dc1=\"inet 10.0.0.1 netmask 255.255.255.0 media 10baseT/UTP\"\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:593 msgid "" "Replace [.filename]#dc0# and [.filename]#dc1# and the IP address information " "with the correct values for the system. Refer to the man page for the " "driver, man:ifconfig[8], and man:rc.conf[5] for more details about the " "allowed options and the syntax of [.filename]#/etc/rc.conf#." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:596 msgid "" "If the network is not using DNS, edit [.filename]#/etc/hosts# to add the " "names and IP addresses of the hosts on the LAN, if they are not already " "there. For more information, refer to man:hosts[5] and to [.filename]#/usr/" "share/examples/etc/hosts#." msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:600 msgid "" "If there is no DHCP server and access to the Internet is needed, manually " "configure the default gateway and the nameserver:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:605 #, no-wrap msgid "" "# sysrc defaultrouter=\"your_default_router\"\n" "# echo 'nameserver your_DNS_server' >> /etc/resolv.conf\n" msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:610 #, no-wrap msgid "Testing and Troubleshooting" msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:614 msgid "" "Once the necessary changes to [.filename]#/etc/rc.conf# are saved, a reboot " "can be used to test the network configuration and to verify that the system " "restarts without any configuration errors. Alternatively, apply the " "settings to the networking system with this command:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:618 #, no-wrap msgid "# service netif restart\n" msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:623 msgid "" "If a default gateway has been set in [.filename]#/etc/rc.conf#, also issue " "this command:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:627 #, no-wrap msgid "# service routing restart\n" msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:632 msgid "Once the networking system has been relaunched, test the NICs." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:633 #, no-wrap msgid "Testing the Ethernet Card" msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:636 msgid "" "To verify that an Ethernet card is configured correctly, man:ping[8] the " "interface itself, and then man:ping[8] another machine on the LAN:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:646 #, no-wrap msgid "" "% ping -c5 192.168.1.3\n" "PING 192.168.1.3 (192.168.1.3): 56 data bytes\n" "64 bytes from 192.168.1.3: icmp_seq=0 ttl=64 time=0.082 ms\n" "64 bytes from 192.168.1.3: icmp_seq=1 ttl=64 time=0.074 ms\n" "64 bytes from 192.168.1.3: icmp_seq=2 ttl=64 time=0.076 ms\n" "64 bytes from 192.168.1.3: icmp_seq=3 ttl=64 time=0.108 ms\n" "64 bytes from 192.168.1.3: icmp_seq=4 ttl=64 time=0.076 ms\n" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:650 #, no-wrap msgid "" "--- 192.168.1.3 ping statistics ---\n" "5 packets transmitted, 5 packets received, 0% packet loss\n" "round-trip min/avg/max/stddev = 0.074/0.083/0.108/0.013 ms\n" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:661 #, no-wrap msgid "" "% ping -c5 192.168.1.2\n" "PING 192.168.1.2 (192.168.1.2): 56 data bytes\n" "64 bytes from 192.168.1.2: icmp_seq=0 ttl=64 time=0.726 ms\n" "64 bytes from 192.168.1.2: icmp_seq=1 ttl=64 time=0.766 ms\n" "64 bytes from 192.168.1.2: icmp_seq=2 ttl=64 time=0.700 ms\n" "64 bytes from 192.168.1.2: icmp_seq=3 ttl=64 time=0.747 ms\n" "64 bytes from 192.168.1.2: icmp_seq=4 ttl=64 time=0.704 ms\n" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:665 #, no-wrap msgid "" "--- 192.168.1.2 ping statistics ---\n" "5 packets transmitted, 5 packets received, 0% packet loss\n" "round-trip min/avg/max/stddev = 0.700/0.729/0.766/0.025 ms\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:671 msgid "" "To test network resolution, use the host name instead of the IP address. If " "there is no DNS server on the network, [.filename]#/etc/hosts# must first be " "configured. To this purpose, edit [.filename]#/etc/hosts# to add the names " "and IP addresses of the hosts on the LAN, if they are not already there. " "For more information, refer to man:hosts[5] and to [.filename]#/usr/share/" "examples/etc/hosts#." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:672 #, no-wrap msgid "Troubleshooting" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:676 msgid "" "When troubleshooting hardware and software configurations, check the simple " "things first. Is the network cable plugged in? Are the network services " "properly configured? Is the firewall configured correctly? Is the NIC " "supported by FreeBSD? Before sending a bug report, always check the Hardware " "Notes, update the version of FreeBSD to the latest STABLE version, check the " "mailing list archives, and search the Internet." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:679 msgid "" "If the card works, yet performance is poor, read through man:tuning[7]. " "Also, check the network configuration as incorrect network settings can " "cause slow connections." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:684 msgid "" "Some users experience one or two `device timeout` messages, which is normal " "for some cards. If they continue, or are bothersome, determine if the " "device is conflicting with another device. Double check the cable " "connections. Consider trying another card." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:689 msgid "" "To resolve `watchdog timeout` errors, first check the network cable. Many " "cards require a PCI slot which supports bus mastering. On some old " "motherboards, only one PCI slot allows it, usually slot 0. Check the NIC " "and the motherboard documentation to determine if that may be the problem." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:694 msgid "" "`No route to host` messages occur if the system is unable to route a packet " "to the destination host. This can happen if no default route is specified " "or if a cable is unplugged. Check the output of `netstat -rn` and make sure " "there is a valid route to the host. If there is not, read crossref:advanced-" "networking[network-routing,“Gateways and Routes”]." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:698 msgid "" "`ping: sendto: Permission denied` error messages are often caused by a " "misconfigured firewall. If a firewall is enabled on FreeBSD but no rules " "have been defined, the default policy is to deny all traffic, even man:" "ping[8]. Refer to crossref:firewalls[firewalls,Firewalls] for more " "information." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:703 msgid "" "Sometimes performance of the card is poor or below average. In these cases, " "try setting the media selection mode from `autoselect` to the correct media " "selection. While this works for most hardware, it may or may not resolve " "the issue. Again, check all the network settings, and refer to man:" "tuning[7]." msgstr "" #. type: Title == #: documentation/content/en/books/handbook/config/_index.adoc:705 #, no-wrap msgid "Virtual Hosts" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:709 msgid "" "A common use of FreeBSD is virtual site hosting, where one server appears to " "the network as many servers. This is achieved by assigning multiple network " "addresses to a single interface." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:712 msgid "" "A given network interface has one \"real\" address, and may have any number " "of \"alias\" addresses. These aliases are normally added by placing alias " "entries in [.filename]#/etc/rc.conf#, as seen in this example:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:716 #, no-wrap msgid "ifconfig_fxp0_alias0=\"inet xxx.xxx.xxx.xxx netmask xxx.xxx.xxx.xxx\"\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:720 msgid "" "Alias entries must start with `alias__0__` using a sequential number such as " "`alias0`, `alias1`, and so on. The configuration process will stop at the " "first missing number." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:724 msgid "" "The calculation of alias netmasks is important. For a given interface, " "there must be one address which correctly represents the network's netmask. " "Any other addresses which fall within this network must have a netmask of " "all ``1``s, expressed as either `255.255.255.255` or `0xffffffff`." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:729 msgid "" "For example, consider the case where the [.filename]#fxp0# interface is " "connected to two networks: `10.1.1.0` with a netmask of `255.255.255.0` and " "`202.0.75.16` with a netmask of `255.255.255.240`. The system is to be " "configured to appear in the ranges `10.1.1.1` through `10.1.1.5` and " "`202.0.75.17` through `202.0.75.20`. Only the first address in a given " "network range should have a real netmask. All the rest (`10.1.1.2` through " "`10.1.1.5` and `202.0.75.18` through `202.0.75.20`) must be configured with " "a netmask of `255.255.255.255`." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:731 msgid "" "The following [.filename]#/etc/rc.conf# entries configure the adapter " "correctly for this scenario:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:743 #, no-wrap msgid "" "ifconfig_fxp0=\"inet 10.1.1.1 netmask 255.255.255.0\"\n" "ifconfig_fxp0_alias0=\"inet 10.1.1.2 netmask 255.255.255.255\"\n" "ifconfig_fxp0_alias1=\"inet 10.1.1.3 netmask 255.255.255.255\"\n" "ifconfig_fxp0_alias2=\"inet 10.1.1.4 netmask 255.255.255.255\"\n" "ifconfig_fxp0_alias3=\"inet 10.1.1.5 netmask 255.255.255.255\"\n" "ifconfig_fxp0_alias4=\"inet 202.0.75.17 netmask 255.255.255.240\"\n" "ifconfig_fxp0_alias5=\"inet 202.0.75.18 netmask 255.255.255.255\"\n" "ifconfig_fxp0_alias6=\"inet 202.0.75.19 netmask 255.255.255.255\"\n" "ifconfig_fxp0_alias7=\"inet 202.0.75.20 netmask 255.255.255.255\"\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:747 msgid "" "A simpler way to express this is with a space-separated list of IP address " "ranges. The first address will be given the indicated subnet mask and the " "additional addresses will have a subnet mask of `255.255.255.255`." msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:751 #, no-wrap msgid "ifconfig_fxp0_aliases=\"inet 10.1.1.1-5/24 inet 202.0.75.17-20/28\"\n" msgstr "" #. type: Title == #: documentation/content/en/books/handbook/config/_index.adoc:754 #, no-wrap msgid "Configuring System Logging" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:760 msgid "" "Generating and reading system logs is an important aspect of system " "administration. The information in system logs can be used to detect " "hardware and software issues as well as application and system configuration " "errors. This information also plays an important role in security auditing " "and incident response. Most system daemons and applications will generate " "log entries." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:766 msgid "" "FreeBSD provides a system logger, syslogd, to manage logging. By default, " "syslogd is started when the system boots. This is controlled by the " "variable `syslogd_enable` in [.filename]#/etc/rc.conf#. There are numerous " "application arguments that can be set using `syslogd_flags` in [.filename]#/" "etc/rc.conf#. Refer to man:syslogd[8] for more information on the available " "arguments." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:768 msgid "" "This section describes how to configure the FreeBSD system logger for both " "local and remote logging and how to perform log rotation and log management." msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:769 #, no-wrap msgid "Configuring Local Logging" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:776 msgid "" "The configuration file, [.filename]#/etc/syslog.conf#, controls what syslogd " "does with log entries as they are received. There are several parameters to " "control the handling of incoming events. The _facility_ describes which " "subsystem generated the message, such as the kernel or a daemon, and the " "_level_ describes the severity of the event that occurred. This makes it " "possible to configure if and where a log message is logged, depending on the " "facility and level. It is also possible to take action depending on the " "application that sent the message, and in the case of remote logging, the " "hostname of the machine generating the logging event." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:784 msgid "" "This configuration file contains one line per action, where the syntax for " "each line is a selector field followed by an action field. The syntax of " "the selector field is _facility.level_ which will match log messages from " "_facility_ at level _level_ or higher. It is also possible to add an " "optional comparison flag before the level to specify more precisely what is " "logged. Multiple selector fields can be used for the same action, and are " "separated with a semicolon (`;`). Using `*` will match everything. The " "action field denotes where to send the log message, such as to a file or " "remote log host. As an example, here is the default [.filename]#syslog." "conf# from FreeBSD:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:822 #, no-wrap msgid "" "# $FreeBSD$\n" "#\n" "# Spaces ARE valid field separators in this file. However,\n" "# other *nix-like systems still insist on using tabs as field\n" "# separators. If you are sharing this file between systems, you\n" "# may want to use only tabs as field separators here.\n" "# Consult the syslog.conf(5) manpage.\n" "*.err;kern.warning;auth.notice;mail.crit /dev/console\n" "*.notice;authpriv.none;kern.debug;lpr.info;mail.crit;news.err /var/log/messages\n" "security.* /var/log/security\n" "auth.info;authpriv.info /var/log/auth.log\n" "mail.info /var/log/maillog\n" "lpr.info /var/log/lpd-errs\n" "ftp.info /var/log/xferlog\n" "cron.* /var/log/cron\n" "!-devd\n" "*.=debug /var/log/debug.log\n" "*.emerg *\n" "# uncomment this to log all writes to /dev/console to /var/log/console.log\n" "#console.info /var/log/console.log\n" "# uncomment this to enable logging of all log messages to /var/log/all.log\n" "# touch /var/log/all.log and chmod it to mode 600 before it will work\n" "#*.* /var/log/all.log\n" "# uncomment this to enable logging to a remote loghost named loghost\n" "#*.* @loghost\n" "# uncomment these if you're running inn\n" "# news.crit /var/log/news/news.crit\n" "# news.err /var/log/news/news.err\n" "# news.notice /var/log/news/news.notice\n" "# Uncomment this if you wish to see messages produced by devd\n" "# !devd\n" "# *.>=info\n" "!ppp\n" "*.* /var/log/ppp.log\n" "!*\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:825 msgid "In this example:" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:827 msgid "" "Line 8 matches all messages with a level of `err` or higher, as well as " "`kern.warning`, `auth.notice` and `mail.crit`, and sends these log messages " "to the console ([.filename]#/dev/console#)." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:828 msgid "" "Line 12 matches all messages from the `mail` facility at level `info` or " "above and logs the messages to [.filename]#/var/log/maillog#." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:829 msgid "" "Line 17 uses a comparison flag (`=`) to only match messages at level `debug` " "and logs them to [.filename]#/var/log/debug.log#." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:830 msgid "" "Line 33 is an example usage of a program specification. This makes the rules " "following it only valid for the specified program. In this case, only the " "messages generated by ppp are logged to [.filename]#/var/log/ppp.log#." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:832 msgid "" "The available levels, in order from most to least critical are `emerg`, " "`alert`, `crit`, `err`, `warning`, `notice`, `info`, and `debug`." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:835 msgid "" "The facilities, in no particular order, are `auth`, `authpriv`, `console`, " "`cron`, `daemon`, `ftp`, `kern`, `lpr`, `mail`, `mark`, `news`, `security`, " "`syslog`, `user`, `uucp`, and `local0` through `local7`. Be aware that " "other operating systems might have different facilities." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:837 msgid "" "To log everything of level `notice` and higher to [.filename]#/var/log/" "daemon.log#, add the following entry:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:841 #, no-wrap msgid "daemon.notice /var/log/daemon.log\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:845 msgid "" "For more information about the different levels and facilities, refer to man:" "syslog[3] and man:syslogd[8]. For more information about [.filename]#/etc/" "syslog.conf#, its syntax, and more advanced usage examples, see man:syslog." "conf[5]." msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:846 #, no-wrap msgid "Log Management and Rotation" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:855 msgid "" "Log files can grow quickly, taking up disk space and making it more " "difficult to locate useful information. Log management attempts to mitigate " "this. In FreeBSD, newsyslog is used to manage log files. This built-in " "program periodically rotates and compresses log files, and optionally " "creates missing log files and signals programs when log files are moved. " "The log files may be generated by syslogd or by any other program which " "generates log files. While newsyslog is normally run from man:cron[8], it " "is not a system daemon. In the default configuration, it runs every hour." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:860 msgid "" "To know which actions to take, newsyslog reads its configuration file, [." "filename]#/etc/newsyslog.conf#. This file contains one line for each log " "file that newsyslog manages. Each line states the file owner, permissions, " "when to rotate that file, optional flags that affect log rotation, such as " "compression, and programs to signal when the log is rotated. Here is the " "default configuration in FreeBSD:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:902 #, no-wrap msgid "" "# configuration file for newsyslog\n" "# $FreeBSD$\n" "#\n" "# Entries which do not specify the '/pid_file' field will cause the\n" "# syslogd process to be signalled when that log file is rotated. This\n" "# action is only appropriate for log files which are written to by the\n" "# syslogd process (ie, files listed in /etc/syslog.conf). If there\n" "# is no process which needs to be signalled when a given log file is\n" "# rotated, then the entry for that file should include the 'N' flag.\n" "#\n" "# The 'flags' field is one or more of the letters: BCDGJNUXZ or a '-'.\n" "#\n" "# Note: some sites will want to select more restrictive protections than the\n" "# defaults. In particular, it may be desirable to switch many of the 644\n" "# entries to 640 or 600. For example, some sites will consider the\n" "# contents of maillog, messages, and lpd-errs to be confidential. In the\n" "# future, these defaults may change to more conservative ones.\n" "#\n" "# logfilename [owner:group] mode count size when flags [/pid_file] [sig_num]\n" "/var/log/all.log 600 7 * @T00 J\n" "/var/log/amd.log 644 7 100 * J\n" "/var/log/auth.log 600 7 100 @0101T JC\n" "/var/log/console.log 600 5 100 * J\n" "/var/log/cron 600 3 100 * JC\n" "/var/log/daily.log 640 7 * @T00 JN\n" "/var/log/debug.log 600 7 100 * JC\n" "/var/log/kerberos.log 600 7 100 * J\n" "/var/log/lpd-errs 644 7 100 * JC\n" "/var/log/maillog 640 7 * @T00 JC\n" "/var/log/messages 644 5 100 @0101T JC\n" "/var/log/monthly.log 640 12 * $M1D0 JN\n" "/var/log/pflog 600 3 100 * JB /var/run/pflogd.pid\n" "/var/log/ppp.log root:network 640 3 100 * JC\n" "/var/log/devd.log 644 3 100 * JC\n" "/var/log/security 600 10 100 * JC\n" "/var/log/sendmail.st 640 10 * 168 B\n" "/var/log/utx.log 644 3 * @01T05 B\n" "/var/log/weekly.log 640 5 1 $W6D0 JN\n" "/var/log/xferlog 600 7 100 * JC\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:911 msgid "" "Each line starts with the name of the log to be rotated, optionally followed " "by an owner and group for both rotated and newly created files. The `mode` " "field sets the permissions on the log file and `count` denotes how many " "rotated log files should be kept. The `size` and `when` fields tell " "newsyslog when to rotate the file. A log file is rotated when either its " "size is larger than the `size` field or when the time in the `when` field " "has passed. An asterisk (`*`) means that this field is ignored. The " "_flags_ field gives further instructions, such as how to compress the " "rotated file or to create the log file if it is missing. The last two " "fields are optional and specify the name of the Process ID (PID) file of a " "process and a signal number to send to that process when the file is rotated." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:914 msgid "" "For more information on all fields, valid flags, and how to specify the " "rotation time, refer to man:newsyslog.conf[5]. Since newsyslog is run from " "man:cron[8], it cannot rotate files more often than it is scheduled to run " "from man:cron[8]." msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:916 #, no-wrap msgid "Configuring Remote Logging" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:920 msgid "" "Monitoring the log files of multiple hosts can become unwieldy as the number " "of systems increases. Configuring centralized logging can reduce some of " "the administrative burden of log file administration." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:924 msgid "" "In FreeBSD, centralized log file aggregation, merging, and rotation can be " "configured using syslogd and newsyslog. This section demonstrates an " "example configuration, where host `A`, named `logserv.example.com`, will " "collect logging information for the local network. Host `B`, named " "`logclient.example.com`, will be configured to pass logging information to " "the logging server." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:925 #, no-wrap msgid "Log Server Configuration" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:929 msgid "" "A log server is a system that has been configured to accept logging " "information from other hosts. Before configuring a log server, check the " "following:" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:931 msgid "" "If there is a firewall between the logging server and any logging clients, " "ensure that the firewall ruleset allows UDP port 514 for both the clients " "and the server." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:932 msgid "" "The logging server and all client machines must have forward and reverse " "entries in the local DNS. If the network does not have a DNS server, create " "entries in each system's [.filename]#/etc/hosts#. Proper name resolution is " "required so that log entries are not rejected by the logging server." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:935 msgid "" "On the log server, edit [.filename]#/etc/syslog.conf# to specify the name of " "the client to receive log entries from, the logging facility to be used, and " "the name of the log to store the host's log entries. This example adds the " "hostname of `B`, logs all facilities, and stores the log entries in [." "filename]#/var/log/logclient.log#." msgstr "" #. type: Block title #: documentation/content/en/books/handbook/config/_index.adoc:936 #, no-wrap msgid "Sample Log Server Configuration" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:944 #, no-wrap msgid "" "+logclient.example.com\n" "*.* /var/log/logclient.log\n" msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:950 msgid "" "When adding multiple log clients, add a similar two-line entry for each " "client. More information about the available facilities may be found in man:" "syslog.conf[5]." msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:952 msgid "Next, configure [.filename]#/etc/rc.conf#:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:957 #, no-wrap msgid "" "syslogd_enable=\"YES\"\n" "syslogd_flags=\"-a logclient.example.com -v -v\"\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:963 msgid "" "The first entry starts syslogd at system boot. The second entry allows log " "entries from the specified client. The `-v -v` increases the verbosity of " "logged messages. This is useful for tweaking facilities as administrators " "are able to see what type of messages are being logged under each facility." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:967 msgid "" "Multiple `-a` options may be specified to allow logging from multiple " "clients. IP addresses and whole netblocks may also be specified. Refer to " "man:syslogd[8] for a full list of possible options." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:969 msgid "Finally, create the log file:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:973 #, no-wrap msgid "# touch /var/log/logclient.log\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:976 msgid "At this point, syslogd should be restarted and verified:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:981 #, no-wrap msgid "" "# service syslogd restart\n" "# pgrep syslog\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:985 msgid "" "If a PID is returned, the server restarted successfully, and client " "configuration can begin. If the server did not restart, consult [." "filename]#/var/log/messages# for the error." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:986 #, no-wrap msgid "Log Client Configuration" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:990 msgid "" "A logging client sends log entries to a logging server on the network. The " "client also keeps a local copy of its own logs." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:992 msgid "" "Once a logging server has been configured, edit [.filename]#/etc/rc.conf# on " "the logging client:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:997 #, no-wrap msgid "" "syslogd_enable=\"YES\"\n" "syslogd_flags=\"-s -v -v\"\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1001 msgid "" "The first entry enables syslogd on boot up. The second entry prevents logs " "from being accepted by this client from other hosts (`-s`) and increases the " "verbosity of logged messages." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1004 msgid "" "Next, define the logging server in the client's [.filename]#/etc/syslog." "conf#. In this example, all logged facilities are sent to a remote system, " "denoted by the `@` symbol, with the specified hostname:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1008 #, no-wrap msgid "*.*\t\t@logserv.example.com\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1011 msgid "After saving the edit, restart syslogd for the changes to take effect:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1015 #: documentation/content/en/books/handbook/config/_index.adoc:1045 #, no-wrap msgid "# service syslogd restart\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1018 msgid "" "To test that log messages are being sent across the network, use man:" "logger[1] on the client to send a message to syslogd:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1022 #, no-wrap msgid "# logger \"Test message from logclient\"\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1025 msgid "" "This message should now exist both in [.filename]#/var/log/messages# on the " "client and [.filename]#/var/log/logclient.log# on the log server." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:1026 #, no-wrap msgid "Debugging Log Servers" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1032 msgid "" "If no messages are being received on the log server, the cause is most " "likely a network connectivity issue, a hostname resolution issue, or a typo " "in a configuration file. To isolate the cause, ensure that both the logging " "server and the logging client are able to `ping` each other using the " "hostname specified in their [.filename]#/etc/rc.conf#. If this fails, check " "the network cabling, the firewall ruleset, and the hostname entries in the " "DNS server or [.filename]#/etc/hosts# on both the logging server and " "clients. Repeat until the `ping` is successful from both hosts." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1036 msgid "" "If the `ping` succeeds on both hosts but log messages are still not being " "received, temporarily increase logging verbosity to narrow down the " "configuration issue. In the following example, [.filename]#/var/log/" "logclient.log# on the logging server is empty and [.filename]#/var/log/" "messages# on the logging client does not indicate a reason for the failure. " "To increase debugging output, edit the `syslogd_flags` entry on the logging " "server and issue a restart:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1040 #, no-wrap msgid "syslogd_flags=\"-d -a logclient.example.com -v -v\"\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1048 msgid "" "Debugging data similar to the following will flash on the console " "immediately after the restart:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1059 #, no-wrap msgid "" "logmsg: pri 56, flags 4, from logserv.example.com, msg syslogd: restart\n" "syslogd: restarted\n" "logmsg: pri 6, flags 4, from logserv.example.com, msg syslogd: kernel boot file is /boot/kernel/kernel\n" "Logging to FILE /var/log/messages\n" "syslogd: kernel boot file is /boot/kernel/kernel\n" "cvthname(192.168.1.10)\n" "validate: dgram from IP 192.168.1.10, port 514, name logclient.example.com;\n" "rejected in rule 0 due to name mismatch.\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1064 msgid "" "In this example, the log messages are being rejected due to a typo which " "results in a hostname mismatch. The client's hostname should be " "`logclient`, not `logclien`. Fix the typo, issue a restart, and verify the " "results:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1080 #, no-wrap msgid "" "# service syslogd restart\n" "logmsg: pri 56, flags 4, from logserv.example.com, msg syslogd: restart\n" "syslogd: restarted\n" "logmsg: pri 6, flags 4, from logserv.example.com, msg syslogd: kernel boot file is /boot/kernel/kernel\n" "syslogd: kernel boot file is /boot/kernel/kernel\n" "logmsg: pri 166, flags 17, from logserv.example.com,\n" "msg Dec 10 20:55:02 logserv.example.com syslogd: exiting on signal 2\n" "cvthname(192.168.1.10)\n" "validate: dgram from IP 192.168.1.10, port 514, name logclient.example.com;\n" "accepted in rule 0.\n" "logmsg: pri 15, flags 0, from logclient.example.com, msg Dec 11 02:01:28 trhodes: Test message 2\n" "Logging to FILE /var/log/logclient.log\n" "Logging to FILE /var/log/messages\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1083 msgid "" "At this point, the messages are being properly received and placed in the " "correct file." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:1084 #, no-wrap msgid "Security Considerations" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1090 msgid "" "As with any network service, security requirements should be considered " "before implementing a logging server. Log files may contain sensitive data " "about services enabled on the local host, user accounts, and configuration " "data. Network data sent from the client to the server will not be encrypted " "or password protected. If a need for encryption exists, consider using " "package:security/stunnel[], which will transmit the logging data over an " "encrypted tunnel." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1098 msgid "" "Local security is also an issue. Log files are not encrypted during use or " "after log rotation. Local users may access log files to gain additional " "insight into system configuration. Setting proper permissions on log files " "is critical. The built-in log rotator, newsyslog, supports setting " "permissions on newly created and rotated log files. Setting log files to " "mode `600` should prevent unwanted access by local users. Refer to man:" "newsyslog.conf[5] for additional information." msgstr "" #. type: Title == #: documentation/content/en/books/handbook/config/_index.adoc:1100 #, no-wrap msgid "Configuration Files" msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:1102 #, no-wrap msgid "[.filename]#/etc# Layout" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1106 msgid "" "There are a number of directories in which configuration information is " "kept. These include:" msgstr "" #. type: Table #: documentation/content/en/books/handbook/config/_index.adoc:1112 #, no-wrap msgid "[.filename]#/etc#" msgstr "" #. type: Table #: documentation/content/en/books/handbook/config/_index.adoc:1114 #, no-wrap msgid "Generic system-specific configuration information." msgstr "" #. type: Table #: documentation/content/en/books/handbook/config/_index.adoc:1115 #, no-wrap msgid "[.filename]#/etc/defaults#" msgstr "" #. type: Table #: documentation/content/en/books/handbook/config/_index.adoc:1117 #, no-wrap msgid "Default versions of system configuration files." msgstr "" #. type: Table #: documentation/content/en/books/handbook/config/_index.adoc:1118 #, no-wrap msgid "[.filename]#/etc/mail#" msgstr "" #. type: Table #: documentation/content/en/books/handbook/config/_index.adoc:1120 #, no-wrap msgid "Extra man:sendmail[8] configuration and other MTA configuration files." msgstr "" #. type: Table #: documentation/content/en/books/handbook/config/_index.adoc:1121 #, no-wrap msgid "[.filename]#/etc/ppp#" msgstr "" #. type: Table #: documentation/content/en/books/handbook/config/_index.adoc:1123 #, no-wrap msgid "Configuration for both user- and kernel-ppp programs." msgstr "" #. type: Table #: documentation/content/en/books/handbook/config/_index.adoc:1124 #, no-wrap msgid "[.filename]#/usr/local/etc#" msgstr "" #. type: Table #: documentation/content/en/books/handbook/config/_index.adoc:1126 #, no-wrap msgid "Configuration files for installed applications. May contain per-application subdirectories." msgstr "" #. type: Table #: documentation/content/en/books/handbook/config/_index.adoc:1127 #, no-wrap msgid "[.filename]#/usr/local/etc/rc.d#" msgstr "" #. type: Table #: documentation/content/en/books/handbook/config/_index.adoc:1129 #, no-wrap msgid "man:rc[8] scripts for installed applications." msgstr "" #. type: Table #: documentation/content/en/books/handbook/config/_index.adoc:1130 #, no-wrap msgid "[.filename]#/var/db#" msgstr "" #. type: Table #: documentation/content/en/books/handbook/config/_index.adoc:1131 #, no-wrap msgid "Automatically generated system-specific database files, such as the package database and the man:locate[1] database." msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:1133 #, no-wrap msgid "Hostnames" msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:1135 #, no-wrap msgid "[.filename]#/etc/resolv.conf#" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1138 msgid "" "How a FreeBSD system accesses the Internet Domain Name System (DNS) is " "controlled by man:resolv.conf[5]." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1140 msgid "The most common entries to [.filename]#/etc/resolv.conf# are:" msgstr "" #. type: Table #: documentation/content/en/books/handbook/config/_index.adoc:1146 #, no-wrap msgid "`nameserver`" msgstr "" #. type: Table #: documentation/content/en/books/handbook/config/_index.adoc:1148 #, no-wrap msgid "The IP address of a name server the resolver should query. The servers are queried in the order listed with a maximum of three." msgstr "" #. type: Table #: documentation/content/en/books/handbook/config/_index.adoc:1149 #, no-wrap msgid "`search`" msgstr "" #. type: Table #: documentation/content/en/books/handbook/config/_index.adoc:1151 #, no-wrap msgid "Search list for hostname lookup. This is normally determined by the domain of the local hostname." msgstr "" #. type: Table #: documentation/content/en/books/handbook/config/_index.adoc:1152 #, no-wrap msgid "`domain`" msgstr "" #. type: Table #: documentation/content/en/books/handbook/config/_index.adoc:1153 #, no-wrap msgid "The local domain name." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1156 msgid "A typical [.filename]#/etc/resolv.conf# looks like this:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1162 #, no-wrap msgid "" "search example.com\n" "nameserver 147.11.1.11\n" "nameserver 147.11.100.30\n" msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1167 msgid "Only one of the `search` and `domain` options should be used." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1170 msgid "" "When using DHCP, man:dhclient[8] usually rewrites [.filename]#/etc/resolv." "conf# with information received from the DHCP server." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:1171 #, no-wrap msgid "[.filename]#/etc/hosts#" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1176 msgid "" "[.filename]#/etc/hosts# is a simple text database which works in conjunction " "with DNS and NIS to provide host name to IP address mappings. Entries for " "local computers connected via a LAN can be added to this file for simplistic " "naming purposes instead of setting up a man:named[8] server. Additionally, " "[.filename]#/etc/hosts# can be used to provide a local record of Internet " "names, reducing the need to query external DNS servers for commonly accessed " "names." msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1211 #, no-wrap msgid "" "# $FreeBSD$\n" "#\n" "#\n" "# Host Database\n" "#\n" "# This file should contain the addresses and aliases for local hosts that\n" "# share this file. Replace 'my.domain' below with the domainname of your\n" "# machine.\n" "#\n" "# In the presence of the domain name service or NIS, this file may\n" "# not be consulted at all; see /etc/nsswitch.conf for the resolution order.\n" "#\n" "#\n" "::1\t\t\tlocalhost localhost.my.domain\n" "127.0.0.1\t\tlocalhost localhost.my.domain\n" "#\n" "# Imaginary network.\n" "#10.0.0.2\t\tmyname.my.domain myname\n" "#10.0.0.3\t\tmyfriend.my.domain myfriend\n" "#\n" "# According to RFC 1918, you can use the following IP networks for\n" "# private nets which will never be connected to the Internet:\n" "#\n" "#\t10.0.0.0\t- 10.255.255.255\n" "#\t172.16.0.0\t- 172.31.255.255\n" "#\t192.168.0.0\t- 192.168.255.255\n" "#\n" "# In case you want to be able to connect to the Internet, you need\n" "# real official assigned numbers. Do not try to invent your own network\n" "# numbers but instead get one from your network provider (if any) or\n" "# from your regional registry (ARIN, APNIC, LACNIC, RIPE NCC, or AfriNIC.)\n" "#\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1214 msgid "The format of [.filename]#/etc/hosts# is as follows:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1218 #, no-wrap msgid "[Internet address] [official hostname] [alias1] [alias2] ...\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1221 msgid "For example:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1225 #, no-wrap msgid "10.0.0.1 myRealHostname.example.com myRealHostname foobar1 foobar2\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1228 msgid "Consult man:hosts[5] for more information." msgstr "" #. type: Title == #: documentation/content/en/books/handbook/config/_index.adoc:1230 #, no-wrap msgid "Tuning with man:sysctl[8]" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1235 msgid "" "man:sysctl[8] is used to make changes to a running FreeBSD system. This " "includes many advanced options of the TCP/IP stack and virtual memory system " "that can dramatically improve performance for an experienced system " "administrator. Over five hundred system variables can be read and set using " "man:sysctl[8]." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1237 msgid "" "At its core, man:sysctl[8] serves two functions: to read and to modify " "system settings." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1239 msgid "To view all readable variables:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1243 #, no-wrap msgid "% sysctl -a\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1246 msgid "To read a particular variable, specify its name:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1251 #, no-wrap msgid "" "% sysctl kern.maxproc\n" "kern.maxproc: 1044\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1254 msgid "To set a particular variable, use the _variable_=_value_ syntax:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1259 #, no-wrap msgid "" "# sysctl kern.maxfiles=5000\n" "kern.maxfiles: 2088 -> 5000\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1262 msgid "" "Settings of sysctl variables are usually either strings, numbers, or " "booleans, where a boolean is `1` for yes or `0` for no." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1265 msgid "" "To automatically set some variables each time the machine boots, add them to " "[.filename]#/etc/sysctl.conf#. For more information, refer to man:sysctl." "conf[5] and <>." msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:1267 #, no-wrap msgid "[.filename]#sysctl.conf#" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1273 msgid "" "The configuration file for man:sysctl[8], [.filename]#/etc/sysctl.conf#, " "looks much like [.filename]#/etc/rc.conf#. Values are set in a " "`variable=value` form. The specified values are set after the system goes " "into multi-user mode. Not all variables are settable in this mode." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1275 msgid "" "For example, to turn off logging of fatal signal exits and prevent users " "from seeing processes started by other users, the following tunables can be " "set in [.filename]#/etc/sysctl.conf#:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1280 #, no-wrap msgid "" "# Do not log fatal signal exits (e.g., sig 11)\n" "kern.logsigexit=0\n" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1284 #, no-wrap msgid "" "# Prevent users from seeing information about processes that\n" "# are being run under another UID.\n" "security.bsd.see_other_uids=0\n" msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:1287 #, no-wrap msgid "man:sysctl[8] Read-only" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1290 msgid "" "In some cases it may be desirable to modify read-only man:sysctl[8] values, " "which will require a reboot of the system." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1292 msgid "" "For instance, on some laptop models the man:cardbus[4] device will not probe " "memory ranges and will fail with errors similar to:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1297 #, no-wrap msgid "" "cbb0: Could not map register memory\n" "device_probe_and_attach: cbb0 attach returned 12\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1302 msgid "" "The fix requires the modification of a read-only man:sysctl[8] setting. Add " "`hw.pci.allow_unsupported_io_range=1` to [.filename]#/boot/loader.conf# and " "reboot. Now man:cardbus[4] should work properly." msgstr "" #. type: Title == #: documentation/content/en/books/handbook/config/_index.adoc:1304 #, no-wrap msgid "Tuning Disks" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1311 msgid "" "The following section will discuss various tuning mechanisms and options " "which may be applied to disk devices. In many cases, disks with mechanical " "parts, such as SCSI drives, will be the bottleneck driving down the overall " "system performance. While a solution is to install a drive without " "mechanical parts, such as a solid state drive, mechanical drives are not " "going away anytime in the near future. When tuning disks, it is advisable " "to utilize the features of the man:iostat[8] command to test various changes " "to the system. This command will allow the user to obtain valuable " "information on system IO." msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:1312 #, no-wrap msgid "Sysctl Variables" msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:1314 #, no-wrap msgid "`vfs.vmiodirenable`" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1325 msgid "" "The `vfs.vmiodirenable` man:sysctl[8] variable may be set to either `0` " "(off) or `1` (on). It is set to `1` by default. This variable controls how " "directories are cached by the system. Most directories are small, using " "just a single fragment (typically 1 K) in the file system and typically 512 " "bytes in the buffer cache. With this variable turned off, the buffer cache " "will only cache a fixed number of directories, even if the system has a huge " "amount of memory. When turned on, this man:sysctl[8] allows the buffer " "cache to use the VM page cache to cache the directories, making all the " "memory available for caching directories. However, the minimum in-core " "memory used to cache a directory is the physical page size (typically 4 K) " "rather than 512 bytes. Keeping this option enabled is recommended if the " "system is running any services which manipulate large numbers of files. " "Such services can include web caches, large mail systems, and news systems. " "Keeping this option on will generally not reduce performance, even with the " "wasted memory, but one should experiment to find out." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:1326 #, no-wrap msgid "`vfs.write_behind`" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1332 msgid "" "The `vfs.write_behind` man:sysctl[8] variable defaults to `1` (on). This " "tells the file system to issue media writes as full clusters are collected, " "which typically occurs when writing large sequential files. This avoids " "saturating the buffer cache with dirty buffers when it would not benefit I/O " "performance. However, this may stall processes and under certain " "circumstances should be turned off." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:1333 #, no-wrap msgid "`vfs.hirunningspace`" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1339 msgid "" "The `vfs.hirunningspace` man:sysctl[8] variable determines how much " "outstanding write I/O may be queued to disk controllers system-wide at any " "given instance. The default is usually sufficient, but on machines with " "many disks, try bumping it up to four or five _megabytes_. Setting too high " "a value which exceeds the buffer cache's write threshold can lead to bad " "clustering performance. Do not set this value arbitrarily high as higher " "write values may add latency to reads occurring at the same time." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1342 msgid "" "There are various other buffer cache and VM page cache related man:sysctl[8] " "values. Modifying these values is not recommended as the VM system does a " "good job of automatically tuning itself." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:1343 #, no-wrap msgid "`vm.swap_idle_enabled`" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1351 msgid "" "The `vm.swap_idle_enabled` man:sysctl[8] variable is useful in large multi-" "user systems with many active login users and lots of idle processes. Such " "systems tend to generate continuous pressure on free memory reserves. " "Turning this feature on and tweaking the swapout hysteresis (in idle " "seconds) via `vm.swap_idle_threshold1` and `vm.swap_idle_threshold2` " "depresses the priority of memory pages associated with idle processes more " "quickly then the normal pageout algorithm. This gives a helping hand to the " "pageout daemon. Only turn this option on if needed, because the tradeoff is " "essentially pre-page memory sooner rather than later which eats more swap " "and disk bandwidth. In a small system this option will have a determinable " "effect, but in a large system that is already doing moderate paging, this " "option allows the VM system to stage whole processes into and out of memory " "easily." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:1352 #, no-wrap msgid "`hw.ata.wc`" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1360 msgid "" "Turning off IDE write caching reduces write bandwidth to IDE disks, but may " "sometimes be necessary due to data consistency issues introduced by hard " "drive vendors. The problem is that some IDE drives lie about when a write " "completes. With IDE write caching turned on, IDE hard drives write data to " "disk out of order and will sometimes delay writing some blocks indefinitely " "when under heavy disk load. A crash or power failure may cause serious file " "system corruption. Check the default on the system by observing the `hw.ata." "wc` man:sysctl[8] variable. If IDE write caching is turned off, one can set " "this read-only variable to `1` in [.filename]#/boot/loader.conf# in order to " "enable it at boot time." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1362 msgid "For more information, refer to man:ata[4]." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:1363 #, no-wrap msgid "`SCSI_DELAY` (`kern.cam.scsi_delay`)" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1370 msgid "" "The `SCSI_DELAY` kernel configuration option may be used to reduce system " "boot times. The defaults are fairly high and can be responsible for `15` " "seconds of delay in the boot process. Reducing it to `5` seconds usually " "works with modern drives. The `kern.cam.scsi_delay` boot time tunable " "should be used. The tunable and kernel configuration option accept values " "in terms of _milliseconds_ and _not seconds_." msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:1372 #, no-wrap msgid "Soft Updates" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1377 msgid "" "To fine-tune a file system, use man:tunefs[8]. This program has many " "different options. To toggle Soft Updates on and off, use:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1382 #, no-wrap msgid "" "# tunefs -n enable /filesystem\n" "# tunefs -n disable /filesystem\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1386 msgid "" "A file system cannot be modified with man:tunefs[8] while it is mounted. A " "good time to enable Soft Updates is before any partitions have been mounted, " "in single-user mode." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1393 msgid "" "Soft Updates is recommended for UFS file systems as it drastically improves " "meta-data performance, mainly file creation and deletion, through the use of " "a memory cache. There are two downsides to Soft Updates to be aware of. " "First, Soft Updates guarantee file system consistency in the case of a " "crash, but could easily be several seconds or even a minute behind updating " "the physical disk. If the system crashes, unwritten data may be lost. " "Secondly, Soft Updates delay the freeing of file system blocks. If the root " "file system is almost full, performing a major update, such as `make " "installworld`, can cause the file system to run out of space and the update " "to fail." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:1394 #, no-wrap msgid "More Details About Soft Updates" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1398 msgid "" "Meta-data updates are updates to non-content data like inodes or " "directories. There are two traditional approaches to writing a file " "system's meta-data back to disk." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1411 msgid "" "Historically, the default behavior was to write out meta-data updates " "synchronously. If a directory changed, the system waited until the change " "was actually written to disk. The file data buffers (file contents) were " "passed through the buffer cache and backed up to disk later on " "asynchronously. The advantage of this implementation is that it operates " "safely. If there is a failure during an update, meta-data is always in a " "consistent state. A file is either created completely or not at all. If " "the data blocks of a file did not find their way out of the buffer cache " "onto the disk by the time of the crash, man:fsck[8] recognizes this and " "repairs the file system by setting the file length to `0`. Additionally, " "the implementation is clear and simple. The disadvantage is that meta-data " "changes are slow. For example, `rm -r` touches all the files in a directory " "sequentially, but each directory change will be written synchronously to the " "disk. This includes updates to the directory itself, to the inode table, " "and possibly to indirect blocks allocated by the file. Similar " "considerations apply for unrolling large hierarchies using `tar -x`." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1422 msgid "" "The second approach is to use asynchronous meta-data updates. This is the " "default for a UFS file system mounted with `mount -o async`. Since all meta-" "data updates are also passed through the buffer cache, they will be " "intermixed with the updates of the file content data. The advantage of this " "implementation is there is no need to wait until each meta-data update has " "been written to disk, so all operations which cause huge amounts of meta-" "data updates work much faster than in the synchronous case. This " "implementation is still clear and simple, so there is a low risk for bugs " "creeping into the code. The disadvantage is that there is no guarantee for " "a consistent state of the file system If there is a failure during an " "operation that updated large amounts of meta-data, like a power failure or " "someone pressing the reset button, the file system will be left in an " "unpredictable state. There is no opportunity to examine the state of the " "file system when the system comes up again as the data blocks of a file " "could already have been written to the disk while the updates of the inode " "table or the associated directory were not. It is impossible to implement a " "man:fsck[8] which is able to clean up the resulting chaos because the " "necessary information is not available on the disk. If the file system has " "been damaged beyond repair, the only choice is to reformat it and restore " "from backup." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1430 msgid "" "The usual solution for this problem is to implement _dirty region logging_, " "which is also referred to as _journaling_. Meta-data updates are still " "written synchronously, but only into a small region of the disk. Later on, " "they are moved to their proper location. Since the logging area is a small, " "contiguous region on the disk, there are no long distances for the disk " "heads to move, even during heavy operations, so these operations are quicker " "than synchronous updates. Additionally, the complexity of the " "implementation is limited, so the risk of bugs being present is low. A " "disadvantage is that all meta-data is written twice, once into the logging " "region and once to the proper location, so performance \"pessimization\" " "might result. On the other hand, in case of a crash, all pending meta-data " "operations can be either quickly rolled back or completed from the logging " "area after the system comes up again, resulting in a fast file system " "startup." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1446 msgid "" "Kirk McKusick, the developer of Berkeley FFS, solved this problem with Soft " "Updates. All pending meta-data updates are kept in memory and written out " "to disk in a sorted sequence (\"ordered meta-data updates\"). This has the " "effect that, in case of heavy meta-data operations, later updates to an item " "\"catch\" the earlier ones which are still in memory and have not already " "been written to disk. All operations are generally performed in memory " "before the update is written to disk and the data blocks are sorted " "according to their position so that they will not be on the disk ahead of " "their meta-data. If the system crashes, an implicit \"log rewind\" causes " "all operations which were not written to the disk appear as if they never " "happened. A consistent file system state is maintained that appears to be " "the one of 30 to 60 seconds earlier. The algorithm used guarantees that all " "resources in use are marked as such in their blocks and inodes. After a " "crash, the only resource allocation error that occurs is that resources are " "marked as \"used\" which are actually \"free\". man:fsck[8] recognizes this " "situation, and frees the resources that are no longer used. It is safe to " "ignore the dirty state of the file system after a crash by forcibly mounting " "it with `mount -f`. In order to free resources that may be unused, man:" "fsck[8] needs to be run at a later time. This is the idea behind the " "_background man:fsck[8]_: at system startup time, only a _snapshot_ of the " "file system is recorded and man:fsck[8] is run afterwards. All file systems " "can then be mounted \"dirty\", so the system startup proceeds in multi-user " "mode. Then, background man:fsck[8] is scheduled for all file systems where " "this is required, to free resources that may be unused. File systems that " "do not use Soft Updates still need the usual foreground man:fsck[8]." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1453 msgid "" "The advantage is that meta-data operations are nearly as fast as " "asynchronous updates and are faster than _logging_, which has to write the " "meta-data twice. The disadvantages are the complexity of the code, a higher " "memory consumption, and some idiosyncrasies. After a crash, the state of " "the file system appears to be somewhat \"older\". In situations where the " "standard synchronous approach would have caused some zero-length files to " "remain after the man:fsck[8], these files do not exist at all with Soft " "Updates because neither the meta-data nor the file contents have been " "written to disk. Disk space is not released until the updates have been " "written to disk, which may take place some time after running man:rm[1]. " "This may cause problems when installing large amounts of data on a file " "system that does not have enough free space to hold all the files twice." msgstr "" #. type: Title == #: documentation/content/en/books/handbook/config/_index.adoc:1455 #, no-wrap msgid "Tuning Kernel Limits" msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:1458 #, no-wrap msgid "File/Process Limits" msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:1461 #, no-wrap msgid "`kern.maxfiles`" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1466 msgid "" "The `kern.maxfiles` man:sysctl[8] variable can be raised or lowered based " "upon system requirements. This variable indicates the maximum number of " "file descriptors on the system. When the file descriptor table is full, " "`file: table is full` will show up repeatedly in the system message buffer, " "which can be viewed using man:dmesg[8]." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1469 msgid "" "Each open file, socket, or fifo uses one file descriptor. A large-scale " "production server may easily require many thousands of file descriptors, " "depending on the kind and number of services running concurrently." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1475 msgid "" "In older FreeBSD releases, the default value of `kern.maxfiles` is derived " "from `maxusers` in the kernel configuration file. `kern.maxfiles` grows " "proportionally to the value of `maxusers`. When compiling a custom kernel, " "consider setting this kernel configuration option according to the use of " "the system. From this number, the kernel is given most of its pre-defined " "limits. Even though a production machine may not have 256 concurrent users, " "the resources needed may be similar to a high-scale web server." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1481 msgid "" "The read-only man:sysctl[8] variable `kern.maxusers` is automatically sized " "at boot based on the amount of memory available in the system, and may be " "determined at run-time by inspecting the value of `kern.maxusers`. Some " "systems require larger or smaller values of `kern.maxusers` and values of " "`64`, `128`, and `256` are not uncommon. Going above `256` is not " "recommended unless a huge number of file descriptors is needed. Many of the " "tunable values set to their defaults by `kern.maxusers` may be individually " "overridden at boot-time or run-time in [.filename]#/boot/loader.conf#. " "Refer to man:loader.conf[5] and [.filename]#/boot/defaults/loader.conf# for " "more details and some hints." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1489 msgid "" "In older releases, the system will auto-tune `maxusers` if it is set to `0`. " "footnote:[The auto-tuning algorithm sets maxusers equal to the amount of " "memory in the system, with a minimum of 32, and a maximum of 384.]. When " "setting this option, set `maxusers` to at least `4`, especially if the " "system runs Xorg or is used to compile software. The most important table " "set by `maxusers` is the maximum number of processes, which is set to `20 + " "16 * maxusers`. If `maxusers` is set to `1`, there can only be `36` " "simultaneous processes, including the `18` or so that the system starts up " "at boot time and the `15` or so used by Xorg. Even a simple task like " "reading a manual page will start up nine processes to filter, decompress, " "and view it. Setting `maxusers` to `64` allows up to `1044` simultaneous " "processes, which should be enough for nearly all uses. If, however, the " "error is displayed when trying to start another program, or a server is " "running with a large number of simultaneous users, increase the number and " "rebuild." msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1494 msgid "" "`maxusers` does _not_ limit the number of users which can log into the " "machine. It instead sets various table sizes to reasonable values " "considering the maximum number of users on the system and how many processes " "each user will be running." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:1496 #, no-wrap msgid "`kern.ipc.soacceptqueue`" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1503 msgid "" "The `kern.ipc.soacceptqueue` man:sysctl[8] variable limits the size of the " "listen queue for accepting new `TCP` connections. The default value of " "`128` is typically too low for robust handling of new connections on a " "heavily loaded web server. For such environments, it is recommended to " "increase this value to `1024` or higher. A service such as man:sendmail[8], " "or Apache may itself limit the listen queue size, but will often have a " "directive in its configuration file to adjust the queue size. Large listen " "queues do a better job of avoiding Denial of Service (DoS) attacks." msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:1505 #, no-wrap msgid "Network Limits" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1516 msgid "" "The `NMBCLUSTERS` kernel configuration option dictates the amount of network " "Mbufs available to the system. A heavily-trafficked server with a low " "number of Mbufs will hinder performance. Each cluster represents " "approximately 2 K of memory, so a value of `1024` represents `2` megabytes " "of kernel memory reserved for network buffers. A simple calculation can be " "done to figure out how many are needed. A web server which maxes out at " "`1000` simultaneous connections where each connection uses a 6 K receive and " "16 K send buffer, requires approximately 32 MB worth of network buffers to " "cover the web server. A good rule of thumb is to multiply by `2`, so 2x32 " "MB / 2 KB = 64 MB / 2 kB = `32768`. Values between `4096` and `32768` are " "recommended for machines with greater amounts of memory. Never specify an " "arbitrarily high value for this parameter as it could lead to a boot time " "crash. To observe network cluster usage, use `-m` with man:netstat[1]." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1519 msgid "" "The `kern.ipc.nmbclusters` loader tunable should be used to tune this at " "boot time. Only older versions of FreeBSD will require the use of the " "`NMBCLUSTERS` kernel man:config[8] option." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1524 msgid "" "For busy servers that make extensive use of the man:sendfile[2] system call, " "it may be necessary to increase the number of man:sendfile[2] buffers via " "the `NSFBUFS` kernel configuration option or by setting its value in [." "filename]#/boot/loader.conf# (see man:loader[8] for details). A common " "indicator that this parameter needs to be adjusted is when processes are " "seen in the `sfbufa` state. The man:sysctl[8] variable `kern.ipc.nsfbufs` " "is read-only. This parameter nominally scales with `kern.maxusers`, however " "it may be necessary to tune accordingly." msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1528 msgid "" "Even though a socket has been marked as non-blocking, calling man:" "sendfile[2] on the non-blocking socket may result in the man:sendfile[2] " "call blocking until enough ``struct sf_buf``'s are made available." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:1530 #, no-wrap msgid "`net.inet.ip.portrange.*`" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1542 msgid "" "The `net.inet.ip.portrange.*` man:sysctl[8] variables control the port " "number ranges automatically bound to `TCP` and `UDP` sockets. There are " "three ranges: a low range, a default range, and a high range. Most network " "programs use the default range which is controlled by `net.inet.ip.portrange." "first` and `net.inet.ip.portrange.last`, which default to `1024` and `5000`, " "respectively. Bound port ranges are used for outgoing connections and it is " "possible to run the system out of ports under certain circumstances. This " "most commonly occurs when running a heavily loaded web proxy. The port " "range is not an issue when running a server which handles mainly incoming " "connections, such as a web server, or has a limited number of outgoing " "connections, such as a mail relay. For situations where there is a shortage " "of ports, it is recommended to increase `net.inet.ip.portrange.last` " "modestly. A value of `10000`, `20000` or `30000` may be reasonable. " "Consider firewall effects when changing the port range. Some firewalls may " "block large ranges of ports, usually low-numbered ports, and expect systems " "to use higher ranges of ports for outgoing connections. For this reason, it " "is not recommended that the value of `net.inet.ip.portrange.first` be " "lowered." msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:1543 #, no-wrap msgid "Virtual Memory" msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:1545 #, no-wrap msgid "`kern.maxvnodes`" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1552 msgid "" "A vnode is the internal representation of a file or directory. Increasing " "the number of vnodes available to the operating system reduces disk I/O. " "Normally, this is handled by the operating system and does not need to be " "changed. In some cases where disk I/O is a bottleneck and the system is " "running out of vnodes, this setting needs to be increased. The amount of " "inactive and free RAM will need to be taken into account." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1554 msgid "To see the current number of vnodes in use:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1559 #, no-wrap msgid "" "# sysctl vfs.numvnodes\n" "vfs.numvnodes: 91349\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1562 msgid "To see the maximum vnodes:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1567 #, no-wrap msgid "" "# sysctl kern.maxvnodes\n" "kern.maxvnodes: 100000\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1573 msgid "" "If the current vnode usage is near the maximum, try increasing `kern." "maxvnodes` by a value of `1000`. Keep an eye on the number of `vfs." "numvnodes`. If it climbs up to the maximum again, `kern.maxvnodes` will " "need to be increased further. Otherwise, a shift in memory usage as " "reported by man:top[1] should be visible and more memory should be active." msgstr "" #. type: Title == #: documentation/content/en/books/handbook/config/_index.adoc:1575 #, no-wrap msgid "Adding Swap Space" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1579 msgid "" "Sometimes a system requires more swap space. This section describes two " "methods to increase swap space: adding swap to an existing partition or new " "hard drive, and creating a swap file on an existing partition." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1581 msgid "" "For information on how to encrypt swap space, which options exist, and why " "it should be done, refer to crossref:disks[swap-encrypting,“Encrypting " "Swap”]." msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:1583 #, no-wrap msgid "Swap on a New Hard Drive or Existing Partition" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1587 msgid "" "Adding a new hard drive for swap gives better performance than using a " "partition on an existing drive. Setting up partitions and hard drives is " "explained in crossref:disks[disks-adding,“Adding Disks”] while crossref:" "bsdinstall[configtuning-initial,“Designing the Partition Layout”] discusses " "partition layouts and swap partition size considerations." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1590 msgid "Use `swapon` to add a swap partition to the system. For example:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1594 #, no-wrap msgid "# swapon /dev/ada1s1b\n" msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1602 msgid "" "It is possible to use any partition not currently mounted, even if it " "already contains data. Using `swapon` on a partition that contains data " "will overwrite and destroy that data. Make sure that the partition to be " "added as swap is really the intended partition before running `swapon`." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1605 msgid "" "To automatically add this swap partition on boot, add an entry to [." "filename]#/etc/fstab#:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1609 #, no-wrap msgid "/dev/ada1s1b\tnone\tswap\tsw\t0\t0\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1613 msgid "" "See man:fstab[5] for an explanation of the entries in [.filename]#/etc/" "fstab#. More information about `swapon` can be found in man:swapon[8]." msgstr "" #. type: Block title #: documentation/content/en/books/handbook/config/_index.adoc:1615 #: documentation/content/en/books/handbook/config/_index.adoc:1623 #, no-wrap msgid "Creating a Swap File" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1618 msgid "" "These examples create a 512M swap file called [.filename]#/usr/swap0# " "instead of using a partition." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1621 msgid "" "Using swap files requires that the module needed by man:md[4] has either " "been built into the kernel or has been loaded before swap is enabled. See " "crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel] for " "information about building a custom kernel." msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1628 msgid "Create the swap file:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1632 #, no-wrap msgid "# dd if=/dev/zero of=/usr/swap0 bs=1m count=512\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1635 msgid "Set the proper permissions on the new file:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1639 #, no-wrap msgid "# chmod 0600 /usr/swap0\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1642 msgid "" "Inform the system about the swap file by adding a line to [.filename]#/etc/" "fstab#:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1646 #, no-wrap msgid "md\tnone\tswap\tsw,file=/usr/swap0,late\t0\t0\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1649 msgid "" "Swap space will be added on system startup. To add swap space immediately, " "use man:swapon[8]:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1653 #, no-wrap msgid "# swapon -aL\n" msgstr "" #. type: Title == #: documentation/content/en/books/handbook/config/_index.adoc:1658 #, no-wrap msgid "Power and Resource Management" msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1668 msgid "" "It is important to utilize hardware resources in an efficient manner. Power " "and resource management allows the operating system to monitor system limits " "and to possibly provide an alert if the system temperature increases " "unexpectedly. An early specification for providing power management was the " "Advanced Power Management (APM) facility. APM controls the power usage of a " "system based on its activity. However, it was difficult and inflexible for " "operating systems to manage the power usage and thermal properties of a " "system. The hardware was managed by the BIOS and the user had limited " "configurability and visibility into the power management settings. The " "APMBIOS is supplied by the vendor and is specific to the hardware platform. " "An APM driver in the operating system mediates access to the APM Software " "Interface, which allows management of power levels." msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1676 msgid "" "There are four major problems in APM. First, power management is done by " "the vendor-specific BIOS, separate from the operating system. For example, " "the user can set idle-time values for a hard drive in the APMBIOS so that, " "when exceeded, the BIOS spins down the hard drive without the consent of the " "operating system. Second, the APM logic is embedded in the BIOS, and it " "operates outside the scope of the operating system. This means that users " "can only fix problems in the APMBIOS by flashing a new one into the ROM, " "which is a dangerous procedure with the potential to leave the system in an " "unrecoverable state if it fails. Third, APM is a vendor-specific " "technology, meaning that there is a lot of duplication of efforts and bugs " "found in one vendor's BIOS may not be solved in others. Lastly, the APMBIOS " "did not have enough room to implement a sophisticated power policy or one " "that can adapt well to the purpose of the machine." msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1681 msgid "" "The Plug and Play BIOS (PNPBIOS) was unreliable in many situations. PNPBIOS " "is 16-bit technology, so the operating system has to use 16-bit emulation in " "order to interface with PNPBIOS methods. FreeBSD provides an APM driver as " "APM should still be used for systems manufactured at or before the year " "2000. The driver is documented in man:apm[4]." msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1685 msgid "" "The successor to APM is the Advanced Configuration and Power Interface " "(ACPI). ACPI is a standard written by an alliance of vendors to provide an " "interface for hardware resources and power management. It is a key element " "in _Operating System-directed configuration and Power Management_ as it " "provides more control and flexibility to the operating system." msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1688 msgid "" "This chapter demonstrates how to configure ACPI on FreeBSD. It then offers " "some tips on how to debug ACPI and how to submit a problem report containing " "debugging information so that developers can diagnosis and fix ACPI issues." msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:1690 #, no-wrap msgid "Configuring ACPI" msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1695 msgid "" "In FreeBSD the man:acpi[4] driver is loaded by default at system boot and " "should _not_ be compiled into the kernel. This driver cannot be unloaded " "after boot because the system bus uses it for various hardware " "interactions. However, if the system is experiencing problems, ACPI can be " "disabled altogether by rebooting after setting `hint.acpi.0.disabled=\"1\"` " "in [.filename]#/boot/loader.conf# or by setting this variable at the loader " "prompt, as described in crossref:boot[boot-loader,“Stage Three”]." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1700 msgid "" "ACPI and APM cannot coexist and should be used separately. The last one to " "load will terminate if the driver notices the other is running." msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1705 msgid "" "ACPI can be used to put the system into a sleep mode with `acpiconf`, the `-" "s` flag, and a number from `1` to `5`. Most users only need `1` (quick " "suspend to RAM) or `3` (suspend to RAM). Option `5` performs a soft-off " "which is the same as running `halt -p`." msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1710 msgid "" "The man:acpi_video[4] driver uses link:https://uefi.org/specs/ACPI/6.4/" "Apx_B_Video_Extensions/Apx_B_Video_Extensions.html[ACPI Video Extensions] to " "control display switching and backlight brightness. It must be loaded after " "any of the DRM kernel modules. After loading the driver, the kbd:[Fn] " "brightness keys will change the brightness of the screen. It is possible to " "check the ACPI events by inspecting [.filename]#/var/run/devd.pipe#:" msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1718 msgid "" "... # cat /var/run/devd.pipe !system=ACPI subsystem=Video type=brightness " "notify=62 !system=ACPI subsystem=Video type=brightness notify=63 !" "system=ACPI subsystem=Video type=brightness notify=64 ..." msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1721 msgid "" "Other options are available using `sysctl`. Refer to man:acpi[4] and man:" "acpiconf[8] for more information." msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:1723 #, no-wrap msgid "Common Problems" msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1730 msgid "" "ACPI is present in all modern computers that conform to the ia32 (x86) and " "amd64 (AMD) architectures. The full standard has many features including " "CPU performance management, power planes control, thermal zones, various " "battery systems, embedded controllers, and bus enumeration. Most systems " "implement less than the full standard. For instance, a desktop system " "usually only implements bus enumeration while a laptop might have cooling " "and battery management support as well. Laptops also have suspend and " "resume, with their own associated complexity." msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1734 msgid "" "An ACPI-compliant system has various components. The BIOS and chipset " "vendors provide various fixed tables, such as FADT, in memory that specify " "things like the APIC map (used for SMP), config registers, and simple " "configuration values. Additionally, a bytecode table, the Differentiated " "System Description Table DSDT, specifies a tree-like name space of devices " "and methods." msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1740 msgid "" "The ACPI driver must parse the fixed tables, implement an interpreter for " "the bytecode, and modify device drivers and the kernel to accept information " "from the ACPI subsystem. For FreeBSD, Intel(R) has provided an interpreter " "(ACPI-CA) that is shared with Linux(R) and NetBSD. The path to the ACPI-CA " "source code is [.filename]#src/sys/contrib/dev/acpica#. The glue code that " "allows ACPI-CA to work on FreeBSD is in [.filename]#src/sys/dev/acpica/" "Osd#. Finally, drivers that implement various ACPI devices are found in [." "filename]#src/sys/dev/acpica#." msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1744 msgid "" "For ACPI to work correctly, all the parts have to work correctly. Here are " "some common problems, in order of frequency of appearance, and some possible " "workarounds or fixes. If a fix does not resolve the issue, refer to <> for instructions on how to submit a bug report." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:1745 #, no-wrap msgid "Mouse Issues" msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1749 msgid "" "In some cases, resuming from a suspend operation will cause the mouse to " "fail. A known work around is to add `hint.psm.0.flags=\"0x3000\"` to [." "filename]#/boot/loader.conf#." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:1750 #, no-wrap msgid "Suspend/Resume" msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1756 msgid "" "ACPI has three suspend to RAM (STR) states, `S1`-`S3`, and one suspend to " "disk state (STD), called `S4`. STD can be implemented in two separate " "ways. The ``S4``BIOS is a BIOS-assisted suspend to disk and ``S4``OS is " "implemented entirely by the operating system. The normal state the system " "is in when plugged in but not powered up is \"soft off\" (`S5`)." msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1759 msgid "" "Use `sysctl hw.acpi` to check for the suspend-related items. These example " "results are from a Thinkpad:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1764 #, no-wrap msgid "" "hw.acpi.supported_sleep_state: S3 S4 S5\n" "hw.acpi.s4bios: 0\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1768 msgid "" "Use `acpiconf -s` to test `S3`, `S4`, and `S5`. An `s4bios` of one (`1`) " "indicates ``S4``BIOS support instead of `S4` operating system support." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1774 msgid "" "When testing suspend/resume, start with `S1`, if supported. This state is " "most likely to work since it does not require much driver support. No one " "has implemented `S2`, which is similar to `S1`. Next, try `S3`. This is " "the deepest STR state and requires a lot of driver support to properly " "reinitialize the hardware." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1777 msgid "" "A common problem with suspend/resume is that many device drivers do not " "save, restore, or reinitialize their firmware, registers, or device memory " "properly. As a first attempt at debugging the problem, try:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1783 #, no-wrap msgid "" "# sysctl debug.bootverbose=1\n" "# sysctl debug.acpi.suspend_bounce=1\n" "# acpiconf -s 3\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1788 msgid "" "This test emulates the suspend/resume cycle of all device drivers without " "actually going into `S3` state. In some cases, problems such as losing " "firmware state, device watchdog time out, and retrying forever, can be " "captured with this method. Note that the system will not really enter `S3` " "state, which means devices may not lose power, and many will work fine even " "if suspend/resume methods are totally missing, unlike real `S3` state." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1790 msgid "" "If the previous test worked, on a laptop it is possible to configure the " "system to suspend into `S3` on lid close and resume when it is open back " "again:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1794 #, no-wrap msgid "# sysctl hw.acpi.lid_switch_state=S3\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1797 msgid "This change can be made persistent across reboots:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1801 #, no-wrap msgid "# echo 'hw.acpi.lid_switch_state=S3' >> /etc/sysctl.conf\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1804 msgid "" "Harder cases require additional hardware, such as a serial port and cable " "for debugging through a serial console, a Firewire port and cable for using " "man:dcons[4], and kernel debugging skills." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1811 msgid "" "To help isolate the problem, unload as many drivers as possible. If it " "works, narrow down which driver is the problem by loading drivers until it " "fails again. Typically, binary drivers like [.filename]#nvidia.ko#, display " "drivers, and USB will have the most problems while Ethernet interfaces " "usually work fine. If drivers can be properly loaded and unloaded, automate " "this by putting the appropriate commands in [.filename]#/etc/rc.suspend# and " "[.filename]#/etc/rc.resume#. Try setting `hw.acpi.reset_video` to `1` if " "the display is messed up after resume. Try setting longer or shorter values " "for `hw.acpi.sleep_delay` to see if that helps." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1817 msgid "" "Try loading a recent Linux(R) distribution to see if suspend/resume works on " "the same hardware. If it works on Linux(R), it is likely a FreeBSD driver " "problem. Narrowing down which driver causes the problem will assist " "developers in fixing the problem. Since the ACPI maintainers rarely " "maintain other drivers, such as sound or ATA, any driver problems should " "also be posted to the {freebsd-current} and mailed to the driver " "maintainer. Advanced users can include debugging man:printf[3]s in a " "problematic driver to track down where in its resume function it hangs." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1821 msgid "" "Finally, try disabling ACPI and enabling APM instead. If suspend/resume " "works with APM, stick with APM, especially on older hardware (pre-2000). It " "took vendors a while to get ACPI support correct and older hardware is more " "likely to have BIOS problems with ACPI." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:1822 #, no-wrap msgid "System Hangs" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1826 msgid "" "Most system hangs are a result of lost interrupts or an interrupt storm. " "Chipsets may have problems based on boot, how the BIOS configures interrupts " "before correctness of the APIC (MADT) table, and routing of the System " "Control Interrupt (SCI)." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1830 msgid "" "Interrupt storms can be distinguished from lost interrupts by checking the " "output of `vmstat -i` and looking at the line that has `acpi0`. If the " "counter is increasing at more than a couple per second, there is an " "interrupt storm. If the system appears hung, try breaking to DDB (kbd:" "[CTRL+ALT+ESC] on console) and type `show interrupts`." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1832 msgid "" "When dealing with interrupt problems, try disabling APIC support with `hint." "apic.0.disabled=\"1\"` in [.filename]#/boot/loader.conf#." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:1833 #, no-wrap msgid "Panics" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1840 msgid "" "Panics are relatively rare for ACPI and are the top priority to be fixed. " "The first step is to isolate the steps to reproduce the panic, if possible, " "and get a backtrace. Follow the advice for enabling `options DDB` and " "setting up a serial console in crossref:serialcomms[serialconsole-" "ddb,“Entering the DDB Debugger from the Serial Line”] or setting up a dump " "partition. To get a backtrace in DDB, use `tr`. When handwriting the " "backtrace, get at least the last five and the top five lines in the trace." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1844 msgid "" "Then, try to isolate the problem by booting with ACPI disabled. If that " "works, isolate the ACPI subsystem by using various values of `debug.acpi." "disable`. See man:acpi[4] for some examples." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:1845 #, no-wrap msgid "System Powers Up After Suspend or Shutdown" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1851 msgid "" "First, try setting `hw.acpi.disable_on_poweroff=\"0\"` in [.filename]#/boot/" "loader.conf#. This keeps ACPI from disabling various events during the " "shutdown process. Some systems need this value set to `1` (the default) for " "the same reason. This usually fixes the problem of a system powering up " "spontaneously after a suspend or poweroff." msgstr "" #. type: Title ==== #: documentation/content/en/books/handbook/config/_index.adoc:1853 #, no-wrap msgid "BIOS Contains Buggy Bytecode" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1857 msgid "" "Some BIOS vendors provide incorrect or buggy bytecode. This is usually " "manifested by kernel console messages like this:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1862 #, no-wrap msgid "" "ACPI-1287: *** Error: Method execution failed [\\\\_SB_.PCI0.LPC0.FIGD._STA] \\\\\n" "(Node 0xc3f6d160), AE_NOT_FOUND\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1866 msgid "" "Often, these problems may be resolved by updating the BIOS to the latest " "revision. Most console messages are harmless, but if there are other " "problems, like the battery status is not working, these messages are a good " "place to start looking for problems." msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:1867 #, no-wrap msgid "Overriding the Default AML" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1871 msgid "" "The BIOS bytecode, known as ACPI Machine Language (AML), is compiled from a " "source language called ACPI Source Language (ASL). The AML is found in the " "table known as the Differentiated System Description Table (DSDT)." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1876 msgid "" "The goal of FreeBSD is for everyone to have working ACPI without any user " "intervention. Workarounds are still being developed for common mistakes " "made by BIOS vendors. The Microsoft(R) interpreter ([.filename]#acpi.sys# " "and [.filename]#acpiec.sys#) does not strictly check for adherence to the " "standard, and thus many BIOS vendors who only test ACPI under Windows(R) " "never fix their ASL. FreeBSD developers continue to identify and document " "which non-standard behavior is allowed by Microsoft(R)'s interpreter and " "replicate it so that FreeBSD can work without forcing users to fix the ASL." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1879 msgid "" "To help identify buggy behavior and possibly fix it manually, a copy can be " "made of the system's ASL. To copy the system's ASL to a specified file " "name, use `acpidump` with `-t`, to show the contents of the fixed tables, " "and `-d`, to disassemble the AML:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1883 #, no-wrap msgid "# acpidump -td > my.asl\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1887 msgid "" "Some AML versions assume the user is running Windows(R). To override this, " "set `hw.acpi.osname=_\"Windows 2009\"_` in [.filename]#/boot/loader.conf#, " "using the most recent Windows(R) version listed in the ASL." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1891 msgid "" "Other workarounds may require [.filename]#my.asl# to be customized. If this " "file is edited, compile the new ASL using the following command. Warnings " "can usually be ignored, but errors are bugs that will usually prevent ACPI " "from working correctly." msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1895 #, no-wrap msgid "# iasl -f my.asl\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1899 msgid "" "Including `-f` forces creation of the AML, even if there are errors during " "compilation. Some errors, such as missing return statements, are " "automatically worked around by the FreeBSD interpreter." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1902 msgid "" "The default output filename for `iasl` is [.filename]#DSDT.aml#. Load this " "file instead of the BIOS's buggy copy, which is still present in flash " "memory, by editing [.filename]#/boot/loader.conf# as follows:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1907 #, no-wrap msgid "" "acpi_dsdt_load=\"YES\"\n" "acpi_dsdt_name=\"/boot/DSDT.aml\"\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1911 msgid "" "Be sure to copy [.filename]#DSDT.aml# to [.filename]#/boot#, then reboot the " "system. If this fixes the problem, send a man:diff[1] of the old and new " "ASL to {freebsd-acpi} so that developers can work around the buggy behavior " "in [.filename]#acpica#." msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:1913 #, no-wrap msgid "Getting and Submitting Debugging Info" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1921 msgid "" "The ACPI driver has a flexible debugging facility. A set of subsystems and " "the level of verbosity can be specified. The subsystems to debug are " "specified as layers and are broken down into components " "(`ACPI_ALL_COMPONENTS`) and ACPI hardware support (`ACPI_ALL_DRIVERS`). The " "verbosity of debugging output is specified as the level and ranges from just " "report errors (`ACPI_LV_ERROR`) to everything (`ACPI_LV_VERBOSE`). The " "level is a bitmask so multiple options can be set at once, separated by " "spaces. In practice, a serial console should be used to log the output so " "it is not lost as the console message buffer flushes. A full list of the " "individual layers and levels is found in man:acpi[4]." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1925 msgid "" "Debugging output is not enabled by default. To enable it, add `options " "ACPI_DEBUG` to the custom kernel configuration file if ACPI is compiled into " "the kernel. Add `ACPI_DEBUG=1` to [.filename]#/etc/make.conf# to enable it " "globally. If a module is used instead of a custom kernel, recompile just " "the [.filename]#acpi.ko# module as follows:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1929 #, no-wrap msgid "# cd /sys/modules/acpi/acpi && make clean && make ACPI_DEBUG=1\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1933 msgid "" "Copy the compiled [.filename]#acpi.ko# to [.filename]#/boot/kernel# and add " "the desired level and layer to [.filename]#/boot/loader.conf#. The entries " "in this example enable debug messages for all ACPI components and hardware " "drivers and output error messages at the least verbose level:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1938 #, no-wrap msgid "" "debug.acpi.layer=\"ACPI_ALL_COMPONENTS ACPI_ALL_DRIVERS\"\n" "debug.acpi.level=\"ACPI_LV_ERROR\"\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1943 msgid "" "If the required information is triggered by a specific event, such as a " "suspend and then resume, do not modify [.filename]#/boot/loader.conf#. " "Instead, use `sysctl` to specify the layer and level after booting and " "preparing the system for the specific event. The variables which can be set " "using `sysctl` are named the same as the tunables in [.filename]#/boot/" "loader.conf#." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1945 msgid "" "Once the debugging information is gathered, it can be sent to {freebsd-acpi} " "so that it can be used by the FreeBSD ACPI maintainers to identify the root " "cause of the problem and to develop a solution." msgstr "" #. type: delimited block = 4 #: documentation/content/en/books/handbook/config/_index.adoc:1949 msgid "" "Before submitting debugging information to this mailing list, ensure the " "latest BIOS version is installed and, if available, the embedded controller " "firmware version." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1952 msgid "When submitting a problem report, include the following information:" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1954 msgid "" "Description of the buggy behavior, including system type, model, and " "anything that causes the bug to appear. Note as accurately as possible when " "the bug began occurring if it is new." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1955 msgid "" "The output of `dmesg` after running `boot -v`, including any error messages " "generated by the bug." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1956 msgid "" "The `dmesg` output from `boot -v` with ACPI disabled, if disabling ACPI " "helps to fix the problem." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1957 msgid "" "Output from `sysctl hw.acpi`. This lists which features the system offers." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1958 msgid "" "The URL to a pasted version of the system's ASL. Do _not_ send the ASL " "directly to the list as it can be very large. Generate a copy of the ASL by " "running this command:" msgstr "" #. type: delimited block . 4 #: documentation/content/en/books/handbook/config/_index.adoc:1962 #, no-wrap msgid "# acpidump -dt > name-system.asl\n" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1966 msgid "" "Substitute the login name for _name_ and manufacturer/model for _system_. " "For example, use [.filename]#njl-FooCo6000.asl#." msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1973 msgid "" "Most FreeBSD developers watch the {freebsd-current}, but one should submit " "problems to {freebsd-acpi} to be sure it is seen. Be patient when waiting " "for a response. If the bug is not immediately apparent, submit a bug " "report. When entering a PR, include the same information as requested " "above. This helps developers to track the problem and resolve it. Do not " "send a PR without emailing {freebsd-acpi} first as it is likely that the " "problem has been reported before." msgstr "" #. type: Title === #: documentation/content/en/books/handbook/config/_index.adoc:1975 #, no-wrap msgid "References" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1978 msgid "More information about ACPI may be found in the following locations:" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1980 msgid "" "The FreeBSD ACPI Mailing List Archives (https://lists.freebsd.org/pipermail/" "freebsd-acpi/[https://lists.freebsd.org/pipermail/freebsd-acpi/])" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1981 msgid "" -"The ACPI 2.0 Specification (http://acpi.info/spec.htm[http://acpi.info/spec." -"htm])" +"The https://uefi.org/specifications#ACPI[ACPI Specification]" msgstr "" #. type: Plain text #: documentation/content/en/books/handbook/config/_index.adoc:1981 msgid "" "man:acpi[4], man:acpi_thermal[4], man:acpidump[8], man:iasl[8], and man:" "acpidb[8]" msgstr "" diff --git a/documentation/content/fr/books/handbook/config/_index.adoc b/documentation/content/fr/books/handbook/config/_index.adoc index 89f66d41a6..76d68d5dcf 100644 --- a/documentation/content/fr/books/handbook/config/_index.adoc +++ b/documentation/content/fr/books/handbook/config/_index.adoc @@ -1,1364 +1,1364 @@ --- title: Chapitre 11. Configuration et optimisation part: Partie III. Administration Système prev: books/handbook/partiii next: books/handbook/boot showBookMenu: true weight: 15 path: "/books/handbook/" --- [[config-tuning]] = Configuration et optimisation :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 11 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/config/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[config-synopsis]] == Synopsis La configuration correcte d'un système peut sensiblement réduire la quantité de travail impliquée dans la maintenance et la mise à jour. Ce chapitre décrit certains des aspects de la configuration des systèmes FreeBSD. Ce chapitre décrira également certains paramètres qui peuvent être modifiés pour configurer un système FreeBSD pour des performances optimales. Après la lecture de ce chapitre, vous saurez: * Les bases de la configuration du fichier [.filename]#rc.conf# et des fichiers de démarrage [.filename]#/usr/local/etc/rc.d#. * Comment configurer et tester une carte réseau. * Comment configurer des hôtes virtuels sur vos périphériques réseau. * Comment utiliser les divers fichiers de configuration du répertoire [.filename]#/etc#. * Comment optimiser FreeBSD en utilisant les variables `sysctl`. * Comment optimiser les performances des disques et modifier les limitations du noyau. Avant de lire ce chapitre, vous devrez: * Comprendre les fondements d'UNIX(R) et de FreeBSD (crossref:basics[basics,Quelques bases d'UNIX]). * Etre familier avec la configuration et la compilation du noyau (crossref:kernelconfig[kernelconfig,Configurer le noyau de FreeBSD]). [[configtuning-core-configuration]] == Configuration principale L'emplacement principal pour les données de configuration du système est le fichier [.filename]#/etc/rc.conf#. Ce fichier contient une large gamme d'informations de configuration, principalement utilisées au démarrage du système pour configurer ce dernier. Son nom le sous-entend; c'est l'information de configuration pour les fichiers [.filename]#rc*#. Un administrateur devrait ajouter des entrées dans le fichier [.filename]#rc.conf# pour remplacer les valeurs par défaut du fichier [.filename]#/etc/defaults/rc.conf#. Les fichiers de valeurs par défaut ne devraient pas être copiés directement tels quels dans [.filename]#/etc# - ils contiennent des valeurs par défaut, et non pas des exemples. Tout changement spécifique au système devrait être fait dans le fichier [.filename]#rc.conf#. Un certain nombre de stratégies peuvent être appliquées dans le cas d'applications en grappe pour séparer la configuration d'un site de celle d'un système afin de réduire le travail d'administration. L'approche recommandée est de placer la configuration propre au site dans le fichier [.filename]#/etc/rc.conf.local#. Par exemple: * [.filename]#/etc/rc.conf#: + [.programlisting] .... sshd_enable="YES" keyrate="fast" defaultrouter="10.1.1.254" .... * [.filename]#/etc/rc.conf.local#: + [.programlisting] .... hostname="node1.example.org" ifconfig_fxp0="inet 10.1.1.1/8" .... Le fichier [.filename]#rc.conf# peut être distribué à l'ensemble des systèmes en utilisant `rsync` ou un programme semblable, tandis que le fichier [.filename]#rc.conf.local# reste unique. Mettre à jour le système en employant man:sysinstall[8] ou `make world` n'écrasera pas le fichier [.filename]#rc.conf#, les informations de configuration du système ne seront donc pas perdues. Le fichier de configuration [.filename]#/etc/rc.conf# est analysé par man:sh[1]. Cela permet aux administrateurs système d'ajouter un certain niveau de logique à ce fichier, ce qui peut aider à créer des scénaris de configuration complexes. Veuillez consulter man:rc.conf[5] pour plus d'information sur ce sujet. [[configtuning-appconfig]] == Configuration des applications Généralement, les applications installées ont leurs propres fichiers de configuration, avec leur propre syntaxe, etc... Il est important que ces fichiers soient séparés du système de base, de sorte qu'ils soient facilement localisables et gérables par les outils de gestion des logiciels installés. Ces fichiers sont généralement installés dans le répertoire [.filename]#/usr/local/etc#. Dans le cas où une application possède un grand nombre de fichiers de configuration, un sous-répertoire sera créé pour les héberger. Normalement, quand un logiciel porté ou pré-compilé est installé, des exemples de fichiers de configuration sont également installés. Ces derniers sont généralement identifiés par un suffixe ".default". Si aucun fichier de configuration n'existe pour l'application, on les créera en copiant les fichiers [.filename]#.default#. Par exemple, considérez le contenu du répertoire [.filename]#/usr/local/etc/apache#: [.programlisting] .... -rw-r--r-- 1 root wheel 2184 May 20 1998 access.conf -rw-r--r-- 1 root wheel 2184 May 20 1998 access.conf.default -rw-r--r-- 1 root wheel 9555 May 20 1998 httpd.conf -rw-r--r-- 1 root wheel 9555 May 20 1998 httpd.conf.default -rw-r--r-- 1 root wheel 12205 May 20 1998 magic -rw-r--r-- 1 root wheel 12205 May 20 1998 magic.default -rw-r--r-- 1 root wheel 2700 May 20 1998 mime.types -rw-r--r-- 1 root wheel 2700 May 20 1998 mime.types.default -rw-r--r-- 1 root wheel 7980 May 20 1998 srm.conf -rw-r--r-- 1 root wheel 7933 May 20 1998 srm.conf.default .... Les tailles des fichiers indiquent que seul le fichier [.filename]#srm.conf# a été modifié. Une mise à jour, plus tard, du logiciel Apache ne devrait pas écraser le fichier modifié. [[configtuning-starting-services]] == Démarrer des services Nombreux sont les utilisateurs qui choisissent d'installer des logiciels tierce partie sous FreeBSD à partir du catalogue des logiciels portés. Dans de nombreuses situations, il peut être nécessaire de configurer le logiciel de manière à ce qu'il soit lancé au démarrage du système. Des services comme package:mail/postfix[] ou package:www/apache22[] sont deux exemples de logiciels parmi tant d'autres qui peuvent être lancés à l'initialisation du système. Cette section explique les procédures disponibles pour démarrer certains logiciels tierce partie. Sous FreeBSD, la plupart des services offerts, comme man:cron[8], sont lancés par l'intermédiaire des procédures de démarrage du système. Ces procédures peuvent varier en fonction de la version de FreeBSD, ou du fournisseur; cependant, l'aspect le plus important à considérer est que leur configuration de démarrage peut être gérée à l'aide de procédures de démarrage simples. === Configuration étendue des applications Maintenant que FreeBSD dispose du système [.filename]#rc.d#, la configuration du démarrage des applications est plus simple, et propose plus de possibilités. En utilisant les mots clés présentés dans la section sur le système <>, les applications peuvent désormais être paramétrées pour démarrer après certains services, par exemple le DNS, des paramètres supplémentaires peuvent être passés par l'intermédiaire de [.filename]#rc.conf# au lieu d'utiliser des paramètres fixes dans les procédures de démarrage, etc. Une procédure de base pourra ressembler à ce qui suit: [.programlisting] .... #!/bin/sh # # PROVIDE: utility # REQUIRE: DAEMON # KEYWORD: shutdown . /etc/rc.subr name=utility rcvar=utility_enable command="/usr/local/sbin/utility" load_rc_config $name # # DO NOT CHANGE THESE DEFAULT VALUES HERE # SET THEM IN THE /etc/rc.conf FILE # utility_enable=${utility_enable-"NO"} pidfile=${utility_pidfile-"/var/run/utility.pid"} run_rc_command "$1" .... Cette procédure s'assurera que l'application utility sera lancée après le le service `DAEMON`. Elle fournie également une méthode de suivi du PID, ou encore ID (identifiant) de processus. Cette application pourra alors avoir la ligne suivante la concernant dans le fichier [.filename]#/etc/rc.conf#: [.programlisting] .... utility_enable="YES" .... Cette méthode permet également une manipulation plus aisée des arguments en ligne de commande, l'inclusion des fonctions offertes par défaut dans [.filename]#/etc/rc.subr#, offre une compatibilité avec l'utilitaire man:rcorder[8] et fournie une configuration plus aisée par l'intermédiaire du fichier [.filename]#rc.conf#. === Utiliser des services pour démarrer d'autres services Certains services, comme les serveurs POP3, IMAP, etc., peuvent être démarrés en utilisant man:inetd[8]. Cela implique d'installer le service à partir du catalogue des logiciels portés et avec une ligne de configuration ajoutée au fichier [.filename]#/etc/inetd.conf#, ou en décommentant une des lignes de configuration déjà présentes. L'utilisation d'inetd et sa configuration sont décrits en profondeur dans la section concernant crossref:network-servers[network-inetd,inetd]. Dans certains cas, il peut être plus approprié d'utiliser le "daemon" man:cron[8] pour démarrer des services. Cette approche présente un certain nombre d'avantages parce que `cron` exécute ces processus sous les privilèges du propriétaire de la table [.filename]#crontab#. Cela permet aux utilisateurs normaux de lancer et maintenir certaines applications. L'utilitaire `cron` offre une fonction unique, `@reboot`, qui peut être utilisée en remplacement de la date d'exécution. Cela provoquera l'exécution de la tâche quand man:cron[8] est lancé, normalement lors de l'initialisation du système. [[configtuning-cron]] == Configuration de l'utilitaire `cron` Un des utilitaires les plus importants de FreeBSD est man:cron[8]. L'utilitaire `cron` tourne en arrière plan et contrôle constamment le fichier [.filename]#/etc/crontab#. L'utilitaire `cron` consulte également le répertoire [.filename]#/var/cron/tabs#, à la recherche de nouveaux fichiers [.filename]#crontab#. Ces fichiers [.filename]#crontab# conservent les informations sur les tâches que `cron` est censé exécuter à des moments donnés. L'utilitaire `cron` utilise deux types différents de fichiers de configuration, le fichier [.filename]#crontab# système et les [.filename]##crontab##s des utilisateurs. Ces deux formats diffèrent à partir du sixième champ. Dans le fichier [.filename]#crontab# système, `cron` exécutera la commande en tant que l'utilisateur indiqué dans le sixième champ. Dans le fichier [.filename]#crontab# d'un utilisateur, toutes les commandes sont exécutées sous l'utilisateur qui a créé ce fichier [.filename]#crontab#, aussi le sixième champ est le dernier champ; c'est un aspect sécurité important. Le dernier champ est toujours la commande à exécuter. [NOTE] ==== Les fichiers [.filename]#crontab# utilisateur permettent aux utilisateurs de planifier l'exécution de tâches sans avoir besoin des privilèges du super-utilisateur `root`. Les commandes contenues dans le fichier [.filename]#crontab# d'un utilisateur s'exécutent avec les privilèges de l'utilisateur auquel appartient ce fichier. Le super-utilisateur `root` peut posséder un fichier [.filename]#crontab# utilisateur comme tout autre utilisateur. Ce fichier est différent de [.filename]#/etc/crontab# (le [.filename]#crontab# système). Etant donné que le fichier [.filename]#crontab# système invoque les commandes spécifiées en tant que `root`, il n'y a généralement pas besoin d'un fichier [.filename]#crontab# utilisateur pour `root`. ==== Examinons le fichier [.filename]#/etc/crontab# (fichier [.filename]#crontab# système): [.programlisting] .... # /etc/crontab - root's crontab for FreeBSD # # $FreeBSD: src/etc/crontab,v 1.32 2002/11/22 16:13:39 tom Exp $ ## <.> # SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin <.> HOME=/var/log # # #minute heure date mois jour utilisateur commande <.> # # */5 * * * * root /usr/libexec/atrun <.> .... <.> Comme pour la plupart des fichiers de configuration de FreeBSD, le caractère `#` indique un commentaire. Un commentaire peut être ajouté dans le fichier comme rappel de ce que fait une action bien précise et pourquoi elle est effectuée. Les commentaires ne peuvent être situés sur la même ligne qu'une commande ou sinon ils seront interprétés comme faisant partie de la commande; ils doivent se trouver sur une nouvelle ligne. Les lignes vides sont ignorées. <.> Tout d'abord, les variables d'environnement doivent être définies. Le caractère égal (`=`) est utilisé pour définir tout paramètre concernant l'environnement, comme dans notre exemple où il a été utilisé pour les variables `SHELL`, `PATH`, et `HOME`. Si la ligne concernant l'interpréteur de commande est omise, `cron` utilisera celui par défaut, qui est `sh`. Si la variable `PATH` est omise, il n'y aura pas de valeur par défaut utilisée et l'emplacement des fichiers devra être absolu. Si `HOME` est omise, `cron` utilisera le répertoire personnel de l'utilisateur qui l'invoque. <.> Cette ligne définie un total de sept champs. Sont listés ici les valeurs `minute`, `heure`, `date`, `mois`, `jour`, `utilisateur`, et `commande`. Ces champs sont relativement explicites. `minute` représente l'heure en minute à laquelle la commande sera exécutée. L'option `heure` est semblable à l'option `minute`, mais en heures. Le champ `date` précise le jour dans le mois. `mois` est similaire à `heure` et `minute` mais désigne le mois. L'option `jour` représente le jour de la semaine. Tous ces champs doivent être des valeurs numériques, et respecter un format horaire de vingt quatre heures. Le champ `utilisateur` est spécial, et n'existe que dans le fichier [.filename]#/etc/crontab#. Ce champ précise sous quel utilisateur sera exécutée la commande. Le dernier champ désigne la commande à exécuter. <.> Cette dernière ligne définie les valeurs discutées ci-dessus. Nous avons ici `\*/5` suivi de plusieurs caractères `\*`. Ces caractères `*` signifient "premier-dernier", et peuvent être interprétés comme voulant dire à _chaque_ instance. Aussi, d'après cette ligne, il apparaît que la commande `atrun` sera invoquée par l'utilisateur `root` toutes les cinq minutes indépendamment du jour ou du mois. Pour plus d'informations sur la commande `atrun`, consultez la page de manuel de man:atrun[8]. N'importe quel nombre d'indicateur peut être passé à ces commandes; cependant, les commandes qui s'étendent sur de multiples lignes doivent être "cassées" avec le caractère, contre-oblique `\`, de continuation de lignes. Ceci est la configuration de base pour chaque fichier [.filename]#crontab#, bien qu'il y ait une différence dans celui présenté ici. Le sixième champ, où est précisé le nom d'utilisateur, n'existe que dans le fichier système [.filename]#/etc/crontab#. Ce champ devrait être omis pour les fichiers [.filename]#crontab# d'utilisateur. [[configtuning-installcrontab]] === Installer un fichier crontab [IMPORTANT] ==== Ne pas utiliser la procédure décrite ci-dessous pour éditer et installer le fichier [.filename]#crontab# système. Utilisez directement votre éditeur: l'utilitaire `cron` remarquera le changement au niveau de ce fichier et utilisera immédiatement la nouvelle version. Consultez extref:{faq}[cette entrée de la FAQ, ROOT-NOT-FOUND-CRON-ERRORS] pour plus d'information. ==== Pour installer un fichier [.filename]#crontab# utilisateur fraîchement rédigé, tout d'abord utilisez votre éditeur favori pour créer un fichier dans le bon format, ensuite utilisez l'utilitaire `crontab`. L'usage le plus typique est: [source,shell] .... # crontab fichier-crontab .... Dans cet exemple, [.filename]#fichier-crontab# est le nom d'un fichier [.filename]#crontab# qui a été précédemment créé. Il existe également une option pour afficher les fichiers [.filename]#crontab# installés, passez simplement le paramètre `-l` à `crontab` et lisez ce qui est affiché. Pour les utilisateurs désirant créer leur fichier crontab à partir de zéro, sans utiliser de modèle, l'option `crontab -e` est disponible. Cela invoquera l'éditeur par défaut avec un fichier vide. Quand le fichier est sauvegardé, il sera automatiquement installé par la commande `crontab`. Afin d'effacer le fichier [.filename]#crontab# utilisateur complètement, utiliser la commande `crontab` avec l'option `-r`. [[configtuning-rcd]] == Utilisation du système man:rc[8] sous FreeBSD En 2002, le système [.filename]#rc.d# de NetBSD pour l'initialisation du système a été intégré à FreeBSD. Les utilisateurs noteront les fichiers présents dans le répertoire [.filename]#/etc/rc.d#. Plusieurs de ces fichiers sont destinés aux services de base qui peuvent être contrôlés avec les options `start`, `stop`, et `restart`. Par exemple, man:sshd[8] peut être relancé avec la commande suivante: [source,shell] .... # /etc/rc.d/sshd restart .... Cette procédure est similaire pour d'autres services. Bien sûr, les services sont généralement lancés automatiquement au démarrage dès qu'ils sont spécifiés dans le fichier man:rc.conf[5]. Par exemple, activer le "daemon" de translation d'adresses au démarrage est aussi simple que d'ajouter la ligne suivante au fichier [.filename]#/etc/rc.conf#: [.programlisting] .... natd_enable="YES" .... Si une ligne `natd_enable="NO"` est déjà présente, modifiez alors le `NO` par `YES`. Les procédures rc chargeront automatiquement les autres services dépendants lors du prochain redémarrage comme décrit ci-dessous. Comme le système [.filename]#rc.d# est à l'origine destiné pour lancer/arrêter les services au démarrage/à l'arrêt du système, les options standards `start`, `stop` et `restart` ne seront effectives que si les variables appropriées sont positionnées dans le fichier [.filename]#/etc/rc.conf#. Par exemple, la commande `sshd restart` ci-dessus ne fonctionnera que si `sshd_enable` est fixée à `YES` dans [.filename]#/etc/rc.conf#. Pour lancer, arrêter ou redémarrer un service indépendemment des paramétrages du fichier [.filename]#/etc/rc.conf#, les commandes doivent être précédées par "one". Par exemple pour redémarrer `sshd` indépendemment du paramétrage du fichier [.filename]#/etc/rc.conf#, exécutez la commande suivante: [source,shell] .... # /etc/rc.d/sshd onerestart .... Il est facile de contrôler si un service est activé dans le fichier [.filename]#/etc/rc.conf# en exécutant la procédure [.filename]#rc.d# appropriée avec l'option `rcvar`. Ainsi, un administrateur peut contrôler que `sshd` est réellement activé dans [.filename]#/etc/rc.conf# en exécutant: [source,shell] .... # /etc/rc.d/sshd rcvar # sshd $sshd_enable=YES .... [NOTE] ==== La seconde ligne (`# sshd`) est la sortie de la commande `sshd` et non pas une console `root`. ==== Pour déterminer si un service est actif, une option appelée `status` est disponible. Par exemple pour vérifier que `sshd` a réellement été lancé: [source,shell] .... # /etc/rc.d/sshd status sshd is running as pid 433. .... Dans certains cas, il est également possible de recharger un service avec l'option `reload`. Le système tentera d'envoyer un signal à un service individuel, le forçant à recharger ses fichiers de configuration. Dans la plupart des cas cela signifie envoyer un signal `SIGHUP` au service. Le support de cette fonctionnalité n'est pas disponible pour chaque service. Le système [.filename]#rc.d# n'est pas uniquement utilisée pour les services réseaux, elle participe à la majeure partie de l'initialisation du système. Prenez par exemple le fichier [.filename]#bgfsck#. Quand cette procédure est exécutée, il affichera le message suivant: [source,shell] .... Starting background file system checks in 60 seconds. .... Donc ce fichier est utilisé pour les vérifications du système de fichiers en arrière plan, qui sont uniquement effectuées lors de l'initialisation du système. De nombreux services système dépendent d'autres services pour fonctionner correctement. Par exemple, NIS et les autres services basés sur les RPCs peuvent échouer s'ils sont lancés après le lancement du service `rpcbind` (portmapper). Pour résoudre ce problème, l'information concernant les dépendances et autres méta-données est inclue dans les commentaires au début de chaque procédure de démarrage. Le programme man:rcorder[8] est alors utilisé pour analyser ces commentaires lors de l'initialisation du système en vue de déterminer l'ordre dans lequel les services système seront invoqués pour satisfaire les dépendances. Les mots suivants doivent être présents en tête de tous les fichiers de démarrage (ils sont nécessaires pour que man:rc.subr[8] active les procédures de démarrages): * `PROVIDE`: indique les services que fournit ce fichier. Les mots clés suivants peuvent être ajoutés au début de chaque fichier de démarrage. Ils ne sont pas strictement nécessaires, mais sont utiles comme aide pour man:rcorder[8]: * `REQUIRE`: liste les fichiers dont dépend ce service. Ce fichier sera exécuté _après_ les services indiqués. * `BEFORE`: liste les services qui dépendent du service présent. Ce fichier sera exécuté _avant_ les services indiqués. En utilisant avec soin ces mots clés pour chaque fichier de démarrage, un administrateur dispose d'un niveau de contrôle très fin de l'ordre d'exécution des procédures de démarrage sans les inconvénients des "runlevels" comme sur d'autres systèmes d'exploitation UNIX(R). Des informations supplémentaires concernant le système [.filename]#rc.d# peuvent être trouvées dans les pages de manuel man:rc[8] et man:rc.subr[8]. Si vous êtes intéressé par l'écriture de vos propres procédures [.filename]#rc.d# ou pour l'amélioration des procédures existantes, vous trouverez extref:{rc-scripting}[cette article] utile. [[config-network-setup]] == Configuration des cartes réseaux De nos jours il est impossible de penser à un ordinateur sans penser connexion à un réseau. Installer et configurer une carte réseau est une tâche classique pour tout administrateur FreeBSD. === Déterminer le bon pilote de périphérique Avant de commencer, vous devez connaître le modèle de la carte dont vous disposez, le circuit qu'elle utilise, et si c'est une carte PCI ou ISA. FreeBSD supporte une large variété de cartes PCI et ISA. Consultez la liste de compatibilité matérielle pour votre version de FreeBSD afin de voir si votre carte est supportée. Une fois que vous êtes sûrs que votre carte est supportée, vous devez déterminer le bon pilote de périphérique pour la carte. Les fichiers [.filename]#/usr/src/sys/conf/NOTES# et [.filename]#/usr/src/sys/arch/conf/NOTES# vous donneront la liste des pilotes de périphériques pour cartes réseaux avec des informations sur les cartes/circuits supportés. Si vous avez des doutes au sujet du bon pilote, lisez la page de manuel du pilote. La page de manuel vous donnera plus d'information sur le matériel supporté et même les éventuels problèmes qui pourront apparaître. Si vous possédez une carte courante, la plupart du temps vous n'aurez pas à chercher trop loin pour trouver un pilote. Les pilotes pour les cartes réseaux courantes sont présents dans le noyau [.filename]#GENERIC#, aussi votre carte devrait apparaître au démarrage, comme suit: [source,shell] .... dc0: <82c169 PNIC 10/100BaseTX> port 0xa000-0xa0ff mem 0xd3800000-0xd38 000ff irq 15 at device 11.0 on pci0 miibus0: on dc0 bmtphy0: PHY 1 on miibus0 bmtphy0: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc0: Ethernet address: 00:a0:cc:da:da:da dc0: [ITHREAD] dc1: <82c169 PNIC 10/100BaseTX> port 0x9800-0x98ff mem 0xd3000000-0xd30 000ff irq 11 at device 12.0 on pci0 miibus1: on dc1 bmtphy1: PHY 1 on miibus1 bmtphy1: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc1: Ethernet address: 00:a0:cc:da:da:db dc1: [ITHREAD] .... Dans cet exemple, nous voyons que deux cartes utilisant le pilote de périphérique man:dc[4] sont présentes sur le système. Si le pilote de votre carte n'est pas présent dans le noyau [.filename]#GENERIC#, vous devrez charger le module approprié pour pouvoir utiliser votre carte. Cela peut être effectué de deux manières différentes: * La méthode la plus simple est de charger le module pour votre carte réseau avec man:kldload[8], ou automatiquement au démarrage du système en ajoutant la ligne appropriée au fichier [.filename]#/boot/loader.conf#. Tous les pilotes de cartes réseau ne sont pas disponibles sous forme de modules; les cartes ISA sont un bon exemple de périphériques pour lesquels les modules n'existent pas. * Alternativement, vous pouvez compiler en statique le support pour votre carte dans votre noyau. Consultez [.filename]#/usr/src/sys/conf/NOTES#, [.filename]#/usr/src/sys/arch/conf/NOTES# et la page de manuel du pilote de périphérique pour savoir ce qu'il faut ajouter au fichier de configuration de votre noyau. Pour plus d'information sur la recompilation de votre noyau, veuillez lire le crossref:kernelconfig[kernelconfig,Configurer le noyau de FreeBSD]. Si votre carte a été détectée au démarrage par votre noyau ([.filename]#GENERIC#) vous n'avez pas à compiler un nouveau noyau. [[config-network-ndis]] ==== Utilisation des pilotes NDIS de Windows(R) Malheureusement il y a toujours de nombreux fabricants qui ne fournissent pas à la communauté des logiciels libres les informations concernant les pilotes pour leurs cartes considérant de telles informations comme des secrets industriels. Par conséquent, il ne reste aux développeurs de FreeBSD et d'autres systèmes d'exploitation libres que deux choix: développer les pilotes en passant par un long et pénible processus de "reverse engineering" ou utiliser les pilotes binaires existants disponibles pour la plateforme Microsoft(R) Windows(R). La plupart des développeurs, y compris ceux impliqués dans FreeBSD, ont choisi cette dernière approche. Grâce aux contributions de Bill Paul (wpaul), il existe un support "natif" pour la spécification d'interface des pilotes de périphérique réseau (Network Driver Interface Specification-NDIS). Le NDISulator FreeBSD (connu également sous le nom de Project Evil) prend un pilote binaire réseau Windows(R) et lui fait penser qu'il est en train de tourner sous Windows(R). Etant donné que le pilote man:ndis[4] utilise un binaire Windows(R), il ne fonctionne que sur les systèmes i386(TM) et amd64. Les périphériques PCI, CardBus, PCMCIA (PC-Card), et USB sont supportés. Pour utiliser le NDISulator, trois choses sont nécessaires: . les sources du noyau; . le pilote binaire Windows(R) XP (extension [.filename]#.SYS#); . le fichier de configuration du pilote Windows(R) XP (extension [.filename]#.INF#). Recherchez les fichiers spécifiques à votre carte. Généralement, ils peuvent être trouvés sur les CDs livrés avec la carte ou sur le site du fabricant. Dans les exemples qui suivent nous utiliseront les fichiers [.filename]#W32DRIVER.SYS# et [.filename]#W32DRIVER.INF#. Le type de pilote doit correspondre à la version de FreeBSD. Pour FreeBSD/i386, utiliser un pilote Windows(R) 32bits. Pour FreeBSD/amd64, un pilote Windows(R) 64bits est nécessaire. L'étape suivante est de compiler le pilote binaire dans un module chargeable du noyau. En tant que `root`, utilisez man:ndisgen[8]: [source,shell] .... # ndisgen /path/to/W32DRIVER.INF /path/to/W32DRIVER.SYS .... L'utilitaire man:ndisgen[8] est interactif, il sollicitera l'utilisateur pour d'éventuelles informations complémentaires si nécessaire. Un nouveau module noyau est créé dans le répertoire courant. Utiliser man:kldload[8] pour charger le nouveau module: [source,shell] .... # kldload ./W32DRIVER_SYS.ko .... Avec le module généré, vous devez également charger les modules [.filename]#ndis.ko# et [.filename]#if_ndis.ko#. Cela devrait être fait automatiquement quand vous chargez un module qui dépend de man:ndis[4]. Si vous désirez les charger manuellement, utilisez les commandes suivantes: [source,shell] .... # kldload ndis # kldload if_ndis .... La première commande charge le pilote d'interface NDIS, la seconde charge l'interface réseau. Contrôlez maintenant la sortie de man:dmesg[8] à la recherche d'une quelconque erreur au chargement. Si tout s'est bien passé, vous devriez obtenir une sortie ressemblant à ce qui suit: [source,shell] .... ndis0: mem 0xf4100000-0xf4101fff irq 3 at device 8.0 on pci1 ndis0: NDIS API version: 5.0 ndis0: Ethernet address: 0a:b1:2c:d3:4e:f5 ndis0: 11b rates: 1Mbps 2Mbps 5.5Mbps 11Mbps ndis0: 11g rates: 6Mbps 9Mbps 12Mbps 18Mbps 36Mbps 48Mbps 54Mbps .... A partir de là vous pouvez traiter le périphérique [.filename]#ndis0# comme n'importe quelle interface réseau (par exemple [.filename]#dc0#). Vous pouvez configurer le système pour charger les modules NDIS au démarrage du système de la même manière que pour n'importe quel autre module. Tout d'abord, copiez le module généré, [.filename]#W32DRIVER_SYS.ko#, dans le répertoire [.filename]#/boot/modules#. Ajoutez ensuite la ligne suivante au fichier [.filename]#/boot/loader.conf#: [.programlisting] .... W32DRIVER_SYS_load="YES" .... === Configuration de la carte réseau Une fois que le bon pilote de périphérique pour la carte réseau est chargé, la carte doit être configurée. Comme beaucoup d'autres choses, la carte aura pu être configurée à l'installation par sysinstall. Pour afficher la configuration des interfaces réseaux de votre système, entrer la commande suivante: [source,shell] .... % ifconfig dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da inet 192.168.1.3 netmask 0xffffff00 broadcast 192.168.1.255 media: Ethernet autoselect (100baseTX ) status: active dc1: flags=8802 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:db inet 10.0.0.1 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet 10baseT/UTP status: no carrier lo0: flags=8049 metric 0 mtu 16384 options=3 inet6 fe80::1%lo0 prefixlen 64 scopeid 0x4 inet6 ::1 prefixlen 128 inet 127.0.0.1 netmask 0xff000000 nd6 options=3 .... Dans cet exemple, les périphériques suivants ont été affichés: * [.filename]#dc0#: La première interface Ethernet * [.filename]#dc1#: La seconde interface Ethernet * [.filename]#lo0#: L'interface "en boucle" ("loopback") FreeBSD utilise le nom du pilote de périphérique suivi par un chiffre représentant l'ordre dans lequel la carte est détectée au démarrage du noyau pour nommer la carte. Par exemple [.filename]#sis2# serait la troisième carte sur le système utilisant le pilote de périphérique man:sis[4]. Dans cet exemple, le périphérique [.filename]#dc0# est actif et en fonctionnement. Les indicateurs importants sont: . `UP` signifie que la carte est configurée et prête. . La carte possède une adresse Internet (`inet`) (dans ce cas-ci `192.168.1.3`). . Elle a un masque de sous-réseau valide (`netmask`; `0xffffff00` est équivalent à `255.255.255.0`). . Elle a une adresse de diffusion valide (dans ce cas-ci `192.168.1.255`). . L'adresse MAC de la carte (`ether`) est `00:a0:cc:da:da:da` . La sélection du média est sur le mode d'autosélection (`media: Ethernet autoselect (100baseTX full-duplex)`). Nous voyons que [.filename]#dc1# a été configurée pour utiliser un matériel de type `10baseT/UTP`. Pour plus d'information sur le type de matériel disponible pour un pilote de périphérique, référez-vous à sa page de manuel. . La liaison (`status`) est `active`, i.e. la porteuse est détectée. Pour [.filename]#dc1#, nous lisons `status: no carrier`. Cela est normal lorsqu'aucun câble n'est branché à la carte. Si le résultat de la commande man:ifconfig[8] est similaire à: [source,shell] .... dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da media: Ethernet autoselect (100baseTX ) status: active .... cela indiquerait que la carte n'a pas été configurée. Pour configurer votre carte, vous avez besoin des privilèges de l'utilisateur `root`. La configuration de la carte réseau peut être faite à partir de la ligne de commande avec man:ifconfig[8] mais vous aurez à répéter cette opération à chaque redémarrage du système. Le fichier [.filename]#/etc/rc.conf# est l'endroit où ajouter la configuration de la carte réseau. Ouvrez le fichier [.filename]#/etc/rc.conf# dans votre éditeur favori. Vous devez ajouter une ligne pour chaque carte réseau présente sur le système, par exemple dans notre cas, nous avons ajouté ces lignes: [.programlisting] .... ifconfig_dc0="inet 192.168.1.3 netmask 255.255.255.0" ifconfig_dc1="inet 10.0.0.1 netmask 255.255.255.0 media 10baseT/UTP" .... Vous devez remplacer [.filename]#dc0#, [.filename]#dc1#, et ainsi de suite, avec le périphérique correspondant pour vos cartes, et les adresses avec celles désirées. Vous devriez lire les pages de manuel du pilote de périphérique et d'man:ifconfig[8] pour plus de détails sur les options autorisées et également la page de manuel de man:rc.conf[5] pour plus d'information sur la syntaxe de [.filename]#/etc/rc.conf#. Si vous avez configuré le réseau à l'installation, des lignes concernant la/les carte(s) réseau pourront être déjà présentes. Contrôler à deux fois le fichier [.filename]#/etc/rc.conf# avant d'y ajouter des lignes. Vous devrez également éditer le fichier [.filename]#/etc/hosts# pour ajouter les noms et les adresses IP des diverses machines du réseau local, si elles ne sont pas déjà présentes. Pour plus d'information référez-vous à la page de manuel man:hosts[5] et au fichier [.filename]#/usr/shared/examples/etc/hosts#. [NOTE] ==== S'il n'y a pas de serveur DHCP et qu'un accès à Internet est nécessaire, configurez manuellement la passerelle par défaut et le serveur de noms: [source,shell] .... # echo 'defaultrouter="your_default_router"' >> /etc/rc.conf # echo 'nameserver your_DNS_server' >> /etc/resolv.conf .... ==== === Test et dépannage Une fois les modifications nécessaires du fichier [.filename]#/etc/rc.conf# effectuées, vous devrez redémarrer votre système. Cela permettra la prise en compte de la ou les modifications au niveau des interfaces, et permettra de vérifier que le système redémarre sans erreur de configuration. Sinon, une autre méthode pour faire prendre en compte les modifications au niveau de la gestion du réseau consiste à utiliser la commande: [source,shell] .... # service netif restart .... [NOTE] ==== Si une passerelle par défaut a été configurée dans [.filename]#/etc/rc.conf#, lancez également cette commande: [source,shell] .... # service routing restart .... ==== Une fois que le système a été redémarré, vous testez les interfaces réseau. ==== Tester la carte Ethernet Pour vérifier qu'une carte Ethernet est configurée correctement, vous devez essayer deux choses. Premièrement, "pinguer" l'interface, puis une autre machine sur le réseau local. Tout d'abord testons l'interface: [source,shell] .... % ping -c5 192.168.1.3 PING 192.168.1.3 (192.168.1.3): 56 data bytes 64 bytes from 192.168.1.3: icmp_seq=0 ttl=64 time=0.082 ms 64 bytes from 192.168.1.3: icmp_seq=1 ttl=64 time=0.074 ms 64 bytes from 192.168.1.3: icmp_seq=2 ttl=64 time=0.076 ms 64 bytes from 192.168.1.3: icmp_seq=3 ttl=64 time=0.108 ms 64 bytes from 192.168.1.3: icmp_seq=4 ttl=64 time=0.076 ms --- 192.168.1.3 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.074/0.083/0.108/0.013 ms .... Nous devons maintenant "pinguer" une autre machine sur le réseau: [source,shell] .... % ping -c5 192.168.1.2 PING 192.168.1.2 (192.168.1.2): 56 data bytes 64 bytes from 192.168.1.2: icmp_seq=0 ttl=64 time=0.726 ms 64 bytes from 192.168.1.2: icmp_seq=1 ttl=64 time=0.766 ms 64 bytes from 192.168.1.2: icmp_seq=2 ttl=64 time=0.700 ms 64 bytes from 192.168.1.2: icmp_seq=3 ttl=64 time=0.747 ms 64 bytes from 192.168.1.2: icmp_seq=4 ttl=64 time=0.704 ms --- 192.168.1.2 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.700/0.729/0.766/0.025 ms .... Vous pourrez utiliser le noms de la machine à la place de `192.168.1.2` si vous avez configuré le fichier [.filename]#/etc/hosts#. ==== Dépannage Le dépannage de matériels ou de logiciels est toujours une tâche relativement pénible, mais qui peut être rendue plus aisée en vérifiant en premier lieu certaines choses élémentaires. Votre câble réseau est-il branché? Avez-vous correctement configuré les services réseau? Le coupe-feu est-il bien configuré? Est-ce que la carte réseau est supportée par FreeBSD? Consultez toujours les notes concernant le matériel avant d'envoyer un rapport de bogue. Mettez à jour votre version de FreeBSD vers la dernière version STABLE. Consultez les archives des listes de diffusion, et faites même des recherches sur l'Internet. Si la carte fonctionne mais les performances sont mauvaises, une lecture de la page de manuel man:tuning[7] peut valoir la peine. Vous pouvez également vérifier la configuration du réseau puisque des paramètres réseau incorrects peuvent donner lieu à des connexions lentes. Certains utilisateurs peuvent voir apparaître un ou deux messages `device timeout`, ce qui est normal pour certaines cartes. Si ces messages se multiplient, assurez-vous que la carte n'est pas en conflit avec un autre périphérique. Contrôlez à deux fois les câbles de connexion. Peut-être que vous avez juste besoin d'une autre carte. Parfois, des utilisateurs sont confrontés à des messages d'erreur `watchdog timeout`. La première chose à faire dans ce cas est de vérifier votre câble réseau. De nombreuses cartes demandent un slot PCI supportant le "Bus Mastering". Sur certaines cartes mère anciennes, seul un slot PCI le permet (la plupart du temps le slot 0). Consultez la documentation de la carte réseau et de la carte mère pour déterminer si cela peut être à l'origine du problème. Les messages `No route to host` surviennent si le système est incapable de router un paquet vers la machine de destination. Cela peut arriver s'il n'y a pas de route par défaut de définie, ou si le câble réseau est débranché. Vérifiez la sortie de la commande `netstat -nr` et assurez-vous qu'il y a une route valide en direction de la machine que vous essayez d'atteindre. Si ce n'est pas le cas, lisez la crossref:advanced-networking[advanced-networking,Administration réseau avancée]. Les messages d'erreur `ping: sendto: Permission denied` sont souvent dus à un coupe-feu mal configuré. Si `ipfw` est activé dans le noyau mais qu'aucune règle n'a été définie, alors la politique par défaut est de refuser tout trafic, même les requêtes "ping"! Lisez crossref:firewalls[firewalls,Firewalls] pour plus d'informations. Parfois les performances de la carte ne sont pas bonnes, ou en dessous de la moyenne. Dans ce cas il est recommandé de passer la sélection du média du mode `autoselect` au mode adéquat. Alors que cela fonctionne généralement pour la plupart du matériel, il se peut que cela ne résolve pas le problème pour tout de monde. Encore une fois, contrôlez les paramétrages réseau et consultez la page de manuel man:tuning[7]. [[configtuning-virtual-hosts]] == Hôtes virtuels Une utilisation très courante de FreeBSD est l'hébergement de sites virtuels, où un serveur apparaît pour le réseau comme étant plusieurs serveurs différents. Ceci est possible en assignant plusieurs adresses réseau à une interface. Une interface réseau donnée possède une adresse "réelle", et peut avoir n'importe quel nombre d'adresses "alias". Ces alias sont normalement ajoutés en plaçant les entrées correspondantes dans le fichier [.filename]#/etc/rc.conf#. Une entrée d'alias pour l'interface [.filename]#fxp0# ressemble à: [.programlisting] .... ifconfig_fxp0_alias0="inet xxx.xxx.xxx.xxx netmask xxx.xxx.xxx.xxx" .... Notez que les entrées d'alias doivent commencer avec alias0 et continuer en ordre croissant, (par exemple, _alias1, _alias2, et ainsi de suite). Le processus de configuration s'arrêtera au premier nombre absent. Le calcul des masques de réseau est important, mais heureusement assez simple. Pour une interface donnée, il doit y avoir une adresse qui représente correctement le masque de réseau de votre réseau. Tout autre adresse appartenant à ce réseau devra avoir un masque de réseau avec chaque bit à `1` (exprimé soit sous la forme `255.255.255.255` soit `0xffffffff`). Par exemple, considérez le cas où l'interface [.filename]#fxp0# est connectée à deux réseaux, le réseau `10.1.1.0` avec un masque de réseau de `255.255.255.0` et le réseau `202.0.75.16` avec un masque de `255.255.255.240`. Nous voulons que le système apparaisse de `10.1.1.1` jusqu'à `10.1.1.5` et à `202.0.75.17` jusqu'à `202.0.75.20`. Comme noté plus haut, seule la première adresse dans un intervalle réseau donné (dans ce cas, `10.0.1.1` et `202.0.75.17`) devrait avoir un masque de sous-réseau réel; toutes les autres adresses (`10.1.1.2` à `10.1.1.5` et `202.0.75.18` jusqu'à `202.0.75.20`) doivent être configurées avec un masque de sous-réseau de `255.255.255.255`. Les entrées suivantes du fichier [.filename]#/etc/rc.conf# configurent la carte correctement pour cet arrangement: [.programlisting] .... ifconfig_fxp0="inet 10.1.1.1 netmask 255.255.255.0" ifconfig_fxp0_alias0="inet 10.1.1.2 netmask 255.255.255.255" ifconfig_fxp0_alias1="inet 10.1.1.3 netmask 255.255.255.255" ifconfig_fxp0_alias2="inet 10.1.1.4 netmask 255.255.255.255" ifconfig_fxp0_alias3="inet 10.1.1.5 netmask 255.255.255.255" ifconfig_fxp0_alias4="inet 202.0.75.17 netmask 255.255.255.240" ifconfig_fxp0_alias5="inet 202.0.75.18 netmask 255.255.255.255" ifconfig_fxp0_alias6="inet 202.0.75.19 netmask 255.255.255.255" ifconfig_fxp0_alias7="inet 202.0.75.20 netmask 255.255.255.255" .... [[configtuning-configfiles]] == Fichiers de configuration === Organisation du répertoire [.filename]#/etc# Il existe un certain nombre de répertoires dans lesquels se trouvent les informations de configuration. Ceux-ci incluent: [.informaltable] [cols="1,1", frame="none"] |=== |[.filename]#/etc# |Information de configuration générique du système; les données ici sont spécifiques au système. |[.filename]#/etc/defaults# |Version par défaut des fichiers de configuration du système. |[.filename]#/etc/mail# |Configuration de man:sendmail[8], et autres fichiers de configuration d'agent de transmission du courrier électronique. |[.filename]#/etc/ppp# |Configuration pour les programmes PPP utilisateur et intégré au noyau. |[.filename]#/etc/namedb# |Emplacement par défaut pour les données de man:named[8]. Normalement [.filename]#named.conf# et les fichiers de zone sont stockés dans ce répertoire. |[.filename]#/usr/local/etc# |Fichiers de configuration pour les applications installées. Peut contenir des sous-répertoires pour chaque application. |[.filename]#/usr/local/etc/rc.d# |Procédures de lancement/d'arrêt pour les applications installées. |[.filename]#/var/db# |Fichiers de bases de données automatiquement générés, spécifiques au système, comme la base de données des logiciels installés, la base de données de localisation des fichiers, et ainsi de suite. |=== === Nom d'hôtes ==== [.filename]#/etc/resolv.conf# [.filename]#/etc/resolv.conf# gère comment le résolveur de FreeBSD accède au système de nom de domaine d'Internet (DNS). Les entrées la plus classiques du fichier [.filename]#resolv.conf# sont: [.informaltable] [cols="1,1", frame="none"] |=== |`nameserver` |L'adresse IP du serveur de noms auquel le résolveur devrait envoyer ses requêtes. Les serveurs sont sollicités dans l'ordre listé avec un maximum de trois. |`search` |Liste de recherche pour la résolution de nom de machine. Ceci est normalement déterminé par le domaine de l'hôte local. |`domain` |Le nom du domaine local. |=== Un fichier [.filename]#resolv.conf# typique: [.programlisting] .... search example.com nameserver 147.11.1.11 nameserver 147.11.100.30 .... [NOTE] ==== Seule une des options `search` et `domain` devrait être utilisée. ==== Si vous utilisez DHCP, man:dhclient[8] réécrit habituellement [.filename]#resolv.conf# avec l'information reçue du serveur DHCP. ==== [.filename]#/etc/hosts# [.filename]#/etc/hosts# est une simple base de données texte, une réminiscence des débuts d'Internet. Il travaille en conjonction avec les serveurs DNS et NIS pour fournir les correspondances nom vers adresse IP. Les ordinateurs locaux reliés par l'intermédiaire d'un réseau local peuvent être ajoutés dans ce fichier pour une résolution de noms simple plutôt que de configurer un serveur man:named[8]. De plus [.filename]#/etc/hosts# peut être utilisé pour fournir un enregistrement local de correspondances de nom, réduisant ainsi le besoin de requêtes vers l'extérieur pour les noms auxquels on accède couramment. [.programlisting] .... # $FreeBSD$ # # # Host Database # # This file should contain the addresses and aliases for local hosts that # share this file. Replace 'my.domain' below with the domainname of your # machine. # # In the presence of the domain name service or NIS, this file may # not be consulted at all; see /etc/nsswitch.conf for the resolution order. # # ::1 localhost localhost.my.domain 127.0.0.1 localhost localhost.my.domain # # Imaginary network. #10.0.0.2 myname.my.domain myname #10.0.0.3 myfriend.my.domain myfriend # # According to RFC 1918, you can use the following IP networks for # private nets which will never be connected to the Internet: # # 10.0.0.0 - 10.255.255.255 # 172.16.0.0 - 172.31.255.255 # 192.168.0.0 - 192.168.255.255 # # In case you want to be able to connect to the Internet, you need # real official assigned numbers. Do not try to invent your own network # numbers but instead get one from your network provider (if any) or # from your regional registry (ARIN, APNIC, LACNIC, RIPE NCC, or AfriNIC.) # .... [.filename]#/etc/hosts# suit le format simple suivant: [.programlisting] .... [Internet address] [official hostname] [alias1] [alias2] ... .... Par exemple: [.programlisting] .... 10.0.0.1 myRealHostname.example.com myRealHostname foobar1 foobar2 .... Consultez la page de manuel man:hosts[5] pour plus d'informations. === Configuration des fichiers de trace ==== [.filename]#syslog.conf# [.filename]#syslog.conf# est le fichier de configuration du programme man:syslogd[8]. Il indique quel type de messages `syslog` sera enregistré dans des fichiers de traces particuliers. [.programlisting] .... # $FreeBSD$ # # Spaces ARE valid field separators in this file. However, # other *nix-like systems still insist on using tabs as field # separators. If you are sharing this file between systems, you # may want to use only tabs as field separators here. # Consult the syslog.conf(5) manual page. *.err;kern.debug;auth.notice;mail.crit /dev/console *.notice;kern.debug;lpr.info;mail.crit;news.err /var/log/messages security.* /var/log/security mail.info /var/log/maillog lpr.info /var/log/lpd-errs cron.* /var/log/cron *.err root *.notice;news.err root *.alert root *.emerg * # uncomment this to log all writes to /dev/console to /var/log/console.log #console.info /var/log/console.log # uncomment this to enable logging of all log messages to /var/log/all.log #*.* /var/log/all.log # uncomment this to enable logging to a remote log host named loghost #*.* @loghost # uncomment these if you're running inn # news.crit /var/log/news/news.crit # news.err /var/log/news/news.err # news.notice /var/log/news/news.notice !startslip *.* /var/log/slip.log !ppp *.* /var/log/ppp.log .... Consultez la page de manuel man:syslog.conf[5] pour plus d'informations. ==== [.filename]#newsyslog.conf# [.filename]#newsyslog.conf# est le fichier de configuration de man:newsyslog[8], un programme qui est normalement programmé man:cron[8] pour s'exécuter périodiquement. man:newsyslog[8] détermine quand les fichiers de traces doivent être archivés ou réorganisés. [.filename]#logfile# devient [.filename]#logfile.0#, [.filename]#logfile.0# devient à son tour [.filename]#logfile.1#, et ainsi de suite. D'autre part, les fichiers de traces peuvent être archivés dans le format man:gzip[1], ils se nommeront alors: [.filename]#logfile.0.gz#, [.filename]#logfile.1.gz#, et ainsi de suite. [.filename]#newsyslog.conf# indique quels fichiers de traces doivent être gérés, combien doivent être conservés, et quand ils doivent être modifiés. Les fichiers de traces peuvent être réorganisés et/ou archivés quand ils ont soit atteint une certaine taille, soit à une certaine période/date. [.programlisting] .... # configuration file for newsyslog # $FreeBSD$ # # filename [owner:group] mode count size when [ZB] [/pid_file] [sig_num] /var/log/cron 600 3 100 * Z /var/log/amd.log 644 7 100 * Z /var/log/kerberos.log 644 7 100 * Z /var/log/lpd-errs 644 7 100 * Z /var/log/maillog 644 7 * @T00 Z /var/log/sendmail.st 644 10 * 168 B /var/log/messages 644 5 100 * Z /var/log/all.log 600 7 * @T00 Z /var/log/slip.log 600 3 100 * Z /var/log/ppp.log 600 3 100 * Z /var/log/security 600 10 100 * Z /var/log/wtmp 644 3 * @01T05 B /var/log/daily.log 640 7 * @T00 Z /var/log/weekly.log 640 5 1 $W6D0 Z /var/log/monthly.log 640 12 * $M1D0 Z /var/log/console.log 640 5 100 * Z .... Consultez la page de manuel man:newsyslog[8] pour plus d'informations. [[configtuning-sysctlconf]] === [.filename]#sysctl.conf# [.filename]#sysctl.conf# ressemble à [.filename]#rc.conf#. Les valeurs sont fixées sous la forme `variable=value`. Les valeurs spécifiées sont positionnées après que le système soit passé dans le mode multi-utilisateurs. Toutes les variables ne sont pas paramétrables dans ce mode. Pour désactiver l'enregistrement des signaux fatals de fin de processus et empêcher les utilisateurs de voir les processus lancés par les autres, les variables suivantes peuvent être paramétrées dans [.filename]#sysctl.conf#: [.programlisting] .... # Do not log fatal signal exits (e.g., sig 11) kern.logsigexit=0 # Prevent users from seeing information about processes that # are being run under another UID. security.bsd.see_other_uids=0 .... [[configtuning-sysctl]] == Optimisation avec man:sysctl[8] man:sysctl[8] est une interface qui vous permet d'effectuer des changements de paramétrage sur un système FreeBSD en fonctionnement. Cela comprend de nombreuses options avancées de la pile TCP/IP et du système de mémoire virtuelle qui peuvent améliorer dramatiquement les performances pour un administrateur système expérimenté. Plus de cinq cent variables système peuvent être lues et modifiées grâce à man:sysctl[8]. man:sysctl[8] remplit deux fonctions: lire et modifier les paramétrages du système. Pour afficher toutes les variables lisibles: [source,shell] .... % sysctl -a .... Pour lire une variable particulière, par exemple, `kern.maxproc`: [source,shell] .... % sysctl kern.maxproc kern.maxproc: 1044 .... Pour fixer une variable particulière, utilisez la syntaxe intuitive _variable_=_valeur_ : [source,shell] .... # sysctl kern.maxfiles=5000 kern.maxfiles: 2088 -> 5000 .... Les valeurs des variables sysctl sont généralement des chaînes de caractères, des nombres, ou des booléens (un variable booléenne étant `1` pour oui ou un `0` pour non). Si vous voulez fixer automatiquement certaines variables à chaque démarrage de la machine, ajoutez-les au fichier [.filename]#/etc/sysctl.conf#. Pour plus d'information consultez la page de manuel man:sysctl.conf[5] et la <>. [[sysctl-readonly]] === Variables man:sysctl[8] en lecture seule Dans certains cas, il peut être nécessaire de modifier des variables man:sysctl[8] en lecture seule. Bien que cela soit parfois inévitable, cela ne peut être fait qu'au (re)démarrage de la machine. Par exemple sur certains modèles d'ordinateurs portables le périphérique man:cardbus[4] ne sondera pas le système à la recherche des zones mémoires, et échouera avec des erreurs du type: [source,shell] .... cbb0: Could not map register memory device_probe_and_attach: cbb0 attach returned 12 .... Des cas comme le précédent demandent généralement la modification de paramètres man:sysctl[8] par défaut qui sont en lecture seule. Pour palier à ces situations un utilisateur peut placer un paramétrage ("OID"-Object IDentifier) man:sysctl[8] dans le fichier local [.filename]#/boot/loader.conf.local#. Les paramétrages par défaut se trouvent dans le fichier [.filename]#/boot/defaults/loader.conf#. Pour corriger le problème précédent, il faudrait que l'utilisateur ajoute la ligne `hw.pci.allow_unsupported_io_range=1` dans le fichier précédemment indiqué. Désormais le périphérique man:cardbus[4] devrait fonctionner normalement. [[configtuning-disk]] == Optimiser les disques === Les variables sysctl ==== `vfs.vmiodirenable` La variable sysctl `vfs.vmiodirenable` peut être positionnée soit à 0 (désactivée) soit à 1 (activée); elle est a 1 par défaut. Cette variable spécifie comment les répertoires sont cachés par le système. La plupart des répertoires sont petits, utilisant juste un simple fragment du système de fichiers (typiquement 1KO) et moins dans le cache en mémoire (typiquement 512 octets). Avec cette variable désactivée (à 0), le cache en mémoire ne cachera qu'un nombre fixe de répertoires même si vous disposez d'une grande quantité de mémoire. Activée (à 1), cette variable sysctl permet au cache en mémoire d'utiliser le cache des pages de mémoire virtuelle pour cacher les répertoires, rendant toute la mémoire disponible pour cacher les répertoires. Cependant, la taille minimale de l'élément mémoire utilisé pour cacher un répertoire est une page physique (typiquement 4KO) plutôt que 512 octets. Nous recommandons de conserver de cette option activée si vous faites fonctionner des services qui manipulent un grand nombre de fichiers. De tels services peuvent être des caches web, d'importants systèmes de courrier électronique, et des systèmes serveurs de groupe de discussion. Conserver cette option activée ne réduira généralement pas les performances même avec la mémoire gaspillée mais vous devriez faire des expériences pour le déterminer. ==== `vfs.write_behind` La variable sysctl `vfs.write_behind` est positionnée par défaut à `1` (activée). Elle demande au système de fichiers d'effectuer les écritures lorsque des grappes complètes de données ont été collectées, ce qui se produit généralement lors de l'écriture séquentielle de gros fichiers. L'idée est d'éviter de saturer le cache tampon avec des tampons sales quand cela n'améliorera pas les performances d'E/S. Cependant, cela peut bloquer les processus et dans certaines conditions vous pouvez vouloir désactiver cette fonction. ==== `vfs.hirunningspace` La variable sysctl `vfs.hirunningspace` détermine combien d'opérations d'écriture peuvent être mises en attente à tout moment au niveau des contrôleurs disques du système. La valeur par défaut est normalement suffisante mais sur les machines avec de nombreux disques, vous pouvez vouloir l'augmenter jusqu'à quatre ou cinq _méga-octets_. Notez que fixer une valeur trop élevée (dépassant la limite d'écriture du cache tampon) peut donner lieu à de très mauvaises performances. Ne fixez pas cette valeur à une valeur élevée arbitraire! Des valeurs d'écriture élevées peuvent ajouter des temps de latence aux opérations d'écriture survenant au même moment. Il existent d'autres variables sysctl relatives aux caches tampons et aux pages VM. Nous ne recommandons pas de modifier ces valeurs, le système VM effectue un très bon travail d'auto-optimisation. ==== `vm.swap_idle_enabled` La variable `vm.swap_idle_enabled` est utile dans le cas de systèmes multi-utilisateurs importants où il y a beaucoup d'utilisateurs s'attachant et quittant le système et de nombreux processus inactifs. De tels systèmes tendent à générer une pression assez importante et continue sur les réserves de mémoire libres. Activer cette fonction et régler l'hystéresis de libération de l'espace de pagination (en secondes d'inactivité) par l'intermédiaire des variables `vm.swap_idle_threshold1` et `vm.swap_idle_threshold2`, vous permet de diminuer la priorité des pages mémoire associées avec les processus inactifs plus rapidement qu'avec l'algorithme normal de libération. Cela aide le "daemon" de libération des pages. N'activez cette option que si vous en besoin, parce que la concession que vous faites est d'utiliser l'espace de pagination pour les pages mémoire plus tôt qu'à l'accoutumé, consommant par conséquent plus d'espace de pagination et de bande passante disque. Sur un petit système, cette option aura un effet limité mais dans le cas d'un système important qui fait appel à l'espace de pagination de façon modérée, cette option permettra au système VM de transférer l'ensemble des processus de et vers la mémoire aisément. ==== `hw.ata.wc` FreeBSD 4.3 a flirté avec la désactivation du cache en écriture des disques IDE. Cela réduisit la bande passante en écriture des disques IDE mais fut considéré comme nécessaire en raison de sérieux problèmes de cohérence de données introduits par les fabricants de disques durs. Le problème est que les disques IDE mentent sur le moment où une écriture est réellement terminée. Avec le cache en écriture IDE activé, les disques durs IDE non seulement n'écriront pas les données dans l'ordre, mais parfois retarderont l'écriture de certains blocs indéfiniment sous une charge disque importante. Un crash ou une coupure secteur pourra être à l'origine de sérieuses corruptions du système de fichiers. Par précaution le paramétrage par défaut de FreeBSD fut modifié. Malheureusement, le résultat fut une telle perte de performances que nous avons réactivé le cache en écriture après cette version de FreeBSD. Vous devriez contrôler la valeur par défaut sur votre système en examinant la variable sysctl `hw.ata.wc`. Si le cache en écriture des disques IDE est désactivé, vous pouvez le réactiver en positionnant la variable à 1. Cela doit être fait à partir du chargeur au démarrage. Tenter de le faire après le démarrage du noyau n'aura aucun effet. Pour plus d'informations, veuillez consulter la page de manuel man:ata[4]. ==== `SCSI_DELAY` (`kern.cam.scsi_delay`) L'option de configuration du noyau `SCSI_DELAY` peut être utilisée pour réduire le temps de démarrage du système. Le délai par défaut est important et peut être responsable de plus de `15` secondes d'attente lors du processus de démarrage. Réduire ce délai à `5` secondes est généralement suffisant (tout particulièrement avec les disques modernes). L'option de démarrage `kern.cam.scsi_delay` devrait être utilisée. Cette option de démarrage et celle de configuration du noyau acceptent des valeurs en _millisecondes_ et _non pas_ en _secondes_. [[soft-updates]] === Les "Soft Updates" Le programme man:tunefs[8] peut être utilisé pour régler finement un système de fichiers. Ce programme dispose de nombreuses options différentes, mais pour l'instant nous nous intéresserons uniquement à l'activation et la désactivation des "Soft Updates", ce qui fait avec: [source,shell] .... # tunefs -n enable /filesystem # tunefs -n disable /filesystem .... Un système de fichiers ne peut être modifié avec man:tunefs[8] tant qu'il est monté. Un bon moment pour activer les "Soft Updates" est avant que les partitions ne soient montées en mode mono-utilisateur. Les "Soft Updates" améliorent de façon drastique les performances sur les méta-données, principalement la création et la suppression de fichier, par l'utilisation d'un cache mémoire. Nous recommandons d'activer les "Soft Updates" sur tous vos systèmes de fichiers. Il y a deux inconvénients aux "Soft Updates" que vous devez connaître: tout d'abord, les "Soft Updates" garantissent la cohérence du système de fichiers en cas de crash mais pourront facilement être en retard de quelques secondes (voir même une minute!) dans la mise à jour du disque. Si votre système plante il se peut que vous perdiez plus de travail que dans d'autres cas. Deuxièmement, les "Soft Updates" retardent la libération des blocs du système de fichiers. Si vous avez un système de fichiers (comme le système de fichiers racine) qui est presque plein, effectuer une mise à jour majeure, comme un `make installworld`, peut mener à un manque d'espace sur le système de fichiers et faire échouer la mise à jour. ==== Plus de détails à propos des "Soft Updates" Il y a deux approches traditionnelles pour écrire les méta-données d'un système de fichiers sur le disque (mise à jour des méta-données et mise à jour des éléments sans données comme les inodes ou les répertoires). Historiquement, le comportement par défaut était d'écrire les mises à jour des méta-données de façon synchrone. Si un répertoire a été modifié, le système attendait jusqu'à ce que le changement soit effectivement écrit sur le disque. Les tampons des données de fichier (contenu du fichier) passaient par le cache mémoire et étaient copiés sur le disque plus tard de façon asynchrone. L'avantage de cette implémentation est qu'elle est effectuée sans risque. S'il y a un problème durant une mise à jour, les méta-données sont toujours dans un état consistant. Un fichier est soit créé complètement soit pas du tout. Si les blocs de données d'un fichier n'ont pas trouvé leur chemin du cache mémoire vers le disque au moment du crash, man:fsck[8] est capable de s'en apercevoir et de réparer le système de fichiers en fixant la taille du fichier à 0. De plus, l'implémentation est claire et simple. L'inconvénient est que la modification des méta-données est lente. Un `rm -r`, par exemple, touche à tous les fichiers dans un répertoire séquentiellement, mais chaque modification du répertoire (effacement d'un fichier) sera écrite de façon synchrone sur le disque. Cela comprend les mises à jour du répertoire lui-même, de la table des inodes, et éventuellement celles sur des blocs indirects alloués par le fichier. Des considérations semblables s'appliquent à la création d'importantes hiérarchies ((`tar -x`). Le deuxième cas est la mise à jour asynchrone des méta-données. C'est le comportement par défaut de Linux/ext2fs et de l'usage de `mount -o async` pour l'UFS des systèmes BSD. Toutes les mises à jour des méta-données passent également par l'intermédiaire d'un cache mémoire, c'est à dire, qu'elles seront mélangées aux mises à jour des données du contenu du fichier. L'avantage de cette implémentation est qu'il n'y a pas besoin d'attendre jusqu'à l'écriture sur le disque de chaque mise à jour de méta-données, donc toutes les opérations qui sont à l'origine d'une grande quantité de mise à jour de méta-données fonctionnent bien plus rapidement que dans le cas synchrone. De plus, l'implémentation est toujours claire et simple, il y a donc peu de risque qu'un bogue se cache dans le code. L'inconvénient est qu'il n'y a aucune garantie du tout sur la cohérence du système de fichiers. S'il y a un problème durant une opération qui met à jour une grande quantité de méta-données (comme une coupure secteur, ou quelqu'un appuyant sur le bouton reset), le système de fichiers sera laissé dans un état imprévisible. Il n'y a aucune opportunité d'examiner l'état du système de fichiers quand le système est à nouveau relancé; les blocs de données d'un fichier pourraient déjà avoir été inscrits sur le disque alors que la mise à jour de la table des inodes ou du répertoire associé n'a pas été faite. Il est en fait impossible d'implémenter un `fsck` qui est capable de nettoyer le chaos résultant (parce que l'information nécessaire n'est pas disponible sur le disque). Si le système de fichiers a été endommagé irrémédiablement, le seul choix est de le recréer avec man:newfs[8] et de récupérer les données à partir de sauvegardes. La solution commune pour ce problème fut d'implémenter une _région de trace_, dont on fait souvent référence sous le terme de _journalisation_, bien que ce terme ne soit pas toujours utilisé de façon cohérente et est occasionnellement utilisé pour d'autres formes de transaction avec trace. Les mises à jour des méta-données sont toujours écrites de façon synchrone, mais seulement sur une petite région du disque. Elles seront plus tard déplacées vers leur emplacement correct. Parce que la région de trace est une petite région contiguë sur le disque, il n'y a pas de grandes distances de déplacement pour les têtes des disques, même durant les opérations importantes, donc ces opérations sont plus rapides que les mises à jour synchrones. De plus la complexité de l'implémentation est relativement limitée, donc le risque de présence de bogues est faible. Un inconvénient est que toutes les méta-données sont écrites deux fois (une fois dans la région de trace et une fois sur l'emplacement correct) donc pour un fonctionnement normal, une baisse des performances pourra en résulter. D'autre part, dans le cas d'un crash, toutes les opérations sur les méta-données en attente peuvent rapidement être annulées ou complétées à partir de la zone de trace après le redémarrage du système, ayant pour résultat un démarrage rapide du système de fichiers. Kirk McKusick, le développeur du FFS de Berkeley, a résolu le problème avec les "Soft Updates": toutes les mises à jour des méta-données sont conservées en mémoire et inscrites sur le disque selon une séquence ordonnée ("mise à jour ordonnée des méta-données"). Ceci a pour effet, dans le cas d'un nombre d'opérations sur les méta-données important, que les dernières mises à jour sur un élément "attrapent" les premières si ces dernières sont encore en mémoire et n'ont pas encore été inscrites sur le disque. Donc toutes les opérations sur, par exemple, un répertoire sont généralement effectuées en mémoire avant que la mise à jour ne soit écrite sur le disque (les blocs de données sont ordonnés en fonction de leur position de sorte à ce qu'ils ne soient pas sur le disque avant leur méta-données). Si le système crash, cela provoque un "retour dans les traces" implicite: toutes les opérations qui n'ont pas trouvé leur chemin vers le disque apparaissent comme si elles n'avaient jamais existé. Un état cohérent du système de fichiers est maintenu et apparaît comme étant celui de 30 ou 60 secondes plus tôt. L'algorithme utilisé garantie que toutes les ressources utilisées soient marquées avec leur bons "bitmaps": blocs et inodes. Après un crash, les seules erreurs d'allocation de ressources qui apparaissent sont les ressources qui ont été marquées comme "utilisées" et qui sont en fait "libre". man:fsck[8] reconnaît cette situation, et libère les ressources qui ne sont plus utilisées. On peut ignorer sans risque l'état "sale" d'un système de fichiers après un crash en forçant son montage avec `mount -f`. Afin de libérer les ressources qui peuvent être inutilisées, man:fsck[8] doit être exécuté plus tard. C'est l'idée qu'il y a derrière le "_background fsck_" (fsck en tâche de fond): au démarrage du système, seule un "_snapshot_" (photographie) du système de fichiers est prise. La commande `fsck` peut être exécutée plus tard sur ce système de fichiers. Tous les systèmes de fichiers peuvent être montés "sales", donc le système passe en mode multi-utilisateurs. Ensuite, les `fsck` en tâche de fond seront programmés pour tous les systèmes de fichiers pour lesquels c'est nécessaire, pour libérer les ressources qui peuvent être inutilisées (les systèmes qui n'utilisent pas les "Soft Updates" ont toujours besoin du `fsck` en avant plan). L'avantage est que les opérations sur les méta-données sont presque aussi rapides que les mises à jour asynchrones (i.e. plus rapide qu'avec le "_logging_" - traçage, qui doit écrire les méta-données deux fois). Les inconvénients sont la complexité du code (impliquant un haut risque de bogues dans une zone qui est hautement sensible en raison de risque perte de données utilisateur), et une plus grande consommation en mémoire. De plus il y a quelques particularités que l'on peut rencontrer lors de l'utilisation. Après un crash, l'état du système apparaît être en quelque sorte "plus vieux". Dans des situations où l'approche synchrone classique aurait donné lieu à des fichiers de taille nulle restant après le `fsck`, ces fichiers n'existent pas du tout avec un système de fichiers utilisant les "Soft Updates" parce que ni les méta-données ni les contenus de fichiers n'ont jamais été inscrits sur le disque. L'espace disque n'est pas rendu tant que les mises à jour n'ont pas été inscrites sur le disque, ce qui peut se produire quelques temps après l'exécution de `rm`. Cela peut être à l'origine de problèmes quand on installe une grande quantité de données sur un système de fichiers qui ne dispose pas de suffisamment d'espace pour contenir tous les fichiers deux fois. [[configtuning-kernel-limits]] == Optimisation des limitations du noyau [[file-process-limits]] === Limitations sur les fichiers et les processus [[kern-maxfiles]] ==== `kern.maxfiles` Le paramètre `kern.maxfiles` peut être augmenté ou diminué en fonction des besoins du système. Cette variable indique le nombre maximal de descripteurs de fichier sur votre système. Quand la table de descripteurs de fichier est pleine, le message `file: table is full` s'affichera régulièrement dans le tampon des messages système, qui peut être visualisé avec la commande `dmesg`. Chaque fichier ouvert, chaque "socket", ou chaque emplacement en pile utilise un descripteur de fichier. Un serveur important peut facilement demander plusieurs milliers de descripteurs de fichiers, en fonction du type et du nombre de services s'exécutant en même temps. Sous les anciennes versions de FreeBSD, la valeur par défaut de `kern.maxfile` est fixée par l'option `maxusers` dans votre fichier de configuration du noyau. `kern.maxfiles` augmente proportionnellement avec la valeur de `maxusers`. Quand vous compilez un noyau sur mesure, il est bon de paramétrer cette option en fonction de l'utilisation de votre système. Ce nombre fixe la plupart des limites pré-définies du noyau. Même si une machine de production pourra ne pas avoir en réalité 256 utilisateurs connectés simultanément, les ressources requises pourront être semblables pour un serveur web important. La variable `kern.maxusers` est automatiquement ajustée au démarrage en fonction de la quantité de mémoire disponible dans le système, sa valeur peut être connue durant le fonctionnement du système en examinant la valeur de la variable sysctl en lecture seule: `kern.maxusers`. Certains systèmes auront besoin de valeurs plus élevées ou plus faibles pour `kern.maxusers` et pourront donc la fixer au chargement du système; des valeurs de 64, 128, ou 256 ne sont pas inhabituelles. Nous recommandons de ne pas dépasser 256 à moins que vous ayez besoin d'un grand nombre de descripteurs de fichiers; plusieurs des variables dont la valeur par défaut dépend de `kern.maxusers` peuvent être fixées individuellement au démarrage ou en fonctionnement dans le fichier [.filename]#/boot/loader.conf# (voir la page de manuel man:loader.conf[5] ou le fichier [.filename]#/boot/defaults/loader.conf# pour des exemples) ou comme décrit en d'autres endroits dans ce document. Sous les anciennes versions, le système auto-ajuste ce paramètre pour vous si vous le fixez explicitement à `0`. En paramétrant cette option, vous devrez fixer `maxusers` à 4 au moins, en particulier si vous utilisez le système X Window ou compilez des logiciels. La raison de cela est que la valeur la plus importante que dimensionne `maxusers` est le nombre maximal de processus, qui est fixé à `20 + 16 * maxusers`, donc si vous positionnez `maxusers` à 1, alors vous ne pouvez avoir que 36 processus en simultanés, comprenant les 18, environ, que le système lance au démarrage et les 15, à peu près, que vous créerez probablement au démarrage du système X Window. Même une tâche simple comme la lecture d'une page de manuel lancera jusqu'à neuf processus pour la filtrer, la décompresser, et l'afficher. Fixer `maxusers` à 64 autorisera jusqu'à 1044 processus simultanés, ce qui devrait suffire dans la plupart des cas. Si, toutefois, vous obtenez le message d'erreur tant redouté quand vous tentez d'exécuter un nouveau programme, ou gérez un serveur avec un grand nombre d'utilisateurs en simultanés (comme `ftp.FreeBSD.org`), vous pouvez toujours augmenter cette valeur et recompiler le noyau. [NOTE] ==== `maxusers` ne limite _pas_ le nombre d'utilisateurs qui pourront ouvrir une session sur votre machine. Cette valeur dimensionne simplement différentes tables à des valeurs raisonnables en fonction du nombre maximal d'utilisateur que vous aurez vraisemblablement sur votre système et combien de processus chacun d'entre eux pourra utiliser. ==== ==== `kern.ipc.somaxconn` La variable sysctl `kern.ipc.somaxconn` limite la taille de la file d'attente acceptant les nouvelles connexions TCP. La valeur par défaut de `128` est généralement trop faible pour une gestion robuste des nouvelles connexions dans un environnement de serveur web très chargé. Pour de tels environnements, il est recommandé d'augmenter cette valeur à `1024` ou plus. Le "daemon" en service peut de lui-même limiter la taille de la file d'attente (e.g. man:sendmail[8], ou Apache) mais disposera, la plupart du temps, d'une directive dans son fichier de configuration pour ajuster la taille de la file d'attente. Les files d'attentes de grandes tailles sont plus adaptées pour éviter les attaques par déni de service (). [[nmbclusters]] === Limitations réseau L'literal du noyau `NMBCLUSTERS` fixe la quantité de "Mbuf";s disponibles pour le système. Un serveur à fort trafic avec un nombre faible de "Mbuf";s sous-emploiera les capacités de FreeBSD. Chaque "cluster" représente approximativement 2 Ko de mémoire, donc une valeur de 1024 représente 2 mégaoctets de mémoire noyau réservée pour les tampons réseau. Un simple calcul peut être fait pour déterminer combien sont nécessaires. Si vous avez un serveur web qui culmine à 1000 connexions simultanées, et que chaque connexion consomme un tampon de réception de 16Ko et un tampon d'émission de 16 Ko, vous avez approximativement besoin de 32 Mo de tampon réseau pour couvrir les besoin du serveur web. Un bon principe est de multiplier ce nombre par 2, soit 2x32 Mo / 2 Ko = 64 Mo / 2 Ko =32768. Nous recommandons des valeurs comprises entre 4096 et 32768 pour les machines avec des quantités de mémoire plus élevées. Vous ne devriez, dans aucun circonstance, spécifier de valeur élevée arbitraire pour ce paramètre étant donné que cela peut être à l'origine d'un plantage au démarrage. L'option `-m` de man:netstat[1] peut être utilisée pour observer l'utilisation des "clusters". La variable `kern.ipc.nmbclusters` configurable au niveau du chargeur est utilisée pour ajuster cela au démarrage. Seules les anciennes versions de FreeBSD vous demanderont d'utiliser l'option de configuration du noyau `NMBCLUSTERS`. Pour les serveurs chargés qui font une utilisation intensive de l'appel système man:sendfile[2], il peut être nécessaire d'augmenter le nombre de tampons man:sendfile[2] par l'intermédiaire de l'option de configuration du noyau `NSFBUFS` ou en fixant sa valeur dans le fichier [.filename]#/boot/loader.conf# (consultez la page de manuel man:loader[8] pour plus de détails). Un indicateur de la nécessité d'ajuster ce paramètre est lorsque des processus sont dans l'état `sfbufa`. La variable sysctl `kern.ipc.nsfbufs` est un aperçu en lecture seule de la variable du noyau. Ce paramètre s'ajuste de façon optimale avec `kern.maxusers`, il peut être cependant nécessaire de l'ajuster en fonction des besoins. [IMPORTANT] ==== Même si une "socket" a été marquée comme étant non-bloquante, un appel de man:sendfile[2] sur la "socket" non-bloquante peut résulter en un blocage de l'appel man:sendfile[2] jusqu'à ce que suffisamment de `struct sf_buf` soient libérées. ==== ==== `net.inet.ip.portrange.*` Les variables `net.inet.ip.portrange.*` contrôlent les intervalles de ports automatiquement alloués aux "socket"s TCP et UDP. Il y a trois intervalles: un intervalle bas, un intervalle par défaut, et intervalle un haut. La plupart des programmes réseau utilisent l'intervalle par défaut qui est contrôlé par `net.inet.ip.portrange.first` et `net.inet.ip.portrange.last`, qui ont pour valeur par défaut respectivement 1024 et 5000. Ces intervalles de ports sont utilisés pour les connexions sortantes, et il est possible de se trouver à court de ports dans certaines conditions. Cela arrive le plus souvent quand votre système fait tourner un proxy web très chargé. L'intervalle de ports n'est pas un problème quand vous exécutez des serveurs qui ne gèrent principalement que des connexions entrantes, comme un server web classique, ou qui ont un nombre de connexions sortantes limitées comme un relai de messagerie. Pour les cas où vous risquez d'être à court de ports, il est recommandé d'augmenter légèrement `net.inet.ip.portrange.last`. Une valeur de `10000`, `20000` ou `30000` doit être suffisante. Vous devriez également penser au problème du coupe-feu lors du changement de l'intervalle des ports. Certains coupes-feu peuvent bloquer de grands intervalles de ports (en général les ports inférieurs) et s'attendent à ce que les systèmes utilisent les intervalles supérieurs pour les connexions sortantes - pour cette raison il n'est pas conseillé de diminuer `net.inet.ip.portrange.first`. ==== Le produit délai-bande passante TCP La limitation du produit délai-bande passante TCP est semblable au TCP/Vegas sous NetBSD. Elle peut être activée en positionnant à `1` la variable `net.inet.tcp.inflight.enable`. Le système tentera alors de calculer le produit délai-bande passante pour chaque connexion et limitera la quantité de données en attente à la quantité juste nécessaire au maintient d'un flux de sortie optimal. Cette fonctionnalité est utile si vous diffusez des données par l'intermédiaire de modems, de connexions Ethernet Gigabit, ou même de liaisons hauts débits WAN (ou toute autre liaison avec un produit délai-bande passante élevé), tout particulièrement si vous utilisez également le dimensionnement des fenêtres d'émission ou que vous avez configuré une fenêtre d'émission importante. Si vous activez cette option, vous devriez également vous assurer que `net.inet.tcp.inflight.debug` est positionnée à `0` (désactive le débogage), et pour une utilisation en production, fixer `net.inet.tcp.inflight.min` à au moins `6144` peut être bénéfique. Notez, cependant, que fixer des minima élevés peut désactiver la limitation de bande passante selon la liaison. La fonction de limitation diminue la quantité de données accumulées dans les files d'attente intermédiaire de routage et de commutation, et diminue également la quantité de données présentes dans les files d'attente de l'interface de la machine locale. Avec moins de paquets dans les files d'attente, les connexions interactives, tout particulièrement sur des modems lents, seront en mesure de fonctionner avec des _temps d'aller-retour_ plus faible. Mais cette fonctionnalité n'affecte que la transmission de données (transmission côté serveur). Ceci n'a aucun effet sur la réception de données (téléchargement). Modifier `net.inet.tcp.inflight.stab` n'est _pas_ recommandé. Ce paramètre est fixé par défaut à la valeur 20, représentant au maximum 2 paquets ajoutés à la fenêtre de calcul du produit délai-bande passante. La fenêtre supplémentaire est nécessaire pour stabiliser l'algorithme et améliorer la réponse aux changements de conditions, mais il peut en résulter des temps de "ping" plus élevés sur les liaisons lentes (mais cependant inférieurs à ce que vous obtiendriez sans l'algorithme de limitation). Dans de tels cas, vous pouvez essayer de réduire ce paramètre à 15, 10, ou 5, et vous pouvez avoir à réduire le paramètre `net.inet.tcp.inflight.min` (par exemple à 3500) pour obtenir l'effet désiré. Ces paramètres ne doivent être réduits qu'en dernier ressort. === Mémoire virtuelle ==== `kern.maxvnodes` Un vnode est la représentation interne d'un fichier ou d'un répertoire. Augmenter le nombre de vnodes disponibles pour le système d'exploitation diminue les accès disque. Cela est normalement géré par le système d'exploitation et n'a pas besoin d'être modifié. Dans certains cas où les accès aux disques sont un goulot d'étranglement pour le système et que ce dernier est à cours de vnodes, ce nombre aura besoin d'être augmenté. La quantité de RAM libre et inactive sera prise en compte. Pour connaître le nombre de vnodes actuellement utilisés: [source,shell] .... # sysctl vfs.numvnodes vfs.numvnodes: 91349 .... Pour connaître le maximum de vnodes utilisables: [source,shell] .... # sysctl kern.maxvnodes kern.maxvnodes: 100000 .... Si l'utilisation actuelle des vnodes est proche du maximum, augmenter de 1000 `kern.maxvnodes` est probablement une bonne idée. Gardez un oeil sur le nombre `vfs.numvnodes`. S'il approche à nouveau le maximum, `kern.maxvnodes` devra être augmenté de manière plus conséquente. Une modification dans votre utilisation de la mémoire devrait être visible dans man:top[1]. Une plus grande quantité de mémoire devrait être annoncée comme active. [[adding-swap-space]] == Ajouter de l'espace de pagination Peu importe comment vous l'avez pensé, parfois un système ne fonctionne pas comme prévu. Si vous trouvez que vous avez besoin de plus d'espace de pagination, il est assez simple d'en rajouter. Vous avez trois manières d'augmenter votre espace de pagination: ajouter un nouveau disque dur, activer la pagination sur NFS, et créer un fichier de pagination sur une partition existante. Pour des informations sur comment chiffrer l'espace de pagination, quelles options existent pour mener à bien cette tâche et pourquoi on devrait le faire, veuillez vous référer à la crossref:disks[swap-encrypting,Chiffrage de l'espace de pagination] du Manuel. [[new-drive-swap]] === Espace de pagination sur un nouveau disque dur ou une partition existante Ajouter un nouveau disque pour l'espace de pagination donne de meilleures performances qu'utiliser une partition sur un disque existant. La configuration des partitions et des disques durs est expliquée dans la crossref:disks[disks-adding,Ajouter des disques] tandis que la crossref:bsdinstall[configtuning-initial,Choix du partitionnement] aborde l'organisation des partitions et les problèmes relatifs à la taille de la partition de l'espace de pagination. Utiliser la commande `swapon` pour ajouter une partition de pagination au système. Par exemple: [source,shell] .... # swapon /dev/ada1s1b .... [WARNING] ==== Il est possible d'utiliser n'importe quelle partition actuellement non-montée, même si cette dernière contient des données. Utiliser `swapon` sur une partition contenant des données écrasera et effacera ces données. Assurez-vous que la partition à utiliser comme espace de pagination est bien celle prévue à cet effet avant d'exécuter `swapon`. ==== Pour ajouter cette partition de pagination automatiquement au démarrage, ajouter une entrée au fichier [.filename]#/etc/fstab#: [.programlisting] .... /dev/ada1s1b none swap sw 0 0 .... Consulter man:fstab[5] pour plus d'explications sur les entrées du fichier [.filename]#/etc/fstab#. Plus d'informations sur `swapon` sont disponibles dans man:swapon[8]. [[nfs-swap]] === Espace de pagination sur NFS L'espace de pagination sur NFS n'est recommandé que si vous n'avez pas de disque dur local sur lequel avoir l'espace de pagination; la pagination sur NFS sera limitée par la bande passante du réseau et sera un fardeau supplémentaire pour le serveur NFS. [[create-swapfile]] === Fichiers de pagination Vous pouvez créer un fichier d'une taille spécifique pour l'utiliser comme fichier de pagination. Dans notre exemple nous utiliserons un fichier de 64MO appelé [.filename]#/usr/swap0#. Vous pouvez, bien sûr, utiliser le nom de votre choix. .Créer un fichier de pagination sous FreeBSD [example] ==== . Le noyau [.filename]#GENERIC# inclut déjà le pilote de disque mémoire (man:md[4]) nécessaire à cette opération. Lors de la compilation d'un noyau sur mesures, assurez-vous d'inclure la ligne suivante dans le fichier de configuration: + [.programlisting] .... device md .... + Pour plus d'information sur la compilation du noyau, veuillez vous réferer à la crossref:kernelconfig[kernelconfig,Configurer le noyau de FreeBSD]. . Créez un fichier de pagination ([.filename]#/usr/swap0#): + [source,shell] .... # dd if=/dev/zero of=/usr/swap0 bs=1024k count=64 .... + . Fixez les bonnes permissions sur [.filename]#/usr/swap0#: + [source,shell] .... # chmod 0600 /usr/swap0 .... + . Activez le fichier de pagination dans [.filename]#/etc/rc.conf#: + [.programlisting] .... swapfile="/usr/swap0" # Set to name of swapfile if aux swapfile desired. .... + . Redémarrez la machine ou activez directement le fichier de pagination: + [source,shell] .... # mdconfig -a -t vnode -f /usr/swap0 -u 0 swapon /dev/md0 .... ==== [[acpi-overview]] == Gestion de l'énergie et des ressources Il est important d'utiliser les ressources matérielles d'une manière efficace. Avant l'apparition de l'ACPI, il était difficile pour les systèmes d'exploitation de gérer l'utilisation de l'alimentation et la température d'un système. Le matériel était géré par le BIOS et donc l'utilisateur avait moins de contrôle et de visibilité sur le paramétrage de la gestion de l'énergie. Une configuration limitée était accessible via l'_Advanced Power Management (APM)_. La gestion de l'énergie et des ressources est un des éléments clés d'un système d'exploitation moderne. Par exemple, vous pourrez vouloir qu'un système d'exploitation surveille certaines limites (et éventuellement vous alerte), au cas où la température de votre système augmente de façon inattendue. Dans cette section, nous fournirons une information complète au sujet de l'ACPI. Il sera fait référence à des documents supplémentaires en fin de section pour plus de détails. [[acpi-intro]] === Qu'est-ce que l'ACPI? L'"interface de configuration et d'alimentation avancée" (ACPI, Advanced Configuration and Power Interface) est une norme créée par un ensemble de constructeurs pour fournir une interface standard à la gestion des ressources et de l'énergie. C'est un élément clé dans le contrôle et la configuration par le système d'exploitation de de la gestion d'énergie, i.e., il permet plus de contrôle et flexibilité au système d'exploitation. Les systèmes modernes ont "repoussé" les limites des interfaces "Plug and Play" antérieures à l'apparition de l'ACPI. L'ACPI est le descendant direct de l'APM (Advanced Power Management - gestion avancée de l'énergie). [[acpi-old-spec]] === Les imperfections de la gestion avancée de l'énergie (APM) Le système de _gestion avancée de l'énergie (APM)_ gère l'utilisation de l'énergie par un système en fonction de son activité. Le BIOS APM est fourni par le fabricant (du système) et est spécifique à la plateforme matérielle. Un pilote APM au niveau du système d'exploitation gère l'accès à l'_interface logicielle APM_ qui autorise la gestion des niveaux de consommation. L'APM devrait être toujours utilisé pour les systèmes fabriqués en ou avant 2000. L'APM présente quatre problèmes majeurs. Tout d'abord la gestion de l'énergie est effectuée par le BIOS (spécifique au constructeur), et le système d'exploitation n'en a aucune connaissance. Un exemple de ce problème, est lorsque l'utilisateur fixe des valeurs pour le temps d'inactivité d'un disque dur dans le BIOS APM, qui une fois dépassé, provoque l'arrêt du disque (par le BIOS) sans le consentement du système d'exploitation. Deuxièmement, la logique de l'APM est interne au BIOS, et agit indépendamment du système d'exploitation. Cela signifie que les utilisateurs ne peuvent corriger les problèmes de leur BIOS APM qu'en flashant un nouveau BIOS; c'est une opération dangereuse, qui si elle échoue peut laisser le système dans un état irrécupérable. Troisièmement, l'APM est une technologie spécifique au constructeur, ce qui veut dire qu'il y a beaucoup de redondances (duplication des efforts) et de bogues qui peuvent être trouvées dans le BIOS d'un constructeur, et qui peuvent ne pas être corrigées dans d'autres BIOS. Et pour terminer, le dernier problème est le fait que le BIOS APM n'a pas suffisamment d'espace pour implémenter une politique sophistiquée de gestion de l'énergie, ou une politique qui peut s'adapter parfaitement aux besoins de la machine. Le _BIOS Plug and Play (PNPBIOS)_ n'était pas fiable dans de nombreuses situations. Le PNPBIOS est une technologie 16 bits, le système d'exploitation doit utiliser une émulation 16 bits afin de faire l'"interface" avec les méthodes PNPBIOS. Le pilote APM FreeBSD est documenté dans la page de manuel man:apm[4]. [[acpi-config]] === Configurer l'ACPI Le pilote [.filename]#acpi.ko# est par défaut chargé par le man:loader[8] au démarrage et ne devrait _pas_ être compilé dans le noyau. La raison derrière cela est que les modules sont plus facile à manipuler, par exemple pour passer à une autre version du module [.filename]#acpi.ko# sans avoir à recompiler le noyau. Cela présente l'avantage de rendre les tests aisés. Une autre raison est que lancer l'ACPI après qu'un système ait terminé son lancement donne souvent lieu à des dysfonctionnements. Si des problèmes surviennent, vous pouvez désactiver l'ACPI. Ce pilote ne devrait et ne peut être déchargé car le bus système l'utilise pour différentes intéraction avec le matériel. L'ACPI peut être déactivé en ajoutant `hint.acpi.0.disabled="1"` dans le fichier [.filename]#/boot/loader.conf# ou directement à l'invite du chargeur (man:loader[8]). [NOTE] ==== L'ACPI et l'APM ne peuvent coexister et devraient être utilisé séparément. Le dernier chargé s'arrêtera s'il détecte l'autre en fonctionnement. ==== L'ACPI peut être utilisé pour mettre en veille un système avec man:acpiconf[8], les options `-s` et `1-5`. La plupart des utilisateurs n'auront besoin que de `1` ou `3` (système suspendu en RAM). L'option `5` provoquera un arrêt de l'alimentation par logiciel, effet identique à un: [source,shell] .... # halt -p .... D'autres options sont disponibles via man:sysctl[8]. Consultez les pages de manuel man:acpi[4] et man:acpiconf[8] pour plus d'informations. [[ACPI-debug]] == Utiliser et déboguer l'ACPI sous FreeBSD L'ACPI est une nouvelle méthode de recherche des périphériques, de gestion de l'énergie, et fourni un accès standardisé à différents matériels gérés auparavant par le BIOS. Des progrès ont été fait vers un fonctionnement de l'ACPI sur tous les systèmes, mais des bogues dans le "bytecode" du _langage machine ACPI_ (_ACPI Machine Language_-AML), des imperfections dans les sous-systèmes du noyau FreeBSD, et des bogues dans l'interpréteur ACPI-CA d'Intel(R) continuent d'apparaître. Ce document est destiné à vous permettre d'aider les développeurs du système ACPI sous FreeBSD à identifier la cause originelle des problèmes que vous observez et à déboguer et développer une solution. Merci de lire ce document et nous espérons pouvoir résoudre les problèmes de votre système. [[ACPI-submitdebug]] === Soumettre des informations de débogage [NOTE] ==== Avant de soumettre un problème, assurez-vous d'utiliser la dernière version de votre BIOS, et si elle est disponible, la dernière version du firmware du contrôleur utilisé. ==== Pour ceux désirant soumettre directement un problème, veuillez faire parvenir les informations suivantes à la liste link:mailto:freebsd-acpi@FreeBSD.org[freebsd-acpi@FreeBSD.org]: * Description du comportement défectueux, en ajoutant le type et le modèle du système et tout ce qui peut causer l'apparition du bogue. Notez également le plus précisément possible quand le bogue a commencé à se manifester s'il est nouveau. * La sortie de man:dmesg[8] après un `boot -v`, y compris tout message généré lors de la manifestation du bogue. * La sortie de man:dmesg[8] après un `boot -v` avec l'ACPI désactivé, si cette désactivation corrige le problème. * La sortie de `sysctl hw.acpi`. C'est également un bon moyen de déterminer quelles fonctionnalités sont offertes par votre système. * Une URL où peut être trouvé votre _code source ACPI_ (ACPI Source Language-ASL). N'envoyez pas directement l'ASL sur la liste de diffusion, ce fichier peut être très gros. Vous pouvez générer une copie de votre ASL en exécutant la commande suivante: + [source,shell] .... # acpidump -dt > name-system.asl .... + (Remplacez _name_ par votre nom d'utilisateur et _system_ par celui du constructeur/modèle. Par exemple: [.filename]#njl-FooCo6000.asl#) La plupart des développeurs lisent la liste {freebsd-current} mais soumettez également les problèmes rencontrés à la liste {freebsd-acpi} afin d'être sûr qu'ils seront vus. Soyez patient, nous avons tous un travail à plein temps qui nous attend ailleurs. Si votre bogue n'est pas immédiatement apparent, nous vous demanderons probablement de soumettre un PR par l'intermédiaire de man:send-pr[1]. Quand vous remplirez un PR, veillez à inclure les mêmes informations que celles précisées précédemment. Cela nous aidera à cerner et à résoudre le problème. N'envoyez pas de PR sans avoir contacté auparavant la liste {freebsd-acpi} étant donné que nous utilisons les PRs comme pense-bêtes de problèmes existants, et non pas comme mécanisme de rapport. Il se peut que votre problème puisse avoir déjà été signalé par quelqu'un d'autre. [[ACPI-background]] === Information de fond L'ACPI est présent sur tous les ordinateurs modernes compatibles avec l'une des architectures ia32 (x86), ia64 (Itanium), et amd64 (AMD). La norme complète définit des fonctionnalités comme la gestion des performances du CPU, des contrôles des niveaux d'énergie, des zones de températures, divers systèmes d'utilisation des batteries, des contrôleurs intégrés, et l'énumération du bus. La plupart des systèmes n'implémentent pas l'intégralité des fonctionnalités de la norme. Par exemple, un ordinateur de bureau n'implémentera généralement que la partie énumération de bus alors qu'un ordinateur portable aura également le support de la gestion du refroidissement et de la batterie. Les ordinateurs portables disposent également des modes de mise en veille et de réveil, avec toute la complexité qui en découle. Un système compatible ACPI dispose de divers composants. Les fabricants de BIOS et de circuits fournissent des tables de description (FADT) fixes en mémoire qui définissent des choses comme la table APIC (utilisée par les systèmes SMP), les registres de configuration, et des valeurs de configuration simples. De plus, est fournie une table de "bytecode" (la _table différenciée de description du système-Differentiated System Description Table_ DSDT) qui spécifie sous forme d'une arborescence l'espace des noms des périphériques et des méthodes. Le pilote ACPI doit analyser les tables, implémenter un interpréteur pour le "bytecode", et modifier les pilotes de périphériques et le noyau pour qu'ils acceptent des informations en provenance du sous-système ACPI. Pour FreeBSD, Intel(R) fourni un interpréteur (ACPI-CA) qui est partagé avec Linux et NetBSD. L'emplacement du code source de l'interpréteur ACPI-CA est [.filename]#src/sys/contrib/dev/acpica#. Le code "glu" permettant à ACPI-CA de fonctionner sous FreeBSD se trouve dans [.filename]#src/sys/dev/acpica/Osd#. Et enfin, les pilotes qui gèrent les différents périphériques ACPI se trouvent dans [.filename]#src/sys/dev/acpica#. [[ACPI-comprob]] === Problèmes courants Pour un fonctionnement correct de l'ACPI, il faut que toutes les parties fonctionnent correctement. Voici quelques problèmes courants, par ordre de fréquence d'apparition, et quelques contournements ou corrections possibles. ==== Problèmes avec la souris Dans certains cas le réveil après une mise en veille sera à l'origine d'un dysfonctionnement de la souris. Une solution connue est d'ajouter la ligne `hint.psm.0.flags="0x3000"` au fichier [.filename]#/boot/loader.conf#. Si cela ne fonctionne pas, pensez à envoyer un rapport de bogue comme décrit plus haut. ==== Mise en veille/réveil L'ACPI dispose de trois modes de mise en veille en RAM (STR-Suspend To RAM), `S1` à `S3`, et un mode de mise en veille vers le disque dur (`STD`-Suspend To Disk), appelé `S4`. Le mode `S5` est un arrêt "soft" et est le mode dans lequel se trouve votre système quand il est branché mais pas allumé. Le mode `S4` peut être implémenté de deux manières différentes. Le mode ``S4``BIOS est une mise en veille vers le disque assistée par le BIOS. Le mode ``S4``OS est implémenté intégralement par le système d'exploitation. Commencez par examiner la sortie de `sysctl hw.acpi` à la recherche d'éléments concernant les modes de mise en veille. Voici les résultats pour un Thinkpad: [source,shell] .... hw.acpi.supported_sleep_state: S3 S4 S5 hw.acpi.s4bios: 0 .... Cela signifie que nous pouvons utiliser `acpiconf -s` pour tester les modes `S3`, ``S4``OS, et `S5`. Si `s4bios` était égal à `1`, nous disposerions d'un support ``S4``BIOS à la place de ``S4``OS. Quand vous testez la mise en veille et le réveil, commencez avec le mode `S1`, pour voir s'il est supporté. Ce mode doit fonctionner dans la plupart des cas puisqu'il nécessite peu de support. Le mode `S2` n'est pas implémenté, mais si vous en disposez, il est similaire au mode `S1`. La chose suivante à essayer est le mode `S3`. C'est le mode STR le plus avancé et il nécessite un support du pilote important pour réinitialiser correctement votre matériel. Si vous avez des problèmes au réveil de la machine, n'hésitez pas à contacter la liste {freebsd-acpi} mais ne vous attendez pas à ce que le problème soit résolu puisqu'il y a de nombreux pilotes/matériels qui nécessitent plus de tests et de développement. Un problème courant avec la mise en veille/le réveil est que de nombreux pilotes de périphériques ne sauvegardent pas, ne restaurent pas, ou ne réinitialisent pas leurs logiciel, registres ou mémoire proprement. En premier lieu pour débogguer le problème, essayez: [source,shell] .... # sysctl debug.bootverbose=1 # sysctl debug.acpi.suspend_bounce=1 # acpiconf -s 3 .... Ce test émule le cycle de mise en veille/réveil de tous les pilotes de périphériques sans réellement passer dans l'état `S3`. Dans certains cas, les problèmes comme la perte de l'état du périphérique, le dépassement du délai du chien de garde du périphérique, les tentatives répétées, peuvent être capturés avec cette méthode. Notez que le système n'entrera pas vraiment dans l'état `S3`, ce qui signifie que les périphériques peuvent ne pas perdre leur alimentation, et nombreux fonctionneront correctement même si les méthodes de mise en veille/réveil sont totalement absentes, contrairement au cas d'un véritable état `S3`. Les cas plus difficiles nécessitent un matériel supplémentaire, tel qu'un port série et un câble pour débogguer à l'aide d'une console série, un port firewire et un câble pour l'utilisation de man:dcons[4], et des compétences en debogguage du noyau. Pour isoler le problème, retirez du noyau tous les pilotes de périphériques possibles. Si cela fonctionne, vous pouvez alors identifier le pilote fautif en chargeant les pilotes un à un jusqu'à l'apparition du problème. Généralement les pilotes binaires comme [.filename]#nvidia.ko#, les pilotes d'affichage X11, ou les pilotes USB seront victimes de la plupart des problèmes tandis que ceux concernant les interfaces Ethernet fonctionneront normalement. Si vous pouvez charger/décharger les pilotes de périphériques correctement, vous pouvez automatiser cela en ajoutant les commandes appropriées dans les fichiers [.filename]#/etc/rc.suspend# et [.filename]#/etc/rc.resume#. Il y a un exemple en commentaire pour décharger ou charger un pilote. Essayez de fixer `hw.acpi.reset_video` à zéro (`0`) si votre affichage est corrompu après un réveil de la machine. Essayez des valeurs plus grandes ou plus faibles pour `hw.acpi.sleep_delay` pour voir si cela aide. Une autre méthode est d'essayer de charger une distribution Linux récente avec le support ACPI et tester la mise en veille et le réveil sur le même matériel. Si cela fonctionne sous Linux, c'est probablement donc un problème de pilotes FreeBSD et déterminer quel pilote est responsable des dysfonctionnements nous aidera à corriger le problème. Notez que les personnes qui maintiennent l'ACPI sous FreeBSD ne s'occupe pas généralement des autres pilotes de périphériques (comme le son, le système ATA, etc.), aussi tout rapport concernant un problème de pilote devrait probablement en fin de compte être posté sur la liste {freebsd-current} et communiqué au responsable du pilote. Si vous vous sentez une âme d'aventurier, commencez à ajouter des man:printf[3]s de débogage dans un pilote problématique pour déterminer à quel moment dans sa fonction de réveil il se bloque. Enfin, essayez de désactiver l'ACPI et d'activer l'APM à la place, pour voir si la mise en veille et le réveil fonctionnent avec l'APM, tout particulièrement dans le cas de matériel ancien (antérieur à 2000). Cela prend du temps aux constructeurs de mettre en place le support ACPI et le matériel ancien aura sûrement des problèmes de BIOS avec l'ACPI. ==== Blocages du système (temporaires ou permanents) La plupart des blocages système sont le résultat d'une perte d'interruptions ou d'une tempête d'interruptions. Les circuits ont beaucoup de problèmes en fonction de la manière dont le BIOS configure les interruptions avant le démarrage, l'exactitude de la table APIC (MADT), et le routage du _System Control Interrupt_ (SCI). Les tempêtes d'interruptions peuvent être distinguées des pertes d'interruptions en contrôlant la sortie de la commande `vmstat -i` en examinant la ligne mentionnant `acpi0`. Si le compteur s'incrémente plusieurs fois par seconde, vous êtes victime d'une tempête d'interruptions. Si le système semble bloqué, essayez de basculer sous DDB (kbd:[CTRL+ALT+ESC] sous la console) et tapez `show interrupts`. Votre plus grand espoir quand vous faites face à des problèmes d'interruptions est d'essayer de désactiver le support APIC avec la ligne `hint.apic.0.disabled="1"` dans le fichier [.filename]#loader.conf#. ==== Paniques Les paniques sont relativement rares dans le cas de l'ACPI et sont au sommet des priorités en matière de problèmes à corriger. Le premier point est d'isoler les étapes nécessaires à la reproduction de la panique (si possible) et d'obtenir une trace de débogage. Suivez l'aide sur l'activation de `options DDB` et la configuration d'une console série (lire la crossref:serialcomms[serialconsole-ddb,Entering the DDB Debugger from the Serial Line]) ou la configuration d'une partition man:dump[8]. Vous pouvez obtenir une trace de débogage sous DDB avec la commande `tr`. Si vous devez recopier à la main la trace de débogage, assurez-vous de relever les cinq dernières lignes et les cinq premières ligne de la trace. Ensuite essayez d'isoler le problème en démarrant avec l'ACPI désactivé. Si cela fonctionne, vous pouvez isoler le sous-système ACPI en utilisant différentes valeurs pour l'option `debug.acpi.disable`. Consultez la page de manuel man:acpi[4] pour des exemples. ==== Le système redémarre après une mise en veille ou un arrêt Tout d'abord, essayez de fixer `hw.acpi.disable_on_poweroff="0"` dans man:loader.conf[5]. Cela empêche l'ACPI de désactiver divers événements lors du processus d'arrêt. Certains systèmes ont besoin d'avoir cette valeur fixée à `1` (valeur par défaut) pour la même raison. Cela corrige généralement le problème d'un système démarrant spontanément après une mise en veille ou un arrêt. ==== Autres problèmes Si vous rencontrez d'autres problèmes avec l'ACPI (impossible de travailler avec une station d'amarrage, périphériques non détectés, etc.), veuillez envoyer un courrier descriptif à la liste de diffusion; cependant, certains de ces problèmes peuvent être relatifs à des partie incomplètes du sous-système ACPI et qui pourront prendre du temps à être implémentées. Soyez patient et prêt à tester les correctifs que nous pourront éventuellement vous envoyer. [[ACPI-aslanddump]] === ASL, `acpidump`, et IASL Le problème le plus courant est le fait que les constructeurs fournissent des "bytecodes" erronés (ou plus simplement bogués!). Cela se manifeste généralement sur la console par des messages du noyau du type: [source,shell] .... ACPI-1287: *** Error: Method execution failed [\\_SB_.PCI0.LPC0.FIGD._STA] \\ (Node 0xc3f6d160), AE_NOT_FOUND .... La plupart du temps vous pouvez corriger ces problèmes en mettant à jour votre BIOS avec la dernière version disponible. La majorité des messages sur la console sont inoffensifs mais si vous avez d'autres problèmes comme l'état de la batterie qui ne fonctionne pas, ce sont de bonnes raisons pour commencer à jeter un oeil à ces problèmes dans l'AML. Le "bytecode", connu sous le nom d'AML, est compilé à partir d'un langage source appelé ASL. L'AML se trouve dans une table appelée DSDT. Pour obtenir une copie de votre ASL, utilisez man:acpidump[8]. Vous devriez utiliser de paire les options `-t` (qui affiche le contenu des tables fixes) et `-d` (qui désassemble l'AML en ASL). Consultez la section <> pour un exemple de syntaxe. Le tout premier test que vous pouvez effectuer est de recompiler votre ASL à la recherche d'erreurs. Les avertissements peuvent être généralement ignorés mais les erreurs sont des bogues qui normalement empêchent l'ACPI de fonctionner correctement. Pour recompiler votre ASL, utilisez la commande suivante: [source,shell] .... # iasl your.asl .... [[ACPI-fixasl]] === Correction de votre ASL A long terme, notre objectif est que tout le monde puisse avoir un système ACPI fonctionnant sans aucune intervention de l'utilisateur. Actuellement, nous sommes toujours en train de développer des solutions pour contourner les erreurs courantes faites par les fabricants de BIOS. L'interpréteur de Microsoft(R) ([.filename]#acpi.sys# et [.filename]#acpiec.sys#) ne contrôle pas de façon stricte la conformité avec la norme, et par conséquent de nombreux fabricants de BIOS qui testent l'ACPI uniquement sous Windows(R) ne corrigent donc jamais leur ASL. Nous espérons poursuivre à identifier et documenter avec exactitude les comportements non-standards autorisés par l'interpréteur de Microsoft(R) et les reproduire de manière à permettre à FreeBSD de fonctionner sans obliger les utilisateurs à corriger leur ASL. Comme solution et pour nous aider à identifier ces comportements, vous pouvez corriger manuellement votre ASL. Si cela fonctionne pour vous, veuillez nous envoyer un man:diff[1] de l'ancien et du nouveau ASL de façon à ce que nous puissions corriger le comportement incorrect dans ACPI-CA et rendre donc inutile à l'avenir votre correctif. Voici une liste des messages d'erreur courants, leur cause, et comment les corriger: ==== Dépendances _OS Certains AMLs supposent que le monde n'est fait de que différentes versions de Windows(R). Vous pouvez demander à FreeBSD de s'annoncer comme étant n'importe quel système d'exploitation pour voir si cela corrige les problèmes que vous pouvez rencontrer. Une manière simple de faire cela est de fixer la variable `hw.acpi.osname="Windows 2001"` dans [.filename]#/boot/loader.conf# ou avec une autre chaîne de caractères que vous trouvez dans l'ASL. ==== `Missing Return statements` Certaines méthodes ne renvoient pas explicitement une valeur comme la norme le demande. Bien qu'ACPI-CA ne gère pas cela, FreeBSD contourne ce problème en renvoyant implicitement la valeur. Vous pouvez également ajouter des "Return statements" explicites où cela est nécessaire si vous connaissez la valeur à renvoyer. Pour forcer `iasl` à compiler l'ASL, utilisez l'option `-f`. ==== Remplacer l'AML par défaut Après avoir personnalisé [.filename]#votre.asl#, vous voudrez le compiler, pour cela exécutez: [source,shell] .... # iasl your.asl .... Vous pouvez ajouter l'option `-f` pour forcer la création de l'AML, même s'il y a des erreurs lors de la compilation. Rappelez-vous que certaines erreurs (e.g., `missing Return statements`) sont automatiquement contournées par l'interpréteur. [.filename]#DSDT.aml# est le fichier de sortie par défaut pour `iasl`. Vous pouvez le charger à la place de la version boguée de votre BIOS (qui est toujours présent dans la mémoire flash) en éditant le fichier [.filename]#/boot/loader.conf# comme suit: [.programlisting] .... acpi_dsdt_load="YES" acpi_dsdt_name="/boot/DSDT.aml" .... Assurez-vous de bien copier votre fichier [.filename]#DSDT.aml# dans le répertoire [.filename]#/boot#. [[ACPI-debugoutput]] === Obtenir d'ACPI une sortie de débogage Le pilote ACPI dispose d'une fonction de débogage très flexible. Elle vous permet de spécifier un ensemble de sous-systèmes ainsi que le niveau de verbosité. Les sous-systèmes que vous désirez déboguer sont indiqués sous la forme de "couches" et sont divisés en composants ACPI-CA (ACPI_ALL_COMPONENTS) et en supports matériel ACPI (ACPI_ALL_DRIVERS). La verbosité de la sortie de débogage est spécifiée par un "niveau" et des intervalles de ACPI_LV_ERROR (rapporte juste les erreurs) à ACPI_LV_VERBOSE (tout). Le "niveau" est un masque de bits séparés par des espaces, aussi de nombreuses options peuvent être fixées à la fois. Dans la pratique, vous voudrez utiliser un console série pour afficher la sortie si les informations de débogage sont si importantes qu'elles dépassent le tampon des messages de la console. Une liste complète des couches individuelles et des niveaux peut être trouvée dans la page de manuel man:acpi[4]. L'affichage des informations de débogage n'est pas activé par défaut. Pour l'activer, ajoutez la ligne `options ACPI_DEBUG` à votre fichier de configuration du noyau si l'ACPI est compilé dans le noyau. Vous pouvez ajouter la ligne `ACPI_DEBUG=1` à votre fichier [.filename]#/etc/make.conf# pour l'activer de façon globale. Si l'ACPI est sous forme de module, vous pouvez recompiler votre module [.filename]#acpi.ko# comme suit: [source,shell] .... # cd /sys/modules/acpi/acpi && make clean && make ACPI_DEBUG=1 .... Installez [.filename]#acpi.ko# dans le répertoire [.filename]#/boot/kernel# et indiquez le niveau et la couche désirée dans [.filename]#loader.conf#. L'exemple suivant active les messages de débogage pour tous les composants ACPI-CA et tous les pilotes de matériel ACPI (CPU, LID, etc.). Il n'affichera que les messages d'erreur, c'est le niveau le moins verbeux. [.programlisting] .... debug.acpi.layer="ACPI_ALL_COMPONENTS ACPI_ALL_DRIVERS" debug.acpi.level="ACPI_LV_ERROR" .... Si l'information que vous voulez est déclenchée par un événement particulier (disons par exemple une mise en veille suivi d'un réveil), vous pouvez abandonner les modifications dans [.filename]#loader.conf# et utiliser à la place `sysctl` pour indiquer la couche et le niveau après le démarrage et préparer votre système pour cet événement particulier. Les variables `sysctl` sont appelées de la même manière que dans le fichier [.filename]#loader.conf#. [[ACPI-References]] === Références Plus d'information au sujet de l'ACPI peut être trouvé aux emplacements suivants: * La liste de diffusion {freebsd-acpi} * Les archives de la liste de diffusion ACPI http://lists.freebsd.org/pipermail/freebsd-acpi/[http://lists.freebsd.org/pipermail/freebsd-acpi/] * Les archives de l'ancienne liste de diffusion ACPI http://home.jp.FreeBSD.org/mail-list/acpi-jp/[http://home.jp.FreeBSD.org/mail-list/acpi-jp/] -* La spécification ACPI 2.0 http://acpi.info/spec.htm[http://acpi.info/spec.htm] +* La https://uefi.org/specifications#ACPI[spécification ACPI] * Les pages de manuel: man:acpi[4], man:acpi_thermal[4], man:acpidump[8], man:iasl[8], man:acpidb[8] * http://www.cpqlinux.com/acpi-howto.html#fix_broken_dsdt[Ressource sur le débogage de la DSDT]. (Utilise un exemple basé sur du matériel Compaq mais qui est en général intéressant.) diff --git a/documentation/content/hu/books/handbook/config/_index.adoc b/documentation/content/hu/books/handbook/config/_index.adoc index 794bc41c38..ea61acd737 100644 --- a/documentation/content/hu/books/handbook/config/_index.adoc +++ b/documentation/content/hu/books/handbook/config/_index.adoc @@ -1,1411 +1,1411 @@ --- title: 11. Fejezet - Beállítás és finomhangolás part: III. Rész Rendszeradminisztráció prev: books/handbook/partiii next: books/handbook/boot showBookMenu: true weight: 15 path: "/books/handbook/" --- [[config-tuning]] = Beállítás és finomhangolás :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 11 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/config/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[config-synopsis]] == Áttekintés A FreeBSD egyik fontos szempontja a rendszer megfelelõ beállítása, aminek segítségével elkerülhetjük a késõbbi frissítések során keletkezõ kellemetlenségeket. Ez a fejezet a FreeBSD beállítási folyamatából kíván minél többet bemutatni, köztük a FreeBSD rendszerek finomhangolására szánt paramétereket. A fejezet elolvasása során megismerjük: * hogyan dolgozzunk hatékonyan az állományrendszerekkel és a lapozóállományokkal; * az [.filename]#rc.conf# beállításának alapjait és a [.filename]#/usr/local/etc/rc.d# könyvtárban található indítási rendszert; * hogyan állítsunk be és próbáljunk ki egy hálózati kártyát; * hogyan állítsunk be virtuális címeket a hálózati eszközeinken; * hogyan használjuk az [.filename]#/etc# könyvtárban megtalálható különféle konfigurációs állományokat; * hogyan hangoljuk a FreeBSD mûködését a `sysctl` változóinak segítségével; * hogyan hangoljuk a lemezek teljesítményét és módosítsuk a rendszermag korlátozásait. A fejezet elolvasásához ajánlott: * a UNIX(R) és a FreeBSD alapjainak megértése (crossref:basics[basics,A UNIX alapjai]); * a rendszermag beállításához és fordításához kötõdõ alapok ismerete (crossref:kernelconfig[kernelconfig,A FreeBSD rendszermag testreszabása]). [[configtuning-initial]] == Kezdeti beállítások === A partíciók kiosztása ==== Alappartíciók Amikor a man:bsdlabel[8] vagy a man:sysinstall[8] segítségével állományrendszereket telepítünk, nem szabad figyelmen kívül hagynunk a tényt, hogy a merevlemezes egységekben a külsõ sávokból gyorsabban lehet hozzáférni az adatokhoz, mint a belsõkbõl. Emiatt a kisebb és gyakrabban elérni kívánt állományrendszereket a meghajtó lemezének külsejéhez közel kell létrehozni, míg például a [.filename]#/usr# partícióhoz hasonló nagyobb partíciókat annak belsõ része felé. A partíciókat a következõ sorrendben érdemes kialakítani: gyökér (rendszerindító), lapozóállomány, [.filename]#/var# és [.filename]#/usr#. A [.filename]#/var# méretének tükröznie kell a számítógép szándékolt használatát. A [.filename]#/var# partíción foglalnak helyet a felhasználók postaládái, a naplóállományok és a nyomtatási sorok. A postaládák és a naplóállományok egészen váratlan mértékben is képesek megnövekedni attól függõen, hogy mennyi felhasználónk van a rendszerben és hogy mekkora naplókat tartunk meg. Itt a legtöbb felhasználónak soha nem lesz szüksége egy gigabyte-nál több helyre. [NOTE] ==== Bizonyos esetekben a [.filename]#/var/tmp# könyvtárban azért ennél több tárterület szükségeltetik. Amikor a man:pkg_add[1] segítségével egy friss szoftvert telepítünk a rendszerünkre, akkor a program a [.filename]#/var/tmp# könyvtárba tömöríti ki a hozzá tartozó csomag tartalmát. Ezért a nagyobb szoftvercsomagok, mint például a Firefox vagy az OpenOffice esetén gondok merülhetnek fel, ha nem rendelkezünk elegendõ szabad területtel a [.filename]#/var/tmp# könyvtárban. ==== A [.filename]#/usr# partíció tartalmaz számos, a rendszer mûködéséhez elengedhetetlenül fontos állományt, többek közt a portok gyûjteményét (ajánlott, lásd man:ports[7]) és a forráskódot (választható). A portok és az alaprendszer forrásai telepítés során választhatóak, de telepítésük esetén akkor ezen a partíción legalább két gigabyte-nyi hely ajánlott. Vegyük figyelembe a tárbeli igényeket, amikor megválasztjuk a partíciók méretét. Igen kellemetlen lehet, amikor úgy futunk ki az egyik partíción a szabad helybõl, hogy a másikat alig használjuk. [NOTE] ==== Egyes felhasználók szerint elõfordulhat, hogy a man:sysinstall[8] `Auto-defaults` opciója a [.filename]#/var# és [.filename]#/# partíciók méretét túl kicsire választja. Particionáljunk okosan és nagylelkûen! ==== [[swap-design]] ==== A lapozóállomány partíciója Általános szabály, hogy a lapozóállományt tároló partíció mérete legyen a rendszer fizikai memóriájának (RAM) kétszerese. Például, ha a számítógépünk 128 megabyte memóriával rendelkezik, akkor a lapozóállomány méretének 256 megabyte-nak kell lennie. Az ennél kevesebb memóriát maguknak tudó rendszerek több lapozóállománnyal jobban teljesítenek. 256 megabyte-nál kevesebb lapozóállományt semmiképpen sem ajánlunk, és inkább a fizikai memóriát érdemes bõvítenünk. A rendszermag virtuális memóriát kezelõ lapozási algoritmusait úgy állították be, hogy abban az esetben teljesítsenek a legjobban, ha a lapozóállomány mérete legalább kétszerese a központi memória mennyiségének. A túl kicsi lapozóállomány beállítása rontja a virtuális memória lapkeresésési rutinjának hatékonyságát és a memória bõvítése esetén még további gondokat is okozhat. A több SCSI-lemezzel (vagy a különbözõ vezérlõkre csatlakoztatott több IDE-lemezzel) bíró nagyobb rendszerek esetében érdemes minden egyes (de legfeljebb négy) meghajtóra beállítani lapozóállományt. A lapozóállományoknak közel azonos méretûnek kell lenniük. A rendszermag tetszõleges méretûeket képes kezelni, azonban a belsejében alkalmazott adatszerkezetek a legnagyobb lapozóállomány méretének négyszereséig képesek növekedni. Ha a lapozóállományokat nagyjából ugyanazon a méreten tartjuk, akkor a rendszermag képes lesz a lapozáshoz felhasznált területet optimálisan elosztani a lemezek között. A nagyobb lapozóállományok használata még akkor is jól jön, ha nem is használjuk annyira. Segítségével sokkal könnyebben talpra tudunk állni egy elszabadult program tombolásából, és nem kell rögtön újraindítanunk a rendszert. ==== Miért particionáljunk? Egyes felhasználók úgy gondolják, hogy egyetlen nagyobb méretû partíció mindenre megfelel, ám ez a gondolat több okból is helytelennek tekinthetõ. Elõször is, minden egyes partíciónak eltér a mûködési jellemzõje, és különválasztásukkal lehetõvé válik az állományrendszerek megfelelõ behangolása. Például a rendszerindításhoz használt és a [.filename]#/usr# partíciókat többségében csak olvasásra használják, és nem sokat írnak rájuk. Eközben a [.filename]#/var# és [.filename]#/var/tmp# könyvtárakban zajlik az írások és olvasások túlnyomó része. A rendszer megfelelõ felosztásával a kisebb, intenzívebben írt partíciókon megjelenõ töredezettség nem szivárog át a többségében csak olvasásra használt partíciókra. Ha a sokat írt partíciókat közel tartjuk a lemez széléhez, akkor azokon a partíciókon növekszik az I/O teljesítménye, ahol az a leggyakrabban megjelenik. Mivel mostanság az I/O teljesítményére inkább a nagyobb partíciók esetén van szükség, azzal nem érünk el ebben különösebb mértékû növekedést, ha a [.filename]#/var# partíciót a lemez szélére toljuk. Befejezésképpen hozzátesszük, hogy ennek vannak biztonsági megfontolásai is. Egy kisebb és takarosabb rendszerindító partíció, ami többnyire írásvédett, nagyobb eséllyel él túl egy csúfos rendszerösszeomlást. [[configtuning-core-configuration]] == A mag beállítása A rendszer beállításaira vonatkozó információk központi lelõhelye az [.filename]#/etc/rc.conf# állomány. Ez az állomány tartalmazza a beállításokra vonatkozó adatok széles körét, amelyet elsõsorban a rendszer indulása során a rendszer beállítására használnak. Erre a neve is utal: ez az [.filename]#rc*# állományok konfigurációs állománya. A rendszergazda az [.filename]#rc.conf# állományban tudja felülbírálni az [.filename]#/etc/defaults/rc.conf# állományban szereplõ alapértelmezett beállításokat. Az alapértelmezéseket tartalmazó állományt nem szabad közvetlenül átmásolni az [.filename]#/etc# könyvtárba, hiszen alapértelmezett értékeket tartalmaz, nem pedig mintákat. Minden rendszerfüggõ beállítást magában az [.filename]#rc.conf# állományban kell elvégezni. Számos stratégia létezik a tömegesen adminisztrált számítógépeknél a közös és rendszerfüggõ beállítások különválasztására, ezáltal a karbantartási költségek csökkentésére. A közös beállításokat ajánlott egy másik helyre, például az [.filename]#/etc/rc.conf.site# állományba rakni, majd hivatkozni erre a kizárólag csak rendszerfüggõ információkat tartalmazó [.filename]#/etc/rc.conf# állományból. Mivel az [.filename]#rc.conf# állományt az man:sh[1] dolgozza fel, ezt elég könnyen el tudjuk érni. Például: * rc.conf: + [.programlisting] .... . /etc/rc.conf.site hostname="node15.example.com" network_interfaces="fxp0 lo0" ifconfig_fxp0="inet 10.1.1.1" .... * rc.conf.site: + [.programlisting] .... defaultrouter="10.1.1.254" saver="daemon" blanktime="100" .... Az [.filename]#rc.conf.site# állomány ezt követõen az `rsync` parancs használatával már szétszórható a rendszerben, miközben az [.filename]#rc.conf# állomány mindenkinél egyedi marad. Ha a rendszert a man:sysinstall[8] vagy a `make world` használatával frissítjük, akkor az [.filename]#rc.conf# tartalma nem íródik felül, így a rendszer beállításairól szóló adatok nem vesznek el. [[configtuning-appconfig]] == Az alkalmazások beállítása A telepített alkalmazások általában saját konfigurációs állományokkal, azok pedig saját formátummal stb. rendelkeznek. Fontos, hogy ezeket az állományokat az alaprendszertõl elkülönítve tároljuk, ezáltal a csomagkezelõ eszközök könnyen rájuk tudjanak találni és dolgozni velük. Ezeket az állományokat általában a [.filename]#/usr/local/etc# könyvtárban találjuk meg. Amennyiben egy alkalmazáshoz több konfigurációs állomány is tartozik, akkor ahhoz ezen belül egy külön alkönyvtár jön létre. Normális esetben, amikor egy portot vagy csomagot telepítünk, minta konfigurációs állományokat is kapunk. Ezek nevében többnyire a [.filename]#.default# utótag szerepel. Ha még nincs konfigurációs állomány az adott alkalmazáshoz, akkor a [.filename]#.default# jelzésû állományokból ez létrehozható. Példaképpen most tekintsük a [.filename]#/usr/local/etc/apache# könyvtár tartalmát: .... -rw-r--r-- 1 root wheel 2184 May 20 1998 access.conf -rw-r--r-- 1 root wheel 2184 May 20 1998 access.conf.default -rw-r--r-- 1 root wheel 9555 May 20 1998 httpd.conf -rw-r--r-- 1 root wheel 9555 May 20 1998 httpd.conf.default -rw-r--r-- 1 root wheel 12205 May 20 1998 magic -rw-r--r-- 1 root wheel 12205 May 20 1998 magic.default -rw-r--r-- 1 root wheel 2700 May 20 1998 mime.types -rw-r--r-- 1 root wheel 2700 May 20 1998 mime.types.default -rw-r--r-- 1 root wheel 7980 May 20 1998 srm.conf -rw-r--r-- 1 root wheel 7933 May 20 1998 srm.conf.default .... Az állományok mérete jól mutatja, hogy csak az [.filename]#srm.conf# változott meg. Az Apache késõbbi frissítései ezt az állományt nem fogják felülírni. [[configtuning-starting-services]] == Szolgáltatások indítása A felhasználók közül sokan választják a FreeBSD Portgyûjteményében található külsõ szoftverek telepítését. A telepített szoftvert ilyenkor gyakran úgy kell beállítani, hogy a rendszer indulásával együtt induljon. Az olyan szolgáltatások, mint például a package:mail/postfix[] vagy a package:www/apache13[] csupán két olyan szoftvercsomag, amelyet a rendszerrel együtt kell elindítani. Ebben a szakaszban a külsõ szoftverek indítására használatos eljárásokkal foglalkozunk. A FreeBSD-ben megjelenõ legtöbb szolgáltatás, mint például a man:cron[8], a rendszerindító szkripteken keresztül kel életre. Habár ezek a szkriptek a FreeBSD egyes verziói vagy az egyes gyártók esetén különbözhetnek, azonban az mindegyikükben közös, hogy az elindításukra vonatkozó beállítások egyszerû indítószkriptekkel adhatóak meg. === Az alkalmazások részletesebb beállítása Most miután a FreeBSD rendelkezik egy [.filename]#rc.d# könyvtárral, az alkalmazások indításának beállítása is könnyebbé és ügyesebbé vált. Az <> mûködésérõl szóló szakaszban megismert kulcsszavak segítségével az alkalmazások mostantól kezdve a többi szolgáltatás, például a DNS után indulnak el, és az [.filename]#rc.conf# állományon keresztül a szkriptekbe huzalozottak helyett most már tetszõleges paramétereket is átadhatunk stb. Egy egyszerû szkript ehhez hasonlóan néz ki: [.programlisting] .... #!/bin/sh # # PROVIDE: utility # REQUIRE: DAEMON # KEYWORD: shutdown . /etc/rc.subr name=utility rcvar=utility_enable command="/usr/local/sbin/utility" load_rc_config $name # # NE VÁLTOZTASSUK MEG AZ ITT LÉVõ ALAPÉRTELMEZÉSEKET, # INKÁBB AZ /etc/rc.conf ÁLLOMÁNYBAN ÁLLÍTSUK BE EZEKET # utility_enable=${utility_enable-"NO"} pidfile=${utility_pidfile-"/var/run/utility.pid"} run_rc_command "$1" .... Ez a szkript gondoskodik arról, hogy a utility nevû alkalmazás a `DAEMON` szolgáltatás után induljon el. Emellett még felkínál egy módszert a PID avagy futó programok azonosítójának beállítására és nyomonkövetésére is. Ezt követõen az [.filename]#/etc/rc.conf# állományból az alkalmazás elindítható az alábbi sor hozzáadásával: [.programlisting] .... utility_enable="YES" .... Ez a módszer megkönnyíti a parancssorban átadott paraméterek módosítását, az [.filename]#/etc/rc.subr# állományban szereplõ alapértelmezett függvények használatát, az man:rcorder[8] segédprogrammal szembeni kompatibilitást és az [.filename]#rc.conf# állomány könnyebb beállítását. === Szolgáltatások indítása szolgáltatásokkal Más szolgáltatások, mint például a POP3 vagy IMAP szerverek démonai stb. az man:inetd[8] segítségével indíthatóak el. Ez a Portgyûjteménybõl telepített szolgáltatások esetén magával vonja az adott segédprogram felvételét vagy a hozzá tartozó sor engedélyezését az [.filename]#/etc/inetd.conf# állományban. Az inetd mûködésével és annak beállításával mélyrehatóbban az crossref:network-servers[network-inetd,inetd] szakasza foglalkozik. A legtöbb esetben a man:cron[8] démon használata kézenfekvõ a rendszerszintû szolgáltatások elindításában. Ez a megközelítés számos elõnyt tartogat, mivel a `cron` ezeket a programokat a felhasználó [.filename]#crontab# állománya alapján futtatja. Ezzel a mezei felhasználók számára is lehetõvé válik, hogy elindítsanak és karbantartsanak alkalmazásokat. A `cron` segédprogramnak van egy olyan speciális lehetõsége, hogy az idõ helyett a `@reboot` értéket adhatjuk meg. Ennek hatására a feladat a man:cron[8] indításával együtt fut le, tehát megszokott esetben a rendszer indítása során. [[configtuning-cron]] == A `cron` segédprogram beállítása A man:cron[8] a FreeBSD egyik leghasznosabb segédprogramja. A `cron` segédprogram a háttérben fut és folyamatosan figyeli az [.filename]#/etc/crontab# állományt. Emellett a `cron` új [.filename]#crontab# állományok után kutatva folyamatosan ellenõrzi a [.filename]#/var/cron/tabs# könyvtárat. Ezek a [.filename]#crontab# állományok olyan feladatokról tárolnak adatokat, amelyeket a `cron` programnak egy adott pillanatban el kell végeznie. A `cron` a konfigurációs állományok két külön fajtáját, a rendszer- és felhasználói crontabokat használja. A két típus között levõ egyetlen különbség a hatodik mezõben található. A rendszerszintû crontabok esetében a hatodik mezõ annak a felhasználónak a nevét tartalmazza, amivel a program fut. Ezzel a rendszer szintjén mûködõ crontaboknak megadatott az a képesség, hogy tetszõleges felhasználó nevében futtassanak programokat. A felhasználók crontabjaiban a hatodik mezõ a futtatandó parancsot tartalmazza, és ilyenkor az összes parancs a crontabot létrehozó felhasználó nevében hajtódik végre. Ez utóbbi egy fontos biztonsági jellemzõ. [NOTE] ==== A felhasználói crontabok lehetõvé teszik az egyes felhasználók számára, hogy a `root` felhasználó jogosultságai nélkül képesek legyenek feladatokat ütemezni, ugyanis a felhasználóhoz tartozó crontabban szereplõ parancsok mindegyike a tulajdonosának engedélyeivel fut. Az átlagos felhasználókhoz hasonlóan a `root` felhasználónak is lehet crontabja, ami nem ugyanaz, mint az [.filename]#/etc/crontab# (a rendszer saját crontab állománya). De mivel a rendszernek külön crontabja van, ezért a `root` felhasználónak nem kell külön crontabot létrehozni. ==== Vessünk egy pillanatást az [.filename]#/etc/crontab# (a rendszer crontabjának) tartalmára: [.programlisting] .... # /etc/crontab - a root crontabja FreeBSD alatt # # $FreeBSD: src/etc/crontab,v 1.32 2002/11/22 16:13:39 tom Exp $ ## <.> # SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin <.> HOME=/var/log # # #minute hour day month wday who command <.> # # */5 * * * * root /usr/libexec/atrun <.> .... <.> A FreeBSD legtöbb konfigurációs állományához hasonlóan itt is a `#` jelöli a megjegyzéseket. Az ilyen megjegyzések remekül használhatóak annak feljegyzésére, hogy mit és miért akarunk futtatni. A megjegyzések azonban nem szerepelhetnek a paranccsal egy sorban, mivel máskülönben a parancs részeként kerülnek értelmezésre. Tehát mindig új sorba kell raknunk ezeket. Az üres sorokat a program nem veszi figyelembe. <.> Elõször is meg kell adnunk egy környezetet. Az egyenlõség (`=`) karakter használatos a környezeti beállítások meghatározására, ahogy mindezt az itteni példában is tapasztalhatjuk a `SHELL`, `PATH` és `HOME` értékek esetében. Ha nem adunk meg mást, akkor a `cron` az alapértelmezés szerinti `sh` parancsértelmezõt használja. Ha nem adjuk meg a `PATH` változó értékét, akkor minden állományra abszolút elérési úttal kell hivatkoznunk, mivel ennek nincs alapértelmezett értéke. Ha nem definiáljuk a `HOME` változó értékét, akkor a `cron` a parancshoz tartozó felhasználó könyvtárából fog dolgozni. <.> Ez a sor írja le a megadható hét mezõt. Az itt szereplõ értékek a `minute` (perc), `hour` (óra), `mday` (a hónap napja), `month` (hónap), `wday` (a hét napja), `who` (ki) és `command` (mit). A mezõk szinte maguktól értetõdnek. A `minute` egy órán belül adja meg azokat a perceket, amikor az adott parancsot le kell futtatni. A `hour` hasonló a `minute` beállításhoz, csak az itt szereplõ értékét órákban kell értelmezni. Az `mday` a hónap napjaiban számol. A `month` hasonló a `minute` és `hour` opciókhoz, de ez hónapot jelöl. A `wday` a hét egy napját jelzi. Ezeknek a mezõknek numerikus, valamint a huszonnégy órás idõformátumnak megfelelõ értékeket kell tartalmazniuk. A `who` mezõ, a többiektõl eltérõ módon, csak az [.filename]#/etc/crontab# állományban jelenik meg. Ez a mezõ adja meg, hogy a parancsot milyen felhasználóval kell futtatni. Ez az opció nem jelenik meg a felhasználók saját [.filename]#crontab# állományainak telepítésekor. A sor végén láthatjuk még a `command` oszlopot is. Ez az utolsó mezõ, és ide kerül a végrehajtandó parancs. <.> Ez az utolsó sor a fentebb tárgyalt értékeket határozza meg. Észrevehetjük, hogy a sor egy `*/5` alakú felírással kezdõdik, amelyet további `*` karakterek követnek. A `*` karakterek jelentése "elsõ-utolsó", ami arra utal, hogy _mindig_. Ennek megfelelõen úgy értelmezhetjük ezt a sort, hogy a `root` felhasználóval le kell futtatni az `atrun` parancsot minden ötödik percben, függetlenül attól, hogy milyen nap vagy hónap van. Az `atrun` parancsról részletesebban az man:atrun[8] man oldalán kapunk felvilágosítást.Az itt szereplõ parancsoknak tetszõleges mennyiségû paraméter adható át, azonban a több soron keresztül átívelõ parancsok tördelését a sor végén a "\" karakterrel kell jelezni. Ez mindegyik [.filename]#crontab# állomány alapbeállítása, habár ettõl általában egy dologban eltérnek. A hatodik mezõ, ahol a felhasználót adtuk meg, csak a rendszer [.filename]#/etc/crontab# állományában jelenik meg. Ez a mezõ a felhasználók [.filename]#crontab# állományaiból kimarad. [[configtuning-installcrontab]] === Egy crontab telepítése [IMPORTANT] ==== Nem kötelezõ az itt ismertetésre kerülõ módon szerkeszteni vagy telepíteni a rendszer crontabját. Egyszerûen nyissuk meg a kedvenc szövegszerkesztõnkkel, és a `cron` segédprogram majd észreveszi, hogy az állomány megváltozott, majd ennek megfelelõen neki is lát a módosított változat használatának. Errõl extref:{faq}[a GYIK-ban (angolul), ROOT-NOT-FOUND-CRON-ERRORS] többet is megtudhatunk. ==== Egy frissen készített felhasználói [.filename]#crontab# telepítéséhez elõször a kedvenc szövegszerkesztõnk segítségével létre kell hoznunk a megfelelõ formátumú állományt, majd használnunk a `crontab` segédprogramot. Ennek általános alakja: [source,shell] .... % crontab crontab_állomány .... Ebben a példában a [.filename]#crontab_állomány# a korábban létrehozott [.filename]#crontab# neve lesz. Lehetõségünk van lekérdezni a telepített [.filename]#crontab# állományokat: egyszerûen adjuk át a `-l` kapcsolót a `crontab` parancsnak, és nézzük meg, mit ad vissza. A `crontab -e` használata olyan felhasználók számára ajánlott, akik sablon alkalmazása nélkül szeretnének teljesen maguktól megírni egy crontab állományt. Ennek hatására a kiválasztott szövegszerkesztõ egy üres állományt kap. Miután ezt az állományt elmentettük, a `crontab` programmal magától telepítésre kerül. Ha a késõbbiekben törölni akarjuk a felhasználónkhoz tartozó [.filename]#crontab# állományt, akkor erre a célra használjuk a `crontab -r` kapcsolóját. [[configtuning-rcd]] == Az rc használata FreeBSD alatt A rendszer indítására a FreeBSD 2002-ben átvette a NetBSD [.filename]#rc.d# rendszerét. Ezt a felhasználók könnyen felismerhetik az [.filename]#/etc/rc.d# könyvtárban található állományokról. A legtöbbjük olyan alapvetõ szolgáltatás, amelyet a `start`, `stop` és `restart` paraméterekkel lehet vezérelni. Például az man:sshd[8] az alábbi paranccsal indítható újra: [source,shell] .... # /etc/rc.d/sshd restart .... Ez az eljárás hasonló a többi szolgáltatás esetén is. Természetesen ezek a szolgáltatások általában maguktól indulnak el a rendszer indítása során az man:rc.conf[5] állományban megadottak szerint. Például ha a rendszerünk indulásakor szeretnénk aktiválni a hálózati címfordítással foglalatoskodó démont, akkor csak adjuk hozzá az [.filename]#/etc/rc.conf# állományhoz a következõ sort: [.programlisting] .... natd_enable="YES" .... Amennyiben a `natd_enable="NO"` sor már szerepel benne, akkor egyszerûen írjuk át a `NO` értéket `YES`-re. Ezután az rc szkriptek a rendszer következõ indításakor a lentieknek megfelelõen automatikusan elindítják a hozzá tartozó szolgáltatásokat is. Mivel az [.filename]#rc.d# rendszert elsõsorban arra használják, hogy szolgáltatásokat indítsanak el vagy állítsanak le az operációs rendszerrel együtt, a szabványos `start`, `stop` és `restart` paraméterek csak abban az esetben látják el a feladatukat, ha a nekik megfelelõ változókat beállítottuk az [.filename]#/etc/rc.conf# állományban. Tehát például az `sshd restart` csak abban az esetben fog bármit is csinálni, ha az [.filename]#/etc/rc.conf# állományban az `sshd_enable` változót a `YES` értékre állítottuk. Ha az [.filename]#/etc/rc.conf# beállításaitól függetlenül kívánunk egy szolgáltatásnak `start`, `stop` vagy `restart` parancsot adni, akkor elé kell tennünk egy "one" szót. Például ha az `sshd` szolgáltatás újraindításához az [.filename]#/etc/rc.conf# tartalmát figyelmen kívül akarjuk hagyni, akkor ezt a parancsot kell kiadnunk: [source,shell] .... # /etc/rc.d/sshd onerestart .... Könnyen ellenõrizni tudjuk, hogy az adott szolgáltatás az [.filename]#/etc/rc.conf# részérõl engedélyezett-e, ha a neki megfelelõ [.filename]#rc.d# szkriptnek megadjuk az `rcvar` paramétert. Ennek segítségével például a rendszergazda így képes ellenõrizni, hogy az `sshd` szolgáltatást engedélyezi-e az [.filename]#/etc/rc.conf#: [source,shell] .... # /etc/rc.d/sshd rcvar # sshd $sshd_enable=YES .... [NOTE] ==== A második sor (`# sshd`) az `sshd` parancs kimenete, nem pedig a `root` parancssora. ==== A `status` paraméterrel kideríthetjük, hogy egy szolgáltatás aktív-e. Ezzel például így tudjuk ellenõrizni az `sshd` szolgáltatás mûködését: [source,shell] .... # /etc/rc.d/sshd status sshd is running as pid 433. .... Az üzenet: [source,shell] .... Az sshd a 433-as azonosítóval fut. .... Bizonyos esetekben a `reload` paraméter használatával lehetõségünk van a szolgáltatások újraindítására is. Ilyenkor a rendszer megpróbál egy olyan jelzést küldeni a szolgáltatásnak, amivel a konfigurációs állományainak újraolvasását kéri. A legtöbbször lényegében ez a `SIGHUP` jelzés kiküldését rejti magában. Ez a lehetõség azonban nem mindegyik szolgáltatás esetén érhetõ el. Az [.filename]#rc.d# rendszer nem csupán hálózati szolgáltatások esetén használatos, hanem nagyrészben hozzájárul a rendszer indításához is. Erre vegyük példának a [.filename]#bgfsck# állományt. Amikor ez a szkript lefut, a következõ üzenetet jeleníti meg: [source,shell] .... Starting background file system checks in 60 seconds. .... Az üzenet fordítása: [source,shell] .... A háttérben 60 másodperc múlva megkezdõdik az állományrendszerek ellenõrzése. .... Ennek megfelelõen tehát ezt az állományt az állományrendszerek háttérben folyó ellenõrzésére használják, ami pedig a rendszer indítása során fut le. Számos rendszerszolgáltatás igényel a mûködéséhez további szolgáltatásokat. Például a NIS és más egyéb távoli eljáráshíváson alapú szolgáltatások egészen addig nem képesek elindulni, amíg az `rpcbind` (portmapper) szolgáltatást el nem indítjuk. Az ilyen jellegû gondok feloldására az indítószkriptek elején levõ megjegyzésekben található egy kevés metainformáció a szkript mûködéséhez szükséges elemekre (függõségeire) vonatkozóan. A rendszer indítása közben az man:rcorder[8] nevû program képes a megjegyzések közt ezeket az információkat feldolgozni és ebbõl megállapítani, hogy a függõségi viszonyok betartásával milyen sorrendben kell elindítani a rendszer által felkínált szolgáltatásokat. Ehhez a következõ kulcsszavakat kell megadni az egyes indító szkriptek elején (az man:rc.subr[8] így tudja "engedélyezni" az indító szkriptet): * `PROVIDE`: segítségével megmondjuk, hogy ez az állomány milyen szolgáltatásokat nyújt. A következõ kulcsszavak az egyes indítóállományok elején szerepelhetnek. Nem kell feltétlenül használnunk ezeket, de velük az man:rcorder[8] munkáját segíthetjük: * `REQUIRE`: felsoroljuk azokat a szolgáltatásokat, amelyek a futásához kellenek. Az állomány tehát az itt megadott szolgáltatások _után_ fog lefutni. * `BEFORE`: felsoroljuk azokat a szolgáltatásokat, amelyek _elõtt_ futtatni kell ezt az állományt. Az indító szkriptekben a kulcsszavak ügyes megválasztásával a rendszergazda nagyon finoman képes az indításkor végrehajtódó szkriptek sorrendjét szabályozni és a többi UNIX(R) alapú operációs rendszerbõl ismert "futtatási szintek" használata nélkül vezérelni a rendszerben megjelenõ szolgáltatásokat. Az [.filename]#rc.d# rendszerrõl bõvebben az man:rc[8] és man:rc.subr[8] man oldalakon olvashatunk. Ha szeretnénk saját [.filename]#rc.d# szkripteket írni vagy javítani a már meglévõkön, akkor ez extref:{rc-scripting}[a cikk] (angolul) segítségünkre lehet. [[config-network-setup]] == A hálózati kártyák beállítása Manapság már el sem tudunk képzelni számítógépet hálózati csatlakozás nélkül. A hálózati csatolókártyák hozzáadása és beállítása egy FreeBSD rendszergazda mindennapos feladata. === A megfelelõ meghajtóprogram felderítése Mielõtt bárminek is nekikezdenénk, érdemes tisztában lennünk azzal, hogy a rendelkezésünkre álló kártya milyen típusú, milyen chipet használ és hogy PCI vagy ISA buszon csatlakozik-e. A FreeBSD a PCI és ISA csatolós kártyák széles spektrumát ismeri. Az egyes kiadásokhoz mellékelt "Hardware Compatibility List" (Hardverkompatibilitási lista) dokumentumokban tudjuk ellenõrizni, hogy a kártyákat ismeri a rendszer. Miután meggyõzõdtünk róla, hogy a kártyánkat ismeri a rendszer, meg kell keresnünk a hozzá tartozó meghajtót. A [.filename]#/usr/src/sys/conf/NOTES# és a [.filename]#/usr/src/sys/arch/conf/NOTES# állományok tartalmazzák a hálózati kártyák meghajtóinak rövid leírását, benne a támogatott chipsetek és kártyák típusaival. Ha ez alapján nem tudjuk teljes biztosággal eldönteni, hogy melyik a számunkra megfelelõ meghajtó, nézzük meg a saját man oldalát. Ezen a man oldalon megtaláljuk az általa ismert összes eszközt és a velük kapcsolatban elõforduló jellemzõ problémákat. Ha egy elterjedt típust sikerült beszereznünk, akkor nem kell különösebben sokáig keresnünk a neki megfelelõ meghajtót. Az ismertebb hálózati kártyák meghajtói ugyanis alapból benne vannak a [.filename]#GENERIC# rendszermagban, ezért a rendszer indítása során ehhez hasonlóan meg is jelennek a kártyák: [source,shell] .... dc0: <82c169 PNIC 10/100BaseTX> port 0xa000-0xa0ff mem 0xd3800000-0xd38 000ff irq 15 at device 11.0 on pci0 miibus0: on dc0 bmtphy0: PHY 1 on miibus0 bmtphy0: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc0: Ethernet address: 00:a0:cc:da:da:da dc0: [ITHREAD] dc1: <82c169 PNIC 10/100BaseTX> port 0x9800-0x98ff mem 0xd3000000-0xd30 000ff irq 11 at device 12.0 on pci0 miibus1: on dc1 bmtphy1: PHY 1 on miibus1 bmtphy1: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc1: Ethernet address: 00:a0:cc:da:da:db dc1: [ITHREAD] .... Ebben a példában láthatunk is két olyan kártyát, amelyek a man:dc[4] meghajtót használják. Ha a hálózati kártyánk meghajtója nem szerepel a [.filename]#GENERIC# konfigurációban, akkor a mûködéséhez be kell tölteni a megfelelõ meghajtót. Ezt alapvetõen kétféleképpen érhetjük el: * Ennek legegyszerûbb módja, ha a man:kldload[8] használatával alkalmanként vagy a [.filename]#/boot/loader.conf# állományban a megfelelõ sor hozzáadásával a rendszer indításával együtt betöltjük a hálózati kártya meghajtójához tartozó modult. Nem mindegyik hálózati kártya meghajtója érhetõ el modul formájában. Erre konkrét például szolgálnak az ISA kártyákhoz tartozó modulok. * Másik lehetõségünk, ha statikusan beépítjük a kártyánk támogatását a rendszermagba. A [.filename]#/usr/src/sys/conf/NOTES# és az [.filename]#/usr/src/sys/arch/conf/NOTES# állományok, valamint a meghajtóhoz tartozó man oldal elolvasásából megtudhatjuk a rendszermag beállításait tartalmazó állományban megadandó paramétereket. A rendszermag újrafordítását lásd crossref:kernelconfig[kernelconfig,A FreeBSD rendszermag testreszabása]. Ha a rendszermag ([.filename]#GENERIC#) az indulás során észlelte a kártyánkat, nem kell újat készítenünk. [[config-network-ndis]] ==== A Windows(R) NDIS meghajtóinak használata Sajnos még mindig sok olyan gyártó akad, akik a nyílt forrású közösség számára nem adják ki a meghajtóik mûködésének alapjait, mivel az ilyen adatokat szakmai titoknak tekintik. Ebbõl következik, hogy a FreeBSD és más operációs rendszerek fejlesztõi számára két választás marad: vagy a gyári meghajtók visszafejtésének hosszú és fájdalmas útján haladva fejlesztik ki a saját meghajtójukat, vagy pedig a Microsoft(R) Windows(R) platformra kiadott meghajtók binárisait hasznosítják. A legtöbb fejlesztõ, köztük a FreeBSD fejlesztõi is, ez utóbbi megközelítést választották. Bill Paul (wpaul) jóvoltából a FreeBSD 5.3-RELEASE változatában megjelent a "Network Driver Interface Specification" (NDIS, avagy hálózati meghajtók szabványos felülete) "natív" támogatása. A FreeBSD NDISulator (másnéven Project Evil, a Gonosz terve) nevû komponense fog egy Windows(R)-os meghajtót és elhiteti vele, hogy a Windows(R) operációs rendszerrel kommunikál. Mivel az man:ndis[4] meghajtó Windows(R) binárisokat használ fel, ezért csak i386 és amd64 rendszerek esetén érhetõ el. [NOTE] ==== Az man:ndis[4] meghajtó leginkább a PCI, CardBus és PCMCIA csatolójú eszközök támogatására lett kitalálva, az USB eszközöket még nem ismeri. ==== Az NDISulator használatához három tényezõre van szükségünk: . A rendszermag forrása . a Windows(R) XP meghajtó binárisa ([.filename]#.SYS# a kiterjesztése) . a Windows(R) XP meghajtó konfigurációs állománya ([.filename]#.INF# a kiterjesztése) Keressük meg az említett állományokat az adott kártyához. Ezeket általában a mellékelt CD-n vagy a gyártó honlapján találjuk meg. A most következõ példákban a [.filename]#W32DRIVER.SYS# és a [.filename]#W32DRIVER.INF# neveket fogjuk használni. [NOTE] ==== A Windows(R) i386 architektúrájú verziójához készült meghajtóprogramokat nem tudjuk a FreeBSD/amd64 verziójával használni. A mûködéshez amd64-re készült Windows(R)-os meghajtókra van szükség. ==== A következõ lépés a meghajtó binárisainak betölthetõ modulba fordítása. Ennek eléréséhez használjuk az man:ndisgen[8] parancsot a `root` felhasználóval: [source,shell] .... # ndisgen /windowsos/meghajtó/W32DRIVER.INF /windowsos/meghajtó/W32DRIVER.SYS .... Az man:ndisgen[8] egy interaktív segédprogram, amely mûködése közben még rákérdez néhány szükséges információra. Az aktuális könyvtárban létrehoz egy rendszermagmodult, amelyet az alábbi módon tudunk betölteni: [source,shell] .... # kldload ./W32DRIVER_SYS.ko .... Az elõállított modul mellé be kell töltenünk még az [.filename]#ndis.ko# és az [.filename]#if_ndis.ko# modulokat is. Ez általában minden olyan modul esetén megtörténik magától, amely függ az man:ndis[4] használatától. Kézileg a következõ parancsokkal tudjuk ezeket betölteni: [source,shell] .... # kldload ndis # kldload if_ndis .... Itt az elsõ parancs betölti az NDIS miniport meghajtó burkolására szánt kódot, valamint a második a tényleges hálózati csatolófelületet. Most pedig a man:dmesg[8] kimenetében ellenõrizzük, hogy történt-e valamilyen hiba a betöltés során. Ha minden jól ment, akkor az alábbiakhoz hasonló kimenetet produkált: [source,shell] .... ndis0: mem 0xf4100000-0xf4101fff irq 3 at device 8.0 on pci1 ndis0: NDIS API version: 5.0 ndis0: Ethernet address: 0a:b1:2c:d3:4e:f5 ndis0: 11b rates: 1Mbps 2Mbps 5.5Mbps 11Mbps ndis0: 11g rates: 6Mbps 9Mbps 12Mbps 18Mbps 36Mbps 48Mbps 54Mbps .... Innentõl kezdve az [.filename]#ndis0# nevû eszközt úgy tudjuk használni, mint bármelyik más hálózati felületet (például [.filename]#dc0#). A többi modulhoz hasonló módon be tudjuk állítani, hogy a rendszer indulásával együtt betöltõdjenek az NDIS modulok. Ehhez elõször másoljuk az imént létrehozott modult, az [.filename]#W32DRIVER_SYS.ko# állományt a [.filename]#/boot/modules# könyvtárba. Ezután adjuk hozzá a következõ sort a [.filename]#/boot/loader.conf# állomány tartalmához: [.programlisting] .... W32DRIVER_SYS_load="YES" .... === A hálózati kártya beállítása Ahogy betöltõdött a megfelelõ meghajtó a hálózati kártyánkhoz, be is kell állítanunk a kártyát. A hálózati kártyák sok más dologgal együtt beállíthatóak a telepítés során a sysinstall segítségével. A rendszerünkben beállított hálózati csatolófelületek megjelenítéséhez gépeljük be a következõ parancsot: [source,shell] .... % ifconfig dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da inet 192.168.1.3 netmask 0xffffff00 broadcast 192.168.1.255 media: Ethernet autoselect (100baseTX ) status: active dc1: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:db inet 10.0.0.1 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet 10baseT/UTP status: no carrier plip0: flags=8810 mtu 1500 lo0: flags=8049 metric 0 mtu 16384 options=3 inet6 fe80::1%lo0 prefixlen 64 scopeid 0x4 inet6 ::1 prefixlen 128 inet 127.0.0.1 netmask 0xff000000 nd6 options=8010 mtu 1500 .... Az elõbbi parancs kimenetében a következõ eszközök jelentek meg: * [.filename]#dc0#: az elsõ Ethernet felület * [.filename]#dc1#: a második Ethernet felület * [.filename]#plilp0#: a párhuzamos port felülete (amennyiben található párhuzamos port a számítógépben) * [.filename]#lo0#: a loopback eszköz A FreeBSD a kártyához tartozó meghajtó nevével és egy sorszámmal azonosítja a rendszermag indulása során talált eszközöket. Például az [.filename]#sis2# a rendszerben található harmadik olyan eszköz, amely a man:sis[4] meghajtót használja. A példában a [.filename]#dc0# eszköz aktív és mûködõképes. Ennek legfontosabb jelei: . Az `UP` szó mutatja, hogy a kártyát sikerült beállítani és készen áll a használatra. . A kártya internet (`inet`) címe (jelen esetünkben ez `192.168.1.3`). . Érvényes hálózati maszkkal rendelkezik (`netmask`, ahol a `0xffffff00` a `255.255.255.0` címnek felel meg). . Érvényes broadcast (üzenetszóró) címmel rendelkezik (ami itt most `192.168.1.255`). . A kártya MAC-címe (`ether`) `00:a0:cc:da:da:da`. . A hozzá tartozó fizikai eszköz kiválasztása automatikus (`media: Ethernet autoselect (100baseTX )`). Láthatjuk, hogy a [.filename]#dc1# eszközt egy `10baseT/UTP` típusú fizikai eszközhöz állítottuk be. Az egyes meghajtókhoz tartozó fizikai módokról a nekik megfelelõ man oldalakon olvashatunk. . A kapcsolat állapota (`status`) `active` értékû, tehát van vonal. A [.filename]#dc1# esetén láthatjuk, hogy a `status: no carrier` (nincs vonal). Ez teljesen normálisnak tekinthetõ minden olyan esetben, amikor a kártyába még nem dugtunk Ethernet-kábelt. Amennyiben az man:ifconfig[8] kimenete valami ilyesmi: [source,shell] .... dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da media: Ethernet autoselect (100baseTX ) status: active .... akkor az arra utal, hogy a kártyát nem állítottuk be. A kártya beállításához a `root` felhasználó jogosultságaira van szükségünk. A hálózati kártyák beállítása az man:ifconfig[8] segítségével elvégezhetõ parancssorból is, de a gép újraindításakor az így megadott értékek elvesznek. Ezért az [.filename]#/etc/rc.conf# állományba kell felvennünk a hálózati kártyák érvényes beállításait. A kedvenc szövegszerkesztõnkben nyissuk meg az [.filename]#/etc/rc.conf# állományt. Minden egyes hálózati csatolóhoz fel kell vennünk benne egy sort, ennek megfelelõen most a példához tartozó módon az alábbiakat: [.programlisting] .... ifconfig_dc0="inet 192.168.1.3 netmask 255.255.255.0" ifconfig_dc1="inet 10.0.0.1 netmask 255.255.255.0 media 10baseT/UTP" .... A [.filename]#dc0# és [.filename]#dc1# neveket kell a rendszerünkben ténylegesen megtalálható eszközök neveire kicserélni, valamint megadni a nekik megfelelõ címeket. A kártya meghajtójának és az man:ifconfig[8] man oldalának elolvasásával kideríthetjük az itt megadható további beállításokat, valamint az man:rc.conf[5] man oldalán részletesebben megismerhetjük az [.filename]#/etc/rc.conf# formai követelményeit. Ha a telepítés során beállítottuk volna a hálózati kapcsolatokat, akkor tapasztalhatjuk, hogy egyes hálózati kártyák sorai itt már szerepelnek. Ellenõrizzük az [.filename]#/etc/rc.conf# tartalmát, mielõtt bõvítenénk! Mindezek mellett az [.filename]#/etc/hosts# állományba is be kell írnunk a helyi hálózatunkon található különféle gépek neveit és IP-címeit, ha még nem szerepelnének ott. Errõl további részleteket a man:hosts[5] man oldalról és az [.filename]#/usr/shared/examples/etc/hosts# állományból tudhatunk meg. [NOTE] ==== Ha a géppel szeretnénk majd csatlakozni az internetre, akkor ne felejtsük el manuálisan beállítani az alapértelmezett átjárót és a névfeloldáshoz szükséges kiszolgálót: [source,shell] .... # echo 'defaultrouter="alapertelmezett_atjaro"' >> /etc/rc.conf # echo 'nameserver DNS_kiszolgalo' >> /etc/resolv.conf .... ==== === Tesztelés és hibaelhárítás Miután az [.filename]#/etc/rc.conf# állományban elvégeztük a szükséges változtatásokat, érdemes újraindítanunk a rendszerünket. Ennek révén érvényesítjük a csatolófelületekkel kapcsolatos változtatásainkat és ellenõrizzük, hogy így a rendszer mindenféle hibaüzenet nélkül képes elindulni. A másik lehetõség, ha csak magát a hálózati alrendszer konfigurációját indítjuk el újra: [source,shell] .... # /etc/rc.d/netif restart .... [NOTE] ==== Ha az [.filename]#/etc/rc.conf# állományban már beállítottuk az alapértelmezett átjárót, akkor elegendõ csupán ez a parancs: [source,shell] .... # /etc/rc.d/routing restart .... ==== Ahogy újrakonfiguráltuk a hálózati alrendszert, ki is tudjuk próbálni a hálózati felületeket. ==== Az Ethernet kártyák tesztelése Az Ethernet kártyák helyes beállításának vizsgálatához két dolgot kell kipróbálnunk. Elõször is pingeljük magát a felületet, majd ezután pingeljünk meg a helyi hálózaton egy másik számítógépet. Elsõként tehát próbáljuk meg a helyi felületet: [source,shell] .... % ping -c5 192.168.1.3 PING 192.168.1.3 (192.168.1.3): 56 data bytes 64 bytes from 192.168.1.3: icmp_seq=0 ttl=64 time=0.082 ms 64 bytes from 192.168.1.3: icmp_seq=1 ttl=64 time=0.074 ms 64 bytes from 192.168.1.3: icmp_seq=2 ttl=64 time=0.076 ms 64 bytes from 192.168.1.3: icmp_seq=3 ttl=64 time=0.108 ms 64 bytes from 192.168.1.3: icmp_seq=4 ttl=64 time=0.076 ms --- 192.168.1.3 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.074/0.083/0.108/0.013 ms .... Most pedig pingeljünk meg egy másik számítógépet a helyi hálózaton: [source,shell] .... % ping -c5 192.168.1.2 PING 192.168.1.2 (192.168.1.2): 56 data bytes 64 bytes from 192.168.1.2: icmp_seq=0 ttl=64 time=0.726 ms 64 bytes from 192.168.1.2: icmp_seq=1 ttl=64 time=0.766 ms 64 bytes from 192.168.1.2: icmp_seq=2 ttl=64 time=0.700 ms 64 bytes from 192.168.1.2: icmp_seq=3 ttl=64 time=0.747 ms 64 bytes from 192.168.1.2: icmp_seq=4 ttl=64 time=0.704 ms --- 192.168.1.2 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.700/0.729/0.766/0.025 ms .... Ha beállítottuk az [.filename]#/etc/hosts# állományt, akkor a `192.168.1.2` helyett a gép nevét is megadhatjuk. ==== A hibák elhárítása A hardverek és szoftverek beállításaiban mindig is valódi kín megtalálni a hibákat, és ezeket a kínokat többnyire úgy tudjuk enyhíteni, ha elõször az egyszerû hibaforrásokat szûrjük ki. Csatlakoztattuk a hálózati kábelt? Tisztességesen beállítottuk a hálózati szolgáltatásokat? Jól állítottuk be a tûzfalat? A FreeBSD képes kezelni a kártyát? A hibajelentések elküldése elõtt mindig bújjuk át a támogatott hardvereszközök listáját. A FreeBSD verziókat frissítsük a legújabb STABLE változatra. Olvassuk át a levelezési listák archívumait vagy legalább keressünk rá a témára az interneten. Ha a kártya mûködik, de a teljesítménye nem kielégítõ, érdemes ennek utánanézni a man:tuning[7] man oldalon. Ilyenkor érdemes ellenõrizni a hálózati beállításainkat is, mivel a helytelen beállítások gyakran okoznak teljesítményvesztést. Bizonyos esetekben láthatunk egy vagy két `device timeout` típusú hibát is, ami a kártyák egyes fajtáinál elfogadható. Ha azonban folyamatosan megjelennek vagy zavaróvá válnak, érdemes utánanéznünk, hogy az eszköz nem ütközik-e valamelyik másikkal. Mindenképpen gyõzõdjünk meg a kábelek épségérõl és csatlakoztatásáról. Még az is elképzelhetõ, hogy egyszerûen csak egy másik hálózati kártyára van szükségünk. Néha felbukkanak `watchdog timeout` jellegû hibák is. Ilyenkor elsõként mindig a hálózati kábelt ellenõrizzük. Egyes kártyáknak olyan PCI foglalatra van szükségük, ami támogatja a Bus Mastering opciót. Néhány régebbi alaplapon csak ilyen PCI bõvítõhely található (ami általában a 0. foglalat). Olvassunk utána a hálózati kártya és az alaplap dokumentációjában, hátha ezek okozzák a problémát. A `No route to host` üzenet akkor jelenik meg, ha a rendszer képtelen megállapítani, milyen úton juttassa el a csomagokat a megadott célhoz. Ez többnyire olyankor történik meg, amikor nem adtunk meg alapértelmezett kézbesítési irányt (default route) vagy nem dugtuk be a hálózati kábelt. A `netstat -rn` kimenetébõl meg tudjuk állapítani, hogy létezik-e érvényes út az elérni kívánt cél felé. Ha nincs, akkor haladjunk tovább a crossref:advanced-networking[advanced-networking,Egyéb haladó hálózati témák]re. A `ping: sendto: Permission denied` jellegû üzeneteket többségében egy helytelenül beállított tûzfal okozza. Ha az `ipfw` mûködését engedélyeztük a rendszermagban, de nem adtunk meg hozzá szabályokat, akkor az alapértelmezett házirend szerint minden forgalmat blokkolni fog, tehát még a pingeket is! Ezzel kapcsolatban a crossref:firewalls[firewalls,Tűzfalak] elolvasását ajánljuk. Elõfordulhat, hogy a kártya teljesítménye igen gyenge vagy az átlagos alatt van. Ilyenkor a fizikai eszköz `autoselect` (automatikus) típusú kiválasztása helyett érdemes megadnunk a konkrét eszköznek megfelelõ típust. Habár ez a legtöbb hardver esetén beválik, nem mindenki számára jelent megoldást. Ismételten csak annyit tudunk ehhez hozzátenni, hogy ellenõrizzük a hálózati beállításainkat és olvassuk el a man:tuning[7] man oldalt. [[configtuning-virtual-hosts]] == Virtuális címek A FreeBSD alkalmazása során igen gyakori a virtuális címek használata, aminek segítségével egyetlen szerver több szerverként képes látszódni a hálózaton. Ezt úgy érik el, hogy egyetlen felülethez több hálózati címet rendelnek hozzá. Az adott hálózati csatolófelületnek van egy "valódi címe" és tetszõleges számú "álcíme". Ezeket az álcímeket általában az [.filename]#/etc/rc.conf# állományban kell feltüntetni. Az [.filename]#fxp0# felület esetén az álcímek megadása valahogy így néz ki: [.programlisting] .... ifconfig_fxp0_alias0="inet xxx.xxx.xxx.xxx netmask xxx.xxx.xxx.xxx" .... Figyeljük meg, hogy az álcímekhez tartozó bejegyzések az `alias0` névvel kezdõdnek és szám szerint növekvõleg következnek egymás után (például, `_alias1`, `_alias2` és így tovább). A beállítás a sorozat elsõ kimaradó tagjánál megszakad. Az álcímek hálózati maszkjának pontos meghatározása nagyon fontos, de szerencsére nem különösebben bonyolult. Minden felület esetén lennie kell egy olyan címnek, amely helyesen reprezentálja a hálózat hálózati maszkját. Minden egyéb olyan címnek, ami ugyanabba az alhálózatba esik, végig `1`-esekbõl álló hálózati maszkkal kell rendelkezniük (ami felírható `255.255.255.255` vagy `0xffffffff` formájában is). Például vegyük azt, hogy az [.filename]#fxp0# felületen keresztül két hálózathoz csatlakozunk, melyek közül az egyik a `10.1.1.0`, amelynek hálózati maszkja `255.255.255.0`, és a `202.0.75.16`, amelynek hálózati maszkja `255.255.255.240`. Azt szeretnénk elérni, hogy a rendszerünk a `10.1.1.1` címtõl a `10.1.1.5` címig, valamint a `202.0.75.17` címtõl a `202.0.75.20` címig jelenjen meg a nekik megfelelõ hálózatokon. Ahogy arra már fentebb is utaltunk, az adott hálózati tartományban csak az elsõ címnek (ebben az esetben ez a `10.0.1.1` és a `202.0.75.17`) kell valódi hálózati maszkkal rendelkeznie. Minden további címnek (a `10.1.1.2` és `10.1.1.5` között, valamint a `202.0.75.18` és `202.0.75.20` között) legyen `255.255.255.255` a hálózati maszkja. Az alábbi [.filename]#/etc/rc.conf# bejegyzések ennek az elrendezésnek megfelelõen állítják be a kártyát: [.programlisting] .... ifconfig_fxp0="inet 10.1.1.1 netmask 255.255.255.0" ifconfig_fxp0_alias0="inet 10.1.1.2 netmask 255.255.255.255" ifconfig_fxp0_alias1="inet 10.1.1.3 netmask 255.255.255.255" ifconfig_fxp0_alias2="inet 10.1.1.4 netmask 255.255.255.255" ifconfig_fxp0_alias3="inet 10.1.1.5 netmask 255.255.255.255" ifconfig_fxp0_alias4="inet 202.0.75.17 netmask 255.255.255.240" ifconfig_fxp0_alias5="inet 202.0.75.18 netmask 255.255.255.255" ifconfig_fxp0_alias6="inet 202.0.75.19 netmask 255.255.255.255" ifconfig_fxp0_alias7="inet 202.0.75.20 netmask 255.255.255.255" .... [[configtuning-configfiles]] == Konfigurációs állományok === Az [.filename]#/etc# felépítése A beállításokkal kapcsolatos információk számos könyvtárban tárolódnak. Többek közt: [.informaltable] [cols="1,1", frame="none"] |=== |[.filename]#/etc# |Általános rendszerszintû beállítások. Az itt levõ adatok a rendszer egészére vonatkoznak. |[.filename]#/etc/defaults# |A rendszer konfigurációs állományainak alapértelmezett változatai. |[.filename]#/etc/mail# |A man:sendmail[8] beállításához tartozó további állományok, egyéb levélküldéshez használt adatok. |[.filename]#/etc/ppp# |A felhasználói és rendszermag szintû ppp programok beállításai. |[.filename]#/etc/namedb# |A man:named[8] mûködéséhez szükséges adatok alapértelmezett helye. Általában a [.filename]#named.conf# és a zónák leírását tároló állományok kerülnek ide. |[.filename]#/usr/local/etc# |A telepített alkalmazások konfigurációs állományai. Néha alkalmazásonként külön könyvtárakba kerülnek a benne található állományok. |[.filename]#/usr/local/etc/rc.d# |A telepített alkalmazások indításával és leállításával kapcsolatos szkriptek. |[.filename]#/var/db# |Automatikusan generált rendszerszintû adatbázisok a csomagokkal, a programok helyével stb. kapcsolatosan. |=== === Hálózati nevek ==== [.filename]#/etc/resolv.conf# Az [.filename]#/etc/resolv.conf# határozza meg, hogy a FreeBSD névfeloldója miként fér hozzá az internet tartománynév rendszeréhez (a DNS-hez). Az [.filename]#resolv.conf# állományban leggyakrabban a következõ bejegyzések fordulnak elõ: [.informaltable] [cols="1,1", frame="none"] |=== |`nameserver` |Annak a névszernek az IP-címe, ahova a névfeloldó küldi a kéréseit. A névszervereket a felírás sorrendjében kérdezi meg, maximum hármat. |`search` |A hálózati nevek keresõlistája. Ezt általában a helyi hálózati nevek tartománya határozza meg. |`domain` |A helyi tartomány neve. |=== Egy átlagos [.filename]#resolv.conf# tartalma: [.programlisting] .... search example.com nameserver 147.11.1.11 nameserver 147.11.100.30 .... [NOTE] ==== Csak egy `search` és `domain` opciót szabad megadni. ==== A DHCP használatakor a man:dhclient[8] felül szokta írni a [.filename]#resolv.conf# tartalmát a DHCP szervertõl kapott információkkal. ==== [.filename]#/etc/hosts# Az [.filename]#/etc/hosts# az internet kezdeti napjaira emlékeztetõ egyszerû szöveges adatbázis. A nevek és IP-címek közti leképzéseket a DNS és NIS rendszerekkel karöltve oldja fel. Ide a helyi hálózaton csatlakozó számítógépek neveit lehet beírni ahelyett, hogy erre a célra beállítanánk egy külön man:named[8] szervert. Ezenkívül még az [.filename]#/etc/hosts# állományba internetes nevek rekordját is felvehetjük, amivel így csökkenthetjük a gyakran használt nevek feloldására irányuló külsõ kéréseket. [.programlisting] .... # $FreeBSD$ # # # A hálózati nevek adatbázisa # # Ebbe az állományba rakjuk a helyi hálózaton található címeket és # a hozzájuk tartozó hálózati neveket, ahol szinte ugyanez az # adatbázis megtalálható. A 'my.domain' helyére a saját gépünk # nevét írjuk be. # # A DNS vagy NIS alkalmazása esetén ez az állomány nem feltétlenül kerül # felhasználásra. A névfeloldás sorrendjét az /etc/nsswitch.conf # állományban adhatjuk meg. # ::1 localhost localhost.my.domain 127.0.0.1 localhost localhost.my.domain # # Egy képzeletbeli hálózat. #10.0.0.2 myname.my.domain myname #10.0.0.3 myfriend.my.domain myfriend # # Az RFC 1918-nak megfelelõen a következõ IP-címekkel rendelkezõ # alhálózatok sosem csatlakozhatnak közvetlenül az internetre: # # 10.0.0.0 - 10.255.255.255 # 172.16.0.0 - 172.31.255.255 # 192.168.0.0 - 192.168.255.255 # # Amikor csatlakozunk az internethez, egy valódi, hivatalosan # kiosztott számra lesz szükségünk. Ne találjunk ki magunknak # hálózati címeket, hanem használjuk az internetszolgáltatótól # kapott címet (amennyiben rendelkezünk # ilyennel) vagy az # regionális internetes nyilvántartásban szereplõ címek közül # valamelyiket (ARIN, APNIC, LACNIC, RIPE NCC vagy AfriNIC). .... Az [.filename]#/etc/hosts# formai felépítése igen egyszerû: [.programlisting] .... [internetes cím] [hivatalos hálózati név] [álnév1] [álnév2] ... .... Tehát például: [.programlisting] .... 10.0.0.1 azEnValodiNevem.aHalozaton.hu azEnValodiNevem izemize1 izemize2 .... A részletekért keressük fel a man:hosts[5] man oldalt. === A naplóállományok beállítása ==== [.filename]#syslog.conf# A [.filename]#syslog.conf# állomány a man:syslogd[8] program beállításait tartalmazza. Segítségével megadhatjuk, hogy a `syslog` által generált üzenetek egyes típusait milyen naplóállományokba mentsük. [.programlisting] .... # $FreeBSD$ # # Ebben az állományban HASZNÁLHATÓAK szóközök a mezõk elválasztására, # habár a többi *nix-típusú rendszer inkább tabulátorokat használ # erre a célra. Ha több rendszeren is használni akarjuk ezt az # állományt, akkor ne használjunk szóközöket. # # A többit lásd a syslog.conf(5) man oldalon. # .err;kern.debug;auth.notice;mail.crit /dev/console *.notice;kern.debug;lpr.info;mail.crit;news.err /var/log/messages security.* /var/log/security mail.info /var/log/maillog lpr.info /var/log/lpd-errs cron.* /var/log/cron *.err root *.notice;news.err root *.alert root *.emerg * # Tegyük vissza ezt a sort, ha a /dev/console eszközre kiírt # üzeneteket át akarjuk irányítani az /var/log/console.log állományba. #console.info /var/log/console.log # Ha az összes üzenetet a /var/log/all.log állományba akarjuk menteni, # akkor tegyük vissza ezt a sort. #*.* /var/log/all.log # Ha egy "loghost" nevû gépre szeretnénk naplózni, akkor tegyük vissza # ezt a sort. #*.* @loghost # Az inn használatakor tegyük vissza ezeket a sorokat. # news.crit /var/log/news/news.crit # news.err /var/log/news/news.err # news.notice /var/log/news/news.notice !startslip *.* /var/log/slip.log !ppp *.* /var/log/ppp.log .... A man:syslog.conf[5] man oldalának elolvasásával tudhatunk meg többet ezekrõl. ==== [.filename]#newsyslog.conf# A [.filename]#newsyslog.conf# a man:newsyslog[8] beállításait tároló állomány. Ez egy olyan program, amelyet általában a man:cron[8] futtat le. A man:newsyslog[8] dönti el, hogy mikor van szükség a naplók archiválására és átrendezésére. Ennek során a [.filename]#logfile# állományból [.filename]#logfile.0# lesz, a [.filename]#logfile.0# állományból pedig [.filename]#logfile.1# és így tovább. Beállíthatjuk úgy is, hogy a naplóállományokat archiválja man:gzip[1] formátumban, aminek megfelelõen ezek [.filename]#logfile.0.gz#, [.filename]#logfile.1.gz# és ehhez hasonló névvel jönnek létre. A [.filename]#newsyslog.conf# megadja, hogy melyik naplóállományokat kell felügyelni, mennyi példányt tartsunk meg belõlük és mikor kell velük foglalkozni. A naplóállományok átrendezhetõek és/vagy archiválhatóak egy adott méret elérésekor vagy egy adott idõ eltelte után. [.programlisting] .... # A newsyslog konfigurációs állománya # $FreeBSD$ # # állománynév [tulajdonos:csoport] mód darab méret mikor [ZB] [/pid_állomány] [jelzés] /var/log/cron 600 3 100 * Z /var/log/amd.log 644 7 100 * Z /var/log/kerberos.log 644 7 100 * Z /var/log/lpd-errs 644 7 100 * Z /var/log/maillog 644 7 * @T00 Z /var/log/sendmail.st 644 10 * 168 B /var/log/messages 644 5 100 * Z /var/log/all.log 600 7 * @T00 Z /var/log/slip.log 600 3 100 * Z /var/log/ppp.log 600 3 100 * Z /var/log/security 600 10 100 * Z /var/log/wtmp 644 3 * @01T05 B /var/log/daily.log 640 7 * @T00 Z /var/log/weekly.log 640 5 1 $W6D0 Z /var/log/monthly.log 640 12 * $M1D0 Z /var/log/console.log 640 5 100 * Z .... További információkat a man:newsyslog[8] man oldaláról nyerhetünk. [[configtuning-sysctlconf]] === [.filename]#sysctl.conf# A [.filename]#sysctl.conf# állomány leginkább az [.filename]#rc.conf# állományhoz hasonlít, benne az értékeket `változó=érték` párokban adhatjuk meg. Az itt definiált értékek akkor kerülnek ténylegesen beállításra, amikor a rendszer többfelhasználós módba vált. Ezen a módon nem mindegyik változó értékét tudjuk átállítani. A [.filename]#sysctl.conf# állományban az alábbi érték beállításával tudjuk beállítani, hogy a rendszer ne naplózza, amikor a programok végzetes jelzéssel fejezõdnek be, valamint azt, hogy a felhasználók láthassák egymás futó programjait: [.programlisting] .... # Ne naplózzuk a végzetes jelzésekhez (például sig 11) tartozó kilépéseket. kern.logsigexit=0 # Ne engedjük a felhasználóknak, hogy lássák egy másik felhasználó # azonosítójával futó programokat. security.bsd.see_other_uids=0 .... [[configtuning-sysctl]] == Finomhangolás a sysctl használatával A man:sysctl[8] egy olyan felület, amely lehetõséget biztosít egy mûködõ FreeBSD rendszer megváltoztatására. Segítségével többek közt hozzáférhetünk a TCP/IP protokollkészlet és a virtuális memóriát kezelõ alrendszer rengeteg apró opciójához, melyek megfelelõ beállításával egy tapasztalt rendszergazda kezében drasztikusan növelhetõ a rendszer teljesítménye. A man:sysctl[8] alkalmazásával több mint ötszáz rendszerszintû változó kérdezhetõ le és állítható be. A man:sysctl[8] két funkciót rejt magában: a rendszer beállításainak lekérdezését és módosítását. Így nézhetjük meg az összes lekérdezhetó változót: [source,shell] .... % sysctl -a .... Így kérhetjük egy konkrét változó, például a `kern.maxproc` értékét: [source,shell] .... % sysctl kern.maxproc kern.maxproc: 1044 .... Egy adott változó értékének módosításához pedig használjuk a _változó_=_érték_ felírást: [source,shell] .... # sysctl kern.maxfiles=5000 kern.maxfiles: 2088 -> 5000 .... A sysctl változók értékei lehetnek karakterláncok, számok és logikai értékek (ahol az `1` az igennek, a `0` a nemnek felel meg). Ha a számítógép indításakor automatikusan be akarunk állítani bizonyos változókat, akkor vegyük fel ezeket az [.filename]#/etc/sysctl.conf# állományba. Ennek pontosabb részleteit a man:sysctl.conf[5] man oldalon és a <>ban találhatjuk meg. [[sysctl-readonly]] === A man:sysctl[8] írásvédett értékei Egyes esetekben szükséges lehet a man:sysctl[8] írásvédett változóinak módosítása. Habár gyakran elengedhetetlen, ezt kizárólag csak a rendszer (újra)indításakor tudjuk megtenni. Például egyes laptopoknál a man:cardbus[4] eszköz nem próbálkozik több memóriaterület használatával, ezért egy ehhez hasonló hibával leáll: [source,shell] .... cbb0: Could not map register memory device_probe_and_attach: cbb0 attach returned 12 .... Az ilyen és ehhez hasonló esetekben gyakran olyan man:sysctl[8] változók alapértelmezett értékeit kellene megváltoztatnunk, amelyek írásvédettek. Ilyenkor tegyük az érintett man:sysctl[8] változó "objektumazonosítóját" (OID) és a hozzá tartozó értéket a [.filename]#/boot/loader.conf# állományunkba. Az alapértelmezéseket a [.filename]#/boot/defaults/loader.conf# állományban találjuk meg. A fentebb tárgyalt probléma megoldásához a felhasználónak a `hw.pci.allow_unsupported_io_range=1` értéket kell beállítania az elõbb említett állományban. Ezután már a man:cardbus[4] megfelelõen fog mûködni. [[configtuning-disk]] == A lemezek finomhangolása === Sysctl változók ==== `vfs.vmiodirenable` A `vfs.vmiodirenable` sysctl változó értéke lehet 0 (ki) vagy 1 (be, és ez az alapértelmezés is). Ez a változó vezérli a könyvtárak gyorsítótárazását a rendszerben. A könyvtárak többsége kis méretû, így az állományrendszerbõl csak egyetlen (általában 1 KB méretû) darabkát használnak és még ennél is kevesebbet (általában 512 byte-ot) a pufferben. A változó kikapcsolt (avagy 0) értéke mellett a puffer csak rögzített számú könyvtárat táraz be még abban az esetben is, amikor temérdek mennyiségû memória áll a rendelkezésére. Ha viszont (az 1 értékkel) engedélyezzük, akkor a rendszer a könyvtárak tárazására felhasználja a virtuális memóriában pufferelt lapokat is, amivel lényegében az összes elérhetõ memóriát a könyvtárak tárazására fordítja. Ilyenkor azonban az egyes könyvtárak tárazására használt legkisebb memóriaterület a fizikai lapmérettel egyezik meg (ami általában 4 KB) és nem 512 byte. Abban az esetben javasoljuk ennek a beállításnak a használatát, ha olyan szolgáltatásokkal dolgozunk, amelyek nagy számú állománnyal dolgoznak egyszerre. Ilyen szolgáltatások többek közt a webes gyorsítótárak, nagyobb levelezõrendszerek és hírrendszerek. Az opció engedélyezése alapvetõen nem veti vissza a rendszer teljesítményét még akkor sem, ha ezzel memóriát pazarlunk el, de ezt igazából érdemes kikísérletezni. ==== `vfs.write_behind` A `vfs.write_behind` sysctl változó alapértelmezett értéke `1` (bekapcsolt). Ez arra utasítja az állományrendszert, hogy csak akkor küldje ki az adatokat az eszközre, ha belõlük teljes fürtök gyûltek össze. Ez jellemzõ módon nagyobb szekvenciális állományok írása esetén kedvezõ. Arra szolgál, hogy segítségével el lehessen kerülni az I/O túlságosan gyakori módosítások okozta terhelését. Bizonyos körülmények közt ez azonban lassíthatja a futó programok mûködését, ezért ilyenkor érdemes megfontolni a kikapcsolását. ==== `vfs.hirunningspace` A `vfs.hirunningspace` sysctl változó értéke azt adja meg, hogy tetszõleges számú példánynál rendszerszinten mekkora mértékû írási mûvelet irányítható át a lemezvezérlõk soraiba. Az alapértelmezés többnyire elegendõ, de olyan gépeken, ahol sok lemez dolgozik egyszerre, ez az érték négy vagy öt _megabyte-ra_ is felszökhet! Hozzátennénk, hogy ha ezt az értéket túlságosan nagyra állítjuk (és így túllépjük a puffer írási küszöbértékét), akkor ezzel hihetetlenül gyenge fürtözési teljesítményt nyerünk. Semmiképp se állítsuk túlzottan nagy értékre! A nagyobb írási értékek a velük párhuzamos olvasások számára késleltetést is jelentenek. Találhatunk még más egyéb pufferelési és gyorsítótárazási sysctl változókat, azonban ezek megváltoztatását egyáltalán nem javasoljuk, mivel a virtuális memória alrendszer kiválóan tudja önállóan állítani ezeket a paramétereit. ==== `vm.swap_idle_enabled` A `vm.swap_idle_enabled` sysctl változó módosítása olyan nagyobb többfelhasználós rendszerekben bizonyulhat hasznosnak, ahol sok felhasználó lép be és lép ki a rendszerbe és sok az üresjáratban futó program. Az ilyen jellegû rendszerek hajlamosak nagy mennyiségû folyamatos terhelést mérni a tartalékolt szabad memóriára. A beállítás engedélyezésével, valamint a `vm.swap_idle_threshold1` és a `vm.swap_idle_threshold2` változókon keresztül a kilapozás "reakcióidejének" alkalmas behangolásával a megszokottnál gyorsabban lenyomhatjuk az üresjáratban dolgozó programokhoz tartozó memórialapok prioritását, amivel a kilapozásokat vezérlõ démon kezére játszunk. Azonban tényleg csak akkor engedélyezzük ezt a lehetõséget, ha valóban szükségünk van rá, mivel így a memóriát jóval elõbb lapozzuk ki és ezzel több lapozóállományt és lemezteljesítményt emésztünk fel. Kisebb rendszerekben jól behatárolható a hatása, azonban a nagyobb rendszerekben, ahol már eleve visszafogott mértékû lapozás történik, ez a beállítás lehetõvé teszi a virtuális memóriát kezelõ alrendszer számára, hogy könnyedén ki- és be rakosgasson komplett futó programokat a memóriába. ==== `hw.ata.wc` A FreeBSD 4.3 egyszer már kacérkodott az IDE-lemezek írási pufferének kikapcsolásával. Ez ugyan csökkentette az IDE-lemezek írási sávszélességét, azonban bizonyos merevlemezgyártók gondatlanságából eredõ súlyos adatvesztések miatt szükséges volt a használata. A gond ezzel kapcsolatban ott van, hogy egyes IDE-meghajtók hazudnak az írások teljesítésérõl. A lemezek írási gyorsítótárazásának bekapcsolásával az IDE-meghajtók nem csak az írások sorrendjét rendezik át, hanem nagyobb terhelés esetén egyes blokkokat jóval késõbb is rögzítenek. Ezért a rendszer esetleges összeomlása vagy egy áramkimaradás súlyos károkat okozhat az állományrendszerben. A FreeBSD úgy döntött, hogy a megbízhatóságot választja. Sajnos ez olyan nagyságú teljesítményvesztést okozott, hogy a következõ kiadásban már kénytelenek voltunk alapértelmezés szerint is visszakapcsolni ezt a lehetõséget. A `hw.ata.wc` nevû sysctl változó vizsgálatával ellenõrizhetjük a rendszerünkön érvényes alapértelmezett beállítást. Amennyiben az IDE írások gyorsítótárazása nem engedélyezett, akkor ezt a változó értékének 1-re állításával állíthatjuk vissza. Ezt a rendszer indításakor a rendszerbetöltõben tehetjük meg. A rendszermag indítása után ennek már nincs hatása. A részleteket a man:ata[4] man oldalon tudhatjuk meg. ==== `SCSI_DELAY` (`kern.cam.scsi_delay`) A rendszermag `SCSI_DELAY` nevû beállítása a rendszer indulásának idejét hivatott mérsékelni. Az alapértelmezett értéke viszonylag magas, innen származik a rendszer indítása során keletkezõ `15` másodperces csúszás. Általában az is megfelelõ, ha ezt visszavesszük az `5` értékre (fõleg a modernebb meghajtók számára). A FreeBSD újabb (5.0 vagy késõbbi) változataiban ez az érték már a `kern.cam.scsi_delay` sysctl változó értékével is megadható a rendszer indításakor. Azonban ügyeljünk rá, hogy mind a finomhangoláshoz használt változó, mind pedig rendszermag beállítása _ezredmásodpercben_ és _nemmásodpercben_ értelmezi ezt az értéket. [[soft-updates]] === Soft Updates A man:tunefs[8] nevû program használható az állományrendszerek finomhangolására. Nagyon sok opciót találhatunk benne, de itt most csak a "Soft Updates" ki- és bekapcsolásával foglalkozunk, amit a következõ módon tehetünk meg: [source,shell] .... # tunefs -n enable /allomanyrendszer # tunefs -n disable /allomanyrendszer .... Amíg egy állományrendszer csatlakoztatott állapotban van, addig nem módosítható a man:tunefs[8] paranccsal. A Soft Updates bekapcsolására ezért az a legalkalmasabb idõpont, amikor egyfelhasználós módban vagyunk és még egyetlen partíciót sem csatlakoztattunk. A Soft Updates beállítás engedélyezése a memóriában pufferelt gyorsítótáron keresztül jelentõs mértékben fokozza a metaadatok teljesítményét, elsõsorban az állományok létrehozását és törlését. A Soft Updates használatát ezért minden állományrendszer esetén ajánljuk. A Soft Updates alkalmazásának két rossz oldalára kell tekintettel lennünk. Elõször is a Soft Updates a rendszer összeomlása esetén ugyan garantálja az állományrendszer konzisztenciáját, de könnyen elképzelhetõ, hogy több másodperccel (vagy akár egy egész perccel!) hátrébb jár a fizikai lemez frissítésében. Másodszor a Soft Updates késlelteti az állományrendszer blokkjainak felszabadítását. Ha van egy olyan állományrendszerünk (mint például a rendszer indításához használt gyökér partíció), ami már majdnem betelt, akkor egy nagyobb frissítés, például a `make installworld` parancs kiadása, során az állományrendszer egyszerûen kifogy a helybõl és így a frissítés meghiúsul. ==== Bõvebben a Soft Updates mûködésérõl Két hagyományos megközelítés létezik az állományrendszerek metaadatainak visszaírására. (A metaadatok módosításakor olyan nem adatot tartalmazó blokkok változnak meg, mint például az állományokra vonatkozó információk vagy a könyvtárak.) Eredetileg alapértelmezés szerint a metaadatok változásait szinkron módon írták ki. Amikor egy könyvtár megváltozott, a rendszer egészen addig várt, amíg ez a változás a lemezre nem íródott. Ugyanekkor az állományok adatait tartalmazó pufferek (az állományok tartalma) átkerültek a pufferelt gyorsítótárba, hogy majd késõbb, aszinkron módon kerüljenek kiírásra. Ennek az implementációnak a biztonságos mûködés volt az elõnye, mivel így a metaadatok még akkor is konzisztens állapotban maradtak, amikor valamilyen hiba következett be. Tehát egy állomány vagy teljesen létrejött vagy egyáltalán nem. Ha az állományhoz tartozó blokkok már nem tudtak kijutni a gyorsítótárból az összeomlás ideje elõtt, akkor az man:fsck[8] felismerte ezt a helyzetet és az állományrendszer ilyen jellegû hibáját úgy orvosolta, hogy az adott állomány méretét nullára állította. Ezenkívül még az implementációs részletek is tiszták és egyszerûek maradtak. Ennek viszont hátránya, hogy a metaadatok kezelése lassú. Ha például kiadunk egy `rm -r` parancsot, akkor az a könyvtárban levõ állományokat szekvenciálisan dolgozza fel, de minden egyes változtatást (az állományok törlését) csak szinkron módon rögzíti a lemezre. Ezek a frissítések érintik magát a könyvtárat, az állományokkal kapcsolatos információkat tároló táblázatot (az ún. inode táblát) és minden valószínûség szerint az állományok által lefoglalt blokkokat is közvetve. Hasonló megfontolások élnek a nagyobb könyvtárszerkezetek kibontása esetén is (`tar -x`). A második lehetõség a metaadatok aszinkron frissítése. Ez az alapértelmezés a Linux ext2fs és BSD-k `mount -o async` opcióval csatlakoztatott UFS állományrendszerei esetén. Ilyenkor minden metaadattal kapcsolatos aktualizálás egyszerûen bekerült a pufferelt gyorsítótárba, tehát az állományok adatai és ezek a típusú frissítések keverednek. Ennek a megvalósításnak az az elõnye, hogy nem kell megvárni, amíg a metaadatok is kiíródnak a lemezre, ezért a metaadatok óriási mennyiségû változásával járó mûveletek sokkal gyorsabban hajtódnak végre, mint a szinkron esetben. Sõt, maga az implementáció is tiszta és egyszerû marad, ezért a kódban megjelenõ hibák beszivárgásának kockázata alacsony. A módszer hátránya, hogy egyáltalán semmilyen garanciát nem kapunk az állományrendszer konzisztenciájára. Ha tehát egy rengeteg metaadat megváltozásával együttjáró mûvelet közben történik valamilyen probléma (áramkimaradás, vagy valaki egyszerûen megnyomja a reset gombot), akkor az állományrendszer elõre kiszámíthatatlan állapotba kerül. A rendszer újbóli indításakor ezért nincs lehetõségünk megvizsgálni az állományrendszer állapotát. Elképzelhetõ, hogy az állományokhoz tartozó adatok már kikerültek a lemezre, miközben a rá vonatkozó inode- vagy könyvtári bejegyzések még nem. Így lényegében lehetetlen olyan `fsck` implementációt készíteni, ami képes lenne eltüntetni ezt a káoszt (hiszen az ehhez szükséges adatok nem állnak rendelkezésre). Ha az állományrendszer helyrehozhatatlanul károsodott, akkor csak a man:newfs[8] és a biztonsági mentés visszaállítása segíthet rajta. Ezt általában úgy küszöbölik ki, hogy az egészhez hozzáteszik még a _módosított területek feljegyzését_, amit gyakran csak _naplózásnak_ (journaling) neveznek, habár ezt az elnevezést nem mindenhol ilyen értelemben használják, ezért a tranzakciók naplózásának más formáira is utalhat. A metaadatok frissítése ebben az esetben is csak szinkron módon történik, de csak a lemez egy kisebb területére. Késõbb ez a megfelelõ helyére kerül. Mivel a lemez naplózásra fordított része egy viszonylag kis méretû, folytonos terület, a lemez fejének még a megterhelõbb mûveletek esetén sem kell sokat mozognia, ezért valójában ez a megoldás gyorsabb, mint a mezei szinkron frissítések. Az implementáció bonyolultsága továbbra is jól behatárolható, a velejáró hibalehetõségek kockázata alacsony. Hátránya, hogy minden metaadat kétszer íródik ki (egyszer a naplózási területre, aztán a megfelelõ helyre), ezért a hétköznapi használat során "visszaesés" tapasztalható a teljesítményben. Másrészrõl azonban egy összeomlás esetén a naplózási terület segítségével minden függõben levõ metaadattal kapcsolatos mûvelet könnyen visszafordítható vagy lezárható a rendszer következõ indításakor, így ezzel egy gyors helyreállítást nyerünk. Kirk McKusick, a Berkeley FFS fejlesztõje ezt a problémát a Soft Updates segítségével hidalta át: a metaadatokkal kapcsolatos minden függõben levõ frissítést a memóriában tart, majd ezeket rendezett sorrendben írja ki a lemezre ("a metaadatok rendezett frissítése"). Ennek következményeképpen a metaadatok komolyabb frissítése során a késõbb érkezõ módosításoknak lehetõségük van "elkapni" a memóriában levõ korábbi változataikat, ha azok még nem kerültek ki a lemezre. Így az összes, például könyvtárakon végzett, mûvelet a lemezre írás elõtt általában elõször a memóriában játszódik le (az adatblokkok a pozíciójuknak megfelelõen kerülnek rendezésre, ezért a rájuk vonatkozó metaadatok elõtt nem jutnak ki a lemezre). Ha eközben a rendszer összeomlik, akkor így implicit módon a "napló visszalapozását" eredményezi: minden olyan mûvelet, ami már nem tudott kijutni a lemezre, meg nem történtnek számít. Ezen a módon az állományrendszernek egy 30 és 60 másodperc közti korábbi állapota marad fenn. Az algoritmus garantálja, hogy az összes használt erõforrás a nekik megfelelõ bittérképekben helyesen jelölõdik, a blokkokban és az inode-okban. Az összeomlás után az erõforrások kiosztásával kapcsolatban csak egyetlen hiba léphet fel: amikor olyan erõforrások jelölõdnek "használtnak", amelyek igazából "szabadok". Az man:fsck[8] azonban képes felismerni ezeket a helyzeteket és felszabadítani a nem használt erõforrásokat. A `mount -f` parancs kiadásával minden további következmény nélkül figyelmen kívül hagyhatjuk az állományrendszer félkész állapotát és csatlakoztathatjuk az állományrendszereket. A használatban már nem levõ erõforrások felszabadításához az man:fsck[8] parancsot késõbb kell futtatni. Ez az alapötlet húzódik meg a _háttérben végzett lemezellenõrzés_ mögött. A rendszer indításakor az állományrendszernek csupán egy _pillanatképét_ rögzítjük, és az `fsck` tényleges lefuttatását késõbbre toljuk. Mivel mindegyik állományrendszer csatlakoztatható "félkész" állapotban, ezért a rendszer képes elindulni többfelhasználós módban. Eközben a háttérben az `fsck` beütemezhetõ minden olyan állományrendszer számára, ahol arra szükség van, hogy szabadítsa fel az esetlegesen már nem használt erõforrásokat. (Így a Soft Updates opciót nem alkalmazó állományrendszerek esetén továbbra is szükség van az elõtérben elvégzett `fsck` parancsra.) A módszer elõnye, hogy így a metaadatokkal kapcsolatos mûveletek közel olyan gyorsak, mint az aszinkron módon végzett frissítések (tehát gyorsabb, mintha _naplóznánk_, ami ugye minden metaadatot kétszer ír ki). A hátránya a bonyolultabb kód (ami miatt növekszik az olyan hibák lehetõsége, amelyek érzékenyen befolyásolhatják a felhasználói adatok elvesztését) és a nagyobb memóriaigény. Ezenkívül még van néhány olyan egyéni jellemzõje, amelyet meg kell szokni. A rendszer összeomlása után az állományrendszer valamivel "régebbi" lesz. Amikor pedig megszokott szinkron megközelítés szerint az `fsck` lefutása után nulla méretû állományok jönnének létre, ezek az állományok a Soft Updates esetén egyáltalán meg sem jelennek, mivel sem a rájuk vonatkozó metaadatok, sem pedig a tartalmuk nem került ki a lemezre. Egy `rm` lefuttatása után a lemezterület addig nem kerül felszabadításra, amíg a frissítések teljesen rá nem kerülnek a lemezre. Ez nagyobb mennyiségû adat telepítésekor gondokat okozhat egy olyan állományrendszeren, ahol nincs elegendõ hely az állományok kétszeri tárolására. [[configtuning-kernel-limits]] == A rendszermag korlátainak finomhangolása [[file-process-limits]] === Az állományok és a futó programok korlátozásai [[kern-maxfiles]] ==== `kern.maxfiles` A `kern.maxfiles` értéke a rendszerünk igényeinek megfelelõen növelhetõ vagy csökkenthetõ. Ez a változó adja meg a rendszerünkben levõ állományleírók maximális számát. Amikor az állományleírókat tároló táblázat megtelik, a rendszer üzenetpufferében egy `file: table is full` üzenet jelenik meg, amit a `dmesg` paranccsal tudunk megnézni. Minden megnyitott állomány, csatlakozás vagy FIFO elhasznál egy állományleírót. Egy nagyméretû szerver könnyen felemészthet több ezernyi állományleírót attól függõen, hogy milyen és mennyi szolgáltatást futtat egymás mellett. A FreeBSD korábbi kiadásaiban a `kern.maxfiles` a rendszermag beállításait tartalmazó állomány `maxusers` (a rendszerben egyszerre jelenlevõ felhasználók maximumának) értékébõl származott, tehát a `kern.maxfiles` a `maxusers` értékével arányosan növekszik. Amikor készítünk egy saját rendszermagot, mindig érdemes a rendszerünk használatának megfelelõen beállítani ezt az értéket, mivel a rendszermag ebbõl a számból határozza meg a legtöbb elõre meghatározott korlátait. Mivel még egy komoly szerveren sem jelentkeznek be egyszerre 256 felhasználónál többen, nagyjából ugyanannyi erõforrásra van szüksége, mint egy nagyobb webszervernek. A `kern.maxusers` értéke a rendelkezésre álló memóriának megfelelõen magától méretezõdik a rendszer indításakor, és amit futás közben csak a `kern.maxusers` sysctl változó írásvédett értékének lekérdezésébõl tudhatunk meg. Egyes oldalak üzemeltetése a `kern.maxusers` így megállapított értékétõl nagyobbat vagy éppen kisebbet igényel, ezért a betöltéskor minden gond nélkül át lehet állítani 64, 128 vagy 256 értékûre. Senkinek sem ajánljuk, hogy 256 felé menjen, hacsak tényleg nincs szüksége ekkora mennyiségû állományleíróra. A `kern.maxusers` függvényében beállított alapértelmezett értékek tetszõleges módon átállíthatóak a rendszer indításakor vagy futás közben a [.filename]#/boot/loader.conf# módosításával (az ide kapcsolódó javaslatokról bõvebben lásd a man:loader.conf[5] man oldalt vagy a [.filename]#/boot/defaults/loader.conf# állományt) illetve a leírás más részén megadott módok szerint. A korábbi kiadásokban úgy lehet önszabályozóra állítani a `maxusers` beállítást, ha explicit módon `0` értéket adtunk meg neki . A `maxusers` paraméter beállításakor érdemes legalább 4-et megadni, különösen akkor, ha használjuk az X Window Systemet vagy szoftvereket fordítunk le. Azért van erre szükség, mert a `maxusers` értéke által szabályozott legfontosabb mennyiség az egyszerre futtatható programok táblázatának maximális mérete, amelyet így számolunk ki: `20 + 16 * maxusers`. Tehát ha a `maxusers` értékét 1-re állítjuk be, akkor az elõbbi képlet értelmében csak 36 programunk futhat egymással párhuzamosan, beleértve mindazt a kb. 18 programot, amelyek a rendszerrel együtt indulnak, illetve még azt a további 15 programot, amelyeket az X Window System használatával indítunk el. Még egy olyan egyszerû dolog is, mint például egy man oldal megnézése, legalább kilenc programot indít el a szûréshez, kitömörítéshez és megnézéshez. Azonban ha a `maxusers` értékét 64-re állítjuk, akkor egyszerre akár már 1044 programot futtathatunk, ami szinte mindenre elegendõ. Ha persze egy új program indításakor kapunk egy típusú üzenetet vagy nagy számú konkurens felhasználóval futtatunk szervert (ilyen például az `ftp.FreeBSD.org`), akkor érdemes növelni ezt a számot és újrafordítani a rendszermagot. [NOTE] ==== A `maxusers` _nem_ korlátozza a számítógépre egyszerre bejelentkezni képes felhasználók számát. Egyszerûen csak beállítja néhány táblázat méretét és az egyszerre futtatható programok mennyiségét a rendszert egyidejûleg használni kívánó felhasználók maximális számának figyelembevételével. ==== ==== `kern.ipc.somaxconn` Az `kern.ipc.somaxconn` sysctl változó a beérkezõ TCP kapcsolatokat fogadó sor hosszát határozza meg. Ennek az alapértelmezett értéke `128`, ami az új kapcsolatok megbízható kezeléséhez általában kevés egy erõsen leterhelt webszerver számára. Ilyen helyzetekben ezt az értéket javasolt `1024`-re vagy még annál is nagyobbra állítani. Az egyes szolgáltatások démonai ugyan szintén korlátozni szokták a fogadósoruk méretét (például a man:sendmail[8] vagy az Apache), de gyakran találunk a beállításai között olyat, amivel ennek a sornak a mérete növelhetõ. A nagyobb fogadósorok mellesleg jó szolgálatot tesznek a Denial of Service () típusú támadásokkal szemben is. [[nmbclusters]] === Hálózati korlátozások A rendszermag `NMBCLUSTERS` nevû beállítása szab határt a rendszer részére elérhetõ memóriapufferek mennyiségének. Egy nagyobb forgalmú szerver esetén a pufferek alacsony száma gátat szabhat a FreeBSD képességeinek. Minden klaszter nagyjából 2 KB memóriát takar, így az 1024-es érték azt jelenti, hogy a rendszermag memóriájából 2 megabyte-ot fordítunk a hálózati pufferelésre. Egyszerûen kiszámítható, mennyire is van szükségünk: ha van egy webszerverünk, amely egyszerre legfeljebb 1000 párhuzamos kapcsolatot fogad, és minden kapcsolat lefoglal 16 KB-ot a fogadó-, valamint újabb 16 KB-ot a küldõpuffer számára, akkor megközelítõleg 32 MB-nyi hálózati pufferre lesz szükségünk a webszerver hatékony mûködéséhez. Ezt az értéket gyakran még érdemes megszorozni kettõvel, így 2 x 32 MB / 2 KB = 64 MB / 2 KB = 32768. Több memóriával rendelkezõ számítógépek esetén egy 4096 és 32768 közti értéket javaslunk. Semmilyen körülmények között ne adjunk meg ennél nagyobb értéket, mert ezzel a rendszer már az indítása során összeomolhat. A man:netstat[1] `-m` beállításával ellenõrizhetjük a hálózati klaszterek kihasználtságát. A `kern.ipc.nmbclusters` változó értékét a rendszer indításakor érdemes megváltoztatni. A FreeBSD korábbi változataiban ehhez a rendszermag `NMBCLUSTERS` nevû man:config[8] paraméterének módosítására van szükségünk. Az olyan forgalmasabb szervereken, ahol sokat használják a man:sendfile[2] rendszerhívást, szükségünk lehet a man:sendfile[2] által használt pufferek számának növelésére a rendszermag `NFSBUFS` nevû konfigurációs paraméterén vagy a [.filename]#/boot/loader.conf# állományon keresztül (lásd man:loader[8]). Amikor a futó programok közül sokan vannak `sfbufa` állapotban, akkor az egyértelmûen annak a jele, hogy ezen a paraméteren állítanunk kell. A `kern.ipc.nsfbufs` egy írásvédett változót, amelyet a rendszermag állít be. Ez a paraméter névlegesen a `kern.maxusers` változó értékének megfelelõen változik, de bizonyos esetekben ettõl függetlenül önállóan kell behangolni. [IMPORTANT] ==== Annak ellenére, hogy egy socketet blokkolásmentesnek jelöltünk meg, a man:sendfile[2] meghívása egy blokkolásmentes socketre blokkolódást eredményezhet egészen addig, amíg a használatához elegendõ `struct sf_buf` struktúra össze nem gyûlik. ==== ==== `net.inet.ip.portrange.*` A `net.inet.ip.portrange.*` sysctl változók vezérlik a TCP és UDP csatlakozásokhoz automatikusan hozzárendelt portszámok tartományát. Három ilyen tartomány létezik: az alsó, az alapértelmezett és a felsõ tartomány. A legtöbb hálózati program a `net.inet.ip.portrange.first` és `net.inet.ip.portrange.last` változók által rendre az 1024-tõl 5000-ig kijelölt alapértelmezett tartományt használja. A kimenõ kapcsolatok is rögzített porttartományokat követnek, és adott körülmények mellett be lehet állítani úgy a rendszerünket, hogy ezen kívül osszon ki portokat. Ez a legtöbbször akkor fordul elõ, amikor egy erõsen leterhelt webproxyt mûködtetünk. A porttartományok nem okoznak gondot olyan szervereknél, ahol általában bejövõ kapcsolatokra lehet számítani, tehát például webszerverek esetén, vagy ahol korlátozott a kimenõ kapcsolatok száma, mint például a levelek továbbításánál. Ha olyan helyzetbe keverednénk, ahol már kifutunk a felhasználható portokból, a `net.inet.ip.portrange.last` mérsékelt növelésével javasolt kitörni. Ilyenkor a `10000`, `20000` vagy `30000` értékek elfogadhatóak. Amikor megváltoztatjuk a porttartományok határait, elõtte mindig gondoljuk át, milyen hatással lehet ez a tûzfalra. Egyes tûzfalak blokkolhatnak bizonyos tartományokat (általában az alacsonyabbakat) és arra számítanak, hogy a rendszerek a kimenõ kapcsolatokhoz a nagyobb számú portokat használják - ebbõl kifolyólag nem ajánlott csökkenteni a `net.inet.ip.portrange.first` értékét. ==== A TCP sávszélesség-késletetés szorzat A TCP sávszélesség-késleltetés szorzat korlátozása hasonlít a NetBSD-ben megtalálható TCP/Vegas implementációhoz. A `net.inet.tcp.inflight.enable` sysctl változó `1`-re állításával lehet engedélyezni. A rendszer ilyenkor minden egyes kapcsolathoz megpróbálja kiszámítani a sávszélesség-késleltetés szorzatot és az optimális átviteli sebesség fenntartásához illeszkedõen korlátozni a hálózat felé küldött adatok sorának hosszát. Ez a lehetõség még olyankor bizonyulhat hasznosnak, amikor modemen, Gigabit Etherneten vagy nagysebességû WAN (vagy bármilyen más nagy sávszélesség-késleltetés szorzattal bíró) összeköttetéseken keresztül küldünk át adatokat, különösen abban az esetben, amikor ablakméretezést is használnunk vagy nagy küldési ablakot állítottunk be. Az engedélyezésekor ne felejtsük el `net.inet.tcp.infligt.debug` változót sem beállítani `0`-ra (amivel így kikapcsoljuk a nyomkövetést),éles használat esetén pedig elõnyös lehet a `net.inet.cp.inflight.min` változót legalább `6144`-re állítani. Azonban hozzátesszük, hogy összeköttetéstõl függõen a nagy minimum értékek tulajdonképpen kikapcsolják a sávszélességkorlátozást. Ez a korlátozási lehetõség csökkenti a közbensõ út adatainak és csomagváltásokhoz tartozó soroknak a méretét, miközben csökkenti a helyi számítógép felületén felépülõ sorok méretét is. Ha kevesebb csomagot rakunk be a sorba, akkor az interaktív kapcsolatok, különösen a lassabb modemek esetében, kisebb _körbejárási idõvel_ (Round Trip Time) mûködnek. Továbbá megemlítenénk, hogy ez a lehetõség csak az adatok küldésére (feltöltésére, szerveroldalra) van hatással. Semmilyen befolyása nincs az adatok fogadására (letöltésére). A `net.inet.tcp.inflight.stab` állítgatása _nem_ ajánlott. A paraméter értéke alapértelmezés szerint 20, ami legfeljebb 2 csomag hozzáadását jelenti a sávszélesség-késleltetés szorzat ablakának kiszámításakor. Erre a kiegészítõ ablakra azért van szükség, hogy stabilizálni tudjuk vele az algoritmust és javítani tudjuk a változó feltételekre adott reakciót, de lassabb összeköttetések esetében nagyobb ping idõket is eredményezhet (habár ezek még így kisebbek, mint ha nem használnánk az algoritmust). Ilyen esetekben megpróbálhatjuk 15-re, 10-re vagy esetleg 5-re visszavenni a paraméter értékét, de ekkor a kívánt hatás eléréséhez minden bizonnyal a `net.inet.tcp.inflight.min` értékét is redukálunk kell majd (például 3500-ra). Ezen paraméterek megváltoztatását csak végsõ esetben ajánljuk! === Virtuális memória ==== `kern.maxvnodes` A vnode egy állomány vagy könyvtár belsõ ábrázolása. Ennek megfelelõen a vnode-ok számának növelésével az operációs rendszer spórolni tud a lemezmûveletekkel. Ezt általában maga az operációs rendszer szabályozza, és nincs szükség a finomhangolására. Néhány esetben, amikor a lemezmûveletek jelentik a rendszerben a szûk keresztmetszetet és kezdenek elfogyni a vnode-ok, szükség lehet ennek a számnak a növelésére. Ehhez az inaktív és szabad fizikai memória mennyiségét kell számításba vennünk. Így kérhetjük le a pillanatnyilag használatban levõ vnode-ok mennyiségét: [source,shell] .... # sysctl vfs.numvnodes vfs.numvnodes: 91349 .... Így tudhatjuk meg a vnode-ok maximális számát: [source,shell] .... # sysctl kern.maxvnodes kern.maxvnodes: 100000 .... Ha a vnode-ok aktuális kihasználtsága megközelíti a csúcsértéket, nagyjából ezerrel javasolt megnövelni a `kern.maxvnodes` értékét. Ezután figyeljük továbbra is a `vfs.numvnodes` változását. Ha ismét felkúszik a maximális értékre, akkor növeljük megint egy keveset a `kern.maxvnodes` értékén. Eközben a man:top[1] használatával figyelhetjük a memória kihasználtságának növekedését is, ilyenkor tehát több memóriának kell használatban lennie. [[adding-swap-space]] == A lapozóterület bõvítése Nem számít, mennyire tervezünk jól elõre, mindig elõfordulhat, hogy a rendszerünk mégsem teljesíti a kitûzött elvárásokat. Amennyiben további lapozóterület hozzáadására lenne szükségünk, azt igen könnyen megtehetjük. Háromféleképpen növelhetjük a lapozásra szánt területet: hozzáadunk a rendszerhez egy újabb merevlemezes meghajtót, NFS-en keresztül lapozunk, vagy egy már meglevõ partíción hozunk létre lapozóállományt. A lapozóterület titkosításával, valamint annak lehetõségeivel és okaival kapcsolatban lapozzuk fel a kézikönyv crossref:disks[swap-encrypting,A lapozóterület titkosítása]át. [[new-drive-swap]] === Lapozás egy új merevlemezre A lapozóterület bõvítésének legjobb módja természetesen remek indok egy új merevlemez beszerzésére is. Elvégre egy merevlemezt mindig fel tudunk ilyen célra használni. Ha ezt a megoldást választjuk, elõtte ajánlott (újra) elolvasni a kézikönyv <>ában a lapozóterületek elrendezésére vonatkozó javaslatokat. [[nfs-swap]] === Lapozás NFS-en keresztül NFS-en keresztül csak akkor lapozzunk, ha ezt helyi lemezek segítségével nem tudjuk megtenni. Az NFS alapú lapozás hatékonyságát erõsen behatárolja a rendelkezésre álló hálózati sávszélesség és további terheket ró az NFS szerverünkre is. [[create-swapfile]] === Lapozóállományok Lapozóállománynak egy adott méretû állományt hozzunk létre. Ebben a példában erre egy [.filename]#/usr/swap0# nevû, 64 MB méretû állományt fogunk használni. Természetesen bármilyen más nevet is választhatunk. .Lapozóállomány létrehozása FreeBSD-ben [example] ==== . Gyõzõdjünk meg róla, hogy a rendszermagunk beállításai között megtalálható a memórialemez meghajtójának (man:md[4]) használata. Ez a [.filename]#GENERIC# rendszermag alapból tartalmazza. + [.programlisting] .... device md # Memória "lemezek" .... + . Hozzunk létre egy lapozóállományt ([.filename]#/usr/swap0#): + [source,shell] .... # dd if=/dev/zero of=/usr/swap0 bs=1024k count=64 .... + . Állítsuk be rá a megfelelõ engedélyeket ([.filename]#/usr/swap0#): + [source,shell] .... # chmod 0600 /usr/swap0 .... + . Adjuk meg a lapozóállományt az [.filename]#/etc/rc.conf# állományban: + [.programlisting] .... swapfile="/usr/swap0" # Állítsuk be swapfile értékét, ha külsõ lapozóállományra van szükségünk. .... + . Indítsuk újra a számítógépünket, vagy a lapozóállomány azonnali használtba vételéhez írjuk be: + [source,shell] .... # mdconfig -a -t vnode -f /usr/swap0 -u 0 && swapon /dev/md0 .... ==== [[acpi-overview]] == Energia- és erõforrásgazdálkodás Fontos a hardveres erõforrásaink hatékony kihasználása. Az ACPI megjelenése elõtt az operációs rendszerek csak nehézkesen és rugalmatlanul tudták kezelni a rendszer energiafelhasználási és hõszabályzási lehetõségeit. A hardvert a BIOS kezelte, ezért a felhasználó kevesebbet tudott látni és irányítani az energiagazdálkodási beállításokból. Az _Fejlett energiagazdálkodás (Advanced Power Management, APM)_ ehhez nyújtott egy erõsen korlátozott felületet. Napjaink operációs rendszereiben az energia- és erõforráskezelés az egyik legfontosabb alkotóelem. Például, ha az operációs rendszerrel folyamatosan figyelni akarjuk a rendszer hõmérsékletének váratlan növekedését (és errõl figyelmeztetést kérni). A FreeBSD kézikönyvének ezen szakaszában az ACPI-rõl adunk egy átfogó áttekintést, a végén pedig összefoglaljuk a témához tartozó irodalmat. [[acpi-intro]] === Mi az ACPI? A speciális energia- és konfigurációs illesztõ felület (Advanced Configuration and Power Interface, avagy ACPI) gyártók egy csoportja által létrehozott szabvány, amely a hardveres erõforrások és az energiagazdálkodás egységes felületét rögzíti (innen a neve). Döntõ szerepet játszik a _Beállítások és az energiagazdálkodás operációs rendszerek áltai vezérlésében_, vagyis segítségével az operációs rendszer még nagyobb mértékben és rugalmassággal tudja irányítani ezeket a lehetõségeket. A modern operációs rendszerek az ACPI felbukkanásával "kitolták" a jelenleg meglevõ Plug and Play felületek korlátait. Az ACPI az APM közvetlen leszármazottja. [[acpi-old-spec]] === A Fejlett energiagazdálkodás (APM) hiányosságai A _Fejlett energiagazdálkodás (APM)_ a rendszer által felhasznált energiát annak elfoglaltsága alapján vezérli. Az APM-et támogató BIOS-t a (rendszert) gyártó állítja elõ és az adott hardverplatformra jellemzõ. Az APM operációs rendszerben levõ meghajtója hozzáférést biztosít az _APM szoftveres felületéhez_, amivel lehetõség nyílik az energiaszintek kezelésére. Az APM-et 2000 elõtt és körül még mindig használták egyes rendszerek gyártásánál. Az APM használata négy nagyobb gondot rejt magában. Elõször is, az energiagazdálkodást a (gyártófüggõ) BIOS végzi el, és az operációs rendszernek errõl semmilyen ismerete nincsen. Ennek egyik példája az, amikor a felhasználó az APM-et ismerõ BIOS-ban beállítja a merevlemezek automatikus kikapcsolásának idejét, majd amikor ez letelik, a BIOS az operációs rendszer tudta nélkül egyszerûen leállítja a lemezt. Másodszor: az APM mûködését a BIOS-ban programozták le, és teljesen az operációs rendszer hatáskörén túl tevékenykedik. Ez azt jelenti, hogy a felhasználó csak úgy tudja korrigálni az APM-es BIOS-ok problémáit, ha frissíti az alaplapi ROM-ot. Ez viszont egy nagyon kockázatos folyamat, amelynek hibája révén a rendszerünk helyrehozhatatlan állapotba kerülhet. Harmadszor: az APM alapvetõen egy gyártófüggõ megoldás, ami azt vonja maga után, hogy sok az átfedés (ugyanazt valósítják meg több módon), és ha az egyik gyártó BIOS-ában hibát találnak, akkor a másikéban az nem feltétlenül javítható. Végül, de nem utolsósorban, az APM alapú BIOS-okban nincs elég hely az igazán kifinomult energiagazdálkodási sémák vagy bármi más kialakítására, amivel a felhasználók képesek lennének az igényeikhez alakítani a számítógépet. A _Plug and Play BIOS (PNPBIOS)_ sok szempontból megbízhatatlannak bizonyult. A PNPBIOS ráadásul egy 16 bites megoldás, ezért az operációs rendszereknek 16 bites emulációt kell használniuk a PNPBIOS eszközeinek "eléréséhez". A FreeBSD APM meghajtójának dokumentációját az man:apm[4] man oldalon találjuk. [[acpi-config]] === Az ACPI beállítása Az [.filename]#acpi.ko# meghajtó alapértelmezés szerint a man:loader[8] segítségével töltõdik be, és _ne_ is fordítsuk bele a rendszermagba. Ezt azzal tudnánk magyarázni, hogy modulokkal könnyebb dolgozni, például ha a rendszermag újrafordítása nélkül egy másik [.filename]#acpi.ko# modult akarunk használni. Ezzel a lényegében a tesztelés is egyszerûbbé válik. Másik magyarázat, hogy a rendszer ACPI támogatása nem minden esetben mûködik rendesen. Ha a rendszer indítása során valamilyen problémát tapasztalunk, akkor próbálkozzunk meg az ACPI kikapcsolásával. Ezt a meghajtót nem lehet és nem is szabad kidobni a memóriából, mivel a hardverrel a rendszerbuszon keresztül tartja a kapcsolatot. Az ACPI a `hint.acpi.0.disabled="1"` sor megadásával kapcsolható a [.filename]#/boot/loader.conf# állományban vagy a man:loader[8] parancssorában. [NOTE] ==== Az ACPI és az APM nem használató egyszerre. Közülük a késõbb betöltött magától kilép, ha észreveszi, hogy a másikuk már mûködésbe lépett. ==== Az ACPI és az man:acpiconf[8] használatával a rendszerünk készenléti módba helyezhetõ az `-s` valamint az `1-5` paraméterek megadásával. Ezek közül is a legtöbb felhasználó számára csak az `1` vagy a `3` (állapot mentése a fizikai memóriába) érdekes. Az `5` opció egy szoftveres kikapcsolást eredményez, ehhez hasonlóan: [source,shell] .... # halt -p .... A további opciók a man:sysctl[8] man oldaláról érhetõek el. Ezen kívül még olvassuk el az man:acpi[4] és man:acpiconf[8] man oldalakat is. [[ACPI-debug]] == A FreeBSD ACPI támogatásának használata és nyomonkövetése Az ACPI az eszközök felderítésének, energiagazdálkodásának és a korábban a BIOS által kezelt hardverek szabványosított hozzáférésének alapjaiban új módja. Az ACPI folyamatosan fejlõdik, de útját az egyes alaplapok _ACPI Machine Language_ (AML) bytekód implementációjában megjelenõ hibák, a FreeBSD rendszermag alrendszereinek befejezetlensége és az Intel(R) ACPI-CA értelmezõjében levõ hibák lassítják. Ez a leírás azzal a szándékkal készült, hogy segítsünk a felhasználóknak megtalálni az általuk tapasztalt problémák gyökerét és ezzel segíteni az ACPI fejlesztõket a nyomonkövetésében és kijavításában. A fejlesztõk köszönik, hogy ezt elolvassuk és segédkezünk a rendszerünkkel kapcsolatban felmerülõ problémák orvosolásában! [[ACPI-submitdebug]] === A nyomkövetési információk beküldése [NOTE] ==== Mielõtt beküldenénk bármilyen problémát is, gondoskodjunk róla, hogy a BIOS-unk, és ha lehetséges, akkor a beágyazott vezérlõk, legfrissebb verzióját használjuk. ==== Megkérnénk azokat, akik hibát akarnak bejelenteni, hogy a következõ információkat küldjék a link:mailto:freebsd-acpi@FreeBSD.org[ freebsd-acpi@FreeBSD.org] címre: * A hibás mûködés leírása, beleértve a rendszer típusát és gyártmányát, illetve minden olyat, aminek köze lehet a hibához. Ha eddig még nem tapasztaltuk, igyekezzünk minél pontosabban leírni a hiba keletkezésének folyamatát. * A `boot -v` paranccsal indított rendszer man:dmesg[8] kimenetét, beleértve a vizsgálni kívánt hiba által okozott összes hibaüzenetet. * A `boot -v` paranccsal és az ACPI használata nélkül indított rendszer man:dmesg[8] kimenete abban az esetben, ha ez segít megoldani a problémát. * A `sysctl hw.acpi` parancs kimenete. Ezzel egyébként kitûnõen kideríthetõ, milyen lehetõségeket is kínál fel a rendszerünk. * Az általunk használt _ACPI forrásnyelvének_ (ACPI Source Language, ASL) elérhetõsége az interneten. Mivel ezek akár igen nagyok is lehetnek, ezért a listára közvetlenül ne küldjünk ASL kódokat! Az ASL másolatát az alábbi parancs kiadásával hozhatjuk létre: + [source,shell] .... # acpidump -dt > név-rendszer.asl .... + (Adjuk meg a _név_ helyett a bejelentkezéshez használt nevünket, a _rendszer_ helyett pedig a gyártót/típust. Például: [.filename]#njl-FooCo6000.asl#) Habár a legtöbb fejlesztõ a {freebsd-current}t figyeli, a problémáink leírását mindenképpen a {freebsd-acpi} listára küldjük, hogy biztosan észrevegyék. A fejlesztõk azt kérik, hogy legyünk türelmesek, hiszen emellett mindannyian teljes állásban is dolgoznak. Ha az általunk felfedezett hiba nem teljesen egyértelmû, akkor a fejlesztõk valószínûleg meg fognak kérni arra, hogy a man:send-pr[1] használatával hozzunk róla létre egy hivatalos hibajelentést. A hibajelentés készítésekor lehetõleg a fentebb megadott információkat ugyanúgy adjuk meg. Ez segít a probléma szemmel tartásában és elhárításában. Az {freebsd-acpi} lista kihagyása nélkül közvetlenül ne küldjünk hibajelentést, mivel a hibabejelentõ rendszert elsõsorban emlékeztetõnek használjuk, nem pedig a hibák tényleges bejelentésére. Gyakran elõfordul, hogy valaki korábban már találkozott az adott problémával. [[ACPI-background]] === Háttér Az ACPI minden olyan modern számítógépben megtalálható, mely megfelel az ia32 (x86), ia64 (Itanium) vagy amd64 (AMD) architektúrának. A teljes szabvány rengeteg lehetõséget biztosít, többek közt a processzor teljesítményének kezelését, az energiaszintek vezérlését, hõzónákat, különféle akkumulátor rendszereket, beágyazott vezérlõk és a buszok felsorolását. A legtöbb rendszer általában nem a teljes szabványt valósítja meg. Például egy asztali rendszer általában csak a buszok felsorolásával kapcsolatos részeket tartalmazza, miközben egy laptop felajánlhatja a hûtés és az akkumulátor kezelését is. A laptopokban gyakorta találunk készenléti üzemmódot a maguk elbonyolított formájában. Egy ACPI-nak megfelelõ rendszert számos összetevõ alkot. A BIOS-ok és chipkészletek gyártói a memóriában egy elõre rögzített ponton elhelyeznek bizonyos táblázatokat (például FADT), amelyekkel megadják például az APIC összerendeléseit (ezt az SMP rendszerek használják), a konfigurációs regisztereket és az egyszerûbb konfigurációs értékeket. Itt ezenkívül még bytekódok egy táblázata (amit _Differenciált rendszerleírtó táblának_, Differentiated System Description Table, DSDT nevezünk) is megtalálható, ahol az eszközök és módszerek nevei szerepelnek faszerû elrendezésben. Az ACPI-hoz tartozó meghajtónak képesnek kell lennie értelmezni ezeket a rögzített táblázatokat, implementálni egy bytekód-értelmezõt, módosítani az eszközmeghajtókat és a rendszermagot az ACPI alrendszerbõl érkezõ információk befogadásához. A Linuxszal és a NetBSD-vel közösen a FreeBSD kapott egy ilyen értelmezõt az Intel(R)tõl (ACPI-CA). Az ACPI-CA forráskódja a rendszer forrásai között, a [.filename]#src/sys/dev/acpica# könyvtárban található. A [.filename]#src/sys/dev/acpica/0sd# könyvtárban található források pedig lehetõvé teszik, hogy az ACPI-CA mûködhessen FreeBSD-n. Végezetül, az ACPI eszközöket megvalósító meghajtók a [.filename]#src/sys/dev/acpica# könyvtárban találhatóak. [[ACPI-comprob]] === Gyakori problémák Az ACPI megfelelõ mûködéséhez minden alkotórésznek helyesen kell mûködnie. A most következendõkben elõfordulásuk gyakorisága szerint felsorolunk néhány ismert problémát, valamint a hozzájuk tartozó javításokat vagy elkerülésük módszerét. ==== Gondok az egérrel Egyes esetekben felfüggesztett állapotból visszatérve az egerünk nem hajlandó mûködni. Ezt úgy lehet elkerülni, ha [.filename]#/boot/loader.conf# állományba beírjuk a `hint.psm.0.flags="0x3000"` sort. Ha ez nem segít, akkor a fentieknek megfelelõen küldjünk be egy hibajelentést. ==== Felfüggesztés/Folytatás Az ACPI három (STR) állapotban képes a fizikai memória segítségével készenléti módba váltani, ezek az `S1`-`S3`, és egy állapotban használja a lemezt (`STD`), amelyet `S4`-nek hívnak. Az `S5` neve a "szoftveres kikapcsolás", ami egy olyan állapotot takar, amikor a rendszerünk áram alatt van, de még nem üzemel. Az ``S4``BIOS állapot a BIOS segítségével a lemezre menti a rendszert, az ``S4``OS állapotot pedig teljes egészében az operációs rendszer valósítja meg. A rendszerünk által ismert készenléti módokat a `sysctl hw.acpi` paranccsal ellenõrizhetjük. Íme mindez egy Thinkpad esetén: [source,shell] .... hw.acpi.supported_sleep_state: S3 S4 S5 hw.acpi.s4bios: 0 .... Ez azt jelenti, hogy az `acpiconf -s` parancs kiadásával kipróbálhatjuk az `S3`, ``S4``OS, és `S5` állapotokat. Ha az `s4bios` értéke egy (`1`), akkor az ``S4``BIOS támogatása helyett az ``S4``OS állapotot kapjuk. A felfüggesztés és folytatás kipróbálása során kezdjük az `S1` állapottal, már amennyiben az támogatott a rendszerünkön. Ez az állapot többnyire használható, mivel nem igényel túlságosan sok támogatást a meghajtó részérõl. Eddig még senki sem implementálta az `S2` állapotot, de ha ezt is tudja a rendszerünk, akkor az `S1`-hez hasonlót nyerünk vele. A következõ próba az `S3` állapoté. Ez a legmélyebb STR állapot, és a hardver megfelelõ újraélesztéséhez rengeteg támogatás szükségeltetik a meghajtó részérõl. Ha gondjaink lennének a rendszerünk felébresztésével, nyugodtan írjunk egy levelet a {freebsd-acpi} listára, ám a probléma gyors megoldódásában ne reménykedjünk, hiszen ehhez még temérdek meghajtón és hardveren kell tesztelni és kell dolgozni. Felfüggesztés és folytatás esetén gyakori probléma, hogy sok eszközmeghajtó nem menti el, nem állítja vissza vagy éppen nem hozza újra rendesen mûködésbe az adott eszközön található firmware-t, a regisztereket vagy memóriát. Az okok felderítéséhez elõször érdemes a következõket kipróbálni: [source,shell] .... # sysctl debug.bootverbose=1 # sysctl debug.acpi.suspend_bounce=1 # acpiconf -s 3 .... Ezzel a módszerrel tesztelni tudjuk az összes meghajtó felfüggesztési és folytatási rutinjait anélkül, hogy ténylegesen `S3` állapotba helyeznénk az eszközt. Bizonyos esetekben ezzel könnyen elcsíphetõ a hiba (például a firmware állapotának elvesztése, watchdog time out, megállás nélküli újrapróbálkozások). A rendszer ilyenkor nem vált `S3` állapotra, vagyis az eszköz nem kerül energiatakarékos állapotba, és eltérõen a valós `S3` állapottól továbbra is mûködik még abban az esetben is, amikor a szükséges felfüggesztési és folytatási rutinok teljesen hiányoznak. Komolyabb esetben további segédeszközökre lesz szükségünk, vagyis soros portra és kábelre a soros vonali nyomkövetéshez, vagy Firewire portra és kábelre a man:dcons[4] használatához, valamint némi tapasztalatra a rendszermagon belüli hibakeresésben. A problémát nagy mértékben segíti különválasztani, ha igyekszünk minél több meghajtót kivenni a rendszermagból. Ha így javul a helyzet, akkor már könnyen le lehet szûkíteni arra a meghajtóra a kört, aminek betöltésével esetleg gondok akadhatnak. Általában ilyenek a bináris meghajtók, mint például az [.filename]#nvidia.ko#, az X11 megjelenítésért felelõs és az USB eszközök meghajtói, miközben az Ethernet eszközök remekül szoktak mûködni. Ha különösebb gond nélkül képesek vagyunk betölteni és eltávolítani ezeket a meghajtókat, akkor ezt a folyamatot önállósítani is tudjuk úgy, hogy az [.filename]#/etc/rc.suspend# és [.filename]#/etc/rc.resume# szkriptekbe beillesztjük az ehhez szükséges parancsokat. Ezekben egyébként találunk is egy megjegyzésbe rakott példát a meghajtók betöltésérõl és eltávolításáról. Ha az ébresztés után elszemetelõdik a képernyõ tartalma, akkor állítsuk át a `hw.acpi.reset_video` változó értékét nullára (`0`). Sokat segíthet meg az is, ha a `hw.acpi.sleep_delay` értékét csökkentjük vagy növeljük. Megpróbálhatjuk azt is, hogy elindítunk egy frissebb Linux disztribúciót ACPI támogatással és ugyanazon a hardveren kipróbáljuk az általa felkínált felfüggesztési és folytatási lehetõséget. Ha Linux alatt ez megbízhatóan mûködik, akkor nagy a valószínûsége, hogy ez FreeBSD alatt az egyik meghajtó hibájából fakadóan nem használható. Így fokozatosan le is tudjuk szûkíteni, hogy pontosan melyikkel lehet a gond, és ezzel a fejlesztõk munkáját segítjük. Megjegyeznénk, hogy az ACPI-t karbantartó fejlesztõk általában nem foglalkoznak más meghajtókkal (például hangkártya vagy ATA stb.), ezért az adott meghajtóval kapcsolatos hibáról javasolt értesíteni a {freebsd-current} listát és a meghajtóért felelõs fejlesztõt is. Ha van egy kis kedvünk és idõnk, mi magunk is belebiggyeszthetünk a meghajtóba néhány man:printf[3] függvényt annak kiderítésére, pontosan hol is fagy le a folytatási funkció. Végül megpróbálkozhatunk az ACPI kikapcsolásával is, és áttérhetünk helyette az APM használatára. Ha az APM-mel mûködnek a készenléti állapotok, akkor érdemes inkább azzal dolgozni, különösen a régebbi (2000 elõtti) hardverek esetében. A gyártóknak eltartott egy ideig, amíg rendes ACPI támogatást voltak képesek adni, ezért a régebbi hardvereknél inkább a BIOS-nak akadnak gondjai az ACPI-val. ==== A rendszer lemerevedik (ideiglenesen vagy teljesen) A legtöbb rendszer olyankor akad meg, amikor sok megszakítás elveszik, vagy amikor éppen sok megszakítás érkezik egyszerre. A chipkészleteknek számos baja származik abból, hogy a BIOS milyen módon állítja be a rendszer indítása elõtt a megszakításokat, mennyire helyes az APIC (MADT) táblázata és hogyan vezérli a _Rendszervezérlõ megszakítást_ (System Control Interrupt, SCI). A megszakítás-viharok a `vmstat -i` parancs kimenetében szereplõ elveszett megszakításokból azonosíthatók be, ahol keressünk rá az `acpi0` sorra. Ha ez a számláló másodpercenként kettõnél többel növekszik, akkor a megszakításaink viharba keveredtek. Ha a rendszer látszólag lefagyott, próbáljuk meg elõhívni a DDB-t (konzolban a kbd:[CTRL+ALT+ESC]) és gépeljük be, hogy `show interrupts`. A megszakítási problémákkal kapcsolatban egyetlen reményünk az APIC támogatás kikapcsolása lehet a [.filename]#loader.conf# állományban a `hint.apic.0.disabled="1"` sor hozzáadásával. ==== Végzetes hibák Az ACPI-vel kapcsolatos végzetes hibák viszonylag ritkák, és javításuk a legfontosabb. Ilyenkor az elsõ teendõnk elkülöníteni a hiba reprodukálásának egyes lépéseit és (ha lehetséges) lekérni a hívási láncot. Kövessük az `options DDB` és a soros vonali konzol beállításához adott tanácsokat (lásd crossref:serialcomms[serialconsole-ddb,A DDB elérése a soros vonalról]) vagy hozzunk létre egy man:dump[8] partíciót. A DDB-ben a hívási láncot a `tr` parancs segítségével kérhetjük le. Ha kézzel írjuk le láncot, akkor legalább az alsó öt (5) és a felsõ öt (5) sorát mindenképpen jegyezzük fel! Ezután próbáljuk meg úgy szûkíteni a probléma lehetõségét, hogy az ACPI használata nélkül indítjuk a rendszert. Ha ezzel nincs semmi gond, akkor a `debug.acpi.disable` változó értékének megfelelõ beállításával egyenként meg tudjuk figyelni az ACPI alrendszer egyes részeit. Ehhez példákat az man:acpi[4] man oldalon találunk. ==== Felfüggesztés vagy leállítás után elindul a rendszer Elõször is próbáljuk meg a `hw.acpi.disable_on_poweroff` változó értékét `0`-ra állítani a man:loader.conf[5] állományban. Ezzel távoltartjuk az ACPI alrendszert a rendszer leállítási folyamatától. Egyes rendszereknek valamilyen okból kifolyólag szükségük van itt az `1` (az alapértelmezett) értékre. Ez többnyire megoldja a problémát, amikor a rendszer váratlanul elindul a készenléti mód aktiválásákor vagy kikapcsoláskor. ==== Egyéb problémák Ha más gondjaink lennének az ACPI-val (dokkoló állomásunk van, egyes eszközöket nem vesz észre stb.), akkor természetesen errõl is küldjünk egy leírást a levelezési listára. Azonban vegyük figyelembe, hogy egyes problémák a ACPI alrendszer eddig még nem implementált, befejezetlen részeihez kötõdnek, ezért azok megoldása még várat magára. Kérünk mindenkit, hogy legyen türelemmel és álljon készen a kiküldött javítások tesztelésére! [[ACPI-aslanddump]] === ASL, `acpidump` és IASL A problémák leggyakoribb forrása, hogy a BIOS-gyártók rossz (vagy kifejezetten hibás!) bytekódokat adnak. Ez általában a következõhöz hasonló rendszerüzenetbõl derül ki: [source,shell] .... ACPI-1287: *** Error: Method execution failed [\\_SB_.PCI0.LPC0.FIGD._STA] \\ (Node 0xc3f6d160), AE_NOT_FOUND .... Az ilyen jellegû hibákat gyakran úgy lehet orvosolni, ha a BIOS-unkat frissítjük a legújabb verzióra. A legtöbb ilyen üzenet teljesen ártalmatlan, de ha vannak más problémáink is, például az akkumulátor állapota nem olvasható le, akkor elõször az AML környékén érdemes kutakodnunk. A bytekód, más néven AML, az ASL elnevezésû forrásnyelvbõl származik. Az AML egy DSDT néven ismert táblázatban található meg. Az ASL másolatát az man:acpidump[8] paranccsal készíthetjük el. Paraméterként egyaránt adjuk meg a `-t` (megmutatja a rögzített táblák tartalmát) és `-d` (visszafejti az AML kódokat az ASL nyelvére) kapcsolókat. A felírás pontos formátumát a <> címû szakaszban olvashatjuk. Elsõként próbáljuk meg újrafordítani az így nyert ASL programot és keressünk benne hibákat. A figyelmeztetések általában nyugodtan figyelmen kívül hagyhatóak, azonban a hibák olyan implementációs hibákra utalnak, amelyek akadályozzák az ACPI helyes mûködését. Az ASL újrafordítását az alábbi paranccsal tudjuk elvégezni: [source,shell] .... # iasl saját.asl .... [[ACPI-fixasl]] === Az ASL kijavítása Végeredményben az a célunk, hogy az ACPI megfelelõ mûködéséhez senkinek se kelljen hozzányúlnia semmihez. Azonban még mindig szükség van BIOS-gyártók által elkövetett gyakori hibák elkerülésének kifejlesztésére. A Microsoft(R) értelmezõje ([.filename]#acpi.sys# és [.filename]#acpiec.sys#) nem ellenõrzi szigorúan a szabvány szerinti megfelelést, ezért számos olyan BIOS-gyártó, akik csak Windows(R) alatt tesztelik az ACPI implementációjukat, soha nem fogják kijavítani a ASL kódjukban ejtett hibáikat. Reménykedünk, hogy folyamatosan sikerül felderíteni és dokumentálni a Microsoft(R) értelmezõje által eltûrt szabványon kívüli viselkedést és leutánozni FreeBSD alatt is, hogy így ne kelljen a felhasználóknak kézzel a saját ASL forrásaikat javítgatni. Az ebbõl fakadó hibákat úgy tudjuk elkerülni és segíteni a fejlesztõknek azonosítani a hozzá társuló viselkedést, hogy magunk javítjuk az ASL-ben felfedezett hibákat. Ha ez beválik, akkor küldjük el a régi és új ASL közti man:diff[1]-et a fejlesztõknek, akik így majd az ACPI-CA-ban ki tudnak dolgozni egy megoldást a hibás viselkedésre, ezzel a javításunk szükségtelenné válik. Most pedig következzenek a legismertebb hibaüzenetek, az okaik és javításuk: ==== Operációs rendszeri függõségek Néhány AML úgy gondolja, hogy a világ csak a különbözõ Windows(R) verziókból áll. A FreeBSD-nek megadható, hogy másik operációs rendszernek adja ki magát, és ezzel talán meg is szüntethetõ pár hiba. Ezt a legegyszerûbb úgy tudjuk megtenni, ha a [.filename]#/boot/loader.conf# állományhoz hozzáfûzzük a `hw.acpi.osname="Windows 2001"` sort, vagy itt egy olyan karakterláncot adunk meg, amit az ASL forrásban láttunk. ==== Hiányzó visszatérési érték Bizonyos módszerek a szabvány szerint elvártaktól eltérõen nem adnak vissza explicit módon értéket. Mivel az ACPI-CA ezt nem kezeli le, ezért a FreeBSD részérõl tartalmaz egy olyan módosítást, amivel implicit módon is vissza lehet adni értéket. Ha biztosak akarunk lenni a visszaadni kívánt értékben, akkor helyezzünk el a megfelelõ helyekre explicit Return utasításokat. Az `iasl` a `-f` paraméterrel kényszeríthetõ az ilyen ASL források lefordítására. ==== Az alapértelmezett AML felülbírálása Miután módosítottuk a [.filename]#saját.asl# állományunkat, így tudjuk lefordítani: [source,shell] .... # iasl saját.asl .... Az `-f` kapcsoló megadásával kikényszeríthetjük az AML létrehozását még abban az esetben is, amikor hibákat tartalmaz. Ügyeljünk rá, hogy bizonyos hibákat (például a hiányzó visszatérési értékeket) a fordító magától kikerül. Az `iasl` alapértelmezett kimenete a [.filename]#DSDT.aml# állomány. A [.filename]#/boot/loader.conf# átírásával így tudjuk ezzel helyettesíteni a BIOS-unk hibás változatát (ami még mindig megtalálható a flash memóriában): [.programlisting] .... acpi_dsdt_load="YES" acpi_dsdt_name="/boot/DSDT.aml" .... Ehhez ne felejtsük el a saját [.filename]#DSDT.aml# állományunkat bemásolni a [.filename]#/boot# könyvtárba. [[ACPI-debugoutput]] === Nyomkövetési információk kinyerése az ACPI-bõl Az ACPI meghajtója nagyon rugalmas nyomkövetési lehetõségekkel rendelkezik. Ennek révén ugyanúgy megadhatjuk a nyomonkövetni kívánt alrendszert, mint ahogy annak mélységét is. A nyomkövetni kívánt alrendszereket "rétegekként" adjuk meg, valamint ezek ACPI-CA komponensekre (ACPI_ALL_COMPONENTS) és ACPI hardvertámogatásra (ACPI_ALL_DRIVERS) bomlanak le. A nyomkövetéskor keletkezõ kimenet részletességét a "szintként" adjuk meg, ami az ACPI_LV_ERROR-tól (csak a hibák) ACPI_LV_VERBOSE-ig (minden) terjedhet. A "szint" itt egy bitmaszk, ezért szóközzel elválasztva egyszerre több beállítás megadható. Ha túlságosan sok üzenet érkezik a konzol üzenetpufferébe, akkor szükségünk lehet a soros konzol keresztüli nyomkövetésre is. Az összes szint és réteg az man:acpi[4] man oldalon található meg. A nyomkövetés alapértelmezés szerint nem engedélyezett. Az engedélyezéséhez hozzá kell adnunk az `options ACPI_DEBUG` sort a rendszermagunk beállításait tartalmazó állományhoz, amennyiben a rendszermagba fordítjuk az ACPI támogatást. Ha az [.filename]#/etc/make.conf# állományba írjuk bele az `ACPI_DEBUG=1` sort, akkor azt globálisan engedélyezhetjük. Ha modulként használjuk, elegendõ csak a következõ módon újrafordítani az [.filename]#acpi.ko# modult: [source,shell] .... # cd /sys/modules/acpi/acpi && make clean && make ACPI_DEBUG=1 .... Telepítsük fel a [.filename]#acpi.ko# modult a [.filename]#/boot/kernel# könyvtárba és állítsuk be a számunkra megfelelõ szintet és réteget a [.filename]#loader.conf# állományban. Az alábbi példában engedélyezzük az összes ACPI-CA komponens és az összes ACPI hardvermeghajtó (processzor, LID stb.) nyomkövetését. Csak a hibaüzeneteket írja ki részletesen. [.programlisting] .... debug.acpi.layer="ACPI_ALL_COMPONENTS ACPI_ALL_DRIVERS" debug.acpi.level="ACPI_LV_ERROR" .... Ha az általunk keresett információt egy adott esemény váltja ki (például egy felfüggesztés vagy egy ébresztés), akkor nem is fontos átírnunk hozzá a [.filename]#loader.conf# állományt, hanem helyette a rendszer indítása után használjuk a `sysctl` parancsot a réteg és a szint megadására akkor, amikor a rendszert felkészítjük az eseményre. A `sysctl` változókat ugyanúgy nevezték el, mint a [.filename]#loader.conf# állományban található beállításokat. [[ACPI-References]] === Hivatkozások Az ACPI-rõl az alábbi helyeken találunk részletesebb információkat: * A {freebsd-acpi} * Az ACPI levelezési lista archívuma: http://lists.freebsd.org/pipermail/freebsd-acpi/[http://lists.freebsd.org/pipermail/freebsd-acpi/] * A korábbi ACPI levelezési lista archívuma: http://home.jp.FreeBSD.org/mail-list/acpi-jp/[http://home.jp.FreeBSD.org/mail-list/acpi-jp/] -* Az ACPI 2.0 specifikációja: http://acpi.info/spec.htm[http://acpi.info/spec.htm] +* Az https://uefi.org/specifications#ACPI[ACPI specifikációja] * A FreeBSD következõ man oldalai: man:acpi[4], man:acpi_thermal[4], man:acpidump[8], man:iasl[8], man:acpidb[8] * http://www.cpqlinux.com/acpi-howto.html#fix_broken_dsdt[ A DSDT nyomkövetése (angolul)]. (Példának a Compaqot hozza fel, de általánosságban véve hasznos.) diff --git a/documentation/content/it/books/handbook/config/_index.adoc b/documentation/content/it/books/handbook/config/_index.adoc index 5cc5f27092..3944b3599f 100644 --- a/documentation/content/it/books/handbook/config/_index.adoc +++ b/documentation/content/it/books/handbook/config/_index.adoc @@ -1,1366 +1,1366 @@ --- title: Capitolo 11. Configurazione e Messa a Punto part: Parte II. Compiti Ordinari prev: books/handbook/partiii next: books/handbook/boot showBookMenu: true weight: 15 path: "/books/handbook/" --- [[config-tuning]] = Configurazione e Messa a Punto :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 11 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/audit/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[config-synopsis]] == Sinossi Uno degli aspetti importanti di FreeBSD è la configurazione del sistema. Una corretta configurazione del sistema aiuterà a prevenire mal di testa durante futuri aggiornamenti. Questo capitolo spiegherà molti dei processi di configurazione di FreeBSD, inclusi alcuni parametri che possono essere impostati per ottimizzare un sistema FreeBSD. Dopo aver letto questo capitolo, saprai: * Come lavorare in maniera efficiente con i file system e le partizioni di swap. * Le basi dei sistemi di configurazione [.filename]#rc.conf# e di avvio [.filename]#/usr/local/etc/rc.d#. * Come configurare e provare una scheda di rete. * Come configurare host virtuali sui dispositivi di rete. * Come usare i vari file di configurazione in [.filename]#/etc#. * Come mettere a punto FreeBSD usando le variabili `sysctl`. * Come ottimizzare la prestazioni del disco e modificare le limitazioni del kernel. Prima di leggere questo capitolo, dovresti: * Comprendere le basi di UNIX(R) e di FreeBSD (crossref:basics[basics,Basi di UNIX]). * Avere dimestichezza nella configurazione/compilazione del kernel (crossref:kernelconfig[kernelconfig,Configurazione del Kernel di FreeBSD]). [[configtuning-initial]] == Configurazione Iniziale === Disposizione delle Partizioni ==== Partizioni di Base Nel disegnare il tuo file system con man:bsdlabel[8] o man:sysinstall[8], ricorda che i dischi rigidi possono trasferire dati ad un ritmo maggiore dalle tracce esterne rispetto a quelle interne. Quindi i file system più piccoli e con un gran numero di accessi dovrebbero essere più vicini alla parte esterna del disco, mentre le partizioni più ampie, come [.filename]#/usr#, dovrebbero essere posizionate verso l'interno. È una buona idea creare le partizioni in un ordine simile al seguente: root, swap, [.filename]#/var#, [.filename]#/usr#. Le dimensioni della partizione [.filename]#/var# riflettono l'uso che intendi fare della macchina. [.filename]#/var# viene usata per mantenere le caselle di posta, i file di log, e gli spool della stampante. Le caselle di posta e file di log potrebbero crescere in maniera imprevedibile in relazione al numero di utenti presenti sul tuo sistema e da quanto a lungo manterrai i file di log. La maggior parte degli utenti non avrà mai bisogno di un gigabyte, ma ricorda che [.filename]#/var/tmp# deve essere abbastanza ampia da contenere tutti i pacchetti. La partizione [.filename]#/usr# contiene molti dei file richiesti per far funzionare il sistema, la collezioni dei man:ports[7] (raccomandata) e il codice sorgente (opzionale). Entrambi sono opzionali al momento dell'installazione. Almeno 2 gigabyte sono raccomandati per questa partizione. Quando decidi le dimensioni delle partizioni, tieni a mente le richieste di spazio. Esaurire lo spazio in una partizione mentre ne usi poco in un'altra può essere molto fastidioso. [NOTE] ==== Alcuni utenti hanno scoperto che il dimensionamento `auto-predefinito` di man:sysinstall[8] a volte crea partizioni [.filename]#/var# o [.filename]#/# più piccole del necessario. Partiziona saggiamente e generosamente. ==== [[swap-design]] ==== Partizione di Swap Come regola generale, la partizione di swap dovrebbe essere tipicamente il doppio della quantità di memoria principale (RAM). Ad esempio, se la macchina avesse 128 megabyte di memoria, il file di swap dovrebbe essere di 256 megabyte. Sistemi con meno memoria potrebbero funzionare meglio con uno swap maggiore. Meno di 256 megabyte di swap non è raccomandato e dovresti pensare ad una espansione della memoria. Gli algoritmi di paginazione sono ottimizzati per funzionare al meglio quando la partizione di swap è almeno due volte la dimensione della memoria principale. Configurare uno swap troppo piccolo potrebbe portare ad una inefficienza nel codice di scansione della VM e potrebbe creare problemi in seguito, nel caso di aggiunta di memoria alla macchina. Su sistemi più grandi con dischi SCSI multipli (o dischi IDE multipli collegati a diversi controller) è consigliabile che ci sia uno swap per ogni disco (fino a quattro dischi). Le partizioni di swap dovrebbero avere approssimativamente le stesse dimensioni. Il kernel può gestire dimensioni arbitrarie ma internamente le strutture dati scalano meglio fino a quattro volte la dimensione della partizione di swap più ampia. Avere partizioni di swap con dimensioni simili permetterà al kernel di distribuire al meglio lo spazio di swap tra i dischi. Partizioni di swap grandi vanno bene, anche se non vengono usate molto. Potrebbe essere più semplice recuperare il sistema da un programma impazzito prima di essere costretti a riavviare. ==== Perchè Partizionare? Molti utenti pensano che un'unica grande partizione vada bene, ma ci sono molte ragioni per cui questa è una cattiva idea. Primo, ogni partizione ha differenti caratteristiche operative e separarle permette ai file system di ottimizzare se stessi di conseguenza. Ad esempio, le partizioni root e [.filename]#/usr# sono per lo più usate in lettura, senza molte operazioni di scrittura. Un sacco di letture e scritture potrebbero esserci in [.filename]#/var# e [.filename]#/var/tmp#. Partizionando in maniera appropriata il sistema, la frammentazione introdotta nelle partizioni più piccole, con più carico in scrittura, non inciderà sulle partizioni per lo più di lettura. Mantenere le partizioni con maggiore carico in scrittura vicine al bordo del disco aumenterà le prestazioni di I/O nelle partizioni dove ne hai più bisogno. Ora, sebbene potresti avere bisogno di prestazioni di I/O anche nelle partizioni più ampie, spostarle verso il bordo del disco non porterebbe nessun miglioramento significativo delle prestazioni, al contrario dello spostamento di [.filename]#/var# all'esterno. Infine, ci sono problemi riguardanti la sicurezza. Una piccola, simpatica partizione di root che è essenzialmente di sola lettura ha ottime possibilità di sopravvivere intatta a un brutto crash. [[configtuning-core-configuration]] == Configurazione Principale Il posto principale per le informazioni di configurazione del sistema è in [.filename]#/etc/rc.conf#. Questo file contiene un'ampia gamma di informazioni di configurazione, usate principalmente all'avvio della macchina per la configurazione del sistema. Il suo nome è autoesplicativo; si tratta di informazioni di configurazione per i file [.filename]#rc*#. Un amministratore dovrebbe aggiungere dei campi nel file [.filename]#rc.conf# per cambiare le impostazioni predefinite di [.filename]#/etc/defaults/rc.conf#. Il file predefinito non dovrebbe essere semplicemente copiato in [.filename]#/etc# - esso contiene valori di default, non esempi. Tutti i cambiamenti specifici del sistema dovrebbero essere effettuati nel file [.filename]#rc.conf# stesso. Nelle applicazioni cluster possono essere adottate differenti strategie per separare le configurazioni generali da quelle specifiche del sistema in maniera da mantenere basso l'impegno di amministrazione. L'approccio raccomandato è di porre le configurazioni generali in un altro file, ad esempio [.filename]#/etc/rc.conf.site#, e poi includerlo in [.filename]#/etc/rc.conf#, che conterrà solo le informazioni specifiche del sistema. Visto che [.filename]#rc.conf# viene letto da man:sh[1] è semplice farlo. Ad esempio: * rc.conf: + [.programlisting] .... . /etc/rc.conf.site hostname="node15.example.com" network_interfaces="fxp0 lo0" ifconfig_fxp0="inet 10.1.1.1" .... * rc.conf.site: + [.programlisting] .... defaultrouter="10.1.1.254" saver="daemon" blanktime="100" .... Il file [.filename]#rc.conf.site# potrà poi essere distribuito su ogni sistema usando `rsync` o un programma simile, mentre il file [.filename]#rc.conf# rimarrà unico. L'aggiornamento del sistema tramite man:sysinstall[8] o `make world` non sovrascriverà il file [.filename]#rc.conf#, quindi le configurazioni del sistema non andranno perse. [[configtuning-appconfig]] == Configurazione delle Applicazioni Tipicamente, le applicazioni installate hanno i propri file di configurazione, con la loro sintassi, ecc. È importante che questi file siano tenuti separati dal sistema di base, in maniera da essere facilmente individuati e gestiti dagli strumenti di gestione dei pacchetti. In genere, questi file vengono installati in [.filename]#/usr/local/etc#. Nel caso in cui un'applicazione abbia un grande numero di file di configurazione, verrà creata una sottodirectory per contenerli. Normalmente, quando viene installato un pacchetto, vengono installati anche file di configurazione d'esempio. In genere questi vengono identificati da un suffisso [.filename]#.default#. Se non ci sono file di configurazione esistenti per l'applicazione, verranno creati copiando i file [.filename]#.default#. Ad esempio, considera il contenuto della directory [.filename]#/usr/local/etc/apache#: .... -rw-r--r-- 1 root wheel 2184 May 20 1998 access.conf -rw-r--r-- 1 root wheel 2184 May 20 1998 access.conf.default -rw-r--r-- 1 root wheel 9555 May 20 1998 httpd.conf -rw-r--r-- 1 root wheel 9555 May 20 1998 httpd.conf.default -rw-r--r-- 1 root wheel 12205 May 20 1998 magic -rw-r--r-- 1 root wheel 12205 May 20 1998 magic.default -rw-r--r-- 1 root wheel 2700 May 20 1998 mime.types -rw-r--r-- 1 root wheel 2700 May 20 1998 mime.types.default -rw-r--r-- 1 root wheel 7980 May 20 1998 srm.conf -rw-r--r-- 1 root wheel 7933 May 20 1998 srm.conf.default .... Le differenze nelle dimensioni dei file mostrano che solo [.filename]#srm.conf# è stato modificato. Una successiva installazione di Apache dai port non sovrascriverà questo file modificato. [[configtuning-starting-services]] == Avvio dei Servizi Molti utenti scelgono di installare software di terze parti in FreeBSD attraverso la collezione dei port. Nell magior parte dei casi potrebbe essere necessario configurare il software in un modo tale che sia avviato all'inizializzazione di sistema. Servizi, come package:mail/postfix[] o package:www/apache13[] sono solo due fra i molti pacchetti software che possono essere avviati durante l'inizializzazione di sistema. Questa sezione spiega le procedure disponibili per avviare software di terze parti. In FreeBSD, molti servizi inclusi, come man:cron[8], sono avviati attraverso gli script di startup. Questi script possono differire a seconda della verione di FreeBSD o del produttore; comunque il più importante aspetto da considerare è che la configurazione di startup può essere gestita tramite semplici script di inizializzazione. Prima dell'avvento di [.filename]#rc.d#, gli applicativi lasciavano un semplice script di avvio nella directory [.filename]#/usr/local/etc/rc.d# che sarebbe stato poi letto dagli script di inizializzazione di sistema. Questi script sarebbero poi eseguiti durante la fase di avvio del sistema. Mentre molti individui hanno speso ore cercando di integrare il vecchio stile di configurazione nel nuovo sistema, resta il fatto che qualche utility di terze parti necessita ancora di uno script semplicemente lasciato nella succitata directory. Le sottili differenze negli script dipendono dal fatto se [.filename]#rc.d# sia usato o meno. Prima di FreeBSD 5.1 viene usato il vecchio metodo di configurazione ed in quasi tutti i casi uno script di nuovo tipo funzionerebbe perfettamente. Mentre ogni script deve rispettare alcuni requisiti minimi, il più delle volte questi requisiti sono indipendenti dalla versioni di FreeBSD. Ogni script deve avere una estensione [.filename]#.sh# appesa alla fine ed ogni script deve essere eseguibile dal sistema. L'ultima richiesta può essere soddisfatta usando il comando `chmod` e impostando i permessi a `755`. Ci dovrebbe essere, come minimo, un'opzione per fare lo `start` dell'applicativo ed un'opzione per farne lo `stop`. Il più semplice script di avvio probabilmente sembrerebbe simile al seguente: [.programlisting] .... #!/bin/sh echo -n ' utility' case "$1" in start) /usr/local/bin/utility ;; stop) kill -9 `cat /var/run/utility.pid` ;; *) echo "Usage: `basename $0` {start|stop}" >&2 exit 64 ;; esac exit 0 .... Questo script fornisce un'opzione `stop` e `start` per l'applicazione a cui ci riferiamo semplicemente come `utility`. Potrebbe essere avviata manualmente con: [source,shell] .... # /usr/local/etc/rc.d/utility.sh start .... Mentre non tutto il software di terze parti richiede la linea in [.filename]#rc.conf#, quasi ogni giorno un nuovo port viene modificato per accettare questa configurazione. Controlla l'output finale dell'installazione per maggiori informazioni su un applicativo specifico. Ci sarà del software di terze parti che fornisce script di avvio che permettono all'applicativo di essere usato con [.filename]#rc.d#; tuttavia, questo sarà discusso nella successiva sezione. === Configurazione Estesa degli Applicativi Ora che FreeBSD include [.filename]#rc.d#, la configurazione dell'avvio degli applicativi è diventata più semplice, e più flessibile. Usando le parole chiave discusse nella sezione <>, gli applicativi ora possono essere configurati dopo certi altri servizi come ad esempio il DNS; possono permettere che siano passati flag extra nel codice attraverso [.filename]#rc.conf# al posto di flag statici negli script di avvio, e molto altro. Uno script basilare potrebbe assomigliare al seguente: [.programlisting] .... #!/bin/sh # # PROVIDE: utility # REQUIRE: DAEMON # KEYWORD: shutdown . /etc/rc.subr name=utility rcvar=utility_enable command="/usr/local/sbin/utility" load_rc_config $name # # DO NOT CHANGE THESE DEFAULT VALUES HERE # SET THEM IN THE /etc/rc.conf FILE # utility_enable=${utility_enable-"NO"} pidfile=${utility_pidfile-"/var/run/utility.pid"} run_rc_command "$1" .... Questo script assicurerà che utility partirà dopo il servizio `daemon`. Fornisce inoltre un metodo per settare e tracciare il PID, o il file dell'ID di processo. Questa applicazione potrebbe avere le seguenti linee piazzate in [.filename]#/etc/rc.conf#: [.programlisting] .... utility_enable="YES" .... Questo metodo permette inoltre una semplice manipolazione degli argomenti di linea di comando, incluse le funzioni di default definite in [.filename]#/etc/rc.subr#, compatibilità con l'utility man:rcorder[8] e fornisce una più semplice configurazione attraverso il file [.filename]#rc.conf#. === Usare i Servizi per Avviare i Servizi Altri servizi, come i demoni POP3, IMAP, etc. potrebbero essere avviati usando man:inetd[8]. Questo implica l'installazione del servizio dalla collezione dei port e l'aggiunta di una linea di configurazione al file [.filename]#/etc/inetd.conf# o togliendo dei commenti in una delle linee di configurazione del file stesso. L'uso di inetd e la sua configurazione è descritto in dettaglio nella sezione crossref:network-servers[network-inetd,inetd]. In alcuni casi, potrebbe essere più plausibile usare il demone man:cron[8] per avviare i servizi di sistema. Questo approccio ha alcuni vantaggi poichè `cron` esegue questi processi come l'utente proprietario del file [.filename]#crontab#. Questo permette ad utenti regolari di avviare e mantenere alcuni applicativi. Il comando `cron` fornisce una caratteristica unica, `@reboot`, che potrebbe essere usato al posto della specifica del tempo. Questo farà sì che il job sia eseguito quando man:cron[8] è avviato, normalmente durante l'inizializzazione di sistema. [[configtuning-cron]] == Configurare l'Utility `cron` Uno dei comandi più utili presenti in FreeBSD è man:cron[8]. L'utility `cron` viene eseguita in background e controlla costantemente il file [.filename]#/etc/crontab#. `cron` controlla anche la directory [.filename]#/var/cron/tabs#, alla ricerca di nuovi file [.filename]#crontab#. Questi file [.filename]#crontab# contengono informazioni sulle specifiche funzioni che ci si aspetta vengano compiute da `cron` a determinati intervalli temporali. L'utility `cron` usa due differenti tipi di file di configurazione, il crontab di sistema ed il crontab utente. La sola differenza fra questi due file è nel sesto campo. Nel crontab di sistema, il sesto campo è il nome dell'utente sotto il quale viene eseguito il comando. Questo dà al crontab di sistema la capacità di eseguire comandi come ogni utente. Nel crontab utente, il sesto campo è il comando da eseguire, e tutti i comandi vengono eseguiti come l'utente che ha creato il crontab; questa è un'importante caratteristica di sicurezza. [NOTE] ==== I crontab utenti permettono ad utenti individuali di schedulare task senza i privilegi di `root`. I comandi in un crontab utente vengono eseguiti con i permessi dell'utente che posseggono il file crontab. L'utente `root` può possedere il crontab proprio come ogni altro utente. Qui c'è una differenza rispetto a [.filename]#/etc/crontab# (il crontab di sistema). Per via del crontab di sistema, di solito non c'è bisogno di creare un crontab per `root`. ==== Diamo un'occhiata al file [.filename]#/etc/crontab# (il crontab di sistema): [.programlisting] .... # /etc/crontab - il crontab di root per FreeBSD # # $FreeBSD: src/etc/crontab,v 1.32 2002/11/22 16:13:39 tom Exp $ ## <.> # SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin <.> HOME=/var/log # # #minute hour mday month wday who command <.> # # */5 * * * * root /usr/libexec/atrun <.> .... <.> Come in molti file di configurazione di FreeBSD, il carattere `#` rappresenta un commento. Un commento può essere posto nel file come una nota su cosa si desidera fare con un certo comando. I commenti non possono essere nella stessa linea di un comando o saranno interpretati come parte di un comando; devono trovarsi su una linea a sè. Le linee vuote vengono ignorate. <.> Anzitutto, deve essere definito l'ambiente. I segni di uguale (`=`) vengono usati per definire ogni impostazione dell'ambiente, come viene fatto in questo esempio per `SHELL`, `PATH`, e `HOME`. Se la linea relativa alla shell viene omessa, `cron` userà quella di default, che è `sh`. Se si omette la variabile `PATH`, non verrà usato nessun default e le locazioni dei file dovranno essere assolute. Se viene omessa `HOME`, `cron` userà la home directory dello user che lo ha richiamato. <.> Questa linea definisce un totale di sette campi. Qui sono elencati i valori `minute`, `hour`, `mday`, `month`, `wday`, `who`, e `command`. Questi nomi sono più o meno autoesplicativi. `minute` è il tempo in minuti al quale dovrà essere eseguito il comando. `hour` è uguale, ma per le ore. `mday` rappresenta il giorno del mese. `month` è simile ad `hour` e `minute`, ma rappresenta il mese. L'opzione `wday` rappresenta il giorno della settimana. Tutti questi campi devono avere un valore numerico, e seguire l'orario di ventiquattro ore. Il campo `who` è speciale, ed esiste solo nel file [.filename]#/etc/crontab#. Questo campo specifica l'utente con il quale deve essere eseguito il comando. Quando un utente installa il suo file [.filename]#crontab#, non avrà a disposizione questa opzione. Infine, viene elencata l'opzione `command`. Questo è l'ultimo campo, e naturalmente indica il comando che deve essere eseguito. <.> Quest'ultima linea definirà i valori discussi prima. Notate che abbiamo un `*/5`, seguito da parecchi caratteri `*`. Questi caratteri `*` significano "dalla prima all'ultima volta", e possono essere interpretati come _ogni_ volta. Dunque, basandosi su questa linea, sembra che il comando `atrun` debba essere invocato da `root` ogni cinque minuti, prescindendo da quale giorno o mese sia. Per maggiori informazioni sul comando `atrun`, vedere la pagina di manuale man:atrun[8].I comandi possono essere richiamati con qualsiasi numero di flag; i comandi che si estendono per più righe potrebbero però avere bisogno di essere spezzati con il carattere di continuazione "\". Questa è l'impostazione di base per ogni file [.filename]#crontab#, anche se c'è qualcosa di particolare in questo. Il sesto campo, dove abbiamo specificato il nome utente, esiste solo nel file di sistema [.filename]#/etc/crontab#. Questo campo dovrebbe venire omesso nei [.filename]#crontab# dei vari utenti. [[configtuning-installcrontab]] === Installare un Crontab [IMPORTANT] ==== Non devi usare la procedura descritta qui per editare/installare il crontab di sistema. Semplicemente usa il tuo editor favorito: l'utility `cron` noterà che il file è cambiato e immediatamente inizierà ad usare la versione aggiornata. Vedi extref:{faq}[queste FAQ, ROOT-NOT-FOUND-CRON-ERRORS] per maggiori informazioni. ==== Per installare un [.filename]#crontab# appena scritto, prima usa il tuo editor preferito per creare un file nel formato corretto, e poi usa l'utility `crontab`. L'uso più corretto è: [source,shell] .... % crontab crontab-file .... In questo esempio, [.filename]#crontab-file# è il nome di un file [.filename]#crontab# che era stato creato in precedenza. C'è anche un'opzione per elencare i file [.filename]#crontab# già installati: passate semplicemente `-l` a `crontab` e date un'occhiata all'output. Per gli utenti che desiderino scrivere il proprio file crontab da zero, senza usare un template, è disponibile `crontab -e`. Questa opzione permetterà loro di invocare l'editor prescelto su un file vuoto. Quando il file verrà salvato, esso verrà automaticamente installato dal comando `crontab`. Se successivamente vuoi rimuovere il tuo [.filename]#crontab# completamente, usa `crontab` con l'opzione `-r`. [[configtuning-rcd]] == Usare rc con FreeBSD Nel 2002 FreeBSD ha integrato il sistema di inizializzazione [.filename]#rc.d# di NetBSD. Gli utenti dovrebbero aver notato i file elencati nella cartella [.filename]#/etc/rc.d#. Molti di questi file sono servizi di base che possono essere controllati con opzioni `start`, `stop`, e `restart`. Ad esempio, man:sshd[8] può essere riavviato con il comando seguente: [source,shell] .... # /etc/rc.d/sshd restart .... Questa procedura è simile a quella per altri servizi. Naturalmente, i servizi in genere vengono avviati automaticamente in fase di avvio secondo quanto specificato in man:rc.conf[5]. Ad esempio, per abilitare il demone per il NAT (Network Address Translation) all'avvio basta aggiungere la linea seguente a [.filename]#/etc/rc.conf#: [.programlisting] .... natd_enable="YES" .... Se esiste già una linea `natd_enable="NO"`, allora basta cambiare il valore da `NO` a `YES`. Gli script rc caricheranno automaticamente ogni altro servizio durante il riavvio seguente, come descritto più avanti. Poichè il sistema di [.filename]#rc.d# è inteso prevalentemente per avviare/bloccare i servizi al momento dell'accensione/spegnimento, le opzioni standard `start`, `stop` e `restart` avranno il comportamento appropriato solo seè stata impostata la variabile appropriata in [.filename]#/etc/rc.conf#. Ad esempio il comando precedente `sshd restart` funzionerà solo se in [.filename]#/etc/rc.conf# è stata impostata l'opzione `sshd_enable` a `YES`. Per avviare (`start`), fermare (`stop`) o riavviare (`restart`) un servizio, ignorandole impostazioni in [.filename]#/etc/rc.conf#, i comandi devono avere il prefisso "one". Ad esempio per riavviare `sshd` trascurando le impostazioni esistenti in [.filename]#/etc/rc.conf#, impartite il comando seguente: [source,shell] .... # /etc/rc.d/sshd onerestart .... È semplice controllare se un servizio è stato abilitato in [.filename]#/etc/rc.conf# eseguendo lo script appropriato in [.filename]#rc.d# con l'opzione `rcvar`. Dunque, un amministratore può controllare che `sshd` sia effettivamente abilitato in [.filename]#/etc/rc.conf# eseguendo: [source,shell] .... # /etc/rc.d/sshd rcvar # sshd $sshd_enable=YES .... [NOTE] ==== La seconda linea (`# sshd`) è l'output del comando `sshd`; non una console di `root`. ==== Per determinare se un servizio è attivo, è disponibile l'opzione `status`. Ad esempio per verificare che `sshd` sia effettivamente avviato: [source,shell] .... # /etc/rc.d/sshd status sshd is running as pid 433. .... In alcuni case è anche possibile effettuare il `reload` di un servizio. Questo tenterà di inviare un segnale al servizio, per fargli ricaricare il suo file di configurazione. Nella maggior parte dei casi si tratterà del segnale `SIGHUP`. Il supporto per questa caratteristica non è garantito per tutti i servizi. La struttura di [.filename]#rc.d# non viene usata solo per i servizi di rete, ma contribuisce anche per buona parte all'inizializzazione del sistema. Ad esempio, considerate il file [.filename]#bgfsck#. Quando lo script viene eseguito, esso stamperà il seguente messaggio: [source,shell] .... Starting background file system checks in 60 seconds. .... Dunque questo file viene usato per il controllo del file system in background, che avviene solo durante l'inizializzazione del sistema. Molti servizi di sistema dipendono da altri servizi per poter funzionare in maniera appropriata. Ad esempio, il NIS ed altri servizi basati sulle RPC potrebbero non funzionare in assenza di `rpcbind` (portmapper). Per risolvere il problema, nei commenti all'inizio di ogni script di avvio ci sono informazioni sulle dipendenze ed altri metadati. Il programma man:rcorder[8] viene poi utilizzato per effettuare il parsing di questi commenti durante l'inizializzazione di sistema e per determinare l'ordine con il quale questi servizi devono essere avviati per avere le proprie dipendenze soddisfatte. In cima ad ogni file di avvio possono essere incluse le seguenti parole: * PROVIDE: Specifica i servizi forniti dal file. * REQUIRE: Elenca i servizi richiesti per far funzionare correttamente questo servizio. Questo file verrà eseguito _dopo_ i tali servizi. * BEFORE: Elenca i servizi che dipendono da questo. Questo file verrà lanciato _prima_ dei servizi specificati. Usando questo metodo, un amministratore può controllare facilmente i servizi di sistema senza il fastidio dei "runlevel" come alcuni altri sistemi operativi UNIX(R). Informazioni addizionali sul sistema [.filename]#rc.d# possono essere trovate nelle pagine man di man:rc[8] e man:rc.subr[8]. Se sei interessato a scrivere un tuo script [.filename]#rc.d# o a migliorarne uno esisente, ti può essere utile extref:{rc-scripting}[questo articolo]. [[config-network-setup]] == Configurazione delle Interfacce di Rete Al giorno d'oggi non riusciamo a pensare ad un computer senza pensare ad una connessione di rete. Aggiungere e configurare una scheda di rete è un compito comune per ogni amministratore di FreeBSD. === Individuazione del Driver Corretto Prima di cominciare, dovresti conoscere il modello della scheda di rete che possiedi, il chip che usa, e se si tratta di una scheda PCI o ISA. FreeBSD supporta un'ampia varietà sia di schede PCI che ISA. Verifica l'Hardware Compatibility List della tua release per vedere se la scheda è supportata. Una volta sicuro che la tua scheda sia supportata, hai bisogno di determinare il driver appropriato per la scheda. I file [.filename]#/usr/src/conf/NOTES# e [.filename]#/usr/src/sys/arch/conf/NOTES# ti forniranno un elenco di driver per le interfacce di rete con alcune informazioni su chipset/schede supportate. Se hai dubbi su quale sia il driver corretto, leggi la pagina man del driver. La pagina man fornirà ulteriori informazioni sull'hardware supportato ed anche sui possibili problemi che potrebbero capitare. Se sei in possesso di una scheda comune, la maggior parte delle volte non dovrai cercare molto per trovare un driver. I driver per le schede di reti comuni sono presenti nel kernel [.filename]#GENERIC#, quindi la tua scheda dovrebbe presentarsi durante l'avvio, in questo modo: [source,shell] .... dc0: <82c169 PNIC 10/100BaseTX> port 0xa000-0xa0ff mem 0xd3800000-0xd38 000ff irq 15 at device 11.0 on pci0 dc0: Ethernet address: 00:a0:cc:da:da:da miibus0: on dc0 ukphy0: on miibus0 ukphy0: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc1: <82c169 PNIC 10/100BaseTX> port 0x9800-0x98ff mem 0xd3000000-0xd30 000ff irq 11 at device 12.0 on pci0 dc1: Ethernet address: 00:a0:cc:da:da:db miibus1: on dc1 ukphy1: on miibus1 ukphy1: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto .... In questo esempio, vediamo che nel sistema sono presenti due schede che usano il driver man:dc[4]. Se il driver per la tua NIC non è presente in [.filename]#GENERIC#, dovrai caricare i driver appropriati per usare la tua NIC. Questo dovrà essere fatto in uno di questi due modi: * Il modo più semplice è caricare un modulo del kernel con man:kldload[8] o caricarlo automaticamente al momento del boot aggiungendo le linee appropriate a [.filename]#/boot/loader.conf#. Non tutti i driver NIC sono disponibili come moduli; esempi notevoli di driver per i quali non esistono moduli sono schede ISA. * Alternativamente, puoi compilare staticamente il supporto per la tua scheda nel kernel. Controlla [.filename]#/usr/src/sys/conf/NOTES#, [.filename]#/usr/src/sys/arch/conf/NOTES# e la pagina di manuale del driver per sapere cosa aggiungere nel tuo file di configurazione del kernel. Per maggiori informazioni sul modo di ricompilare il kernel, per favore consulta il crossref:kernelconfig[kernelconfig,Configurazione del Kernel di FreeBSD]. Se la tua scheda era riconosciuta al boot dal tuo kernel ([.filename]#GENERIC#) non devi ricompilare un nuovo kernel. [[config-network-ndis]] ==== Usare driver NDIS Windows(R) Sfortunatamente, ci sono ancora molti venditori di hardware che non forniscono specifiche dei loro driver alla comunità open source perchè ritengono che tale informazione sia un segreto commerciale. Conseguentemente, gli sviluppatori di FreeBSD e di altri sistemi operativi hanno due scelte: sviluppare i driver con un lungo ed arduo processo di reverse engineering o usare i driver binari disponibili per le piattaforme Microsoft(R) Windows(R). La maggior parte degli sviluppatori, inclusi quelli coinvolti in FreeBSD, ha preso la seconda strada. Grazie al contributo di Bill Paul (wpaul), a partire da FreeBSD 5.3-RELEASE c'è supporto "nativo" per Network Driver Interface Specification (NDIS). Il NDISulator di FreeBSD (anche noto come Progetto Evil) prende un driver binario per Windows(R) e sostanzialmente crea un inganno fingendo di eseguirlo in Windows(R). Poichè il driver man:ndis[4] sta usando un binario Windows(R), è usabile solo su sistemi i386(TM) e amd64. [NOTE] ==== Il driver man:ndis[4] è designato per supportare principalmente device PCI, CardBus e PCMCIA, i device USB non sono ancora supportati. ==== Per usare il NDISulator, hai bisogno sostanzialmente di tre cose: . Sorgenti del kernel . binari dei driver di Windows(R) XP (estensione [.filename]#.SYS#) . file di configurazione dei driver per Windows(R) XP (estensione [.filename]#.INF#) Localizza i file per la tua carta specifica. Generalmente, posso essere trovati nel CD incluso o sui siti web dei venditori. Nei seguenti esempi, useremo [.filename]#W32DRIVER.SYS# e [.filename]#W32DRIVER.INF#. [NOTE] ==== Non puoi usare un driver Windows(R)/i386 con FreeBSD/amd64, devi trovare un driver Windows(R)/amd64 per farlo funzionare correttamente. ==== Il prossimo passo è compilare il binario del driver in un modulo caricabile dal kernel. Per fare questo, come `root`, usa man:ndisgen[8]: [source,shell] .... # ndisgen /path/to/W32DRIVER.INF /path/to/W32DRIVER.SYS .... L'utility man:ndisgen[8] è interattiva e chiederà altre informazioni di cui necessita; produrrà un modulo del kernel nella presente directory che può essere caricato in questo modo: [source,shell] .... # kldload ./W32DRIVER.ko .... In aggiunta al modulo del kernel generato, devi caricare i moduli [.filename]#ndis.ko# e [.filename]#if_ndis.ko#. Questo dovrebbe avvenire automaticamente quando uno carica un modulo che dipende da man:ndis[4]. Se vuoi caricarli manualmente, usa il seguente comando: [source,shell] .... # kldload ndis # kldload if_ndis .... Il primo comando carica il wrapper del driver miniport NDIS, il secondo carica l'interfaccia di rete in questione. Ora controlla man:dmesg[8] per vedere se c'era qualche errore durante il caricamento. Se tutto è andato bene, dovresti ottenere dell'output che somiglia a questo: [source,shell] .... ndis0: mem 0xf4100000-0xf4101fff irq 3 at device 8.0 on pci1 ndis0: NDIS API version: 5.0 ndis0: Ethernet address: 0a:b1:2c:d3:4e:f5 ndis0: 11b rates: 1Mbps 2Mbps 5.5Mbps 11Mbps ndis0: 11g rates: 6Mbps 9Mbps 12Mbps 18Mbps 36Mbps 48Mbps 54Mbps .... D'ora in poi, puoi trattare il device [.filename]#ndis0# come ogni altra scheda di rete (ad esempio [.filename]#dc0#). Puoi configurare il sistema perché carichi il modulo NDIS al momento del boot nello stesso modo di ogni altro modulo. Per prima cosa, copia il modulo generato [.filename]#W32DRIVER.ko#, nella directory [.filename]#/boot/modules#. Quindi, aggiungi le seguenti linee a [.filename]#/boot/loader.conf#: [.programlisting] .... W32DRIVER_load="YES" .... === Configurazione della Scheda di Rete Una volta che il driver giusto per la scheda di rete è stato caricato, la scheda ha bisogno di essere configurata. Come molte altre cose, la scheda di rete potrebbe essere già stata configurata al momento dell'installazione tramite sysinstall. Per mostrare la configurazione delle interfacce di rete sul tuo sistema, immetti il seguente comando: [source,shell] .... % ifconfig dc0: flags=8843 mtu 1500 inet 192.168.1.3 netmask 0xffffff00 broadcast 192.168.1.255 ether 00:a0:cc:da:da:da media: Ethernet autoselect (100baseTX ) status: active dc1: flags=8843 mtu 1500 inet 10.0.0.1 netmask 0xffffff00 broadcast 10.0.0.255 ether 00:a0:cc:da:da:db media: Ethernet 10baseT/UTP status: no carrier lp0: flags=8810 mtu 1500 lo0: flags=8049 mtu 16384 inet 127.0.0.1 netmask 0xff000000 tun0: flags=8010 mtu 1500 .... [NOTE] ==== Vecchie versioni di FreeBSD potrebbero richiedere l'opzione `-a` dopo man:ifconfig[8], per maggiori dettagli sulla sintassi corretta di man:ifconfig[8], fai riferimento alla pagina man. Nota anche che le voci relative all'IPv6 (`inet6` ecc.) sono state omesse in questo esempio. ==== In questo esempio, vengono mostrati i seguenti dispositivi: * [.filename]#dc0#: La prima interfaccia Ethernet * [.filename]#dc1#: La seconda interfaccia Ethernet * [.filename]#lp0#: L'interfaccia della porta parallela * [.filename]#lo0#: Il dispositivo di loopback * [.filename]#tun0#: Il dispositivo tunnel usato da ppp FreeBSD usa il nome del driver seguito dall'ordine nel quale la scheda è stata rilevata all'avvio del kernel per dare un nome alla scheda di rete. Ad esempio [.filename]#sis2# sarebbe la terza scheda di rete nel sistema che usa il driver man:sis[4]. In questo esempio, il dispositivo [.filename]#dc0# è attivo. Gli indicatori chiave sono: . `UP` significa che la scheda è pronta e configurata. . La scheda ha un indirizzo Internet (`inet`) (in questo caso `192.168.1.3`). . Ha una maschera di sotto-rete valida (`netmask`; `0xffffff00` è lo stesso di `255.255.255.0`). . Ha un indirizzo di broadcast valido (in questo caso, `192.168.1.255`). . L'indirizzo MAC della scheda (`ether`) è `00:a0:cc:da:da:da`. . La selezione del mezzo fisico è in modalità auto selezione (`media: Ethernet autoselect (100baseTX )`). Vediamo che [.filename]#dc1# è stata configurata con un mezzo fisico `10baseT/UTP`. Per ulteriori informazioni sui tipi di mezzi disponibili per un driver, fai riferimento alla sua pagina man. . Lo stato del collegamento (`status`) è `active`, ovvero è stata rilevata la portante. Per [.filename]#dc1#, vediamo `status: no carrier`. Questo è normale quando un cavo Ethernet non è stato inserito nella scheda. Se l'output di man:ifconfig[8] avesse mostrato qualcosa di simile a: [source,shell] .... dc0: flags=8843 mtu 1500 ether 00:a0:cc:da:da:da .... ciò avrebbe indicato che la scheda non era stata ben configurata. Per configurare la tua scheda, avrai bisogno dei privilegi di `root`. La configurazione della scheda di rete può essere effettuata da riga di comando con man:ifconfig[8], ma avresti bisogno di farlo ad ogni riavvio del sistema. Il file [.filename]#/etc/rc.conf# è il posto giusto dove scrivere la configurazione della scheda di rete. Apri [.filename]#/etc/rc.conf# con il tuo editor preferito. Avrai bisogno di aggiungere una riga per ogni scheda di rete presente nel sistema, ad esempio nel nostro caso, abbiamo aggiunto queste linee: [.programlisting] .... ifconfig_dc0="inet 192.168.1.3 netmask 255.255.255.0" ifconfig_dc1="inet 10.0.0.1 netmask 255.255.255.0 media 10baseT/UTP" .... Dovrai sostituire [.filename]#dc0#, [.filename]#dc1#, e così via, con i dispositivi corretti per la tua scheda, e gli indirizzi con quelli appropriati. Dovresti leggere le pagine man del driver e di man:ifconfig[8] per maggiori dettagli sulle opzioni permesse ed anche la pagina man di man:rc.conf[5] per maggiori informazioni sulla sintassi di [.filename]#/etc/rc.conf#. Se hai configurato la rete durante l'installazione, alcune linee relative alle schede di rete potrebbero essere già presenti. Controlla due volte [.filename]#/etc/rc.conf# prima di aggiungere ogni linea. Avrai anche bisogno di modificare il file [.filename]#/etc/hosts# per aggiungere i nomi e gli IP delle varie macchine della LAN, se non sono già lì. Per maggiori informazioni, fai riferimento a man:hosts[5] ed a [.filename]#/usr/shared/examples/etc/hosts#. === Verifica e Risoluzione dei Problemi Una volta che hai effettuato i cambiamenti necessari a [.filename]#/etc/rc.conf#, dovresti riavviare la macchina. Ciò farà sì che i cambiamenti alle interfacce vengano applicati, e verificherà che il sistema si riavvii senza nessun errore di configurazione. Una volta che il sistema è stato riavviato, dovresti testare le interfacce di rete. ==== Test della Scheda Ethernet Per verificare che una scheda Ethernet sia configurata correttamente, si devono provare due cose. Prima, effettuare un ping verso l'interfaccia stessa, e poi un ping verso un'altra macchina sulla LAN. Prima proviamo l'interfaccia: [source,shell] .... % ping -c5 192.168.1.3 PING 192.168.1.3 (192.168.1.3): 56 data bytes 64 bytes from 192.168.1.3: icmp_seq=0 ttl=64 time=0.082 ms 64 bytes from 192.168.1.3: icmp_seq=1 ttl=64 time=0.074 ms 64 bytes from 192.168.1.3: icmp_seq=2 ttl=64 time=0.076 ms 64 bytes from 192.168.1.3: icmp_seq=3 ttl=64 time=0.108 ms 64 bytes from 192.168.1.3: icmp_seq=4 ttl=64 time=0.076 ms --- 192.168.1.3 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.074/0.083/0.108/0.013 ms .... Ora dobbiamo effettuare un ping verso un'altra macchina della LAN: [source,shell] .... % ping -c5 192.168.1.2 PING 192.168.1.2 (192.168.1.2): 56 data bytes 64 bytes from 192.168.1.2: icmp_seq=0 ttl=64 time=0.726 ms 64 bytes from 192.168.1.2: icmp_seq=1 ttl=64 time=0.766 ms 64 bytes from 192.168.1.2: icmp_seq=2 ttl=64 time=0.700 ms 64 bytes from 192.168.1.2: icmp_seq=3 ttl=64 time=0.747 ms 64 bytes from 192.168.1.2: icmp_seq=4 ttl=64 time=0.704 ms --- 192.168.1.2 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.700/0.729/0.766/0.025 ms .... Puoi usare il nome della macchina invece di `192.168.1.2` se hai sistemato il file [.filename]#/etc/hosts#. ==== Risoluzione dei Problemi Risolvere i problemi delle varie configurazioni hardware e software è sempre una faticaccia, ma è una fatica che può essere diminuita controllando da subito le cose semplici. Avete collegato il cavo di rete? Avete configurato i servizi di rete? Avete configurato il firewall correttamente? La scheda di rete che state usando è supportata da FreeBSD? Controllate sempre le note sul vostro hardware prima di inviare un bug report. Aggiornate la vostra versione di FreeBSD all'ultima versione STABLE disponibile. Controllate gli archivi delle mailing list, o magari cercate su Internet. Se la scheda funziona, ma le prestazioni sono scadenti, potrebbe esservi utile la lettura della pagina man man:tuning[7]. Potreste anche verificare la vostra configurazione della rete, poichè una configurazione scorretta può essere la causa di connessioni lente. Alcuni utenti riscontrano dei `device timeouts`, il che è normale per alcune schede. Se questi continuano, o se sono fastidiosi, potreste voler ricontrollare che non ci siano conflitti con altri dispositivi. Controllate due volte la connessione di rete. Forse dovreste procurarvi un'altra scheda. Alcune volte, gli utenti notano alcuni errori `watchdog timeout`. La prima cosa da fare è controllare il cavo di rete. Alcune schede di rete richiedono uno slot PCI che supporti il Bus Mastering. Su alcune vecchie schede madri, ciò è permesso solo per uno slot PCI (tipicamente lo slot 0). Controllate la documentazione della scheda di rete e della scheda madre per determinare se possa essere quello il problema. Messaggi `No route to host` vengono generati se il sistema non è in grado di effettuare il routing di un pacchetto verso una certa destinazione. Ciò può accadere se non è specificata una route di default, o se il cavo è scollegato. Controllate l'output di `netstat -rn` ed assicuratevi che ci sia una route valida per l'host che state cercando di raggiungere. Se non c'è, leggete il crossref:advanced-networking[advanced-networking,Networking Avanzato]. I messaggi d'errore `ping: sendto: Permission denied` sono spessi causati da un firewall mal configurato. Se `ipfw` è abilitato nel kernel ma non ci sono regole definite, allora la politica di default è di negare tutto il traffico, comprese le richieste di ping! Leggete il crossref:firewalls[firewalls,Firewall] per maggiori informazioni. Talvolta le prestazioni della scheda di rete sono scadenti, o sotto la media. In questi casi è preferibile cambiare la selezione del media da `autoselect` ad una selezione corretta. Anche se questo sistema funziona con la maggior parte dell'hardware, potrebbe non risolvere il problema per tutti. Ancora una volta, controllate tutte le impostazioni di rete, e leggete la pagina man man:tuning[7] . [[configtuning-virtual-hosts]] == Host Virtuali Un uso piuttosto comune di FreeBSD è come hosting di siti virtuali, dove un solo server appare alla rete come molti server distinti. Ciò viene effettuato assegnando indirizzi di rete multipli ad una sola interfaccia. Una data interfaccia di rete ha un solo indirizzo "reale", e può avere un numero qualsiasi di indirizzi "alias". Questi alias vengono normalmente aggiunti mettendo dei campi alias in [.filename]#/etc/rc.conf#. Un campo alias per l'interfaccia [.filename]#fxp0# appare così: [.programlisting] .... ifconfig_fxp0_alias0="inet xxx.xxx.xxx.xxx netmask xxx.xxx.xxx.xxx" .... Nota che il campo alias deve iniziare con `alias0` e aumentare in ordine, (ad esempio, `_alias1`, `_alias2`, e così via). Il processo di configurazione si fermerà al primo numero mancante. Il calcolo delle maschere di sotto-rete degli alias è importante, ma, fortunatamente, è anche abbastanza semplice. Per una data interfaccia, deve esserci un indirizzo che rappresenta correttamente la maschera di sotto-rete. Ogni altro indirizzo che ricada in questa rete deve avere una maschera di sotto-rete con tutti `1` (espressi come `255.255.255.255` o `0xffffffff`). Ad esempio, considera il caso in cui l'interfaccia [.filename]#fxp0# sia connessa a due reti, la rete `10.1.1.0` con maschera di sotto-rete `255.255.255.0` e la rete `202.0.75.16` con maschera di sotto-rete `255.255.255.240`. Vogliamo che il sistema sia visibile come `10.1.1.1` fino a `10.1.1.5` e come `202.0.75.17` fino a `202.0.75.20`. Come notato sopra, solo il primo indirizzo in un dato range di sotto-rete (in questo caso, `10.0.1.1` e `202.0.75.17`) dovrebbe avere una vera netmask; tutto il resto ( `10.1.1.2` fino a `10.1.1.5` e `202.0.75.18` fino a `202.0.75.20`) dovrebbe essere configurato con una netmask di `255.255.255.255`. Le seguenti righe configurano il dispositivo correttamente per questo scopo: [.programlisting] .... ifconfig_fxp0="inet 10.1.1.1 netmask 255.255.255.0" ifconfig_fxp0_alias0="inet 10.1.1.2 netmask 255.255.255.255" ifconfig_fxp0_alias1="inet 10.1.1.3 netmask 255.255.255.255" ifconfig_fxp0_alias2="inet 10.1.1.4 netmask 255.255.255.255" ifconfig_fxp0_alias3="inet 10.1.1.5 netmask 255.255.255.255" ifconfig_fxp0_alias4="inet 202.0.75.17 netmask 255.255.255.240" ifconfig_fxp0_alias5="inet 202.0.75.18 netmask 255.255.255.255" ifconfig_fxp0_alias6="inet 202.0.75.19 netmask 255.255.255.255" ifconfig_fxp0_alias7="inet 202.0.75.20 netmask 255.255.255.255" .... [[configtuning-configfiles]] == File di Configurazione === Struttura di [.filename]#/etc# Ci sono molte directory nelle quali vengono tenute le informazioni di configurazione. Tra queste ci sono: [.informaltable] [cols="1,1", frame="none"] |=== |[.filename]#/etc# |Informazioni generiche sulla configurazione del sistema; questi dati sono specifici del sistema. |[.filename]#/etc/defaults# |Versioni di default dei file di configurazione del sistema. |[.filename]#/etc/mail# |Configurazioni extra di man:sendmail[8], o file di configurazione di altri MTA. |[.filename]#/etc/ppp# |Configurazione ppp sia per i programmi a livello utente che a livello kernel. |[.filename]#/etc/namedb# |Posizione predefinita per i dati di man:named[8]. Normalmente qui si trova [.filename]#named.conf# insieme ai file di zona. |[.filename]#/usr/local/etc# |File di configurazione per le applicazioni installate. Può contenere sottodirectory. |[.filename]#/usr/local/etc/rc.d# |Script start/stop per i programmi installati. |[.filename]#/var/db# |File di dati specifici del sistema generati automaticamente, come il database dei package, il database di locate, e così via. |=== === Nomi degli Host ==== [.filename]#/etc/resolv.conf# [.filename]#/etc/resolv.conf# detta il modo in cui il sistema di risoluzione dei nomi di FreeBSD accede al DNS (Internet Domain Name System). I campi più comuni in [.filename]#resolv.conf# sono: [.informaltable] [cols="1,1", frame="none"] |=== |`nameserver` |L'indirizzo IP di un name server al quale dovrà rivolgersi il sistema di risoluzione. I server vengono interrogati nell'ordine in cui sono elencati, fino a un massimo di tre. |`search` |Lista di ricerca per i nomi degli host. Normalmente questo viene determinato dal dominio dell'host locale. |`domain` |Il nome del dominio locale. |=== Un [.filename]#resolv.conf# tipico: [.programlisting] .... search example.com nameserver 147.11.1.11 nameserver 147.11.100.30 .... [NOTE] ==== Si dovrebbe usare solo una tra le due opzioni `search` e `domain`. ==== Se stai usando DHCP, man:dhclient[8] generalmente sovrascriverà [.filename]#resolv.conf# con le informazioni ricevute dal server DHCP. ==== [.filename]#/etc/hosts# [.filename]#/etc/hosts# è un semplice database testuale, reminiscenza della vecchia rete Internet. Esso lavora in congiunzione con DNS e NIS fornendo una mappatura da nome a indirizzo IP. Computer locali connessi ad una LAN possono essere messi in questo file per una gestione semplice dei nomi, invece di mettere su un server man:named[8]. Inoltre, [.filename]#/etc/hosts# può essere usato per fornire un registro locale dei nomi di Internet, riducendo la necessità di effettuare richieste esternamente per i nomi ad accesso frequente. [.programlisting] .... # $FreeBSD$ # # Host Database # Questo file dovrebbe contenere gli indirizzi e gli alias # per gli host locali che condividono questo file. # In presenza di DNS o NIS, questo file potrebbe non essere consultato affatto; # guarda /etc/nsswitch.conf per l'ordine di risoluzione. # # ::1 localhost localhost.my.domain myname.my.domain 127.0.0.1 localhost localhost.my.domain myname.my.domain # # Rete immaginaria. #10.0.0.2 myname.my.domain myname #10.0.0.3 myfriend.my.domain myfriend # # In accordo all'RFC 1918, puoi usare le seguenti classi di IP per reti private # che non verranno mai connesse ad Internet: # # 10.0.0.0 - 10.255.255.255 # 172.16.0.0 - 172.31.255.255 # 192.168.0.0 - 192.168.255.255 # # In caso volessi essere in grado di collegarti ad Internet, avrai bisogno # di veri numeri ufficiali assegnati. PER FAVORE PER FAVORE PER FAVORE # non tentare di inventarti i numeri della tua rete ma fattene assegnare # uno dal tuo provider (se ne hai uno) o dall'Internet Registry (ftp su # rs.internic.net, directory `/templates'). # .... [.filename]#/etc/hosts# accetta il semplicissimo formato: [.programlisting] .... [Indirizzo Internet ] [nome host ufficiale] [alias1] [alias2] ... .... Ad esempio: [.programlisting] .... 10.0.0.1 myRealHostname.example.com myRealHostname foobar1 foobar2 .... Consulta man:hosts[5] per maggiori informazioni. === Configurazione dei File di Log ==== [.filename]#syslog.conf# [.filename]#syslog.conf# è il file di configurazione per il programma man:syslogd[8]. Indica quale tipo di messaggi `syslog` verranno scritti su ogni file di log. [.programlisting] .... # $FreeBSD$ # # Gli spazi SONO validi separatori dei campi in questo file. Ad ogni modo, # altri sistemi *nix-like insistono ancora nell'usare tab come separatori # di campo. Se condividi questo file tra più sistemi, potresti # voler usare solo dei tab come separatori. # Consulta la pagina man di syslog.conf(5). *.err;kern.debug;auth.notice;mail.crit /dev/console *.notice;kern.debug;lpr.info;mail.crit;news.err /var/log/messages security.* /var/log/security mail.info /var/log/maillog lpr.info /var/log/lpd-errs cron.* /var/log/cron *.err root *.notice;news.err root *.alert root *.emerg * # togli il commento a questo per loggare tutte le scritture su /dev/console # in /var/log/console.log #console.info /var/log/console.log # togli il commento a questo per abilitare il logging di tutti i messaggi di log # su /var/log/all.log #*.* /var/log/all.log # togli il commento a questo per abilitare il logging su un host remoto di nome # loghost #*.* @loghost # togli i commenti a questi se hai inn in funzione # news.crit /var/log/news/news.crit # news.err /var/log/news/news.err # news.notice /var/log/news/news.notice !startslip *.* /var/log/slip.log !ppp *.* /var/log/ppp.log .... Consulta la pagina man di man:syslog.conf[5] per maggiori informazioni. ==== [.filename]#newsyslog.conf# [.filename]#newsyslog.conf# è il file di configurazione di man:newsyslog[8], un programma che normalmente viene eseguito da man:cron[8]. man:newsyslog[8] determina quando i file di log richiedono un'archiviazione o un riordinamento. [.filename]#logfile# viene rinominato in [.filename]#logfile.0#, [.filename]#logfile.0# in [.filename]#logfile.1# e così via. Alternativamente, i file potranno essere archiviati in formato man:gzip[1], e quindi diventeranno: [.filename]#logfile.0.gz#, [.filename]#logfile.1.gz#, e così via. [.filename]#newsyslog.conf# indica quali file di log devono essere gestiti, quanti devono essere mantenuti, e quando devono essere toccati. I file di log possono essere riordinati e/o archiviati quando raggiungono una certa dimensione, o a una certa data/ora periodica. [.programlisting] .... # file di configurazione per newsyslog # $FreeBSD$ # # filename [owner:group] mode count size when [ZB] [/pid_file] [sig_num] /var/log/cron 600 3 100 * Z /var/log/amd.log 644 7 100 * Z /var/log/kerberos.log 644 7 100 * Z /var/log/lpd-errs 644 7 100 * Z /var/log/maillog 644 7 * @T00 Z /var/log/sendmail.st 644 10 * 168 B /var/log/messages 644 5 100 * Z /var/log/all.log 600 7 * @T00 Z /var/log/slip.log 600 3 100 * Z /var/log/ppp.log 600 3 100 * Z /var/log/security 600 10 100 * Z /var/log/wtmp 644 3 * @01T05 B /var/log/daily.log 640 7 * @T00 Z /var/log/weekly.log 640 5 1 $W6D0 Z /var/log/monthly.log 640 12 * $M1D0 Z /var/log/console.log 640 5 100 * Z .... Consulta la pagina man di man:newsyslog[8] per maggiori informazioni. [[configtuning-sysctlconf]] === [.filename]#sysctl.conf# [.filename]#sysctl.conf# assomiglia molto a [.filename]#rc.conf#. I valori vengono impostati nella forma `variabile=valore`. I valori specificati vengono impostati dopo che il sistema è entrato in modalità multiutente. Non tutte le variabili sono gestibili in questo modo. Per disabilitare il log sulle uscite dei processi per segnale fatale ed impedire agli utenti di vedere che i processi sono avviati con altre utenze, puoi settare in [.filename]#sysctl.conf# la riga seguente: [.programlisting] .... # Do not log fatal signal exits (e.g. sig 11) kern.logsigexit=0 # Prevent users from seeing information about processes that # are being run under another UID. security.bsd.see_other_uids=0 .... [[configtuning-sysctl]] == Messa a Punto con sysctl man:sysctl[8] è un'interfaccia che permette di effettuare cambiamenti ad un sistema FreeBSD già attivo. Questo include molte opzioni avanzate dello stack TCP/IP e del sistema di memoria virtuale che possono permettere di migliorare drammaticamente le prestazioni ad un sistemista che abbia esperienza. Più di cinquecento variabili di sistema possono essere lette e modificate usando man:sysctl[8]. In sostanza, man:sysctl[8] serve a due cose: a leggere e a modificare le impostazioni di sistema. Per visualizzare tutte le variabili leggibili: [source,shell] .... % sysctl -a .... Per leggere una particolare variabile, ad esempio, `kern.maxproc`: [source,shell] .... % sysctl kern.maxproc kern.maxproc: 1044 .... Per impostare una particolare variabile, usa l'intuitiva sintassi _variabile_=_valore_: [source,shell] .... # sysctl kern.maxfiles=5000 kern.maxfiles: 2088 -> 5000 .... I valori validi per le variabili di sysctl sono generalmente o stringhe, o numeri, o valori booleani (un valore booleano può valere `1` per sì o `0` per no). Se vuoi settare in modo automatico alcune variabile ad ogni avvio della macchina, usa il file [.filename]#/etc/sysctl.conf#. Per maggiori informazioni guarda la pagina man di man:sysctl.conf[5] e la <>. [[sysctl-readonly]] === man:sysctl[8] in sola lettura In alcuni casi può essere desiderabile modificare i valori di man:sysctl[8] in sola lettura. Anche se questo talvolta è inevitabile, può essere fatto solo con un riavvio. Ad esempio in alcuni modelli di laptop il dispositivo man:cardbus[4] non effettuerà il controllo sugli intervalli di memoria, e fallirà con errori che assomigliano a questi: [source,shell] .... cbb0: Could not map register memory device_probe_and_attach: cbb0 attach returned 12 .... Casi come il precedente richiedono tipicamente la modifica di alcuni valori predefiniti di man:sysctl[8] che sono impostati come sola lettura. Per superare queste situazioni un utente può mettere degli "OID" di man:sysctl[8] nel proprio [.filename]#/boot/loader.conf.local#. I valori predefiniti sono indicati nel file [.filename]#/boot/defaults/loader.conf#. Per risolvere i problemi menzionati qui sopra sarà necessario modificare `hw.pci.allow_unsupported_io_range=1` nel file suddetto. Ora man:cardbus[4] funzionerà correttamente. [[configtuning-disk]] == Messa a Punto dei Dischi === Variabili Sysctl ==== `vfs.vmiodirenable` La variabile sysctl `vfs.vmiodirenable` può essere impostata a 0 (inattivo) o 1 (attivo); di default è 1. Questa variabile controlla il modo in cui le directory vengono messe nella cache dal sistema. La maggior parte delle directory sono piccole, e usano solo un singolo frammento (tipicamente 1 K) nel file system e meno (tipicamente 512 byte) nella cache. Con questa variabile impostata a 0, il buffer manterrà soltanto un numero fissato di directory nella cache anche se hai una quantità enorme di memoria. Attivando questa sysctl si permette al buffer di usare la VM Page Cache per immagazzinare le directory, rendendo disponibile tutta la memoria disponibile per il caching delle directory. In ogni caso, la minima quantità di memoria usata per memorizzare una directory sarà la dimensione della pagina fisica (in genere 4 K) invece di 512 byte. Noi consigliamo di attivare questa opzione se si hanno in esecuzione dei servizi che manipolano un grosso numero file. Servizi di questo tipo sono le cache web, i grandi sistemi di posta, e quelli di news. Attivare questa opzione in generale non ridurrà le prestazioni nonostante la memoria sprecata, ma dovresti sperimentare tu stesso per verificare. ==== `vfs.write_behind` La variabile sysctl `vfs.write_behind` ha il valore predefinito di `1` (attivo). Essa dice al file system di effettuare le scritture sul media quando vengono raccolti cluster completi, il che accade tipicamente quando si scrivono grossi file sequenziali. L'idea è di evitare la saturazione del buffer cache con buffer "sporchi" quando le prestazioni dell'I/O non ne trarrebbero giovamento. Ad ogni modo, questo può causare uno stallo dei processi, ed in alcune circostanze potreste desiderare di disabilitarlo. ==== `vfs.hirunningspace` La variabile sysctl `vfs.hirunningspace` determina quanto grande deve essere la coda I/O in tutti i controller dei dischi nel sistema in un dato momento. Il valore predefinito in genere è sufficiente ma su macchine con molti dischi potreste voler aumentarlo a quattro o cinque _megabyte_. Notate che impostandolo ad un valore troppo alto (superando i limiti della cache) potreste avere delle performance peggiori. Non impostate un valore troppo alto arbitrariamente! Valori più alti aumentano la latenza nelle letture contemporanee. Ci sono altre sysctl relative alla buffer-cache ed alle cache delle pagine VM. Non vi consigliamo di cambiare questi valori, il sistema di VM fa già un ottimo lavoro di messa a punto automatica. ==== `vm.swap_idle_enabled` La variabile sysctl `vm.swap_idle_enabled` è utile in grossi sistemi multiutente dove si hanno molti utenti che entrano ed escono lasciando molti processi inattivi. Questi sistemi tendono a generare un grande pressione sulle riserve di memoria libera. Attivando questa caratteristica e manipolando l'isteresi di swap (in secondi di inattività) tramite `vm.swap_idle_threshold1` e `vm.swap_idle_threshold2` potete abbassare la priorità delle pagine di memoria associate con i processi inattivi più velocemente che con il normale algoritmo di paginazione. Ciò dà una mano al demone di paginazione. Non attivate questa opzione a meno che non ne abbiate bisogno, poichè il compromesso che state accettando è essenzialmente di pre-paginare la memoria in anticipo piuttosto che in ritardo, consumando dunque più swap e banda di trasmissione verso il disco. In un piccolo sistema questa opzione avrà un effetto ridotto ma in un grosso sistema che è già sottoposto a un moderato carico di paginazione questa opzione permette al sistema VM di spostare facilmente interi processi dentro e fuori la memoria. ==== `hw.ata.wc` FreeBSD 4.3 ha giocato un pò con l'idea di disattivare il caching IDE in scrittura. Questo ha ridotto la larghezza di banda in scrittura verso i dischi IDE ma è stato considerato necessario a causa di gravi problemi di consistenza dei dati introdotti dai venditori di dischi rigidi. Il problema è che il disco IDE rimane inattivo dopo che una scrittura è stata completata. Con il caching in scrittura attivo, i dischi IDE non scrivono soltanto i dati sui dischi in maniera disordinata, ma talvolta rimandano la scrittura indefinitamente sotto carichi di lavoro del disco pesanti. Un crash o un calo di tensione possono condurre a seri problemi di corruzione del file system. L'impostazione predefinita di FreeBSD fu cambiata in favore della sicurezza. Sfortunatamente, il risultato è stato una perdita di prestazioni talmente tremenda che abbiamo dovuto reinserire il caching in scrittura di default dopo quella release. Dovresti verificare il valore di default sul tuo sistema osservando la variabile sysctl `hw.ata.wc`. Se il caching IDE in scrittura è disattivato, potete attivarlo reimpostando la variabile del kernel a 1. Questo dovrebbe essere effettuato dal boot loader all'avvio. Tentare di effettuare questo cambiamento dopo che il kernel è stato avviato non avrà nessun effetto. Per maggiori informazioni, guarda man:ata[4]. ==== `SCSI_DELAY` (`kern.cam.scsi_delay`) La configurazione del kernel `SCSI_DELAY` può ridurre il tempo di avvio del sistema. I valori di default sono piuttosto alti e possono essere responsabili anche di `15` secondi di ritardo nel processo di avvio. Ridurre il valore a `5` secondi funziona in molti casi (specialmente con i dispositivi moderni). Nuove versioni di FreeBSD (5.0 e superiori) dovrebbero essere in grado di usare `kern.cam.scsi_delay` come un'opzione da boot. Quest'ultima e l'opzione di configurazione del kernel accettano valori in _millisecondi_ , e _non_ in _secondi_. [[soft-updates]] === Soft Update Il programma man:tunefs[8] può essere usato per mettere a punto con accuratezza un file system. Questo programma ha molte opzioni differenti, ma per ora noi ci preoccuperemo solo di attivare e disattivare i Soft Update, che verrà effettuato tramite: [source,shell] .... # tunefs -n enable /filesystem # tunefs -n disable /filesystem .... Un file system non potrà essere modificato con man:tunefs[8] mentre è montato. Un buon momento per attivare i Soft Update è prima che le partizioni siano montate, in modalità singolo utente. I Soft Update migliorano drasticamente le prestazioni dei meta-dati, principalmente la creazione e la cancellazione di file, attraverso l'uso di una memoria cache. Consigliamo di attivare i Soft Update su tutti i file system. Ci sono due lati negativi relativi ai Soft Update dei quali dovresti essere a conoscenza: primo, i Soft Update garantiscono la consistenza del file system in caso di crash ma è più che probabile che passino molti secondi (anche un minuto!) prima che venga aggiornato fisicamente il disco. Se il sistema va in crash potresti perdere molto più lavoro in questo modo. Secondo, i Soft Update rallentano la liberazione dei blocchi liberi del file system. Se hai un file system (come il file system root) che è quasi pieno, la realizzazione di un grosso aggiornamento, come un `make installworld`, potrebbe essere causa di un superamento dei limiti di spazio del file system e di un fallimento dell'aggiornamento. ==== Maggiori Dettagli sui Soft Update Ci sono due approcci tradizionalmente nella scrittura dei meta-dati del file system su disco. (Gli aggiornamenti dei meta-dati sono aggiornamenti ai dati che non sono contenuto, come gli inode o le directory.) Storicamente, il comportamento predefinito era di scrivere gli aggiornamenti dei meta-dati in maniera sincrona. Se una directory veniva modificata, il sistema attendeva finchè il cambiamento venisse effettivamente scritto su disco. I buffer con i dati dei file (i contenuti dei file) venivano passati attraverso la cache e salvati su disco in seguito, in maniera asincrona. Il vantaggio di questa implementazione è che avviene in maniera sicura. Se si verifica un problema durante un aggiornamento, i meta-dati sono sempre in uno stato consistente. Un file viene creato completamente o non viene creato affatto. Se i blocchi dati di un file non sono riusciti ad uscire dalla cache e arrivare al disco prima del crash, man:fsck[8] è in grado di capirlo e riparare il file system impostando a zero la lunghezza del file. Inoltre, l'implementazione è chiara e semplice. Lo svantaggio è che i cambiamenti dei meta-dati sono lenti. Un `rm -r`, ad esempio, tocca tutti i file in una directory consecutivamente, ma ogni cambiamento della directory (la cancellazione del file) verrà scritto su disco in maniera sincrona. Questo include gli aggiornamenti alla directory stessa, alla tabella degli inode, e magari anche ai blocchi indiretti allocati dal file. Simili considerazioni si applicano nell'elenco di grosse gerarchie (`tar -x`). Il secondo caso è l'aggiornamento asincrono dei meta-dati. Questo è il comportamento predefinito per Linux/ext2fs e `mount -o async` per *BSD/ufs. Anche tutti gli aggiornamenti dei meta-dati vengono semplicemente fatti passare attraverso la cache, cioè vengono mescolati con gli aggiornamenti dei dati contenuti nel file. Il vantaggio di questa implementazione è che non c'è bisogno di attendere che ogni aggiornamento dei meta-dati venga scritto su disco, dunque tutte le operazioni che causano enormi quantità di aggiornamenti dei meta-dati lavorano molto più velocemente che nel caso sincrono. Inoltre, l'implementazione è ancora semplice e chiara, dunque c'è un basso rischio che si annidino dei bug nel codice. Lo svantaggio è che non c'è nessuna garanzia di uno stato consistente del file system. Se si verifica un problema durante un'operazione che ha aggiornato grandi quantità di meta-dati (ad esempio un abbassamento di tensione, o qualcuno che preme il tasto reset), il file system verrà lasciato in uno stato imprevedibile. Non c'è opportunità di esaminare lo stato del file system quando il sistema viene riavviato; i blocchi dati di un file potrebbero essere già stati scritti sul disco mentre gli aggiornamenti della tabella degli inode o la directory associata non lo sono. È praticamente impossibile implementare un `fsck` che sia in grado di ripulire il caos risultante (perchè i dati necessari non sono disponibili sul disco). Se il file system è stato danneggiato più del riparabile, la sola scelta è di usare man:newfs[8] per ricrearlo e recuperarlo da un backup. La soluzione comune di questo problema era implementare _la registrazione delle regioni sporche_, a cui spesso si fa riferimento come _journaling_, anche se questo termine non viene usato coerentemente e talvolta viene applicato ad altre forme di logging delle transazioni. Gli aggiornamenti dei meta-dati sono ancora scritti in maniera sincrona, ma solo in una piccola regione del disco. In seguito vengono spostati nella posizione appropriata. Poichè l'area di registrazione è una piccola regione contigua sul disco, non ci sono lunghe distanze da percorrere per le testine del disco, anche durante le operazioni pesanti, dunque queste operazioni sono più veloci degli aggiornamenti sincroni. Inoltre la complessità dell'implementazione è piuttosto limitata, dunque il rischio che si presentino dei bug è basso. Uno svantaggio è che tutti i meta-dati vengono scritti due volte (una volta nella regione di logging ed un'altra nella posizione appropriata) e quindi per un lavoro normale si può avere un "peggioramento" delle prestazioni. D'altro canto, in caso di crash, tutte le operazioni sui meta-dati in sospeso possono essere velocemente annullate o recuperate dall'area di registrazione quando il sistema è di nuovo attivo, e come risultato si ha un avvio veloce del file system. Kirk McKusick, lo sviluppatore del Berkeley FFS, ha risolto questo problema con i Soft Update: tutti gli aggiornamenti dei meta-dati vengono tenuti in memoria e vengono scritti su disco in sequenza ordinata ("aggiornamenti ordinati dei meta-dati"). Ciò porta all'effetto che, in caso di operazioni pesanti sui meta-dati, gli ultimi aggiornamenti ad un elemento "recuperano" i precedenti se questi sono ancora in memoria e non sono già stati scritti su disco. Dunque tutte le operazioni, diciamo su una directory, vengono effettuate principalmente in memoria prima che l'aggiornamento sia scritto su disco (i blocchi dei dati vengono ordinati in relazione alla loro posizione, in modo che non vengano scritti su disco prima dei loro meta-dati). Se il sistema va in crash, ciò causa un implicito "riavvolgimento del log": tutte le operazioni che non hanno ancora trovato posto sul disco appariranno come mai effettuate. Viene mantenuto uno stato consistente del file system che sarà quello di 30 o 60 secondi prima. L'algoritmo usato garantisce anche che tutte le risorse in uso siano marcate come tali nelle appropriate tabelle di bit: blocchi e inode. Dopo un crash, il solo errore di allocazione è che vengono marcate come "usate" anche risorse che sono effettivamente "libere". man:fsck[8] riconosce questa situazione, e libera le risorse che non sono più in uso. Non c'è pericolo nell'ignorare lo stato di _sporcizia_ del file system dopo un crash montandolo di forza con `mount -f`. Per poter liberare le risorse che potrebbero essere non usate, man:fsck[8] ha bisogno di essere avviato in seguito. Questa è l'idea di un _fsck in background_: all'avvio del sistema, viene registrata solo una _immagine_ del file system. `fsck` può essere eseguito in seguito. Tutti i file system possono essere montati "sporchi", quindi il processo di avvio del sistema procede in modalità multiutente. In seguito, `fsck` viene avviato in background su tutti i file system dove è necessario, per liberare le risorse che potrebbero essere inutilizzate. (I file system che non usano i Soft Updates hanno ancora bisogno del solito `fsck`, comunque.) Il vantaggio è che le operazioni sui meta-dati sono veloci quasi come gli aggiornamenti asincroni (cioè più veloci che con il _logging_, che deve scrivere i meta-dati due volte). Gli svantaggi sono nella complessità del codice (che implica un maggiore rischio di trovare bug in un'area molto sensibile, essendo legata alla perdita dei dati degli utenti), ed un consumo di memoria maggiore. Inoltre ci sono alcune idiosincrasie alle quali ci si deve abituare. Dopo un crash, lo stato del file system appare in qualche modo "vecchio". In situazioni dove l'approccio sincrono avrebbe causato la permanenza di alcuni file di lunghezza zero dopo un `fsck`, questi file non esistono affatto con un file system con Soft Update, perchè nè i meta-dati nè i contenuti dei file sono mai stati scritti su disco. Lo spazio su disco non viene rilasciato finchè gli aggiornamenti non sono stati scritti su disco, il che può avvenire qualche tempo dopo che è stato eseguito `rm`. Questo potrebbe causare problemi durante l'installazione di grandi quantità di dati su un file system che non avesse abbastanza spazio per contenere tutti i file due volte. [[configtuning-kernel-limits]] == Messa a Punto dei Limiti del Kernel [[file-process-limits]] === Limiti dei File/Processi [[kern-maxfiles]] ==== `kern.maxfiles` `kern.maxfiles` può essere aumentato o abbassato a seconda dei requisiti del tuo sistema. Questa variabile indica il numero massimo di descrittori di file sul tuo sistema. Quando la tabella dei descrittori di file è piena, apparirà ripetutamente la scritta `file: table is full` nel buffer dei messaggi di sistema, che può essere visualizzato con il comando `dmesg`. Ogni file, socket, o fifo aperta usa un descrittore di file. Un server di produzione di larga scala può richiedere facilmente molte migliaia di descrittori di file, in relazione al tipo e al numero di servizi in esecuzione insieme. Nelle vecchie release di FreeBSD, il valore predefinito di `kern.maxfile` viene dettato dall'opzione `maxusers` nel file di configurazione del kernel. `kern.maxfiles` cresce proporzionalmente al valore di `maxusers`. Quando si compila un kernel personalizzato, è una buona idea impostare questa opzione di configurazione del kernel in base agli usi del proprio sistema. Da questo numero, dipendono molti dei limiti predefiniti del kernel. Anche se una macchina in produzione potrebbe non avere effettivamente 256 utenti connessi contemporaneamente, le risorse necessarie potrebbero essere simili a quelle di un server web su larga scala. A partire da FreeBSD 4.5, `kern.maxusers` è automaticamente dimensionato sulla base della memoria disponibile nel sistema, e può essere determinato a run-time leggendo il valore del sysctl read-only `kern.maxusers`. Alcuni siti richiedono valori minori o maggiori di `kern.maxusers` e questo può essere impostato come un parametro modificabile dal loader; valori di 64, 128 o 256 non sono fuori dal comune. Non raccomandiamo di andare oltre i 256 a meno che non si necessiti di un numero esagerato di file descriptor; molti dei valori modificati nel loro default da `kern.maxusers` possono essere singolarmente sovrascritti a boot-time o a run-time in [.filename]#/boot/loader.conf# (leggi la pagina di manuale man:loader.conf[5] o il file [.filename]#/boot/defaults/loader.conf# per alcuni suggerimenti) o come descritto altrove in questo documento. Sistemi precedenti a FreeBSD 4.4 devono invece impostare questo valore attraverso l'opzione di man:config[8] `maxusers`. Nelle release precedenti, il sistema setterà in modo automatico `maxusers` se lo imposti a `0`. Quando usi quest'opzione, impostalo almeno a 4, specialmente se stai usando il sistema a finestre X o se compili software. Questo è dovuto al fatto che la tabella più importante settata da `maxusers` è quella relativa al numero massimo di processi, risultato di `20 + 16 * maxusers`, e quindi se setti `maxusers` a 1, puoi avere solo 36 processi in modo simultaneo, inclusi i 18 o più di avvio del sistema e i 15 o più che verranno creati all'avvio del sistema a finestre X. Perfino una semplice attività come la lettura di una pagina man avvia fino a 9 processi per filtrare, decomprimere, e visualizzare la pagina. Settando `maxusers` a 64 avrai fino a 1044 processi simultanei, che dovrebbero essere sufficienti per quasi tutti gli utenti. Ad ogni modo, se vedi il temuto errore quando tenti di avviare un programma, o se stai usando un server con molti utenti simultanei (come `ftp.FreeBSD.org`), puoi sempre incrementare il numero e ricompilare. [NOTE] ==== `maxusers` _non_ limita il numero degli utenti che possono loggarsi sulla tua macchina. Semplicemente setta la dimensione di alcune tabelle a un valore ragionevole considerando il numero massimo di utenti che probabilmente avrai sul tuo sistema e quanti processi ognuno di loro avranno in esecuzione. Un'opzione che limita il numero di login remoti simultanei e di terminali windows è crossref:kernelconfig[kernelconfig-ptys,`pseudo-device pty 16`]. Con FreeBSD 5.X, non ti devi preoccupare di questo numero poichè il driver man:pty[4] è "auto-cloning"; semplicemente usa la linea `device pty` nel tuo file di configurazione. ==== ==== `kern.ipc.somaxconn` La variabile sysctl `kern.ipc.somaxconn` limita la dimensione della coda in ascolto per le connessioni TCP. Il valore predefinito è di `128`, generalmente troppo basso per una gestione robusta di nuove connessioni in ambienti come i web server molto carichi. Per tali ambienti, è consigliato aumentare questo valore a `1024` o maggiore. Il demone di servizio può a sua volta limitare la dimensione della coda (e.g. man:sendmail[8], o Apache) ma spesso avrà una direttiva nel proprio file di configurazione per correggere la dimensione della coda. Grosse code di ascolto aiutano anche ad evitare attacchi di tipo Denial of Service (). [[nmbclusters]] === Limiti di Rete L'opzione di configurazione del kernel `NMBCLUSTERS` decide la quantità di Mbuf di rete disponibili al sistema. Un server molto trafficato con un numero basso di Mbuf ostacolerebbe le possibilità di FreeBSD. Ogni cluster rappresenta approssimativamente 2 K di memoria, dunque un valore di 1024 rappresenta 2 megabyte di memoria del kernel riservata per i buffer di rete. Può essere effettuato un semplice calcolo per capire quanti ne siano necessari. Se hai un web server che arriva al massimo a 1000 connessioni simultanee, ed ogni connessione consuma un buffer di 16 K in ricezione e un altro di 16 K in trasmissione, avrai bisogno approssimativamente di 32 MB di buffer di rete per coprire il web server. Una buona regola generale è di moltiplicare per 2, dunque 2x32 MB / 2 KB = 64 MB / 2 KB = 32768. Consigliamo valori compresi tra 4096 e 32768 per macchine con grandi quantità di memoria. In nessun caso dovreste specificare un valore alto arbitrario per questo parametro, poichè potrebbe portare ad un crash all'avvio. L'opzione `-m` di man:netstat[1] può essere usata per osservare l'uso della rete. L'opzione del loader `kern.ipc.nmbclusters` può essere usata per impostare questi valori all'avvio. Solo versioni vecchie di FreeBSD richiedono l'uso dell'opzione `NMBCLUSTERS` come configurazione del kernel (man:config[8]). Per server sotto carico che fanno un uso massiccio della chiamata di sistema man:sendfile[2], potrebbe essere necessario aumentare il numero di buffer man:sendfile[2] tramite l'opzione di configurazione del kernel `NSFBUFS` o impostando il suo valore in [.filename]#/boot/loader.conf# (vedere man:loader[8] per maggiori dettagli). Un indicatore comune che questo parametro deve essere corretto è la comparsa di processi nello stato `sfbufa`. La variabile sysctl `kern.ipc.nsfbufs` è solo un riferimento read-only alla variabile configurata nel kernel. Questo parametro aumenta nominalmente con `kern.maxusers`, in ogni caso potrebbe essere necessario effettuare piccole correzioni per farli concordare. [IMPORTANT] ==== Anche se un socket è stato segnalato come non-bloccante, richiamando man:sendfile[2] su di esso si potrebbe avere un blocco della chiamata man:sendfile[2] fino a quando non sono disponibili delle `struct sf_buf`. ==== ==== `net.inet.ip.portrange.*` La variabili sysctl `net.inet.ip.portrange.*` controllano i numeri di porta automaticamente assegnate a socket TCP ed UDP. Ci sono tre intervalli: uno basso, uno predefinito, ed uno alto. La maggior parte dei programmi usa l'intervallo predefinito che è controllato da `net.inet.ip.portrange.first` e `net.inet.ip.portrange.last`, che hanno valori predefiniti di 1024 e 5000. Questi intervalli sono usati per le connessioni in uscita, ed è possibile che il sistema esaurisca le porte in alcune circostanze. Ciò accade per lo più quando avete un web proxy molto carico. L'intervallo di porte non è un problema quando si usano server che abbiano per lo più connessioni in ingresso, come i normali web server, o un numero limitato di connessioni in uscita, come i relay di posta. Per situazioni nelle quali potreste terminare le porte, è consigliato aumentare leggermente `net.inet.ip.portrange.last`. Un valore di `10000`, `20000` o `30000` può essere ragionevole. Dovreste anche considerare gli effetti relativi ad un firewall nel cambiare il range di porte. Alcuni firewall potrebbero bloccare grandi intervalli di porte (tipicamente le porte basse) ed aspettarsi che i sistemi usino porte più alte per le connessioni in uscita - per questa ragione si consiglia di non abbassare il valore di `net.inet.ip.portrange.first`. ==== Prodotto del Ritardo di Banda TCP Il limite del Prodotto del Ritardo di Banda TCP è simile a TCP/Vegas in NetBSD. Può essere abilitato impostando la variabile sysctl `net.inet.tcp.inflight_enable` ad `1`. Il sistema tenterà di calcolare il prodotto del ritardo di banda per ogni connessione e limiterà l'ammontare di dati accodati per la trasmissione su rete al livello migliore per garantire il massimo throughput. Questa funzionalità è utile quando si inviano dati su modem multipli, su Ethernet Gigabit, o su collegamenti WAN ad alta velocità (o qualsiasi altro collegamento con un alto prodotto a banda di ritardo), in particolar modo se state usando anche il window scaling o se avete configurato una finestra TCP molto ampia. Se abilitate questa opzione, dovreste anche assicurarvi di impostare a `0 net.inet.tcp.inflight_debug` (per disabilitare il debugging), e per un uso di produzione può essere utile impostare `net.inet.tcp.inflight_min` ad almeno `6144`. Notate comunque che impostando dei livelli minimi alti può in pratica disabilitare la limitazione di banda, su alcuni tipi di collegamento. La funzionalità di limitazione della banda riduce la quantità di dati creati in rotte intermedie e fa circolare le code di pacchetti così come riduce la quantità di dati creati nella coda di interfaccia dell'host locale. Con meno pacchetti accodati, le connessioni interattive, specialmente sopra modem lenti, opereranno con lenti _Round Trip Times_ (tempi di andata e ritorno). Comunque, nota che questa feature ha effetto solo sulla trasmissione dati (uploading / lato server). Non ha effetto sulla ricezione (downloading). Modificare `net.inet.tcp.inflight.stab` non è raccomandato. Questo parametro è di default a 20, rappresentando 2 pacchetti massimi aggiunti al ritardo del prodotto della banda della finestra. La finestra addizionale è richiesta per stabilizzare l'algoritmo e migliorare la risposta alle condizioni che cambiano ma può risultare in tempi lunghi sui ping sopra link lenti (anche se molto più lento di quello che otterresti senza l'algoritmo di inflight). In questi casi, puoi voler ridurre questo parametro a 15, 10 o 5; e puoi anche ridurre `net.inet.tcp.inflight.min` (per esempio, a 3500) per ottenere l'effetto desiderato. Ridurre questi parametri dovrebbe essere fatto solo come ultima spiaggia. === Memoria Virtuale ==== `kern.maxvnodes` Un vnode è la rappresentazione di un file o una directory. Aumentare il numero di vnodi disponibili sul sistema operativo aumenterà l'I/O di disco. Normalmente questo viene gestito dal sistema operativo e non deve essere cambiato. In pochi casi dove l'I/O di disco è un collo di bottiglia ed il sistema sta finendo i suoi vnodi, questo parametro sarà aumentato. L'aumento di RAM libera ed inattiva sarà tenuto in conto. Per vedere il numero corrente di vnodi in uso: [source,shell] .... # sysctl vfs.numvnodes vfs.numvnodes: 91349 .... Per vedere il numero massimo di vnodi: [source,shell] .... # sysctl kern.maxvnodes kern.maxvnodes: 100000 .... Se l'uso del nodo corrente è vicino alla fine, aumentare `kern.maxvnodes` di un valore di 1.000 è probabilmente una buona idea. Tenete un occhio sul numero di `vfs.numvnodes`. Se scala al massimo, `kern.maxvnodes` dovrà essere incrementato ancora. Dovrebbe essere visibile con man:top[1] uno spostamento nell'uso della memoria. Molta memoria dovrebbe essere attiva. [[adding-swap-space]] == Aggiunta di Spazio di Swap Non importa con quanta cura pianifichi tutto, a volte un sistema non funziona come ti aspetti. Se ti trovi ad avere bisogno di maggiore spazio di swap, è abbastanza semplice aggiungerlo. Ci sono tre modi per aumentare lo spazio di swap: aggiungere un nuovo disco rigido, abilitare lo swap su NFS, e creare un file di swap su una partizione esistente. Per informazioni su come criptare lo spazio di swap, quali opzioni esistono e perchè dovrebbe essere fatto, vedere la sezione swap-encrypting del Manuale. [[new-drive-swap]] === Swap su un Nuovo Disco Rigido Il modo migliore per aggiungere dello swap, ovviamente, è usare questa come scusa per aggiungere un altro disco rigido. Puoi sempre aggiungere un nuovo disco, dopo tutto. Se puoi fare così, vai a rileggere la discussione sullo spazio di swap nella <> del Manuale per alcuni suggerimenti su come organizzare al meglio lo spazio di swap. [[nfs-swap]] === Swap su NFS Lo swap su NFS è consigliato solo se non hai un disco locale su cui realizzare lo swap. Lo swap via NFS è limitato dalla larghezza di banda disponibile sulla rete e aggiunge ulteriore lavoro per il server NFS. [[create-swapfile]] === File di Swap Puoi creare un file delle dimensioni specifiche per usarlo come file di swap. In questo nostro esempio useremo un file di 64MB chiamato [.filename]#/usr/swap0#. Puoi usare qualsiasi nome vuoi, ovviamente. .Creare un file di Swap su FreeBSD [example] ==== . Accertati che il tuo file di configurazione del kernel includa il memory disk driver (man:md[4]). È di default nel kernel [.filename]#GENERIC#. + [.programlisting] .... device md # Memory "disks" .... . Crea un file di swap ([.filename]#/usr/swap0#): + [source,shell] .... # dd if=/dev/zero of=/usr/swap0 bs=1024k count=64 .... . Imposta i permessi appropriati su ([.filename]#/usr/swap0#): + [source,shell] .... # chmod 0600 /usr/swap0 .... . Riavvia la macchina o per abilitare il file di swap immediatamente scrivi: + [source,shell] .... # mdconfig -a -t vnode -f /usr/swap0 -u 0 && swapon /dev/md0 .... ==== [[acpi-overview]] == Gestione dell'Energia e delle Risorse È importante utilizzare le risorse hardware in maniera efficiente. Prima che ACPI fosse introdotto era difficile e per nulla flessibile per il sistema operativo gestire l'energia e le proprietà termiche del sistema. L'hardware era controllato dal BIOS e quindi l'utente aveva meno controllo e visibilità per il settaggio della gestione dell'energia. Una configurazione limitata era disponibile tramite _Advanced Power Management (APM)_. La gestione dell'energia e delle risorse è uno dei concetti fondamentali di un moderno sistema operativo. Per esempio, puoi far sì che un sistema operativo faccia il monitoraggio dei limiti di sistema (e possibilmente ti avvisi) in caso la temperatura del sistema cresca in maniera incontrollata. In questa sezione del Manuale di FreeBSD, ti forniremo informazioni esaustive circa ACPI. Alla fine saranno forniti maggiori riferimenti per ulteriori letture. [[acpi-intro]] === Cos'è ACPI? ACPI (Advanced Configuration and Power Interface) è uno standard scritto da un gruppo di venditori per fornire un'interfaccia standard per risorse hardware e gestione dell'energia (da qui il nome). È un elemento centrale nella _configurazione diretta del sistema operativo e nella gestione dell'energia_, ad esempio: fornisce più controllo e flessibilità al sistema operativo (OS). I sistemi moderni "stressano" i limiti delle interfacce correnti Plug and Play, prima della introduzione di ACPI. ACPI è il diretto successore di APM (Advanced Power Management). [[acpi-old-spec]] === Riassunto della Gestione Avanzata dell'Energia (APM) La tecnologia _Advanced Power Management (APM)_ controlla l'uso dell'energia di un sistema basandosi sulla sua attività. Il BIOS APM è fornito dal venditore del sistema ed è specifico alla piattaforma hardware. Un driver APM nell'OS media l'accesso all'_Interfaccia Software APM_ che permette la gestione dei livelli di energia. APM dovrebbe essere usato per sistemi prodotti nel o prima dell'anno 2000. Ci sono quattro problemi maggiori in APM. Primo, la gestione dell'energia è fatta dal BIOS (specifico del venditore) e l'OS non ne ha conoscenza. Un esempio di questo è quando l'utente imposta i valori di pausa per un disco nell'APM BIOS, che quando vengono ecceduti, il BIOS rallenta il disco, senza il consenso dell'OS. Secondo, la logica di APM è integrata nel BIOS, e opera al di fuori lo scopo dell'OS. Questo significa che gli utenti possono riparare i problemi nel loro BIOS APM facendo un flash di una nuova memoria nel ROM; il che è una procedura molto difficile con il pericolo potenziale di lasciare il sistema in uno stato irrecuperabile se fallisce. Terzo, APM è una tecnologia specifica del venditore il che significa che c'è un sacco di duplicazione degli sforzi e bachi trovati nel BIOS di un venditore che non possono essere risolti in altri. In ultima analisi, il BIOS APM non ha abbastanza spazio per implementare una politica sofisticata, o una che può adattarsi molto bene allo scopo della macchina. _Plug and Play BIOS (PNPBIOS)_ era inaffidabile in molte situazioni. PNPBIOS era una tecnologia a 16 bit, così il sistema operativo doveva usare l'emulazione a 16 bit per "interfacciarsi" con i metodi PNPBIOS. Il driver APM di FreeBSD è documentato nella pagina di manuale man:apm[4]. [[acpi-config]] === Configurare ACPI Il driver [.filename]#acpi.ko# è caricato di default all'avvio dal man:loader[8] e _non_ dovrebbe essere compilato nel kernel. Il ragionamento dietro a questo è che è più facile lavorare coi moduli, ad esempio se si passa ad un altro [.filename]#acpi.ko# senza fare un rebuild del kernel. Questo ha il vantaggio di rendere il testing più facile. Un altro motivo è che avviare ACPI dopo che un sistema è stato riavviato spesso non funziona bene. Se incontri dei problemi, puoi disabilitare completamente ACPI. Questo driver non dovrebbe e non può essere scaricato perchè il bus di sistema lo usa per diverse interazioni hardware. ACPI può essere disabilitato settando `hint.acpi.0.disabled="1"` in [.filename]#/boot/loader.conf# o al prompt del man:loader[8]. [NOTE] ==== ACPI ed APM non possono coesistere e dovrebbero essere usati separatamente. L'ultimo ad essere caricato terminerà se il driver nota che l'altro è già in funzione. ==== ACPI può essere usato per mettere il sistema in modalità sleep con man:acpiconf[8], l'opzione `-s` ed un'opzione `1-5`. La maggior parte degli utenti avranno bisogno solo di `1` o `3` (sospensione della RAM). L'opzione `5` farà un morbido shutdown che è la stessa azione di: [source,shell] .... # halt -p .... Sono disponibili altre opzioni via man:sysctl[8]. Controlla la pagina man di man:acpi[4] e man:acpiconf[8] per maggiori informazioni. [[ACPI-debug]] == Usare e Debuggare ACPI di FreeBSD ACPI è un modo fondamentalmente nuovo di utilizzare dispositivi, gestire le risorse elettriche, e fornire accesso standardizzato all'hardware gestito precedentemente dal BIOS. Si stanno facendo progressi per far funzionare ACPI su tutti i sistemi, ma continuano ad apparire bachi nel codice del _Linguaggio Macchina ACPI_ (AML), incompletezza nel sottosistema kernel di FreeBSD, e bachi nell'interprete ACPI-CA di Intel(R). Questo documento è creato per aiutarti ad assistere i manutentori di ACPI di FreeBSD nell'identificare le cause primarie dei problemi che riscontri e debuggare e sviluppare una soluzione. Grazie per l'attenzione e speriamo di poter risolvere i problemi del tuo sistema. [[ACPI-submitdebug]] === Fornire Informazione di Debug [NOTE] ==== Prima di sottomettere un problema, accertati di avere in esecuzione l'ultima versione del BIOS e, se disponibile, la versione del firmware del controller integrato. ==== Per quelli di voi che vogliono sottomettere un problema subito, per favore inviate la seguente informazione a link:mailto:freebsd-acpi@FreeBSD.org[ freebsd-acpi@FreeBSD.org]: * Descrizione del comportamento affetto da bachi, inclusi il tipo di sistema ed il modello e tutto quello che fa sì che il baco appaia. Inoltre, per favore annotati il più accuratamente possibile quando il baco è iniziato ad apparire se è nuovo per il tuo sistema. * L'output del comando man:dmesg[8] dopo `boot -v`, incluso ogni messaggio di errore generato dal tuo sistema mentre investigavi questo baco. * L'output del comando man:dmesg[8] dopo `boot -v` con ACPI disabilitato, se disabitarlo ti aiuta a rimettere a posto il sistema. * L'output di `sysctl hw.acpi`. Anche questo è un buon modo di figurarti quali caratteristiche il tuo sistema offre. * URL dove il tuo _ACPI Source Language_ (ASL) risiede. _Non_ inviare la ASL direttamente alla lista dato che può essere molto grande. Generate una copia della vostra ASL eseguendo questo comando: + [source,shell] .... # acpidump -dt > name-system.asl .... + (Sostituite _name_ con la vostra login ed il modello/manifattura del _sistema_. Ad esempio [.filename]#njl-FooCoo6000.asl#) Molti degli sviluppatori seguono la {freebsd-current} ma per favore sottomettete i vostri problemi a {freebsd-acpi} per essere sicuri che siano visti. Per favore siate pazienti, abbiamo tutti lavori full-time altrove. Se i vostri bachi non sono chiarissimi, vi chiederemo di sottomettere un PR attraverso man:send-pr[1]. Quando si invia un PR, per favore includete le stesse informazioni sopracitate. Questo aiuterà a tracciare il problema e risolverlo. Non inviare un PR senza prima inviare una email a {freebsd-acpi}, dato che noi usiamo PR come promemoria di problemi esistenti, non come meccanismo di reporting. È probabile che i vostri problemi siano stati riportati da qualcun altro prima. [[ACPI-background]] === Background ACPI è presente su tutti i computer moderni che conformi all'architettura ia32(x86), ia64 (Itanium), e amd64 (AMD). L'intero standard ha molte caratteristiche che includono la gestione della performance della CPU, il controllo dei piani energetici, delle zone termiche, delle batterie del sistema, controller incorporati, ed enumerazione dei bus. Molti sistemi implementano meno dello standard completo. Per esempio, un sistema desktop di solito implementa le parti di enumerazione dei bus mentre un laptop potrebbe avere il raffreddamento ed anche il supporto alla gestione della batteria. I laptop hanno anche sospensioni e riavvii, con la loro complessità associata. Un sistema ACPI-compliant ha molte componenti. Il BIOS ed i venditori di chipset forniscono varie tabelle fisse in memoria (ad esempio FADT) che specificano cose come la mappa APIC (usata per SMP), i registri di configurazione, e semplici valori di configurazione. Inoltre viene fornita una tabella di codici di byte (la _Differentiated System Description Table_ DSDT) per specificare uno spazio dei nomi ad albero di dispositivi e metodi. Il driver ACPI deve fare il parse delle tabelle fisse, implementare un interprete per il codice di byte, e modificare i device driver ed il kernel per accettare informazioni dal sottosistema ACPI. Per FreeBSD, Intel(R) ha fornito un interprete (ACPI-CA) che è condiviso fra Linux e NetBSD. Il path al codice sorgente ACPI-CA è [.filename]#src/sys/contrib/dev/acpica#. Il codice che permette ad ACPI-CA di lavorare con FreeBSD è in [.filename]#src/sys/dev/acpica/Osd#. Finalmente, i driver che implementano vari dispositivi ACPI si trovano in [.filename]#src/sys/dev/acpica#. [[ACPI-comprob]] === Problemi Comuni Affincè ACPI funzioni correttamente tutte le parti devono funzionare correttamente. Ci sono alcuni problemi comuni, in ordine di frequenza di apparizione, ed alcuni possibili workaround o mezzi per aggiustarli. ==== Questioni di Mouse In alcuni casi, ripartire dopo una operazione di sospensione, fa sì che il mouse non riparta. Un noto workaround è aggiungere `hint.psm.0.flags="0x3000"` al file [.filename]#/boot/loader.conf#. Se questo non funziona allora per favore considera l'invio di un report del baco come descritto in precedenza. ==== Sospensione/Riavvio ACPI ha tre stati di sospensione RAM (STR), `S1`-`S3` ed un stato di sospensione disco (`STD`), chiamato `S4`. `S5` è il "soft off" ed è il normale stato in cui il tuo sistema si trova quando è collegato ma non acceso. `S4` può essere implementato in due modi separati. ``S4``BIOS è una sospensione BIOS-assistita da disco. ``S4``OS è implementato direttamente dal sistema operativo. Inizia a controllare `sysctl hw.acpi` per le entry relative alla sospensione. Questi sono i risultati per un Thinkpad: [source,shell] .... hw.acpi.supported_sleep_state: S3 S4 S5 hw.acpi.s4bios: 0 .... Questo significa che possiamo usare `acpiconf -s` per testare `S3`, ``S4``OS, `S5`. Se `s4bios` fosse stato uno (`1`), avremmo supporto a ``S4``BIOS invece di ``S4``OS. Quando si testa la sospensione/riavvio, inizia con `S1`, se supportato. È più probabile che funzioni questo stato dato che non richiede molto supporto dal driver. Nessuno ha implementato `S2`, ma se tu lo hai, è simile a `S1`. La prossima cosa da provare è `S3`. Questo è lo stato più profondo STR e richiede molto supporto dal driver per reinizializzare il tuo hardware. Se hai problemi a riavviarlo, sentiti libero di segnalarlo via mail alla lista {freebsd-acpi} ma non aspettarti che il problema sia risolto dato che ci sono molti driver/hardware che hanno bisogno di test e di lavoro aggiuntivo. Per aiutare ad isolare il problema, rimuovi quanti più driver possibile dal tuo kernel. Se funziona, puoi scoprire quale driver causa il problema caricando dei driver fino a che il problema si ripresenta. Tipicamente i driver binari come [.filename]#nvidia.ko#, i driver di display di X11, e USB avranno la maggior parte dei problemi mentre interfacce Ethernet funzioneranno bene. Se puoi caricare/scaricare driver correttamente, puoi automatizzare questo piazzando i comandi appropriati in [.filename]#/etc/rc.suspend# e [.filename]#/etc/rc.resume#. C'è un esempio commentato su come caricare e scaricare un driver. Prova a impostare `hw.acpi.reset_video` a zero (`0`) se il tuo display è confuso dopo il riavvio. Prova a impostare valori più lunghi o corti per `hw.acpi.sleep_delay` per vedere se aiuta. Un'altra cosa da provare è caricare una distribuzione Linux recente con supporto ACPI e testare il loro supporto sospensione/riavvio sullo stesso hardware. Se funziona su Linux, è probabile che sia un problema driver relativo a FreeBSD e restringere il campo di indagine su quale driver causi il problema può aiutare a risolvere il problema. Notate che i manutentori di ACPI non mantengono altri driver (ad esempio suono, ATA, etc.) così ogni lavoro fatto sull'identificazione del problema del driver dovrebbe alla fine essere risolto dalla lista {freebsd-current} e inviato via mail al manutentore del driver. Se ti senti avventuroso, vai avanti e inizia a porre qualche man:printf[3] in un driver che dà problemi per tracciare in quale driver nella sua funzione di resume vada in palla. Alla fine, cerca di disabilitare ACPI ed ad abilitare APM invece. Se la sospensione ed il riavvio funziona con APM, è meglio che tu continui con APM, specialmente su hardware vecchio (pre-2000). Ci vuole un pò di tempo per i venditori per ottenere un supporto corretto all'ACPI e l'hardware più vecchio è più probabile che abbia problemi BIOS con ACPI. ==== Blocco del Sistema (temporanea o permanente) La maggior parte dei blocchisono causati da interrupt persi o da una tempesta di interrupt. I chipset hanno un sacco di problemi su come il BIOS configuri gli interrupt prima del boot, la correttezza delle tabelle ACPI (MADT) ed il routing del _System Control Interrupt_ (SCI). Le tempeste di interrupt possono essere distinte da interrupt persi controllando l'output di `vmstat -i` e guardando alla linea che riguarda `acpi0`. Se il contatore sta avanzando più di un paio di secondi per volta, hai una tempesta di interrupt. Se il sistema si blocca, cerca di di entrare in DDB (kbd:[CTRL+ALT+ESC] sulla console) e digita `show interrupts`. Il modo migliore in caso di problemi di interrupt è provare a disabilitare il supporto APIC con `hint.apic.0.disabled="1"` in [.filename]#loader.conf#. ==== Panici I panici sono relativamente rari per ACPI e sono il primo problema ad essere corretto. Il primo passo da fare è riprodurre il panico (se possibile) ed ottenere un backtrace. Segui l'avvertimento per abilitare `options DDB` e imposta una console seriale (vedi la crossref:serialcomms[serialconsole-ddb,Accesso al Debugger DDB dalla Linea Seriale]) o imposta una partizione di man:dump[8]. Puoi ottenere un backtrace in DDB con `tr`. Se hai scritto a mano il backtrace, accertati di ottenere le ultime cinque (5) e le prime cinque (5) linee nella traccia. Poi, prova ad isolare il problema facendo boot con ACPI disabilitato. Se funziona, puoi isolare il sottosistema ACPI usando vari valori di `debug.acpi.disable`. Leggi la pagina di manuale di man:acpi[4] per alcuni esempi. ==== Riavvii di sistema dopo Sospensioni o Spegnimenti Prima, cerca di impostare `hw.acpi.disable_on_poweroff="0"` in man:loader.conf[5]. Questo fa sì che ACPI abbia disabilitato alcuni eventi durante il processo di shutdown. Alcuni sistemi hanno bisogno di impostare questo valore a `1` (il default) per la stessa ragione. Questo di solito aggiusta il problema di un sistema che si accende spontaneamente dopo una sospensione o uno spegnimento. ==== Altri problemi Se hai altri problemi con ACPI (lavorare con un docking station, dispositivi non trovati, ecc.), per favore invia via mail una descrizione anche alla mailing list; comunque, alcune di queste questioni possono essere correlate a parti del sottosistema ACPI così può volerci un pò prima che siano implementate. Per favore sii paziente e preparato a testare le patch che ti vengono inviate. [[ACPI-aslanddump]] === ASL, `acpidump`, e IASL Il più comune problema è il BIOS di venditori che forniscono bytecode incorretto (o addirittura con bachi). Questo si deduce usualmente da messaggi del kernel come questo: [source,shell] .... ACPI-1287: *** Error: Method execution failed [\\_SB_.PCI0.LPC0.FIGD._STA] \\ (Node 0xc3f6d160), AE_NOT_FOUND .... Spesso puoi risolvere questi problemi aggiornando il tuo BIOS all'ultima versione. La maggior parte dei messaggi di console non indica nulla di notevole, ma se hai altri problemi come lo stato della batteria non funzionante, questi sono un buon inizio per iniziare a cercare problemi in AML. Il bytecode, noto come AML, è compilato da un insieme di codici sorgenti chiamato ASL. L'AML, è trovato nella tabella nota come come DSDT. Per trovare una copia del tuo ASL usa man:acpidump[8]. Dovresti usare entrambe le opzioni `-t` (mostra i contenuti della tabella fissa) e la `-d` (disassembla AML ad ASL). Vedi la sezione <> per un esempio della sintassi. Il tuo primo controllo che puoi fare è ricompilare il tuo ASL per controllare errori. Possono essere ignorati i 'warning' ma gli errori sono bachi che impediranno all'ACPI di funzionare correttamente. Per ricompilare il tuo ASL, usa il comando seguente: [source,shell] .... # iasl your.asl .... [[ACPI-fixasl]] === Aggiustare il tuo ASL Alla lunga, il nostro obiettivo è avere ACPI che funzioni per tutti senza intervento. A questo punto, comunque stiamo ancora sviluppando workaround per errori comuni fatti dal venditore del BIOS. L'interprete Microsoft(R) ([.filename]#acpi.sys# e [.filename]#acpiec.sys#) non è strettamente conforme agli standard, e così molti venditori BIOS che testano solo ACPI sotto Windows(R) non aggiustano mai il loro ASL. Vogliamo continuare a identificare e documentare esattamente quali comportamenti non standard sono concessi dall'interprete Microsoft(R) e replicarlo cosicchè FreeBSD può funzionare senza forzare gli utenti ad usare ASL. Come workaround e per aiutarci ad identificare il comportamento puoi fissare la ASL manualmente. Se questo funziona per favore invia un man:diff[1] del vecchio e del nuovo ASL, cosicchè possiamo lavorare attorno al comportamento bacato di ACPI-CA e così rimettere a posto il necessario. Qui c'è una lista di messaggi di errori comuni, le loro cause e come fissarli: ==== Dipendenze OS Alcuni AML assumono che il mondo consiste di varie versioni Windows(R). Puoi far sì che FreeBSD simuli qualsiasi OS per vedere se questo risolve il problema che hai. Un modo facile per sovrascrivere questo è porre `hw.acpi.osname="Windows 2001"` in [.filename]#/boot/loader.conf# o altre stringhe simili che trovi nella ASL. ==== Valori di Ritorno Mancanti Alcuni metodi non ritornano esplicitamente un valore come i requisiti standard. Mentre ACPI-CA non gestisce questo, FreeBSD ha un workaround che permette di ritornare i valori implicitamente. Puoi anche aggiungere espliciti Valori di Ritorno dove si richiede se sai quale valore dovrebbe essere ritornato. Per forzare `iasl` a compilare l'ASL usa il flag `-f`. ==== Sovrascrivere il Default AML Dopo che personalizzi il tuo [.filename]#your.asl#, potresti volerlo compilare, esegui: [source,shell] .... # iasl your.asl .... Puoi aggiungere il flag `-f` per forzare la creazione dell'AML, anche se ci sono errori durante la compilazione. Ricorda che alcuni errori (ad esempio valori di Ritorno mancanti) sono automaticamente riaggiustati dall'interprete. [.filename]#DSDT.aml# è il nome del file di default del comando `iasl`. Puoi caricare questo invece della copia difettosa del tuo BIOS (che è ancora presente in memoria) editando il file [.filename]#/boot/loader.conf# come segue: [.programlisting] .... acpi_dsdt_load="YES" acpi_dsdt_name="/boot/DSDT.aml" .... Assicurati di copiare il tuo file [.filename]#DSDT.aml# nella directory [.filename]#/boot#. [[ACPI-debugpoint]] === Ottenere Output di Debug da ACPI Il driver ACPI ha una facility di debug molto utile. Permette di specificare un insieme di sottosistemi come anche un livello di verbosità. I sottosistemi che desideri debuggare sono specificati come "strati" e sono divisi in componenti ACPI-CA (ACPI_ALL_COMPONENTS) e supporto hardware ACPI (ACPI_ALL_DRIVERS). La verbosità dell'output di debug è specificata come "livello" e varia da ACPI_LV_ERROR (riporta solo gli errori) ad ACIP_LV_VERBOSE (tutto). Il "livello" è una bitmask che fa sì che molte opzioni possano essere impostate una alla volta, separate da spazi. In pratica, puoi usare una console seriale per loggare l'output se è così lungo da riempire il buffer di messaggi della console. Una lista completa degli strati individuali e dei livelli è disponibile nella pagina man man:acpi[4]. L'output di debug non è abilitato di default. Per abilitarlo, aggiungi `options ACPI_DEBUG` al tuo file di configurazione del kernel se ACPI è compilato nel kernel. Puoi aggiungere `ACPI_DEBUG=1` al tuo [.filename]#/etc/make.conf# per abilitarlo in modo globale. Se è un modulo, puoi ricompilare soltanto il tuo modulo [.filename]#acpi.ko# come segue: [source,shell] .... # cd /sys/modules/acpi/acpi && make clean && make ACPI_DEBUG=1 .... Installa [.filename]#acpi.ko# in [.filename]#/boot/kernel# ed aggiungi il tuo livello desiderato e gli strati in [.filename]#loader.conf#. Questo esempio abilita i messaggi per tutti i componenti ACPI-CA e tutti i driver hardware ACPI (CPU, LID, etc.). Produrrà solo messaggi di errore, i meno verbosi. [.programlisting] .... debug.acpi.layer="ACPI_ALL_COMPONENENTS ACPI_ALL_DRIVERS" debug.acpi.level="ACPI_LV_ERROR" .... Se l'informazione che vuoi ottenere è prodotta da un evento specifico (ad esempio, una sospensione ed un riavvio), puoi tralasciare i cambiamenti di [.filename]#loader.conf# ed invece usare `sysctl` per specificare lo strato ed il livello dopo il boot e preparare il tuo sistema per l'evento specifico. I `sysctl` sono nominati allo stesso modo dei parametri in [.filename]#loader.conf#. [[ACPI-References]] === Riferimenti Maggiori informazioni su ACPI possono essere trovate nei seguenti posti: * La {freebsd-acpi} * Gli archivi della mailing list ACPI http://lists.freebsd.org/pipermail/freebsd-acpi/[http://lists.freebsd.org/pipermail/freebsd-acpi/] * I vecchi archivi della mailing list ACPI http://home.jp.FreeBSD.org/mail-list/acpi-jp/[http://home.jp.FreeBSD.org/mail-list/acpi-jp/] -* La specificazione ACPI 2.0 http://acpi.info/spec.htm[http://acpi.info/spec.htm] +* La https://uefi.org/specifications#ACPI[specificazione ACPI] * Le pagine man di FreeBSD: man:acpi[4], man:acpi_thermal[4], man:acpidump[8], man:iasl[8], man:acpidb[8] * http://www.cpqlinux.com/acpi-howto.html#fix_broken_dsdt[ Le risorse di debugging di DSDT]. (Usa Compaq come esempio ma è sempre utile.) diff --git a/documentation/content/mn/books/handbook/config/_index.adoc b/documentation/content/mn/books/handbook/config/_index.adoc index 8aa7fcdd11..01cb4ed002 100644 --- a/documentation/content/mn/books/handbook/config/_index.adoc +++ b/documentation/content/mn/books/handbook/config/_index.adoc @@ -1,1459 +1,1459 @@ --- title: Бүлэг 12. Тохиргоо ба Тааруулалт part: хэсэг III. Системийн Удирдлага prev: books/handbook/partiii next: books/handbook/boot showBookMenu: true weight: 16 path: "/books/handbook/" --- [[config-tuning]] = Тохиргоо ба Тааруулалт :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 12 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/config/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[config-synopsis]] == Ерөнхий агуулга FreeBSD-ийн хамгийн чухал зүйлүүдийн нэг нь системийн тохиргоо юм. Зөв системийн тохиргоо нь ирээдүйн шинэчлэлтүүдийн үед толгойн өвчин гаргахгүй байхад тусална. Энэ бүлэг FreeBSD системийг тааруулахад хэрэглэгддэг зарим нэг параметрүүд болон тохиргооны процессийн талаар илүү тайлбарлах болно. Энэ бүлгийг уншсаны дараа, та дараах зүйлсийг мэдэх болно: * Файлын системүүд болон хуваалтуудтай хэрхэн үр ашигтай ажиллах талаар. * [.filename]#rc.conf# тохиргоо болон [.filename]#/usr/local/etc/rc.d# эхлэлийн системүүдийн үндсүүд. * Сүлжээний картыг хэрхэн тохиргоо болон тест хийх талаар. * Сүлжээний төхөөрөмж дээрээ виртуал хостууд хэрхэн тохируулах талаар. * [.filename]#/etc# дэх төрөл бүрийн тохиргооны файлыг хэрхэн ашиглах талаар. * `sysctl` хувьсагчуудыг ашиглан FreeBSD-ийг хэрхэн тааруулах талаар. * Дискний хурдан ажиллагааг хэрхэн тааруулах болон цөмийн хязгааруудыг хэрхэн өөрчлөх талаар. Энэ бүлгийг уншихаасаа өмнө, та дараах зүйлсийг мэдэх шаардлагатай: * UNIX(R) болон FreeBSD-ийн үндсийг ойлгох (crossref:basics[basics,Юниксийн үндэс]). * Цөмийн тохиргоо/хөрвүүлэлтийн үндсүүдийн талаар ойлголттой байх (crossref:kernelconfig[kernelconfig,FreeBSD цөмийг тохируулах нь]). [[configtuning-initial]] == Эхний Тохиргоо === Хуваалтын байрлал ==== Үндсэн Хуваалтууд man:bsdlabel[8] болон man:sysinstall[8] ашиглан файлын системүүдийг байрлуулахдаа хатуу хөтлөгчүүд өгөгдлийг дотоод замуудаас илүү гаднах замуудаас хурдан шилжүүлдгийг санаарай. Тиймээс жижиг, байнга ханддаг файлын системүүд хөтлөгчийн гадна тал уруу ойрхон байх ёстой бөгөөд [.filename]#/usr# зэрэг том хуваалтууд дискийн дотор тал уруу байх хэрэгтэй. Хуваалтуудыг иймэрхүү дарааллаар байрлуулах нь зөв юм: root, swap, [.filename]#/var#, [.filename]#/usr#. [.filename]#/var# хуваалтын хэмжээ төлөвлөсөн машины хэрэглээг тусгадаг. [.filename]#/var# файлын систем нь шуудангийн хайрцгууд, бүртгэлийн файлууд, болон принтерийн spool агуулдаг. Шуудангийн хайрцгууд болон бүртгэлийн файлууд хичнээн хэрэглэгч байгаа болон ямар хугацаанд бүртгэлийн файлууд байхаас хамаараад төсөөлөшгүй хэмжээнд хүртэл ихсэж болдог. Ихэнх хэрэглэгчдийн хувьд [.filename]#/var#-д нэг гигабайт сул зай байхад хангалттай байдаг. [NOTE] ==== [.filename]#/var/tmp#-д ихээхэн хэмжээний дискийн зай шаардагддаг цөөхөн тохиолдол байдаг. Шинэ програм хангамжийг man:pkg_add[1] ашиглан суулгахад багцлах хэрэгслүүд багцын түр зуурын хуулбарыг [.filename]#/var/tmp#-д задалдаг. [.filename]#/var/tmp#-д хангалттай дискийн чөлөөтэй зай байхгүй бол Firefox, OpenOffice эсвэл LibreOffice зэрэг томоохон програм хангамжийн багцуудыг суулгахад төвөгтэй байж болох юм. ==== [.filename]#/usr# хуваалт man:ports[7] цуглуулга (байлгахыг зөвлөдөг), болон эх код (заавал биш) зэрэг системийг дэмжихэд шаардлагатай ихэнх файлуудыг агуулдаг. Портууд болон үндсэн системийн эхүүдийг суулгалтын үед сонгох боломжтой боловч бид энэ хуваалтад хамгийн багаар бодоход 2 гигабайт байхыг зөвлөдөг. Хуваалтын хэмжээг сонгохдоо зайн шаардлагыг бодох хэрэгтэй. Нэг хуваалт нь бараг л ашиглагдахгүй байхад нөгөө нь зайгүй болж байх нь асуудал юм. [NOTE] ==== man:sysinstall[8]-ийн `Auto-defaults` хуваалтын хэмжээг өгөгч нь заримдаа [.filename]#/var# болон [.filename]#/# хуваалтуудад боломжоос бага хэмжээг сонгодгийг зарим хэрэглэгчид олсон байна. Хуваалтыг ухаалгаар харамгүй хийгээрэй. ==== [[swap-design]] ==== Swap Хуваалт Swap хуваалтын хэмжээ системийн санах ойг (RAM) хоёр дахин авсан хэмжээтэй байх ёстой. Жишээлбэл машин 128 мегабайт санах ойтой бол swap файл 256 мегабайт байх ёстой. Бага санах ойтой системүүд их swap-тай бол илүү хурдан ажиллаж болох юм. 256 мегабайтаас бага swap-ийг хэрэглэхийг зөвлөдөггүй бөгөөд санах ойн өргөтгөл хэрэгтэй. Цөмийн VM хуудаслах алгоритмууд нь багаар бодоход гол санах ойг хоёр дахин авсантай тэнцэх swap хуваалттай байх үед хамгийн хурдан ажиллахаар тааруулагдсан байдаг. Хэтэрхий бага swap тохируулах нь VM хуудас скан хийх кодыг үр ашиггүйтэлд хүргэж илүү санах ой хожим нэмэхэд асуудал үүсгэж болох юм. Олон SCSI дискнүүд бүхий (эсвэл олон IDE дискнүүд өөр өөр хянагчууд дээр ажиллаж байгаа) томоохон системүүдэд swap-ийг хөтлөгч болгон дээр (4 хөтлөгч хүртэл) тохируулахыг зөвлөдөг. Swap хуваалтууд нь ойролцоогоор адилхан хэмжээний байх шаардлагатай. Цөм дурын хэмжээтэй ажиллаж чадах боловч дотоод өгөгдлийн бүтцүүд хамгийн том swap хуваалтыг 4 дахин авсантай адил хэмжээгээр томрох боломжтой. Swap хуваалтуудыг ойролцоогоор адил хэмжээтэй байлгах нь swap зайг дискнүүдийн дагуу оновчтойгоор судал үүсгэх боломжийг цөмд олгодог. Swap их ашиглагддаггүй байсан ч гэсэн том swap хэмжээ байж болно. Хүчээр дахин ачаалагдах үед дагаж хаагдсан програмаас өгөгдлийг сэргээх нь амархан байж болох юм. ==== Яагаад Хуваах хэрэгтэй гэж? Зарим хэрэглэгчид ганц том хуваалт байхад болно гэж боддог, гэхдээ энэ нь яагаад буруу болох хэд хэдэн шалтгаан бий. Нэгдүгээрт хуваалт болгон өөр өөр ажиллагааны шинж чанаруудтай бөгөөд тэдгээрийг тусгаарласнаар файлын системийг тэдгээрт тааруулах боломжийг олгодог. Жишээ нь root болон [.filename]#/usr# хуваалтууд байнга бичигдэхээсээ илүү ихэвчлэн уншигддаг. Харин уншилт болон бичилт [.filename]#/var# болон [.filename]#/var/tmp#-д байнга хийгддэг. Системийг зөв хувааснаар ачаалалтай хуваалтуудад хийсэн жижиг бичилтээр гарсан хэсэглэлт илүүдэж байнга уншигддаг хуваалтууд уруу хальдаггүй. Бичилт-ачаалсан хуваалтуудыг дискний ирмэг уруу байрлуулах нь бичилт ихэвчлэн хийгддэг хуваалтууд дахь I/O ажиллагааг хурдасгадаг. Том хуваалтуудад I/O-н хурдан ажиллагаа хэрэгтэй байж болох ч тэдгээрийг дискний ирмэг уруу илүүтэй ойртуулах нь [.filename]#/var#-ийг ирмэг уруу шилжүүлснээс илүү мэдэгдэхүйц хурдан ажиллагаанд хүргэхгүй. Эцэст нь найдвартай байдлыг бодох ёстой. Ихэвчлэн уншигддаг, жижиг, цэвэрхэн root хуваалт хэцүү сүйрэл болоход сэргэх боломж нь хамаагүй илүү байна. [[configtuning-core-configuration]] == Гол Тохиргоо Системийн тохиргооны мэдээлэл [.filename]#/etc/rc.conf# дотор байдаг. Энэ файл нь өргөн хүрээний, зарчмын хувьд системийг эхлэх үед системийг тохируулахад ашиглагддаг тохиргооны мэдээллүүдээс тогтоно. Үүний нэр нь шууд утгыг тодорхойлно; энэ нь [.filename]#rc*# файлуудад зориулсан тохиргооны мэдээлэл юм. Администратор [.filename]#/etc/defaults/rc.conf#-ийн анхдагч утгуудыг [.filename]#rc.conf# файлд өөрчилж оруулах хэрэгтэй. Анхдагчуудын файл [.filename]#/etc# уруу хуулагдах ёсгүй - энэ нь жишээ биш анхдагч утгуудыг агуулдаг. Бүх системийн холбогдолтой өөрчлөлтүүд [.filename]#rc.conf# файлд өөрт нь хийгдэх ёстой. Удирдлагын нэмэлт ачааллыг байнга бага байлгахын тулд сайт дагуух тохиргоог системийн тусгайлсан тохиргооноос тусгаарлах хэд хэдэн стратеги кластер хийгдсэн програмуудад байж болох юм. Тухайн системийн тохиргоог [.filename]#/etc/rc.conf.local# файлд байрлуулах нь зүйтэй. Жишээ нь: * [.filename]#/etc/rc.conf#: + [.programlisting] .... sshd_enable="YES" keyrate="fast" defaultrouter="10.1.1.254" .... * [.filename]#/etc/rc.conf.local#: + [.programlisting] .... hostname="node1.example.org" ifconfig_fxp0="inet 10.1.1.1/8" .... Дараа нь [.filename]#rc.conf# файл систем болгонд `rsync` эсвэл адил програмаар түгээгдэж болох бөгөөд харин [.filename]#rc.conf.local# файл нь өөр өөр хэвээр байх болно. man:sysinstall[8] эсвэл `make world` ашиглан системийг шинэчлэхэд [.filename]#rc.conf# файлыг дарж бичихгүй, тэгэхээр системийн тохиргооны мэдээлэл хаягдахгүй. [TIP] ==== [.filename]#/etc/rc.conf# тохиргооны файлыг man:sh[1]-р уншуулдаг. Энэ нь системийн операторуудад уг файлд тодорхой хэмжээний логик нэмэх боломжийг олгодог бөгөөд ингэснээр илүү нарийн төвөгтэй тохиргооны хувилбарууд үүсгэхэд тусалдаг. Энэ талаар дэлгэрэнгүйг man:rc.conf[5]-с үзнэ үү. ==== [[configtuning-appconfig]] == Програмын Тохиргоо Ерөнхийдөө суулгасан програмууд нь өөрийн дүрэм гэх мэт онцлогтой өөр өөрийн тохиргооны файлуудтай байдаг. Эдгээр файлуудыг багц удирдах хэрэгслүүдээр амархан олж удирдаж болохоор үндсэн системээс тусад нь байлгах нь чухал юм. Ерөнхийдөө эдгээр файлууд нь [.filename]#/usr/local/etc# дотор суулгагддаг. Програм их олон тооны тохиргооны файлуудтай тохиолдолд тэдгээрийг агуулж дэд сан үүсгэгдэнэ. Ихэнхдээ порт эсвэл багц суухад жишээ тохиргооны файлууд бас суудаг. Эдгээр нь ихэнхдээ [.filename]#.default# дагавраар танигддаг. Хэрэв програмын хувьд тохиргооны файлууд байхгүй байвал тэдгээрийг [.filename]#.default# файлуудыг хуулж үүсгэнэ. Жишээ нь [.filename]#/usr/local/etc/apache# санд байгаа файлуудыг үзье: .... -rw-r--r-- 1 root wheel 2184 May 20 1998 access.conf -rw-r--r-- 1 root wheel 2184 May 20 1998 access.conf.default -rw-r--r-- 1 root wheel 9555 May 20 1998 httpd.conf -rw-r--r-- 1 root wheel 9555 May 20 1998 httpd.conf.default -rw-r--r-- 1 root wheel 12205 May 20 1998 magic -rw-r--r-- 1 root wheel 12205 May 20 1998 magic.default -rw-r--r-- 1 root wheel 2700 May 20 1998 mime.types -rw-r--r-- 1 root wheel 2700 May 20 1998 mime.types.default -rw-r--r-- 1 root wheel 7980 May 20 1998 srm.conf -rw-r--r-- 1 root wheel 7933 May 20 1998 srm.conf.default .... Файлын хэмжээнүүд нь зөвхөн [.filename]#srm.conf# файл өөрчлөгдсөнийг харуулж байна. Apache портын дараагийн шинэчлэл энэ өөрчлөгдсөн файлыг дарж хуулахгүй. [[configtuning-starting-services]] == Үйлчилгээнүүдийг эхлүүлэх нь Олон хэрэглэгчид Портуудын Цуглуулгаас гуравдагч програм хангамжуудыг FreeBSD дээр суулгахаар сонгодог. Ихэнх тохиолдолд програм хангамжийг систем ачаалахад эхлүүлэхээр тохируулах шаардлагатай байж болох юм. package:mail/postfix[] эсвэл package:www/apache22[] зэрэг үйлчилгээнүүд нь системийг ачаалахад эхлүүлж болох програм хангамжийн багцуудын зөвхөн хоёрхон жишээ юм. Энэ хэсэгт гуравдагч програм хангамжийг ажиллуулах процедурын талаар тайлбарлах болно. FreeBSD дээр man:cron[8] зэрэг ихэнх үйлчилгээнүүд системийн эхлүүлэх скриптүүдийн тусламжтай эхэлдэг. Эдгээр скриптүүд FreeBSD эсвэл үйлдвэрлэгчийн хувилбараас хамааран өөр өөр байна; гэхдээ хамгийн чухал авч үзэх зүйл нь тэдгээрийн эхлэх тохиргоог энгийн эхлүүлэх скриптүүдээр хийх боломжтой явдал юм. === Програмын Өргөтгөсөн Тохиргоо Одоогийн FreeBSD-ийн [.filename]#rc.d#-г агуулдаг нь програмын эхлүүлэх тохиргоог илүү хялбар, боломжтой болгосон. <> хэсэгт хэлэлцсэн түлхүүр үгүүдийг ашиглан програмууд жишээ нь DNS зэрэг зарим үйлчилгээнүүдийн дараа ажиллахаар тохируулагдаж болно; эхлүүлэх скриптүүдэд хатуугаар бичигдсэн тугуудын оронд [.filename]#rc.conf#-оор нэмэлт тугуудыг өгөхийг зөвшөөрч болох гэх мэт. Үндсэн скрипт дараах байдлаар харагдаж болно: [.programlisting] .... #!/bin/sh # # PROVIDE: utility # REQUIRE: DAEMON # KEYWORD: shutdown . /etc/rc.subr name="utility" rcvar=utility_enable command="/usr/local/sbin/utility" load_rc_config $name # # DO NOT CHANGE THESE DEFAULT VALUES HERE # SET THEM IN THE /etc/rc.conf FILE # utility_enable=${utility_enable-"NO"} pidfile=${utility_pidfile-"/var/run/utility.pid"} run_rc_command "$1" .... Энэ скрипт нь өгөгдсөн utility-г `DAEMON` псевдо үйлчилгээний дараа ажиллуулахаар тохируулагдсан. Мөн PID, эсвэл процессийн ID файлыг заах болон дагах аргыг бас хангадаг. Энэ програм дараах мөрийг [.filename]#/etc/rc.conf# файлд оруулж болно: [.programlisting] .... utility_enable="YES" .... Энэхүү арга нь тушаалын мөрийн нэмэлт өгөгдлүүдийг илүү хялбараар удирдах боломжийг зөвшөөрдөг бөгөөд [.filename]#/etc/rc.subr# дахь анхдагч функцуудыг оруулах, man:rcorder[8] хэрэгсэлтэй нийцтэй байх, болон [.filename]#rc.conf# файлын тусламжтай хялбараар тохиргоо хийх боломжийг бас хангадаг. === Үйлчилгээнүүдийг эхлүүлэхийн тулд үйлчилгээнүүдийг ашиглах нь POP3 сервер дэмонууд, IMAP зэрэг бусад үйлчилгээнүүд man:inetd[8] ашиглан эхэлж болдог. Энэ нь Портуудын Цуглуулгаас [.filename]#/etc/inetd.conf# файлд нэмэгдэх мөр бүхий эсвэл одоогийн байгаа мөрүүдийн нэгнээс тайлбарыг болиулж идэвхжүүлдэг үйлчилгээний хэрэгслийг суулгаснаар хэрэгждэг. inetd болон түүний тохиргоотой ажиллах талаар crossref:network-servers[network-inetd,inetd] хэсэгт гүнзгий тайлбарласан байгаа болно. Зарим тохиолдолд man:cron[8] ашиглан системийн үйлчилгээнүүдийг эхлүүлэх нь илүү ашигтай байж болох юм. Энэ арга нь хэд хэдэн давуу талуудтай бөгөөд учир нь `cron` эдгээр процессуудыг [.filename]#crontab#-н файлын эзэмшигчийн эрхээр ажиллуулдаг. Энэ нь ердийн хэрэглэгчдэд зарим програмуудыг эхлүүлж ажиллагааг хангах боломжийг олгодог. `cron` хэрэгсэл `@reboot` гэсэн бусдад байхгүй боломжийг олгодог бөгөөд цаг хугацааг заах хэсэгт ашиглагдах боломжтой. Энэ нь системийг эхлүүлэх явцад man:cron[8] эхлэх үед тухайн ажлыг ажиллуулдаг. [[configtuning-cron]] == `cron` хэрэгслийг тохируулах нь FreeBSD-ийн хамгийн ашигтай хэрэгслүүдийн нэг нь man:cron[8] юм. `cron` хэрэгсэл ард ажилладаг бөгөөд [.filename]#/etc/crontab# файлыг байнга шалгаж байдаг. `cron` хэрэгсэл [.filename]#/var/cron/tabs# сангаас шинэ [.filename]#crontab# файлуудыг бас шалгадаг. Эдгээр [.filename]#crontab# файлууд нь тусгай функцуудыг агуулдаг бөгөөд эдгээрийг `cron` тодорхой хугацаанд ажиллуулах ёстой байдаг. `cron` хэрэгсэл системийн crontab болон хэрэглэгчийн crontab гэсэн хоёр төрлийн тохиргооны файлыг ашигладаг. Энэ хоёр хэлбэршилтийн зөвхөн ялгаа нь зургаа дахь талбараас хойш юм. Системийн crontab дээр `cron` тушаал зургаа дахь талбар дээр зааж өгсөн хэрэглэгчээр тушаалыг ажиллуулна. Хэрэглэгчийн crontab дээр crontab үүсгэсэн хэрэглэгчээр бүх тушаалыг ажиллуулах ба зургаа дахь талбар нь хамгийн сүүлийн талбар юм; энэ нь аюулгүй байдлын нэг чухал боломж юм. [NOTE] ==== Хэрэглэгчийн crontab-ууд нь хэрэглэгчдэд `root` эрхийн шаардлагагүйгээр бодлогуудыг цагийн хуваариар ажиллуулах боломж олгодог. Хэрэглэгчийн crontab дахь тушаалууд нь crontab-ийг эзэмшиж байгаа хэрэглэгчийн эрхээр ажилладаг. `root` хэрэглэгч бас бусад хэрэглэгчийн нэгэн адил хэрэглэгчийн crontab-тай байж болно. `root` хэрэглэгчийн crontab нь [.filename]#/etc/crontab#-аас (системийн crontab) тусдаа байна. Яагаад гэвэл системийн crontab нь заасан тушаалуудыг root эрхээр ажиллуулдаг учраас `root` хэрэглэгчийн хувьд ихэнхдээ хэрэглэгчийн crontab шаардлагагүй байдаг. ==== Системийн crontab [.filename]#/etc/crontab# файлыг харцгаая: [.programlisting] .... # /etc/crontab - root's crontab for FreeBSD # # $FreeBSD: src/etc/crontab,v 1.32 2002/11/22 16:13:39 tom Exp $ ## <.> # SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin <.> HOME=/var/log # # #minute hour mday month wday who command <.> # # */5 * * * * root /usr/libexec/atrun <.> .... <.> FreeBSD-ийн ихэнх тохиргооны файлуудын адил `#` тэмдэгтээр эхэлсэн мөрүүд тайлбар юм. Тайлбарыг хүсэж байгаа үйлдэл нь юу болох яагаад хийгдэж байгааг сануулах зорилгоор файлд тавьж болдог. Тайлбаруудыг тушаал байгаа мөрд хийж болохгүй бөгөөд ингэсэн тохиолдолд тушаалын хэсэг мэтээр ойлгогдоно; тэдгээр нь шинэ мөрөнд байх ёстой. Хоосон мөрүүдийг тооцохгүй. <.> Эхлээд орчин тодорхойлогдох шаардлагатай. Тэнцүүгийн (`=`) тэмдэг орчны тохиргоог тодорхойлоход ашиглагддаг бөгөөд энэ жишээн дээр `SHELL`,`PATH`, болон `HOME` тохируулгуудад ашиглагдаж байна. Хэрэв бүрхүүлийн мөрийг орхисон бол `cron` анхдагч болох `sh`-ийг ашигладаг. Хэрэв `PATH` хувьсагчийг орхисон бол ямар ч анхдагч ашиглагдахгүй бөгөөд файлын байрлалууд абсолют байх хэрэгтэй. Хэрэв `HOME` мөрийг орхисон бол `cron` ажиллуулж байгаа хэрэглэгчийн гэрийн санг ашигладаг. <.> Энэ мөр нь нийт долоон талбарыг тодорхойлдог. Энд жагсаагдсан утгууд нь `minute`, `hour`, `mday`, `month`, `wday`, `who`, болон `command` юм. Эдгээрийг нэрээс нь харахад ойлгомжтой. `minute` нь тушаал ажиллах минутаар илэрхийлэгдсэн хугацаа. `hour` нь `minute`-ын адил тохируулга бөгөөд цагаар илэрхийлэгддэг. `mday` нь сарын өдрийг заана. `month` нь `hour` болон `minute`-тай адил бөгөөд сарыг зааж өгнө. `wday` тохируулга нь долоо хоногийн өдрийг заана. Эдгээр бүх талбарууд нь тоон утга байх ёстой бөгөөд хорин дөрвөн цагийг дагадаг. `who` талбар нь тусгай бөгөөд зөвхөн [.filename]#/etc/crontab# файлд байдаг. Энэ талбар нь аль хэрэглэгчийн эрхээр тушаал ажиллахыг заадаг. Сүүлийн талбар нь ажиллуулах тушаалд зориулагдсан байна. <.> Энэ сүүлийн мөр нь дээр дурдсан утгуудыг тодорхойлдог. Энд бид хэд хэдэн `*` тэмдэгтүүд дараалсан `*/5` гэсэн жагсаалт байгааг анзаарах хэрэгтэй. Эдгээр `*` тэмдэгтүүд нь "эхний-эцсийн" гэсэн үг бөгөөд _үргэлж_ гэж ойлгогдож болно. Тэгвэл энэ мөрөөс үзэхэд `atrun` тушаал нь `root` эрхээр 5 минут тутам аль өдөр сар байгаагаас үл хамааран ажиллана. `atrun` тушаалын талаар дэлгэрэнгүй мэдээллийг man:atrun[8] гарын авлагаас үзнэ үү.Тушаалууд тэдгээрт өгч болох дурын тооны тугуудтай байж болно; гэхдээ олон мөр болон уртассан тушаалууд урагшаа ташуу "\" үргэлжлүүлэх тэмдэгтээр хуваагдсан байх ёстой. Энэ нь [.filename]#crontab# файл болгоны хувьд үндсэн тохиргоо байна, гэхдээ нэг зүйл нь үүнээс өөр байна. Хэрэглэгчийг заадаг зургаа дахь талбар нь зөвхөн системийн [.filename]#/etc/crontab# файлд байна. Энэ талбарыг хэрэглэгчийн [.filename]#crontab# файлуудын хувьд орхих хэрэгтэй. [[configtuning-installcrontab]] === Crontab суулгах нь [IMPORTANT] ==== Та энд тайлбарласан процедурыг ашиглан системийн crontab [.filename]#/etc/crontab#-ийг засаж болон суулгах хэрэггүй. Зүгээр л өөрийн дуртай засварлагчийг ашигла: `cron` хэрэгсэл файл өөрчлөгдсөнийг мэдээд тэр даруй шинэчлэгдсэн хувилбарыг ашиглаж эхэлнэ. Дэлгэрэнгүй мэдээллийг extref:{faq}[Энэ БХА-ын оруулгаас, ROOT-NOT-FOUND-CRON-ERRORS] үзнэ үү. ==== Хэрэглэгчийн бичсэн шинэ [.filename]#crontab# файлыг суулгахын тулд эхлээд өөрийн дуртай засварлагчийг ашиглаад зөв хэлбэршилттэй файл үүсгээд дараа нь `crontab` хэрэгслийг ашигла. Хамгийн их ашиглагддаг тушаал бол: [source,shell] .... % crontab crontab-file .... Энэ жишээн дээрх [.filename]#crontab-file# нь урд нь үүсгэгдсэн [.filename]#crontab#-ийн файлын нэр юм. Суулгасан [.filename]#crontab# файлуудыг үзүүлдэг тохируулга бас байдаг: `-l` тохируулгыг `crontab` уруу өгч ажиллуулаад гарах үр дүнг хараарай. Өөрийн crontab файлыг загвар ашиглалгүйгээр эхнээс нь эхлүүлэхийг хүссэн хэрэглэгчдэд зориулсан `crontab -e` тохируулга байдаг. Энэ нь сонгосон засварлагчийг хоосон файлтай ажиллуулдаг. Файл хадгалагдсаны дараа автоматаар `crontab` тушаалаар суулгагддаг. Хэрэглэгчийн [.filename]#crontab#-ийг бүр мөсөн устгахыг хүсвэл `crontab`-ийг `-r` тохируулгатай ашиглаарай. [[configtuning-rcd]] == FreeBSD дээр man:rc[8] ашиглах нь 2002 онд FreeBSD системийг эхлүүлэхэд зориулж NetBSD-ийн [.filename]#rc.d# системийг оруулсан. Хэрэглэгчид [.filename]#/etc/rc.d# сан доторх файлуудыг анзаарах хэрэгтэй. Эдгээр файлуудын ихэнх нь `start`, `stop`, болон `restart` тохируулгуудаар хянагддаг үндсэн үйлчилгээнүүд байдаг. Жишээ нь man:sshd[8] нь дараах тушаалаар дахин эхлэж болно: [source,shell] .... # /etc/rc.d/sshd restart .... Энэ процедур нь бусад үйлчилгээнүүдийн адил юм. Мэдээж үйлчилгээнүүд ихэнхдээ автоматаар man:rc.conf[5]-д зааснаар ачаалах үед эхэлдэг. Жишээ нь Сүлжээний Хаяг Хөрвүүлэх дэмонг эхлэх үед ажиллуулахаар нээх нь амархан бөгөөд [.filename]#/etc/rc.conf#-д дараах мөрийг нэмдэг: [.programlisting] .... natd_enable="YES" .... Хэрэв `natd_enable="NO"` мөр аль хэдийн байвал `NO`-ийг `YES` болгож өөрчлөөрэй. rc скриптүүд өөр бусад хамааралтай үйлчилгээнүүдийг дараагийн дахин ачаалалтын үеэр доор тайлбарласны дагуу автоматаар ачаалдаг. [.filename]#rc.d# систем нь үндсэндээ системийн эхлэх/унтрах үеэр үйлчилгээнүүдийг эхлүүлэх/зогсоох зорилготой бөгөөд стандарт `start`, `stop` болон `restart` тохируулгууд нь зөвхөн [.filename]#/etc/rc.conf#-ийн харгалзах хувьсагчууд заагдсан үед өөрийн үйлдлийг гүйцэтгэдэг. Жишээ нь дээр дурдсан `sshd restart` тушаал нь [.filename]#/etc/rc.conf#-д `sshd_enable` хувьсагч `YES` гэсэн тохиолдолд зөвхөн ажиллана. [.filename]#/etc/rc.conf#-д байгаа тохируулгаас үл хамааран үйлчилгээг `start`, `stop` эсвэл `restart` хийхийн тулд тушаалууд "one" угтвартай байх шаардлагатай. Жишээ нь `sshd`-г [.filename]#/etc/rc.conf# дахь тохиргооноос үл хамааран дахин эхлүүлэхдээ дараах тушаалыг ашиглана: [source,shell] .... # /etc/rc.d/sshd onerestart .... Тохирох [.filename]#rc.d# скриптийг `rcvar` тохируулгатай ажиллуулж [.filename]#/etc/rc.conf#-д үйлчилгээ нээгдсэн эсэхийг амархан шалгадаг. Тиймээс администратор `sshd`-г [.filename]#/etc/rc.conf#-д нээгдсэн эсэхийг дараах тушаалыг ажиллуулж шалгаж болно: [source,shell] .... # /etc/rc.d/sshd rcvar # sshd $sshd_enable=YES .... [NOTE] ==== Хоёр дахь мөр (`# sshd`) нь `root` консолынх биш `sshd` тушаалын гаргасан үр дүн юм. ==== Үйлчилгээг ажиллах байгаа эсэхийг шалгах `status` тохируулга байдаг. Жишээ нь `sshd` эхэлсэн эсэхийг шалгахдаа: [source,shell] .... # /etc/rc.d/sshd status sshd is running as pid 433. .... Зарим тохиолдолд үйлчилгээг `reload` хийх бас боломжтой байдаг. Энэ нь үйлчилгээг өөрийн тохиргооны файлуудыг дахин уншихыг зааж үйлчилгээ уруу дохио шидэхийг оролддог. Ихэнх тохиолдолд энэ нь үйлчилгээ уруу `SIGHUP` дохио шиднэ гэсэн үг юм. Үйлчилгээ болгонд энэ боломжийн дэмжлэг байдаггүй. [.filename]#rc.d# систем нь зөвхөн сүлжээний үйлчилгээнд ашиглагдаад зогсохгүй мөн системийн эхлүүлэлтэд бас ихээхэн хувь нэмэр оруулдаг. Жишээ нь [.filename]#bgfsck# файлыг авч үзье. Энэ скрипт ажиллахад дараах мэдээллийг хэвлэж гаргана: [source,shell] .... Starting background file system checks in 60 seconds. .... Тиймээс энэ файлыг зөвхөн системийг эхлүүлэх үед файлын системийн арын шалгалтыг хийхэд хэрэглэдэг. Системийн олон үйлчилгээнүүд зөв ажиллахын тулд бусад үйлчилгээнүүдээс хамаардаг. Жишээ нь NIS болон бусад RPC дээр тулгуурласан үйлчилгээнүүд `rpcbind` (portmapper) үйлчилгээ ажиллахаас нааш амжилттай ажилладаггүй. Үүнийг шийдэхийн тулд хамаарлуудын тухай болон бусад мета-өгөгдлийн тухай мэдээллийг эхлүүлэх скрипт бүрийн дээд хэсэгт тайлбараар оруулсан байдаг. man:rcorder[8] програм хамаарлуудыг хангаж системийн үйлчилгээнүүдийг ямар дарааллаар ажиллуулах ёстойг тогтоохын тулд эдгээр тайлбаруудыг уншдаг. Дараах үгнүүдийг бүх эхлүүлэх скриптэд оруулах ёстой (Эдгээр нь эхлүүлэх скриптийг "идэвхжүүлэх"эд man:rc.subr[8]-д шаардлагатай байдаг): * `PROVIDE`: Энэ файлын хангаж байгаа үйлчилгээнүүдийг заана. Дараах үгнүүдийг эхлүүлэх скрипт бүрийн эхэнд оруулж болно. Эдгээр нь заавал шаардлагатай биш боловч man:rcorder[8]-д тус дөхөм болох ашигтай байдаг: * `REQUIRE`: Энэ үйлчилгээнд шаардлагатай үйлчилгээнүүдийг жагсаана. Энэ файл заагдсан үйлчилгээнүүдийн _дараа_ ажиллана. * `BEFORE`: Энэ үйлчилгээнээс хамааралтай үйлчилгээнүүдийг жагсаана. Энэ файл заагдсан үйлчилгээнүүдийн _өмнө_ ажиллана. Эдгээр түлхүүр үгнүүдийг эхлүүлэх скрипт болгонд болгоомжтойгоор тохируулж өгснөөр бусад зарим UNIX(R) үйлдлийн системүүд шиг "ажиллах түвшингүүдтэй (runlevels)" зууралдалгүйгээр скриптүүдийн эхлэх дарааллыг маш сайн хянах боломжийг администраторт бий болгох юм. [.filename]#rc.d# системийн талаар нэмэлт мэдээллийг man:rc[8] болон man:rc.subr[8] гарын авлагын хуудаснуудаас олж болно. Хэрэв та өөрийн rc.d скриптүүд бичих эсвэл байгаагаа сайжруулахыг сонирхож байгаа бол танд бас extref:{rc-scripting}[энэ нийтлэл] хэрэгтэй байж болох юм. [[config-network-setup]] == Сүлжээний интерфэйс картууд суулгах нь Өнөөдөр бид сүлжээний холболтгүй компьютерийн талаар бодох ч аргагүй болсон билээ. Сүлжээний картыг нэмж тохируулах нь FreeBSD-ийн дурын администраторын ердийн ажил болдог. === Тохирох драйверийг олох нь Эхлэхээсээ өмнө та өөрт байгаа картынхаа загвар, түүнд ашигласан бичил схем болон PCI эсвэл ISA картын аль нь эсэхийг мэдэх шаардлагатай. FreeBSD өргөн төрлийн PCI болон ISA картуудыг дэмждэг. Таны карт таны ашиглах хувилбар дээр дэмжигдсэн эсэхийг Тоног Төхөөрөмжийн Нийцтэй Байдлын Жагсаалтаас шалгаарай. Таны карт дэмжигдсэнийг мэдсэний дараа та өөрийн картанд тохирох драйвераа тодорхойлох хэрэгтэй. [.filename]#/usr/src/sys/conf/NOTES# болон [.filename]#/usr/src/sys/arch/conf/NOTES# нь сүлжээний интерфэйс драйверуудын жагсаалтыг дэмжигдсэн бичил схем/картуудын тухай зарим мэдээллийн хамтаар танд өгөх болно. Хэрэв та аль драйвер нь зөв эсэхэд эргэлзэж байгаа бол драйверийн гарын авлагын хуудсыг уншаарай. Гарын авлагын хуудас нь дэмжигдсэн тоног төхөөрөмж болон бүр учирч болзошгүй асуудлуудын тухай дэлгэрэнгүй мэдээллийг өгдөг. Хэрэв та ердийн карттай бол ихэнхдээ драйверийг хичээнгүйлэн хайх шаардлагагүй юм. Ердийн сүлжээний картуудад зориулсан драйверууд нь [.filename]#GENERIC# цөмд байдаг, тэгэхээр таны карт ачаалах явцад иймэрхүү харагдах ёстой: [source,shell] .... dc0: <82c169 PNIC 10/100BaseTX> port 0xa000-0xa0ff mem 0xd3800000-0xd38 000ff irq 15 at device 11.0 on pci0 miibus0: on dc0 bmtphy0: PHY 1 on miibus0 bmtphy0: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc0: Ethernet address: 00:a0:cc:da:da:da dc0: [ITHREAD] dc1: <82c169 PNIC 10/100BaseTX> port 0x9800-0x98ff mem 0xd3000000-0xd30 000ff irq 11 at device 12.0 on pci0 miibus1: on dc1 bmtphy1: PHY 1 on miibus1 bmtphy1: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc1: Ethernet address: 00:a0:cc:da:da:db dc1: [ITHREAD] .... Энэ жишээн дээр систем дээр байгаа хоёр карт man:dc[4] драйверийг ашиглаж байгааг бид харж байна. Хэрэв таны NIC-д (Network Interface Card буюу Сүлжээний Интерфэйс Карт) зориулсан драйвер [.filename]#GENERIC#-д байхгүй бол та өөрийн NIC-г ашиглахын тулд тохирох драйверийг ачаалах хэрэгтэй. Ингэхийн тулд хоёр аргын аль нэгийг ашиглана: * Хамгийн амархан арга нь ердөө л өөрийн сүлжээний картанд зориулсан цөмийн модулийг man:kldload[8] ашиглан эсвэл тохирох мөрийг [.filename]#/boot/loader.conf#-д нэмж ачаалах үед автоматаар ачаалах юм. Бүх NIC драйверууд модуль хэлбэрээр байдаггүй; модулиуд нь байдаггүй төхөөрөмжүүдийн дурдаж болох жишээнүүд гэвэл ISA картууд юм. * Өөр нэг арга нь та өөрийн картын дэмжлэгийг цөмд оруулан статикаар хөрвүүлж болох юм. Өөрийн цөмийн тохиргооны файлд юу нэмэх ёстойг мэдэхийн тулд [.filename]#/usr/src/sys/conf/NOTES#, [.filename]#/usr/src/sys/arch/conf/NOTES# болон драйверийн гарын авлагын хуудсыг шалгаарай. Цөмийг дахин хөрвүүлэх талаар дэлгэрэнгүй мэдээллийг crossref:kernelconfig[kernelconfig,FreeBSD цөмийг тохируулах нь]-с үзнэ үү. Хэрэв таны картыг таны цөм ([.filename]#GENERIC#) ачаалах явцад илрүүлсэн бол та шинэ цөм бүтээх шаардлагагүй. [[config-network-ndis]] ==== Windows(R)-ийн NDIS драйверуудыг ашиглах нь Харамсалтай нь өөрийн драйверуудад зориулсан схемүүдийг нээлттэй эхийн хүрээнийхэнд өгдөггүй, тийм мэдээллийг худалдааны нууц гэж үздэг олон үйлдвэрлэгчид байсаар байна. Ингэснээр FreeBSD болон өөр үйлдлийн системүүдийн хөгжүүлэгчдэд хоёр сонголт үлдсэн: буцаах инженерчлэлийн хүнд хэцүү, урт хугацааны процессийг туулж драйверуудыг хөгжүүлэх эсвэл Microsoft(R) Windows(R) тавцангуудад байдаг хоёртын хэлбэрийн драйверуудыг ашиглах арга замууд юм. FreeBSD-тэй холбогдсон зэрэг ихэнх хөгжүүлэгчид сүүлийн хандлагыг авч ашигладаг. Билл Полын (wpaul) оруулсан хувь нэмрийн ачаар Сүлжээний Драйверийн Интерфэйсийн Тодорхойлолтын (NDIS) "эх (native)" дэмжлэг ордог болсон. FreeBSD NDISulator (өөрөөр Чөтгөр Төсөл) Windows(R) хоёртын драйверийг аваад ерөнхийдөө түүнийг Windows(R) дээр ажиллаж байгаа мэтээр хуурдаг. man:ndis[4] драйвер нь Windows(R) хоёртын файл ашиглаж байгаа учраас энэ нь зөвхөн i386(TM) болон amd64 системүүд дээр ажилладаг. PCI, CardBus, PCMCIA (PC-Card), болон USB төхөөрөмжүүдийг дэмждэг. NDISulator ашиглахын тулд 3 зүйл хэрэгтэй: . Цөмийн эхүүд . Windows(R) XP драйверийн хоёртын файл ([.filename]#.SYS# өргөтгөл) . Windows(R) XP драйверийн тохиргооны файл ([.filename]#.INF# өргөтгөл) Та өөрийн картад зориулсан файлуудыг олоорой. Ерөнхийдөө тэдгээрийг хавсаргасан CD-үүд эсвэл үйлдвэрлэгчүүдийн вэб хуудаснаас олж болно. Дараах жишээнүүдэд бид [.filename]#W32DRIVER.SYS# болон [.filename]#W32DRIVER.INF# файлуудыг ашиглах болно. Драйверын битийн урт FreeBSD-ийн хувилбарынхтай таарсан байх ёстой. FreeBSD/i386-н хувьд Windows(R) 32-бит драйвер ашиглана. FreeBSD/amd64-н хувьд Windows(R) 64-бит драйвер хэрэгтэй. Дараагийн алхамд драйверийн хоёртын файлыг цөмийн ачаалж болох модуль болгон хөрвүүлнэ. `root` эрхээр man:ndisgen[8]-г хэрэглэнэ: [source,shell] .... # ndisgen /path/to/W32DRIVER.INF /path/to/W32DRIVER.SYS .... man:ndisgen[8] хэрэгсэл нь интерактив бөгөөд шаардлагатай нэмэлт мэдээллийг асуудаг. Одоо байгаа санд цөмийн шинэ модуль үүсгэнэ. man:kldload[8] ашиглан шинэ модулийг ачаална: [source,shell] .... # kldload ./W32DRIVER_SYS.ko .... Үүсгэгдсэн цөмийн модулиас гадна та [.filename]#ndis.ko# болон [.filename]#if_ndis.ko# модулиудыг ачаалах хэрэгтэй. Энэ нь таныг man:ndis[4]-ээс хамаарсан дурын модулийг ачаалах үед автоматаар хийгдэх ёстой. Хэрэв та тэдгээрийг гараар ачаалахыг хүсвэл дараах тушаалыг ашиглаарай: [source,shell] .... # kldload ndis # kldload if_ndis .... Эхний тушаал нь NDIS минипорт драйвер дугтуйлагчийг ачаалах бөгөөд хоёр дахь нь яг сүлжээний интерфэйсийг ачаална. Одоо man:dmesg[8]-ийг шалгаж ачаалахад алдаа байгаа эсэхийг үзэх хэрэгтэй. Бүгд сайн болж өнгөрсөн бол та дараах үр дүнг харах ёстой: [source,shell] .... ndis0: mem 0xf4100000-0xf4101fff irq 3 at device 8.0 on pci1 ndis0: NDIS API version: 5.0 ndis0: Ethernet address: 0a:b1:2c:d3:4e:f5 ndis0: 11b rates: 1Mbps 2Mbps 5.5Mbps 11Mbps ndis0: 11g rates: 6Mbps 9Mbps 12Mbps 18Mbps 36Mbps 48Mbps 54Mbps .... Эндээс эхлээд та [.filename]#ndis0# төхөөрөмжид өөр бусад сүлжээний интерфэйсийн (өөрөөр хэлбэл [.filename]#dc0#) нэгэн адилаар хандах боломжтой болох юм. Та бусад модулиудтай адилаар NDIS модулиудыг ачаалах явцад ачаалахаар системийг тохируулж болно. Эхлээд үүсгэгдсэн модуль [.filename]#W32DRIVER_SYS.ko#-г [.filename]#/boot/modules# уруу хуулах хэрэгтэй. Тэгээд дараах мөрийг [.filename]#/boot/loader.conf#-д нэмнэ: [.programlisting] .... W32DRIVER_SYS_load="YES" .... === Сүлжээний карт тохируулах нь Сүлжээний картанд зориулсан зөв драйвер ачаалагдсаны дараа картыг тохируулах шаардлагатай. Бусад олон зүйлсийн адил сүлжээний карт нь sysinstall програмаар суулгах явцад тохируулагдаж болно. Таны системийн сүлжээний интерфэйсүүдэд зориулсан тохиргоог харуулахын тулд дараах тушаалыг ажиллуулна: [source,shell] .... % ifconfig dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da inet 192.168.1.3 netmask 0xffffff00 broadcast 192.168.1.255 media: Ethernet autoselect (100baseTX ) status: active dc1: flags=8802 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:db inet 10.0.0.1 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet 10baseT/UTP status: no carrier plip0: flags=8810 metric 0 mtu 1500 lo0: flags=8049 metric 0 mtu 16384 options=3 inet6 fe80::1%lo0 prefixlen 64 scopeid 0x4 inet6 ::1 prefixlen 128 inet 127.0.0.1 netmask 0xff000000 nd6 options=3 .... Энэ жишээн дээр дараах төхөөрөмжүүдийг харуулсан: * [.filename]#dc0#: Эхний Ethernet интерфэйс * [.filename]#dc1#: Хоёрдугаар Ethernet интерфэйс * [.filename]#plip0#: Параллел порт интерфэйс (хэрэв параллел порт машин дээр байгаа бол) * [.filename]#lo0#: Буцаж эргэх төхөөрөмж FreeBSD нь драйверийн нэр дээр цөмийн ачаалах явцад картууд ямар дарааллаар илрүүлэгдсэн тэр дарааллын тоог нэмж сүлжээний картыг нэрлэдэг. Жишээ нь [.filename]#sis2# нь систем дээрх man:sis[4] драйвер ашиглаж байгаа 3 дахь сүлжээний карт байж болох юм. Энэ жишээн дээр [.filename]#dc0# төхөөрөмж босон ажиллаж байна. Түлхүүр индикаторууд нь: . `UP` нь картын тохиргоо хийгдэж бэлэн болсныг илэрхийлнэ. . Карт нь Интернэт (`inet`) хаягтай (энэ тохиолдолд `192.168.1.3`). . Энэ нь зөв дэд сүлжээний багтай (`netmask`; `0xffffff00` нь `255.255.255.0` адил). . Энэ нь зөв нийтэд цацах хаягтай (энэ тохиолдолд `192.168.1.255`). . Картны MAC (`ether`) хаяг нь `00:a0:cc:da:da:da` байна. . Физик зөөгчийн сонголт нь автомат сонголтын горим дээр байна (`media: Ethernet autoselect (100baseTX )`). [.filename]#dc1# нь `10baseT/UTP` зөөгчтэй ажиллахаар тохируулагдсан байгааг бид харж болно. Байж болох зөөгчийн төрлүүдийн тухай дэлгэрэнгүй мэдээллийн талаар өөрийнх нь гарын авлагын хуудсанд хандаж үзнэ үү. . Холболтын (`status`) төлөв нь `active` буюу идэвхтэй байна, өөрөөр хэлбэл дамжуулагч илэрсэн байна. [.filename]#dc1#-ийн хувьд бид `status: no carrier` буюу дамжуулагч байхгүйг харж болно. Энэ нь Ethernet кабель картанд залгагдаагүй байх үед хэвийн байна. Хэрэв man:ifconfig[8]-ийн үр дүн дараах маягтай төстэй байвал: [source,shell] .... dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da media: Ethernet autoselect (100baseTX ) status: active .... Энэ нь карт тохируулагдаагүйг илэрхийлнэ. Картаа тохируулахын тулд танд `root` зөвшөөрлүүд хэрэгтэй. Сүлжээний картын тохируулгууд тушаалын мөрөөс man:ifconfig[8]-р хийгдэх боломжтой, гэхдээ та системийг дахин ачаалсан болгоныхоо дараа үүнийг хийх хэрэгтэй болно. [.filename]#/etc/rc.conf# файл нь сүлжээний картын тохиргоог нэмэх газар юм. [.filename]#/etc/rc.conf#-ийг өөрийн дуртай засварлагч дээр нээгээрэй. Систем дээрх сүлжээний карт бүрийн хувьд мөр нэмэх хэрэгтэй, манай жишээн дээр бид эдгээр мөрүүдийг нэмсэн: [.programlisting] .... ifconfig_dc0="inet 192.168.1.3 netmask 255.255.255.0" ifconfig_dc1="inet 10.0.0.1 netmask 255.255.255.0 media 10baseT/UTP" .... Та [.filename]#dc0#, [.filename]#dc1# болон бусдуудыг өөрийн картуудад зориулсан төхөөрөмжөөр өөрчлөх болон хаягуудыг зөвөөр солих хэрэгтэй. Зөвшөөрөгдсөн тохируулгуудын талаар дэлгэрэнгүйг картын драйвер болон man:ifconfig[8]-ийн гарын авлагын хуудаснуудаас, бас man:rc.conf[5] гарын авлагын хуудаснаас [.filename]#/etc/rc.conf#-ийн синтаксын тухай дэлгэрэнгүй мэдээллийг унших хэрэгтэй. Хэрэв та суулгах явцад сүлжээг тохируулсан бол сүлжээний карт(ууд)ын талаар зарим мөрүүд аль хэдийн байж болох юм. Мөрүүд нэмэхээсээ өмнө [.filename]#/etc/rc.conf#-ийг дахин шалгаарай. Мөн та LAN дахь төрөл бүрийн машинуудын нэрүүд болон IP хаягууд [.filename]#/etc/hosts# файлд байхгүй бол тэдгээрийг нэмж засварлах шаардлагатай. Дэлгэрэнгүй мэдээллийн талаар man:hosts[5] болон [.filename]#/usr/shared/examples/etc/hosts# файлд хандана уу. [NOTE] ==== Хэрэв энэ машинаар Интернэтэд холболт хийхээр төлөвлөсөн бол та гараараа анхдагч гарц болон нэрийн серверийг бас тохируулж өгөх ёстой: [source,shell] .... # echo 'defaultrouter="your_default_router"' >> /etc/rc.conf # echo 'nameserver your_DNS_server' >> /etc/resolv.conf .... ==== === Тест хийх болон алдааг олж засварлах нь [.filename]#/etc/rc.conf#-д хэрэгцээтэй өөрчлөлтүүдийг хийснийхээ дараа та системээ дахин ачаалах шаардлагатай. Ингэснээр интерфэйс(үүд)эд хийгдэх өөрчлөлт(үүд)ийг зөвшөөрөх бөгөөд ямар нэг тохиргооны алдаагүйгээр систем ачаалж байгаа эсэхийг шалгадаг. Мөн өөрөөр та сүлжээний системээ дахин дуудаж болно: [source,shell] .... # /etc/rc.d/netif restart .... [NOTE] ==== Хэрэв анхдагч гарцыг [.filename]#/etc/rc.conf# файлд зааж өгсөн бол энэ тушаалыг ашиглана: [source,shell] .... # /etc/rc.d/routing restart .... ==== Сүлжээний систем дахин дуудагдсаны дараа та сүлжээний интерфэйсүүдээ тест хийх хэрэгтэй. ==== Ethernet карт тест хийх нь Ethernet карт зөв тохируулагдсаныг шалгахдаа та 2 зүйлийг оролдох хэрэгтэй. Эхлээд интерфэйс уруу өөр уруу нь ping хийгээд дараа нь LAN дахь өөр машин уруу ping хийх хэрэгтэй. Эхлээд локал интерфэйсийг тест хийнэ: [source,shell] .... % ping -c5 192.168.1.3 PING 192.168.1.3 (192.168.1.3): 56 data bytes 64 bytes from 192.168.1.3: icmp_seq=0 ttl=64 time=0.082 ms 64 bytes from 192.168.1.3: icmp_seq=1 ttl=64 time=0.074 ms 64 bytes from 192.168.1.3: icmp_seq=2 ttl=64 time=0.076 ms 64 bytes from 192.168.1.3: icmp_seq=3 ttl=64 time=0.108 ms 64 bytes from 192.168.1.3: icmp_seq=4 ttl=64 time=0.076 ms --- 192.168.1.3 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.074/0.083/0.108/0.013 ms .... Одоо бид LAN дахь өөр машин уруу ping хийх хэрэгтэй: [source,shell] .... % ping -c5 192.168.1.2 PING 192.168.1.2 (192.168.1.2): 56 data bytes 64 bytes from 192.168.1.2: icmp_seq=0 ttl=64 time=0.726 ms 64 bytes from 192.168.1.2: icmp_seq=1 ttl=64 time=0.766 ms 64 bytes from 192.168.1.2: icmp_seq=2 ttl=64 time=0.700 ms 64 bytes from 192.168.1.2: icmp_seq=3 ttl=64 time=0.747 ms 64 bytes from 192.168.1.2: icmp_seq=4 ttl=64 time=0.704 ms --- 192.168.1.2 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.700/0.729/0.766/0.025 ms .... Хэрэв та [.filename]#/etc/hosts# файлыг тохируулсан бол `192.168.1.2`-ийн оронд машины нэрийг бас ашиглаж болох болох юм. ==== Алдааг олж засварлах нь Тоног төхөөрөмж болон програм хангамжийн тохиргоонуудын алдааг олж засварлах нь үргэлж зовлон байдаг бөгөөд зовлонг энгийн зүйлүүдийг эхлээд шалгаснаар багасгах боломжтой. Таны сүлжээний кабель холбогдсон уу? Сүлжээний үйлчилгээнүүдээ зөв тохируулсан уу? Галт ханаа зөв тохируулсан уу? Таны хэрэглэж байгаа картыг FreeBSD дэмждэг үү? Алдааны тайланг явуулахаасаа өмнө тоног төхөөрөмжийн тэмдэглэлийг заавал шалгах хэрэгтэй. Өөрийн FreeBSD-ийн хувилбарыг хамгийн сүүлийн STABLE хувилбар уруу шинэчлээрэй. Захидлын жагсаалтын архивууд шалгах буюу эсвэл Интернетээс хайгаарай. Хэрэв карт ажилласан мөртлөө ажиллагаа муу бол man:tuning[7] гарын авлагын хуудсыг унших нь зүйтэй юм. Мөн буруу сүлжээний тохиргоонууд удаан холболтын шалтгаан болдог учир та сүлжээний тохиргоог бас шалгаж болох юм. Зарим хэрэглэгчид ганц хоёр `device timeout` мэдээлэлтэй тулгарч болох бөгөөд энэ нь зарим картуудын хувьд хэвийн юм. Хэрэв энэ нь үргэлжлээд эсвэл шаналгаатай болоод эхэлбэл уг төхөөрөмж өөр бусад төхөөрөмжтэй зөрчилдөж байгаа эсэхийг та магадгүй шалгахыг хүсэх байх. Кабелийн холболтуудыг дахин шалгаарай. Магадгүй танд өөр нэг карт хэрэгтэй байж болох юм. Хэрэглэгчид зарим үед цөөн `watchdog timeout` гэсэн алдаанууд хардаг. Ийм үед эхлээд хийх юм нь сүлжээний кабелийг шалгана. Олон картууд Bus Mastering дэмждэг PCI оролтыг шаарддаг. Зарим нэг эх хавтангуудад үүнийг зөвхөн нэг PCI оролт зөвшөөрдөг (ихэнхдээ 0-р оролт). Энэ нь асуудал байж болох эсэхийг сүлжээний карт болон эх хавтангийн баримтаас шалгаарай. Систем пакетийг зорьсон газар нь чиглүүлж чадахгүй тохиолдолд `No route to host` мэдээллүүд гардаг. Энэ нь анхдагч чиглүүлэлт заагаагүй тохиолдолд эсвэл кабель салгагдсан бол гардаг. `netstat -rn` тушаалын үр дүнг үзээд таны хүрэхийг оролдож байгаа тэр хост уруу чинь зөв чиглүүлэлт байгаа эсэхийг шалгаарай. Хэрэв байхгүй бол crossref:advanced-networking[advanced-networking,Сүлжээний нэмэлт ойлголтууд]-г уншаарай. `ping: sendto: Permission denied` алдааны мэдээллүүд нь буруу тохируулсан галт ханаас ихэвчлэн болдог. Хэрэв `ipfw` нь цөмд идэвхжсэн бөгөөд ямар ч дүрэм тодорхойлогдоогүй бол анхдагч бодлого нь бүх трафикийг бүр ping хүсэлтийг хүртэл татгалзан хаадаг! Дэлгэрэнгүйг crossref:firewalls[firewalls,Галт хана]-с уншина уу. Заримдаа картын ажиллагаа муу эсвэл дунджаас доогуур байдаг. Эдгээр тохиолдолд зөөгч сонголтын горимыг `autoselect` горимоос зөв зөөгчийн сонголт уруу болгож тааруулах нь шилдэг арга юм. Энэ нь ихэнх тоног төхөөрөмжийн хувьд ихэвчлэн ажиллах боловч хүн болгоны хувьд байгаа ийм асуудлыг шийдэхгүй ч байж болох юм. Дахин хэлэхэд бүх сүлжээний тохиргоонуудыг шалгаж man:tuning[7] гарын авлагын хуудсыг уншаарай. [[configtuning-virtual-hosts]] == Виртуал Хостууд FreeBSD-ийн хамгийн түгээмэл хэрэглээ бол нэг сервер сүлжээн дээр олон сервер мэтээр ажиллах виртуал сайт хост хийх боломж юм. Үүнийг нэг интерфэйс дээр олон сүлжээний хаягууд тавьж хийдэг. Өгөгдсөн сүлжээний интерфэйс нь нэг "жинхэнэ" хаягтай бөгөөд дурын тооны "өөр(alias)" хаягуудтай байж болох юм. Эдгээр өөр хаягуудыг ихэнхдээ [.filename]#/etc/rc.conf#-д тохирох хаягийн оруулгуудыг оруулан нэмж өгдөг. [.filename]#fxp0# интерфэйсд зориулсан өөр хаягийн оруулга нь иймэрхүү байна: [.programlisting] .... ifconfig_fxp0_alias0="inet xxx.xxx.xxx.xxx netmask xxx.xxx.xxx.xxx" .... Өөр хаягийн оруулгууд нь `alias0` гэж эхлэх ёстой бөгөөд дээш өгсөх дарааллаар явдаг (жишээ нь `_alias1`, `_alias2`, гэх мэт). Тохиргооны үйл явц эхний байхгүй дугаар дээр хүрч зогсдог. Өөр хаягийн сүлжээний багуудыг тооцоолох нь чухал байдаг, гэхдээ азаар энэ нь маш амархан. Өгөгдсөн интерфэйсийн хувьд сүлжээний багийг зөвөөр үзүүлдэг нэг хаяг байх ёстой. Энэ сүлжээн дэх өөр бусад хаягууд бүгд `1`-ээс (энэ нь `255.255.255.255` гэх буюу эсвэл `0xffffffff` гэж илэрхийлэгддэг) тогтсон сүлжээний багтай байх ёстой. Жишээ нь [.filename]#fxp0# интерфэйс нь `10.1.1.0` сүлжээнд `255.255.255.0` болон `202.0.75.16` сүлжээнд `255.255.255.240` багуудыг ашиглаж хоёр сүлжээнд холбогдсон гэж бодъё. Бид системийг `10.1.1.1`-ээс `10.1.1.5` хүртэл болон `202.0.75.17`-ээс эхлээд `202.0.75.20` хүртэлх хаягууд дээр байлгахыг хүсэж байна. Дээр тэмдэглэсний дагуу өгөгдсөн сүлжээний хүрээн дэх зөвхөн эхний хаяг (энэ тохиолдолд `10.0.1.1` болон `202.0.75.17`) жинхэнэ сүлжээний багтай байх ёстой; бусад үлдсэн бүгд (`10.1.1.2`-ээс `10.1.1.5` хүртэл болон `202.0.75.18`-ээс эхлээд `202.0.75.20` хүртэл) `255.255.255.255` сүлжээний багтай байхаар тохируулагдах хэрэгтэй. Дараах [.filename]#/etc/rc.conf# оруулгууд нь энэ зорилгоор адаптерийг зөв тохируулж байна: [.programlisting] .... ifconfig_fxp0="inet 10.1.1.1 netmask 255.255.255.0" ifconfig_fxp0_alias0="inet 10.1.1.2 netmask 255.255.255.255" ifconfig_fxp0_alias1="inet 10.1.1.3 netmask 255.255.255.255" ifconfig_fxp0_alias2="inet 10.1.1.4 netmask 255.255.255.255" ifconfig_fxp0_alias3="inet 10.1.1.5 netmask 255.255.255.255" ifconfig_fxp0_alias4="inet 202.0.75.17 netmask 255.255.255.240" ifconfig_fxp0_alias5="inet 202.0.75.18 netmask 255.255.255.255" ifconfig_fxp0_alias6="inet 202.0.75.19 netmask 255.255.255.255" ifconfig_fxp0_alias7="inet 202.0.75.20 netmask 255.255.255.255" .... [[configtuning-syslog]] == Системийн лог хийгч syslogd-г тохируулах нь Систем лог хийх нь системийг удирдахад чухал зүйл юм. Үүнийг тоног төхөөрөмж болоод програм хангамжийн асуудлууд, мөн систем дэх алдаануудыг олж илрүүлэхэд хэрэглэдэг. Аюулгүй байдлын аудит хийх болон аливаа учралд хариу үзүүлэхэд бас маш чухал үүрэг гүйцэтгэдэг. Хяналтын терминалгүй системийн демонууд мэдээллийг системийн лог хийгч рүү эсвэл бусад лог файл руу ихэвчлэн бас лог хийдэг. Энэ хэсэгт FreeBSD системийн лог хийгч man:syslogd[8]-г хэрхэн тохируулж ашиглах талаар болон логийг багасгах ба man:newsyslog[8] ашиглан лог удирдах талаар хэлэлцэх болно. Локал машин дээр `syslogd`-г тохируулж ашиглах талаар анхаарах болно. Тусдаа лог хост ашиглах талаарх нэмэлт тохиргооны тухай дэлгэрэнгүйг crossref:network-servers[network-syslogd,syslogd ашиглан алсын хост руу бүртгэх нь] хэсгээс үзнэ үү. === syslogd ашиглах нь FreeBSD-н man:syslogd[8]-н анхдагч тохиргоо ачаалах үед эхэлдэг. Үүнийг [.filename]#/etc/rc.conf# дахь `syslogd_enable` хувьсагчаар хянадаг. man:syslogd[8]-н ажиллагаанд нөлөөлдөг програмын хэд хэдэн аргументууд байдаг. Тэдгээрийг өөрчлөхийн тулд [.filename]#/etc/rc.conf# дахь `syslogd_flags`-г ашиглана. Аргументуудын талаар дэлгэрэнгүйг man:syslogd[8]-оос, man:rc.conf[5] ба <> болон <> хэсгээс [.filename]#/etc/rc.conf# ба man:rc[8] дэд системийн талаар дэлгэрэнгүйг үзнэ үү. === syslogd-г тохируулах нь Тохиргооны файл нь анхдагчаар [.filename]#/etc/syslog.conf# бөгөөд логуудыг хүлээж авсныхаа дараа хэрхэн яаж ажиллахыг хянадаг. Ирж байгаа үйл явдлуудтай ажиллахыг хянах хэд хэдэн параметрүүд байдаг бөгөөд тэдгээрээс хамгийн хялбар нь _facility_ ба _level_ юм. Хэрэгсэл нь цөм эсвэл демон гэх мэт аль дэд систем логийг үүсгэснийг тайлбарлах бөгөөд түвшин нь учирсан үйл явдлын хор хөнөөлийг тайлбарладаг. Энэ нь логийг өөр лог файлууд рүү өгөх эсвэл хаях зэргээр тохиргоо болон түвшингээс хамааруулан хийх боломжтой болгодог. Лог илгээсэн програм болон алсаас лог хийж байгаа тохиолдолд лог үйл явц үүсгэж байгаа машины хостын нэрээс хамаарч арга хэмжээ авах боломж бас байдаг. man:syslogd[8]-г тохируулах нь хялбар байдаг. Тохиргооны файл нь хийх үйлдэл бүрийн хувьд нэг мөртэй байх бөгөөд мөр бүрийн синтакс нь сонголтын талбар болон арга хэмжээний талбараас тогтоно. Сонголтын талбарын синтакс нь _facility.level_ байх бөгөөд _facility_ буюу хэрэгслээс ирж байгаа логуудыг _level_ түвшинд буюу түүнээс дээш түвшинд авах тохиргоо юм. Мөн нэмэлтээр юу лог хийхийг илүү нарийн зааж өгөхийн тулд харьцуулах флагийг түвшингийн өмнө нэмж өгөх бас боломжтой. Адил үйлдэлд олон сонголтын талбарыг ашиглаж болох бөгөөд тэдгээрийг цэг таслалаар (`;`) тусгаарладаг. `*`-г ашиглавал бүгдийг гэсэн утгатай. Арга хэмжээний талбар нь файл эсвэл алсын лог хост зэрэг хаашаа логийг илгээхийг зааж өгдөг. Жишээ нь энд FreeBSD-н анхдагч [.filename]#syslog.conf# байна: [.programlisting] .... # $FreeBSD$ # # Spaces ARE valid field separators in this file. However, # other *nix-like systems still insist on using tabs as field # separators. If you are sharing this file between systems, you # may want to use only tabs as field separators here. # Consult the syslog.conf(5) manpage. *.err;kern.warning;auth.notice;mail.crit /dev/console <.> *.notice;authpriv.none;kern.debug;lpr.info;mail.crit;news.err /var/log/messages security.* /var/log/security auth.info;authpriv.info /var/log/auth.log mail.info /var/log/maillog <.> lpr.info /var/log/lpd-errs ftp.info /var/log/xferlog cron.* /var/log/cron *.=debug /var/log/debug.log <.> *.emerg * # uncomment this to log all writes to /dev/console to /var/log/console.log #console.info /var/log/console.log # uncomment this to enable logging of all log messages to /var/log/all.log # touch /var/log/all.log and chmod it to mode 600 before it will work #*.* /var/log/all.log # uncomment this to enable logging to a remote loghost named loghost #*.* @loghost # uncomment these if you're running inn # news.crit /var/log/news/news.crit # news.err /var/log/news/news.err # news.notice /var/log/news/news.notice !ppp <.> *.* /var/log/ppp.log !* .... <.> `err` болон түүнээс дээш, мөн `kern.warning`, `auth.notice` ба `mail.crit` түвшний бүх мэдээллийг лог хийж эдгээр мэдээллийг консол ([.filename]#/dev/console#) руу гаргах. <.> `mail` хэрэгслийн `info` буюу түүнээс дээш түвшний бүх мэдээллийг барьж логийг [.filename]#/var/log/maillog# руу авах. <.> Энэ мөр нь `=` буюу харьцуулах флагийг ашиглаж байгаа бөгөөд `debug` түвшний мэдээллийг авч [.filename]#/var/log/debug.log# руу бичихийг заана. <.> Энд _програмыг хэрхэн заах_ талаар жишээг харуулсан байна. Энэ нь програмыг зааж өгсөн тэр програмын хувьд ажиллах тийм дүрэм бий болгоно. Энэ тохиолдлын хувьд энэ мөр болон түүний дараах нь зөвхөн `ppp`-с гарах бүх мэдээллийг [.filename]#/var/log/ppp.log# файл руу авч байна. Энэ жишээ нь олон түвшин болон дэд системүүд байгааг харуулж байна. Түвшингүүд нь хамгийн чухлаас бага руу жагсаагдсан байна: `emerg`, `alert`, `crit`, `err`, `warning`, `notice`, `info` ба `debug`. Хэрэгслүүд нь ямар нэг дараалалгүйгээр дараах байна: `auth`, `authpriv`, `console`, `cron`, `daemon`, `ftp`, `kern`, `lpr`, `mail`, `mark`, `news`, `security`, `syslog`, `user`, `uucp` ба `local0`-с `local7` хүртэл байна. Өөр үйлдлийн системүүдийн хувьд өөр хэрэгслүүд байж болохыг анхаараарай. Эдгээрийг мэдсэний дараа `notice` болон түүнээс дээш түвшинд янз бүрийн демонгоос гарч байгаа бүгдийг [.filename]#/var/log/daemon.log# руу лог хийх тохиргооны мөрийг [.filename]#/etc/syslog.conf# руу нэмэх нь хялбар байх болно. Дараахийг нэмэхэд л болно: [.programlisting] .... daemon.notice /var/log/daemon.log .... Түвшингүүд болон хэрэгслүүдийн талаарх дэлгэрэнгүй мэдээллийг man:syslog[3] ба man:syslogd[8]-с үзнэ үү. [.filename]#syslog.conf# болон түүний синтакс, илүү нарийн тохиргоо бүхий жишээнүүдийн талаар дэлгэрэнгүйг man:syslog.conf[5] ба crossref:network-servers[network-syslogd,syslogd ашиглан алсын хост руу бүртгэх нь]-с үзнэ үү. === Лог удирдах ба newsyslog ашиглан багасгах Лог файлууд нь хурдан томорч аажмаар нэмэгдэх нь элбэг байдаг. Энэ нь тийм ч чухал биш мэдээллээр файл болон хатуу дискийг дүүргэхэд хүргэдэг. Үүнийг арилгахын тулд логийн удирдлагыг ашигладаг. FreeBSD-д man:newsyslog[8] ашиглан лог файлуудыг удирддаг. Энэ програм нь тодорхой давтамжтайгаар лог файлуудын хэмжээг багасгаж архивлах болон байхгүй болсон лог файлуудыг үүсгэх, лог файлуудыг зөөх үед дохио өгөх зэрэгт ашиглагддаг. Лог файлууд нь заавал syslog-с гарсан байх шаардлагагүй байдаг. man:newsyslog[8] нь дурын програмаас гарсан дурын логтой ажиллаж чаддаг. `newsyslog`-г man:cron[8]-с ихэвчлэн ажиллуулдаг бөгөөд системийн демон биш гэдгийг санах хэрэгтэй. Анхдагч тохиргоогоор цаг бүр ажиллахаар тохируулагдсан байдаг. ==== newsyslog-г тохируулах Ямар арга хэмжээ авахыг мэдэхийн тулд man:newsyslog[8] анхдагчаар [.filename]#/etc/newsyslog.conf# тохиргооны файлыг уншдаг. Энэ тохиргооны файл нь man:newsyslog[8] удирддаг файл бүрийн хувьд нэг мөрийг агуулсан байдаг. Мөр бүр нь файлын эзэн, зөвшөөрлүүд, файлын хэмжээг хэзээ багасгаж арвивлах болон логийг багасгахад (шахалт гэх мэт) нөлөөлөх нэмэлт флагууд ба логийг хэзээ багасгахыг хэлэх програмуудыг заадаг. Жишээ нь энд FreeBSD дээрх анхдагч тохиргоо байна: [.programlisting] .... # configuration file for newsyslog # $FreeBSD$ # # Entries which do not specify the '/pid_file' field will cause the # syslogd process to be signalled when that log file is rotated. This # action is only appropriate for log files which are written to by the # syslogd process (ie, files listed in /etc/syslog.conf). If there # is no process which needs to be signalled when a given log file is # rotated, then the entry for that file should include the 'N' flag. # # The 'flags' field is one or more of the letters: BCDGJNUXZ or a '-'. # # Note: some sites will want to select more restrictive protections than the # defaults. In particular, it may be desirable to switch many of the 644 # entries to 640 or 600. For example, some sites will consider the # contents of maillog, messages, and lpd-errs to be confidential. In the # future, these defaults may change to more conservative ones. # # logfilename [owner:group] mode count size when flags [/pid_file] [sig_num] /var/log/all.log 600 7 * @T00 J /var/log/amd.log 644 7 100 * J /var/log/auth.log 600 7 100 @0101T JC /var/log/console.log 600 5 100 * J /var/log/cron 600 3 100 * JC /var/log/daily.log 640 7 * @T00 JN /var/log/debug.log 600 7 100 * JC /var/log/init.log 644 3 100 * J /var/log/kerberos.log 600 7 100 * J /var/log/lpd-errs 644 7 100 * JC /var/log/maillog 640 7 * @T00 JC /var/log/messages 644 5 100 @0101T JC /var/log/monthly.log 640 12 * $M1D0 JN /var/log/pflog 600 3 100 * JB /var/run/pflogd.pid /var/log/ppp.log root:network 640 3 100 * JC /var/log/security 600 10 100 * JC /var/log/sendmail.st 640 10 * 168 B /var/log/utx.log 644 3 * @01T05 B /var/log/weekly.log 640 5 1 $W6D0 JN /var/log/xferlog 600 7 100 * JC .... Мөр бүр багасгах файлын нэрээс эхэлдэг бөгөөд үүний дараа багасгасан болон шинээр үүссэн файлуудын эзэн болон бүлэг нэмэлтээр байж болно. Дараагийн талбар `mode` нь файлуудын горим бөгөөд `count` нь багасгасан файл хэдийг үлдээхийг зааж өгдөг. `size` ба `when` талбарууд нь файлыг хэзээ багасгахыг `newsyslog`-д хэлж өгнө. Лог файлыг `size` талбарт зааснаас том болсон үед эсвэл `when` талбарт заасан хугацаа өнгөрсөн үед багасгадаг. `*` нь энэ талбарыг орхино гэсэн утгатай. _flags_ талбар нь багасгасан файлыг хэрхэн шахах эсвэл байхгүй байгаа лог файлыг үүсгэх зэрэг заавруудыг man:newsyslog[8]-д өгдөг. Хамгийн сүүлийн хоёр талбар нь нэмэлт бөгөөд процессын PID-file болон сигналын дугаарыг зааж файлыг багасгах үед тухайн процесс руу илгээх сигналыг зааж өгдөг. Бүх талбарууд, флагууд болон багасгах хугацааг хэрхэн зааж өгөх талаарх дэлгэрэнгүй мэдээллийг man:newsyslog.conf[5]-с үзнэ үү. `newsyslog` нь `cron`-с ажилладаг бөгөөд man:cron[8]-ы ажиллах давтамжаас илүү олон ажиллах боложмгүй гэдгийг санаарай. [[configtuning-configfiles]] == Тохиргооны Файлууд === [.filename]#/etc#-н бүтэц Тохиргооны мэдээллийг хадгалдаг хэд хэдэн сангууд байдаг. Эдгээр нь: [.informaltable] [cols="1,1", frame="none"] |=== |[.filename]#/etc# |Системийн ерөнхий тохиргооны мэдээлэл; энд байгаа өгөгдөл нь системийн хувьд өөр өөр. |[.filename]#/etc/defaults# |Системийн тохиргооны файлуудын анхдагч хувилбарууд. |[.filename]#/etc/mail# |man:sendmail[8]-ийн нэмэлт тохиргоо, бусад MTA тохиргооны файлууд. |[.filename]#/etc/ppp# |Хэрэглэгч- болон цөмийн-ppp програмуудад зориулсан тохиргоо. |[.filename]#/etc/namedb# |man:named[8] өгөгдөлд зориулсан анхдагч байрлал. Ихэнхдээ [.filename]#named.conf# болон бүсийн файлууд энд хадгалагддаг. |[.filename]#/usr/local/etc# |Суулгагдсан програмуудад зориулсан тохиргооны файлууд. Програм болгоны дэд сангуудыг агуулж болно. |[.filename]#/usr/local/etc/rc.d# |Суулгагдсан програмуудад зориулсан эхлүүлэх/зогсоох скриптүүд. |[.filename]#/var/db# |Багцын өгөгдлийн бааз, байршил олох өгөгдлийн бааз, гэх зэрэг систем болгоны хувьд автоматаар үүсгэгдсэн өгөгдлийн баазын файлууд. |=== === Хостын нэрс ==== [.filename]#/etc/resolv.conf# [.filename]#/etc/resolv.conf# нь FreeBSD-ийн тодорхойлогч Интернэт Домэйн Нэрийн Системд (DNS) хэрхэн хандахыг заадаг. [.filename]#resolv.conf# дахь хамгийн түгээмэл оруулгууд нь: [.informaltable] [cols="1,1", frame="none"] |=== |`nameserver` |Тодорхойлогчийн асуух нэрийн серверийн IP хаяг. Серверүүд нь хамгийн ихдээ гурав байх жагсаасан дарааллаар асуугддаг. |`search` |Хостын нэрийн хайлтад зориулж жагсаалтаас хайх. Энэ нь ихэнхдээ локал хостын нэрийн домэйноор тодорхойлогддог. |`domain` |Локал домэйн нэр. |=== Ердийн [.filename]#resolv.conf#: [.programlisting] .... search example.com nameserver 147.11.1.11 nameserver 147.11.100.30 .... [NOTE] ==== `search` болон `domain` тохируулгуудын зөвхөн нэг нь хэрэглэгдэх ёстой. ==== Хэрэв та DHCP ашиглаж байгаа бол man:dhclient[8] нь DHCP серверээс хүлээн авсан мэдээллээр [.filename]#resolv.conf#-г дарж бичдэг. ==== [.filename]#/etc/hosts# [.filename]#/etc/hosts# нь хуучин Интернэтийн үлдэгдэл энгийн текст өгөгдлийн бааз юм. Энэ нь DNS болон NIS-тэй цуг нэрийг IP хаяг уруу болгож тааруулах боломжийг ханган ажилладаг. LAN-аар холбогдсон локал компьютеруудыг амархан нэрлэх зориулалтаар man:named[8] сервер суулгаж тохируулахын оронд энд байрлуулж болдог. Мөн [.filename]#/etc/hosts# нь түгээмэл ханддаг нэрсэд зориулагдсан гадагшаа хандах хүсэлтийг багасгаж Интернэтийн нэрсийн локал бичлэгийг хангадаг байж болно. [.programlisting] .... # $FreeBSD$ # # # Host Database # # This file should contain the addresses and aliases for local hosts that # share this file. Replace 'my.domain' below with the domainname of your # machine. # # In the presence of the domain name service or NIS, this file may # not be consulted at all; see /etc/nsswitch.conf for the resolution order. # # ::1 localhost localhost.my.domain 127.0.0.1 localhost localhost.my.domain # # Imaginary network. #10.0.0.2 myname.my.domain myname #10.0.0.3 myfriend.my.domain myfriend # # According to RFC 1918, you can use the following IP networks for # private nets which will never be connected to the Internet: # # 10.0.0.0 - 10.255.255.255 # 172.16.0.0 - 172.31.255.255 # 192.168.0.0 - 192.168.255.255 # # In case you want to be able to connect to the Internet, you need # real official assigned numbers. Do not try to invent your own network # numbers but instead get one from your network provider (if any) or # from your regional registry (ARIN, APNIC, LACNIC, RIPE NCC, or AfriNIC.) # .... [.filename]#/etc/hosts# нь энгийн хэлбэрийг агуулдаг: [.programlisting] .... [Internet address] [official hostname] [alias1] [alias2] ... .... Жишээ нь: [.programlisting] .... 10.0.0.1 myRealHostname.example.com myRealHostname foobar1 foobar2 .... Дэлгэрэнгүй мэдээллийн талаар man:hosts[5] хуудаснаас зөвлөгөө авна уу. [[configtuning-sysctlconf]] === [.filename]#sysctl.conf# [.filename]#sysctl.conf# нь [.filename]#rc.conf#-той бараг л адил харагддаг. Утгууд нь `хувьсагч=утга` хэлбэрээр заагддаг. Тодорхойлсон утгууд нь систем олон-хэрэглэгчийн горимд шилжсэний дараа тохируулагддаг. Энэ горимд бүх хувьсагчууд тохируулагдах боломжгүй. Сүйрлийн дохионы гаралтуудын бүртгэлийг хааж бусад хэрэглэгчдийн эхлүүлсэн процессуудыг өөр хэрэглэгчдэд харуулахгүй байлгахын тулд дараах тохируулгуудыг [.filename]#sysctl.conf# файлд тохируулж өгч болно: [.programlisting] .... # Do not log fatal signal exits (e.g., sig 11) kern.logsigexit=0 # Prevent users from seeing information about processes that # are being run under another UID. security.bsd.see_other_uids=0 .... [[configtuning-sysctl]] == man:sysctl[8] ашиглан тааруулах нь man:sysctl[8] нь ажиллаж байгаа FreeBSD системд өөрчлөлтүүдийг хийхийг танд зөвшөөрдөг интерфэйс юм. Энэ нь туршлагатай системийн администраторын хувьд ажиллагааг мэдэгдэхүйц сайжруулж чадах TCP/IP болон виртуал санах ойн системийн олон нарийн тохируулгуудыг агуулдаг. Таван зуу гаруй системийн хувьсагчуудыг man:sysctl[8] ашиглан унших болон тохируулж болдог. man:sysctl[8] нь голдоо хоёр үүргийг гүйцэтгэдэг: системийн тохиргоонуудыг унших болон өөрчлөх. Уншигдаж болох бүх хувьсагчуудыг харахдаа: [source,shell] .... % sysctl -a .... Тухайн хувьсагчийг уншихдаа, жишээ нь, `kern.maxproc`: [source,shell] .... % sysctl kern.maxproc kern.maxproc: 1044 .... Тухайн хувьсагчийг заахдаа хялбар _хувьсагч=утга_ синтаксийг ашиглаарай: [source,shell] .... # sysctl kern.maxfiles=5000 kern.maxfiles: 2088 -> 5000 .... sysctl хувьсагчуудын тохиргоонууд нь ихэвчлэн тэмдэгтүүд (strings), тоонууд эсвэл boolean (boolean `1` нь тийм эсвэл `0` нь үгүй байна) утгууд байна. Хэрэв та машин ачаалах болгонд автоматаар зарим хувьсагчуудыг тохируулахыг хүсвэл [.filename]#/etc/sysctl.conf# файлд тэдгээрийг нэмээрэй. Дэлгэрэнгүй мэдээллийн талаар man:sysctl.conf[5] гарын авлагын хуудас болон <>-с үзнэ үү. [[sysctl-readonly]] === Зөвхөн-унших man:sysctl[8] Зарим тохиолдолд зөвхөн-унших man:sysctl[8] утгуудыг өөрчлөх шаардлагатай байж болох юм. Энэ нь заримдаа хийхээс өөр аргагүй байдаг боловч зөвхөн (дахин) ачаалахад хийгдэх боломжтой. Жишээ нь зарим зөөврийн компьютерийн загваруудад man:cardbus[4] төхөөрөмж нь санах ойн хүрээг шалгадаггүй бөгөөд доор дурдсантай төстэй алдаанууд гарган амжилтгүй болдог: [source,shell] .... cbb0: Could not map register memory device_probe_and_attach: cbb0 attach returned 12 .... Дээрх шиг тохиолдлууд нь ихэвчлэн зөвхөн уншихаар тохируулагдсан зарим анхдагч man:sysctl[8] тохиргоонуудыг өөрчлөхийг шаарддаг. Эдгээр нөхцөлүүдийг давж гарахын тулд хэрэглэгч man:sysctl[8] "OID"-уудыг тэдгээрийн [.filename]#/boot/loader.conf# файлд хийж өгч болно. Анхдагч тохиргоонууд [.filename]#/boot/defaults/loader.conf# файлд байрладаг. Дээр дурдсан асуудлыг шийдэхийн тулд хэрэглэгч урьд нь дурдсан файлд `hw.pci.allow_unsupported_io_range=1` гэж тохируулах шаардлагатай. Ингэснээр man:cardbus[4] зөв ажиллах болно. [[configtuning-disk]] == Дискнүүдийг тааруулах нь === Sysctl хувьсагчууд ==== `vfs.vmiodirenable` `vfs.vmiodirenable` sysctl хувьсагч нь 0 (идэвхгүй) эсвэл 1 (идэвхтэй) гэж тохируулагдаж болно; анхдагчаар 1 байна. Энэ хувьсагч нь систем сангуудыг хэрхэн кэш (шуурхай санамж) хийхийг хянадаг. Ихэнх сангууд зөвхөн ганц фрагментийг (ихэвчлэн 1 K) файлын системд болон түүнээс багыг буфер кэшд хэрэглэн жижиг хэмжээтэй байдаг. Энэ хувьсагчийг хааснаар (0 болгосноор) буфер кэш нь таныг асар их хэмжээний санах ойтой байсан ч гэсэн зөвхөн тодорхой тооны сангуудыг кэш хийдэг. Нээгдсэн (1 болгосон) үед энэ sysctl нь бүх санах ойг кэш хийхэд бэлэн болгож буфер кэшд VM Хуудасны Кэшийг хэрэглэн сангуудыг кэш хийх боломжийг олгодог. Гэхдээ сангуудыг кэш хийх хамгийн бага гол дахь санах ой нь 512 байт биш харин физик хуудасны хэмжээ (ихэвчлэн 4 K) байдаг. Хэрэв та их олон тооны файлуудтай ажилладаг үйлчилгээ ажиллуулж байгаа бол бид энэ тохируулгыг идэвхтэй байлгахыг зөвлөж байна. Тийм үйлчилгээнүүдэд вэб кэшүүд, том захидлын системүүд, болон мэдээний системүүд орж болно. Энэ тохируулгыг идэвхтэй байлгах нь хайр гамгүй зарцуулсан санах ойтой байхад ч гэсэн ерөнхийдөө ажиллагааг удаашруулдаггүй, гэхдээ та түүнийг мэдэхийн тулд туршиж үзэж болно. ==== `vfs.write_behind` `vfs.write_behind` sysctl хувьсагчийн анхдагч утга нь `1` (идэвхтэй) байна. Энэ нь том дараалсан файлуудыг бичих үед ихэвчлэн гардаг бүх кластеруудыг цуглуулсан үед зөөгчийн бичилтүүдийг хийхийг файлын системд хэлж өгдөг. Санаа нь бол I/O ажиллагааны хувьд ашиггүй байхад бохир буферууд бүхий буферийн кэшийг замхруулахаас зайлсхийхэд оршдог. Гэхдээ энэ нь процессуудыг зогсоож магадгүй бөгөөд зарим нөхцөл байдалд та магадгүй үүнийг идэвхгүй болгохыг хүсэж болох юм. ==== `vfs.hirunningspace` `vfs.hirunningspace` sysctl хувьсагч өгөгдсөн дурын хоромд системийн хувьд бүхэлд нь хэдий хэмжээний хүлээгдэж байгаа бичих I/O-г дискний хянагчуудад өгөх дараалалд оруулж болохыг тодорхойлдог. Анхдагч утга нь ихэвчлэн хангалттай гэхдээ олон дисктэй машинууд дээр та үүнийг дөрөв эсвэл таван _мегабайт_ хүртэл ихэсгэхийг хүсэж болох юм. Утгыг хэтэрхий өндөр тавих нь (буфер кэшийн бичих тогтоосон хэмжээг давах нь) туйлын муу кластерлах ажиллагаанд хүргэж болно. Энэ утгыг хэтэрхий өндөр бүү тавь! Өндөр бичих утгууд нь яг тэр үед хийгдэж байгаа уншилтуудад хоцрогдол нэмж магадгүй юм. Бусад төрөл бүрийн буфер-кэш болон VM хуудасны кэштэй холбоотой sysctl-ууд байдаг. Бид эдгээр утгуудыг өөрчлөхийг зөвлөдөггүй, VM систем нь өөрийгөө автоматаар тааруулж туйлын сайн ажилладаг. ==== `vm.swap_idle_enabled` `vm.swap_idle_enabled` sysctl хувьсагч нь маш олон хэрэглэгчид таны системд орж гарч байдаг, сул зогссон олон процессуудтай, том, олон-хэрэглэгчийн системүүд дээр ашигтай байдаг. Ийм системүүд нь чөлөөт санах ойн хадгалалтад ихээхэн хэмжээний байнгын дарамтыг үүсгэж байдаг. Энэ боломжийг идэвхтэй болгож ар араас нь swap хийн гаргахыг (зогссон секундээр) `vm.swap_idle_threshold1` болон `vm.swap_idle_threshold2` хувьсагчуудын тусламжтай тохируулснаар зогссон процессуудтай холбоотой санах ойн хуудаснуудын дарааллыг ердийн хуудаслаж гаргах алгоритмаас илүү хурднаар багасгах боломжийг олгодог. Энэ нь хуудаслаж гаргах дэмонд тусламжийн гарыг өгөх болно. Энэ тохируулгыг танд хэрэгтэй л биш бол идэвхтэй болгож болохгүй, учир нь үүнийг та хийснээр үндсэндээ санах ойг илүү түргэн урьдчилан-хуудаслаж ингэснээр swap болон дискний багтаамжийг илүүтэйгээр идэхэд хүргэх юм. Жижиг систем дээр энэ тохируулга нь тодорхойлогдож болохуйц нөлөөлөлтэй байх ба харин боломжийн хуудаслалт аль хэдийн хийгээд байгаа том системүүдэд энэ тохируулга нь VM системд бүх процессуудыг санах ой уруу болон санах ойгоос хялбараар гаргах боломжийг бүрдүүлдэг. ==== `hw.ata.wc` FreeBSD 4.3-д IDE бичих кэш хийлтийг хаасан байдаг. Энэ нь IDE дискэнд бичих багтаамжийг багасгасан боловч хатуу диск үйлдвэрлэгчдийн гаргасан өгөгдлийн бүрэн бүтэн байдлын ноцтой асуудлуудаас болоод шаардлагатай болсон. Тэр асуудал нь IDE хөтлөгчүүд бичилт дуусах үед худлаа мэдээлдэг явдал юм. IDE бичих кэшийг идэвхтэй болгосноор IDE хатуу дискнүүд ямар нэг дараалалгүйгээр бичихээс гадна диск их ачаалалтай үед зарим блокуудыг бичихэд заримдаа тодорхойгүй саатдаг. Сүйрэл болон тэжээлийн уналт файлын системийн ноцтой эвдрэлд хүргэж болзошгүй байдаг. FreeBSD-ийн анхдагч нь аюулгүй байхаар өөрчлөгдсөн. Харамсалтай нь үүний үр дүнд ажиллагааны асар том алдагдалд хүргэсэн бөгөөд хувилбар гарсны дараа бид бичих кэш хийлтийг анхдагчаар идэвхтэй байхаар буцаан өөрчилсөн юм. Та өөрийн систем дээрээ `hw.ata.wc` sysctl хувьсагчийг ажиглан анхдагч утгыг шалгах хэрэгтэй. Хэрэв IDE бичих кэш хийлт хаалттай бол та цөмийн хувьсагчийн утгыг 1 болгон түүнийг идэвхжүүлж болно. Үүнийг ачаалах үед ачаалагчаас хийх шаардлагатай. Цөм ачаалсны дараа хийхийг оролдвол ямар ч нөлөө үзүүлэхгүй. Дэлгэрэнгүй мэдээллийн талаар man:ata[4]-с үзнэ үү. ==== `SCSI_DELAY` (`kern.cam.scsi_delay`) `SCSI_DELAY` цөмийн тохиргоо нь системийн ачаалах хугацааг багасгахад хэрэглэгддэг. Анхдагч утга нь нэлээн өндөр бөгөөд `15` секундын саатлыг ачаалах процессийн үед өгөхийг хариуцдаг. `5` секунд хүртэл багасгахад ихэвчлэн ажилладаг (ялангуяа орчин үеийн хөтлөгчүүдийн хувьд). Ачаалах үеийн тохируулга болох `kern.cam.scsi_delay` хувьсагчийг ашиглах хэрэгтэй. Энэ тохируулга болон цөмийн тохиргооны тохируулга нь _секундээр__биш__миллисекундээр_ утгыг хүлээн авдаг. [[soft-updates]] === Зөөлөн Шинэчлэлтүүд man:tunefs[8] програм файлын системийг нарийн тааруулахад ашиглагдаж болно. Энэ програм нь олон янзын тохируулгуудтай гэхдээ одоохондоо бид зөвхөн Зөөлөн Шинэчлэлтүүдийг идэвхжүүлэх ба хаах дээр анхаарах бөгөөд үүнийг дараах аргаар хийнэ: [source,shell] .... # tunefs -n enable /filesystem # tunefs -n disable /filesystem .... Файлын систем нь холбогдсон байхдаа man:tunefs[8]-ээр өөрчлөгдөх боломжгүй. Зөөлөн Шинэчлэлтүүдийг идэвхжүүлэхэд тохирох үе нь аль ч хуваалтууд холболт хийгдээгүй байгаа ганц хэрэглэгчийн горим юм. Зөөлөн Шинэчлэлтүүд нь мета-өгөгдлийн ажиллагааг мэдэгдэхүйц сайжруулдаг бөгөөд санах ойн кэшийг ашиглан голчлон файлын үүсгэлт болон устгалтыг хурдасгадаг. Бид Зөөлөн Шинэчлэлтүүдийг өөрийн бүх файлын системүүдэд ашиглахыг зөвлөж байна. Зөөлөн Шинэчлэлтүүдийн хоёр дутагдалтай талыг та мэдэж байх ёстой: Нэгдүгээрт, Зөөлөн Шинэчлэлтүүд нь сүйрэл болсон тохиолдолд файлын системийн бүрэн бүтэн байдалд баталгаа өгдөг боловч физик дискийг шинэчлэхэд хэдэн секундын (минут ч байж болно!) хоцрогдолтой байж болно. Хэрэв таны систем сүйрэхэд бусад тохиолдлоос илүүтэйгээр та хийсэн ажлаа алдаж болзошгүй юм. Хоёрдугаарт, Зөөлөн Шинэчлэлтүүд нь файлын системийн блокуудыг чөлөөлөхийг саатуулдаг. Хэрэв та бараг дүүрсэн файлын системтэй (root файл систем гэх зэрэг) байгаа бол `make installworld` зэрэг гол шинэчлэлтийг хийх нь файлын системийг зайгүй болгож шинэчлэлт амжилтгүй болох шалтгаанд хүргэж болох юм. ==== Зөөлөн Шинэчлэлтүүдийн талаар дэлгэрэнгүй Файлын системийн мета-өгөгдлийг диск уруу бичих уламжлалт хоёр хандлага байдаг. (Мета-өгөгдлийн шинэчлэлтүүд нь inode эсвэл сангууд зэрэг агуулгын бус өгөгдөлд хийх шинэчлэлтүүд юм) Түүхээс авч үзэхэд анхдагч ажиллах горим нь мета-өгөгдлийн шинэчлэлтүүдийг синхроноор буюу зэрэг бичдэг байсан явдал юм. Хэрэв сан өөрчлөгдсөн бол систем өөрчлөлтийг диск уруу бичигдэхийг хүлээдэг. Файлын өгөгдлийн буферууд (файлын агуулгууд) буфер кэшээр дамжин диск уруу сүүлд нь асинхроноор хадгалагддаг. Энэ шийдлийн давуу тал нь аюулгүй ажилладаг. Хэрэв шинэчлэлтийн үед амжилтгүй болбол мета-өгөгдөл нь үргэлж бүрэн бүтэн байдаг. Файл эсвэл бүрэн үүсч эсвэл бүр ерөөсөө үүсдэггүй. Хэрэв файлын өгөгдлийн блокууд сүйрэл болох үед буферийн кэшээс диск уруу өөрсдийн гарах замаа олохгүй байгаа бол man:fsck[8] нь үүнийг таньж файлын уртыг 0 болгон файлын системийг засварладаг. Нэмж хэлэхэд энэ шийдэл нь цэвэрхэн ба хялбар юм. Сул тал нь мета-өгөгдлийн өөрчлөлтүүд нь удаан байдаг. `rm -r` тушаал жишээ нь сан дахь бүх файлуудад дараалан хандах бөгөөд гэхдээ сан болгоны өөрчлөлт (файлын устгалт) синхроноор зэрэг диск уруу бичигддэг. Үүнд сан уруу өөрт нь хийгдэх шинэчлэлтүүд, inode хүснэгт болон магадгүй файлын гаргасан шууд бус блокуудад хийх шинэчлэлтүүд ордог. Том иерархуудыг задлахад (`tar -x`) үүний нэгэн адилаар авч үздэг. Хоёр дахь нь асинхрон мета-өгөгдлийн шинэчлэлтүүд юм. Энэ нь Линукс/ext2fs-ийн хувьд анхдагч байх бөгөөд *BSD ufs-ийн хувьд `mount -o async` байх юм. Бүх мета-өгөгдлийн шинэчлэлтүүд нь буфер кэшээр бас дамждаг, тэгэхээр тэдгээр нь файлын агуулгын өгөгдлийн шинэчлэлтүүдтэй харилцан холилдох болно. Энэ шийдлийн давуу тал нь мета-өгөгдөл бүрийн шинэчлэлт диск уруу бичигдэхийг хүлээдэггүй бөгөөд ингэснээр ихээхэн хэмжээний мета-өгөгдлийн шинэчлэлтүүдийг хийдэг бүх үйлдлүүд синхрон хийгдэхээс хамаагүй хурдан ажилладаг. Мөн энэ шийдэл нь цэвэрхэн бас энгийн бөгөөд ингэснээр хорхойнууд (алдаа) код уруу мөлхөн орох эрсдэл бага юм. Сул тал нь файлын системийн бүрэн бүтэн төлвийн ямар нэг баталгаа ерөөсөө байдаггүй. Хэрэв их хэмжээний мета-өгөгдөл шинэчлэх үйлдлийн явцад амжилтгүй болсон бол (тэжээлийн тасалдал, эсвэл хэн нэг нь дахин эхлүүлэх товч дарсан зэрэгт) файлын систем тааж болшгүй төлөвт үлдэх болно. Систем дахин ачаалаад дуусахад файлын системийн төлөвийг мэдэх боломжгүй байдаг; inode хүснэгт эсвэл холбоотой сангийн шинэчлэлтүүд бичигдээгүй байхад файлын өгөгдлийн блокууд диск уруу аль хэдийн бичигдчихсэн байж болох юм. Ер нь гаргасан замбараагүйтлийг (учир нь хэрэгцээтэй мэдээлэл диск дээр байхгүй) цэвэрлэж чаддаг `fsck` тушаалын шийдлийг хийх боломжгүй. Хэрэв файлын систем засвар хийж чадахааргүй эвдэрсэн бол түүнд дээр man:newfs[8]-ийг хэрэглэж нөөцөөс сэргээхээс өөр аргагүй юм. Энэ асуудлын шийдэл нь _бохир бүсийн бүртгэл_ буюу бас _журналчлалт_ гэгддэг шийдлийг гаргах явдал бөгөөд энэ ухагдахуун нь тогтвортой хэрэглэгддэггүй ба шилжүүлэлтийн бүртгэлийн бусад хэлбэрүүдэд бас заримдаа ашиглагддаг. Мета-өгөгдлийн шинэчлэлтүүд нь синхроноор бичигдсэн хэвээр байх бөгөөд гэхдээ зөвхөн дискний жижиг бүсэд бичигдэнэ. Дараа нь тэдгээрийг тэдний зөв байрлал уруу зөөдөг. Бүртгэлийн талбар нь диск дээр бага, үргэлжилсэн бүс байдаг учраас бүр хүнд үйлдлүүдийн үед ч гэсэн дискний толгойнууд шилжихэд хол зайтай биш байдаг болохоор эдгээр үйлдлүүд нь синхрон шинэчлэлтүүдээс илүү хурдан байдаг. Мөн энэ шийдлийн төвөгтэй байдал нь маш хязгаарлагдмал болохоор алдаанууд байх эрсдэл нь бага байдаг. Сул тал нь бүх мета-өгөгдөл нь хоёр удаа бичигддэг (бүртгэлийн бүсэд нэг удаа болон зөв байрлал уруу бас нэг удаа) болохоор энгийн ажлын хувьд ажиллагааны "өөдрөг бус үзэгдэл" гарч болзошгүй юм. Нөгөө талаас сүйрэл болоод систем дахин ачаалаад дуусахад хүлээгдэж байгаа бүх мета-өгөгдлийн үйлдлүүд бүртгэлийн талбараас хурдан буцаагдаж эсвэл гүйцэд хийгдэн дуусч болох бөгөөд энэ нь файлын системийг хурдан эхлүүлэхэд хүргэдэг. Беркли FFS-ийн хөгжүүлэгч Кирк МкКюзик энэ асуудлыг Soft Updates буюу Зөөлөн Шинэчлэлтүүдээр шийдсэн: хүлээгдэж байгаа бүх мета-өгөгдлийн шинэчлэлтүүд нь санах ойд хадгалагдах бөгөөд диск уруу эрэмбэлэгдсэн дарааллаар бичигддэг ("дараалуулсан мета-өгөгдлийн шинэчлэлтүүд"). Энэ нь мета-өгөгдлийн хүнд үйлдлүүдийн үед хэрэв эрт хийгдсэн шинэчлэлтүүд диск уруу бичигдээгүй санах ойд байж байхад нь сүүлд хийгдэх шинэчлэлтүүд тэдгээрийг "барьж" авдаг. Тэгэхээр сангийн хувьд хэлбэл түүнд хийгдэх бүх үйлдлүүд нь санах ойд шинэчлэлт диск уруу бичигдэхээс өмнө хийгддэг (өгөгдлийн блокууд нь мета-өгөгдлөөсөө түрүүлээд диск дээр байж байхгүйгээр өөрсдийн байрлалынхаа дагуу эрэмбэлэгддэг ). Хэрэв систем сүйрвэл энэ нь "бүртгэл урагшлуулахад" хүргэдэг: диск уруу гарах замаа олохгүй байгаа бүх үйлдлүүд хэзээ ч хийгдээгүй юм шиг байдаг. Файлын системийн бүрэн бүтэн төлөв хадгалагдаж 30-аас 60 секундын өмнөх төлөвт ордог. Хэрэглэгдэж байгаа эх үүсвэрүүдийг тэдгээрийн өөрсдийнх харгалзах битмапуудад: блокууд болон inode-уудад байдаг шигээр тэмдэглэхийг үүнд ашигласан алгоритм нь баталгаатай хангадаг. Сүйрэл болсны дараа зөвхөн гарсан эх үүсвэр суллан гаргалтын алдаа нь яг үнэндээ "чөлөөтэй" мөртлөө "ашиглагдаж байгаа" гэж тэмдэглэгдсэн эх үүсвэрүүд байдаг. man:fsck[8] энэ байдлыг таних бөгөөд ашиглагдаагүй байгаа эх үүсвэрүүдийг чөлөөлдөг. Сүйрлийн дараа файлын системийн бохир төлвийг авч үзэлгүйгээр хүчээр `mount -f` тушаалаар холбох нь аюулгүй юм. Ашиглагдаагүй байж болзошгүй эх үүсвэрүүдийг чөлөөлөхдөө man:fsck[8]-г сүүлд нь ажиллуулах хэрэгтэй. Энэ нь _ард ажиллах fsck_-ийн цаана байгаа санаа юм: системийг эхлүүлэх үед зөвхөн файлын системийн _хормын зураг_ бичигддэг. `fsck`-г сүүлд нь ажиллуулж болно. Дараа нь бүх файлын системүүд "бохир" холбогдож системийн эхлэлт олон хэрэглэгчийн горимд үргэлжилдэг. Дараа нь ард ажиллах `fsck`-үүд ашиглагдаагүй байгаа эх үүсвэрүүдийг чөлөөлөхөөр шаардлагатай байгаа бүх файлын системийн хувьд ажиллахаар төлөвлөгддөг. (Зөөлөн Шинэчлэлтүүд ашигладаггүй файлын системүүдэд ердийн нүүрэн дээр ажиллах `fsck` хэрэгтэй хэвээр байна) Давуу тал нь мета-өгөгдлийн үйлдлүүд нь асинхрон шинэчлэлтүүдтэй бараг л адил хурдан байдаг (өөрөөр хэлбэл мета-өгөгдлийг хоёр дахин бичдэг _бүртгэл хийлтээс_ хурдан байдаг). Сул талууд нь төвөгтэй код (хэрэглэгчийн өгөгдлийн алдагдлын хувьд их мэдрэмтгий талбар дахь байж болох алдаануудын тэр өндөр эрсдэлийг хэлж байна) болон санах ойн илүү хэрэглээ юм. Мөн хэн нэгний хэрэглэж байсан хувийн тохиргоонууд ч бас байдаг. Сүйрэл болсны дараа файлын системийн төлөв "хуучин" юм шиг харагддаг. Стандарт синхрон хандлага нь `fsck`-ийн дараа зарим нэг тэг-урттай файлуудыг үлдээхэд хүргэсэн нөхцөлд тэдгээр файлууд нь Зөөлөн Шинэчлэлтүүдтэй файлын системийн үед огт байдаггүй бөгөөд учир нь мета-өгөгдөл болон файлын агуулгууд хэзээ ч диск уруу бичигдээгүй байдаг. Дискний зай нь магадгүй `rm` ажиллуулснаас хэсэг хугацааны дараа диск уруу шинэчлэлтүүд бичигдэх хүртэл сулардаггүй. Энэ нь бүх файлуудыг хоёр дахин хадгалахад хангалттай хүрэлцэхүйц хэмжээний чөлөөтэй зай байхгүй файлын систем дээр их хэмжээний өгөгдлийг суулгаж байх үед асуудлууд гарахад хүргэж болох юм. [[configtuning-kernel-limits]] == Цөмийн хязгаарууд тохируулах нь [[file-process-limits]] === Файл/Процессийн хязгаарууд [[kern-maxfiles]] ==== `kern.maxfiles` `kern.maxfiles` нь таны системийн шаардлагуудаас хамаараад дээшилж эсвэл доошилж болно. Энэ хувьсагч нь таны систем дээрх файлын тодорхойлогчуудын (descriptor) хамгийн их тоог илэрхийлдэг. Файлын тодорхойлогчийн хүснэгт дүүрсэн тохиолдолд `file: table is full` буюу файл: хүснэгт дүүрсэн гэсэн мэдээлэл давтагдан системийн богино мэдээллийн буфферт үзэгдэх бөгөөд үүнийг `dmesg` тушаал ашиглан үзэж болдог. Нээлттэй файл, сокет эсвэл fifo болгон нэг файлын тодорхойлогч хэрэглэдэг. Ажиллаж байгаа том-хэмжээний сервер зэрэгцээ ажиллаж байгаа үйлчилгээнүүдийн тоо болон төрлөөс хамааран олон мянган файлын тодорхойлогчуудыг өлхөн шаардаж болох юм. Хуучин FreeBSD хувилбаруудад `kern.maxfiles`-ийн анхдагч утга нь таны цөмийн тохиргооны файлын `maxusers` тохируулгаас гарсан байдаг. `kern.maxfiles` нь `maxusers` утгатай пропорционалаар өсдөг. Өөрчлөн тохируулсан цөмийг бүтээхдээ энэ цөмийн тохиргооны тохируулгыг өөрийн системийн хэрэглээний дагуу зааж өгөх нь зүйтэй байдаг. Энэ тооноос хамаарч цөм өөрийн ихэнх урьдчилан-тодорхойлсон хязгааруудыг өгдөг. Ажиллагаанд байгаа машин яг үнэндээ нэг удаа 256 хэрэглэгч зэрэг холбогдоогүй байж болох боловч өндөр-хэмжээний вэб серверийнхтэй адил эх үүсвэрүүд хэрэгтэй байж болох юм. `kern.maxusers` хувьсагч нь системд байгаа санах ойн дээр үндэслэн ачаалах үед автоматаар тавигддаг бөгөөд ажиллаж байх явцад зөвхөн уншигдах `kern.maxusers` sysctl хувьсагчийн утгыг шалгаж тогтоогдож болох юм. Зарим сайтууд `kern.maxusers`-ийн илүү их эсвэл бага утгуудыг шаардаж үүнийг ачаалагчаар тааруулагдахаар тохируулж болох юм; 64, 128, болон 256 утгууд нь ховор байдаг. Танд асар их тооны файлын тодорхойлогчууд хэрэгтэй л биш бол бид 256-аас дээш байлгахыг зөвлөдөггүй; өөрсдийн анхдагч утгуудад `kern.maxusers`-р заагддаг, тааруулагдах боломжтой утгуудын олонх нь тус тусдаа ачаалалтын үед эсвэл ажиллах явцад [.filename]#/boot/loader.conf#-оор эсвэл энэ баримтын хаа нэгтээ тайлбарласнаар өөрчлөгдөж болдог (man:loader.conf[5] гарын авлага эсвэл [.filename]#/boot/defaults/loader.conf# файлыг санаа авахын тулд үзнэ үү). Хуучин хувилбаруудад хэрэв та `maxusers`-ийг `0` гэж шууд зааж өгсөн бол систем автоматаар тааруулж өгдөг . Энэ тохируулгыг заахдаа ялангуяа та хэрэв X Цонхны Систем ашиглаж байгаа эсвэл програм хангамж хөрвүүлж байгаа бол `maxusers`-ийг хамгийн багадаа 4 гэж заахыг хүсэх болно. Шалтгаан нь гэвэл `maxusers`-ээр заагдсан хамгийн чухал хүснэгт бол `20 + 16 * maxusers` гэж заагдсан процессуудын хамгийн их тоо бөгөөд хэрэв та `maxusers`-ийг 1 гэж заасан бол та 18 орчмыг нь ачаалах үед системийг эхлүүлэхэд болон 15 орчмыг нь таныг X Цонхны Системийг эхлүүлэхэд магадгүй үүсэж та нийт зөвхөн 36 зэрэг процесстой байж болох юм. Гарын авлагыг унших зэрэг хялбар бодлого хүртэл шүүх, шахсаныг задлах, болон үзэхэд зориулж есөн процессийг эхлүүлдэг. `maxusers`-ийг 64 гэж заах нь бараг л бүх хэрэгцээнд хангалттай байх 1044 зэрэг процесстой байж болохыг танд зөвшөөрнө. Гэхдээ өөр програм эхлүүлэхээр оролдож байх үед эсвэл их олон тооны зэрэгцээ хэрэглэгчидтэй сервер (`ftp.FreeBSD.org`-той адил) ажиллуулж байхад айдас төрүүлэм буюу proc хүснэгт дүүрсэн гэсэн алдаа хэрэв та харах юм бол үргэлж энэ тоог ихэсгэн цөмийг дахин бүтээж болох юм. [NOTE] ==== `maxusers` нь таны машин уруу нэвтрэх хэрэглэгчдийн тоог _хязгаарладаггүй_. Энэ нь ердөө л таны систем дээр байж болох хамгийн их хэрэглэгчийн тоо болон тэдгээр тус бүрийн ажиллуулах процессийн тооноос хамааран төрөл бүрийн хүснэгтийн хэмжээнүүдийг боломжийн утгуудаар зааж өгдөг. ==== ==== `kern.ipc.somaxconn` `kern.ipc.somaxconn` sysctl хувьсагч нь шинэ TCP холболтуудыг хүлээн авахад зориулсан сонсох дарааллын хэмжээг хязгаарладаг. Анхдагч утга `128` нь ачаалал ихтэй вэб серверийн орчин дахь шинэ холболтуудыг хүлээж авахад ерөнхийдөө хэтэрхий бага юм. Тийм орчны хувьд энэ утгыг `1024` эсвэл түүнээс их болгохыг зөвлөдөг. Үйлчилгээний дэмон нь өөрөө сонсох дарааллын хэмжээгээ (өөрөөр хэлбэл man:sendmail[8], эсвэл Apache) хязгаарлаж болох боловч ихэвчлэн өөрийн тохиргооны файлдаа дарааллын хэмжээг тааруулах тохиргооны мөртэй байдаг. Их хэмжээний сонсох дарааллууд нь бас Үйлчилгээг Зогсоох халдлагуудаас () илүү сайн зайлсхийж ажилладаг. [[nmbclusters]] === Сүлжээний хязгаарууд `NMBCLUSTERS` цөмийн тохиргооны тохируулга нь системд байгаа сүлжээний Mbuf-уудын тоог зааж өгдөг. Бага тооны Mbuf-уудтай трафикийн ачаалал ихтэй сервер FreeBSD-ийн чадварт саад болдог. Кластер бүр ойролцоогоор 2 K санах ойг илэрхийлдэг, тийм болохоор 1024 гэсэн утга нь сүлжээний буферуудад зориулж хадгалсан 2 мегабайт цөмийн санах ойг илэрхийлнэ. Хичнээн хэрэгтэйг олохын тулд хялбар тооцоо хийж болно. Хэрэв та хамгийн ихдээ 1000 зэрэгцээ холболтуудтай, холболт бүр нь 16 K хүлээн авах болон 16 K илгээх буферийг иддэг вэб сервертэй бол танд ойролцоогоор вэб серверийг хангахын тулд 32 MB хэмжээтэй тэнцэх сүлжээний буферууд хэрэгтэй болно. Практикаар ер нь 2-оор үржүүлдэг, тэгэхээр 2x32 MB / 2 KB = 64 MB / 2 kB = 32768 болох юм. Бид их санах ойтой машинуудын хувьд утгуудыг 4096-аас 32768-ын хооронд байлгахыг зөвлөдөг. Энэ параметрийн хувьд өндөр утгыг ямар ч нөхцөлд тавьж болохгүй, учир нь энэ нь ачаалах үеийн сүйрэлд хүргэж болно. man:netstat[1]-д `-m` тохируулгыг ашиглаж сүлжээний кластерийн ашиглалтыг ажиглаж болох юм. `kern.ipc.nmbclusters` ачаалалтын тааруулах боломжтой тохируулга нь ачаалах үед үүнийг тааруулахад хэрэглэгдэх ёстой. Зөвхөн FreeBSD-ийн хуучин хувилбарууд `NMBCLUSTERS` цөмийн man:config[8] тохируулгыг ашиглахыг танаас шаарддаг. man:sendfile[2] системийн дуудлагыг өргөнөөр ашигладаг завгүй серверүүдийн хувьд `NSFBUFS` цөмийн тохиргооны тохируулгын тусламжтай эсвэл түүний утгыг [.filename]#/boot/loader.conf#-д зааж man:sendfile[2] буферуудын тоог ихэсгэх шаардлагатай байж болох юм (дэлгэрэнгүйг man:loader[8]-с үзнэ үү). Процессууд `sfbufa` төлөвт харагдах нь энэ параметрийг тааруулах хэрэгтэйг ихэвчлэн заадаг. `kern.ipc.nsfbufs` sysctl хувьсагч нь цөмөөр тохируулагдсан хувьсагч дахь зөвхөн уншигддаг гялбаа юм. Энэ параметр нь `kern.maxusers`-ийн хэмжээгээр тааруулагддаг, гэхдээ үүнийг түүний дагуу тохируурах шаардлагатай байж болох юм. [IMPORTANT] ==== Сокет блок-хийгддэггүй гэж тэмдэглэгдсэн ч гэсэн блок-хийгддэггүй сокет дээр man:sendfile[2]-ийг дуудах нь хангалттай хэмжээний `struct sf_buf`-уудыг бий болготол man:sendfile[2] дуудлага блок хийгдэхэд хүргэж болох юм. ==== ==== `net.inet.ip.portrange.*` `net.inet.ip.portrange.*` sysctl хувьсагчууд нь TCP болон UDP сокетуудад автоматаар уягдах портын дугаарын хүрээнүүдийг хянадаг. Гурван хүрээ байдаг: доод хүрээ, анхдагч хүрээ, болон өндөр хүрээ. Ихэнх сүлжээний програмууд нь анхдагчаар 1024 болон 5000 байдаг `net.inet.ip.portrange.first` болон `net.inet.ip.portrange.last` хувьсагчуудаар хянагддаг анхдагч хүрээг ашигладаг. Уягдах портын хүрээнүүд гарах холболтуудад ашиглагддаг бөгөөд зарим тохиолдолд систем дэх портууд дуусч болох юм. Энэ нь ихэвчлэн таныг ачаалал ихтэй вэб прокси ашиглаж байхад гардаг. Ихэвчлэн ирж байгаа холболтуудыг хүлээн авдаг ердийн вэб сервер эсвэл захидал дамжуулагч зэрэг хязгаарлагдмал тооны гарах холболтуудтай серверүүдийг ажиллуулж байхад портын хүрээ нь асуудал биш юм. Таны порт дуусаж болох тийм тохиолдлуудад `net.inet.ip.portrange.last` хувьсагчийг даруухнаар ихэсгэхийг зөвлөдөг. `10000`, `20000` эсвэл `30000` нь боломжийн утгууд юм. Портын хүрээг өөрчилж байхдаа галт ханын нөлөөллүүдийг бас бодолцох хэрэгтэй. Зарим галт хана их хэмжээний портуудыг хааж болох бөгөөд (ихэнхдээ бага дугаарын портууд) систем өндөр дугаарын портуудыг гарах холболтууддаа ашигладгийг бодолцох ёстой - ийм учраас `net.inet.ip.portrange.first`-ийг багасгахыг зөвлөдөггүй. ==== TCP хурд сааруулагч бүтээгдэхүүнүүд TCP хурд сааруулагч бүтээгдэхүүний хязгаарлалт нь NetBSD дэх TCP/Vegas-тай адилхан юм. `net.inet.tcp.inflight.enable` sysctl хувьсагчийг `1` болгон тохируулж үүнийг идэвхжүүлдэг. Систем холболт бүрийн хувьд хурд сааруулагч бүтээгдэхүүнийг тооцоолохыг оролддог бөгөөд сүлжээн дэх дараалалд оруулах өгөгдлийн хэмжээг хамгийн боломжийн нэвтрүүлэх чадамжийг байнга барьж байх тэр хэмжээнд хүргэж хязгаарладаг. Хэрэв та өгөгдлийг модемууд, Гигабит Ethernet, эсвэл бүр өндөр хурдны WAN холболтуудаар (эсвэл дурын өндөр хурд сааруулагч бүтээгдэхүүнтэй холболт) дамжуулж байгаа бол ялангуяа та бас цонх өсгөлтийг ашиглаж байгаа эсвэл том илгээх цонх тохируулсан бол энэ боломж нь ашигтай юм. Хэрэв та энэ тохируулгыг идэвхжүүлэх бол бас `net.inet.tcp.inflight.debug`-ийг `0` (дибаг хийхийг болиулах) болгож тохируулах хэрэгтэй бөгөөд үйлдвэрлэлийн ашиглалтад `net.inet.tcp.inflight.min`-ийг хамгийн багаар бодоход `6144` болгох нь ашигтай байж болох юм. Гэхдээ хамгийн бага тоог өндөр болгох нь холболтоос хамааран хурд хязгаарлалтыг идэвхтэйгээр болиулж болохыг санах хэрэгтэй. Хязгаарлах боломж нь дундын чиглүүлэлтийн үед бүтээгдсэн өгөгдлийн хэмжээг багасгах бөгөөд пакетийн дарааллуудыг сольж локал хостын интерфэйс дэх дараалал дээр бүтээгдсэн өгөгдийн хэмжээг мөн багасгадаг. Дараалалд орсон цөөн тооны пакетуудтай, ялангуяа удаан модемоор дамжсан интерактив холболтууд нь бага _Round Trip Times буюу Эргэн Аялах Хугацаатайгаар_ ажиллаж бас чаддаг. Гэхдээ энэ боломж нь зөвхөн өгөгдөл дамжуулалтад (илгээх / сервер талын) нөлөөлдгийг санах хэрэгтэй. Энэ нь өгөгдөл хүлээн авахад нөлөө үзүүлэхгүй (татаж авах). `net.inet.tcp.inflight.stab`-ийг тааруулахыг _зөвлөдөггүй_. Энэ параметр нь хурд сааруулах бүтээгдэхүүний цонхны тооцоололд нэмсэн 2 хамгийн их пакетийг илэрхийлж анхдагчаар 20 байдаг. Энэ алгоритмийг тогтворжуулах болон өөрчлөгдөж байгаа нөхцлүүдэд хариу өгөх боломжийг сайжруулахад нэмэлт цонх шаардлагатай боловч энэ нь бас удаан холболт дээр ping хийх хугацаа ихэсгэхэд хүргэдэг (гэхдээ таныг энэ (inflight) алгоритмийг ашиглаагүй байхад гарсан үр дүнгээс хамаагүй бага хэвээр л байна). Ийм тохиолдолд энэ параметрийг 15, 10, эсвэл 5 болгон багасгахыг хүсэж болох юм; мөн хүссэн үр дүндээ хүрэхийн тулд `net.inet.tcp.inflight.min` хувьсагчийг (жишээ нь 3500 болгож) бас багасгаж болох юм. Эдгээр параметрүүдийг багасгах нь хамгийн сүүлд авах арга хэмжээ байх ёстой юм. === Виртуал санах ой ==== `kern.maxvnodes` vnode нь файл эсвэл сангийн дотоод дүрслэл юм. Тэгэхээр үйлдлийн системд байх vnode-ийн тоог ихэсгэх нь диск I/O-г багасгадаг. Энэ нь ихэвчлэн үйлдлийн системээр зохицуулагддаг бөгөөд өөрчлөх хэрэггүй байдаг. Зарим тохиолдолд диск I/O нь гол асуудал учруулж системд vnode байхгүй болж байвал энэ тохируулгыг ихэсгэх хэрэгтэй болно. Идэвхгүй болон чөлөөтэй RAM-ийн хэмжээг бодолцох шаардлагатай. Тухайн үед ашиглагдаж байгаа vnode-уудыг үзэхдээ: [source,shell] .... # sysctl vfs.numvnodes vfs.numvnodes: 91349 .... Хамгийн их vnode-уудыг үзэхдээ: [source,shell] .... # sysctl kern.maxvnodes kern.maxvnodes: 100000 .... Хэрэв тухайн үеийн vnode ашиглалт хамгийн их хэмжээ уруу бараг дөхөж байвал `kern.maxvnodes`-ийг 1,000-аар ихэсгэх нь зүйтэй байж болох юм. `vfs.numvnodes`-ийн тоон дээр бас анхаарлаа хандуулаарай. Хэрэв энэ нь дахин хамгийн их уруугаа дээшилбэл `kern.maxvnodes`-ийг цааш ихэсгэх шаардлагатай болно. man:top[1]-ийн гаргасан дүнгээс таны санах ойн өөрчлөлт харагдах ёстой. Түрүүнийхээс илүү санах ой идэвхтэй байх ёстой. [[adding-swap-space]] == Swap зай нэмэх нь Та яаж ч сайн төлөвлөсөн байлаа гэсэн заримдаа систем таны бодсоноор ажилладагүй. Хэрэв танд swap зай илүү хэрэгцээтэйг мэдвэл та үүнийг амархнаар нэмж болно. Та гурван аргаар swap зайг ихэсгэж болно: шинэ хатуу диск нэмэх, NFS-ийн тусламжтай swap идэвхжүүлэх болон байгаа хуваалт дээр swap файл үүсгэж ихэсгэж болно. Swap зайг хэрхэн шифрлэх, ямар тохируулгууд байгаа болон яагаад хийх ёстой талаар гарын авлагын crossref:disks[swap-encrypting,Swap зайг шифрлэх] хуудсанд хандана уу. [[new-drive-swap]] === Шинэ эсвэл байгаа диск дээрх swap swap-т зориулж шинэ хатуу диск нэмэх нь байгаа диск дээр хуваалт нэмэхээсээ илүүтэй ажиллагааны хувьд сайжруулдаг. Хуваалтуудыг үүсгэх болон хатуу диск нэмэх талаар crossref:disks[disks-adding,Диск нэмэх] хэсэгт тайлбарласан байгаа. <> хэсэгт хуваалтын байдал болон swap хуваалтын зайн талаарх анхаарах зүйлсийг тайлбарласан байгаа. man:swapon[8] ашиглан swap хуваалтыг системийг нэмж өгнө. Жишээ нь: [source,shell] .... # swapon /dev/ada1s1b .... [WARNING] ==== Өгөгдөлтэй ч гэсэн холбогдоогүй байгаа хуваалтыг ашиглах боломжтой. man:swapon[8] ашигласнаар өгөгдэлтэй байгаа хуваалт дээр бичилт хийгдэж өгөгдлийг нь устгах болно. swap хэлбэрээр нэмэгдэх хуваалт нь яг тэр зорилгоор ашиглагдах гэж байгаа эсэхийг man:swapon[8] ажиллуулахаасаа өмнө шалгаарай. ==== Ачаалахад ашиглагдахаар автоматаар энэ swap хуваалтыг нэмэхийн тулд [.filename]#/etc/fstab# файлд тухайн хуваалтын талаарх оруулгыг нэмнэ: [.programlisting] .... /dev/ada1s1b none swap sw 0 0 .... [.filename]#/etc/fstab# дахь оруулгуудын талаарх тайлбарыг man:fstab[5] гарын авлагын хуудаснаас үзнэ үү. [[nfs-swap]] === NFS-ийн тусламжтай swap хийх нь NFS-ийн тусламжтай swap хийхийг зөвхөн swap хийх локал хатуу диск танд байхгүй үед л зөвлөдөг; NFS swap хийх нь байгаа сүлжээний хурдаар хязгаарлагддаг бөгөөд NFS серверт нэмэлт ачаалал үзүүлдэг. [[create-swapfile]] === Swap файлууд Та swap файл болгон ашиглахаар заасан хэмжээтэй файлыг үүсгэж болно. Энд байгаа жишээн дээр бид [.filename]#/usr/swap0# гэсэн нэртэй 64MB файлыг ашиглана. Мэдээж та хүссэн ямар ч нэрээ ашиглаж болно. .Swap файл FreeBSD дээр үүсгэх нь [example] ==== . [.filename]#GENERIC# цөм нь энэ үйлдэлд шаардлагатай санах ойн дискний драйверийг (man:md[4]) агуулсан байдаг. Цөмийг тохируулан өөрчлөх гэж байгаа бол доорх мөрийг цөмийн тохиргооны файлдаа оруулахаа мартуузай: + [.programlisting] .... device md .... + Өөрийн хэрэгцээнд зориулж цөм бүтээх талаар crossref:kernelconfig[kernelconfig,FreeBSD цөмийг тохируулах нь] бүлгээс үзнэ үү. . Swap файл ([.filename]#/usr/swap0#) үүсгэнэ: + [source,shell] .... # dd if=/dev/zero of=/usr/swap0 bs=1024k count=64 .... . Зөв зөвшөөрлүүдийг ([.filename]#/usr/swap0#-д) нээж тохируулна: + [source,shell] .... # chmod 0600 /usr/swap0 .... . [.filename]#/etc/rc.conf#-д swap файлыг идэвхжүүлнэ: + [.programlisting] .... swapfile="/usr/swap0" # Set to name of swapfile if aux swapfile desired. .... . Машиныг дахин эхлүүлнэ эсвэл swap файлыг шууд идэвхжүүлэхийн тулд дараах тушаалыг ажиллуулна: + [source,shell] .... # mdconfig -a -t vnode -f /usr/swap0 -u 0 && swapon /dev/md0 .... ==== [[acpi-overview]] == Тэжээл болон Эх үүсвэрийн Удирдлага Тоног төхөөрөмжийн эх үүсвэрүүдийг үр ашигтай ашиглах нь чухал юм. ACPI танилцуулагдахаас өмнө системийн тэжээлийн ашиглалт болон дулааны шинж чанаруудыг удирдахад үйлдлийн системүүдийн хувьд хэцүү, уян хатан биш байсан. Тоног төхөөрөмж нь BIOS-оор удирдагддаг байсан болохоор тэжээлийн удирдлагын тохиргоонуудын харагдац бага бөгөөд хэрэглэгчид хянах боломж бага байсан юм.Зарим нэгэн хязгаарлагдмал тохиргооны боломж _Advanced Power Management буюу Тэжээлийн Дэвшилттэй Удирдлага (APM)_ интерфэйсээр хийгдэх боломжтой байсан. Тэжээл болон Эх үүсвэрийн Удирдлага нь орчин үеийн үйлдлийн системийн түлхүүр хэсгүүдийн нэг юм. Жишээ нь таны системийн хэм гэнэт нэмэгдэх тохиолдолд системийн хязгааруудыг үйлдлийн систем монитор хийхийг (магадгүй танд мэдээлэхийг) хүсэж болох юм. FreeBSD Гарын авлагын энэ хэсэгт бид ACPI-ийн талаар нэвтэрхий мэдээллээр хангах болно. Цааш нэмж уншихад зориулсан мэдээллүүдийг төгсгөл хэсэгт оруулсан байгаа. [[acpi-intro]] === ACPI гэж юу вэ? Advanced Configuration and Power Interface буюу Дэвшилттэй Тохиргоо ба Тэжээлийн Интерфэйс (ACPI) нь тоног төхөөрөмжийн эх үүсвэрүүд болон тэжээлийн удирдлагад (эндээс нэр гарсан) зориулсан стандарт интерфэйсийг хангах зорилгоор үйлдвэрлэгчдийн холбооноос бичин гаргасан стандарт юм. Энэ нь _Үйлдлийн Системээр заалгасан тохиргоо ба Тэжээлийн Удирдлагын_ түлхүүр элемент юм, өөрөөр хэлбэл: энэ нь илүү хяналт болон уян хатан байдлыг үйлдлийн системд (OS) хангадаг. ACPI-г танилцуулахаас өмнө одоогийн Залгаад Тоглуулах интерфэйсүүдийн хязгааруудыг орчин үеийн системүүд "сунгасан" юм. ACPI нь APM-ийн (Advanced Power Management буюу Тэжээлийн Дэвшилтэт Удирдлага) шууд залгамжлагч юм. [[acpi-old-spec]] === Тэжээлийн Дэвшилтэт Удирдлагын (APM) сул талууд _Тэжээлийн Дэвшилтэт Удирдлага (APM)_ боломж нь системийн тэжээлийн ашиглалтыг түүний ажиллагаан дээр үндэслэн хянадаг. APM BIOS нь (систем) үйлдвэрлэгчээс хангагддаг бөгөөд тоног төхөөрөмжийн тавцан бүрийн хувьд онцлог байдаг. OS дахь APM драйвер нь тэжээлийн түвшингүүдийн удирдлагыг зөвшөөрдөг _APM Програм хангамжийн Интерфэйс_ уруу хандах хандалтыг зуучилж өгдөг. APM-ийг 2000 онд болон тэрнээс өмнө үйлдвэрлэсэн системүүдэд ашиглах ёстой хэвээр байдаг. APM-д дөрвөн үндсэн асуудал байдаг. Нэгдүгээрт, тэжээлийн удирдлага (үйлдвэрлэгчийн онцлогтой) BIOS-оор хийгддэг бөгөөд OS нь энэ талын ямар ч мэдлэг байдаггүй. Үүний нэг жишээ нь хэрэглэгч хатуу дискний сул зогсох хугацааг APM BIOS дээр зааж өгөөд тэр нь зааснаас илүү гарвал BIOS хатуу дискийг OS-ийн зөвшөөрөлгүйгээр эргүүлдэг. Хоёрдугаарт, APM-ийн логик BIOS-д суулгагдсан байдаг бөгөөд OS-ийн эрх хэмжээнээс гадна ажилладаг. Энэ нь хэрэглэгчид өөрсдийн APM BIOS-ийг зөвхөн шинэ хувилбараар нь ROM уруу нь шарж асуудлуудыг засварлах боломжтой гэсэн үг юм; энэ нь амжилтгүй болбол системийг дахин сэргээгдэхгүй төлөвт орхиж болох боломжтой маш аюултай процедур юм. Гуравдугаарт, APM нь үйлдвэрлэгчийн онцлогтой технологи бөгөөд энэ нь маш олон адил төсөөтэй байдал (чармайлтуудын хуулбар) болон нэг үйлдвэрлэгчийн BIOS-д олдсон алдаанууд бусад үйлдвэрлэгчдийн хувьд шийдэгдээгүй байж болно гэсэн үг юм. Хамгийн сүүлд гэхдээ төгсгөлийнх биш, APM BIOS нь тэжээлийн маш нарийн бодлого эсвэл машины зориулалтад зориулагдан маш сайн тохируулагдах тийм шийдлийг хийхэд хангалттай зайгүй байдаг. _Залгаад Тоглуулах BIOS (PNPBIOS)_ нь олон тохиолдолд найдвартай биш байсан юм. PNPBIOS нь 16-битийн технологи, тийм болохоор OS нь PNPBIOS аргуудтай холбогдохдоо 16-битийн эмуляц хэрэглэх шаардлагатай болдог. FreeBSD-ийн APM драйвер man:apm[4] гарын авлагын хуудсанд баримтжуулагдсан байдаг. [[acpi-config]] === ACPI-г тохируулах нь [.filename]#acpi.ko# драйвер нь системийг эхлүүлэх үед man:loader[8]-оор анхдагчаар ачаалагддаг бөгөөд цөмд оруулж _хөрвүүлэгдэх_ ёсгүй. Үүний цаадах шалтгаан нь модулиудтай ажиллах хялбар байдаг, өөрөөр хэлбэл цөмийг дахин хөрвүүлэлгүйгээр өөр [.filename]#acpi.ko# уруу шилждэг. Энэ нь тест хийлтийг илүү амархан болгодог давуу талтай юм. Нөгөө нэг шалтгаан нь системийг ажиллуулж дууссаны дараа ACPI-г ажиллуулахад ихэвчлэн сайн ажилладаггүй. Хэрэв та асуудлуудтай учирч байгаа бол ACPI-г бүхэлд нь хаах хэрэгтэй. Энэ драйверийг ачаалсны дараа буулгаж болиулж чаддаггүй, болдоггүй, учир нь системийн шугам үүнийг төрөл бүрийн тоног төхөөрөмжүүдийн харилцан үйлдлүүдэд хэрэглэдэг. ACPI-г [.filename]#/boot/loader.conf# файлд юм уу эсвэл man:loader[8] хүлээх мөрөнд `hint.acpi.0.disabled="1"` гэж тохируулан хааж болдог. [NOTE] ==== ACPI болон APM нь цуг байж болохгүй бөгөөд салангид хэрэглэгдэх ёстой. Сүүлд ачаалагдах драйвер нь хэрэв нөгөө нэгийг ажиллаж байгааг мэдвэл ажиллагаагаа дуусгавар болгодог. ==== ACPI нь man:acpiconf[8]-ийн `-s` туг болон `1-5` тохируулгын тусламжтайгаар системийг унтах горим шилжүүлэхэд хэрэглэгдэж болно. Ихэнх хэрэглэгчдэд зөвхөн `1` эсвэл `3` (RAM руу түр зогсоох) хэрэгтэй байдаг. `5` тохируулга нь дараах тушаалтай нэг ёсондоо адилыг гүйцэтгэнэ: [source,shell] .... # halt -p .... Бусад тохируулгууд man:sysctl[8]-ийн тусламжтай байдаг. Дэлгэрэнгүй мэдээллийн талаар man:acpi[4] болон man:acpiconf[8] гарын авлагын хуудаснуудаас шалгана уу. [[ACPI-debug]] == FreeBSD-ийн ACPI-г ашиглах нь ба дибаг хийх нь ACPI нь төхөөрөмжүүдийг илрүүлэх, тэжээлийн ашиглалтыг удирдах болон урьд нь BIOS-оор удирдагддаг байсан төрөл бүрийн тоног төхөөрөмжид хандах стандартчилагдсан хандалтыг хангадаг цоо шинэ арга юм. Бүх системүүд дээр ACPI-г ажиллуулах тал дээр дэвшил хийгдсэн бөгөөд гэхдээ зарим эх хавтангуудын __ACPI Машины Хэл__ний (AML) байткод дахь алдаанууд, FreeBSD-ийн цөмийн дэд системүүдийн бүрэн бүтэн бус байдал болон Intel(R) ACPI-CA тайлбарлагч дахь алдаанууд илэрсээр байна. Энэ баримт нь таныг FreeBSD-ийн ACPI дэмжигчдэд тусалж таны ажигласан асуудлуудын үндсэн учир шалтгааныг таних, дибаг хийх болон шийдлийг хөгжүүлэхэд туслах зорилготой юм. Үүнийг уншиж байгаад талархлаа илэрхийлэхийн ялдамд бид таны системийн асуудлуудыг шийдэж чадна гэдэгт найдаж байна. [[ACPI-submitdebug]] === Дибаг мэдээллийг илгээх нь [NOTE] ==== Асуудлыг илгээхээсээ өмнө та хамгийн сүүлийн үеийн BIOS-ийн хувилбар болон хэрэв байх юм бол суулгагдсан хянагчийн хамгийн сүүлийн firmware хувилбар ажиллуулж байгаа эсэхээ шалгаарай. ==== Асуудлыг шууд илгээхийг хүсэж байгаачууд дараах мэдээллийг link:mailto:freebsd-acpi@FreeBSD.org[freebsd-acpi@FreeBSD.org] уруу илгээнэ үү: * Системийн төрөл болон загварыг оролцуулан алдааг гаргаж байгаа зүйлийн хамтаар алдаатай ажиллагааг тайлбарласан мэдээлэл. Мөн хэрэв алдаа таны хувьд шинэ бол яг хэзээ гарч эхэлснийг аль болох тодорхой гаргаарай. * `boot -v` ажилласны дараах man:dmesg[8]-ийн гаралтыг алдааг шалгаж байхад таны үүсгэсэн алдааны мэдээллүүдийн хамтаар. * Хэрэв ACPI-г хаасан байхад асуудлыг шийдэж байвал тийм байх үе дэх `boot -v`-ийн гаралт. * `sysctl hw.acpi`-ийн гаралт. Энэ нь таны систем ямар ямар боломжуудыг санал болгож байгааг мэдэх бас нэг сайн арга юм. * Таны _ACPI Эх Хэл_ (ASL) байх URL хаяг. ASL нь маш том байж болох учир шууд _битгий_ жагсаалт уруу илгээгээрэй. Өөрийн ASL-ийн хуулбарыг энэ тушаалыг ашиглаж үүсгээрэй: + [source,shell] .... # acpidump -dt > name-system.asl .... + (Өөрийн нэвтрэх нэрийг _name_-ийн оронд болон үйлдвэрлэгч/загварыг _system_-ийн оронд солиорой. Жишээ нь: [.filename]#njl-FooCo6000.asl#) Ихэнх хөгжүүлэгчид {freebsd-current} үзэж байдаг, гэхдээ асуудлуудаа харагдуулахын тулд {freebsd-acpi} уруу илгээгээрэй. Бид бүгд хаа нэгтээ өөр өөрийн үндсэн ажилтай учир тэвчээртэй байна уу. Хэрэв таны алдаа шууд илэрхий биш байх юм бол магадгүй бид таныг man:send-pr[1]-ийн тусламжтай PR илгээхийг асуух байх. PR оруулахдаа дээр хүссэний адил мэдээллээ оруулна уу. Энэ нь асуудлыг мөшгөж шийдвэрлэхэд бидэнд туслах юм. Бид PR-уудыг мэдээлэх механизмын зорилгоор биш байгаа асуудлуудыг санаж байх зорилгоор ашигладаг болохоор эхлээд {freebsd-acpi} уруу захидал илгээлгүйгээр PR битгий илгээгээрэй. Магадгүй таны асуудлыг урд нь өөр хэн нэгэн мэдээлсэн байж болох юм. [[ACPI-background]] === Оршил ACPI нь ia32 (x86), ia64 (Itanium) болон amd64 (AMD) архитектуруудтай нийцтэй орчин үеийн бүх компьютерт байдаг. Бүрэн стандарт нь CPU-ны ажиллагааны удирдлага, тэжээлийн онгоцуудын хяналт, дулааны бүсүүд, төрөл бүрийн батарейний системүүд, суулгагдсан хянагчууд болон шугамын жагсаалт зэрэг олон боломжуудтай. Ихэнх системүүд нь бүрэн стандартыг бүгдийг хангасан шийдэлтэй байдаггүй. Жишээ нь зөөврийн компьютер хөргөх болон бас батарейний удирдлагын дэмжлэгтэй байхад ширээний систем зөвхөн шугамын жагсаалтын хэсгийн шийдлийг агуулсан байдаг. Зөөврийн компьютерууд нь бас өөр өөрийн ярвигтай асуудлуудыг агуулсан түр зогсоох болон үргэлжлүүлэх боломжуудыг агуулдаг. ACPI-нийцтэй систем нь төрөл бүрийн хэсгүүдтэй байдаг. BIOS болон бичил схемийн үйлдвэрлэгчид APIC зураг (SMP-д ашиглагддаг), тохиргооны регистрүүд болон хялбар тохиргооны утгууд зэрэг зүйлсүүдийг заадаг төрөл бүрийн тогтмол хүснэгтүүдийг (өөрөөр хэлбэл FADT) санах ойд хангаж өгдөг. Мөн төхөөрөмжүүд болон аргуудын мод хэлбэрийн нэрийн талбарыг заадаг байткодын хүснэгтээр (_Differentiated System Description Table буюу Системийн Ялгаварласан Тайлбарын Хүснэгт_ DSDT) бас хангадаг. ACPI драйвер нь тогтмол хүснэгтүүдийг задлан ялгал хийх, байткодын тайлбарлагчийг шийдэх болон ACPI дэд системийн мэдээллийг хүлээн авахаар төхөөрөмжүүдийн драйверууд болон цөмийг өөрчлөх ёстой. FreeBSD-ийн хувьд Intel(R) нь Линукс болон NetBSD-тэй хуваалцан хэрэглэгддэг тайлбарлагчаар хангадаг. ACPI-CA эх кодын зам нь [.filename]#src/sys/contrib/dev/acpica#. ACPI-CA-г FreeBSD дээр ажиллуулах тэр цавуу код нь [.filename]#src/sys/dev/acpica/Osd# байршилд байдаг. Эцэст нь төрөл бүрийн ACPI төхөөрөмжүүдийн драйверууд [.filename]#src/sys/dev/acpica# байршлаас олддог. [[ACPI-comprob]] === Нийтлэг асуудлууд ACPI зөв ажиллахын тулд бүх хэсгүүд бас зөв ажилласан байх ёстой. Энд зарим нэг нийтлэг асуудлуудыг илэрч байгаа давтамжийн дарааллаар зарим нэг тойрон гарах замууд болон засваруудтайгаар нь дурдъя. ==== Хулганы асуудлууд Зарим тохиолдолд түр зогсоох үйлдэл хийгдсэний дараа үргэлжлүүлэхэд хулганыг ажиллахгүй болгодог. Мэдэгдэж байгаа тойрон гарах арга зам нь `hint.psm.0.flags="0x3000"` мөрийг [.filename]#/boot/loader.conf# файлд нэмэх явдал юм. Хэрэв энэ нь ажиллахгүй бол дээр тайлбарласны дагуу алдааны тайлан илгээхийг бодно уу. ==== Suspend/Resume буюу Түр зогсоох/Үргэлжлүүлэх ACPI нь RAM уруу түр зогсоох `S1`-`S3` гэсэн гурван төлөвтэй (STR) бөгөөд диск уруу түр зогсоох `S4` гэгддэг нэг төлөвтэй (`STD`). `S5` нь "soft off буюу зөөлөн зогсоолт" бөгөөд тэжээлд залгагдсан боловч асаагдаагүй байх үеийн таны системийн жирийн төлөв юм. `S4` нь хоёр тусдаа аргаар хийгдэх боломжтой. ``S4``BIOS нь BIOS-ийн тусламжтайгаар диск уруу хийгдэх түр зогсоолт юм. ``S4``OS нь бүхэлдээ үйлдлийн системээр хийгддэг. Түр зогсоолттой холбоотой зүйлүүдийг `sysctl hw.acpi` тушаалаар шалгаж эхлээрэй. Энд Thinkpad-тай холбоотой үр дүнгүүд байна: [source,shell] .... hw.acpi.supported_sleep_state: S3 S4 S5 hw.acpi.s4bios: 0 .... Энэ нь бид `S3`, ``S4``OS болон `S5`-ийг шалгахад `acpiconf -s` тушаалыг ашиглаж болно гэсэн үг юм. Хэрэв `s4bios` нь нэг (`1`) байх юм бол бид ``S4``OS-ийн оронд ``S4``BIOS дэмжлэгтэй байх юм. Түр зогсоолт/үргэлжлүүлэлтийг тест хийхдээ хэрэв дэмжигдсэн бол `S1`-ээс эхлээрэй. Энэ төлөв нь драйверийн дэмжлэг барагтаа л шаарддаггүй болохоор бараг л ажиллах болно. Хэн ч `S2`-ийг хийгээгүй байдаг бөгөөд танд энэ хэрэв байгаа бол энэ нь `S1`-тэй адил байна. Дараагийн оролдох зүйл нь `S3` юм. Энэ нь хамгийн гүнзгий STR төлөв бөгөөд таны тоног төхөөрөмжийг дахин зөв эхлүүлэхийн тулд драйверийн ихээхэн дэмжлэг шаарддаг. Хэрэв үргэлжлүүлэх үед танд асуудлууд гарч байгаа бол {freebsd-acpi} жагсаалт уруу цахим захидал чөлөөтэй илгээгээрэй, гэхдээ илүү их тест хийлт, ажил шаардсан маш олон драйверууд/тоног төхөөрөмжүүд байдаг учир асуудал шийдэгдэхийг хүлээх хэрэггүй юм. Түр зогсоолт/үргэлжлүүлэлттэй холбоотой түгээмэл асуудал бол олон төхөөрөмжийн драйверууд өөрсдийн эхлүүлэх програм, регистрүүд болон төхөөрөмжийн санах ойг зөв хадгалж, сэргээж, эсвэл дахин эхлүүлж чаддаггүй. Асуудлыг эхний удаа дибаг хийхийг оролдохдоо дараах тушаалыг ажиллуулж үзээрэй: [source,shell] .... # sysctl debug.bootverbose=1 # sysctl debug.acpi.suspend_bounce=1 # acpiconf -s 3 .... Энэ тест нь `S3` төлөв рүү жинхнээсээ оролгүйгээр бүх төхөөрөмжийн драйверуудын түр зогсолт/үргэлжлүүлэлтийн циклийг эмуляц хийдэг. Зарим тохиолдолд энэ аргыг ашиглан та асуудлыг хялбархнаар олж болно (жишээ нь эхлүүлэх програмын төлөв алдагдах, төхөөрөмжийн watchdog timeout болж дуусахгүй дахин оролдох). Систем нь жинхнээсээ `S3` төлөвт орохгүй болохыг санаарай. Тэгэхээр төхөөрөмжүүд нь тэжээлээс салгагдахгүй бөгөөд түр зогсолт/үргэлжлүүлэлтийн арга тэдний хувьд байхгүй гэсэн олонхи нь зүгээр ажиллах болно. Харин жинхэнэ `S3` төлвийн хувьд эсрэгээр байж магадгүй юм. Хэцүү тохиолдлууд нэмэлт тоног төхөөрөмж шаарддаг, жишээ нь цуваа консолд зориулсан цуваа порт/кабель эсвэл man:dcons[4]-д зориулсан Firewire порт/кабел болон цөм дибаг хийх чадвар зэргийг дурдаж болно. Асуудлыг тусгаарлахад туслахын тулд өөрийн цөмөөс аль болох олон драйверуудыг арилгаарай. Хэрэв энэ нь ажиллаж байвал та яг аль драйвер асуудалтай байгааг драйверуудыг амжилтгүй ажиллах хүртэл ачаалан тодорхойлж болох юм. [.filename]#nvidia.ko#, X11 дэлгэцийн драйверууд болон USB зэрэг хоёртын драйверууд нь ерөнхийдөө хамгийн их асуудлуудтай байдаг байхад Ethernet интерфэйсүүд ихэвчлэн зүгээр ажилладаг. Хэрэв та драйверуудыг зөв ачаалж/буулгаж чадаж байвал та тохирох тушаалуудыг [.filename]#/etc/rc.suspend# болон [.filename]#/etc/rc.resume# файлуудад хийж үүнийг автоматжуулж болно. Драйверийг буулгах болон ачаалахад зориулсан тайлбар болгосон жишээ байдаг. Хэрэв таны дэлгэц үргэлжлүүлэлт хийгдсэний дараа заваарсан бол `hw.acpi.reset_video`-г тэг (`0`) болгож үзээрэй. Хэрэв тусламж болохоор бол `hw.acpi.sleep_delay`-г арай урт эсвэл арай богино утгуудаар тохируулж үзээрэй. Өөр нэг турших зүйл нь ACPI дэмжлэгтэй сүүлийн үеийн Линуксийн түгээлтийг ачаалан тэдний түр зогсоолт/үргэлжлүүлэлтийн дэмжлэгийг адил тоног төхөөрөмж дээр турших явдал юм. Хэрэв Линукс дээр ажиллаж байвал энэ нь FreeBSD-ийн драйверийн асуудал гэсэн үг бөгөөд яг аль драйвер асуудлыг үүсгэж байгааг олсноор асуудлыг засварлахад бидэнд тус болох болно. ACPI-ийг дэмжиж байдаг дэмжигчид нь өөр бусад драйверуудыг (өөрөөр хэлбэл дуу, ATA гэх мэт) ихэвчлэн дэмжин ажилладаггүй болохоор драйверийн асуудлыг мөшгөж хийгдсэн ажил бүр магадгүй эцсийн эцэст {freebsd-current} жагсаалт болон драйверийг дэмжигч уруу илгээгдэх хэрэгтэйг санаарай. Хэрэв та адал явдлыг эрж байгаа бол драйверийн үргэлжлүүлэлтийн функцын аль хэсэгт өлгөгдөж байгааг мөшгөхийн тулд зарим дибаг хийх man:printf[3]-үүдийг асуудалтай драйверт хийж эхлээрэй. Эцэст нь ACPI-г хааж оронд нь APM-г нээж оролдоорой. Хэрэв түр зогсоолт/үргэлжлүүлэлт APM-тэй байхад ажиллаж байвал та APM-тэйгээ үлдэх нь ялангуяа хуучин тоног төхөөрөмжийн (2000 оноос өмнөх) хувьд бараг дээр байх бизээ. ACPI дэмжлэгийг зөв болгоход үйлдвэрлэгчдэд цаг хугацаа шаардах бөгөөд магадгүй хуучин тоног төхөөрөмжүүд нь ACPI-ийн хувьд BIOS-ийн асуудлуудтай ихэвчлэн байдаг. ==== Систем өлгөгдөх (түр хугацаагаар эсвэл бүрмөсөн) Ихэнх системийн өлгөгдлүүд нь гээгдсэн тасалдлууд эсвэл тасалдлын шуургын үр дүн юм. Бичил схемүүд нь ачаалахаас өмнө тасалдлуудыг BIOS хэрхэн тохируулдгаас болсон асуудлууд, APIC (MADT) хүснэгтийн зөв байдал болон _System Control Interrupt буюу Системийн Хянагч Тасалдлын_ (SCI) чиглүүлэлт дээр тулгуурласан олон асуудлуудтай байдаг. Тасалдлын шуургыг `vmstat -i` тушаалын гаралтаас `acpi0` бүхий мөрийг шалгаж гээгдсэн тасалдлуудаас ялгаж болно. Хэрэв тоологч секунд тутам хоёроор нэмэгдэж байвал та тасалдлын шуургатай байна. Хэрэв систем өлгөгдсөн юм шиг байвал DDB (консол дээр kbd:[CTRL+ALT+ESC]) уруу орж `show interrupts` гэж бичих хэрэгтэй. Тасалдлын асуудлуудтай ажиллаж байхад таны хамгийн шилдэг итгэл найдвар бол [.filename]#loader.conf#-д `hint.apic.0.disabled="1"` хэмээн зааж APIC дэмжлэгийг хаах явдал юм. ==== Үймээнүүд Үймээнүүд нь ACPI-ийн хувьд харьцангуй ховор байдаг бөгөөд засварлах нэн тэргүүн ээлжийн асуудал байдаг. Эхний алхам бол үймээнийг дахин гаргах (хэрэв боломжтой бол) алхмуудыг тусгаарлаж буцах мөрийг (backtrace) авах явдал юм. `options DDB` мөрийг нээж сериал консол (crossref:serialcommsserialconsole-ddb,Цуваа шугамнаас DDB дибаг хийгч уруу орох]-г үзнэ үү) тохируулах эсвэл man:dump[8] хуваалтыг тохируулах зөвлөгөөг дагаарай. Та буцах мөрийг DDB дээр `tr`-р авч болно. Хэрэв та буцах мөрийг гараар бичих болбол мөр дэх хамгийн доодох тав (5) болон хамгийн дээдэх таван (5) мөрийг хамгийн багадаа бодоход аваарай. Дараа нь асуудлыг тусгаарлахыг оролдож ACPI-г хааж ачаалж үзээрэй. Хэрэв энэ нь ажиллаж байвал `debug.acpi.disable`-ийн төрөл бүрийн утгуудыг хэрэглэж та ACPI дэд системийг тусгаарлаж болно. Зарим жишээнүүдийг man:acpi[4] гарын авлагын хуудаснаас үзнэ үү. ==== Түр зогссоны дараа эсвэл унтраасны дараа систем дахин эхлэх Эхлээд man:loader.conf[5] дээр `hw.acpi.disable_on_poweroff="0"` гэж тохируулаад үз. Энэ нь унтраах процессийн үед төрөл бүрийн үйл явцуудыг ACPI хаахыг болиулдаг. Энэ зорилгын нэгэн адил зарим системүүд энэ утгыг `1` (анхдагч) болгож тохируулахыг шаарддаг. Энэ нь түр зогсоолт эсвэл унтраалт хийгдсэний дараа аяндаа гарсан систем асаж эхлэх асуудлыг ихэвчлэн засварладаг. ==== Бусад асуудлууд Хэрэв танд ACPI-тай холбоотой бусад асуудлууд (суулгах станцтай ажиллах, төхөөрөмжүүд илрүүлэгдэхгүй гэх мэт) байвал тайлбарыг захидлын жагсаалт уруу бас илгээнэ үү; гэхдээ эдгээр асуудлуудын зарим нь ACPI дэд системийн дуусаагүй хэсгүүдтэй холбоотой байж болох бөгөөд тэдгээрийг шийдэж хийхэд нэлээн хугацаа зарцуулж болох юм. Тэвчээртэй байж бидний илгээж болох засваруудыг тест хийхэд бэлэн байгаарай. [[ACPI-aslanddump]] === ASL, `acpidump`, болон IASL Хамгийн нийтлэг асуудал бол BIOS үйлдвэрлэгчдийн гаргасан буруу (эсвэл алдаатай!) байткод юм. Энэ нь ихэвчлэн дараах шиг цөмийн консол мэдээллүүдээр ил тод болдог: [source,shell] .... ACPI-1287: *** Error: Method execution failed [\\_SB_.PCI0.LPC0.FIGD._STA] \\ (Node 0xc3f6d160), AE_NOT_FOUND .... Ихэвчлэн та эдгээр асуудлуудыг өөрийн BIOS-ийг хамгийн сүүлийн хувилбар уруу шинэчилснээр шийдэж болно. Ихэнх консолын мэдээллүүд нь аюулгүй гэхдээ хэрэв танд батарейний төлөв ажиллахгүй гэх мэт өөр бусад асуудлууд байгаа бол тэдгээр мэдээллүүд нь AML-д байгаа асуудлуудыг хайж болох боломжийн газар нь юм. AML гэгддэг байткод нь ASL хэмээгддэг эх хэлээс хөрвүүлэгддэг. AML нь DSDT гэгддэг хүснэгтэд байдаг. Өөрийн ASL-ийн хуулбарыг авахын тулд man:acpidump[8]-ийг ашиглана. Та `-t` (тогтмол хүснэгтүүдийн агуулгуудыг үзүүлэх) болон `-d` (AML-ийг ASL уруу дизассембл хийх) тохируулгыг хоёуланг нь ашиглах хэрэгтэй. Синтаксын жишээг <> хэсгээс үзнэ үү. Таны хийж болох хамгийн хялбар анхны шалгалт нь алдаануудыг шалгахын тулд өөрийн ASL-ийг хөрвүүлэх явдал юм. Анхааруулгуудыг ихэвчлэн орхиж болох боловч алдаанууд нь ACPI-г зөв ажиллуулахад гол төлөв саад болдог хорхойнууд байдаг. Өөрийн ASL-ийг дахин хөрвүүлэхдээ дараах тушаалыг ажиллуулна: [source,shell] .... # iasl your.asl .... [[ACPI-fixasl]] === Өөрийн ASL-г засварлах нь Бидний эцсийн зорилго бол бараг хүн болгоны хувьд хэрэглэгчийн ямар ч оролцоогүйгээр ACPI-г ажиллуулах явдал юм. Гэхдээ өнөөг хүртэл бид BIOS үйлдвэрлэгчдийн гаргасан нийтлэг алдаануудад зориулан тойрон гарах арга замуудыг хөгжүүлсээр байгаа билээ. Microsoft(R)-ийн тайлбарлагч ([.filename]#acpi.sys# болон [.filename]#acpiec.sys#) нь стандартыг баримталж байгааг чанд шалгадаггүй бөгөөд BIOS-ийн олон үйлдвэрлэгчид ACPI-г зөвхөн Windows(R) дээр тест хийж өөрсдийн ASL-ийг хэзээ ч засдаггүй. Бид Microsoft(R)-ийн тайлбарлагчид зөвшөөрөгдсөн ямар стандартын бус ажиллагаа байгааг үргэлжлүүлэн нарийн таньж баримтжуулан хэрэглэгчдээр ASL-ийг хүчлэн засуулалгүйгээр FreeBSD ажиллаж чадахаар түүнийг хуулбарлах болно гэж найдаж байна. Тойрон гарах арга зам болгон биднийг энэ ажиллагааг танихад тусалж та ASL-ийг гараар засварлаж болно. Хэрэв таны хувьд энэ нь ажиллавал хуучин болон шинэ ASL-ийнхээ man:diff[1]-ийг илгээнэ үү, бид бололцоогоороо ACPI-CA дахь алдаатай ажиллагааг тойрон гарч ингэснээр хойшид таны засвар байнга хийгдэх шаардлагагүй болох юм. Энд нийтлэг алдааны мэдээллүүд, тэдгээрийн шалтгаан болон хэрхэн засаж болох жагсаалтыг үзүүлэв: ==== _OS хамаарлууд Зарим AML нь ертөнц төрөл бүрийн Windows(R) хувилбаруудаас тогтдог гэж үздэг. Хэрэв танд байгаа асуудлыг засаж чадаж байвал та FreeBSD-г ямар нэг OS гэж харагдуулахаар хэлж өгч болно. Үүнийг хялбар аргаар дарж бичихийн тулд [.filename]#/boot/loader.conf#-д `hw.acpi.osname="Windows 2001"` гэж эсвэл ASL дахь өөр бусад адил мөрүүдийг тохируулж өгнө. ==== Буцах мэдээллүүд байхгүй бол Зарим аргууд нь стандартын дагуу шууд утга буцаадаггүй. ACPI-CA нь үүнтэй ажиллаж чадахгүй байхад FreeBSD үүнийг далдаар утга буцаалгах боломжийг олгодог тойрон гарах арга замтай байдаг. Хэрэв та утга буцаагдах ёстойг мэдэж байвал шаардлагатай газар нь Return буюу Буцах мэдээллүүдийг шууд нэмж болно. ASL-ийг `iasl` тушаалаар хүчээр хөрвүүлэхдээ `-f` тугийг ашиглана. ==== Анхдагч AML-ийг дарж өөрчлөх нь [.filename]#your.asl#-ийг өөрчилсний дараа үүнийг та хөрвүүлэхдээ: [source,shell] .... # iasl your.asl .... Хөрвүүлэх явцад алдаанууд байсан ч гэсэн та `-f` тугийг нэмж AML-ийг хүчээр үүсгэж болно. Зарим алдаануудыг (өөрөөр хэлбэл Буцах мэдээллүүд байхгүй гэх мэт) тайлбарлагчийн тусламжтайгаар автоматаар тойрон гардгийг санаарай. [.filename]#DSDT.aml# нь `iasl`-ийн анхдагч гаралт файлын нэр юм. Та өөрийн BIOS-ийн алдаатай хуулбарын (флэш санах ойд байсаар байгаа) оронд [.filename]#/boot/loader.conf#-ийг дараах байдлаар засварлан үүнийг ачаалж болно: [.programlisting] .... acpi_dsdt_load="YES" acpi_dsdt_name="/boot/DSDT.aml" .... Өөрийн [.filename]#DSDT.aml# файлын хуулбарыг [.filename]#/boot# сан уруу хуулах хэрэгтэй. [[ACPI-debugoutput]] === ACPI-аас дибаг мэдээлэл гаргаж авах нь ACPI драйвер нь маш уян хатан дибаг хийх боломжтой. Энэ нь дэд системүүдийн олонлог болон харуулах түвшинг зааж өгөхийг танд зөвшөөрдөг. Таны дибаг хийхийг хүсэж байгаа дэд системүүд нь "давхаргууд" болж заагдсан байдаг бөгөөд ACPI-CA хэсгүүд (ACPI_ALL_COMPONENTS) болон ACPI тоног төхөөрөмжийн дэмжлэг (ACPI_ALL_DRIVERS) болж задардаг. Дибаг гаралтын харуулалт нь "үе"ээр заагддаг бөгөөд ACPI_LV_ERROR (зөвхөн алдаануудыг хэлдэг) тогтмолоос ACPI_LV_VERBOSE (бүгд) хүртэл байдаг. "Үе" нь олон тохируулгуудыг нэг удаа зайгаар зааглан тохируулж болох бит баг (bitmask) юм. Хэрэв энэ нь маш урт тэгээд консолын мэдээллийн буферийг арилган шинэчилж байвал та практик дээр гаралтыг бүртгэх сериал консолыг ашиглахыг хүсэж болох юм. Бие даасан давхаргууд болон түвшингүүдийн бүрэн жагсаалт man:acpi[4] гарын авлагын хуудсанд байдаг. Дибаг гаралт анхдагчаар идэвхжүүлэгдээгүй байдаг. Идэвхтэй болгохын тулд ACPI хэрэв цөмд хөрвүүлэгдсэн бол `options ACPI_DEBUG` мөрийг өөрийн цөмийн тохиргооны файлд нэмэх хэрэгтэй. Нийтэд нь идэвхтэй болгохын тулд [.filename]#/etc/make.conf#-д `ACPI_DEBUG=1` мөрийг нэмж болно. Хэрэв энэ нь модуль бол та өөрийн [.filename]#acpi.ko# модулийг дараах маягаар дахин хөрвүүлж болно: [source,shell] .... # cd /sys/modules/acpi/acpi && make clean && make ACPI_DEBUG=1 .... [.filename]#acpi.ko#-г [.filename]#/boot/kernel#-д суулгаад өөрийн хүссэн давхарга болон түвшинг [.filename]#loader.conf#-д нэмнэ. Энэ жишээ нь ACPI-CA-ийн бүх хэсгүүд болон бүх ACPI тоног төхөөрөмжийн драйверуудад (CPU, LID, гэх мэт.) зориулан дибаг мэдээллүүдийг идэвхжүүлдэг. Энэ нь зөвхөн алдааны мэдээллүүдийг хамгийн багаар гаргаж харуулна. [.programlisting] .... debug.acpi.layer="ACPI_ALL_COMPONENTS ACPI_ALL_DRIVERS" debug.acpi.level="ACPI_LV_ERROR" .... Хэрэв таны хүссэн мэдээлэл онцгой үйл явцаар эхэлсэн бол (түр зогсоолт болон үргэлжлүүлэлт гэж бодъё) та [.filename]#loader.conf#-ийн өөрчлөлтүүдийг орхиж оронд нь `sysctl`-ийг ашиглан давхарга болон түвшинг ачаалсны дараа зааж онцгой үйл явцад зориулан өөрийн системийг бэлдэж болно. `sysctl`-ууд нь [.filename]#loader.conf# дахь тохируулгуудын адилаар нэрлэгддэг. [[ACPI-References]] === Лавлагаанууд ACPI-ийн талаар дэлгэрэнгүй мэдээллийг дараах байршлуудаас олж болно: * {freebsd-acpi} * ACPI Захидлын Жагсаалтын Архивууд http://lists.freebsd.org/pipermail/freebsd-acpi/[http://lists.freebsd.org/pipermail/freebsd-acpi/] * Хуучин ACPI Захидлын Жагсаалтын Архивууд http://home.jp.FreeBSD.org/mail-list/acpi-jp/[http://home.jp.FreeBSD.org/mail-list/acpi-jp/] -* ACPI 2.0 Тодорхойлолт http://acpi.info/spec.htm[http://acpi.info/spec.htm] +* https://uefi.org/specifications#ACPI[ACPI Тодорхойлолт] * FreeBSD Гарын авлагын хуудаснууд: man:acpi[4], man:acpi_thermal[4], man:acpidump[8], man:iasl[8], man:acpidb[8] * http://www.cpqlinux.com/acpi-howto.html#fix_broken_dsdt[DSDT дибаг эх үүсвэр]. (Compaq-ийг жишээ болгон хэрэглэсэн боловч ерөнхийдөө хэрэгтэй.) diff --git a/documentation/content/nl/books/handbook/config/_index.adoc b/documentation/content/nl/books/handbook/config/_index.adoc index 51268a210f..d817972090 100644 --- a/documentation/content/nl/books/handbook/config/_index.adoc +++ b/documentation/content/nl/books/handbook/config/_index.adoc @@ -1,1450 +1,1450 @@ --- title: Hoofdstuk 12. Instellingen en optimalisatie part: Deel III. Systeembeheer prev: books/handbook/partiii next: books/handbook/boot showBookMenu: true weight: 16 path: "/books/handbook/" --- [[config-tuning]] = Instellingen en optimalisatie :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 12 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/config/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[config-synopsis]] == Overzicht Systeeminstellingen zijn een belangrijk aspect van FreeBSD. Correcte instellingen helpen moeilijkheden bij toekomstige upgrades te voorkomen. In dit hoofdstuk wordt het instellen van FreeBSD beschreven, alsmede een aantal prestatiebevorderende maatregelen waarmee een FreeBSD systeem geoptimaliseerd kan worden. Na het lezen van dit hoofdstuk weet de lezer: * Hoe efficiënt om te gaan met bestandssystemen en wisselpartities; * De grondbeginselen van het [.filename]#rc.conf# instellingensysteem en van het opstarten van toepassingen (diensten) met [.filename]#/usr/local/etc/rc.d#; * Hoe een netwerkkaart ingesteld en getest wordt; * Hoe virtuele hosts op netwerkapparatuur ingesteld worden; * Hoe de instellingenbestanden in [.filename]#/etc# gebruikt worden; * Hoe FreeBSD geoptimaliseerd kan worden met `sysctl`-variabelen; * Hoe schijfprestaties te verbeteren en hoe kernelbeperkingen gewijzigd kunnen worden. Veronderstelde voorkennis: * De grondbeginselen van UNIX(R) en FreeBSD (crossref:basics[basics,UNIX® beginselen]) begrijpen; * Bekend zijn met de grondbeginselen van kernelinstellingen en compilatie (crossref:kernelconfig[kernelconfig,De FreeBSD-kernel instellen]). [[configtuning-initial]] == Initiële instellingen === Partitioneren ==== Basispartities Bij het aanmaken van bestandssystemen met man:bsdlabel[8] of man:sysinstall[8] is het van belang dat op een harde schijf de gegevensoverdracht het snelst is aan de buitenste sporen en het langzaamst aan de binnenste. Kleinere en veelgebruikte bestandssystemen kunnen daarom het beste aan de buitenkant van de schijf geplaatst worden, terwijl grotere partities als [.filename]#/usr# meer naar de binnenkant van de schijf geplaatst kunnen worden. Het is een goed idee om partities aan te maken in deze of gelijksoortige volgorde: root, swap, [.filename]#/var#, [.filename]#/usr#. De grootte van de partitie [.filename]#/var# hangt af van de wijze waarop de machine gebruikt gaat worden. Het bestandssysteem [.filename]#/var# wordt gebruikt voor onder meer postbussen, logbestanden en printergegevens en -wachtrijen. Postbussen en logbestanden kunnen onverwacht groot worden, afhankelijk van het aantal systeemgebruikers en de bewaarduur van logbestanden. De meeste gebruikers zullen zelden meer dan ongeveer een gigabyte aan vrije schijfruimte op [.filename]#/var# nodig hebben. [NOTE] ==== Er zijn een aantal gevallen waar een grote hoeveelheid ruimte in [.filename]#/var/tmp# nodig is. Wanneer er nieuwe software wordt geïnstalleerd met man:pkg_add[1] pakken de pakketprogramma's een tijdelijke kopie van de pakketten uit in [.filename]#/var/tmp#. Grote softwarepakketten, zoals Firefox, OpenOffice of LibreOffice kunnen lastig zijn om te installeren wanneer er onvoldoende vrije schijfruimte beschikbaar is onder [.filename]#/var/tmp#. ==== De partitie [.filename]#/usr# bevat veel van de benodigde systeembestanden, waaronder de man:ports[7] collectie (aanbevolen) en de broncode (optioneel). Beide zijn optioneel tijdens de installatie, maar we raden voor deze partitie tenminste 2 gigabyte aan. Het is verstandig rekening te houden met de vereiste schijfruimte bij het kiezen van partitiegroottes. Als in een partitie onvoldoende vrije schijfruimte is, terwijl een andere vrijwel niet gebruikt wordt, is dat een vervelend en niet optimaal oplosbaar probleem. [NOTE] ==== man:sysinstall[8]'s `Auto-defaults` partitiekeuze kan in de ervaring van sommige gebruikers mogelijk te kleine [.filename]#/var# en [.filename]#/# partities opleveren. Partitioneren moet verstandig en niet te zuinig gebeuren. ==== [[swap-design]] ==== Wisselpartities (swap) De vuistregel is dat het wisselbestand ongeveer het dubbele van de grootte van het systeemgeheugen (RAM) moet zijn. Als de machine bijvoorbeeld 128 megabytes geheugen heeft, kan het beste een wisselbestand van (tenminste) 256 megabytes gebruikt worden. Minder dan 256 megabytes swap is in dit geval af te raden. Systemen met weinig geheugen kunnen overigens beter functioneren met meer swap. Ook is het verstandig rekening te houden met eventuele geheugenuitbreiding in de toekomst. Bovendien zijn de VM paging-algoritmen van de kernel zo afgestemd dat ze het beste presteren bij een wisselbestand van tenminste tweemaal de grootte van het geheugen. Een te kleine swap kan dus inefficiënties in de VM-code tot gevolg hebben en mogelijk problemen veroorzaken als het systeemgeheugen uitgebreid wordt. Op grotere systemen met meerdere SCSI-schijven (of meerdere IDE-schijven op verschillende controllers) is het aan te raden om op elke schijf een wisselpartitie in te stellen (dit kan tot en met vier schijven), elk met ongeveer dezelfde grootte. De kernel kan met arbitraire groottes werken, maar interne datastructuren schalen tot viermaal de grootste swappartitie. De kernel kan de beschikbare ruimte voor het wisselbestand het meest optimaal indelen als de partities ongeveer even groot zijn. Een grote swap is prima, ook als ze zelden gebruikt wordt. Zo kan het gemakkelijker zijn om een (uit de hand gelopen) proces dat het systeem grotendeels bezet houdt te beëindigen, voordat er opnieuw opgestart moet worden. ==== Waarom partitioneren? Waarom niet één enkele grote partitie gebruiken? Er zijn verscheidene redenen waarom dit niet zo'n goed idee is. De verschillende partities hebben hun eigen karakteristieke operationele gedrag en vereisten. Door ze te scheiden zijn er betere mogelijkheden om het systeem te optimaliseren. Vanaf de [.filename]#/# en [.filename]#/usr# partities wordt bijvoorbeeld vooral gelezen en er wordt weinig naar geschreven, terwijl er in [.filename]#/var# en [.filename]#/var/tmp# zowel veel gelezen als geschreven wordt. Door een systeem goed te partitioneren wordt vermeden dat fragmentatie die optreedt in de kleinere partities met veel schrijfactiviteit doorsijpelt naar partities die vooral lees-intensief zijn. Door schrijf-intensieve partities aan het begin van de schijf te plaatsen, zijn de prestaties wat betreft invoer/uitvoer het beste daar waar het het meest nodig is. Ofschoon er natuurlijk ook de best mogelijke in/uit prestaties wenselijk zijn in de grotere partities, weegt het plaatsen van deze bestandssystemen aan het begin van de schijf niet tegen de voordelen van het plaatsen van [.filename]#/var# aan het begin van de schijf (na root en swap) voor de totale snelheid van het systeem. Tenslotte zijn er veiligheidsoverwegingen. Een compacte en nette rootpartitie die vrijwel alleen-lezen is, heeft een betere kans om een nare crash te overleven. [[configtuning-core-configuration]] == Hoofdinstellingen De voornaamste lokatie voor systeeminstellingen is [.filename]#/etc/rc.conf#. Dit bestand bevat een scala aan instellingen, die gebruikt wordt om het systeem in te stellen bij het opstarten. De naam impliceert dit al. Het is informatie voor de [.filename]#rc*# bestanden (rc staat voor "resource configuration" of broninstellingen). De systeembeheerder wordt geacht regels toe te voegen aan [.filename]#rc.conf# om de standaardinstellingen uit [.filename]#/etc/defaults/rc.conf# aan te passen. Het standaardbestand moet niet letterlijk gekopiëerd worden naar [.filename]#/etc#. Het bevat standaardwaardes en is niet bedoeld als voorbeeld. Alle wijzigingen die specifiek zijn voor een systeem horen in [.filename]#/etc/rc.conf# thuis. In een clusterscenario is het nuttig om systeemspecifieke instellingen te scheiden van algemene instellingen die voor het hele cluster gelden. Hiervoor kunnen een aantal strategieën worden gebruikt. De aanbevolen benadering is om systeem-specifieke instellingen in [.filename]#/etc/rc.conf.local# te plaatsen. Een voorbeeld: * [.filename]#/etc/rc.conf#: + [.programlisting] .... sshd_enable="YES" keyrate="fast" defaultrouter="10.1.1.254" .... * [.filename]#/etc/rc.conf.local#: + [.programlisting] .... hostname="node1.example.org" ifconfig_fxp0="inet 10.1.1.1/8" .... [.filename]#rc.conf# kan vervolgens naar elk systeem gedistribueerd worden met `rsync` of een gelijksoortig programma, terwijl [.filename]#rc.conf.local# uniek blijft. Het actualiseren van het systeem met man:sysinstall[8] of `make world` overschrijft [.filename]#rc.conf# niet, zodat de bestaande systeeminstellingen niet verloren gaan. [TIP] ==== Het instellingenbestand [.filename]#/etc/rc.conf# wordt gelezen door man:sh[1]. Dit stelt systeembeheerders in staat om een zekere hoeveelheid logica aan dit bestand toe te voegen, dat kan helpen in het creëren van zeer ingewikkelde configuratiescenario's. Bekijk man:rc.conf[5] voor meer informatie over dit onderwerp. ==== [[configtuning-appconfig]] == Toepassingen instellen Geïnstalleerde toepassingen hebben meestal hun eigen instellingenbestanden, met hun eigen syntaxis, etc. Het is van belang deze bestanden apart te houden van het basissysteem, zodat ze makkelijk gelokaliseerd kunnen worden en beheerd kunnen worden met de hulpmiddelen voor pakketbeheer. Deze bestanden worden meestal geïnstalleerd in [.filename]#/usr/local/etc#. Als een toepassing een uitgebreide verzameling bestanden voor instellingen heeft, wordt er een submap voor aangemaakt. Bij de installatie van een port of pakket, worden normaliter ook voorbeeldbestanden met instellingen geïnstalleerd. Deze zijn doorgaans te herkennen aan een toevoegsel [.filename]#.default#. Als er geen bestaande instellingenbestanden voor de toepassing zijn, kunnen ze gemaakt worden door de [.filename]#.default#-bestanden te kopiëren. Een voorbeeld is de map [.filename]#/usr/local/etc/apache#: .... -rw-r--r-- 1 root wheel 2184 May 20 1998 access.conf -rw-r--r-- 1 root wheel 2184 May 20 1998 access.conf.default -rw-r--r-- 1 root wheel 9555 May 20 1998 httpd.conf -rw-r--r-- 1 root wheel 9555 May 20 1998 httpd.conf.default -rw-r--r-- 1 root wheel 12205 May 20 1998 magic -rw-r--r-- 1 root wheel 12205 May 20 1998 magic.default -rw-r--r-- 1 root wheel 2700 May 20 1998 mime.types -rw-r--r-- 1 root wheel 2700 May 20 1998 mime.types.default -rw-r--r-- 1 root wheel 7980 May 20 1998 srm.conf -rw-r--r-- 1 root wheel 7933 May 20 1998 srm.conf.default .... Aan de grootte van de bestanden is te zien dat alleen [.filename]#srm.conf# gewijzigd is. Als later de port Apache wordt vernieuwd, wordt dit bestand niet overschreven. [[configtuning-starting-services]] == Diensten starten Veel gebruikers kiezen ervoor om software van derden te installeren op FreeBSD vanuit de Portscollectie. In veel gevallen is het noodzakelijk om de software dusdanig in te stellen dat het opstart tijdens het opstarten van de computer. Diensten zoals package:mail/postfix[] of package:www/apache22[] zijn slechts twee voorbeelden van softwarepakketten die gestart kunnen worden tijdens de systeemstart. In deze paragraaf wordt toegelicht hoe software van derde partijen kan worden gestart. In FreeBSD worden de meeste diensten, zoals man:cron[8], door de opstartscripts van het systeem gestart. Deze scripts kunnen verschillen tussen FreeBSD en leverancierversies, echter het meest belangrijke aspect om in gedachten te houden is dat hun opstartinstellingen verwerkt kunnen worden door simpele opstartscripts. === Uitgebreide applicatieinstellingen Nu FreeBSD [.filename]#rc.d# heeft, zijn de instellingen van applicaties die mee moeten opstarten versimpeld en rijker aan mogelijkheden. Door gebruik te maken van de sleutelwoorden die in de paragraaf <> behandeld worden, kunnen applicaties nu starten na andere diensten. DNS kan bijvoorbeeld extra opties meekrijgen van [.filename]#/etc/rc.conf# in plaats van hard ingestelde opties in het opstartscript. Een basisscript ziet er ongeveer als volgt uit: [.programlisting] .... #!/bin/sh # # PROVIDE: utility # REQUIRE: DAEMON # KEYWORD: shutdown . /etc/rc.subr name=utility rcvar=utility_enable command="/usr/local/sbin/utility" load_rc_config $name # # VERANDER DE STANDAARDWAARDEN HIER NIET # STEL ZE IN HET BESTAND /etc/rc.conf IN # utility_enable=${utility_enable-"NO"} pidfile=${utility_pidfile-"/var/run/utility.pid"} run_rc_command "$1" .... Dit script zorgt ervoor dat utility wordt gestart na de pseudodienst `DAEMON`. Het biedt ook de mogelijkheid voor het instellingen en volgen van het PID of het proces-ID bestand. Voor deze applicatie kan dan de volgende regel in [.filename]#/etc/rc.conf# geplaatst worden: [.programlisting] .... utility_enable="YES" .... Deze methode maakt het volgende mogelijk: makkelijker commandoregelopties manipuleren, importeren van standaardfuncties uit [.filename]#/etc/rc.subr#, compatibiliteit met het gereedschap man:rcorder[8] en het levert makkelijkere configuratie via [.filename]#rc.conf#. === Diensten met diensten starten Andere diensten, zoals POP3-server daemons, IMAP, enzovoort, kunnen gestart worden door gebruik te maken van man:inetd[8]. Daaraan is voorafgegaan dat die dienst uit de Portscollectie is geïstalleerd en dat er een regel met instellingen is toegevoegd aan [.filename]#/etc/inetd.conf# of één van de bestaande niet-actieve regels is geactiveerd. Werken met inetd en zijn instellingen wordt uitgebreid toegelicht in de paragraaf over crossref:network-servers[network-inetd,inetd]. In sommige gevallen is het handiger om man:cron[8] te gebruiken om diensten te starten. Deze aanpak heeft een aantal voordelen omdat `cron` start als de eigenaar van [.filename]#crontab#. Dit stelt reguliere gebruikers in staat om sommige applicaties te starten en te onderhouden. `cron` levert een unieke optie: in plaats van een tijdsspecificatie kan `@reboot` gebruikt worden. Dit zorgt ervoor dat de taak gestart wordt als man:cron[8] gestart wordt, meestal tijdens een systeemstart. [[configtuning-cron]] == `cron` instellen Een zeer nuttig hulpprogramma in FreeBSD is man:cron[8]. De daemon `cron` draait op de achtergrond en controleert voortdurend [.filename]#/etc/crontab#. Ook controleert `cron` de map [.filename]#/var/cron/tabs#, op zoek naar nieuwe [.filename]#crontab# bestanden. Deze [.filename]#crontab# bestanden bevatten informatie over specifieke taken die `cron` moet verrichten op gezette tijden. `cron` gebruikt twee verschillende soorten instellingenbestanden: de systeemcrontab en gebruikerscrontabs. Deze formaten verschillen alleen in het zesde en verdere velden. In de systeemcrontab zal `cron` het commando draaien als de gebruiker die in het zesde veld is opgegeven. In een gebruikerscrontab draaien alle commando's onder de gebruiker die de crontab heeft aangemaakt, dus is het zesde veld het laatste veld; dit is een belangrijk beveiligingsaspect. Het laatste veld is altijd het commando dat gedraaid wordt. [NOTE] ==== Gebruikerscrontabs geven individuele gebruikers de mogelijkheid om bepaalde terugkerende taken automatisch te laten uitvoeren zonder dat `root`-rechten noodig zijn. Commando's in de crontab van een gebruiker worden uitgevoerd met de rechten van de eigenaar. `root` kan ook een gebruikerscrontab aanleggen net als elke andere gebruiker. Dit is niet dezelfde als [.filename]#/etc/crontab#, de systeemcrontab. Omdat de systeemcrontab in de praktijk de commando's als root uitvoert, is het doorgaans niet nodig om een gebruikerscrontab voor `root` te maken. ==== [.filename]#/etc/crontab# (de systeemcrontab) ziet er uit als volgt: [.programlisting] .... # /etc/crontab - root's crontab for FreeBSD # # $FreeBSD: src/etc/crontab,v 1.32 2002/11/22 16:13:39 tom Exp $ ## <.> # SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin <.> HOME=/var/log # # #minuut uur mdag maand wdag wie commando <.> # # */5 * * * * root /usr/libexec/atrun <.> .... <.> Zoals in de meeste instellingenbestanden van FreeBSD zijn regels die met het karakter `#` beginnen commentaar. Commentaar wordt gebruikt als uitleg en geheugensteun. Commentaar dient niet vermengd te worden met commando's, anders wordt het commentaar opgevat als deel van het commando. Blanco regels worden genegeerd. <.> Eerst worden omgevingsvariabelen gedefiniëerd. Hoervoor wordt het is-gelijk karakter (`=`) gebruikt. In het bovenstaande voorbeeld wordt het gebruikt voor de variabelen `SHELL`, `PATH` en `HOME`. Als de regel `SHELL` ontbreekt, gebruikt `cron` standaard `sh` als shell. Voor de omgevingsvariabele `PATH` bestaat geen standaardwaarde. Als `PATH` ontbreekt moeten absolute paden gebruikt worden. Als `HOME` ontbreekt, gebruikt `cron` de thuismap van de gebruiker die `cron` aanroept. <.> In deze commentaarregel staan de zeven velden van een crontabdefinitie. Dit zijn `minuut`, `uur`, `mdag`, `maand`, `wdag`, `wie` en `commando`. De betekenissen liggen voor de hand: `minuut` is het aantal minuten van het tijdstip waarop het commando moet worden uitgevoerd; `uur` geeft het uur aan; `mdag` staat voor de dag van de maand; `maand` staat voor het maandnummer en `wdag` geeft de dag van de week aan. Het veld `wie` is bijzonder en bestaat alleen in [.filename]#/etc/crontab#. Het geeft aan als welke gebruiker het commando uitgevoerd moet worden. Het laatste veld bevat het uit te voeren commando. <.> In deze regel worden aan de hierboven besproken opties waarden toegekend. Er wordt gebruik gemaakt van `*/5` en `*` karakters. Deze betekenen "eerst-laatst" en kunnen gezien worden als _telkens_. In deze regel staat dus dat `atrun` elke vijf minuten moet worden uitgevoerd door `root`, ongeacht welke dag of maand het is. Meer informatie over `atrun` staat in man:atrun[8].Commando's kunnen een willekeurig aantal opties of argumenten meekrijgen. Als commando's echter meerdere regels nodig hebben moeten deze regels afgebroken worden met een backslash "\" karakter, om aan te geven dat ze op de volgende regel vervolgd worden. Dit is de basisopzet voor elk [.filename]#crontab# bestand. De enige uitzondering is de aanwezigheid van veld zes, waar de gebruikersnaam wordt aangegeven. Dit veld bestaat alleen in de systeemversie van [.filename]#/etc/crontab#. Voor [.filename]#crontab#-bestanden van individuele gebruikers moet dit veld worden weggelaten. [[configtuning-installcrontab]] === Een crontab installeren [IMPORTANT] ==== De onderstaande procedure moet niet gebruikt worden om de systeemcrontab [.filename]#/etc/crontab# te wijzigen of te installeren. Er kan een gewone editor gebruikt worden. `cron` ziet dat het bestand veranderd is en begint direct met het gebruiken van de nieuwe versie. extref:{faq}[Deze FAQ vraag, ROOT-NOT-FOUND-CRON-ERRORS] geeft verdere uitleg. ==== Om een nieuwe [.filename]#crontab# te installeren moet eerst een bestand in het juiste formaat gemaakt worden en daarna moet het geiuml;nstalleerd worden met commando `crontab`: [source,shell] .... # crontab crontabbestand .... In dit voorbeeld is [.filename]#crontabbestand# de naam van een eerder gemaakt [.filename]#crontab#-bestand. Er bestaat ook een optie om een lijst van geïnstalleerde [.filename]#crontab#-bestanden op te vragen, namelijk de optie `-l` van `crontab`. Gebruikers die hun eigen crontabbestand willen schrijven zonder het gebruik van een sjabloon, kunnen gebruik maken van `crontab -e`. Dit opent de `EDITOR` met een leeg bestand. Als het bestand wordt opgeslagen en de editor wordt afgesloten, wordt het bestand automatisch als [.filename]#crontab# geïnstalleerd. Een gebruikers [.filename]#crontab# kan verwijderd worden door de met `crontab` de optie `-r` te gebruiken. [[configtuning-rcd]] == Gebruik van rc met FreeBSD Sinds 2002 gebruikt FreeBSD het NetBSD [.filename]#rc.d# systeem bij het opstarten van het systeem. Veel van de bestanden in [.filename]#/etc/rc.d# zijn scripts voor basisdiensten die werken met de opties `start`, `stop` en `restart`, analoog aan hoe diensten die via een port of pakket zijn geïnstalleerd gestart worden met de scripts in [.filename]#/usr/local/etc/rc.d#. man:sshd[8] kan bijvoorbeeld als volgt herstart worden: [source,shell] .... # service restart .... Deze procedure is vrijwel gelijk voor andere diensten. Uiteraard worden diensten meestal automatisch tijdens het opstarten van de computer gestart zoals in man:rc.conf[5] staat. Om de Network Address Translation daemon bij het opstarten te laten starten is de volgende regel in [.filename]#/etc/rc.conf# bijvoorbeeld voldoende: [.programlisting] .... natd_enable="YES" .... Als er reeds een `natd_enable="NO"` regel is, kan `NO` gewoon in `YES` veranderd worden. De rc scripts starten, voor zover nodig, automatisch andere afhankelijke diensten. Omdat het [.filename]#rc.d# systeem in eerste instantie bedoeld is om diensten te starten en stoppen bij het opstarten en afsluiten van het systeem, werken de standaardopties `start`, `stop` en `restart` alleen als de juiste variabelen in [.filename]#/etc/rc.conf# zijn ingesteld. Het commando `sshd restart` alleen dan als `sshd_enable` de waarde `YES` heeft in [.filename]#/etc/rc.conf#. Als er een dienst gestart, gestopt of herstart moet worden, ongeacht de definities in [.filename]#/etc/rc.conf#, moet het commando voorafgegaan worden door "one". Dus om `sshd` te herstarten ongeacht de instellingen in [.filename]#/etc/rc.conf#, voldoet het volgende commando: [source,shell] .... # service sshd onerestart .... Het is eenvoudig te controleren of een dienst is ingeschakeld is in [.filename]#/etc/rc.conf# door het bijpassende [.filename]#rc.d#-script uit te voeren met de optie `rcvar`. Voor `sshd`: [source,shell] .... # service sshd rcvar # sshd $sshd_enable=YES .... [NOTE] ==== De tweede regel (`# sshd`) is de uitvoer van `sshd`, geen `root`-console. ==== De optie `status` wordt gebruikt om vast te stellen of een dienst gestart is. Om bijvoorbeeld te controleren of `sshd` gestart is: [source,shell] .... # service sshd status sshd is running as pid 433. .... In sommige gevallen is het ook mogelijk om een dienst te herstarten met de optie `reload`. Dan wordt er getracht een signaal te sturen aan een individuele dienst, waarbij de dienst de bestanden met instellingen opnieuw in moet lezen. Meestal komt dit neer op het verzenden van het signaal `SIGHUP`. Deze optie wordt niet door alle diensten ondersteund. Het rc.d-systeem wordt niet alleen gebruikt voor netwerkdiensten, maar ook voor het merendeel van de systeemstart. In dit kader is bijvoorbeeld het bestand [.filename]#bgfsck# interessant. Als dit script wordt uitgevoerd, wordt de volgende boodschap getoond: [source,shell] .... Starting background file system checks in 60 seconds. .... Dit script wordt dus gebruikt voor bestandssysteemcontrole in de achtergrond, hetgeen alleen tijdens de systeemstart gebeurt. Veel systeemdiensten zijn afhankelijk van andere diensten om correct te kunnen functioneren. Zo starten NIS en andere RPC-gebaseerde diensten niet als de dienst `rpcbind` (portmapper) nog niet draait. Om dit te stroomlijnen wordt informatie over afhankelijkheden en andere metagegevens ingevoegd in het commentaar bovenaan het opstartscript. Deze commentaarregels worden vervolgens tijdens de systeemstart met man:rcorder[8] verwerkt om zo vast te stellen in welke volgorde de systeemdiensten gestart moeten worden. De volgende woorden moeten in alle opstartscripts staan (ze zijn benodigd door man:rc.subr[8] om het opstartscript te activeren): * `PROVIDE`: geeft aan in welke diensten dit bestand voorziet. * `REQUIRE`: geeft aan welke andere diensten vereist zijn voor deze dienst. Dit script wordt uitgevoerd _na_ de aangegeven diensten. * `BEFORE`: geeft diensten aan die afhankelijk zijn van deze dienst. Dit bestand wordt uitgevoerd _vóór_ de aangegeven diensten. Met deze methode kan een systeembeheerder gemakkelijk systeemdiensten besturen, zonder gedoe met "runlevels" zoals bij sommige andere UNIX(R) systemen. Meer informatie over het [.filename]#rc.d#-systeem staat in man:rc[8] en man:rc.subr[8]. Als u geïnteresseerd bent in het schrijven van uw eigen [.filename]#rc.d#-script of om de huidige scripts te verbeteren is wellicht extref:{rc-scripting}[dit artikel] interessant. [[config-network-setup]] == Netwerkkaarten instellen Het is tegenwoordig nauwelijks voorstelbaar dat een computer geen netwerkverbinding heeft. Het toevoegen en instellen van een netwerkkaart is een gebruikelijke taak voor een FreeBSD-beheerder. === Het juiste stuurprogramma vinden Voor het zoeken begint, moet duidelijk zijn om welke kaart het gaat, welke chip erop zit en of het een PCI- of ISA-kaart is. FreeBSD ondersteunt vele kaarten. Op de Hardware Compatibiliteitslijst voor de betreffende uitgave staan de kaarten die ondersteund worden. Als duidelijk is dat een kaart ondersteund wordt, moet vastgesteld worden wat het geschikte stuurprogramma is. In het bestand [.filename]#/usr/src/sys/conf/NOTES# staat een lijst van stuurprogramma's voor netwerkinterfaces met wat informatie over de ondersteunde chipsets of kaarten. In geval van twijfel biedt de hulppagina voor het stuurprogramma (`man`) vaak uitkomst. In het algemeen bevat deze meer informatie over de ondersteunde hardware en mogelijke problemen die kunnen optreden. Als een veelgebruikte kaart gebruikt wordt, hoeft meestal niet ver gezocht te worden. Stuurprogramma's voor veelvoorkomende netwerkinterfaces zijn al aanwezig in de algemene kernel [.filename]#GENERIC#. In dat geval wordt zo'n kaart al gevonden bij het opstarten, bijvoorbeeld met het volgende bericht: [source,shell] .... dc0: <82c169 PNIC 10/100BaseTX> port 0xa000-0xa0ff mem 0xd3800000-0xd38 000ff irq 15 at device 11.0 on pci0 miibus0: on dc0 bmtphy0: PHY 1 on miibus0 bmtphy0: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc0: Ethernet address: 00:a0:cc:da:da:da dc0: [ITHREAD] dc1: <82c169 PNIC 10/100BaseTX> port 0x9800-0x98ff mem 0xd3000000-0xd30 000ff irq 11 at device 12.0 on pci0 miibus1: on dc1 bmtphy1: PHY 1 on miibus1 bmtphy1: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc1: Ethernet address: 00:a0:cc:da:da:db dc1: [ITHREAD] .... In dit voorbeeld zitten er twee kaarten in het systeem die het stuurprogramma man:dc[4] gebruiken. Als het stuurprogramma voor een NIC geen onderdeel is van de kernel [.filename]#GENERIC#, dan dient het juiste stuurprogramma voor die NIC geladen te worden. Dit kan op twee manieren: * De meest eenvoudige manier is het laden van een kernelmodule voor een netwerkkaart met man:kldload[8] of automatisch tijdens het opstarten van het systeem door de benodigde regel toe te voegen aan [.filename]#/boot/loader.conf#. Niet alle NIC-stuurprogramma's zijn als module beschikbaar. Zo zijn er bijvoorbeeld geen modules beschikbaar voor ISA-kaarten. * Ondersteuning voor een kaart kan ook in de kernel gecompileerd worden. In [.filename]#/usr/src/sys/conf/NOTES#, [.filename]#/usr/src/sys/arch/conf/NOTES# en de hulppagina van het stuurprogramma is na te lezen wat er in het kernelinstellingenbestand moet staan. In crossref:kernelconfig[kernelconfig,De FreeBSD-kernel instellen] staat meer informatie over het compileren van een eigen kernel. Als een netwerkkaart al bij het opstarten wordt herkend door de kernel [.filename]#GENERIC#, is er geen reden om een andere kernel te bouwen. [[config-network-ndis]] ==== Gebruik maken van Windows(R) NDIS-stuurprogramma's Helaas zijn er nog steeds veel leveranciers die geen schema's leveren voor stuurprogramma's aan de open-source gemeenschap, omdat ze deze informatie beschouwen als handelsgeheimen. Als gevolg daarvan hebben de ontwikkelaars van FreeBSD en andere projecten twee keuzes: zelf de stuurprogramma's ontwikkelen door een langdurig en pijnlijk proces van de huidige stuurprogramma's te ontcijferen, of door gebruik te maken van de huidige binaire bestanden voor het Microsoft(R) Windows(R) platform. De meeste ontwikkelaars, inclusief diegeen die gekoppeld zijn aan FreeBSD, hebben voor het laatste gekozen. Dankzij de bijdragen van Bill Paul (wpaul) is er "native" ondersteuning voor de Network Driver Interface Specification (NDIS). De FreeBSD NDISulator (ook wel bekend als Project Evil) neemt een binair Windows(R) stuurprogramma en doet net alsof deze in een Windows(R) systeem draait. Omdat het stuurprogramma man:ndis[4] een Windows(R) binary gebruikt; draait het alleen op i386(TM)- en amd64-systemen. PCI, CardBus, PCMCIA (PC-Card) en USB-apparaten worden ondersteund. Om de NDISulator te gebruiken zijn drie dingen nodig: . De bronbestanden van de kernel . Een Windows(R) XP stuurprogramma (met de extensie [.filename]#.SYS#) . Een instellingenbestand van het Windows(R) XP stuurprogramma (met de extensie [.filename]#.INF#) Lokaliseer de bestanden voor uw specifieke kaart. Over het algemeen kunnen deze gevonden worden op de bijgeleverde CD's of op de website van de leverancier. In de volgende voorbeelden maken we gebruik van [.filename]#W32DRIVER.SYS# en [.filename]#W32DRIVER.INF#. De bit-breedte van het stuurprogramma moet overeenkomen met die van het stuurprogramma. Gebruik voor FreeBSD/i386 een 32-bits Windows(R) stuurprogramma. Voor FreeBSD/amd64 is een 64-bits Windows(R) stuurprogramma nodig. De volgende stap is het compileren van het binaire stuurprogramma in een laadbare kernelmodule. Gebruik man:ndisgen[8] als `root`: [source,shell] .... # ndisgen /pad/naar/W32DRIVER.INF /pad/naar/W32DRIVER.SYS .... man:ndisgen[8] is interactief en vraagt om extra informatie als het dat nodig heeft. Een nieuwe kernel-module wordt in de huidige map geschreven. Gebruik man:kldload[8] om de nieuwe module te laden: [source,shell] .... # kldload ./W32DRIVER_SYS.ko .... Naast de gegenereerde kernelmodule, moeten ook de modules [.filename]#ndis.ko# en [.filename]#if_ndis.ko# geladen worden. Dit zou automatisch moeten gebeuren als er een module geladen wordt dit afhankelijk is van man:ndis[4]. Als ze handmatig ingeladen moeten worden gebruik dan de volgende commando's: [source,shell] .... # kldload ndis # kldload if_ndis .... Het eerste commando laadt de stuurprogrammawrapper voor de NDIS miniport, de tweede laadt de daadwerkelijke netwerkinterface. Controleer nu man:dmesg[8] om te zien of er ergens fouten voorkomen. Als alles goed gegaan is ziet u ongeveer het volgende: [source,shell] .... ndis0: mem 0xf4100000-0xf4101fff irq 3 at device 8.0 on pci1 ndis0: NDIS API version: 5.0 ndis0: Ethernet address: 0a:b1:2c:d3:4e:f5 ndis0: 11b rates: 1Mbps 2Mbps 5.5Mbps 11Mbps ndis0: 11g rates: 6Mbps 9Mbps 12Mbps 18Mbps 36Mbps 48Mbps 54Mbps .... Vanaf dit moment kan de [.filename]#ndis0# net zo gebruikt worden als elke andere netwerkkaart (bv. [.filename]#dc0#). Het systeem kan geconfigureerd worden zodat de NDIS-modules automatisch gestart worden tijdens het opstarten van het systeem, net zoals bij andere modules. Kopieer eerst de gegenereerde module [.filename]#W32DRIVER_SYS.ko# naar de map [.filename]#/boot/modules#. Voeg daarna de volgende regel toe aan [.filename]#/boot/loader.conf#: [.programlisting] .... W32DRIVER_SYS_load="YES" .... === De netwerkkaart instellen Nadat een geschikt stuurprogramma geladen is, moet de kaart nog ingesteld worden. Mogelijk is dit al gebeurd door sysinstall tijdens de installatie. Om de instellen van de netwerkkaarten weer te geven: [source,shell] .... % ifconfig dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da inet 192.168.1.3 netmask 0xffffff00 broadcast 192.168.1.255 media: Ethernet autoselect (100baseTX ) status: active dc1: flags=8802 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:db inet 10.0.0.1 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet 10baseT/UTP status: no carrier lo0: flags=8049 metric 0 mtu 16384 options=3 inet6 fe80::1%lo0 prefixlen 64 scopeid 0x4 inet6 ::1 prefixlen 128 nd6 options=3 .... In dit voorbeeld werden de volgende apparaten weergegeven: * [.filename]#dc0#: de eerste Ethernet-interface; * [.filename]#dc1#: de tweede Ethernet-interface; * [.filename]#lo0#: het loopback-apparaat; FreeBSD gebruikt de naam van het stuurprogramma gevolgd door een nummer voor de volgorde waarop de kaarten gedetecteerd zijn bij het opstarten. [.filename]#sis2# is de derde netwerkkaart in het systeem die het stuurprogramma man:sis[4] gebruikt. In het vorige voorbeeld is het apparaat [.filename]#dc0# volledig operationeel. Dit blijkt uit de volgende indicatoren: . `UP` betekent dat de kaart ingesteld is en klaar is voor gebruik; . De kaart heeft een Internet (`inet`) adres (in dit geval `192.168.1.3`); . Het heeft een geldig subnetmasker (`netmask`; `0xffffff00` is hetzelfde als `255.255.255.0`); . Het heeft een geldig broadcastadres (in dit geval `192.168.1.255`); . Het MAC-adres van de kaart (`ether`) is `00:a0:cc:da:da:da`; . De fysieke mediaselectie staat in autoselectiemodus (`media: Ethernet autoselect (100baseTX full-duplex)`). [.filename]#dc1# is ingesteld om met `10baseT/UTP`-media te werken. Meer informatie over de mogelijke mediatypes staan in de hulppagina's voor het betreffende stuurprogramma. . De status van de verbinding (`status`) is `active`, dat wil zeggen dat de drager is gevonden. Bij [.filename]#dc1# staat echter `status: no carrier`. Dit is normaal als er geen Ethernetkabel in de kaart gestoken is. Als de uitvoer man:ifconfig[8] er ongeveer zoals hieronder uitziet, dan is de netwerkkaart nog niet ingesteld: [source,shell] .... dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da media: Ethernet autoselect (100baseTX ) status: active .... Om de kaart in te stellen zijn `root`-rechten nodig. De netwerkkaart kan vanaf de console worden ingesteld met man:ifconfig[8], maar dan moet dat na elke herstart herhaald worden. Daarom wordt het vrijwel altijd in [.filename]#/etc/rc.conf# gezet. In [.filename]#/etc/rc.conf# moet voor elke netwerkkaart in een systeem een regel toegevoegd worden. In het huidige voorbeeld zou dat het volgende kunnen zijn: [.programlisting] .... ifconfig_dc0="inet 192.168.1.3 netmask 255.255.255.0" ifconfig_dc1="inet 10.0.0.1 netmask 255.255.255.0 media 10baseT/UTP" .... [.filename]#dc0#, [.filename]#dc1#, enzovoort, moeten vervangen worden door de correcte stuurprogramma's voor de netwerkkaarten, zo ook de IP-adressen. In de handleiding van het stuurprogramma en van man:ifconfig[8] staan meer details over de mogelijke opties en in man:rc.conf[5] staat meer informatie over [.filename]#/etc/rc.conf#. Als het netwerk al is ingesteld tijdens het installeren van FreeBSD staan er al enkele regels met betrekking tot de netwerkkaart(en) in [.filename]#/etc/rc.conf#. Het is dus handig [.filename]#/etc/rc.conf# te controleren voordat er regels toegevoegd worden. Ook [.filename]#/etc/hosts# moet worden gewijzigd om de namen en IP adressen van verschillende machines op het lokale netwerk, als ze er nog niet in staan. Meer informatie staat in man:hosts[5] en [.filename]#/usr/shared/examples/etc/hosts#. [NOTE] ==== Als internettoegang nodig is met dit apparaat, kan het zijn dat de default gateway en de naamserver handmatig moeten worden ingesteld: [source,shell] .... # echo 'defaultrouter="your_default_router"' >> /etc/rc.conf # echo 'nameserver your_DNS_server' >> /etc/resolv.conf .... ==== === Testen en problemen oplossen Als de veranderingen in [.filename]#/etc/rc.conf# zijn gemaakt, moet het systeem opnieuw gestarten worden (of moeten nauwkeurig alle daemons gestart of herstart worden). Veranderingen aan de interface(s) worden dan toegepast en dan kan er controleerd worden of herstarten goed werkt zonder foutmeldingen. Als alternatief kan ook het netwerk systeem herstart worden: [source,shell] .... # service netif restart .... [NOTE] ==== Als er ook een default gateway ingesteld is in het [.filename]#/etc/rc.conf# bestand, moet ook onderstaand command worden gegeven: [source,shell] .... # service routing restart .... ==== Zodra het netwerk systeem is herstart, moeten de netwerk interfaces opnieuw getest worden. ==== Testen van de netwerkkaart Om te controleren of een ethernet kaart goed geconfigureerd is, moeten er twee dingen gedaan worden. Allereerst, ping de interface zelf, en daarna een andere machine op het LAN. Test eerst de lokale interface: [source,shell] .... % ping -c5 192.168.1.3 PING 192.168.1.3 (192.168.1.3): 56 data bytes 64 bytes from 192.168.1.3: icmp_seq=0 ttl=64 time=0.082 ms 64 bytes from 192.168.1.3: icmp_seq=1 ttl=64 time=0.074 ms 64 bytes from 192.168.1.3: icmp_seq=2 ttl=64 time=0.076 ms 64 bytes from 192.168.1.3: icmp_seq=3 ttl=64 time=0.108 ms 64 bytes from 192.168.1.3: icmp_seq=4 ttl=64 time=0.076 ms --- 192.168.1.3 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.074/0.083/0.108/0.013 ms .... Nu kan er een andere machine op het LAN gepinged worden: [source,shell] .... % ping -c5 192.168.1.2 PING 192.168.1.2 (192.168.1.2): 56 data bytes 64 bytes from 192.168.1.2: icmp_seq=0 ttl=64 time=0.726 ms 64 bytes from 192.168.1.2: icmp_seq=1 ttl=64 time=0.766 ms 64 bytes from 192.168.1.2: icmp_seq=2 ttl=64 time=0.700 ms 64 bytes from 192.168.1.2: icmp_seq=3 ttl=64 time=0.747 ms 64 bytes from 192.168.1.2: icmp_seq=4 ttl=64 time=0.704 ms --- 192.168.1.2 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.700/0.729/0.766/0.025 ms .... Dit kan ook worden geprobeerd met de machine naam in plaats van met `192.168.1.2` als dit geconfigureerd is in [.filename]#/etc/hosts#. ==== Problemen oplossen Het testen en zoeken van problemen is altijd een pijnpunt, welke verminderd kan worden door een aantal simpele dingen eerst te controleren. Is de netwerkkabel ingestoken? Zijn de netwerk instellingen correct opgegeven? Is de firewall goed geconfigureerd? Is de netwerkkaart ondersteund door FreeBSD? Controleer altijd de hardware notities voordat er een probleem rapport wordt verstuurd. Update naar de laatste -STABLE versie, en controleer de mailing lijsten en misschien zelfs het internet. Als de kaart werkt, maar de prestaties zijn slecht, dan kan het de moeite waard zijn om man:tuning[7] door te nemen. Incorrecte netwerkinstellingen kunnen ook tot langzame verbindingen leiden. Soms kunnen enkele `device timeouts` optreden. Met sommige kaarten is dit normaal gedrag. Maar als dit continu gebeurt of storend is, is het verstandig uit te zoeken of er geen sprake is van een hardwareconfict tussen de netwerkkaart en een ander apparaat. Ook dient nogmaals de bekabeling gecontroleerd te worden. Misschien zit er niets anders op dan een andere netwerkkaart te gebruiken. Het is ook mogelijk dat er `watchdog timeout` foutmeldingen optreden. Als eerste moet dan de netwerkkabel gecontroleerd worden. Veel kaarten hebben een PCI-slot nodig dat Bus Mastering ondersteunt. Sommige oudere moederborden hebben maar één PCI-slot waarmee dit kan (meestal slot 0). In de documentatie van de netwerkkaart en het moederbord is na te gaan of dit het probleem is. `No route to host` meldingen treden op als het systeem niet in staat is om een pakket naar de eindbestemming te routeren. Dit kan gebeuren als er geen standaardroute aangegeven is of als er een kabel niet verbonden is. De uitvoer van `netstat -rn` moet gecontroleerd worden of er een geldige route is naar de bestemming. Mocht dit niet het geval zijn, dan staat er meer informatie in crossref:advanced-networking[advanced-networking,Netwerken voor gevorderden]. `ping: sendto: Permission denied` foutmeldingen worden vaak veroorzaakt door een verkeerd ingestelde firewall. Als de kernel `ipfw` activeert bij het opstarten zonder dat er firewallregels zijn gedefiniëerd, is het standaardbeleid om alle verkeer te weigeren, zelfs pings! In crossref:firewalls[firewalls,Firewalls] staat meer informatie. Er kan ook sprake zijn van onvoldoende prestaties doordat de instelling van de mediaselectie niet optimaal is. In dergelijke gevallen is het mogelijk om de mediaselectie niet als `autoselect` in te stellen, maar expliciet aan te geven wat de mediaselectie moet zijn, bijvoorbeeld 10baseT/UTP voor twisted pair. Hoewel dit voor de meeste hardware helpt, kan het zijn dat de problemen blijven. Dan moeten nogmaals de netwerkinstellingen gecontroleerd worden en geeft de man:tuning[7] handleiding wellicht meer informatie. [[configtuning-virtual-hosts]] == Virtuele hosts FreeBSD wordt veel gebruikt voor virtuele sitehosting, waarbij één fysieke server er op het netwerk uitziet alsof het meerdere servers zijn. Dit kan bereikt worden door meerdere IP-adressen toe te kennen aan dezelfde interface. Een bepaalde netwerkinterface heeft een "echt" adres en kan daarnaast een willekeurig aantal "alias"-adressen hebben. Normaliter worden dergelijke aliassen toegevoegd door aliasregels toe te voegen aan [.filename]#/etc/rc.conf#. Een aliasregel voor de interface [.filename]#fxp0# ziet er zo uit: [.programlisting] .... ifconfig_fxp0_alias0="inet xxx.xxx.xxx.xxx netmask xxx.xxx.xxx.xxx" .... De aliasregels moeten beginnen met `alias0` en moete elkaar dan opvolgen (bijvoorbeeld `_alias1,`, `_alias2`, enzovoort). Het instelproces stopt als er een nummer ontbreekt. Het is belangrijk dat aliassen het juiste netmasker hebben. Dit is eenvoudig: Een bepaalde interface moet altijd één adres hebben dat het netmasker van het netwerk correct representeert. Elk ander adres binnen dit netwerk op deze interface (alias) moet een netmasker van allemaal ``1``'en (bits) hebben (getoond als `255.255.255.255` of `0xffffffff`). Een voorbeeld. Stel de interface [.filename]#fxp0# is verbonden met twee netwerken, het netwerk `10.1.1.0` met masker `255.255.255.0` en het netwerk `202.0.75.16` met netmasker `255.255.255.240`. Het systeem moet ook de adressen `10.1.1.1` tot en met `10.1.1.5` en `202.0.75.17` tot en met `202.0.75.20` krijgen. Zoals hierboven vermeld, heeft alleen het eerste adres in een netwerkreeks (in dit geval `10.0.1.1` en `202.0.75.17`) een geldig netmasker. Alle overige (`10.1.1.2` tot en met `10.1.1.5` en `202.0.75.18` tot en met `202.0.75.20`) moeten ingesteld worden met het netmasker `255.255.255.255`. De volgende regels voor [.filename]#/etc/rc.conf# stellen een adapter in voor het bovenstaande scenario: [.programlisting] .... ifconfig_fxp0="inet 10.1.1.1 netmask 255.255.255.0" ifconfig_fxp0_alias0="inet 10.1.1.2 netmask 255.255.255.255" ifconfig_fxp0_alias1="inet 10.1.1.3 netmask 255.255.255.255" ifconfig_fxp0_alias2="inet 10.1.1.4 netmask 255.255.255.255" ifconfig_fxp0_alias3="inet 10.1.1.5 netmask 255.255.255.255" ifconfig_fxp0_alias4="inet 202.0.75.17 netmask 255.255.255.240" ifconfig_fxp0_alias5="inet 202.0.75.18 netmask 255.255.255.255" ifconfig_fxp0_alias6="inet 202.0.75.19 netmask 255.255.255.255" ifconfig_fxp0_alias7="inet 202.0.75.20 netmask 255.255.255.255" .... [[configtuning-syslog]] == De systeemlogger syslogd configureren Systeemlogging is een belangrijk aspect van systeembeheer. Het wordt zowel gebruikt voor het opsporen van hardware-problemen als voor software-problemen in het systeem. Het speelt ook zeer belangrijke rol bij het controleren van de beveiliging en het reageren op incidenten. Systeem-daemons die niet in een terminal beheerd worden, loggen gewoonlijk informatie naar een systeemlogfaciliteit of een ander logbestand. Deze sectie beschrijft hoe de FreeBSD systeemlogger, man:syslogd[8], te configureren en te gebruiken, en behandelt logrotatie en logbeheer met man:newsyslog[8]. De focus ligt bij het opzetten en gebruiken van `syslogd` op een lokale machine. Meer geavanceerdere opstellingen die een aparte loghost gebruiken staan in crossref:network-servers[network-syslogd,Hosts op afstand loggen met syslogd]. === syslogd gebruiken In de standaardconfiguratie van FreeBSD wordt man:syslogd[8] gestart tijdens het opstarten. Dit wordt bepaald door de variabele `syslogd_enable` in [.filename]#/etc/rc.conf#. Er zijn vele toepassingsargumenten die het gedrag van man:syslogd[8] beïnvloeden. Gebruik `syslogd_flags` in [.filename]#/etc/rc.conf# om ze te veranderen. Bekijk man:syslogd[8] voor meer informatie over de argumenten, en man:rc.conf[5], <> en <> voor meer informatie over [.filename]#/etc/rc.conf# en het deelsysteem man:rc[8]. === syslogd configureren Het configuratiebestand, standaard [.filename]#/etc/syslog.conf#, bepaalt wat man:syslogd[8] doet met de logregels nadat ze eenmaal ontvangen zijn. Er zijn verschillende parameters om de afhandeling van binnenkomende gebeurtenissen te beheren, waarvan de twee basaalste _faciliteit_ en _niveau_ zijn. De faciliteit beschrijft welk deelsysteem het bericht genereerde, zoals de kernel of een daemon, het niveau beschrijft de ernst van de opgetreden gebeurtenis. Dit maakt het mogelijk om het bericht naar verschillende logbestanden te loggen, of het weg te gooien, afhankelijk van de faciliteit en het niveau. Het is ook mogelijk om actie te nemen afhankelijk van de toepassing dat het bericht verstuurde, en in het geval van loggen op afstand, ook de hostnaam van de machine dat het logbericht genereerde. Het configureren van man:syslogd[8] is vrij rechttoe-rechtaan. Het configuratiebestand bevat één regel per actie, de syntaxis van elke regel is een selecteerderveld gevolgd door een actieveld. De syntaxis van het selecteerderveld is _faciliteit.niveau_ dat overeenkomt met logberichten van _faciliteit_ op niveau _niveau_ of hoger. Het is ook mogelijk om een optionele vergelijkingsvlag voor het niveau toe te voegen om meer precies te specificeren wat er gelogd wordt. Er kunnen meerdere selecteerdervelden worden gebruikt voor dezelfde actie, ze worden gescheiden door een puntkomma (`;`). Het gebruik van `*` zal met alles overeenkomen. Het actieveld bepaalt waar het logbericht naar toe wordt gezonden, zoals een bestand of een loghost op afstand. Als voorbeeld is hier de standaard [.filename]#syslog.conf# van FreeBSD: [.programlisting] .... # $FreeBSD$ # # Spaces ARE valid field separators in this file. However, # other *nix-like systems still insist on using tabs as field # separators. If you are sharing this file between systems, you # may want to use only tabs as field separators here. # Consult the man:syslog.conf[5] manpage. *.err;kern.warning;auth.notice;mail.crit /dev/console <.> *.notice;authpriv.none;kern.debug;lpr.info;mail.crit;news.err /var/log/messages security.* /var/log/security auth.info;authpriv.info /var/log/auth.log mail.info /var/log/maillog <.> lpr.info /var/log/lpd-errs ftp.info /var/log/xferlog cron.* /var/log/cron *.=debug /var/log/debug.log <.> *.emerg * # uncomment this to log all writes to /dev/console to /var/log/console.log #console.info /var/log/console.log # uncomment this to enable logging of all log messages to /var/log/all.log # touch /var/log/all.log and chmod it to mode 600 before it will work #*.* /var/log/all.log # uncomment this to enable logging to a remote loghost named loghost #*.* @loghost # uncomment these if you're running inn # news.crit /var/log/news/news.crit # news.err /var/log/news/news.err # news.notice /var/log/news/news.notice !ppp <.> *.* /var/log/ppp.log !* .... <.> Komt overeen met alle berichten met een `err` of hoger, alsook met `kern.warning`, `auth.notice` en `mail.crit`, en stuur deze logberichten naar de console ( [.filename]#/dev/console#). <.> Komt overeen met alle berichten van de faciliteit `mail` op niveau `info` of hoger, en logt de berichten in [.filename]#/var/log/maillog#. <.> Deze regel gebruikt een vergelijkingsvlag, `=` om alleen met de berichten op niveau `debug` overeen te komen en ze op te slaan in [.filename]#/var/log/debug.log#. <.> Hier volgt een gebruiksvoorbeeld van een _programmaspecificatie_. Dit zorgt ervoor dat de regels alleen geldig zijn voor het programma in de programmaspecificatie. In dit geval zorgen deze en de volgende regel ervoor dat alle berichten van `ppp`, maar niet van andere programma's, in [.filename]#/var/log/ppp.log# terechtkomen. Dit voorbeeld toont dat er vele niveaus en deelsystemen zijn. De niveaus zijn, in volgorde van meest naar minst kritisch: `emerg`, `alert`, `crit`, `err`, `warning`, `notice`, `info` en `debug`. De faciliteiten zijn, in geen specifieke volgorde: `auth`, `authpriv`, `console`, `cron`, `daemon`, `ftp`, `kern`, `lpr`, `mail`, `mark`, `news`, `security`, `syslog`, `user`, `uucp` en `local0` tot en met `local7`. Let erop dat andere besturingssystemen andere faciliteiten kunnen hebben. Met deze kennis is het eenvoudig om een nieuwe regel aan [.filename]#/etc/syslog.conf# toe te voegen om alles van de verschillende daemons op niveau `notice` en hoger naar [.filename]#/var/log/daemon.log# te loggen: [.programlisting] .... daemon.notice /var/log/daemon.log .... Bekijk man:syslog[3] en man:syslogd[8] voor meer informatie over de verschillende niveaus en faciliteiten. Zie man:syslog.conf[5] en crossref:network-servers[network-syslogd,Hosts op afstand loggen met syslogd] voor meer informatie over [.filename]#syslog.conf#, de syntaxis, en geavanceerdere gebruiksvoorbeelden. === Logbeheer en -rotatie met newsyslog Logbestanden hebben de neiging om snel te groeien en gestadig opgehoopt te raken. Dit leidt tot bestanden die vol zitten met minder direct bruikbare informatie en de harde schijf volmaken. Logbeheer kan gebruikt worden om dit te beheersen. In FreeBSD wordt man:newsyslog[8] gebruikt om logbestanden te beheren. Dit programma wordt gebruikt om periodiek logbestanden te roteren en te comprimeren en om optioneel ontbrekende logbestanden aan te maken en programma's te signaleren dat logbestanden zijn verplaatst. De logbestanden hoeven niet per sé van syslog afkomstig te zijn; man:newsyslog[8] werkt met elke log van elk programma. Het is belangrijk om op te merken dat `newsyslog` normaliter vanuit man:cron[8] wordt gedraaid en niet een systeem-daemon is. In de standaardconfiguratie wordt het elk uur gedraaid. ==== newsyslog configureren Om te weten wat het moet doen leest man:newsyslog[8] zijn configuratiebestand, standaard is dit [.filename]#/etc/newsyslog.conf#. Dit configuratiebestand bevat één regel voor elk bestand dat man:newsyslog[8] beheert. Elke regel noemt de eigenaar van het bestand, rechten, en wanneer dat bestand te roteren, alsook optionele vlaggen die de logrotatie beïnvloeden (zoals compressie) en naar welke programma's een signaal te sturen wanner de log is geroteerd. Als voorbeeld is hier de standaard configuratie in FreeBSD: [.programlisting] .... # configuration file for newsyslog # $FreeBSD$ # # Entries which do not specify the '/pid_file' field will cause the # syslogd process to be signalled when that log file is rotated. This # action is only appropriate for log files which are written to by the # syslogd process (ie, files listed in /etc/syslog.conf). If there # is no process which needs to be signalled when a given log file is # rotated, then the entry for that file should include the 'N' flag. # # The 'flags' field is one or more of the letters: BCDGJNUXZ or a '-'. # # Note: some sites will want to select more restrictive protections than the # defaults. In particular, it may be desirable to switch many of the 644 # entries to 640 or 600. For example, some sites will consider the # contents of maillog, messages, and lpd-errs to be confidential. In the # future, these defaults may change to more conservative ones. # # logfilename [owner:group] mode count size when flags [/pid_file] [sig_num] /var/log/all.log 600 7 * @T00 J /var/log/amd.log 644 7 100 * J /var/log/auth.log 600 7 100 @0101T JC /var/log/console.log 600 5 100 * J /var/log/cron 600 3 100 * JC /var/log/daily.log 640 7 * @T00 JN /var/log/debug.log 600 7 100 * JC /var/log/init.log 644 3 100 * J /var/log/kerberos.log 600 7 100 * J /var/log/lpd-errs 644 7 100 * JC /var/log/maillog 640 7 * @T00 JC /var/log/messages 644 5 100 @0101T JC /var/log/monthly.log 640 12 * $M1D0 JN /var/log/pflog 600 3 100 * JB /var/run/pflogd.pid /var/log/ppp.log root:network 640 3 100 * JC /var/log/security 600 10 100 * JC /var/log/sendmail.st 640 10 * 168 B /var/log/utx.log 644 3 * @01T05 B /var/log/weekly.log 640 5 1 $W6D0 JN /var/log/xferlog 600 7 100 * JC .... Elke regel begint met de naam van het bestand dat geroteerd moet worden, optioneel gevolgd door een eigenaar en groep voor zowel de geroteerde als nieuw aangemaakte bestanden. Het volgende veld, `mode` is de modus van de bestanden en `count` geeft aan hoeveel geroteerde logbestanden bewaard moeten worden. De velden `size` en `when` vertellen `newyslog` wanneer het bestand geroteerd moet worden. Een logbestand wordt geroteerd wanneer òfwel de grootte meer is dan de waarde in het veld `size`, òfwel wanneer de tijd in het veld `when` is verstreken. `*` geeft aan dat dit veld genegeerd wordt. Het veld _flags_ geeft man:newsyslog[8] verdere instructies, zoals hoe het geroteerde bestand te comprimeren of om het logbestand aan te maken als het ontbreekt. De laatste twee velden zijn optioneel en specificeren het PID-bestand van een proces en een naar dat proces te verzenden signaalnummer wanneer het bestand wordt geroteerd. Raadpleeg man:newsyslog.conf[5] voor meer informatie over alle velden, geldige vlaggen en hoe de rotatietijd te specificeren. Herinner dat `newsyslog` wordt gedraaid vanuit `cron` en niet vaker bestanden kan roteren dan dat het gedraaid wordt vanuit man:cron[8]. [[configtuning-configfiles]] == Instellingenbestanden === [.filename]#/etc# layout Instellingengegevens wordt in een aantal mappen bewaard. Daar zijn onder andere: [.informaltable] [cols="1,1", frame="none"] |=== |[.filename]#/etc# |Generieke systeeminstellingenbestanden, specifiek voor het systeem. |[.filename]#/etc/defaults# |De standaardversies van systeeminstellingenbestanden. |[.filename]#/etc/mail# |Extra man:sendmail[8] instellingenbestanden of instellingenbestanden voor andere MTAs. |[.filename]#/etc/ppp# |Instellingen voor zowel gebruiker- als kernel-ppp programma's. |[.filename]#/etc/namedb# |Standaardlocatie voor man:named[8] gegevens. Normaal gesproken bevinden zich hier [.filename]#named.conf# en zonebestanden. |[.filename]#/usr/local/etc# |Instellingenbestanden voor geïnstalleerde software. Kan submappen hebben waarin bij elkaar horende instellingengegevens van een applicatie gegroepeerd zijn. |[.filename]#/usr/local/etc/rc.d# |Start- en stopscripts voor geïnstalleerde diensten. |[.filename]#/var/db# |Automatisch gemaakte systeemspecifieke databasebestanden, zoals de pakketdatabase, de man:locate[1] database, enzovoort. |=== === Hostnamen ==== [.filename]#/etc/resolv.conf# In [.filename]#/etc/resolv.conf# wordt voorgeschreven op welke wijze FreeBSD het Domain Name System (DNS) moet gebruiken. De meest voorkomende termen in [.filename]#resolv.conf# zijn: [.informaltable] [cols="1,1", frame="none"] |=== |`nameserver` |Het IP-adres van een naamserver die ondervraagd moet worden voor naam/IP-conversie. De servers worden in volgorde geprobeerd en het maximale aantal is drie. |`search` |Zoeklijst voor het opzoeken van hostnamen. Meestal wordt deze bepaald door het domein waarop de lokale hostnaam zich bevindt. |`domain` |De lokale domeinnaam. |=== Een typisch [.filename]#resolv.conf# bestand: [.programlisting] .... search example.com nameserver 147.11.1.11 nameserver 147.11.100.30 .... [NOTE] ==== `search` en `domain` dienen niet tegelijk gebruikt te worden. ==== Als DHCP wordt gebruikt: man:dhclient[8] overschrijft meestal [.filename]#resolv.conf# met informatie ontvangen van de DHCP-server. ==== [.filename]#/etc/hosts# [.filename]#/etc/hosts# is een eenvoudige tekstdatabase uit de dagen van het oude Internet. Het werkt samen met DNS en NIS om namen en IP adressen over en weer te vertalen. Lokale computers, verbonden via een LAN, kunnen hier het beste in opgenomen worden om zo op simpele wijze naam/IP conversie voor een LAN te hebben, zonder noodzaak voor een man:named[8] server. Ook kunnen naamaliassen toegekend worden (vergelijkbaar met CNAMES bij DNS). Op soortgelijke wijze kan [.filename]#/etc/hosts# gebruikt worden als een (zeer beperkte) lokale DNS cache. [.programlisting] .... # $FreeBSD$ # # Host Database # Dit bestand hoort de adressen en aliassen te bevatten # voor de lokale hosts die dit bestand gebruiken. # Bij gebruik van DNS of NIS hoeft dit bestand helemaal niet gebruikt # te worden. Zie /etc/nsswitch.conf voor de volgorde van resolutie. # # ::1 localhost localhost.my.domain myname.my.domain 127.0.0.1 localhost localhost.my.domain myname.my.domain # # Verzonnen netwerk. #10.0.0.2 myname.my.domain myname #10.0.0.3 myfriend.my.domain myfriend # # Volgens RFC 1918 mogen de volgende IP netwerken gebruikt worden # als private netwerken die niet met Internet verbonden zijn: # # 10.0.0.0 - 10.255.255.255 # 172.16.0.0 - 172.31.255.255 # 192.168.0.0 - 192.168.255.255 # # Als er toch verbinding moet zijn met Internet, zijn echte # officieel toegewezen nummers nodig. Probeer ECHT GEEN eigen # netwerknummers te verzinnen, maar vraag ze op bij de provider # (als die er is) of bij de Internet Registry (ftp naar # rs.internic.net, map `/templates'). # .... [.filename]#/etc/hosts# heeft als formaat: [.programlisting] .... [Internet address] [official hostname] [alias1] [alias2] ... .... Bijvoorbeeld: [.programlisting] .... 10.0.0.1 myRealHostname.example.com myRealHostname foobar1 foobar2 .... In man:hosts[5] staat meer informatie. [[configtuning-sysctlconf]] === [.filename]#sysctl.conf# [.filename]#sysctl.conf# lijkt veel op [.filename]#rc.conf#. Waardetoekenning heeft weer de vorm `variable=value`. De ingestelde man:sysctl[8]-waarden worden doorgevoerd op het moment dat het systeem naar multi-user modus gaat. Niet alle variabelen kunnen in deze modus gewijzigd worden. Om te voorkomen dat er logregels geplaatst worden als processen crashen en om te voorkomen dat andere gebruikers kunnen zien welke processen er gestart zijn door een andere gebruiker, kunnen de volgende instellingen worden gezet in [.filename]#sysctl.conf#: [.programlisting] .... #Log exits met fatale signalen niet (bv. sig 11) kern.logsigexit=0 # Voorkom dat gebruikers informatie zien over processen die # worden gedraaid onder een ander UID. security.bsd.see_other_uids=0 .... [[configtuning-sysctl]] == Optimaliseren met sysctl man:sysctl[8] is een interface waarmee veranderingen gemaakt kunnen worden aan een draaiend FreeBSD-systeem. Er zijn onder meer vele geavanceerde opties voor de TCP/IP-stack en het virtuele geheugensysteem, waarmee een ervaren systeembeheerder de systeemprestaties drastisch kan verbeteren. Met man:sysctl[8] kunnen meer dan vijfhonderd systeemvariabelen opgevraagd en ingesteld worden. In essentie heeft man:sysctl[8] twee functies: het lezen en wijzigen van systeeminstellingen. Om alle leesbare variabelen te tonen: [source,shell] .... % sysctl -a .... Om een bepaalde variabele op te vragen, bijvoorbeeld `kern.maxproc`: [source,shell] .... % sysctl kern.maxproc kern.maxproc: 1044 .... Om een bepaalde variabele toe te kennen (te wijzigen), is de syntaxis _variable_=_value_: [source,shell] .... # sysctl kern.maxfiles=5000 kern.maxfiles: 2088 -> 5000 .... Waarden van sysctl-variabelen zijn doorgaans strings (tekst), getallen of booleans (`1` als waar, `0` als onwaar). Om automatisch variabelen in te stellen als de machine start, kunnen ze toegevoegd worden aan [.filename]#/etc/sysctl.conf#. Meer informatie staat in man:sysctl.conf[5] en <>. [[sysctl-readonly]] === man:sysctl[8] alleen-lezen In sommige gevallen is het wenselijk om man:sysctl[8]-waarden die alleen-lezen zijn toch te wijzigen. Hoewel dit soms onontkoombaar is, kan het alleen bij een (her)start gedaan worden. Op sommige laptops is bijvoorbeeld het apparaat man:cardbus[4] niet in staat om geheugenregio's af te tasten, met als gevolg foutmeldingen als: [source,shell] .... cbb0: Could not map register memory device_probe_and_attach: cbb0 attach returned 12 .... In dergelijke gevallen moeten er meestal enkele man:sysctl[8]-instellingen gewijzigd worden die alleen-lezen zijn en een standaardwaarde hebben. Dit kan bereikt worden door man:sysctl[8] "OIDs" in de lokale [.filename]#/boot/loader.conf# te zetten. Standaardinstellingen staan in [.filename]#/boot/defaults/loader.conf#. Om het bovenstaande probleem op te lossen moet in [.filename]#/boot/loader.conf#`hw.pci.allow_unsupported_io_range=1` ingesteld worden. Dan werkt man:cardbus[4] wel goed. [[configtuning-disk]] == Harde schijven optimaliseren === Sysctl-variabelen ==== `vfs.vmiodirenable` De sysctl-variabele `vfs.vmiodirenable` kan de waarde 0 (uit) of 1 (aan) hebben. De standaardwaarde is 1. Deze variabele bepaalt hoe mappen door het systeem in een cache bewaard worden. De meeste mappen zijn klein en gebruiken slechts een klein fragment (typisch 1 K) in het bestandssysteem en nog minder (typisch 512 bytes) in de buffercache. Als deze variabele uit staat (op 0) bewaart de buffercache slechts een bepaald aantal mappen in de cache, ook al is er een overvloed aan geheugen beschikbaar. Wanneer deze aan staat (op 1), wordt de VM paginacache gebruikt, waardoor voor het cachen van mappen al het geheugen kan worden gebruikt. Het is echter wel zo dat het minimale in-core geheugen dat gebruikt wordt om een map te cachen in dat geval de fysieke paginagrootte is (typisch 4 K) in plaats van 512 bytes. Het is aan te raden deze optie aan te laten staan als gebruik gemaakt wordt van diensten die met grote aantallen bestanden werken, zoals webcaches, grote mailsystemen en newsservers. Als deze optie aan blijft staan, verlaagt die de prestaties niet, ook al kost het meer geheugen. Door experimenteren is dit voor een systeem na te gaan. ==== `vfs.write_behind` De sysctl-variabele `vfs.write_behind` staat standaard aan (`1`). Dit betekent dat het bestandssysteem gegevens naar het medium gaat schrijven op het moment dat er een volledig cluster aan gegevens verzameld is. Dit is meestal het geval bij het schrijven van grote sequentiële bestanden. Het idee is om te voorkomen dat de buffercache verzadigd raakt met vuile buffers zonder dat dit bijdraagt aan de I/O-prestaties. Dit kan echter processen ophouden en onder sommige omstandigheden is het wellicht beter deze sysctl uit te zetten. ==== `vfs.hirunningspace` De sysctl-variabele `vfs.hirunningspace` bepaalt hoeveel nog te schrijven gegevens er in het complete systeem op elk moment in de wachtrij naar schijfcontrollers mag staan. De standaardwaarde is meestal voldoende, maar op machines met veel schijven, is het beter deze te verhogen naar vier of vijf _megabyte_. Het instellen van een te hoge waarde (groter dan de schrijfdrempel van de buffercache) kan leiden tot zeer slechte prestaties bij clustering. Stel deze waarde niet arbitrair hoog in! Hogere schrijfwaarden kunnen vertraging veroorzaken in het lezen, als dit tegelijk plaatsvindt. Er zijn verscheidene andere sysctl's voor buffercache en VM-pagecache. Het wordt afgeraden deze te wijzigen. Het VM-systeem is zeer goed in staat zichzelf automatisch te optimaliseren. ==== `vm.swap_idle_enabled` De sysctl-variabele `vm.swap_idle_enabled` is nuttig in grote meergebruikersystemen met veel gebruikers die af- en aanmelden en veel onbenutte processen. Dergelijke systemen hebben de neiging om voortdurend de vrije geheugenreserves onder druk te zetten. Het is mogelijk om de prioriteit van geheugenpagina's die verband houden met onbenutte processen sneller te laten dalen dan met het normale pageout-algoritme, door deze sysctl aan te zetten en via `vm.swap_idle_threshold1` en `vm.swap_idle_threshold2` de swapout hysterese (in seconden onbenut) af te stemmen. Deze optie dient alleen gebruikt te worden als ze echt nodig is, want de andere kant van de medaille is dat dit eerder pre-page geheugen inhoudt in plaats van later, waardoor het meer wisselbestand- en schijfbandbreedte kost. In een klein systeem heeft deze optie een voorspelbaar effect, maar in grote systemen waar al sprake is van een matige paging kan deze optie het mogelijk maken voor het VM-systeem om hele processen gemakkelijk in en uit het geheugen te halen. ==== `hw.ata.wc` Ten tijde van FreeBSD 4.3 is er geflirt met het uitzetten van IDE-schrijfcaching. Hierdoor neemt de bandbraadte naar IDE-schijven af, maar het werd als noodzakelijk beschouwd vanwege ernstige problemen met gegevensinconsistentie die door harde schijfproducenten geëintroduceerd waren. Het probleem is dat IDE-schijven niet de waarheid vertellen over wanneer een schrijfactie klaar is. Door IDE-schrijfcaching wordt data niet alleen ongeordend geschreven, maar soms kan zelfs het schrijven van sommige blokken voortdurend uitgesteld worden als er sprake is van een hoge schijfbelasting. Een crash of stroomstoring kan dan ernstige corruptie aan het bestandssysteem veroorzaken. Daarom werd de standaardinstelling van FreeBSD voor alle zekerheid gewijzigd. Helaas was het resultaat een groot verlies aan prestaties en na die uitgave is de standaardwaarde weer terug veranderd. Met de sysctl-variabele `hw.ata.wc` kan gecontroleerd worden of schrijfcaching aan of uit staat. Als schrijfcaching uit staat, kan het die weer aangezet worden door `hw.ata.wc` op 1 te zetten. Aangezien dit een kernelvariabele is, moet deze ingesteld worden vanuit de bootloader tijdens het opstarten. Nadat de kernel eenmaal opgestart is, heeft het wijzigen van deze sysctl geen effect. Meer informatie staat in man:ata[4]. ==== `SCSI_DELAY` (`kern.cam.scsi_delay`) De kernelinstelling `SCSI_DELAY` kan gebruikt worden om de opstarttijd te versnellen. De standaardwaarde is nogal hoog en kan `15` seconden vertraging veroorzaken. Met modernere SCSI-systemen is `5` seconden al voldoende (zeker met moderne schijven). De `kern.cam.scsi_delay` opstart variabele moet hier gebruikt worden. De variabele en kernelconfiguratie-optie accepteren waarden uitgedrukt in _milliseconden_ en _niet_ in _seconden_. [[soft-updates]] === Softupdates man:tunefs[8] kan gebruikt worden om een bestandsysteem nauwkeurig af te stellen. Het heeft veel opties, maar nu wordt alleen het aan- en uitzetten van softupdates besproken. Dat gaat als volgt: [source,shell] .... # tunefs -n enable /filesystem # tunefs -n disable /filesystem .... Een bestandssysteem kan niet met man:tunefs[8] gewijzigd worden als het aangekoppeld is. Softupdates aanzetten wordt dus in het algemeen gedaan vanuit enkelegebruikermodus, voordat partities aangekoppeld zijn. Softupdates zorgen voor een drastische verbetering van de prestaties met betrekking tot metagegevens, met name het aanmaken en verwijderen van bestanden, door gebruik van een geheugencache. Het wordt dan ook aangeraden om op alle bestandssystemen softupdates te gebruiken. Er zijn twee nadelen aan softupdates: softupdates garanderen een consistent bestandssysteem in geval van een crash, maar het kan makkelijk enkele seconden (zelfs een minuut) achter liggen met het daadwerkelijk bijwerken op de fysieke harde schijf. Als een systeem crasht gaat wellicht meer werk verloren dan anders het geval zou zijn. Daarnaast vertragen softupdates het vrijgeven van bestandssysteemblokken. Als een bestandssysteem (zoals de rootpartitie) bijna vol is, dan kan het verrichten van een grote update, zoals `make installworld`, ertoe leiden dat het bestandssysteem ruimtegebrek krijgt en dat daardoor de operatie mislukt. ==== Meer over softupdates Er zijn traditioneel twee methodes om de metagegevens van een bestandssysteem terug naar de schijf te schrijven. Het bijwerken van metagegevens houdt het bijwerken van van niet-inhoudelijke gegevens zoals inodes of mappen in. Historisch gezien was het gebruikelijk om updates aan metagegevens synchroon weg te schrijven. Als een map bijvoorbeeld gewijzigd was, wachtte het systeem totdat de verandering daadwerkelijk naar de schijf geschreven was. De gegevensbuffers (de inhoud van een bestand) werden doorgeschoven naar de buffercache en op een later moment asynchroon op de schijf opgeslagen. Het voordeel van deze benadering is dat ze altijd veilig is. Als het systeem faalt tijdens het bijwerken, zijn de metagegevens nog altijd consistent. Een bestand kan volledig gecreëerd zijn of helemaal niet. Als de gegevensblokken van een bestand nog niet van de buffercache naar de schijf geschreven zijn ten tijde van de crash, is man:fsck[8] in staat om dit te herkennen en het bestandssysteem te repareren door de lengte van het bestand nul te maken. Deze implementatie is ook helder en eenvoudig. Het nadeel is echter dat het wijzigen van metagegevens een traag proces is. Een `rm -r` benadert bijvoorbeeld alle bestanden in een map sequentiëel, maar elke mapverandering (verwijderen van een bestand) wordt synchroon naar de schijf geschreven. Dit omvat ook het bijwerken van de map zelf, van de inodetabel en mogelijk ook van indirecte blokken die voor het bestand in kwestie zijn gealloceerd. Gelijksoortige processen spelen zich af bij een commando als `tar -x`, waarbij een grote bestandshiëearchie wordt uitgepakt. De tweede mogelijkheid is om het bijwerken van metagegevens asynchroon weg te schrijven. Dit is standaard in Linux(R)/ext2fs en als een *BSD UFS-bestandssysteem met `mount -o async` aangekoppeld is, is de werking hetzelfde. Alle bijwerkingen aan metagegevens worden eenvoudigweg doorgegeven aan de buffercache en vermengd met inhoudelijke updates van de bestandsgegevens. Het voordeel is een grote winst aan snelheid, omdat er niet telkens gewacht hoeft te worden op het bijwerken van metagegevens tot deze daadwerkelijk naar de schijf geschreven zijn. De implementatie is ook in dit geval helder en eenvoudig. Het grote nadeel is uiteraard dat er geen enkele garantie is voor de consistentie van het bestandssysteem. Als het systeem faalt tijdens een operatie waarbij veel metagegevens worden bijgewerkt (bijvoorbeeld door een stroomstoring of iemand drukt op de resetknop), blijft het bestandssysteem in een onvoorspelbare toestand achter. Er is geen mogelijkheid om de toestand van het bestandssysteem te onderzoeken als het systeem weer opstart, want de gegevensblokken van een bestand kunnen al weggeschreven zijn geweest terwijl het wegschrijven van bijwerkingen aan de inodetabel of de bijhorende map nog niet plaats heeft gevonden. Het is zelfs onmogelijk om een `fsck` te implementeren die de overgebleven chaos kan opruimen: de benodigde informatie is gewoon niet volledig aanwezig op de schijf. Als een bestandssysteem op deze manier onherstelbaar beschadigd is, is de enige optie man:newfs[8] te gebruiken en vervolgens te herstellen van een back-up. De gebruikelijke oplossing voor dit probleem is het implementeren van _dirty region logging_, ook wel _journaling_ genoemd, hoewel deze term niet consistent gebruikt wordt en soms ook wordt gebruikt voor andere vormen van transactielogging. Het bijwerken van metagegevens wordt nog steeds synchroon geschreven, maar slechts naar een klein gebied van de schijf. Later worden ze dan naar de juiste locatie verplaatst. Omdat het loggebied klein is, hoeven de koppen van de schijf zelfs tijdens schrijfintensieve operaties nog maar over een kleine fysieke afstand te bewegen en door deze snellere respons zijn dit soort operaties sneller dan op de traditionele manier. De extra complexiteit van de implementatie is nogal beperkt, dus het risico van introductie van extra bugs valt mee. Een nadeel is dat alle metagegevens tweemaal geschreven worden (eerst naar het loggebied en later nog eens naar de definitieve locatie). Dus bij normaal gebruik kan er sprake zijn van wat men wel noemt een "performance pessimization". Anderzijds kunnen in geval van een crash alle nog uitstaande metagegevensoperaties snel worden teruggedraaid of vanuit het loggebied alsnog worden afgemaakt wanneer de machine weer opstart. Het bestandssysteem start dan snel op. Kirk McKusick, de vader van het Berkeley FFS, loste dit probleem op met softupdates, wat betekent dat alle uitstaande acties voor het bijwerken van metagegevens in het geheugen bewaard worden en dan geordend naar de schijf geschreven worden. Dit heeft het gevolg dat in geval van intensieve operaties met betrekking tot metagegevens, latere bijwerkingen aan een item eerdere bewerkingen opvangen ("catch") als deze nog in het geheugen zitten en nog niet weggeschreven waren. Dus alle operaties, op bijvoorbeeld een map, worden in het algemeen eerst in het geheugen uitgevoerd voordat er wordt bijgewerkt naar schijf. De gegevensblokken worden geordend conform hun positie, zodat ze nooit weggeschreven worden voordat hun metagegevens geschreven zijn. Als het systeem een crash ondervindt, veroorzaakt dat impliciet het terugdraaien van uitstaande operaties ("log rewind"): alle operaties die nog niet weggeschreven waren lijken nooit gebeurd te zijn. Zo wordt een consistent bestandssysteem in stand gehouden dat eruit ziet alsof het 30 tot 60 seconden eerder was. Het gebruikte algoritme garandeert dat alle bronnen die in gebruik zijn als zodanig gemarkeerd worden in hun daarvoor geschikte bitmaps: blokken en inodes. Na een crash is de enige allocatiefout die kan optreden dat bronnen gemarkeerd kunnen zijn als in gebruik ("used"), terwijl ze feitelijk alweer beschikbaar ("free") zijn. man:fsck[8] herkent deze situatie en stelt dergelijke vrij te maken bronnen opnieuw beschikbaar. Het is volkomen veilig om na een crash te negeren dat het bestandssysteem niet schoon is en het tot aankoppelen te dwingen met `mount -f`. Om niet langer gebruikte bronnen vrij te maken moet later man:fsck[8] uitgevoerd worden. Dit is dan ook het idee achter _background fsck_: op het moment dat het systeem aan het opstarten is, wordt er alleen een _snapshot_ van het systeem bewaard. `fsck` kan later uitgevoerd worden. Alle bestandssystemen kunnen "dirty" aangekoppeld worden en het systeem kan gewoon verder opstarten naar meergebruikermodus. Vervolgens zijn er ``fsck``s gepland die in de achtergrond draaien voor elk bestandssysteem dat niet schoon is en waarmee bezette bronnen vrijgegeven worden. Bestandssystemen die geen gebruik maken van softupdates moeten echter nog steeds gebruik maken van de normale `fsck` in de voorgrond. Het voordeel van softupdates is dat operaties op metagegevens bijna net zo snel zijn als asynchrone updates (dat wil zeggen sneller dan met _logging_, waarbij de metagegevens keer op keer geschreven worden). Nadelen zijn de complexiteit van de code (wat een groter risico op bugs impliceert in een gebied dat bijzonder gevoelig is voor verlies van gebruikersgegevens) en een groter geheugenverbruik. Tevens moet de gebruiker wennen aan enkele eigenaardigheden. Na een crash lijkt de toestand van het bestandssysteem wat "ouder". In situaties waar de standaard synchrone benadering een aantal lege bestanden zou hebben achtergelaten na `fsck`, is het met softupdates juist zo dat dergelijke bestanden er helemaal niet zijn, omdat de metagegevens of de bestandsinhoud nooit naar de schijf zijn geschreven. Schijfruimte wordt pas vrijgegeven als de bijwerkingen aan metagegevens en inhoudelijke bestandsgegevens weggeschreven zijn, wat mogelijk pas enige tijd na het uitvoeren van `rm` plaatsvindt. Dit kan problemen veroorzaken als er grote hoeveelheden gegevens naar een bestandssysteem geschreven worden dat onvoldoende vrije ruimte heeft om alle bestanden twee keer te kunnen bevatten (bijvoorbeeld in [.filename]#/tmp#). [[configtuning-kernel-limits]] == Fijnafstemming van kernellimieten [[file-process-limits]] === Bestandsproceslimieten [[kern-maxfiles]] ==== `kern.maxfiles` `kern.maxfiles` kan worden verhoogd of verlaagd, afhankelijk van de systeembehoeften. Deze variabele geeft het maximale aantal bestandsdescriptors op een systeem. Als de bestandsdescriptortabel vol is, toont de systeembuffer meerdere malen `file: table is full`, hetgeen achteraf te zien is met `dmesg`. Elk geopend bestand, socket of fifo heeft een bestandsdescriptor. Een grote produktieserver kan makkelijk enige duizenden bestandsdescriptors nodig hebben, afhankelijk van het soort en aantal diensten die tegelijk draaien. In oudere versies van FreeBSD werd de standaard waarde van `kern.maxfiles` afgeleid van de optie `maxusers` in het kernelconfiguratiebestand. `kern.maxfiles` groeit evenredig met de waarde van `maxusers`. Als een aangepaste kernel wordt gebouwd, is het een goed idee om deze kerneloptie in te stellen afhankelijk van het gebruikt van een systeem (maar niet te laag). Hoewel een produktieserver misschien niet 256 gelijktijdige gebruikers heeft, kunnen de benodigde systeembronnen het beste vergeleken worden met een grootschalige webserver. De optie `maxusers` stelt de grootte van een aantal belangrijke systeemtabellen in. Dit aantal moet ruwweg gelijk zijn aan het aantal gebruikers dat verwacht wordt gelijktijdig van de machine gebruik te maken. Vanaf FreeBSD 4.5 wordt `kern.maxusers` automatisch ingesteld tijdens het opstarten gebaseerd op de hoeveelheid beschikbare geheugen in het systeem en kan worden vastgesteld tijdens het draaien door te kijken naar de alleen-lezen sysctl `kern.maxusers`. Sommige configuraties hebben grotere of kleinere waarden nodig van `kern.maxusers`, deze kunnen worden gezet als een opstartvariabele. Waardes van 64, 128 en 256 zijn daarin niet ongewoon. We raden aan om niet boven de 256 te gaan tenzij er heel veel bestandsdescriptors benodigd zijn; veel van de aanpasbaare waarden die standaard worden bepaald door `kern.maxusers` kunnen individueel worden overschreven tijdens het opstarten en/of tijdens het draaien van het systeem in [.filename]#/boot/loader.conf# (zie de handleiding man:loader.conf[5] of [.filename]#/boot/defaults/loader.conf# voor een paar aanwijzingen) of zoals elders beschreven in dit document. Voor oudere versies stelt het systeem deze waarde zelf in als deze uitdrukkelijk op `0` is gezet. Als het gewenst is om deze waarde zelf aan te geven, wordt aangeraden om `maxusers` minstens op 4 te zetten, met name als het X Window systeem in gebruik is of als er software gecompileerd wordt. De reden hiervoor is dat de belangrijkste tabel die door `maxusers` ingesteld wordt, het maximum aantal processen is, dat ingesteld wordt op `20 + 16 * maxusers`, dus als `maxusers` op 1 ingesteld wordt, zijn er maar 36 gelijktijdige processen mogelijk, inclusief de ongeveer achttien processen die door het systeem tijdens het opstarten start en de ongeveer vijftien processen die waarschijnlijk aangemaakt worden door het opstarten van het X Window systeem. Zelfs een eenvoudige taak als het afbeelden van een hulppagina start negen processen op om de pagina te filteren, te decomprimeren en af te beelden. Als `maxusers` op 64 ingesteld wordt, zijn er 1044 gelijktijdige processen mogelijk, wat genoeg moet zijn voor bijna alle soorten gebruik. Als echter de gevreesde fout verschijnt als er geprobeerd wordt om een programma op te starten of als er een server gedraaid wordt met een groot aantal gelijktijdige gebruikers, zoals `ftp.FreeBSD.org`, kan het getal altijd verhoogd worden en kan de kernel opnieuw gebouwd worden. [NOTE] ==== `maxusers` stelt _geen_ grens aan het aantal gebruikers dat zich op de machine kan aanmelden. Het stelt gewoon verschillende tabelgroottes in op redelijke waardes, uitgaande van het maximum aantal gebruikers dat waarschijnlijk de machine gebruikt en van het aantal processen dat elk van deze gebruikers zal draaien. Een sleutelwoord dat _wel_ het aantal gelijktijdige aanmeldingen op afstand en X-terminalvensters begrensd is crossref:kernelconfig[kernelconfig-ptys,`pseudo-device pty 16`]. In FreeBSD 5.X kan dit getal genegeerd worden omdat daar het stuurprogramma man:pty[4] "auto-cloning" is. Er kan eenvoudig gebruik worden gemaakt van de regel `device pty` in het instellingenbestand. ==== ==== `kern.ipc.somaxconn` De sysctl-variabele `kern.ipc.somaxconn` beparkt de grootte van de luisterwachtrij voor het accepteren van nieuwe TCP-verbindingen. De standaardwaarde van `128` is meestal te laag voor robuuste behandeling van nieuwe verbindingen in een zwaarbeladen webserveromgeving. Voor zulke omgevingen wordt aangeraden deze waarde te verhogen tot `1024` of hoger. De dienstdaemon beperkt misschien zelf de luisterwachtrij (bijvoorbeeld man:sendmail[8] of Apache), maar heeft vaak een mogelijkheid in een configuratiebestand de wachtrijgrootte aan te passen. Grote luisterwachtrijen zijn ook beter in het ontwijken van Ontzegging van Dienst () aanvallen. [[nmbclusters]] === Netwerkbeperkingen De kerneloptie `NMBCLUSTERS` bepaalt het aantal netwerk-Mbufs dat beschikbaar is voor een systeem. Een veel bezochte server met een laag aantal Mbufs beperkt de mogelijkheden van FreeBSD. Elk cluster staat voor ongeveer 2 K geheugen, dus een waarde van 1024 stelt 2 megabyte aan kernelgeheugen voor, dat is gereserveerd voor netwerkbuffers. Een simpele berekening geeft aan hoeveel er nodig is. Stel dat een webserver met een maximum van 1000 simultane verbindingen voor elke verbinding 16 K aan ontvangstnetwerkbuffers en 16 K aan zendbuffers kost, dan is ongeveer 32 MB aan netbuffers nodig voor de webserver. Een goede vuistregel is te vermeniguldigen met twee, dus 2x32 MB / 2 KB = 64 MB / 2 kB = 32768. Voor machines met veel geheugen wordt 4096 tot 32768 aangeraden. Er moet in geen geval een arbitrair hoge waarde voor deze sysctl opgegeven worden, want dat kan leiden tot een crash tijdens het opstarten. Met de optie `-m` van man:netstat[1] kan het clustergebruik van het netwerk bekeken worden. De loaderparameter `kern.ipc.nmbclusters` moet gebruikt worden om dit tijdens het opstarten toe te passen. Alleen voor oudere versies van FreeBSD is het nodig om de kerneloptie `NMBCLUSTERS` te gebruiken. Voor drukke servers die extensief gebruik maken van de systeemaanroep man:sendfile[2], kan het nodig zijn het aantal man:sendfile[2]-buffers te verhogen via de kerneloptie `NSFBUFS` of door de waarde in te stellen in [.filename]#/boot/loader.conf# (in man:loader[8] staan details). Als er in de procestabel processen staan met een status `sfbufa` is dat een algemene indicator dat deze parameter aangepast moet worden. De sysctl-variabele `kern.ipc.nsfbufs` is alleen-lezen en laat zien op welke waarde deze kernelvariabele is ingesteld. Deze parameter schaalt engiszins met de variabele `kern.maxusers`, maar het kan nodig zijn om deze bij te stellen. [IMPORTANT] ==== Zelfs als een socket als non-blocking gemarkeerd is, dan nog kan het aanroepen van man:sendfile[2] op de non-blocking socket ertoe leiden dat er toch blokkade optreedt totdat er voldoende ``struct sf_buf``'s vrijgemaakt zijn. ==== ==== `net.inet.ip.portrange.*` De sysctl-variabelen `net.inet.ip.portrange.*` bepalen welke reeks poortnummers automatisch gebonden wordt aan TCP- en UDP-sockets. Er zijn drie gebieden: een laag gebied, een (standaard) middengebied en een hoog gebied. De meeste netwerkprogramma's gebruiken het standaardbereik, wat begrensd wordt door `net.inet.ip.portrange.first` en `net.inet.ip.portrange.last` met standaardwaarden van respectievelijk 1024 en 5000. Gebonden poortreeksen worden gebruikt voor uitgaande verbindingen en het is onder bepaalde omstandigheden mogelijk dat poorten op raken. Dit gebeurt meestal in het geval van een zwaar belaste webproxy. Poortbereik is niet van belang als vooral diensten draaien die zich bezighouden met inkomende verbindingen, zoals een normale webserver, of als het aantal uitgaande verbindingen beperkt is, zoals bij een mailrelay. Voor situaties waarin een tekort aan poorten dreigt, wordt aangeraden om `net.inet.ip.portrange.last` bescheiden op te hogen. Een waarde van `10000`, `20000` of `30000` is redelijk. Er moet ook rekening met effecten op firewalls gehouden worden als de poortreeks gewijzigd wordt. Sommige firewalls kunnen grote poortreeksen blokkeren, meestal de lagere poorten, en verwachten dat andere systemen hogere poorten gebruiken voor uitgaande verbindingen. Om deze reden wordt het niet aanbevolen om `net.inet.ip.portrange.first` te verlagen. ==== TCP Bandbreedtevertragingsproduct (TCP Bandwidth Delay Product) De TCP-bandbreedtevertragingsproductlimitatie lijkt op TCP/Vegas in NetBSD. Het kan aangezet worden door de sysctl-variabele `net.inet.tcp.inflight.enable` de waarde `1` te geven. Het systeem tracht dan het bandbreedtevertragingssprodukt te berekenen voor elke verbinding en beperkt dan de hoeveelheid gegevens in de wachtrij naar het netwerk tot de hoeveelheid die vereist is om maximale doorvoer te kunnen handhaven. Dit is nuttig bij gebruik van modems, Gigabit Ethernet of zelfs bij WAN-verbindingen met hoge snelheid (of elke andere verbinding met een groot bandbreedtevertragingsprodukt), in het bijzonder als ook windowschaling of een groot verzendwindow gebruikt wordt. Als deze optie aangezet wordt, dient ook `net.inet.tcp.inflight.debug` de waarde `0` te krijgen (geen debugging) en voor produktiegebruik kan het instellen van `net.inet.tcp.inflight.min` naar minstens `6144` voordeel opleveren. Het instellen van hoge minima kan effectief het beperken van bandbreedte ondermijnen, afhankelijk van de verbinding. De mogelijkheid tot limitering zorgt ervoor dat de hoeveelheid gegevens die opgebouwd wordt, in tussentijdse route- en switchwachtrijen verlaagd kan worden en tevens kan de hoeveelheid gegevens die opgebouwd wordt in de interfacewachtrij van de lokale host verlaagd worden. Met minder pakketten in wachtrijen kunnen interactieve verbindingen opereren met lagere _Round Trip_ tijden, met name over langzame modems. Deze optie gaat alleen over datatransmissie (upload / serverkant) en heeft geen effect gegevensontvangst (download / cliëntkant). Aanpassen van `net.inet.tcp.inflight.stab` wordt _niet_ aangeraden. Deze parameter krijgt standaard een waarde van 20, wat 2 maximale pakketten opgeteld bij de bandbreedtevensterberekening representeert. Het extra venster is nodig om het algoritme stabiel te houden en om de reactietijd bij veranderende omstandigheden te verbeteren, maar het kan ook leiden tot langere pingtijden over langzame verbindingen (zonder het inflight-algoritme kan dit echter nog erger zijn). In dergelijke gevallen kan deze parameter misschien verlaagd worden naar 15, 10 of 5 en misschien moet voor het gewenste effect ook `net.inet.tcp.inflight.min` verlaagd worden (bijvoorbeeld naar 3500). Het verlagen van deze parameters moet pas in laatste instantie overwogen worden. === Virtueel Geheugen ==== `kern.maxvnodes` Een vnode is de interne representatie van een bestand of een map. Het verlagen van het aantal beschikbare vnodes voor het besturingssysteem leidt dus tot een daling van schijf-I/O. Normaliter wordt dit door het besturingssysteem afgehandeld en hoeft de instelling niet gewijzigd te worden. Im sommige gevallen kan schijf-I/O de beperkende factor zijn en kan het systeem alle beschikbare vnodes in gebruik hebben. Dan dient deze instelling gewijzigd te worden. De hoeveelheid inactief en beschikbaar RAM dient meegenomen te worden in de beslissing. Het huidige aantal gebruikte vnodes kan als volgt bekeken worden: [source,shell] .... # sysctl vfs.numvnodes vfs.numvnodes: 91349 .... Om het maximale aantal vnodes weer te geven: [source,shell] .... # sysctl kern.maxvnodes kern.maxvnodes: 100000 .... Als het huidige aantal gebruikte vnodes dicht bij het maximale aantal ligt, is het verstandig om `kern.maxvnodes` op te hogen met 1.000. Ook `vfs.numvnodes` dient in de gaten gehouden te worden. Als de waarde weer tot aan het maximum stijgt, dan moet `kern.maxvnodes` verder opgehoogd worden. Er dient een verschuiving op te treden in het door man:top[1] gerapporteerde geheugengebruik. Er hoort meer geheugen actief te zijn. [[adding-swap-space]] == Wisselbestandruimte toevoegen Hoe goed er ook gepland wordt, soms draait een systeem gewoon niet zoals verwacht. Een oorzaak hiervoor kan een tekort aan wisselbestandruimte zijn. Als blijkt dat er meer wisselbestandruimte nodig is, kan dat eenvoudig. Er zijn drie manieren om de totale ruimte beschikbaar als wisselbestand te vergroten: een nieuwe harde schijf toevoegen, swappen over NFS of een wisselbestand maken op een bestaande (UFS of andere) partitie. Kijk voor informatie over het beveiligen van het wisselbestand, welke opties hiervoor bestaan, en waarom dit gedaan zou moeten worden in crossref:disks[swap-encrypting,Het versleutelen van de wisselbestand ruimte] van het handboek. [[new-drive-swap]] === Swap op een nieuwe of bestaande harde schijf Een nieuwe harde schijf voor swap toevoegen geeft betere prestaties dan een partitie aan een bestaande schijf toevoegen. Het aanmaken van partities en harde schijven wordt uitgelegd in crossref:disks[disks-adding,Schijven toevoegen]. <> bespreekt de overwegingen van partitie-indelingen en de grootte van swap-partities. Gebruik man:swapon[8] om een swap-partitie aan het systeem toe te voegen, bijvoorbeeld: [source,shell] .... # swapon /dev/ada1s1b .... [WARNING] ==== Het is mogelijk om elke partitie te gebruiken die momenteel niet aangekoppeld is, zelfs als deze al gegevens bevat. Het gebruik van man:swapon[8] op een partitie die gegevens bevat zal deze gegevens overschrijven en vernietigen. Zorg ervoor dat de partitie die als swap toegevoegd wordt echt de bedoelde partitie is voordat man:swapon[8] gebruikt wordt. ==== Voeg een regel toe aan [.filename]#/etc/fstab# voor de partitie om deze swap-partitie automatisch toe te voegen tijdens het opstarten: [.programlisting] .... /dev/ada1s1b none swap sw 0 0 .... Raadpleeg man:fstab[5] voor een uitleg over de regels in [.filename]#/etc/fstab#. [[nfs-swap]] === Swappen over NFS In het algemeen wordt swappen over NFS niet aangeraden behalve als het onmogelijk is om naar een lokale schijf te swappen. NFS-swappen wordt gelimiteerd door de hoeveelheid beschikbare bandbreedte en belast het de NFS-server. [[create-swapfile]] === Wisselbestanden Het is mogelijk om een bestand aan te maken van een bepaalde grootte en dit als swap te gebruiken. In dit voorbeeld wordt een bestand van 64 MB gebruikt, [.filename]#/usr/swap0#. Uiteraard kan een willekeurige naam gebruikt worden. .Een wisselbestand aanmaken op FreeBSD [example] ==== . De kernel [.filename]#GENERIC# bevat reeds het stuurprogramma voor geheugenschijven (man:md[4]) dat nodig is voor deze bewerking. Zorg ervoor dat tijdens het bouwen van een eigen kernel de volgende regel in uw configuratiebestand zit: + [.programlisting] .... device md .... + Kijk voor meer informatie over het bouwen van een eigen kernel in crossref:kernelconfig[kernelconfig,De FreeBSD-kernel instellen]. . Het wisselbestand [.filename]#/usr/swap0# aanmaken: + [source,shell] .... # dd if=/dev/zero of=/usr/swap0 bs=1024k count=64 .... + . De correcte rechten op [.filename]#/usr/swap0# instellen: + [source,shell] .... # chmod 0600 /usr/swap0 .... + . Het wisselbestand opnemen in [.filename]#/etc/rc.conf#: + [.programlisting] .... swapfile="/usr/swap0" # Instellen op naam van wisselbestand als hulpwisselbestand gewenst is .... + . De machine moet herstart worden of om het wisselbestand direct in te schakelen: + [source,shell] .... # mdconfig -a -t vnode -f /usr/swap0 -u 0 swapon /dev/md0 .... ==== [[acpi-overview]] == Energie- en bronnenbeheer Het is belangrijk om hardwarebronnen op een efficiënte wijze te benutten. Voordat ACPI geïntroduceerd werd was het lastig en onflexibel om het energieverbruik en de thermische eigenschappen van een systeem te beheersen. De hardware werd beheerst de BIOS en dus had de gebruiker minder controle en zichtbaarheid in de energiebeheerinstellingen. Enige gelimiteerde configuratie was mogelijk via _Advanced Power Management (APM)_. Energie- en bronnenbeheer is een belangrijk onderdeel van moderne machines. Het besturingssysteem moet bijvoorbeeld systeemlimieten in de gaten houdt (en mogelijk een SMS sturen of iets dergelijks) als de systeemtemperatuur onverwacht toeneemt. In dit deel van het FreeBSD handboek wordt uitgebreide informatie verschaft over ACPI. Aan het einde worden referenties geleverd naar meer leesmateriaal. [[acpi-intro]] === Wat is ACPI? Advanced Configuration and Power Interface (ACPI) is een standaard die door een alliantie van producenten geschreven is, met als doel te voorzien in een standaardinterface voor hardwarebronnen- en energiebeheer. Een belangrijk element is dat het meer flexibiliteit en beheersmogelijkheden biedt aan het besturingssysteem (OS). Moderne systemen hebben de limieten van de huidige PNP-interfaces verder opgerekt dan wenselijk en misschien wel mogelijk was. ACPI is de directe opvolger van APM (Advanced Power Management). Centraal is het verleggen van hardwarebeheer en -monitoring naar de OS-laag in plaats van de zeer beperkte BIOS-laag. [[acpi-old-spec]] === Tekortkomingen van APM Met de _Advanced Power Management (APM)_ faciliteit kan het energieverbruik van een systeem geregeld worden op basis van de systeemactiviteit. Het APM-BIOS wordt geleverd door de systeemproducent of -verkoper en het is specifiek voor dat betreffende hardwareplatform. Een APM-stuurprogramma in het besturingssysteem regelt vervolgens de toegang tot de _APM Software Interface_, die het besturen van vermogensniveau mogelijk maakt. APM dient nog steeds gebruikt te worden met systemen die gefabriceerd zijn voor het jaar 2000. Er zijn vier hoofdproblemen met APM te onderscheiden: ten eerste wordt het energiebeheer verricht door een BIOS (afhankelijk van producent) en het besturingssysteem heeft daar geen kennis van. De gebruiker die idle-time waarden instelt voor een harde schijf in het APM-BIOS is hier een voorbeeld van. Dan zal het BIOS de harde schijf langzamer kunnen laten draaien zonder dat het besturingssysteem de noodzaak ziet of het goedkeurt. Ten tweede: de APM-logica is ingebed in de BIOS, waardoor het buiten het besturingssysteem om opereert. Dit houdt in dat gebruikers problemen met hun APM-BIOS alleen kunnen verhelpen door een nieuw BIOS in het ROM te flashen, wat een gevaarlijke en mogelijk onherstelbare operatie is. Ten derde is APM een producent-specifieke technologie, in de zin dat er altijd een hoge mate van duplicatie zal zijn van al dan niet geslaagde pogingen om het wiel opnieuw uit te vinden en uiteraard ook van bugs. Er is geen enkele garantie dat het wegnemen van een bug door een producent ook een zelfde bug wegneemt bij een concurrent. Tenslotte is het van belang te weten dat de APM-BIOS in het algemeen gewoon te weing geheugen kon gebruiken om een ingewikkeld energiebeheer te kunnen implementeren. Laat staan dat deze goed aanpasbaar was aan veranderlijke doelstellingen voor de betreffende machine. _Plug-n-play BIOS (PNPBIOS)_ was in veel situaties onbetrouwbaar. PNPBIOS is 16-bitstechnologie, dus het besturingssysteem moet 16-bit emulatie gebruiken om met PNPBIOS-methoden te kunnen samenwerken. Het FreeBSD-stuurprogramma APM is gedocumenteerd in man:apm[4]. [[acpi-config]] === ACPI instellen Het stuurprogramma [.filename]#acpi.ko# wordt standaard geladen bij het opstarten door de man:loader[8] en hoeft _niet_ gecompileerd te worden. De redenatie is dat er met modules gemakkelijker gewerkt kan worden, bijvoorbeeld een andere [.filename]#acpi.ko# gebruiken zonder dat er een nieuwe kernel gebouwd moet worden. Dit heeft het voordeel dat testen eenvoudiger is. Een andere reden is dat het opstarten van ACPI nadat een systeem eenmaal volledig opgestart is meestal niet goed werkt. Mocht er hinder ondervonden worden, dan kan ACPI beter uitgeschakeld worden. Dit stuurprogramma kan niet gestopt worden als het eenmaal geladen is, omdat de systeembus het gebruikt voor allerlei interacties met hardware. ACPI kan uitgezet worden door het instellen van `hint.acpi.0.disabled="1"` in [.filename]#/boot/loader.conf# of in de man:loader[8] prompt. [NOTE] ==== ACPI en APM kunnen niet samenleven en moeten afzonderlijk en exclusief gebruikt worden. De laatste die gestart wordt bepaalt of het stuurprogramma de ander wel of niet ziet. ==== In haar eenvoudigste vorm kan ACPI gebruikt worden om het systeem in slaapmodus te zetten met man:acpiconf[8] met de vlag `-s` en een optie `1-5`. De meeste gebruikers hebben alleen `1` of `3` nodig. De optie `5` verricht een "soft-off", wat hetzelfde is als: [source,shell] .... # halt -p .... Andere opties zijn mogelijk via man:sysctl[8]. Zie de handleidingen van man:acpi[4] en man:acpiconf[8] voor meer informatie. [[ACPI-debug]] == FreeBSD ACPI gebruiken en debuggen ACPI is een totaal nieuwe manier om apparaten te ontdekken, om energieverbruik te beheren en om een gestandaardiseerde toegang te bieden tot allerlei apparaten die eerder via het BIOS beheerd werden. Er wordt voortdurend vooruitgang geboekt om ACPI op alle systemen te laten werken, maar bugs in de _ACPIMachine Language_ (AML) bytecode van sommige moederborden, onvolledigheden in de subsystemen van de kernel van FreeBSD en bugs in de Intel(R) ACPI-CA interpreter blijven opduiken. Deze tekst is bedoeld om u te helpen met het bijstaan van de FreeBSD ACPI beheerders met het vinden van de hoofdoorzaken van problemen die u opmerkt en met het debuggen en het vinden van een oplossing. [[ACPI-submitdebug]] === Debuginformatie aanleveren [NOTE] ==== Voordat een probleem wordt gemeld, moet het zeker zijn dat de laatste BIOS versie draait en indien beschikbaar de geïntregeerde controller firmware versie. ==== Diegenen die meteen een probleem willen indienen, sturen de volgende informatie naar link:mailto:freebsd-acpi@FreeBSD.org[ freebsd-acpi@FreeBSD.org]: * Omschrijving van het foutieve gedrag, inclusief systeemtype en -model en alles wat de fout kan veroorzaken. Als het een nieuw fenomeen is, dan dient ook zo accuraat mogelijk aangegeven te worden wanneer de fout het eerst optrad. * De uitvoer van man:dmesg[8] van `boot -v`, inclusief foutmeldingen die gegenereerd worden als de fout optreedt. * De uitvoer van man:dmesg[8] van `boot -v` met ACPI uitgeschakeld, indien het uitzetten van ACPI het probleem oplost. * Uitvoer van `sysctl hw.acpi`. Dit is tevens een goede manier om uit te vinden welke ACPI-mogelijkheden een systeem heeft. * Een URL waar de _ACPISource Language_ (ASL) gevonden kan worden. De ASL dient _niet_ rechtstreeks naar de lijst gezonden te worden, omdat deze nogal groot kan zijn. Een kopie van een ASL kan gemaakt worden met het volgende commando: + [source,shell] .... # acpidump -dt > naam-systeem.asl .... + (Vervang uw aanmeldnaam door [.filename]#$NAME# en producent/model door [.filename]#$SYSTEM#. Bijvoorbeeld: [.filename]#njl-FooCo6000.asl#) De meeste FreeBSD-programmeurs lezen de {freebsd-current}, maar problemen gaan bij voorkeur ook naar {freebsd-acpi} zodat ze zeker gezien worden. Het kan enige tijd duren voordat er antwoord komt, omdat deze mensen elders ook nog volledige banen hebben. Als de bug niet meteen duidelijk is, komt er waarschijnlijk en verzoek om een PR in te dienen via man:send-pr[1]. Als er een PR moet worden opgesteld, dan dient alle hierboven gevraagde informatie vermeld te worden. Dit helpt om het probleem te kunnen volgen en oplossen. Het sturen van een PR zonder eerst {freebsd-acpi} te mailen is niet wenselijk, aangezien men PRs gebruikt als herinnering van bestaande problemen, niet als rapportagesysteem. Mogelijk is een probleem al eens door iemand anders gemeld. [[ACPI-background]] === Achtergrond ACPI is aanwezig op alle moderne computers die voldoen aan de ia32 (x86), ia64 (Itanium) of amd64 (AMD) architecturen. De volledige standaard heeft vele mogelijkheden zoals CPU-prestatiebeheer, energiebeheer, thermische zones, diverse batterijsystemen, ingebedde controllers en busnummering. De meeste systemen implementeren minder dan de volledige standaard. Een desktopsysteem implementeert bijvoorbeeld meestal alleen busnummering, terwijl laptops mogelijk ook koeling- en batterijbeheer ondersteunen. Laptops hebben ook suspend en resume (slapen en wakker worden) met hun eigen aanverwante comlexiteit. Een ACPI-compliant systeem heeft verscheidene componenten. Het BIOS- en chipsetverkopers bieden verscheidene vaste tabellen aan zoals FADT in het geheugen die zaken als de APIC-afbeelding (gebruikt voor SMP), configuratieregisters, en eenvoudige configuratiewaarden specificeren. Ook wordt er een tabel van bytecode (de _Differentiated System Description Table_ of DSDT) geleverd die een op een boomstructuur lijkende namespace biedt voor apparaten en methoden. Het stuurprogramma ACPI moet de voorgedefinieerde tabellen verwerken, een interpreter voor de bytecode implementeren en apparaatstuurprogramma's en de kernel aanpassen om informatie van het ACPI-subsysteem te accepteren. Intel(R) heeft een interpreter beschikbaar gesteld (ACPI-CA) die door FreeBSD en ook door Linux(R) en NetBSD gebruikt wordt. De ACPI-CA-broncode staat in [.filename]#src/sys/contrib/dev/acpica#. De lijmcode die ACPI-CA laat werken met FreeBSD staat in [.filename]#src/sys/dev/acpica/Osd#. Stuurprogramma's die verscheidene ACPI-apparaten implementeren staan in [.filename]#src/sys/dev/acpica#. [[ACPI-comprob]] === Algemene problemen Wil ACPI goed werken, dan moeten alle onderdelen goed werken. Hieronder staan enkele algemene problemen in volgorde van hoe vaak ze optreden en enkele mogelijke oplossingen of manieren om de problemen te vermijden. ==== Muisproblemen Soms doet een muis het niet bij het opstarten uit de slaapstand. Een bekend lapmiddel is het toevoegen van `hint.psm.0.flags="0x3000"` aan [.filename]#/boot/loader.conf#. Als dat niet werkt, dan wordt aangeraden een bugrapport in te sturen, zoals eerder is beschreven. ==== Suspend/resume ACPI heeft drie slaapstanden waarbij het geheugen (RAM) wordt ingezet. Dit zijn de STR-toestanden `S1`-`S3`, en nog een slaap-met-gebruik-van-harde-schijf toestand (`STD`) die `S4` heet. `S5` is "zacht uit" en is de normale status van een systeem als het is aangesloten maar niet is aangezet. `S4` kan feitelijk op twee manieren geïmplementeerd worden: ``S4``BIOS is een slaapstand naar schijf met behulp van het BIOS en ``S4``OS wordt volledig door het besturingssysteem geïmplenteerd. als eerste dienen de `sysctl hw.acpi` items die iets met de slaapstand te maken hebben gecontroleerd te worden. Hieronder staan de resultaten voor een Thinkpad: [source,shell] .... hw.acpi.supported_sleep_state: S3 S4 S5 hw.acpi.s4bios: 0 .... Dit betekent dat hier `acpiconf -s` gebruikt kan worden om `S3`, ``S4``OS en `S5` te testen. Als `s4bios` gelijk was aan (`1`), dan zou er ``S4``BIOS ondersteuning zijn in plaats van ``S4``OS. Als suspend/resume getest moet worden, dient, indien ondersteund, bij `S1` begonnen te worden. Deze toestand heeft de grootste kans om te werken, omdat deze niet veel stuurprogrammaondersteuning vereist. Niemand heeft nog `S2` geïmplementeerd, maar het is ongeveer hetzelfde als `S1`. Daarna wordt `S3` getest. Dit is het diepste STR-niveau en heeft uitgebreide ondersteuning van stuurprogramma's nodig om hardware goed opnieuw te kunnen starten. Mochten er blokkades optreden, dan kan naar de {freebsd-acpi} lijst gemaild worden. Er kan echter geen snelle oplossing verwacht worden, omdat er nog de nodige stuurprogramma's/hardware liggen om getest en bewerkt te worden. Een veelvoorkomend probleem met suspend/resume is dat veel apparaatstuurprogramma's hun firmware, registers of apparaatgeheugen niet fatsoenlijk opslaan, herstellen, of herinitialiseren. Een eerste poging om het probleem te vinden omvat: [source,shell] .... # sysctl debug.bootverbose=1 # sysctl debug.acpi.suspend_bounce=1 # acpiconf -s 3 .... Deze test emuleert de suspend/resume-cyclus van alle apparaten zonder daadwerkelijk naar de toestand `S3` te gaan. In sommige gevallen kunt u zo eenvoudig problemen vaststellen (bijvoorbeeld het verliezen van de firmware-toestand, timeout van de apparaatwaakhond, en steeds opnieuw iets proberen). Merk op dat het systeem niet werkelijk naar de toestand `S3` gaat, wat inhoudt dat apparaten geen spanning verliezen waardoor velen prima zullen werken zelfs als de suspend/resume-methoden geheel ontbreken, dit in tegenstelling tot de echte toestand `S3`. Moeilijkere gevallen vereisen aanvullende hardware, dat is een serieële poort/kabel voor de serieële console of een Firewire poort/kabel voor man:dcons[4], en vaardigheden in het debuggen van de kernel. Om een probleem te kunnen isoleren helpt het om zoveel mogelijk stuurprogramma's uit de kernel te halen. Als dit werkt, kan er teruggewerkt worden naar het stuurprogramma dat schuldig is aan het falen. Meestal vertonen binaire stuurprogramma's als [.filename]#nvidia.ko#, X11 beeldschermstuurprogramma's en USB de meeste problemen, terwijl bijvoorbeeld Ethernet-interfaces meestal meteen goed werken. Als de stuurprogramma's zonder problemen geladen en verwijderd kunnen worden, dan is dit te automatiseren door de juiste commando's in [.filename]#/etc/rc.suspend# en [.filename]#/etc/rc.resume# te zetten. Er staat een voorbeeld (achter commentaartekens) voor het laden en verwijderen van een stuurprogramma. Als het beeldscherm er na wakker worden vreemd uitziet, kan geprobeerd worden `hw.acpi.reset_video` op nul te zetten. Met langere of kortere waarden voor `hw.acpi.sleep_delay` kan bekeken worden of dat helpt. In geval van problemen is het ook een optie om een recente Linux(R) distibutie met ondersteuning voor ACPI support te starten en daarvan de suspend/resume ondersteuning op dezelfde hardware uit te proberen. Als het werkt met Linux(R), dan is het waarschijnlijk een FreeBSD stuurprogrammaprobleem en als het mogelijk is uit te vinden over welk stuurprogramma het gaat, kan dat bijdragen aan het oplossen van het probleem. ACPI houdt zich in het algemeen niet bezig met andere stuurprogramma's zoals geluid, ATA, enzovoort. Als er dus een echt probleem met een stuurprogramma is, dan is waarchijnlijk uiteindelijk ook nodig naar de {freebsd-current} lijst te posten en naar de beheerder van het stuurprogramma. Voor degenen met moed is het vooral aan te raden een paar man:printf[3]s in problematische stukken van een stuurprogramma te plaatsen voor debugging om na te gaan waar de resumefunctie precies hangt. Tot slot kan geprobeerd worden om ACPI uit te zetten en in plaats daarvan APM aan te zetten. Als suspend/resume werkt met APM, is het wellicht verstandig het daarbij te houden, vooral met wat oudere apparatuur (voor 2000). Producenten hebben nogal wat tijd nodig gehad om ACPI ondersteuning goed te krijgen en voor oudere hardware is het waarschijnlijker dat er BIOS-problemen zijn met ACPI. ==== Systeem hangt (tijdelijk of permanent) Meestal is het hangen van het systeem het gevolg van verloren interrupts of een interruptstorm. Chipsets kunnen een heleboel problemen hebben, afhankelijk van hoe het BIOS interrupts instelt voor het opstarten, of de APIC (MADT) tabel correct is en de routering van het _System Control Interrupt_ (SCI). Interruptstorms kunnen onderscheiden worden van verloren geraakte interrupts door de uitvoer van `vmstat -i` te controleren en de regel met `acpi0` goed te lezen. Als de teller in toenemende mate hoger staat dan enkele per seconde, dan is sprake van een interruptstorm. Als het systeem lijkt te hangen, is het wellicht nog mogelijk door te dringen tot de DDB (kbd:[CTRL+ALT+ESC]) en `show interrupts` uit te voeren. De beste hoop in geval van interruptproblemen is om APIC-ondersteuning uit te zetten met `hint.apic.0.disabled="1"` in [.filename]#loader.conf#. ==== Panics Panics zijn relatief zeldzaam met ACPI en krijgen de hoogste prioriteit bij het oplossen. Eerst moeten de verschillende gebeurtenissen waarmee de panic (als mogelijk) te reproduceren is geïsoleerd worden en moet een backtrace gemaakt worden. `options DDB` dient aangezet te worden en er dient een seriële console (crossref:serialcomms[serialconsole-ddb,De debugger DDB gebruiken via de seriële verbinding]) of een man:dump[8] partitie te komen. In DDB is een backtrace te maken met `tr`. Als de backtrace handmatig opgeschreven moet worden, is het belangrijk dat in ieder geval de bovenste en onderste vijf (5) regels van de backtrace genoteerd worden. Daarna dient getracht te worden het systeem te starten zonder ACPI. Als dat werkt, is het ACPI-subsysteem geïsoleerd en kunnen de verschillende `debug.acpi.disable`-waarden uitgeprobeerd worden. In man:acpi[4] staan enkele voorbeelden. ==== Systeem slaat aan na slaapstand of stop `hw.acpi.disable_on_poweroff="0"` kan uitgezet worden in man:loader.conf[5]. Hierdoor schakelt ACPI bepaalde gebeurtenissen tijdens het afsluitproces niet uit. Om dezelfde redenen moeten sommige systemen deze waarde altijd op `1` (standaard) hebben staan. In het algemeen lost dit een probleem op waarbij een systeem spontaan weer opkomt nadat het in slaapstand is gezet of geheel gestopt is. ==== Overige problemen Als er nog andere problemen zijn met ACPI (met een docking station of apparaten niet gedetecteerd, enzovoort), dan kan een mail met beschijving naar de mailinglijst gezonden worden. Sommige zaken kunnen echter gerelateerd zijn aan delen van het ACPI-subsysteem die nog niet af zijn, dus het kan in sommige gevallen een tijd duren. Gebruikers moeten soms geduld en de bereidheid om eventuele patches uit te proberen hebben. [[ACPI-aslanddump]] === ASL, `acpidump` en IASL Het grootste probleem is dat BIOS-producenten vaak incorrecte (of gewoon foutieve) bytecode leveren. Dit blijkt doorgaans uit kernelboodschappen als: [source,shell] .... ACPI-1287: *** Error: Method execution failed [\\_SB_.PCI0.LPC0.FIGD._STA] \\ (Node 0xc3f6d160), AE_NOT_FOUND .... Vaak kunnen dergelijke problemen geoplost worden door de BIOS bij te werken tot de laatste revisie. De meeste consoleberichten zijn onschuldig, maar als er andere problemen zijn, zoals batterijstatus die niet werkt, dan ligt het voor de hand te zoeken naar problemen in de AML-code. De bytecode die AML genoemd wordt, wordt gecompileerd van een broncodetaal ASL. Deze staat weer in een tabel DSDT. Met man:acpidump[8] kan een kopie van de ASL gemaakt worden. Dan moeten zowel de opties `-t` (laat inhoud van vaste tabellen zien) als `-d` (disassembleer AML naar ASL) gebruikt worden. In <> staat een voorbeeld. De eenvoudigste eerste controle is de ASL-code opnieuw compileren en kijken of er foutmeldingen optreden. Waarschuwingen kunnen doorgaans genegeerd worden, maar fouten zijn bugs die er meestal toe leiden dat ACPI niet correct werkt. Om ASL te hercompileren: [source,shell] .... # iasl eigen.asl .... [[ACPI-fixasl]] === ASL repareren Op langere termijn is het de bedoeling dat voor vrijwel elke machine ACPI werkt zonder enig ingrijpen van de gebruiker. Op dit moment wordt er echter nog gewerkt aan oplossingen voor veel voorkomende vergissingen die BIOS-producenten maken. De Microsoft(R) interpreter ([.filename]#acpi.sys# en [.filename]#acpiec.sys#) controleert niet strikt of het BIOS volledig aan de standaard voldoet, waardoor het voorkomt dat BIOS-makers die alleen testen onder Windows(R) bepaalde fouten in hun ASL nooit correct repareren. FreeBSD hoopt door te gaan met de identificatie en documentatie van welk niet-standaard gedrag precies wordt toegelaten door Microsoft(R)'s interpreter en te dit te repliceren zodat FreeBSD kan werken zonder dat gebruikers zich gedwongen zien om de ASL te repareren. Als een tijdelijke oplossing en om te helpen met het in kaart brengen van bepaald gedrag, kan de ASL handmatig gerepareerd worden. Mocht dit lukken, dan wordt erop aangedrongen een man:diff[1] van de oude en de nieuwe ASL te mailen, zodat het foutieve gedrag mogelijk in ACPI-CA kan worden verwerkt, waardoor andere gebruikers niet meer handmatig met hun ASL aan de gang hoeven. Hieronder staat een lijst algemene foutmeldingen, hun oorzaken en hoe ze op te lossen: ==== _OS afhankelijkheden Sommige AMLs gaan ervan uit dat de wereld enkel bestaat uit Windows(R) versies. FreeBSD kan zich voordoen als elk OS om te kijken of dit problemen oplost. Een gemakkelijke manier om dit te doen is `hw.acpi.osname="Windows 2001"` in te stellen in [.filename]#/boot/loader.conf# of andere gelijksoortige strings die in een ASL staan. ==== Ontbrekende return-opdrachten Sommige methoden hebben geen specifieke returnwaarde, zoals wel vereist wordt door de standaard. Hoewel ACPI-CA hier niets mee doet, heeft FreeBSD de mogelijkheid tot impliciete returns. Er kunnen ook expliciete return-opdrachten toegevoegd worden waar vereist, als het bekend is welke waarden teruggevoerd moeten worden. Om `iasl` te dwingen tot compilatie van ASL kan de schakeloptie `-f` gebruikt worden. ==== De standaard AML aanpassen Nadat [.filename]#eigen.asl# aangepast is, kan deze als volgt gecompileerd worden: [source,shell] .... # iasl eigen.asl .... Met de optie `-f` is af te dwingen dat de AML gemaakt wordt, zelfs als er compileerfouten optreden. Sommige fouten (zoals ontbrekende return-opdrachten) worden automatisch opgelost door de interpreter. [.filename]#DSDT.aml# is de standaardnaam voor het bestand dat door `iasl` wordt geproduceerd. Dit is in plaats van de foutieve versie uit het BIOS (die nog steeds aanwezig is in het flashgeneugen) te laden door [.filename]#/boot/loader.conf# als volgt te wijzigen: [.programlisting] .... acpi_dsdt_load="YES" acpi_dsdt_name="/boot/DSDT.aml" .... [.filename]#DSDT.aml# moet in de map [.filename]#/boot# staan. [[ACPI-debugoutput]] === Debuguitvoer van ACPI verkrijgen Het stuurprogramma ACPI heeft een zeer flexibele debugfaciliteit. Er kan zowel een verzameling van subsystemen aangegeven worden als het niveau van uitvoerigheid. De te debuggen subsystemen worden aangegeven als lagen ("layers") en zijn opgedeeld in ACPI-CA-componenten (ACPI_ALL_COMPONENTS) en ACPI-hardware-ondersteuning (ACPI_ALL_DRIVERS). De uitvoerigheid van debuguitvoer wordt aangegeven als het niveau ("level") en gaat van CPI_LV_ERROR (alleen fouten rapporteren) tot ACPI_LV_VERBOSE (alles). Het niveau is een bitmasker en dus kunnen er meerdere opties tegelijk ingeschakeld worden (gescheiden door spaties). In de praktijk wordt wellicht een seriële console gebruikt om de uitvoer te loggen als deze zo omvangrijk is dat de console berichtbuffer vol loopt (misschien wel meerdere keren). Een complete lijst van de individuele lagen en niveaus staat in man:acpi[4]. Debuguitvoer staat standaard niet aan. Door `options ACPI_DEBUG` toe te voegen aan het bestand met kernelinstellingen als ACPI als de kernel is gebouwd, wordt het ingeschakeld. Door `ACPI_DEBUG=1` toe te voegen aan [.filename]#/etc/make.conf# wordt het systeembreed ingeschakeld. Als ACPI als module wordt gebruikt (de normale situatie), dan hoeft slechts de module [.filename]#acpi.ko# opnieuw gecompileerd te worden: [source,shell] .... # cd /sys/modules/acpi/acpi make clean make ACPI_DEBUG=1 .... [.filename]#acpi.ko# moet in [.filename]#/boot/kernel# komen te staan en de gewenste debuglaag en het gewenste niveau van uitvoerigheid dienen toegevoegd te worden aan [.filename]#loader.conf#. Hieronder een voorbeeld waarmee debuguitvoer wordt aangezet voor alle ACPI-CA-componenten en alle ACPI-hardware-stuurprogramma's (CPU, LID, enzovoort. Het niveau van uitvoerigheid is het laagst mogelijke. Er worden alleen fouten gemeld. [.programlisting] .... debug.acpi.layer="ACPI_ALL_COMPONENTS ACPI_ALL_DRIVERS" debug.acpi.level="ACPI_LV_ERROR" .... Als de gezochte informatie wordt veroorzaakt door een specifieke gebeurtenis (bijvoorbeeld in en uit slaapstand gaan), dan kunnen wijzigingen aan [.filename]#loader.conf# achterwege blijven en in plaats daarvan kan `sysctl` gebruikt worden om laag en niveau in te stellen na het opstarten en zo het systeem voor te bereiden op die specifieke gebeurtenis. De ``sysctl``s hebben dezelfde namen als de parameters in [.filename]#loader.conf#. [[ACPI-References]] === Verwijzingen Meer informatie over ACPI staat op de volgende locaties: * De {freebsd-acpi} * De ACPI mailinglijst archieven http://lists.freebsd.org/pipermail/freebsd-acpi/[http://lists.freebsd.org/pipermail/freebsd-acpi/] * De oude ACPI mailinglijst archieven http://home.jp.FreeBSD.org/mail-list/acpi-jp/[http://home.jp.FreeBSD.org/mail-list/acpi-jp/] -* De ACPI 2.0 specificatie http://acpi.info/spec.htm[http://acpi.info/spec.htm] +* De https://uefi.org/specifications#ACPI[ACPI specificatie] * FreeBSD Handleidingen: man:acpi[4], man:acpi_thermal[4], man:acpidump[8], man:iasl[8], man:acpidb[8] * http://www.cpqlinux.com/acpi-howto.html#fix_broken_dsdt[ DSDT debugging informatie]. (Gebruikt Compaq als voorbeeld, maar van algemeen nut). diff --git a/documentation/content/pl/books/handbook/config/_index.adoc b/documentation/content/pl/books/handbook/config/_index.adoc index 2f7704ba36..d127bf7412 100644 --- a/documentation/content/pl/books/handbook/config/_index.adoc +++ b/documentation/content/pl/books/handbook/config/_index.adoc @@ -1,1525 +1,1525 @@ --- title: Rozdział 11. Configuration and Tuning part: Część III. Administracja systemem prev: books/handbook/partiii next: books/handbook/boot showBookMenu: true weight: 15 path: "/books/handbook/" --- [[config-tuning]] = Configuration and Tuning :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 11 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/config/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[config-synopsis]] == Synopsis One of the important aspects of FreeBSD is proper system configuration. This chapter explains much of the FreeBSD configuration process, including some of the parameters which can be set to tune a FreeBSD system. After reading this chapter, you will know: * The basics of [.filename]#rc.conf# configuration and [.filename]#/usr/local/etc/rc.d# startup scripts. * How to configure and test a network card. * How to configure virtual hosts on network devices. * How to use the various configuration files in [.filename]#/etc#. * How to tune FreeBSD using man:sysctl[8] variables. * How to tune disk performance and modify kernel limitations. Before reading this chapter, you should: * Understand UNIX(R) and FreeBSD basics (crossref:basics[basics,FreeBSD Basics]). * Be familiar with the basics of kernel configuration and compilation (crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]). [[configtuning-starting-services]] == Starting Services Many users install third party software on FreeBSD from the Ports Collection and require the installed services to be started upon system initialization. Services, such as package:mail/postfix[] or package:www/apache22[] are just two of the many software packages which may be started during system initialization. This section explains the procedures available for starting third party software. In FreeBSD, most included services, such as man:cron[8], are started through the system startup scripts. === Extended Application Configuration Now that FreeBSD includes [.filename]#rc.d#, configuration of application startup is easier and provides more features. Using the key words discussed in <>, applications can be set to start after certain other services and extra flags can be passed through [.filename]#/etc/rc.conf# in place of hard coded flags in the startup script. A basic script may look similar to the following: [.programlisting] .... #!/bin/sh # # PROVIDE: utility # REQUIRE: DAEMON # KEYWORD: shutdown . /etc/rc.subr name=utility rcvar=utility_enable command="/usr/local/sbin/utility" load_rc_config $name # # DO NOT CHANGE THESE DEFAULT VALUES HERE # SET THEM IN THE /etc/rc.conf FILE # utility_enable=${utility_enable-"NO"} pidfile=${utility_pidfile-"/var/run/utility.pid"} run_rc_command "$1" .... This script will ensure that the provided `utility` will be started after the `DAEMON` pseudo-service. It also provides a method for setting and tracking the process ID (PID). This application could then have the following line placed in [.filename]#/etc/rc.conf#: [.programlisting] .... utility_enable="YES" .... This method allows for easier manipulation of command line arguments, inclusion of the default functions provided in [.filename]#/etc/rc.subr#, compatibility with man:rcorder[8], and provides for easier configuration via [.filename]#rc.conf#. === Using Services to Start Services Other services can be started using man:inetd[8]. Working with man:inetd[8] and its configuration is described in depth in crossref:network-servers[network-inetd,“The inetd Super-Server”]. In some cases, it may make more sense to use man:cron[8] to start system services. This approach has a number of advantages as man:cron[8] runs these processes as the owner of the man:crontab[5]. This allows regular users to start and maintain their own applications. The `@reboot` feature of man:cron[8], may be used in place of the time specification. This causes the job to run when man:cron[8] is started, normally during system initialization. [[configtuning-cron]] == Configuring man:cron[8] One of the most useful utilities in FreeBSD is cron. This utility runs in the background and regularly checks [.filename]#/etc/crontab# for tasks to execute and searches [.filename]#/var/cron/tabs# for custom crontab files. These files are used to schedule tasks which cron runs at the specified times. Each entry in a crontab defines a task to run and is known as a _cron job_. Two different types of configuration files are used: the system crontab, which should not be modified, and user crontabs, which can be created and edited as needed. The format used by these files is documented in man:crontab[5]. The format of the system crontab, [.filename]#/etc/crontab# includes a `who` column which does not exist in user crontabs. In the system crontab, cron runs the command as the user specified in this column. In a user crontab, all commands run as the user who created the crontab. User crontabs allow individual users to schedule their own tasks. The `root` user can also have a user [.filename]#crontab# which can be used to schedule tasks that do not exist in the system [.filename]#crontab#. Here is a sample entry from the system crontab, [.filename]#/etc/crontab#: [.programlisting] .... # /etc/crontab - root's crontab for FreeBSD # # $FreeBSD$ # <.> SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin <.> # #minute hour mday month wday who command <.> # */5 * * * * root /usr/libexec/atrun <.> .... <.> Lines that begin with the `#` character are comments. A comment can be placed in the file as a reminder of what and why a desired action is performed. Comments cannot be on the same line as a command or else they will be interpreted as part of the command; they must be on a new line. Blank lines are ignored. <.> The equals (`=`) character is used to define any environment settings. In this example, it is used to define the `SHELL` and `PATH`. If the `SHELL` is omitted, cron will use the default Bourne shell. If the `PATH` is omitted, the full path must be given to the command or script to run. <.> This line defines the seven fields used in a system crontab: `minute`, `hour`, `mday`, `month`, `wday`, `who`, and `command`. The `minute` field is the time in minutes when the specified command will be run, the `hour` is the hour when the specified command will be run, the `mday` is the day of the month, `month` is the month, and `wday` is the day of the week. These fields must be numeric values, representing the twenty-four hour clock, or a `*`, representing all values for that field. The `who` field only exists in the system crontab and specifies which user the command should be run as. The last field is the command to be executed. <.> This entry defines the values for this cron job. The `\*/5`, followed by several more `*` characters, specifies that `/usr/libexec/atrun` is invoked by `root` every five minutes of every hour, of every day and day of the week, of every month.Commands can include any number of switches. However, commands which extend to multiple lines need to be broken with the backslash "\" continuation character. [[configtuning-installcrontab]] === Creating a User Crontab To create a user crontab, invoke `crontab` in editor mode: [source,shell] .... % crontab -e .... This will open the user's crontab using the default text editor. The first time a user runs this command, it will open an empty file. Once a user creates a crontab, this command will open that file for editing. It is useful to add these lines to the top of the crontab file in order to set the environment variables and to remember the meanings of the fields in the crontab: [.programlisting] .... SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin # Order of crontab fields # minute hour mday month wday command .... Then add a line for each command or script to run, specifying the time to run the command. This example runs the specified custom Bourne shell script every day at two in the afternoon. Since the path to the script is not specified in `PATH`, the full path to the script is given: [.programlisting] .... 0 14 * * * /usr/home/dru/bin/mycustomscript.sh .... [TIP] ==== Before using a custom script, make sure it is executable and test it with the limited set of environment variables set by cron. To replicate the environment that would be used to run the above cron entry, use: [.programlisting] .... env -i SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin HOME=/home/dru LOGNAME=dru /usr/home/dru/bin/mycustomscript.sh .... The environment set by cron is discussed in man:crontab[5]. Checking that scripts operate correctly in a cron environment is especially important if they include any commands that delete files using wildcards. ==== When finished editing the crontab, save the file. It will automatically be installed and cron will read the crontab and run its cron jobs at their specified times. To list the cron jobs in a crontab, use this command: [source,shell] .... % crontab -l 0 14 * * * /usr/home/dru/bin/mycustomscript.sh .... To remove all of the cron jobs in a user crontab: [source,shell] .... % crontab -r remove crontab for dru? y .... [[configtuning-rcd]] == Managing Services in FreeBSD FreeBSD uses the man:rc[8] system of startup scripts during system initialization and for managing services. The scripts listed in [.filename]#/etc/rc.d# provide basic services which can be controlled with the `start`, `stop`, and `restart` options to man:service[8]. For instance, man:sshd[8] can be restarted with the following command: [source,shell] .... # service sshd restart .... This procedure can be used to start services on a running system. Services will be started automatically at boot time as specified in man:rc.conf[5]. For example, to enable man:natd[8] at system startup, add the following line to [.filename]#/etc/rc.conf#: [.programlisting] .... natd_enable="YES" .... If a `natd_enable="NO"` line is already present, change the `NO` to `YES`. The man:rc[8] scripts will automatically load any dependent services during the next boot, as described below. Since the man:rc[8] system is primarily intended to start and stop services at system startup and shutdown time, the `start`, `stop` and `restart` options will only perform their action if the appropriate [.filename]#/etc/rc.conf# variable is set. For instance, `sshd restart` will only work if `sshd_enable` is set to `YES` in [.filename]#/etc/rc.conf#. To `start`, `stop` or `restart` a service regardless of the settings in [.filename]#/etc/rc.conf#, these commands should be prefixed with "one". For instance, to restart man:sshd[8] regardless of the current [.filename]#/etc/rc.conf# setting, execute the following command: [source,shell] .... # service sshd onerestart .... To check if a service is enabled in [.filename]#/etc/rc.conf#, run the appropriate man:rc[8] script with `rcvar`. This example checks to see if man:sshd[8] is enabled in [.filename]#/etc/rc.conf#: [source,shell] .... # service sshd rcvar # sshd # sshd_enable="YES" # (default: "") .... [NOTE] ==== The `# sshd` line is output from the above command, not a `root` console. ==== To determine whether or not a service is running, use `status`. For instance, to verify that man:sshd[8] is running: [source,shell] .... # service sshd status sshd is running as pid 433. .... In some cases, it is also possible to `reload` a service. This attempts to send a signal to an individual service, forcing the service to reload its configuration files. In most cases, this means sending the service a `SIGHUP` signal. Support for this feature is not included for every service. The man:rc[8] system is used for network services and it also contributes to most of the system initialization. For instance, when the [.filename]#/etc/rc.d/bgfsck# script is executed, it prints out the following message: [source,shell] .... Starting background file system checks in 60 seconds. .... This script is used for background file system checks, which occur only during system initialization. Many system services depend on other services to function properly. For example, man:yp[8] and other RPC-based services may fail to start until after the man:rpcbind[8] service has started. To resolve this issue, information about dependencies and other meta-data is included in the comments at the top of each startup script. The man:rcorder[8] program is used to parse these comments during system initialization to determine the order in which system services should be invoked to satisfy the dependencies. The following key word must be included in all startup scripts as it is required by man:rc.subr[8] to "enable" the startup script: * `PROVIDE`: Specifies the services this file provides. The following key words may be included at the top of each startup script. They are not strictly necessary, but are useful as hints to man:rcorder[8]: * `REQUIRE`: Lists services which are required for this service. The script containing this key word will run _after_ the specified services. * `BEFORE`: Lists services which depend on this service. The script containing this key word will run _before_ the specified services. By carefully setting these keywords for each startup script, an administrator has a fine-grained level of control of the startup order of the scripts, without the need for "runlevels" used by some UNIX(R) operating systems. Additional information can be found in man:rc[8] and man:rc.subr[8]. Refer to extref:{rc-scripting}[this article] for instructions on how to create custom man:rc[8] scripts. [[configtuning-core-configuration]] === Managing System-Specific Configuration The principal location for system configuration information is [.filename]#/etc/rc.conf#. This file contains a wide range of configuration information and it is read at system startup to configure the system. It provides the configuration information for the [.filename]#rc*# files. The entries in [.filename]#/etc/rc.conf# override the default settings in [.filename]#/etc/defaults/rc.conf#. The file containing the default settings should not be edited. Instead, all system-specific changes should be made to [.filename]#/etc/rc.conf#. A number of strategies may be applied in clustered applications to separate site-wide configuration from system-specific configuration in order to reduce administration overhead. The recommended approach is to place system-specific configuration into [.filename]#/etc/rc.conf.local#. For example, these entries in [.filename]#/etc/rc.conf# apply to all systems: [.programlisting] .... sshd_enable="YES" keyrate="fast" defaultrouter="10.1.1.254" .... Whereas these entries in [.filename]#/etc/rc.conf.local# apply to this system only: [.programlisting] .... hostname="node1.example.org" ifconfig_fxp0="inet 10.1.1.1/8" .... Distribute [.filename]#/etc/rc.conf# to every system using an application such as rsync or puppet, while [.filename]#/etc/rc.conf.local# remains unique. Upgrading the system will not overwrite [.filename]#/etc/rc.conf#, so system configuration information will not be lost. [TIP] ==== Both [.filename]#/etc/rc.conf# and [.filename]#/etc/rc.conf.local# are parsed by man:sh[1]. This allows system operators to create complex configuration scenarios. Refer to man:rc.conf[5] for further information on this topic. ==== [[config-network-setup]] == Setting Up Network Interface Cards Adding and configuring a network interface card (NIC) is a common task for any FreeBSD administrator. === Locating the Correct Driver First, determine the model of the NIC and the chip it uses. FreeBSD supports a wide variety of NICs. Check the Hardware Compatibility List for the FreeBSD release to see if the NIC is supported. If the NIC is supported, determine the name of the FreeBSD driver for the NIC. Refer to [.filename]#/usr/src/sys/conf/NOTES# and [.filename]#/usr/src/sys/arch/conf/NOTES# for the list of NIC drivers with some information about the supported chipsets. When in doubt, read the manual page of the driver as it will provide more information about the supported hardware and any known limitations of the driver. The drivers for common NICs are already present in the [.filename]#GENERIC# kernel, meaning the NIC should be probed during boot. The system's boot messages can be viewed by typing `more /var/run/dmesg.boot` and using the spacebar to scroll through the text. In this example, two Ethernet NICs using the man:dc[4] driver are present on the system: [source,shell] .... dc0: <82c169 PNIC 10/100BaseTX> port 0xa000-0xa0ff mem 0xd3800000-0xd38 000ff irq 15 at device 11.0 on pci0 miibus0: on dc0 bmtphy0: PHY 1 on miibus0 bmtphy0: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc0: Ethernet address: 00:a0:cc:da:da:da dc0: [ITHREAD] dc1: <82c169 PNIC 10/100BaseTX> port 0x9800-0x98ff mem 0xd3000000-0xd30 000ff irq 11 at device 12.0 on pci0 miibus1: on dc1 bmtphy1: PHY 1 on miibus1 bmtphy1: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc1: Ethernet address: 00:a0:cc:da:da:db dc1: [ITHREAD] .... If the driver for the NIC is not present in [.filename]#GENERIC#, but a driver is available, the driver will need to be loaded before the NIC can be configured and used. This may be accomplished in one of two ways: * The easiest way is to load a kernel module for the NIC using man:kldload[8]. To also automatically load the driver at boot time, add the appropriate line to [.filename]#/boot/loader.conf#. Not all NIC drivers are available as modules. * Alternatively, statically compile support for the NIC into a custom kernel. Refer to [.filename]#/usr/src/sys/conf/NOTES#, [.filename]#/usr/src/sys/arch/conf/NOTES# and the manual page of the driver to determine which line to add to the custom kernel configuration file. For more information about recompiling the kernel, refer to crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]. If the NIC was detected at boot, the kernel does not need to be recompiled. [[config-network-ndis]] ==== Using Windows(R) NDIS Drivers Unfortunately, there are still many vendors that do not provide schematics for their drivers to the open source community because they regard such information as trade secrets. Consequently, the developers of FreeBSD and other operating systems are left with two choices: develop the drivers by a long and pain-staking process of reverse engineering or using the existing driver binaries available for Microsoft(R) Windows(R) platforms. FreeBSD provides "native" support for the Network Driver Interface Specification (NDIS). It includes man:ndisgen[8] which can be used to convert a Windows(R) XP driver into a format that can be used on FreeBSD. Because the man:ndis[4] driver uses a Windows(R) XP binary, it only runs on i386(TM) and amd64 systems. PCI, CardBus, PCMCIA, and USB devices are supported. To use man:ndisgen[8], three things are needed: . FreeBSD kernel sources. . A Windows(R) XP driver binary with a [.filename]#.SYS# extension. . A Windows(R) XP driver configuration file with a [.filename]#.INF# extension. Download the [.filename]#.SYS# and [.filename]#.INF# files for the specific NIC. Generally, these can be found on the driver CD or at the vendor's website. The following examples use [.filename]#W32DRIVER.SYS# and [.filename]#W32DRIVER.INF#. The driver bit width must match the version of FreeBSD. For FreeBSD/i386, use a Windows(R) 32-bit driver. For FreeBSD/amd64, a Windows(R) 64-bit driver is needed. The next step is to compile the driver binary into a loadable kernel module. As `root`, use man:ndisgen[8]: [source,shell] .... # ndisgen /path/to/W32DRIVER.INF /path/to/W32DRIVER.SYS .... This command is interactive and prompts for any extra information it requires. A new kernel module will be generated in the current directory. Use man:kldload[8] to load the new module: [source,shell] .... # kldload ./W32DRIVER_SYS.ko .... In addition to the generated kernel module, the [.filename]#ndis.ko# and [.filename]#if_ndis.ko# modules must be loaded. This should happen automatically when any module that depends on man:ndis[4] is loaded. If not, load them manually, using the following commands: [source,shell] .... # kldload ndis # kldload if_ndis .... The first command loads the man:ndis[4] miniport driver wrapper and the second loads the generated NIC driver. Check man:dmesg[8] to see if there were any load errors. If all went well, the output should be similar to the following: [source,shell] .... ndis0: mem 0xf4100000-0xf4101fff irq 3 at device 8.0 on pci1 ndis0: NDIS API version: 5.0 ndis0: Ethernet address: 0a:b1:2c:d3:4e:f5 ndis0: 11b rates: 1Mbps 2Mbps 5.5Mbps 11Mbps ndis0: 11g rates: 6Mbps 9Mbps 12Mbps 18Mbps 36Mbps 48Mbps 54Mbps .... From here, [.filename]#ndis0# can be configured like any other NIC. To configure the system to load the man:ndis[4] modules at boot time, copy the generated module, [.filename]#W32DRIVER_SYS.ko#, to [.filename]#/boot/modules#. Then, add the following line to [.filename]#/boot/loader.conf#: [.programlisting] .... W32DRIVER_SYS_load="YES" .... === Configuring the Network Card Once the right driver is loaded for the NIC, the card needs to be configured. It may have been configured at installation time by man:bsdinstall[8]. To display the NIC configuration, enter the following command: [source,shell] .... % ifconfig dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da inet 192.168.1.3 netmask 0xffffff00 broadcast 192.168.1.255 media: Ethernet autoselect (100baseTX ) status: active dc1: flags=8802 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:db inet 10.0.0.1 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet 10baseT/UTP status: no carrier lo0: flags=8049 metric 0 mtu 16384 options=3 inet6 fe80::1%lo0 prefixlen 64 scopeid 0x4 inet6 ::1 prefixlen 128 inet 127.0.0.1 netmask 0xff000000 nd6 options=3 .... In this example, the following devices were displayed: * [.filename]#dc0#: The first Ethernet interface. * [.filename]#dc1#: The second Ethernet interface. * [.filename]#lo0#: The loopback device. FreeBSD uses the driver name followed by the order in which the card is detected at boot to name the NIC. For example, [.filename]#sis2# is the third NIC on the system using the man:sis[4] driver. In this example, [.filename]#dc0# is up and running. The key indicators are: . `UP` means that the card is configured and ready. . The card has an Internet (`inet`) address, `192.168.1.3`. . It has a valid subnet mask (`netmask`), where `0xffffff00` is the same as `255.255.255.0`. . It has a valid broadcast address, `192.168.1.255`. . The MAC address of the card (`ether`) is `00:a0:cc:da:da:da`. . The physical media selection is on autoselection mode (`media: Ethernet autoselect (100baseTX )`). In this example, [.filename]#dc1# is configured to run with `10baseT/UTP` media. For more information on available media types for a driver, refer to its manual page. . The status of the link (`status`) is `active`, indicating that the carrier signal is detected. For [.filename]#dc1#, the `status: no carrier` status is normal when an Ethernet cable is not plugged into the card. If the man:ifconfig[8] output had shown something similar to: [source,shell] .... dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da media: Ethernet autoselect (100baseTX ) status: active .... it would indicate the card has not been configured. The card must be configured as `root`. The NIC configuration can be performed from the command line with man:ifconfig[8] but will not persist after a reboot unless the configuration is also added to [.filename]#/etc/rc.conf#. If a DHCP server is present on the LAN, just add this line: [.programlisting] .... ifconfig_dc0="DHCP" .... Replace _dc0_ with the correct value for the system. The line added, then, follow the instructions given in <>. [NOTE] ==== If the network was configured during installation, some entries for the NIC(s) may be already present. Double check [.filename]#/etc/rc.conf# before adding any lines. ==== If there is no DHCP server, the NIC(s) must be configured manually. Add a line for each NIC present on the system, as seen in this example: [.programlisting] .... ifconfig_dc0="inet 192.168.1.3 netmask 255.255.255.0" ifconfig_dc1="inet 10.0.0.1 netmask 255.255.255.0 media 10baseT/UTP" .... Replace [.filename]#dc0# and [.filename]#dc1# and the IP address information with the correct values for the system. Refer to the man page for the driver, man:ifconfig[8], and man:rc.conf[5] for more details about the allowed options and the syntax of [.filename]#/etc/rc.conf#. If the network is not using DNS, edit [.filename]#/etc/hosts# to add the names and IP addresses of the hosts on the LAN, if they are not already there. For more information, refer to man:hosts[5] and to [.filename]#/usr/shared/examples/etc/hosts#. [NOTE] ==== If there is no DHCP server and access to the Internet is needed, manually configure the default gateway and the nameserver: [source,shell] .... # echo 'defaultrouter="your_default_router"' >> /etc/rc.conf # echo 'nameserver your_DNS_server' >> /etc/resolv.conf .... ==== [[config-network-testing]] === Testing and Troubleshooting Once the necessary changes to [.filename]#/etc/rc.conf# are saved, a reboot can be used to test the network configuration and to verify that the system restarts without any configuration errors. Alternatively, apply the settings to the networking system with this command: [source,shell] .... # service netif restart .... [NOTE] ==== If a default gateway has been set in [.filename]#/etc/rc.conf#, also issue this command: [source,shell] .... # service routing restart .... ==== Once the networking system has been relaunched, test the NICs. ==== Testing the Ethernet Card To verify that an Ethernet card is configured correctly, man:ping[8] the interface itself, and then man:ping[8] another machine on the LAN: [source,shell] .... % ping -c5 192.168.1.3 PING 192.168.1.3 (192.168.1.3): 56 data bytes 64 bytes from 192.168.1.3: icmp_seq=0 ttl=64 time=0.082 ms 64 bytes from 192.168.1.3: icmp_seq=1 ttl=64 time=0.074 ms 64 bytes from 192.168.1.3: icmp_seq=2 ttl=64 time=0.076 ms 64 bytes from 192.168.1.3: icmp_seq=3 ttl=64 time=0.108 ms 64 bytes from 192.168.1.3: icmp_seq=4 ttl=64 time=0.076 ms --- 192.168.1.3 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.074/0.083/0.108/0.013 ms .... [source,shell] .... % ping -c5 192.168.1.2 PING 192.168.1.2 (192.168.1.2): 56 data bytes 64 bytes from 192.168.1.2: icmp_seq=0 ttl=64 time=0.726 ms 64 bytes from 192.168.1.2: icmp_seq=1 ttl=64 time=0.766 ms 64 bytes from 192.168.1.2: icmp_seq=2 ttl=64 time=0.700 ms 64 bytes from 192.168.1.2: icmp_seq=3 ttl=64 time=0.747 ms 64 bytes from 192.168.1.2: icmp_seq=4 ttl=64 time=0.704 ms --- 192.168.1.2 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.700/0.729/0.766/0.025 ms .... To test network resolution, use the host name instead of the IP address. If there is no DNS server on the network, [.filename]#/etc/hosts# must first be configured. To this purpose, edit [.filename]#/etc/hosts# to add the names and IP addresses of the hosts on the LAN, if they are not already there. For more information, refer to man:hosts[5] and to [.filename]#/usr/shared/examples/etc/hosts#. ==== Troubleshooting When troubleshooting hardware and software configurations, check the simple things first. Is the network cable plugged in? Are the network services properly configured? Is the firewall configured correctly? Is the NIC supported by FreeBSD? Before sending a bug report, always check the Hardware Notes, update the version of FreeBSD to the latest STABLE version, check the mailing list archives, and search the Internet. If the card works, yet performance is poor, read through man:tuning[7]. Also, check the network configuration as incorrect network settings can cause slow connections. Some users experience one or two `device timeout` messages, which is normal for some cards. If they continue, or are bothersome, determine if the device is conflicting with another device. Double check the cable connections. Consider trying another card. To resolve `watchdog timeout` errors, first check the network cable. Many cards require a PCI slot which supports bus mastering. On some old motherboards, only one PCI slot allows it, usually slot 0. Check the NIC and the motherboard documentation to determine if that may be the problem. `No route to host` messages occur if the system is unable to route a packet to the destination host. This can happen if no default route is specified or if a cable is unplugged. Check the output of `netstat -rn` and make sure there is a valid route to the host. If there is not, read crossref:advanced-networking[network-routing,“Gateways and Routes”]. `ping: sendto: Permission denied` error messages are often caused by a misconfigured firewall. If a firewall is enabled on FreeBSD but no rules have been defined, the default policy is to deny all traffic, even man:ping[8]. Refer to crossref:firewalls[firewalls,Firewalls] for more information. Sometimes performance of the card is poor or below average. In these cases, try setting the media selection mode from `autoselect` to the correct media selection. While this works for most hardware, it may or may not resolve the issue. Again, check all the network settings, and refer to man:tuning[7]. [[configtuning-virtual-hosts]] == Virtual Hosts A common use of FreeBSD is virtual site hosting, where one server appears to the network as many servers. This is achieved by assigning multiple network addresses to a single interface. A given network interface has one "real" address, and may have any number of "alias" addresses. These aliases are normally added by placing alias entries in [.filename]#/etc/rc.conf#, as seen in this example: [.programlisting] .... ifconfig_fxp0_alias0="inet xxx.xxx.xxx.xxx netmask xxx.xxx.xxx.xxx" .... Alias entries must start with `alias__0__` using a sequential number such as `alias0`, `alias1`, and so on. The configuration process will stop at the first missing number. The calculation of alias netmasks is important. For a given interface, there must be one address which correctly represents the network's netmask. Any other addresses which fall within this network must have a netmask of all ``1``s, expressed as either `255.255.255.255` or `0xffffffff`. For example, consider the case where the [.filename]#fxp0# interface is connected to two networks: `10.1.1.0` with a netmask of `255.255.255.0` and `202.0.75.16` with a netmask of `255.255.255.240`. The system is to be configured to appear in the ranges `10.1.1.1` through `10.1.1.5` and `202.0.75.17` through `202.0.75.20`. Only the first address in a given network range should have a real netmask. All the rest (`10.1.1.2` through `10.1.1.5` and `202.0.75.18` through `202.0.75.20`) must be configured with a netmask of `255.255.255.255`. The following [.filename]#/etc/rc.conf# entries configure the adapter correctly for this scenario: [.programlisting] .... ifconfig_fxp0="inet 10.1.1.1 netmask 255.255.255.0" ifconfig_fxp0_alias0="inet 10.1.1.2 netmask 255.255.255.255" ifconfig_fxp0_alias1="inet 10.1.1.3 netmask 255.255.255.255" ifconfig_fxp0_alias2="inet 10.1.1.4 netmask 255.255.255.255" ifconfig_fxp0_alias3="inet 10.1.1.5 netmask 255.255.255.255" ifconfig_fxp0_alias4="inet 202.0.75.17 netmask 255.255.255.240" ifconfig_fxp0_alias5="inet 202.0.75.18 netmask 255.255.255.255" ifconfig_fxp0_alias6="inet 202.0.75.19 netmask 255.255.255.255" ifconfig_fxp0_alias7="inet 202.0.75.20 netmask 255.255.255.255" .... A simpler way to express this is with a space-separated list of IP address ranges. The first address will be given the indicated subnet mask and the additional addresses will have a subnet mask of `255.255.255.255`. [.programlisting] .... ifconfig_fxp0_aliases="inet 10.1.1.1-5/24 inet 202.0.75.17-20/28" .... [[configtuning-syslog]] == Configuring System Logging Generating and reading system logs is an important aspect of system administration. The information in system logs can be used to detect hardware and software issues as well as application and system configuration errors. This information also plays an important role in security auditing and incident response. Most system daemons and applications will generate log entries. FreeBSD provides a system logger, syslogd, to manage logging. By default, syslogd is started when the system boots. This is controlled by the variable `syslogd_enable` in [.filename]#/etc/rc.conf#. There are numerous application arguments that can be set using `syslogd_flags` in [.filename]#/etc/rc.conf#. Refer to man:syslogd[8] for more information on the available arguments. This section describes how to configure the FreeBSD system logger for both local and remote logging and how to perform log rotation and log management. === Configuring Local Logging The configuration file, [.filename]#/etc/syslog.conf#, controls what syslogd does with log entries as they are received. There are several parameters to control the handling of incoming events. The _facility_ describes which subsystem generated the message, such as the kernel or a daemon, and the _level_ describes the severity of the event that occurred. This makes it possible to configure if and where a log message is logged, depending on the facility and level. It is also possible to take action depending on the application that sent the message, and in the case of remote logging, the hostname of the machine generating the logging event. This configuration file contains one line per action, where the syntax for each line is a selector field followed by an action field. The syntax of the selector field is _facility.level_ which will match log messages from _facility_ at level _level_ or higher. It is also possible to add an optional comparison flag before the level to specify more precisely what is logged. Multiple selector fields can be used for the same action, and are separated with a semicolon (`;`). Using `*` will match everything. The action field denotes where to send the log message, such as to a file or remote log host. As an example, here is the default [.filename]#syslog.conf# from FreeBSD: [.programlisting] .... # $FreeBSD$ # # Spaces ARE valid field separators in this file. However, # other *nix-like systems still insist on using tabs as field # separators. If you are sharing this file between systems, you # may want to use only tabs as field separators here. # Consult the syslog.conf(5) manpage. *.err;kern.warning;auth.notice;mail.crit /dev/console *.notice;authpriv.none;kern.debug;lpr.info;mail.crit;news.err /var/log/messages security.* /var/log/security auth.info;authpriv.info /var/log/auth.log mail.info /var/log/maillog lpr.info /var/log/lpd-errs ftp.info /var/log/xferlog cron.* /var/log/cron !-devd *.=debug /var/log/debug.log *.emerg * # uncomment this to log all writes to /dev/console to /var/log/console.log #console.info /var/log/console.log # uncomment this to enable logging of all log messages to /var/log/all.log # touch /var/log/all.log and chmod it to mode 600 before it will work #*.* /var/log/all.log # uncomment this to enable logging to a remote loghost named loghost #*.* @loghost # uncomment these if you're running inn # news.crit /var/log/news/news.crit # news.err /var/log/news/news.err # news.notice /var/log/news/news.notice # Uncomment this if you wish to see messages produced by devd # !devd # *.>=info !ppp *.* /var/log/ppp.log !* .... In this example: * Line 8 matches all messages with a level of `err` or higher, as well as `kern.warning`, `auth.notice` and `mail.crit`, and sends these log messages to the console ([.filename]#/dev/console#). * Line 12 matches all messages from the `mail` facility at level `info` or above and logs the messages to [.filename]#/var/log/maillog#. * Line 17 uses a comparison flag (`=`) to only match messages at level `debug` and logs them to [.filename]#/var/log/debug.log#. * Line 33 is an example usage of a program specification. This makes the rules following it only valid for the specified program. In this case, only the messages generated by ppp are logged to [.filename]#/var/log/ppp.log#. The available levels, in order from most to least critical are `emerg`, `alert`, `crit`, `err`, `warning`, `notice`, `info`, and `debug`. The facilities, in no particular order, are `auth`, `authpriv`, `console`, `cron`, `daemon`, `ftp`, `kern`, `lpr`, `mail`, `mark`, `news`, `security`, `syslog`, `user`, `uucp`, and `local0` through `local7`. Be aware that other operating systems might have different facilities. To log everything of level `notice` and higher to [.filename]#/var/log/daemon.log#, add the following entry: [.programlisting] .... daemon.notice /var/log/daemon.log .... For more information about the different levels and facilities, refer to man:syslog[3] and man:syslogd[8]. For more information about [.filename]#/etc/syslog.conf#, its syntax, and more advanced usage examples, see man:syslog.conf[5]. === Log Management and Rotation Log files can grow quickly, taking up disk space and making it more difficult to locate useful information. Log management attempts to mitigate this. In FreeBSD, newsyslog is used to manage log files. This built-in program periodically rotates and compresses log files, and optionally creates missing log files and signals programs when log files are moved. The log files may be generated by syslogd or by any other program which generates log files. While newsyslog is normally run from man:cron[8], it is not a system daemon. In the default configuration, it runs every hour. To know which actions to take, newsyslog reads its configuration file, [.filename]#/etc/newsyslog.conf#. This file contains one line for each log file that newsyslog manages. Each line states the file owner, permissions, when to rotate that file, optional flags that affect log rotation, such as compression, and programs to signal when the log is rotated. Here is the default configuration in FreeBSD: [.programlisting] .... # configuration file for newsyslog # $FreeBSD$ # # Entries which do not specify the '/pid_file' field will cause the # syslogd process to be signalled when that log file is rotated. This # action is only appropriate for log files which are written to by the # syslogd process (ie, files listed in /etc/syslog.conf). If there # is no process which needs to be signalled when a given log file is # rotated, then the entry for that file should include the 'N' flag. # # The 'flags' field is one or more of the letters: BCDGJNUXZ or a '-'. # # Note: some sites will want to select more restrictive protections than the # defaults. In particular, it may be desirable to switch many of the 644 # entries to 640 or 600. For example, some sites will consider the # contents of maillog, messages, and lpd-errs to be confidential. In the # future, these defaults may change to more conservative ones. # # logfilename [owner:group] mode count size when flags [/pid_file] [sig_num] /var/log/all.log 600 7 * @T00 J /var/log/amd.log 644 7 100 * J /var/log/auth.log 600 7 100 @0101T JC /var/log/console.log 600 5 100 * J /var/log/cron 600 3 100 * JC /var/log/daily.log 640 7 * @T00 JN /var/log/debug.log 600 7 100 * JC /var/log/kerberos.log 600 7 100 * J /var/log/lpd-errs 644 7 100 * JC /var/log/maillog 640 7 * @T00 JC /var/log/messages 644 5 100 @0101T JC /var/log/monthly.log 640 12 * $M1D0 JN /var/log/pflog 600 3 100 * JB /var/run/pflogd.pid /var/log/ppp.log root:network 640 3 100 * JC /var/log/devd.log 644 3 100 * JC /var/log/security 600 10 100 * JC /var/log/sendmail.st 640 10 * 168 B /var/log/utx.log 644 3 * @01T05 B /var/log/weekly.log 640 5 1 $W6D0 JN /var/log/xferlog 600 7 100 * JC .... Each line starts with the name of the log to be rotated, optionally followed by an owner and group for both rotated and newly created files. The `mode` field sets the permissions on the log file and `count` denotes how many rotated log files should be kept. The `size` and `when` fields tell newsyslog when to rotate the file. A log file is rotated when either its size is larger than the `size` field or when the time in the `when` field has passed. An asterisk (`*`) means that this field is ignored. The _flags_ field gives further instructions, such as how to compress the rotated file or to create the log file if it is missing. The last two fields are optional and specify the name of the Process ID (PID) file of a process and a signal number to send to that process when the file is rotated. For more information on all fields, valid flags, and how to specify the rotation time, refer to man:newsyslog.conf[5]. Since newsyslog is run from man:cron[8], it cannot rotate files more often than it is scheduled to run from man:cron[8]. [[network-syslogd]] === Configuring Remote Logging Monitoring the log files of multiple hosts can become unwieldy as the number of systems increases. Configuring centralized logging can reduce some of the administrative burden of log file administration. In FreeBSD, centralized log file aggregation, merging, and rotation can be configured using syslogd and newsyslog. This section demonstrates an example configuration, where host `A`, named `logserv.example.com`, will collect logging information for the local network. Host `B`, named `logclient.example.com`, will be configured to pass logging information to the logging server. ==== Log Server Configuration A log server is a system that has been configured to accept logging information from other hosts. Before configuring a log server, check the following: * If there is a firewall between the logging server and any logging clients, ensure that the firewall ruleset allows UDP port 514 for both the clients and the server. * The logging server and all client machines must have forward and reverse entries in the local DNS. If the network does not have a DNS server, create entries in each system's [.filename]#/etc/hosts#. Proper name resolution is required so that log entries are not rejected by the logging server. On the log server, edit [.filename]#/etc/syslog.conf# to specify the name of the client to receive log entries from, the logging facility to be used, and the name of the log to store the host's log entries. This example adds the hostname of `B`, logs all facilities, and stores the log entries in [.filename]#/var/log/logclient.log#. .Sample Log Server Configuration [example] ==== [.programlisting] .... +logclient.example.com *.* /var/log/logclient.log .... ==== When adding multiple log clients, add a similar two-line entry for each client. More information about the available facilities may be found in man:syslog.conf[5]. Next, configure [.filename]#/etc/rc.conf#: [.programlisting] .... syslogd_enable="YES" syslogd_flags="-a logclient.example.com -v -v" .... The first entry starts syslogd at system boot. The second entry allows log entries from the specified client. The `-v -v` increases the verbosity of logged messages. This is useful for tweaking facilities as administrators are able to see what type of messages are being logged under each facility. Multiple `-a` options may be specified to allow logging from multiple clients. IP addresses and whole netblocks may also be specified. Refer to man:syslogd[8] for a full list of possible options. Finally, create the log file: [source,shell] .... # touch /var/log/logclient.log .... At this point, syslogd should be restarted and verified: [source,shell] .... # service syslogd restart # pgrep syslog .... If a PID is returned, the server restarted successfully, and client configuration can begin. If the server did not restart, consult [.filename]#/var/log/messages# for the error. ==== Log Client Configuration A logging client sends log entries to a logging server on the network. The client also keeps a local copy of its own logs. Once a logging server has been configured, edit [.filename]#/etc/rc.conf# on the logging client: [.programlisting] .... syslogd_enable="YES" syslogd_flags="-s -v -v" .... The first entry enables syslogd on boot up. The second entry prevents logs from being accepted by this client from other hosts (`-s`) and increases the verbosity of logged messages. Next, define the logging server in the client's [.filename]#/etc/syslog.conf#. In this example, all logged facilities are sent to a remote system, denoted by the `@` symbol, with the specified hostname: [.programlisting] .... *.* @logserv.example.com .... After saving the edit, restart syslogd for the changes to take effect: [source,shell] .... # service syslogd restart .... To test that log messages are being sent across the network, use man:logger[1] on the client to send a message to syslogd: [source,shell] .... # logger "Test message from logclient" .... This message should now exist both in [.filename]#/var/log/messages# on the client and [.filename]#/var/log/logclient.log# on the log server. ==== Debugging Log Servers If no messages are being received on the log server, the cause is most likely a network connectivity issue, a hostname resolution issue, or a typo in a configuration file. To isolate the cause, ensure that both the logging server and the logging client are able to `ping` each other using the hostname specified in their [.filename]#/etc/rc.conf#. If this fails, check the network cabling, the firewall ruleset, and the hostname entries in the DNS server or [.filename]#/etc/hosts# on both the logging server and clients. Repeat until the `ping` is successful from both hosts. If the `ping` succeeds on both hosts but log messages are still not being received, temporarily increase logging verbosity to narrow down the configuration issue. In the following example, [.filename]#/var/log/logclient.log# on the logging server is empty and [.filename]#/var/log/messages# on the logging client does not indicate a reason for the failure. To increase debugging output, edit the `syslogd_flags` entry on the logging server and issue a restart: [.programlisting] .... syslogd_flags="-d -a logclient.example.com -v -v" .... [source,shell] .... # service syslogd restart .... Debugging data similar to the following will flash on the console immediately after the restart: [source,shell] .... logmsg: pri 56, flags 4, from logserv.example.com, msg syslogd: restart syslogd: restarted logmsg: pri 6, flags 4, from logserv.example.com, msg syslogd: kernel boot file is /boot/kernel/kernel Logging to FILE /var/log/messages syslogd: kernel boot file is /boot/kernel/kernel cvthname(192.168.1.10) validate: dgram from IP 192.168.1.10, port 514, name logclient.example.com; rejected in rule 0 due to name mismatch. .... In this example, the log messages are being rejected due to a typo which results in a hostname mismatch. The client's hostname should be `logclient`, not `logclien`. Fix the typo, issue a restart, and verify the results: [source,shell] .... # service syslogd restart logmsg: pri 56, flags 4, from logserv.example.com, msg syslogd: restart syslogd: restarted logmsg: pri 6, flags 4, from logserv.example.com, msg syslogd: kernel boot file is /boot/kernel/kernel syslogd: kernel boot file is /boot/kernel/kernel logmsg: pri 166, flags 17, from logserv.example.com, msg Dec 10 20:55:02 logserv.example.com syslogd: exiting on signal 2 cvthname(192.168.1.10) validate: dgram from IP 192.168.1.10, port 514, name logclient.example.com; accepted in rule 0. logmsg: pri 15, flags 0, from logclient.example.com, msg Dec 11 02:01:28 trhodes: Test message 2 Logging to FILE /var/log/logclient.log Logging to FILE /var/log/messages .... At this point, the messages are being properly received and placed in the correct file. ==== Security Considerations As with any network service, security requirements should be considered before implementing a logging server. Log files may contain sensitive data about services enabled on the local host, user accounts, and configuration data. Network data sent from the client to the server will not be encrypted or password protected. If a need for encryption exists, consider using package:security/stunnel[], which will transmit the logging data over an encrypted tunnel. Local security is also an issue. Log files are not encrypted during use or after log rotation. Local users may access log files to gain additional insight into system configuration. Setting proper permissions on log files is critical. The built-in log rotator, newsyslog, supports setting permissions on newly created and rotated log files. Setting log files to mode `600` should prevent unwanted access by local users. Refer to man:newsyslog.conf[5] for additional information. [[configtuning-configfiles]] == Configuration Files === [.filename]#/etc# Layout There are a number of directories in which configuration information is kept. These include: [.informaltable] [cols="1,1", frame="none"] |=== |[.filename]#/etc# |Generic system-specific configuration information. |[.filename]#/etc/defaults# |Default versions of system configuration files. |[.filename]#/etc/mail# |Extra man:sendmail[8] configuration and other MTA configuration files. |[.filename]#/etc/ppp# |Configuration for both user- and kernel-ppp programs. |[.filename]#/usr/local/etc# |Configuration files for installed applications. May contain per-application subdirectories. |[.filename]#/usr/local/etc/rc.d# |man:rc[8] scripts for installed applications. |[.filename]#/var/db# |Automatically generated system-specific database files, such as the package database and the man:locate[1] database. |=== === Hostnames ==== [.filename]#/etc/resolv.conf# How a FreeBSD system accesses the Internet Domain Name System (DNS) is controlled by man:resolv.conf[5]. The most common entries to [.filename]#/etc/resolv.conf# are: [.informaltable] [cols="1,1", frame="none"] |=== |`nameserver` |The IP address of a name server the resolver should query. The servers are queried in the order listed with a maximum of three. |`search` |Search list for hostname lookup. This is normally determined by the domain of the local hostname. |`domain` |The local domain name. |=== A typical [.filename]#/etc/resolv.conf# looks like this: [.programlisting] .... search example.com nameserver 147.11.1.11 nameserver 147.11.100.30 .... [NOTE] ==== Only one of the `search` and `domain` options should be used. ==== When using DHCP, man:dhclient[8] usually rewrites [.filename]#/etc/resolv.conf# with information received from the DHCP server. ==== [.filename]#/etc/hosts# [.filename]#/etc/hosts# is a simple text database which works in conjunction with DNS and NIS to provide host name to IP address mappings. Entries for local computers connected via a LAN can be added to this file for simplistic naming purposes instead of setting up a man:named[8] server. Additionally, [.filename]#/etc/hosts# can be used to provide a local record of Internet names, reducing the need to query external DNS servers for commonly accessed names. [.programlisting] .... # $FreeBSD$ # # # Host Database # # This file should contain the addresses and aliases for local hosts that # share this file. Replace 'my.domain' below with the domainname of your # machine. # # In the presence of the domain name service or NIS, this file may # not be consulted at all; see /etc/nsswitch.conf for the resolution order. # # ::1 localhost localhost.my.domain 127.0.0.1 localhost localhost.my.domain # # Imaginary network. #10.0.0.2 myname.my.domain myname #10.0.0.3 myfriend.my.domain myfriend # # According to RFC 1918, you can use the following IP networks for # private nets which will never be connected to the Internet: # # 10.0.0.0 - 10.255.255.255 # 172.16.0.0 - 172.31.255.255 # 192.168.0.0 - 192.168.255.255 # # In case you want to be able to connect to the Internet, you need # real official assigned numbers. Do not try to invent your own network # numbers but instead get one from your network provider (if any) or # from your regional registry (ARIN, APNIC, LACNIC, RIPE NCC, or AfriNIC.) # .... The format of [.filename]#/etc/hosts# is as follows: [.programlisting] .... [Internet address] [official hostname] [alias1] [alias2] ... .... For example: [.programlisting] .... 10.0.0.1 myRealHostname.example.com myRealHostname foobar1 foobar2 .... Consult man:hosts[5] for more information. [[configtuning-sysctl]] == Tuning with man:sysctl[8] man:sysctl[8] is used to make changes to a running FreeBSD system. This includes many advanced options of the TCP/IP stack and virtual memory system that can dramatically improve performance for an experienced system administrator. Over five hundred system variables can be read and set using man:sysctl[8]. At its core, man:sysctl[8] serves two functions: to read and to modify system settings. To view all readable variables: [source,shell] .... % sysctl -a .... To read a particular variable, specify its name: [source,shell] .... % sysctl kern.maxproc kern.maxproc: 1044 .... To set a particular variable, use the _variable_=_value_ syntax: [source,shell] .... # sysctl kern.maxfiles=5000 kern.maxfiles: 2088 -> 5000 .... Settings of sysctl variables are usually either strings, numbers, or booleans, where a boolean is `1` for yes or `0` for no. To automatically set some variables each time the machine boots, add them to [.filename]#/etc/sysctl.conf#. For more information, refer to man:sysctl.conf[5] and <>. [[configtuning-sysctlconf]] === [.filename]#sysctl.conf# The configuration file for man:sysctl[8], [.filename]#/etc/sysctl.conf#, looks much like [.filename]#/etc/rc.conf#. Values are set in a `variable=value` form. The specified values are set after the system goes into multi-user mode. Not all variables are settable in this mode. For example, to turn off logging of fatal signal exits and prevent users from seeing processes started by other users, the following tunables can be set in [.filename]#/etc/sysctl.conf#: [.programlisting] .... # Do not log fatal signal exits (e.g., sig 11) kern.logsigexit=0 # Prevent users from seeing information about processes that # are being run under another UID. security.bsd.see_other_uids=0 .... [[sysctl-readonly]] === man:sysctl[8] Read-only In some cases it may be desirable to modify read-only man:sysctl[8] values, which will require a reboot of the system. For instance, on some laptop models the man:cardbus[4] device will not probe memory ranges and will fail with errors similar to: [source,shell] .... cbb0: Could not map register memory device_probe_and_attach: cbb0 attach returned 12 .... The fix requires the modification of a read-only man:sysctl[8] setting. Add `hw.pci.allow_unsupported_io_range=1` to [.filename]#/boot/loader.conf# and reboot. Now man:cardbus[4] should work properly. [[configtuning-disk]] == Tuning Disks The following section will discuss various tuning mechanisms and options which may be applied to disk devices. In many cases, disks with mechanical parts, such as SCSI drives, will be the bottleneck driving down the overall system performance. While a solution is to install a drive without mechanical parts, such as a solid state drive, mechanical drives are not going away anytime in the near future. When tuning disks, it is advisable to utilize the features of the man:iostat[8] command to test various changes to the system. This command will allow the user to obtain valuable information on system IO. === Sysctl Variables ==== `vfs.vmiodirenable` The `vfs.vmiodirenable` man:sysctl[8] variable may be set to either `0` (off) or `1` (on). It is set to `1` by default. This variable controls how directories are cached by the system. Most directories are small, using just a single fragment (typically 1 K) in the file system and typically 512 bytes in the buffer cache. With this variable turned off, the buffer cache will only cache a fixed number of directories, even if the system has a huge amount of memory. When turned on, this man:sysctl[8] allows the buffer cache to use the VM page cache to cache the directories, making all the memory available for caching directories. However, the minimum in-core memory used to cache a directory is the physical page size (typically 4 K) rather than 512 bytes. Keeping this option enabled is recommended if the system is running any services which manipulate large numbers of files. Such services can include web caches, large mail systems, and news systems. Keeping this option on will generally not reduce performance, even with the wasted memory, but one should experiment to find out. ==== `vfs.write_behind` The `vfs.write_behind` man:sysctl[8] variable defaults to `1` (on). This tells the file system to issue media writes as full clusters are collected, which typically occurs when writing large sequential files. This avoids saturating the buffer cache with dirty buffers when it would not benefit I/O performance. However, this may stall processes and under certain circumstances should be turned off. ==== `vfs.hirunningspace` The `vfs.hirunningspace` man:sysctl[8] variable determines how much outstanding write I/O may be queued to disk controllers system-wide at any given instance. The default is usually sufficient, but on machines with many disks, try bumping it up to four or five _megabytes_. Setting too high a value which exceeds the buffer cache's write threshold can lead to bad clustering performance. Do not set this value arbitrarily high as higher write values may add latency to reads occurring at the same time. There are various other buffer cache and VM page cache related man:sysctl[8] values. Modifying these values is not recommended as the VM system does a good job of automatically tuning itself. ==== `vm.swap_idle_enabled` The `vm.swap_idle_enabled` man:sysctl[8] variable is useful in large multi-user systems with many active login users and lots of idle processes. Such systems tend to generate continuous pressure on free memory reserves. Turning this feature on and tweaking the swapout hysteresis (in idle seconds) via `vm.swap_idle_threshold1` and `vm.swap_idle_threshold2` depresses the priority of memory pages associated with idle processes more quickly then the normal pageout algorithm. This gives a helping hand to the pageout daemon. Only turn this option on if needed, because the tradeoff is essentially pre-page memory sooner rather than later which eats more swap and disk bandwidth. In a small system this option will have a determinable effect, but in a large system that is already doing moderate paging, this option allows the VM system to stage whole processes into and out of memory easily. ==== `hw.ata.wc` Turning off IDE write caching reduces write bandwidth to IDE disks, but may sometimes be necessary due to data consistency issues introduced by hard drive vendors. The problem is that some IDE drives lie about when a write completes. With IDE write caching turned on, IDE hard drives write data to disk out of order and will sometimes delay writing some blocks indefinitely when under heavy disk load. A crash or power failure may cause serious file system corruption. Check the default on the system by observing the `hw.ata.wc` man:sysctl[8] variable. If IDE write caching is turned off, one can set this read-only variable to `1` in [.filename]#/boot/loader.conf# in order to enable it at boot time. For more information, refer to man:ata[4]. ==== `SCSI_DELAY` (`kern.cam.scsi_delay`) The `SCSI_DELAY` kernel configuration option may be used to reduce system boot times. The defaults are fairly high and can be responsible for `15` seconds of delay in the boot process. Reducing it to `5` seconds usually works with modern drives. The `kern.cam.scsi_delay` boot time tunable should be used. The tunable and kernel configuration option accept values in terms of _milliseconds_ and _not seconds_. [[soft-updates]] === Soft Updates To fine-tune a file system, use man:tunefs[8]. This program has many different options. To toggle Soft Updates on and off, use: [source,shell] .... # tunefs -n enable /filesystem # tunefs -n disable /filesystem .... A file system cannot be modified with man:tunefs[8] while it is mounted. A good time to enable Soft Updates is before any partitions have been mounted, in single-user mode. Soft Updates is recommended for UFS file systems as it drastically improves meta-data performance, mainly file creation and deletion, through the use of a memory cache. There are two downsides to Soft Updates to be aware of. First, Soft Updates guarantee file system consistency in the case of a crash, but could easily be several seconds or even a minute behind updating the physical disk. If the system crashes, unwritten data may be lost. Secondly, Soft Updates delay the freeing of file system blocks. If the root file system is almost full, performing a major update, such as `make installworld`, can cause the file system to run out of space and the update to fail. ==== More Details About Soft Updates Meta-data updates are updates to non-content data like inodes or directories. There are two traditional approaches to writing a file system's meta-data back to disk. Historically, the default behavior was to write out meta-data updates synchronously. If a directory changed, the system waited until the change was actually written to disk. The file data buffers (file contents) were passed through the buffer cache and backed up to disk later on asynchronously. The advantage of this implementation is that it operates safely. If there is a failure during an update, meta-data is always in a consistent state. A file is either created completely or not at all. If the data blocks of a file did not find their way out of the buffer cache onto the disk by the time of the crash, man:fsck[8] recognizes this and repairs the file system by setting the file length to `0`. Additionally, the implementation is clear and simple. The disadvantage is that meta-data changes are slow. For example, `rm -r` touches all the files in a directory sequentially, but each directory change will be written synchronously to the disk. This includes updates to the directory itself, to the inode table, and possibly to indirect blocks allocated by the file. Similar considerations apply for unrolling large hierarchies using `tar -x`. The second approach is to use asynchronous meta-data updates. This is the default for a UFS file system mounted with `mount -o async`. Since all meta-data updates are also passed through the buffer cache, they will be intermixed with the updates of the file content data. The advantage of this implementation is there is no need to wait until each meta-data update has been written to disk, so all operations which cause huge amounts of meta-data updates work much faster than in the synchronous case. This implementation is still clear and simple, so there is a low risk for bugs creeping into the code. The disadvantage is that there is no guarantee for a consistent state of the file system. If there is a failure during an operation that updated large amounts of meta-data, like a power failure or someone pressing the reset button, the file system will be left in an unpredictable state. There is no opportunity to examine the state of the file system when the system comes up again as the data blocks of a file could already have been written to the disk while the updates of the inode table or the associated directory were not. It is impossible to implement a man:fsck[8] which is able to clean up the resulting chaos because the necessary information is not available on the disk. If the file system has been damaged beyond repair, the only choice is to reformat it and restore from backup. The usual solution for this problem is to implement _dirty region logging_, which is also referred to as _journaling_. Meta-data updates are still written synchronously, but only into a small region of the disk. Later on, they are moved to their proper location. Because the logging area is a small, contiguous region on the disk, there are no long distances for the disk heads to move, even during heavy operations, so these operations are quicker than synchronous updates. Additionally, the complexity of the implementation is limited, so the risk of bugs being present is low. A disadvantage is that all meta-data is written twice, once into the logging region and once to the proper location, so performance "pessimization" might result. On the other hand, in case of a crash, all pending meta-data operations can be either quickly rolled back or completed from the logging area after the system comes up again, resulting in a fast file system startup. Kirk McKusick, the developer of Berkeley FFS, solved this problem with Soft Updates. All pending meta-data updates are kept in memory and written out to disk in a sorted sequence ("ordered meta-data updates"). This has the effect that, in case of heavy meta-data operations, later updates to an item "catch" the earlier ones which are still in memory and have not already been written to disk. All operations are generally performed in memory before the update is written to disk and the data blocks are sorted according to their position so that they will not be on the disk ahead of their meta-data. If the system crashes, an implicit "log rewind" causes all operations which were not written to the disk appear as if they never happened. A consistent file system state is maintained that appears to be the one of 30 to 60 seconds earlier. The algorithm used guarantees that all resources in use are marked as such in their blocks and inodes. After a crash, the only resource allocation error that occurs is that resources are marked as "used" which are actually "free". man:fsck[8] recognizes this situation, and frees the resources that are no longer used. It is safe to ignore the dirty state of the file system after a crash by forcibly mounting it with `mount -f`. In order to free resources that may be unused, man:fsck[8] needs to be run at a later time. This is the idea behind the _background man:fsck[8]_: at system startup time, only a _snapshot_ of the file system is recorded and man:fsck[8] is run afterwards. All file systems can then be mounted "dirty", so the system startup proceeds in multi-user mode. Then, background man:fsck[8] is scheduled for all file systems where this is required, to free resources that may be unused. File systems that do not use Soft Updates still need the usual foreground man:fsck[8]. The advantage is that meta-data operations are nearly as fast as asynchronous updates and are faster than _logging_, which has to write the meta-data twice. The disadvantages are the complexity of the code, a higher memory consumption, and some idiosyncrasies. After a crash, the state of the file system appears to be somewhat "older". In situations where the standard synchronous approach would have caused some zero-length files to remain after the man:fsck[8], these files do not exist at all with Soft Updates because neither the meta-data nor the file contents have been written to disk. Disk space is not released until the updates have been written to disk, which may take place some time after running man:rm[1]. This may cause problems when installing large amounts of data on a file system that does not have enough free space to hold all the files twice. [[configtuning-kernel-limits]] == Tuning Kernel Limits [[file-process-limits]] === File/Process Limits [[kern-maxfiles]] ==== `kern.maxfiles` The `kern.maxfiles` man:sysctl[8] variable can be raised or lowered based upon system requirements. This variable indicates the maximum number of file descriptors on the system. When the file descriptor table is full, `file: table is full` will show up repeatedly in the system message buffer, which can be viewed using man:dmesg[8]. Each open file, socket, or fifo uses one file descriptor. A large-scale production server may easily require many thousands of file descriptors, depending on the kind and number of services running concurrently. In older FreeBSD releases, the default value of `kern.maxfiles` is derived from `maxusers` in the kernel configuration file. `kern.maxfiles` grows proportionally to the value of `maxusers`. When compiling a custom kernel, consider setting this kernel configuration option according to the use of the system. From this number, the kernel is given most of its pre-defined limits. Even though a production machine may not have 256 concurrent users, the resources needed may be similar to a high-scale web server. The read-only man:sysctl[8] variable `kern.maxusers` is automatically sized at boot based on the amount of memory available in the system, and may be determined at run-time by inspecting the value of `kern.maxusers`. Some systems require larger or smaller values of `kern.maxusers` and values of `64`, `128`, and `256` are not uncommon. Going above `256` is not recommended unless a huge number of file descriptors is needed. Many of the tunable values set to their defaults by `kern.maxusers` may be individually overridden at boot-time or run-time in [.filename]#/boot/loader.conf#. Refer to man:loader.conf[5] and [.filename]#/boot/defaults/loader.conf# for more details and some hints. In older releases, the system will auto-tune `maxusers` if it is set to `0`. footnote:[The auto-tuning algorithm sets maxusers equal to the amount of memory in the system, with a minimum of 32, and a maximum of 384.]. When setting this option, set `maxusers` to at least `4`, especially if the system runs Xorg or is used to compile software. The most important table set by `maxusers` is the maximum number of processes, which is set to `20 + 16 * maxusers`. If `maxusers` is set to `1`, there can only be `36` simultaneous processes, including the `18` or so that the system starts up at boot time and the `15` or so used by Xorg. Even a simple task like reading a manual page will start up nine processes to filter, decompress, and view it. Setting `maxusers` to `64` allows up to `1044` simultaneous processes, which should be enough for nearly all uses. If, however, the error is displayed when trying to start another program, or a server is running with a large number of simultaneous users, increase the number and rebuild. [NOTE] ==== `maxusers` does _not_ limit the number of users which can log into the machine. It instead sets various table sizes to reasonable values considering the maximum number of users on the system and how many processes each user will be running. ==== ==== `kern.ipc.soacceptqueue` The `kern.ipc.soacceptqueue` man:sysctl[8] variable limits the size of the listen queue for accepting new `TCP` connections. The default value of `128` is typically too low for robust handling of new connections on a heavily loaded web server. For such environments, it is recommended to increase this value to `1024` or higher. A service such as man:sendmail[8], or Apache may itself limit the listen queue size, but will often have a directive in its configuration file to adjust the queue size. Large listen queues do a better job of avoiding Denial of Service (DoS) attacks. [[nmbclusters]] === Network Limits The `NMBCLUSTERS` kernel configuration option dictates the amount of network Mbufs available to the system. A heavily-trafficked server with a low number of Mbufs will hinder performance. Each cluster represents approximately 2 K of memory, so a value of `1024` represents `2` megabytes of kernel memory reserved for network buffers. A simple calculation can be done to figure out how many are needed. A web server which maxes out at `1000` simultaneous connections where each connection uses a 6 K receive and 16 K send buffer, requires approximately 32 MB worth of network buffers to cover the web server. A good rule of thumb is to multiply by `2`, so 2x32 MB / 2 KB = 64 MB / 2 kB = `32768`. Values between `4096` and `32768` are recommended for machines with greater amounts of memory. Never specify an arbitrarily high value for this parameter as it could lead to a boot time crash. To observe network cluster usage, use `-m` with man:netstat[1]. The `kern.ipc.nmbclusters` loader tunable should be used to tune this at boot time. Only older versions of FreeBSD will require the use of the `NMBCLUSTERS` kernel man:config[8] option. For busy servers that make extensive use of the man:sendfile[2] system call, it may be necessary to increase the number of man:sendfile[2] buffers via the `NSFBUFS` kernel configuration option or by setting its value in [.filename]#/boot/loader.conf# (see man:loader[8] for details). A common indicator that this parameter needs to be adjusted is when processes are seen in the `sfbufa` state. The man:sysctl[8] variable `kern.ipc.nsfbufs` is read-only. This parameter nominally scales with `kern.maxusers`, however it may be necessary to tune accordingly. [IMPORTANT] ==== Even though a socket has been marked as non-blocking, calling man:sendfile[2] on the non-blocking socket may result in the man:sendfile[2] call blocking until enough ``struct sf_buf``'s are made available. ==== ==== `net.inet.ip.portrange.*` The `net.inet.ip.portrange.*` man:sysctl[8] variables control the port number ranges automatically bound to `TCP` and `UDP` sockets. There are three ranges: a low range, a default range, and a high range. Most network programs use the default range which is controlled by `net.inet.ip.portrange.first` and `net.inet.ip.portrange.last`, which default to `1024` and `5000`, respectively. Bound port ranges are used for outgoing connections and it is possible to run the system out of ports under certain circumstances. This most commonly occurs when running a heavily loaded web proxy. The port range is not an issue when running a server which handles mainly incoming connections, such as a web server, or has a limited number of outgoing connections, such as a mail relay. For situations where there is a shortage of ports, it is recommended to increase `net.inet.ip.portrange.last` modestly. A value of `10000`, `20000` or `30000` may be reasonable. Consider firewall effects when changing the port range. Some firewalls may block large ranges of ports, usually low-numbered ports, and expect systems to use higher ranges of ports for outgoing connections. For this reason, it is not recommended that the value of `net.inet.ip.portrange.first` be lowered. ==== `TCP` Bandwidth Delay Product `TCP` bandwidth delay product limiting can be enabled by setting the `net.inet.tcp.inflight.enable` man:sysctl[8] variable to `1`. This instructs the system to attempt to calculate the bandwidth delay product for each connection and limit the amount of data queued to the network to just the amount required to maintain optimum throughput. This feature is useful when serving data over modems, Gigabit Ethernet, high speed `WAN` links, or any other link with a high bandwidth delay product, especially when also using window scaling or when a large send window has been configured. When enabling this option, also set `net.inet.tcp.inflight.debug` to `0` to disable debugging. For production use, setting `net.inet.tcp.inflight.min` to at least `6144` may be beneficial. Setting high minimums may effectively disable bandwidth limiting, depending on the link. The limiting feature reduces the amount of data built up in intermediate route and switch packet queues and reduces the amount of data built up in the local host's interface queue. With fewer queued packets, interactive connections, especially over slow modems, will operate with lower _Round Trip Times_. This feature only effects server side data transmission such as uploading. It has no effect on data reception or downloading. Adjusting `net.inet.tcp.inflight.stab` is _not_ recommended. This parameter defaults to `20`, representing 2 maximal packets added to the bandwidth delay product window calculation. The additional window is required to stabilize the algorithm and improve responsiveness to changing conditions, but it can also result in higher man:ping[8] times over slow links, though still much lower than without the inflight algorithm. In such cases, try reducing this parameter to `15`, `10`, or `5` and reducing `net.inet.tcp.inflight.min` to a value such as `3500` to get the desired effect. Reducing these parameters should be done as a last resort only. === Virtual Memory ==== `kern.maxvnodes` A vnode is the internal representation of a file or directory. Increasing the number of vnodes available to the operating system reduces disk I/O. Normally, this is handled by the operating system and does not need to be changed. In some cases where disk I/O is a bottleneck and the system is running out of vnodes, this setting needs to be increased. The amount of inactive and free RAM will need to be taken into account. To see the current number of vnodes in use: [source,shell] .... # sysctl vfs.numvnodes vfs.numvnodes: 91349 .... To see the maximum vnodes: [source,shell] .... # sysctl kern.maxvnodes kern.maxvnodes: 100000 .... If the current vnode usage is near the maximum, try increasing `kern.maxvnodes` by a value of `1000`. Keep an eye on the number of `vfs.numvnodes`. If it climbs up to the maximum again, `kern.maxvnodes` will need to be increased further. Otherwise, a shift in memory usage as reported by man:top[1] should be visible and more memory should be active. [[adding-swap-space]] == Adding Swap Space Sometimes a system requires more swap space. This section describes two methods to increase swap space: adding swap to an existing partition or new hard drive, and creating a swap file on an existing partition. For information on how to encrypt swap space, which options exist, and why it should be done, refer to crossref:disks[swap-encrypting,“Encrypting Swap”]. [[new-drive-swap]] === Swap on a New Hard Drive or Existing Partition Adding a new hard drive for swap gives better performance than using a partition on an existing drive. Setting up partitions and hard drives is explained in crossref:disks[disks-adding,“Adding Disks”] while crossref:bsdinstall[configtuning-initial,“Designing the Partition Layout”] discusses partition layouts and swap partition size considerations. Use `swapon` to add a swap partition to the system. For example: [source,shell] .... # swapon /dev/ada1s1b .... [WARNING] ==== It is possible to use any partition not currently mounted, even if it already contains data. Using `swapon` on a partition that contains data will overwrite and destroy that data. Make sure that the partition to be added as swap is really the intended partition before running `swapon`. ==== To automatically add this swap partition on boot, add an entry to [.filename]#/etc/fstab#: [.programlisting] .... /dev/ada1s1b none swap sw 0 0 .... See man:fstab[5] for an explanation of the entries in [.filename]#/etc/fstab#. More information about `swapon` can be found in man:swapon[8]. [[create-swapfile]] === Creating a Swap File These examples create a 512M swap file called [.filename]#/usr/swap0# instead of using a partition. Using swap files requires that the module needed by man:md[4] has either been built into the kernel or has been loaded before swap is enabled. See crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel] for information about building a custom kernel. [[swapfile-10-and-later]] .Creating a Swap File [example] ==== [.procedure] . Create the swap file: + [source,shell] .... # dd if=/dev/zero of=/usr/swap0 bs=1m count=512 .... . Set the proper permissions on the new file: + [source,shell] .... # chmod 0600 /usr/swap0 .... . Inform the system about the swap file by adding a line to [.filename]#/etc/fstab#: + [.programlisting] .... md99 none swap sw,file=/usr/swap0,late 0 0 .... + The man:md[4] device [.filename]#md99# is used, leaving lower device numbers available for interactive use. . Swap space will be added on system startup. To add swap space immediately, use man:swapon[8]: + [source,shell] .... # swapon -aL .... ==== [[acpi-overview]] == Power and Resource Management It is important to utilize hardware resources in an efficient manner. Power and resource management allows the operating system to monitor system limits and to possibly provide an alert if the system temperature increases unexpectedly. An early specification for providing power management was the Advanced Power Management (APM) facility. APM controls the power usage of a system based on its activity. However, it was difficult and inflexible for operating systems to manage the power usage and thermal properties of a system. The hardware was managed by the BIOS and the user had limited configurability and visibility into the power management settings. The APMBIOS is supplied by the vendor and is specific to the hardware platform. An APM driver in the operating system mediates access to the APM Software Interface, which allows management of power levels. There are four major problems in APM. First, power management is done by the vendor-specific BIOS, separate from the operating system. For example, the user can set idle-time values for a hard drive in the APMBIOS so that, when exceeded, the BIOS spins down the hard drive without the consent of the operating system. Second, the APM logic is embedded in the BIOS, and it operates outside the scope of the operating system. This means that users can only fix problems in the APMBIOS by flashing a new one into the ROM, which is a dangerous procedure with the potential to leave the system in an unrecoverable state if it fails. Third, APM is a vendor-specific technology, meaning that there is a lot of duplication of efforts and bugs found in one vendor's BIOS may not be solved in others. Lastly, the APMBIOS did not have enough room to implement a sophisticated power policy or one that can adapt well to the purpose of the machine. The Plug and Play BIOS (PNPBIOS) was unreliable in many situations. PNPBIOS is 16-bit technology, so the operating system has to use 16-bit emulation in order to interface with PNPBIOS methods. FreeBSD provides an APM driver as APM should still be used for systems manufactured at or before the year 2000. The driver is documented in man:apm[4]. The successor to APM is the Advanced Configuration and Power Interface (ACPI). ACPI is a standard written by an alliance of vendors to provide an interface for hardware resources and power management. It is a key element in _Operating System-directed configuration and Power Management_ as it provides more control and flexibility to the operating system. This chapter demonstrates how to configure ACPI on FreeBSD. It then offers some tips on how to debug ACPI and how to submit a problem report containing debugging information so that developers can diagnosis and fix ACPI issues. [[acpi-config]] === Configuring ACPI In FreeBSD the man:acpi[4] driver is loaded by default at system boot and should _not_ be compiled into the kernel. This driver cannot be unloaded after boot because the system bus uses it for various hardware interactions. However, if the system is experiencing problems, ACPI can be disabled altogether by rebooting after setting `hint.acpi.0.disabled="1"` in [.filename]#/boot/loader.conf# or by setting this variable at the loader prompt, as described in crossref:boot[boot-loader,“Stage Three”]. [NOTE] ==== ACPI and APM cannot coexist and should be used separately. The last one to load will terminate if the driver notices the other is running. ==== ACPI can be used to put the system into a sleep mode with `acpiconf`, the `-s` flag, and a number from `1` to `5`. Most users only need `1` (quick suspend to RAM) or `3` (suspend to RAM). Option `5` performs a soft-off which is the same as running `halt -p`. Other options are available using `sysctl`. Refer to man:acpi[4] and man:acpiconf[8] for more information. [[ACPI-comprob]] === Common Problems ACPI is present in all modern computers that conform to the ia32 (x86) and amd64 (AMD) architectures. The full standard has many features including CPU performance management, power planes control, thermal zones, various battery systems, embedded controllers, and bus enumeration. Most systems implement less than the full standard. For instance, a desktop system usually only implements bus enumeration while a laptop might have cooling and battery management support as well. Laptops also have suspend and resume, with their own associated complexity. An ACPI-compliant system has various components. The BIOS and chipset vendors provide various fixed tables, such as FADT, in memory that specify things like the APIC map (used for SMP), config registers, and simple configuration values. Additionally, a bytecode table, the Differentiated System Description Table DSDT, specifies a tree-like name space of devices and methods. The ACPI driver must parse the fixed tables, implement an interpreter for the bytecode, and modify device drivers and the kernel to accept information from the ACPI subsystem. For FreeBSD, Intel(R) has provided an interpreter (ACPI-CA) that is shared with Linux(R) and NetBSD. The path to the ACPI-CA source code is [.filename]#src/sys/contrib/dev/acpica#. The glue code that allows ACPI-CA to work on FreeBSD is in [.filename]#src/sys/dev/acpica/Osd#. Finally, drivers that implement various ACPI devices are found in [.filename]#src/sys/dev/acpica#. For ACPI to work correctly, all the parts have to work correctly. Here are some common problems, in order of frequency of appearance, and some possible workarounds or fixes. If a fix does not resolve the issue, refer to <> for instructions on how to submit a bug report. ==== Mouse Issues In some cases, resuming from a suspend operation will cause the mouse to fail. A known work around is to add `hint.psm.0.flags="0x3000"` to [.filename]#/boot/loader.conf#. ==== Suspend/Resume ACPI has three suspend to RAM (STR) states, `S1`-`S3`, and one suspend to disk state (STD), called `S4`. STD can be implemented in two separate ways. The ``S4``BIOS is a BIOS-assisted suspend to disk and ``S4``OS is implemented entirely by the operating system. The normal state the system is in when plugged in but not powered up is "soft off" (`S5`). Use `sysctl hw.acpi` to check for the suspend-related items. These example results are from a Thinkpad: [source,shell] .... hw.acpi.supported_sleep_state: S3 S4 S5 hw.acpi.s4bios: 0 .... Use `acpiconf -s` to test `S3`, `S4`, and `S5`. An `s4bios` of one (`1`) indicates ``S4``BIOS support instead of `S4` operating system support. When testing suspend/resume, start with `S1`, if supported. This state is most likely to work since it does not require much driver support. No one has implemented `S2`, which is similar to `S1`. Next, try `S3`. This is the deepest STR state and requires a lot of driver support to properly reinitialize the hardware. A common problem with suspend/resume is that many device drivers do not save, restore, or reinitialize their firmware, registers, or device memory properly. As a first attempt at debugging the problem, try: [source,shell] .... # sysctl debug.bootverbose=1 # sysctl debug.acpi.suspend_bounce=1 # acpiconf -s 3 .... This test emulates the suspend/resume cycle of all device drivers without actually going into `S3` state. In some cases, problems such as losing firmware state, device watchdog time out, and retrying forever, can be captured with this method. Note that the system will not really enter `S3` state, which means devices may not lose power, and many will work fine even if suspend/resume methods are totally missing, unlike real `S3` state. Harder cases require additional hardware, such as a serial port and cable for debugging through a serial console, a Firewire port and cable for using man:dcons[4], and kernel debugging skills. To help isolate the problem, unload as many drivers as possible. If it works, narrow down which driver is the problem by loading drivers until it fails again. Typically, binary drivers like [.filename]#nvidia.ko#, display drivers, and USB will have the most problems while Ethernet interfaces usually work fine. If drivers can be properly loaded and unloaded, automate this by putting the appropriate commands in [.filename]#/etc/rc.suspend# and [.filename]#/etc/rc.resume#. Try setting `hw.acpi.reset_video` to `1` if the display is messed up after resume. Try setting longer or shorter values for `hw.acpi.sleep_delay` to see if that helps. Try loading a recent Linux(R) distribution to see if suspend/resume works on the same hardware. If it works on Linux(R), it is likely a FreeBSD driver problem. Narrowing down which driver causes the problem will assist developers in fixing the problem. Since the ACPI maintainers rarely maintain other drivers, such as sound or ATA, any driver problems should also be posted to the {freebsd-current} and mailed to the driver maintainer. Advanced users can include debugging man:printf[3]s in a problematic driver to track down where in its resume function it hangs. Finally, try disabling ACPI and enabling APM instead. If suspend/resume works with APM, stick with APM, especially on older hardware (pre-2000). It took vendors a while to get ACPI support correct and older hardware is more likely to have BIOS problems with ACPI. ==== System Hangs Most system hangs are a result of lost interrupts or an interrupt storm. Chipsets may have problems based on boot, how the BIOS configures interrupts before correctness of the APIC (MADT) table, and routing of the System Control Interrupt (SCI). Interrupt storms can be distinguished from lost interrupts by checking the output of `vmstat -i` and looking at the line that has `acpi0`. If the counter is increasing at more than a couple per second, there is an interrupt storm. If the system appears hung, try breaking to DDB (kbd:[CTRL+ALT+ESC] on console) and type `show interrupts`. When dealing with interrupt problems, try disabling APIC support with `hint.apic.0.disabled="1"` in [.filename]#/boot/loader.conf#. ==== Panics Panics are relatively rare for ACPI and are the top priority to be fixed. The first step is to isolate the steps to reproduce the panic, if possible, and get a backtrace. Follow the advice for enabling `options DDB` and setting up a serial console in crossref:serialcomms[serialconsole-ddb,“Entering the DDB Debugger from the Serial Line”] or setting up a dump partition. To get a backtrace in DDB, use `tr`. When handwriting the backtrace, get at least the last five and the top five lines in the trace. Then, try to isolate the problem by booting with ACPI disabled. If that works, isolate the ACPI subsystem by using various values of `debug.acpi.disable`. See man:acpi[4] for some examples. ==== System Powers Up After Suspend or Shutdown First, try setting `hw.acpi.disable_on_poweroff="0"` in [.filename]#/boot/loader.conf#. This keeps ACPI from disabling various events during the shutdown process. Some systems need this value set to `1` (the default) for the same reason. This usually fixes the problem of a system powering up spontaneously after a suspend or poweroff. [[ACPI-aslanddump]] ==== BIOS Contains Buggy Bytecode Some BIOS vendors provide incorrect or buggy bytecode. This is usually manifested by kernel console messages like this: [source,shell] .... ACPI-1287: *** Error: Method execution failed [\\_SB_.PCI0.LPC0.FIGD._STA] \\ (Node 0xc3f6d160), AE_NOT_FOUND .... Often, these problems may be resolved by updating the BIOS to the latest revision. Most console messages are harmless, but if there are other problems, like the battery status is not working, these messages are a good place to start looking for problems. === Overriding the Default AML The BIOS bytecode, known as ACPI Machine Language (AML), is compiled from a source language called ACPI Source Language (ASL). The AML is found in the table known as the Differentiated System Description Table (DSDT). The goal of FreeBSD is for everyone to have working ACPI without any user intervention. Workarounds are still being developed for common mistakes made by BIOS vendors. The Microsoft(R) interpreter ([.filename]#acpi.sys# and [.filename]#acpiec.sys#) does not strictly check for adherence to the standard, and thus many BIOS vendors who only test ACPI under Windows(R) never fix their ASL. FreeBSD developers continue to identify and document which non-standard behavior is allowed by Microsoft(R)'s interpreter and replicate it so that FreeBSD can work without forcing users to fix the ASL. To help identify buggy behavior and possibly fix it manually, a copy can be made of the system's ASL. To copy the system's ASL to a specified file name, use `acpidump` with `-t`, to show the contents of the fixed tables, and `-d`, to disassemble the AML: [source,shell] .... # acpidump -td > my.asl .... Some AML versions assume the user is running Windows(R). To override this, set `hw.acpi.osname=_"Windows 2009"_` in [.filename]#/boot/loader.conf#, using the most recent Windows(R) version listed in the ASL. Other workarounds may require [.filename]#my.asl# to be customized. If this file is edited, compile the new ASL using the following command. Warnings can usually be ignored, but errors are bugs that will usually prevent ACPI from working correctly. [source,shell] .... # iasl -f my.asl .... Including `-f` forces creation of the AML, even if there are errors during compilation. Some errors, such as missing return statements, are automatically worked around by the FreeBSD interpreter. The default output filename for `iasl` is [.filename]#DSDT.aml#. Load this file instead of the BIOS's buggy copy, which is still present in flash memory, by editing [.filename]#/boot/loader.conf# as follows: [.programlisting] .... acpi_dsdt_load="YES" acpi_dsdt_name="/boot/DSDT.aml" .... Be sure to copy [.filename]#DSDT.aml# to [.filename]#/boot#, then reboot the system. If this fixes the problem, send a man:diff[1] of the old and new ASL to {freebsd-acpi} so that developers can work around the buggy behavior in [.filename]#acpica#. [[ACPI-submitdebug]] === Getting and Submitting Debugging Info The ACPI driver has a flexible debugging facility. A set of subsystems and the level of verbosity can be specified. The subsystems to debug are specified as layers and are broken down into components (`ACPI_ALL_COMPONENTS`) and ACPI hardware support (`ACPI_ALL_DRIVERS`). The verbosity of debugging output is specified as the level and ranges from just report errors (`ACPI_LV_ERROR`) to everything (`ACPI_LV_VERBOSE`). The level is a bitmask so multiple options can be set at once, separated by spaces. In practice, a serial console should be used to log the output so it is not lost as the console message buffer flushes. A full list of the individual layers and levels is found in man:acpi[4]. Debugging output is not enabled by default. To enable it, add `options ACPI_DEBUG` to the custom kernel configuration file if ACPI is compiled into the kernel. Add `ACPI_DEBUG=1` to [.filename]#/etc/make.conf# to enable it globally. If a module is used instead of a custom kernel, recompile just the [.filename]#acpi.ko# module as follows: [source,shell] .... # cd /sys/modules/acpi/acpi && make clean && make ACPI_DEBUG=1 .... Copy the compiled [.filename]#acpi.ko# to [.filename]#/boot/kernel# and add the desired level and layer to [.filename]#/boot/loader.conf#. The entries in this example enable debug messages for all ACPI components and hardware drivers and output error messages at the least verbose level: [.programlisting] .... debug.acpi.layer="ACPI_ALL_COMPONENTS ACPI_ALL_DRIVERS" debug.acpi.level="ACPI_LV_ERROR" .... If the required information is triggered by a specific event, such as a suspend and then resume, do not modify [.filename]#/boot/loader.conf#. Instead, use `sysctl` to specify the layer and level after booting and preparing the system for the specific event. The variables which can be set using `sysctl` are named the same as the tunables in [.filename]#/boot/loader.conf#. Once the debugging information is gathered, it can be sent to {freebsd-acpi} so that it can be used by the FreeBSD ACPI maintainers to identify the root cause of the problem and to develop a solution. [NOTE] ==== Before submitting debugging information to this mailing list, ensure the latest BIOS version is installed and, if available, the embedded controller firmware version. ==== When submitting a problem report, include the following information: * Description of the buggy behavior, including system type, model, and anything that causes the bug to appear. Note as accurately as possible when the bug began occurring if it is new. * The output of `dmesg` after running `boot -v`, including any error messages generated by the bug. * The `dmesg` output from `boot -v` with ACPI disabled, if disabling ACPI helps to fix the problem. * Output from `sysctl hw.acpi`. This lists which features the system offers. * The URL to a pasted version of the system's ASL. Do _not_ send the ASL directly to the list as it can be very large. Generate a copy of the ASL by running this command: + [source,shell] .... # acpidump -dt > name-system.asl .... + Substitute the login name for _name_ and manufacturer/model for _system_. For example, use [.filename]#njl-FooCo6000.asl#. Most FreeBSD developers watch the {freebsd-current}, but one should submit problems to {freebsd-acpi} to be sure it is seen. Be patient when waiting for a response. If the bug is not immediately apparent, submit a bug report. When entering a PR, include the same information as requested above. This helps developers to track the problem and resolve it. Do not send a PR without emailing {freebsd-acpi} first as it is likely that the problem has been reported before. [[ACPI-References]] === References More information about ACPI may be found in the following locations: * The FreeBSD ACPI Mailing List Archives (https://lists.freebsd.org/pipermail/freebsd-acpi/[https://lists.freebsd.org/pipermail/freebsd-acpi/]) -* The ACPI 2.0 Specification (http://acpi.info/spec.htm[http://acpi.info/spec.htm]) +* The https://uefi.org/specifications#ACPI[ACPI Specification] * man:acpi[4], man:acpi_thermal[4], man:acpidump[8], man:iasl[8], and man:acpidb[8] diff --git a/documentation/content/pt-br/books/handbook/config/_index.adoc b/documentation/content/pt-br/books/handbook/config/_index.adoc index 5552030259..e3623f805f 100644 --- a/documentation/content/pt-br/books/handbook/config/_index.adoc +++ b/documentation/content/pt-br/books/handbook/config/_index.adoc @@ -1,1528 +1,1528 @@ --- title: Capítulo 11. Configuração e Ajuste part: Parte III. Administração do Sistema prev: books/handbook/partiii next: books/handbook/boot showBookMenu: true weight: 15 path: "/books/handbook/" --- [[config-tuning]] = Configuração e Ajuste :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 11 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/config/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[config-synopsis]] == Sinopse Um dos aspectos importantes do FreeBSD é a configuração adequada do sistema. Este capítulo explica muito do processo de configuração do FreeBSD, incluindo alguns dos parâmetros que podem ser configurados para ajustar um sistema FreeBSD. Depois de ler este capítulo, você saberá: * O básico da configuração do [.filename]#rc.conf# e dos scripts de inicialização [.filename]#/usr/local/etc/rc.d#. * Como configurar e testar uma placa de rede. * Como configurar hosts virtuais em dispositivos de rede. * Como usar os vários arquivos de configuração em [.filename]#/etc#. * Como ajustar o FreeBSD usando variáveis man:sysctl[8]. * Como ajustar o desempenho do disco e modificar as limitações do kernel. Antes de ler este capítulo, você deve: * Entender os fundamentos do UNIX(TM) e do FreeBSD (crossref:basics[basics, Fundamentos do FreeBSD]). * Estar familiarizado com os conceitos básicos de configuração e compilação do kernel (crossref:kernelconfig[kernelconfig, Configurando o kernel do FreeBSD]). [[configtuning-starting-services]] == Inicialização de Serviços Muitos usuários instalam software de terceiros no FreeBSD a partir da coleção de Ports e precisam que os serviços instalados sejam iniciados durante a inicialização do sistema. Serviços como package:mail/postfix[] ou package:www/apache22[] são apenas dois dos muitos pacotes de software que podem ser iniciados durante a inicialização do sistema. Esta seção explica os procedimentos disponíveis para iniciar o software de terceiros. No FreeBSD, a maioria dos serviços incluídos, como o man:cron[8], são iniciados através dos scripts de inicialização do sistema. === Configuração Estendida dos Aplicativos Agora que o FreeBSD inclui o [.filename]#rc.d#, a configuração da inicialização do aplicativo é mais fácil e fornece mais recursos. Usando as palavras-chave discutidas em <>, os aplicativos podem ser configurados para iniciar depois de certos outros serviços e flags extras poderem ser passadas através do [.filename]#/etc/rc.conf# no lugar de sinalizadores codificados no script de inicialização. Um script básico pode ser semelhante ao seguinte: [.programlisting] .... #!/bin/sh # # PROVIDE: utility # REQUIRE: DAEMON # KEYWORD: shutdown . /etc/rc.subr name=utility rcvar=utility_enable command="/usr/local/sbin/utility" load_rc_config $name # # DO NOT CHANGE THESE DEFAULT VALUES HERE # SET THEM IN THE /etc/rc.conf FILE # utility_enable=${utility_enable-"NO"} pidfile=${utility_pidfile-"/var/run/utility.pid"} run_rc_command "$1" .... Este script irá garantir que o `utilitário` fornecido será iniciado após o pseudo-serviço `DAEMON`. Ele também fornece um método para definir e rastrear o ID do processo (PID). Esta aplicação poderia então ter a seguinte linha colocada no [.filename]#/etc/rc.conf#: [.programlisting] .... utility_enable="YES" .... Este método permite a manipulação mais fácil de argumentos de linha de comando, inclusão das funções padrões fornecidas em [.filename]#/etc/rc.subr#, compatibilidade com o man:rcorder[8], e fornece uma configuração mais fácil via [.filename]#rc.conf#. === Usando o Services para Inicializar Serviços Outros serviços podem ser iniciados usando o man:inetd[8]. O uso do man:inetd[8] e sua configuração é descrita em profundidade em crossref:network-servers[network-inetd,O super-servidor inetd]. Em alguns casos, pode fazer mais sentido usar o man:cron[8] para iniciar os serviços do sistema. Esta abordagem tem várias vantagens, pois o man:cron[8] executa estes processos como o proprietário do man:crontab[5]. Isto permite que usuários regulares iniciem e mantenham seus próprios aplicativos. O recurso `@reboot` do man:cron[8], pode ser usado no lugar da especificação de hora. Isso faz com que o job seja executado quando man:cron[8] é iniciado, normalmente durante a inicialização do sistema. [[configtuning-cron]] == Configurando o man:cron[8] Um dos utilitários mais úteis no FreeBSD é o cron. Este utilitário é executado em segundo plano e verifica regularmente o [.filename]#/etc/crontab# para que as tarefas sejam executadas e procura [.filename]#/var/cron/tabs# para arquivos crontab personalizados. Estes arquivos são usados para planejar tarefas que o cron executa nos horários especificados. Cada entrada em um crontab define uma tarefa para ser executada e é conhecida como uma _tarefa do cron_. Dois tipos diferentes de arquivos de configuração são usados: o crontab do sistema, que não deve ser modificado, e crontabs de usuário, que podem ser criados e editados conforme necessário. O formato usado por esses arquivos está documentado em man:crontab[5]. O formato do sistema crontab, [.filename]#/etc/crontab# inclui uma coluna `who` que não existe nos crontabs de usuário. No crontab do sistema , o cron executa o comando como o usuário especificado nesta coluna. Em um crontab de usuário, todos os comandos são executados como o usuário que criou o crontab. Os crontabs de usuário permitem que usuários individuais programem suas próprias tarefas. O usuário `root` também pode ter um [.filename]#crontab# de usuário que pode ser usado para agendar tarefas que não existem no [.filename]#crontab# do sistema . Aqui está uma entrada de amostra do crontab do sistema, [.filename]#/etc/crontab#: [.programlisting] .... # /etc/crontab - root's crontab for FreeBSD # # $FreeBSD: head/pt_BR.ISO8859-1/books/handbook/book.xml 53984 2020-03-15 16:03:31Z dbaio $ ## <.> SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin <.> # #minute hour mday month wday who command <.> # */5 * * * * root /usr/libexec/atrun <.> .... <.> Linhas que começam com o caractere `#` são comentários. Um comentário pode ser colocado no arquivo como um lembrete do que uma ação faz e do porque a sua execução é desejada. Comentários não podem estar na mesma linha que um comando ou então serão interpretados como parte do comando; eles devem estar em uma nova linha. Linhas em branco são ignoradas. <.> O caractere igual (`=`) é usado para definir qualquer configuração de ambiente. Neste exemplo, ele é usado para definir o `SHELL` e o `PATH`. Se o `SHELL` for omitido, o cron usará o shell Bourne padrão. Se o `PATH` for omitido, o caminho completo deverá ser fornecido ao comando ou script a ser executado. <.> Esta linha define os sete campos usados em um crontab do sistema: `minute`, `hora`, `mday`, `month`, `wday`, `who` e `command`. O campo `minute` é o tempo em minutos quando o comando especificado será executado, a `hour` é a hora em que o comando especificado será executado, o `mday` é o dia do mês, `month` é o mês e `wday` é o dia da semana. Estes campos devem ser valores numéricos, representando o relógio de vinte e quatro horas, ou um `*`, representando todos os valores desse campo. O campo `who` existe somente no crontab do sistema e especifica com qual usuário o comando deve ser executado. O último campo é o comando a ser executado. <.> Esta entrada define os valores para este trabalho do cron. O `*/5`, seguido por vários outros caracteres `*`, especifica que `/usr/libexec/atrun` é invocado pelo `root` a cada cinco minutos de cada hora, de cada dia e dia da semana, de cada mês.Comandos podem incluir qualquer número de opções. No entanto, os comandos que se estendem a várias linhas precisam ser quebrados com o caractere de continuação da barra invertida "\". [[configtuning-installcrontab]] === Criando um Crontab de Usuário Para criar um crontab de usuário, invoque o `crontab` no modo editor: [source,shell] .... % crontab -e .... Isto irá abrir o crontab do usuário usando o editor de texto padrão. A primeira vez que um usuário executa este comando, ele abre um arquivo vazio. Depois que um usuário cria um crontab, esse comando abrirá este arquivo para edição. É útil adicionar estas linhas a parte superior do arquivo crontab para configurar as variáveis de ambiente e lembrar os significados dos campos no crontab: [.programlisting] .... SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin # Order of crontab fields # minute hour mday month wday command .... Em seguida, adicione uma linha para cada comando ou script a ser executado, especificando o horário para executar o comando. Este exemplo executa o script de shell Bourne personalizado especificado todos os dias às duas da tarde. Como o caminho para o script não está especificado em `PATH`, o caminho completo para o script é fornecido: [.programlisting] .... 0 14 * * * /usr/home/dru/bin/mycustomscript.sh .... [TIP] ==== Antes de usar um script personalizado, verifique se ele é executável e teste-o com o conjunto limitado de variáveis de ambiente definidas pelo cron. Para replicar o ambiente que seria usado para executar a entrada do cron acima, use: [.programlisting] .... env -i SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin HOME=/home/dru LOGNAME=dru /usr/home/dru/bin/mycustomscript.sh .... O ambiente definido pelo cron é discutido em man:crontab[5]. Verificar se os scripts operam corretamente em um ambiente cron é especialmente importante se incluírem quaisquer comandos que excluam arquivos usando curingas. ==== Quando terminar de editar o crontab, salve o arquivo. Ele será instalado automaticamente e o cron lerá o crontab e executará seus cron jobs nos horários especificados. Para listar as tarefas agendadas em um crontab, use este comando: [source,shell] .... % crontab -l 0 14 * * * /usr/home/dru/bin/mycustomscript.sh .... Para remover todas as tarefas cron em um crontab de usuário: [source,shell] .... % crontab -r remove crontab for dru? y .... [[configtuning-rcd]] == Gerenciando Serviços no FreeBSD O FreeBSD usa o sistema man:rc[8] de scripts de inicialização durante a inicialização do sistema e para gerenciar serviços. Os scripts listados em [.filename]#/etc/rc.d# fornecem serviços básicos que podem ser controlados com `start`, `stop` e `restart` opções para man:service[8]. Por exemplo, man:sshd[8] pode ser reiniciado com o seguinte comando: [source,shell] .... # service sshd restart .... Este procedimento pode ser usado para iniciar serviços em um sistema em execução. Os serviços serão iniciados automaticamente no momento da inicialização, conforme especificado em man:rc.conf[5]. Por exemplo, para ativar o man:natd[8] na inicialização do sistema, adicione a seguinte linha ao [.filename]#/etc/rc.conf#: [.programlisting] .... natd_enable="YES" .... Se uma linha `natd_enable="NO"` já estiver presente, altere o `NO` para `YES`. Os scripts man:rc[8] carregarão automaticamente todos os serviços dependentes durante a próxima inicialização, conforme descrito abaixo. Como o sistema man:rc[8] é destinado principalmente a iniciar e parar serviços na inicialização do sistema e no tempo de desligamento, o `start`, as opções `stop` e `restart` somente executarão suas ações se a variável apropriada estiver configurada no [.filename]#/etc/rc.conf#. Por exemplo, o `sshd restart` só funcionará se `sshd_enable` estiver definido como `YES` em [.filename]#/etc/rc.conf#. Para `iniciar`, `parar` ou `reiniciar` um serviço independente das configurações em [.filename]#/etc/rc.conf#, estes comandos deve ser prefixado com "one". Por exemplo, para reiniciar man:sshd[8] independentemente da configuração atual do [.filename]#/etc/rc.conf#, execute o seguinte comando: [source,shell] .... # service sshd onerestart .... Para verificar se um serviço está habilitado em [.filename]#/etc/rc.conf#, execute o script apropriado man:rc[8] com `rcvar`. Este exemplo verifica se o man:sshd[8] está habilitado no [.filename]#/etc/rc.conf#: [source,shell] .... # service sshd rcvar # sshd # sshd_enable="YES" # (default: "") .... [NOTE] ==== A linha `# sshd` é gerada pelo comando acima, não pelo console do `root`. ==== Para determinar se um serviço está ou não em execução, use `status`. Por exemplo, para verificar se o man:sshd[8] está em execução: [source,shell] .... # service sshd status sshd is running as pid 433. .... Em alguns casos, também é possível fazer o `reload` denum serviço. Isso tenta enviar um sinal para um serviço individual, forçando o serviço a recarregar seus arquivos de configuração. Na maioria dos casos, isso significa enviar ao serviço um sinal `SIGHUP`. O suporte para esse recurso não está incluído para todos os serviços. O sistema man:rc[8] é usado para serviços de rede e também contribui para a maior parte da inicialização do sistema. Por exemplo, quando o script [.filename]#/etc/rc.d/bgfsck# é executado, ele imprime a seguinte mensagem: [source,shell] .... Starting background file system checks in 60 seconds. .... Esse script é usado para verificações do sistema de arquivos em segundo plano, que ocorrem apenas durante a inicialização do sistema. Muitos serviços do sistema dependem de outros serviços para funcionar corretamente. Por exemplo, o man:yp[8] e outros serviços baseados em RPC podem falhar ao iniciar até que o man:rpcbind[8] seja iniciado. Para resolver esse problema, informações sobre dependências e outros meta-dados são incluídas nos comentários na parte superior de cada script de inicialização. O programa man:rcorder[8] é usado para analisar esses comentários durante a inicialização do sistema para determinar a ordem na qual os serviços do sistema devem ser invocados para satisfazer as dependências. A seguinte palavra-chave deve ser incluída em todos os scripts de inicialização, conforme exigido pelo man:rc.subr[8] para "habilitar" o script de inicialização: * `PROVIDE`: Especifica os serviços que este arquivo fornece. As seguintes palavras-chave podem ser incluídas na parte superior de cada script de inicialização. Eles não são estritamente necessárias, mas são úteis como sugestões para man:rcorder[8]: * `REQUIRE`: lista os serviços necessários para este serviço. O script que contém esta palavra chave será executado _após_ os serviços especificados. * `BEFORE`: lista os serviços que dependem deste serviço. O script que contém esta palavra chave será executado _antes_ dos serviços especificados. Ao definir cuidadosamente essas palavras-chave para cada script de inicialização, um administrador passa a ter um nível refinado de controle da ordem de inicialização dos scripts, sem a necessidade dos "runlevels" usados por alguns sistemas operacionais UNIX(TM). Informações adicionais podem ser encontradas em man:rc[8] e man:rc.subr[8]. Consulte extref:{rc-scripting}[este artigo] para obter instruções sobre como criar um script man:rc[8] personalizado. [[configtuning-core-configuration]] === Gerenciando a configuração específica do sistema A localização principal das informações de configuração do sistema é arquivo [.filename]#/etc/rc.conf#. Este arquivo contém uma ampla gama de informações de configuração e é lido na inicialização do sistema para configurar o sistema. Ele fornece as informações de configuração para os arquivos [.filename]#rc*#. As entradas em [.filename]#/etc/rc.conf# substituem as configurações padrões em [.filename]#/etc/defaults/rc.conf#. O arquivo contendo as configurações padrões não deve ser editado. Ao invés disso, todas as alterações específicas do sistema devem ser feitas em [.filename]#/etc/rc.conf#. Várias estratégias podem ser aplicadas em aplicativos em cluster para separar as configurações que afetam todo o site da configuração específica do sistema para reduzir a sobrecarga de administração. A abordagem recomendada é colocar a configuração específica do sistema em [.filename]#/etc/rc.conf.local#. Por exemplo, estas entradas em [.filename]#/etc/rc.conf# aplicam-se a todos os sistemas: [.programlisting] .... sshd_enable="YES" keyrate="fast" defaultrouter="10.1.1.254" .... Considerando que estas entradas em [.filename]#/etc/rc.conf.local# se aplicam somente a este sistema: [.programlisting] .... hostname="node1.example.org" ifconfig_fxp0="inet 10.1.1.1/8" .... Distribua o [.filename]#/etc/rc.conf# para cada sistema usando um aplicativo como o rsync ou o puppet, enquanto o [.filename]#/etc/rc.conf.local# permanece único. A atualização do sistema não sobrescreverá o [.filename]#/etc/rc.conf#, portanto as informações de configuração do sistema não serão perdidas. [TIP] ==== Ambos [.filename]#/etc/rc.conf# e [.filename]#/etc/rc.conf.local# são analisados pelo man:sh[1]. Isto permite que os operadores do sistema criem cenários de configuração complexos. Consulte man:rc.conf[5] para obter mais informações sobre este tópico. ==== [[config-network-setup]] == Configurando Placas de Interface de Rede Adicionar e configurar uma placa de interface de rede (NIC) é uma tarefa comum para qualquer administrador do FreeBSD. === Localizando o Driver Correto Primeiro, determine o modelo da NIC e o chip utilizado. O FreeBSD suporta uma ampla variedade de NICs. Verifique a lista de compatibilidade de hardware para a release do FreeBSD para ver se a NIC é suportada. Se a NIC é suportada, determine o nome do driver do FreeBSD para a NIC. Consulte [.filename]#/usr/src/sys/conf/NOTES# e [.filename]#/usr/src/sys/arch/conf/NOTES# para a lista de Drivers NIC com algumas informações sobre os chipsets suportados. Em caso de dúvida, leia a página de manual do driver, pois ele fornecerá mais informações sobre o hardware suportado e quaisquer limitações conhecidas do driver. Os drivers para as NICs comuns já estão presentes no kernel [.filename]#GENERIC#, o que significa que a NIC deve ser verificada durante a inicialização. As mensagens de inicialização do sistema podem ser visualizadas digitando `more /var/run/dmesg.boot` e usando a barra de espaço para percorrer o texto. Neste exemplo, duas NICs Ethernet que utilizam o driver man:dc[4] estão presentes no sistema: [source,shell] .... dc0: <82c169 PNIC 10/100BaseTX> port 0xa000-0xa0ff mem 0xd3800000-0xd38 000ff irq 15 at device 11.0 on pci0 miibus0: on dc0 bmtphy0: PHY 1 on miibus0 bmtphy0: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc0: Ethernet address: 00:a0:cc:da:da:da dc0: [ITHREAD] dc1: <82c169 PNIC 10/100BaseTX> port 0x9800-0x98ff mem 0xd3000000-0xd30 000ff irq 11 at device 12.0 on pci0 miibus1: on dc1 bmtphy1: PHY 1 on miibus1 bmtphy1: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc1: Ethernet address: 00:a0:cc:da:da:db dc1: [ITHREAD] .... Se o driver da NIC não estiver presente em [.filename]#GENERIC#, mas houver um driver disponível, o driver precisará ser carregado antes que a NIC possa ser configurada e usada. Isso pode ser feito de duas maneiras: * A maneira mais fácil é carregar um módulo do kernel para a NIC usando o man:kldload[8]. Para carregar automaticamente o driver no momento da inicialização, adicione a linha apropriada ao [.filename]#/boot/loader.conf#. Nem todos os drivers NIC estão disponíveis como módulos. * Como alternativa, compile estaticamente o suporte para a NIC em um kernel personalizado. Consulte [.filename]#/usr/src/sys/conf/NOTES#, [.filename]#/usr/src/sys/arch/conf/NOTES# e a página de manual do driver para determinar qual linha adicionar ao arquivo de configuração do kernel personalizado. Para mais informações sobre como recompilar o kernel, consulte crossref:kernelconfig[kernelconfig, Configurando o kernel do FreeBSD]. Se a NIC foi detectada na inicialização, o kernel não precisa ser recompilado. [[config-network-ndis]] ==== Utilizando os Drivers Windows(TM)NDIS Infelizmente, ainda existem muitos fornecedores que não fornecem esquemas para seus drivers para a comunidade de código aberto porque consideram essas informações como segredos comerciais. Consequentemente, os desenvolvedores do FreeBSD e de outros sistemas operacionais são deixados com duas opções: desenvolver os drivers por um processo longo e complexo de engenharia reversa ou usar os binários de drivers existentes disponíveis para plataforma Microsoft(TM) Windows(TM). O FreeBSD fornece suporte "nativo" para a especificação de interface de driver de rede (NDIS). Ele inclui o man:ndisgen[8] que pode ser utilizado para converter um driver Windows(TM) XP num formato que pode ser usado no FreeBSD. Como o driver man:ndis[4] usa um binário Windows(TM) XP, ele só é executado em sistemas i386(TM) e amd64. Dispositivos PCI, CardBus, PCMCIA e USB são suportados. Para usar o man:ndisgen[8], três coisas são necessárias: . Código-fonte do kernel do FreeBSD. . Um binário do driver do Windows(TM) XP com uma extensão [.filename]#.SYS#. . Um arquivo de configuração do driver do Windows(TM) XP com uma extensão [.filename]#.INF#. Faça o download dos arquivos [.filename]#.SYS# e [.filename]#.INF# para a NIC específica. Geralmente, eles podem ser encontrados no CD do driver ou no site do fornecedor. Os exemplos a seguir usam o [.filename]#W32DRIVER.SYS# e o [.filename]#W32DRIVER.INF#. A largura do bit do driver deve corresponder à versão do FreeBSD. Para FreeBSD/i386, use um driver de 32 bits Windows(TM). Para o FreeBSD/amd64, é necessário um driver de 64 bits do Windows(TM). O próximo passo é compilar o binário do driver em um módulo do kernel carregável. Como `root`, use man:ndisgen[8]: [source,shell] .... # ndisgen /path/to/W32DRIVER.INF /path/to/W32DRIVER.SYS .... Este comando é interativo e solicita qualquer informação extra necessária. Um novo módulo do kernel será gerado no diretório atual. Use man:kldload[8] para carregar o novo módulo: [source,shell] .... # kldload ./W32DRIVER_SYS.ko .... Além do módulo do kernel gerado, os módulos [.filename]#ndis.ko# e [.filename]#if_ndis.ko# devem ser carregados. Isso deve acontecer automaticamente quando qualquer módulo que dependa do man:ndis[4] for carregado. Caso contrário, carregue-os manualmente, usando os seguintes comandos: [source,shell] .... # kldload ndis # kldload if_ndis .... O primeiro comando carrega o wrapper do driver da miniporta man:ndis[4] e o segundo carrega o driver NIC gerado. Execute o comando man:dmesg[8] para ver se houve algum erro de carregamento. Se tudo correu bem, a saída deve ser semelhante à seguinte: [source,shell] .... ndis0: mem 0xf4100000-0xf4101fff irq 3 at device 8.0 on pci1 ndis0: NDIS API version: 5.0 ndis0: Ethernet address: 0a:b1:2c:d3:4e:f5 ndis0: 11b rates: 1Mbps 2Mbps 5.5Mbps 11Mbps ndis0: 11g rates: 6Mbps 9Mbps 12Mbps 18Mbps 36Mbps 48Mbps 54Mbps .... A partir daqui, o [.filename]#ndis0# pode ser configurado como qualquer outra NIC. Para configurar o sistema para carregar os módulos man:ndis[4] no momento da inicialização, copie o módulo gerado, [.filename]#W32DRIVER_SYS.ko#, para [.filename]#/boot/modules#. Em seguida, adicione a seguinte linha ao [.filename]#/boot/loader.conf#: [.programlisting] .... W32DRIVER_SYS_load="YES" .... === Configurando a placa de rede Quando o driver correto é carregado para a NIC, a placa precisa ser configurada. Ele pode ter sido configurado no momento da instalação por man:bsdinstall[8]. Para exibir a configuração da NIC, digite o seguinte comando: [source,shell] .... % ifconfig dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da inet 192.168.1.3 netmask 0xffffff00 broadcast 192.168.1.255 media: Ethernet autoselect (100baseTX ) status: active dc1: flags=8802 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:db inet 10.0.0.1 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet 10baseT/UTP status: no carrier lo0: flags=8049 metric 0 mtu 16384 options=3 inet6 fe80::1%lo0 prefixlen 64 scopeid 0x4 inet6 ::1 prefixlen 128 inet 127.0.0.1 netmask 0xff000000 nd6 options=3 .... Neste exemplo, os seguintes dispositivos foram exibidos: * [.filename]#dc0#: A primeira interface Ethernet. * [.filename]#dc1#: A segunda interface Ethernet. * [.filename]#lo0#: o dispositivo de loopback. O FreeBSD usa o nome do driver seguido da ordem em que a placa é detectada na inicialização para nomear a NIC. Por exemplo, [.filename]#sis2# é a terceira NIC no sistema usando driver man:sis[4]. Neste exemplo, o [.filename]#dc0# está ativo e em execução. Os principais indicadores são: . `UP` significa que a placa está configurada e pronta. . A placa tem um endereço da Internet (`inet`), `192.168.1.3`. . Ela tem uma máscara de sub-rede válida (`netmask`), onde `0xffffff00` é o mesmo que `255.255.255.0` . . Tem um endereço de broadcast válido, `192.168.1.255`. . O endereço MAC da placa (`ether`) é `00:a0:cc:da:da:da`. . A seleção de mídia física está no modo de seleção automática (`media:Ethernet autoselect (100baseTX )`). Neste exemplo, o [.filename]#dc1# está configurado para ser executado com a mídia `10baseT/UTP`. Para obter mais informações sobre tipos de mídia disponíveis para um driver, consulte sua página de manual. . O status do link (`status`) é `active`, indicando que o sinal da portadora foi detectado. Para [.filename]#dc1#, o status `status: no carrier` é normal quando um cabo Ethernet não está conectado à placa. Se a saída man:ifconfig[8] tivesse mostrado algo semelhante a: [source,shell] .... dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da media: Ethernet autoselect (100baseTX ) status: active .... isso indicaria que a placa não foi configurada. A placa deve ser configurada como `root`. A configuração da NIC pode ser realizada a partir da linha de comando com o man:ifconfig[8], mas não persistirá após uma reinicialização, a menos que a configuração também seja adicionada ao [.filename]#/etc/rc.conf#. Se um servidor DHCP estiver presente na LAN, basta adicionar esta linha: [.programlisting] .... ifconfig_dc0="DHCP" .... Substitua _dc0_ com o valor correto para o sistema. A linha adicionada, então, segue as instruções dadas em <>. [NOTE] ==== Se a rede foi configurada durante a instalação, algumas entradas para a NIC podem já estar presentes. Verifique novamente o [.filename]#/etc/rc.conf# antes de adicionar novas linhas. ==== Se não existir um servidor DHCP, a NIC deve ser configurada manualmente. Adicione uma linha para cada NIC presente no sistema, conforme mostrado neste exemplo: [.programlisting] .... ifconfig_dc0="inet 192.168.1.3 netmask 255.255.255.0" ifconfig_dc1="inet 10.0.0.1 netmask 255.255.255.0 media 10baseT/UTP" .... Substitua [.filename]#dc0# e [.filename]#dc1# e as informações de endereço IP com os valores corretos para o sistema. Consulte a man page do driver, man:ifconfig[8] e man:rc.conf[5] para maiores detalhes sobre as opções permitidas e a sintaxe de [.filename]#/etc/rc.conf#. Se a rede não estiver usando DNS, edite o [.filename]#/etc/hosts# para adicionar os nomes e endereços IP dos hosts na LAN, se eles ainda não estiverem lá. Para maiores informações, consulte man:hosts[5] e [.filename]#/usr/shared/examples/etc/hosts#. [NOTE] ==== Se não houver um servidor DHCP e o acesso à Internet for necessário, configure manualmente o gateway padrão e o nameserver: [source,shell] .... # echo 'defaultrouter="your_default_router"' >> /etc/rc.conf # echo 'nameserver your_DNS_server' >> /etc/resolv.conf .... ==== [[config-network-testing]] === Teste e solução de problemas Uma vez que as alterações necessárias no [.filename]#/etc/rc.conf# sejam salvas, uma reinicialização pode ser usada para testar a configuração de rede e verificar se o sistema é reiniciado sem nenhum erro. Como alternativa, aplique as configurações ao sistema de rede com este comando: [source,shell] .... # service netif restart .... [NOTE] ==== Se um gateway padrão foi configurado no [.filename]#/etc/rc.conf#, também execute este comando: [source,shell] .... # service routing restart .... ==== Uma vez que o sistema de rede tiver sido reiniciado, teste as NIC. ==== Testando uma placa Ethernet Para verificar se uma placa Ethernet está configurada corretamente, execute um man:ping[8] na própria interface e, em seguida, man:ping[8] outra máquina na LAN: [source,shell] .... % ping -c5 192.168.1.3 PING 192.168.1.3 (192.168.1.3): 56 data bytes 64 bytes from 192.168.1.3: icmp_seq=0 ttl=64 time=0.082 ms 64 bytes from 192.168.1.3: icmp_seq=1 ttl=64 time=0.074 ms 64 bytes from 192.168.1.3: icmp_seq=2 ttl=64 time=0.076 ms 64 bytes from 192.168.1.3: icmp_seq=3 ttl=64 time=0.108 ms 64 bytes from 192.168.1.3: icmp_seq=4 ttl=64 time=0.076 ms --- 192.168.1.3 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.074/0.083/0.108/0.013 ms .... [source,shell] .... % ping -c5 192.168.1.2 PING 192.168.1.2 (192.168.1.2): 56 data bytes 64 bytes from 192.168.1.2: icmp_seq=0 ttl=64 time=0.726 ms 64 bytes from 192.168.1.2: icmp_seq=1 ttl=64 time=0.766 ms 64 bytes from 192.168.1.2: icmp_seq=2 ttl=64 time=0.700 ms 64 bytes from 192.168.1.2: icmp_seq=3 ttl=64 time=0.747 ms 64 bytes from 192.168.1.2: icmp_seq=4 ttl=64 time=0.704 ms --- 192.168.1.2 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.700/0.729/0.766/0.025 ms .... Para testar a resolução da rede, use o nome do host em vez do endereço IP. Se não houver nenhum servidor DNS na rede, o [.filename]#/etc/hosts# deve ser configurado primeiro. Para este propósito, edite o [.filename]#/etc/hosts# para adicionar os nomes e os endereços IP dos hosts na LAN, se eles ainda não estiverem lá . Para maiores informações, consulte man:hosts[5] e [.filename]#/usr/shared/examples/etc/hosts#. ==== Solução de problemas Ao solucionar problemas de configurações de hardware e software, verifique primeiro as coisas simples. O cabo de rede está conectado? Os serviços de rede estão configurados corretamente? O firewall está configurado corretamente? A NIC é suportada pelo FreeBSD? Antes de enviar um relatório de bug, sempre verifique as Notas de Hardware, atualize a versão do FreeBSD para a versão mais recente do STABLE, verifique os arquivos da lista de discussão e pesquise na Internet. Se a placa funcionar, mas o desempenho for ruim, leia man:tuning[7]. Além disso, verifique a configuração da rede, pois configurações de rede incorretas podem causar conexões lentas. Alguns usuários experimentam uma ou duas mensagens de `device timeout`, o que é normal para algumas placas. Se eles continuarem ou forem incômodos, verifique se o dispositivo está em conflito com outro. Verifique novamente as conexões dos cabos. Considere tentar outra placa. Para resolver erros de `watchdog timeout`, primeiro verifique o cabo de rede. Muitas placas requerem um slot PCI que suporte a masterização de barramento. Em algumas placas-mãe antigas, apenas um slot PCI permite, normalmente o slot 0. Verifique a NIC e a documentação da placa-mãe para determinar se esse pode ser o problema. As mensagens `No route to host` ocorrem se o sistema não puder rotear um pacote para o host de destino. Isso pode acontecer se nenhuma rota padrão for especificada ou se um cabo for desconectado. Verifique a saída do `netstat -rn` e certifique-se de que haja uma rota válida para o host. Se não houver, leia crossref:advanced-networking[network-routing,Gateways e Rotas]. As mensagens de erro `ping: sendto: Permission denied` são geralmente causadas por um firewall mal configurado. Se um firewall está habilitado no FreeBSD, mas nenhuma regra foi definida, a política padrão é negar todo o tráfego, mesmo o man:ping[8]. Consulte crossref:firewalls[firewalls, Firewalls] para maiores informações. Às vezes, o desempenho da placa é ruim ou abaixo da média. Nesses casos, tente configurar o modo de seleção de mídia de `autoselect` para a seleção de mídia correta. Embora isso funcione para a maioria dos hardwares, isso pode ou não resolver o problema. Novamente, verifique todas as configurações de rede e consulte man:tuning[7]. [[configtuning-virtual-hosts]] == Hosts Virtuais Um uso comum do FreeBSD é a hospedagem de sites virtuais, onde um servidor aparece na rede como muitos servidores. Isso é conseguido atribuindo vários endereços de rede a uma única interface. Uma determinada interface de rede tem um endereço "real" e pode ter qualquer número de endereços "alias". Esses aliases são normalmente adicionados colocando entradas de alias no [.filename]#/etc/rc.conf#, como mostrado neste exemplo: [.programlisting] .... ifconfig_fxp0_alias0="inet xxx.xxx.xxx.xxx netmask xxx.xxx.xxx.xxx" .... As entradas de alias devem começar com `alias_0_` usando um número sequencial como `alias0`, `alias1` e assim por diante. O processo de configuração será interrompido no primeiro número ausente. O cálculo de máscaras de alias é importante. Para uma determinada interface, deve haver um endereço que represente corretamente a máscara de rede da rede. Qualquer outro endereço dentro dessa rede deve ter uma máscara de rede toda de ``1``s, expressa como `255.255.255.255` ou `0xffffffff`. Por exemplo, considere o caso em que a interface [.filename]#fxp0# está conectada a duas redes: `10.1.1.0` com uma máscara de rede de `255.255.255.0` e `202.0.75.16` com uma máscara de rede de `255.255.255.240`. O sistema deve ser configurado para aparecer nos intervalos `10.1.1.1` até `10.1.1.5` e `202.0.75.17` até `202.0.75.20`. Somente o primeiro endereço em um determinado intervalo de rede deve ter uma máscara de rede real. Todo o resto de (`10.1.1.2` até `10.1.1.5` e de `202.0.75.18` até `202.0.75.20`) deve ser configurado com uma máscara de rede `255.255.255.255`. As seguintes entradas [.filename]#/etc/rc.conf# configuram o adaptador corretamente para este cenário: [.programlisting] .... ifconfig_fxp0="inet 10.1.1.1 netmask 255.255.255.0" ifconfig_fxp0_alias0="inet 10.1.1.2 netmask 255.255.255.255" ifconfig_fxp0_alias1="inet 10.1.1.3 netmask 255.255.255.255" ifconfig_fxp0_alias2="inet 10.1.1.4 netmask 255.255.255.255" ifconfig_fxp0_alias3="inet 10.1.1.5 netmask 255.255.255.255" ifconfig_fxp0_alias4="inet 202.0.75.17 netmask 255.255.255.240" ifconfig_fxp0_alias5="inet 202.0.75.18 netmask 255.255.255.255" ifconfig_fxp0_alias6="inet 202.0.75.19 netmask 255.255.255.255" ifconfig_fxp0_alias7="inet 202.0.75.20 netmask 255.255.255.255" .... Uma maneira mais simples de expressar isso é com uma lista separada por espaço de intervalos de endereços IP. O primeiro endereço receberá a máscara de sub-rede indicada e os endereços adicionais terão uma máscara de sub-rede `255.255.255.255`. [.programlisting] .... ifconfig_fxp0_aliases="inet 10.1.1.1-5/24 inet 202.0.75.17-20/28" .... [[configtuning-syslog]] == Configurando o log do sistema Gerar e ler logs do sistema é um aspecto importante da administração do sistema. As informações nos registros do sistema podem ser usadas para detectar problemas de hardware e software, bem como erros de configuração dos aplicativos e do sistema. Essas informações também desempenham um papel importante na auditoria de segurança e na resposta a incidentes. A maioria dos daemons e aplicativos do sistema geram entradas de log. O FreeBSD fornece um registrador de sistema, o syslogd, para gerenciar o registro. Por padrão, o syslogd é iniciado quando o sistema é inicializado. Isto é controlado pela variável `syslogd_enable` no [.filename]#/etc/rc.conf#. Existem vários argumentos de aplicação que podem ser definidos usando `syslogd_flags` no [.filename]#/etc/rc.conf#. Consulte man:syslogd[8] para obter maiores informações sobre os argumentos disponíveis. Esta seção descreve como configurar o criador de logs do sistema FreeBSD para log local e remoto e como executar a rotação de log e o gerenciamento de log. === Configurando os logs locais O arquivo de configuração, [.filename]#/etc/syslog.conf#, controla o que o syslogd faz com as entradas de log à medida que são recebidas. Existem vários parâmetros para controlar o tratamento de eventos recebidos. O _facility_ descreve qual subsistema gerou a mensagem, como o kernel ou um daemon, e o _level_ descreve a gravidade do evento que ocorreu. Isso possibilita configurar onde uma mensagem de log é registrada, dependendo da instalação e do nível. Também é possível executar uma ação dependendo do aplicativo que enviou a mensagem e, no caso de log remoto, o nome do host da máquina que gera o evento de log. Este arquivo de configuração contém uma linha por ação, em que a sintaxe de cada linha é um campo seletor seguido por um campo de ação. A sintaxe do campo seletor é _facility.level_, que corresponderá às mensagens de log de _facility_ no nível _level_ ou superior. Também é possível adicionar um sinalizador de comparação opcional antes do nível para especificar mais precisamente o que está registrado. Vários campos seletores podem ser usados para a mesma ação e são separados por um ponto-e-vírgula (`;`). Usar `*` irá corresponder a tudo. O campo de ação indica para onde enviar a mensagem de log, como para um arquivo ou host de log remoto. Por exemplo, aqui está o [.filename]#syslog.conf# padrão do FreeBSD: [.programlisting] .... # $FreeBSD: head/pt_BR.ISO8859-1/books/handbook/book.xml 53984 2020-03-15 16:03:31Z dbaio $ # # Spaces ARE valid field separators in this file. However, # other *nix-like systems still insist on using tabs as field # separators. If you are sharing this file between systems, you # may want to use only tabs as field separators here. # Consult the syslog.conf(5) manpage. *.err;kern.warning;auth.notice;mail.crit /dev/console *.notice;authpriv.none;kern.debug;lpr.info;mail.crit;news.err /var/log/messages security.* /var/log/security auth.info;authpriv.info /var/log/auth.log mail.info /var/log/maillog lpr.info /var/log/lpd-errs ftp.info /var/log/xferlog cron.* /var/log/cron !-devd *.=debug /var/log/debug.log *.emerg * # uncomment this to log all writes to /dev/console to /var/log/console.log #console.info /var/log/console.log # uncomment this to enable logging of all log messages to /var/log/all.log # touch /var/log/all.log and chmod it to mode 600 before it will work #*.* /var/log/all.log # uncomment this to enable logging to a remote loghost named loghost #*.* @loghost # uncomment these if you're running inn # news.crit /var/log/news/news.crit # news.err /var/log/news/news.err # news.notice /var/log/news/news.notice # Uncomment this if you wish to see messages produced by devd # !devd # *.>=info !ppp *.* /var/log/ppp.log !* .... Neste exemplo: * A linha 8 combina todas as mensagens com um nível de `err` ou superior, bem como `kern.warning`, `auth.notice` e `mail.crit`, e envia essas mensagens de log para o console ([.filename]#/dev/console#). * A linha 12 combina todas as mensagens do recurso `mail` no nível `info` ou acima e registra as mensagens em [.filename]#/var/log/maillog#. * A linha 17 usa um sinalizador de comparação (`=`) para corresponder apenas as mensagens no nível `debug` e registrá-las em [.filename]#/var/log/debug.log#. * A linha 33 é um exemplo de uso de uma especificação de programa. Isso faz com que as regras que a seguem apenas sejam válidas para o programa especificado. Neste caso, somente as mensagens geradas pelo ppp são registradas em [.filename]#/var/log/ppp.log#. Os níveis disponíveis, na ordem dos mais para o menos críticos, são `emerg`, `alert`, `crit`, `err`, `warning`, `notice`, `info`, and `debug`. As facilities, em nenhuma ordem particular, são `auth`, `authpriv`, `console`, `cron`, `daemon`, `ftp`, `kern`, `lpr`, `mail`, `mark`, `news`, `security`, `syslog`, `user`, `uucp`, and `local0` through `local7`. Esteja ciente de que outros sistemas operacionais podem ter recursos diferentes. Para registrar tudo do nível `notice` e superior para [.filename]#/var/log/daemon.log#, adicione a seguinte entrada: [.programlisting] .... daemon.notice /var/log/daemon.log .... Para obter mais informações sobre os diferentes níveis e facilities, consulte man:syslog[3] e man:syslogd[8]. Para maiores informações sobre [.filename]#/etc/syslog.conf#, sua sintaxe e exemplos de uso mais avançados, veja man:syslog.conf[5]. === Gerenciamento de log e rotação Os arquivos de log podem crescer rapidamente, ocupando espaço em disco e dificultando a localização de informações úteis. O gerenciamento de log tenta atenuar isso. No FreeBSD, o newsyslog é usado para gerenciar arquivos de log. Este programa interno rotaciona e comprime periodicamente arquivos de log e, opcionalmente, cria arquivos de log ausentes e sinaliza os programas quando os arquivos de log são movidos. Os arquivos de log podem ser gerados pelo syslogd ou por qualquer outro programa que gere arquivos de log. Enquanto o newsyslog é normalmente executado a partir do man:cron[8], ele não é um daemon do sistema. Na configuração padrão, ele é executado a cada hora. Para saber quais ações executar, o newsyslog lê seu arquivo de configuração, [.filename]#/etc/newsyslog.conf#. Este arquivo contém uma linha para cada arquivo de log que o newsyslog gerencia. Cada linha indica o proprietário do arquivo, suas permissões, quando rotacionar esse arquivo, flags opcionais que afetam a rotação do log, como compactação, e programas para sinalizar quando o log é rotacionado. Aqui está a configuração padrão no FreeBSD: [.programlisting] .... # configuration file for newsyslog # $FreeBSD: head/pt_BR.ISO8859-1/books/handbook/book.xml 53984 2020-03-15 16:03:31Z dbaio $ # # Entries which do not specify the '/pid_file' field will cause the # syslogd process to be signalled when that log file is rotated. This # action is only appropriate for log files which are written to by the # syslogd process (ie, files listed in /etc/syslog.conf). If there # is no process which needs to be signalled when a given log file is # rotated, then the entry for that file should include the 'N' flag. # # The 'flags' field is one or more of the letters: BCDGJNUXZ or a '-'. # # Note: some sites will want to select more restrictive protections than the # defaults. In particular, it may be desirable to switch many of the 644 # entries to 640 or 600. For example, some sites will consider the # contents of maillog, messages, and lpd-errs to be confidential. In the # future, these defaults may change to more conservative ones. # # logfilename [owner:group] mode count size when flags [/pid_file] [sig_num] /var/log/all.log 600 7 * @T00 J /var/log/amd.log 644 7 100 * J /var/log/auth.log 600 7 100 @0101T JC /var/log/console.log 600 5 100 * J /var/log/cron 600 3 100 * JC /var/log/daily.log 640 7 * @T00 JN /var/log/debug.log 600 7 100 * JC /var/log/kerberos.log 600 7 100 * J /var/log/lpd-errs 644 7 100 * JC /var/log/maillog 640 7 * @T00 JC /var/log/messages 644 5 100 @0101T JC /var/log/monthly.log 640 12 * $M1D0 JN /var/log/pflog 600 3 100 * JB /var/run/pflogd.pid /var/log/ppp.log root:network 640 3 100 * JC /var/log/devd.log 644 3 100 * JC /var/log/security 600 10 100 * JC /var/log/sendmail.st 640 10 * 168 B /var/log/utx.log 644 3 * @01T05 B /var/log/weekly.log 640 5 1 $W6D0 JN /var/log/xferlog 600 7 100 * JC .... Cada linha começa com o nome do log a ser rotacionado, seguido opcionalmente por um proprietário e um grupo para arquivos rotacionados e recém-criados. O campo `mode` define as permissões no arquivo de log e `count` indica quantos arquivos de log rotacionados devem ser mantidos. Os campos `size` e `when` informam o newsyslog quando rotacionar o arquivo. Um arquivo de log é rotacionado quando seu tamanho é maior que o campo `size` ou quando o tempo no campo `when` tiver terminado. Um asterisco (`*`) significa que este campo é ignorado. O campo _flags_ fornece instruções adicionais, por exemplo, como compactar o arquivo rotacionado ou criar o arquivo de log se ele estiver ausente. Os dois últimos campos são opcionais e especificam o nome do arquivo de ID de Processo (PID) e um número de sinal para enviar a esse processo quando o arquivo é rotacionado. Para obter maiores informações sobre todos os campos, sinalizadores válidos e como sobre especificar o tempo de rotação, consulte man:newsyslog.conf[5]. Como o newsyslog é executado a partir do man:cron[8], ele não pode rotacionar arquivos com mais frequência do que a que está planejada para ser executada no man:cron[8]. [[network-syslogd]] === Configurando o log remoto Monitorar os arquivos de log de vários hosts pode se tornar difícil à medida que o número de sistemas aumenta. Configurar o log centralizado pode reduzir parte da carga administrativa da administração dos arquivos de log. No FreeBSD, a agregação, a fusão e a rotação centralizada de arquivos de log podem ser configuradas usando o syslogd e o newsyslog. Esta seção demonstra um exemplo de configuração, em que host o `A`, chamado `logserv.example.com`, coletará informações de log para a rede local. O host `B`, denominado `logclient.example.com`, será configurado para transmitir informações de log para o servidor de registro em log. ==== Configuração do servidor de log Um servidor de log é um sistema que foi configurado para aceitar informações de log de outros hosts. Antes de configurar um servidor de log, verifique o seguinte: * Se houver um firewall entre o servidor de log e qualquer cliente de log, certifique-se de que o conjunto de regras do firewall permita a porta 514 do UDP para os clientes e o servidor. * O servidor de log e todas as máquinas clientes devem ter entradas de nome diretas e reversas no DNS local. Se a rede não tiver um servidor DNS, crie entradas no [.filename]#/etc/hosts# de cada sistema. A resolução adequada de nomes é necessária para que as entradas de log não sejam rejeitadas pelo servidor de log. No servidor de log, edite o [.filename]#/etc/syslog.conf# para especificar o nome do cliente para receber as entradas de log, o recurso de log a ser usado e o nome do log para armazenar as entradas de log do host. Este exemplo adiciona o nome do host de `B`, registra todos os recursos e armazena as entradas de log em [.filename]#/var/log/logclient.log#. .Configuração do servidor de log de exemplo [example] ==== [.programlisting] .... +logclient.example.com *.* /var/log/logclient.log .... ==== Ao adicionar vários clientes de log, adicione uma entrada semelhante de duas linhas para cada cliente. Maiores informações sobre os recursos disponíveis podem ser encontradas em man:syslog.conf[5]. Em seguida, configure o [.filename]#/etc/rc.conf#: [.programlisting] .... syslogd_enable="YES" syslogd_flags="-a logclient.example.com -v -v" .... A primeira entrada inicia o syslogd na inicialização do sistema. A segunda entrada permite entradas de log do cliente especificado. A opção `-v -v` aumenta a verbosidade das mensagens registradas. Isso é útil para ajustar os recursos, pois os administradores podem ver o tipo de mensagens que estão sendo registradas em cada facility. Múltiplas opções `-a` podem ser especificadas para permitir o registro de múltiplos clientes. Endereços IP e netblocks inteiros também podem ser especificados. Consulte man:syslogd[8] para obter uma lista completa de opções possíveis. Finalmente, crie o arquivo de log: [source,shell] .... # touch /var/log/logclient.log .... Neste ponto, o syslogd deve ser reiniciado e verificado: [source,shell] .... # service syslogd restart # pgrep syslog .... Se um PID for retornado, o servidor será reiniciado com êxito e a configuração do cliente poderá ser iniciada. Se o servidor não reiniciar, consulte [.filename]#/var/log/messages# para visualizar o erro. ==== Configuração do cliente de log Um cliente de log envia entradas de log para um servidor de log na rede. O cliente também mantém uma cópia local de seus próprios logs. Uma vez que o servidor de log foi configurado, edite o [.filename]#/etc/rc.conf# no cliente de registro: [.programlisting] .... syslogd_enable="YES" syslogd_flags="-s -v -v" .... A primeira entrada ativa o syslogd na inicialização. A segunda entrada impede que os logs sejam aceitos por esse cliente de outros hosts (`-s`) e aumenta a verbosidade das mensagens registradas. Em seguida, defina o servidor de log no [.filename]#/etc/syslog.conf# do cliente. Neste exemplo, todos os facilities registrados são enviados para um sistema remoto, indicado pelo símbolo `@`, com o nome do host especificado: [.programlisting] .... *.* @logserv.example.com .... Depois de salvar a edição, reinicie o syslogd para que as alterações entrem em vigor: [source,shell] .... # service syslogd restart .... Para testar se as mensagens de log estão sendo enviadas pela rede, use o man:logger[1] no cliente para enviar uma mensagem para syslogd: [source,shell] .... # logger "Test message from logclient" .... Esta mensagem agora deve existir tanto no [.filename]#/var/log/messages# do cliente e no [.filename]#/var/log/logclient.log# do servidor de log. ==== Debugando servidores de log Se nenhuma mensagem estiver sendo recebida no servidor de log, a causa provavelmente é um problema de conectividade de rede, um problema de resolução de nome de host ou um erro de digitação em um arquivo de configuração. Para isolar a causa, certifique-se de que o servidor de log e o cliente de log sejam capazes de comunicarem através do `ping` usando o nome do host especificado em seu [.filename]#/etc/rc.conf#. Se isso falhar, verifique o cabeamento da rede, o conjunto de regras do firewall e as entradas de nome de host no servidor DNS ou [.filename]#/etc/hosts# no servidor de log e nos clientes. Repita até que o `ping` seja bem-sucedido em ambos os hosts. Se o `ping` for bem-sucedido em ambos os hosts, mas as mensagens de log ainda não estiverem sendo recebidas, aumente temporariamente o detalhamento do log para diminuir o problema de configuração. No exemplo a seguir, o [.filename]#/var/log/logclient.log# no servidor de log está vazio e o [.filename]#/var/log/messages# no cliente de log não indica uma razão para a falha. Para aumentar a saída de debug, edite a entrada `syslogd_flags` no servidor de log e execute uma reinicialização: [.programlisting] .... syslogd_flags="-d -a logclient.example.com -v -v" .... [source,shell] .... # service syslogd restart .... Dados de debug semelhantes aos seguintes irão aparecer no console imediatamente após a reinicialização: [source,shell] .... logmsg: pri 56, flags 4, from logserv.example.com, msg syslogd: restart syslogd: restarted logmsg: pri 6, flags 4, from logserv.example.com, msg syslogd: kernel boot file is /boot/kernel/kernel Logging to FILE /var/log/messages syslogd: kernel boot file is /boot/kernel/kernel cvthname(192.168.1.10) validate: dgram from IP 192.168.1.10, port 514, name logclient.example.com; rejected in rule 0 due to name mismatch. .... Neste exemplo, as mensagens de log estão sendo rejeitadas devido a um erro de digitação que resulta em uma incompatibilidade de nome de host. O nome do host do cliente deve ser `logclient`, não `logclien`. Corrija o erro de digitação, execute uma reinicialização e verifique os resultados: [source,shell] .... # service syslogd restart logmsg: pri 56, flags 4, from logserv.example.com, msg syslogd: restart syslogd: restarted logmsg: pri 6, flags 4, from logserv.example.com, msg syslogd: kernel boot file is /boot/kernel/kernel syslogd: kernel boot file is /boot/kernel/kernel logmsg: pri 166, flags 17, from logserv.example.com, msg Dec 10 20:55:02 logserv.example.com syslogd: exiting on signal 2 cvthname(192.168.1.10) validate: dgram from IP 192.168.1.10, port 514, name logclient.example.com; accepted in rule 0. logmsg: pri 15, flags 0, from logclient.example.com, msg Dec 11 02:01:28 trhodes: Test message 2 Logging to FILE /var/log/logclient.log Logging to FILE /var/log/messages .... Neste ponto, as mensagens estão sendo recebidas e colocadas corretamente no arquivo correto. ==== Considerações de segurança Como com qualquer serviço de rede, os requisitos de segurança devem ser considerados antes de implementar um servidor de log. Os arquivos de log podem conter dados confidenciais sobre serviços ativados no host local, contas de usuário e dados de configuração. Os dados enviados pela rede do cliente para o servidor não serão criptografados nem protegidos por senha. Se houver necessidade de criptografia, considere o uso do package:security/stunnel[], que transmitirá os dados de log em um túnel criptografado. A segurança local também é um problema. Os arquivos de log não são criptografados durante o uso ou após a rotação do log. Usuários locais podem acessar arquivos de log para obter informações adicionais sobre a configuração do sistema. Definir permissões adequadas nos arquivos de log é crítico. O rotacionador de log integrado, newsyslog, suporta a configuração de permissões em arquivos de log recém-criados e rotacionados. A configuração de arquivos de log no modo `600` deve impedir o acesso indesejado por usuários locais. Consulte man:newsyslog.conf[5] para obter informações adicionais. [[configtuning-configfiles]] == Arquivos de Configuração === Layout do [.filename]#/etc# Existem vários diretórios nos quais as informações de configuração são mantidas. Estes incluem: [.informaltable] [cols="1,1", frame="none"] |=== |[.filename]#/etc# |Informações de configuração específica do sistema genérico. |[.filename]#/etc/defaults# |Versões padrão dos arquivos de configuração do sistema. |[.filename]#/etc/mail# |Configuração extra do man:sendmail[8] e outros arquivos de configuração MTA. |[.filename]#/etc/ppp# |Configuração para ambos os programas, user- e kernel-ppp. |[.filename]#/usr/local/etc# |Arquivos de configuração para aplicativos instalados. Pode conter subdiretórios para cada aplicativo. |[.filename]#/usr/local/etc/rc.d# |scripts man:rc[8] para os aplicativos instalados. |[.filename]#/var/db# |Arquivos de banco de dados específicos do sistema gerados automaticamente, como o banco de dados de pacotes e o banco de dados man:locate[1]. |=== === Hostnames ==== [.filename]#/etc/resolv.conf# Como um sistema FreeBSD acessa o Sistema de Nomes de Domínio da Internet (Internet Domain Name System - DNS) é controlado por man:resolv.conf[5]. As entradas mais comuns para o [.filename]#/etc/resolv.conf# são: [.informaltable] [cols="1,1", frame="none"] |=== |`nameserver` |O endereço IP de um servidor de nomes que o resolvedor deve consultar. Os servidores são consultados na ordem listada com um máximo de três. |`search` |Lista de pesquisa, para busca de nomes de host. Isso é normalmente determinado pelo domínio do nome do host local. |`domain` |O nome do domínio local. |=== Um típico [.filename]#/etc/resolv.conf# é assim: [.programlisting] .... search example.com nameserver 147.11.1.11 nameserver 147.11.100.30 .... [NOTE] ==== Apenas uma das opções `search` e `domain` deve ser usada. ==== Ao usar o DHCP, o man:dhclient[8] geralmente reescreve o [.filename]#/etc/resolv.conf# com informações recebidas do servidor DHCP. ==== [.filename]#/etc/hosts# O [.filename]#/etc/hosts# é um banco de dados de texto simples que funciona em conjunto com o DNS e o NIS para fornecer o nome do host aos mapeamentos de endereços IP. Entradas para computadores locais conectados através de uma LAN podem ser adicionadas a este arquivo para propósitos simplistas de nomeação em vez de configurar um servidor man:named[8]. Além disso, o [.filename]#/etc/hosts# pode ser usado para fornecer um registro local de nomes da Internet, reduzindo a necessidade de consultar servidores DNS externos para nomes comumente acessados. [.programlisting] .... # $FreeBSD: head/pt_BR.ISO8859-1/books/handbook/book.xml 53984 2020-03-15 16:03:31Z dbaio $ # # # Host Database # # This file should contain the addresses and aliases for local hosts that # share this file. Replace 'my.domain' below with the domainname of your # machine. # # In the presence of the domain name service or NIS, this file may # not be consulted at all; see /etc/nsswitch.conf for the resolution order. # # ::1 localhost localhost.my.domain 127.0.0.1 localhost localhost.my.domain # # Imaginary network. #10.0.0.2 myname.my.domain myname #10.0.0.3 myfriend.my.domain myfriend # # According to RFC 1918, you can use the following IP networks for # private nets which will never be connected to the Internet: # # 10.0.0.0 - 10.255.255.255 # 172.16.0.0 - 172.31.255.255 # 192.168.0.0 - 192.168.255.255 # # In case you want to be able to connect to the Internet, you need # real official assigned numbers. Do not try to invent your own network # numbers but instead get one from your network provider (if any) or # from your regional registry (ARIN, APNIC, LACNIC, RIPE NCC, or AfriNIC.) # .... O formato do [.filename]#/etc/hosts# é o seguinte: [.programlisting] .... [Internet address] [official hostname] [alias1] [alias2] ... .... Por exemplo: [.programlisting] .... 10.0.0.1 myRealHostname.example.com myRealHostname foobar1 foobar2 .... Consulte man:hosts[5] para obter maiores informações. [[configtuning-sysctl]] == Efetuando ajustes com o man:sysctl[8] O man:sysctl[8] é usado para fazer mudanças em um sistema FreeBSD em execução. Isso inclui muitas opções avançadas da stack TCP/IP e do sistema de memória virtual as quais podem melhorar drasticamente o desempenho do FreeBSD para um administrador de sistema experiente. Mais de quinhentas variáveis do sistema podem ser lidas e definidas usando o man:sysctl[8]. Em sua essência, o man:sysctl[8] serve duas funções: ler e modificar as configurações do sistema. Para ver todas as variáveis legíveis: [source,shell] .... % sysctl -a .... Para ler uma variável específica, especifique seu nome: [source,shell] .... % sysctl kern.maxproc kern.maxproc: 1044 .... Para definir uma variável específica, use a sintaxe _variable_=_value_: [source,shell] .... # sysctl kern.maxfiles=5000 kern.maxfiles: 2088 -> 5000 .... As configurações das variáveis sysctl são geralmente strings, números ou booleanos, onde um booleano é `1` para sim `0` para não. Para definir automaticamente algumas variáveis sempre que a máquina inicializar, adicione-as ao [.filename]#/etc/sysctl.conf#. Para maiores informações, consulte man:sysctl.conf[5] e <>. [[configtuning-sysctlconf]] === [.filename]#sysctl.conf# O arquivo de configuração para o man:sysctl[8], [.filename]#/etc/sysctl.conf#, se parece muito com o [.filename]#/etc /rc.conf#. Os valores são definidos na forma `variable=value`. Os valores especificados são definidos após o sistema entrar no modo multiusuário. Nem todas as variáveis são configuráveis neste modo. Por exemplo, para desativar o log de saídas de sinais fatais e impedir que os usuários vejam processos iniciados por outros usuários, os seguintes ajustes podem ser configurados em [.filename]#/etc/sysctl.conf#: [.programlisting] .... # Do not log fatal signal exits (e.g., sig 11) kern.logsigexit=0 # Prevent users from seeing information about processes that # are being run under another UID. security.bsd.see_other_uids=0 .... [[sysctl-readonly]] === Variáveis man:sysctl[8] apenas de leitura Em alguns casos, pode ser desejável modificar os valores de variáveis do man:sysctl[8] que são somente de leitura, o que exigirá uma reinicialização do sistema. Por exemplo, em alguns modelos de laptops, o dispositivo man:cardbus[4] não examinará os intervalos de memória e falhará com erros semelhantes a: [source,shell] .... cbb0: Could not map register memory device_probe_and_attach: cbb0 attach returned 12 .... A correção requer a modificação de uma configuração definida por uma variável do man:sysctl[8] que é somente de leitura. Adicione `hw.pci.allow_unsupported_io_range=1` ao arquivo [.filename]#/boot/loader.conf# e reinicie. Agora o man:cardbus[4] deve funcionar corretamente. [[configtuning-disk]] == Otimização de Discos A seção a seguir discutirá vários mecanismos e opções de ajuste que podem ser aplicados a dispositivos de disco. Em muitos casos, discos com partes mecânicas, como unidades SCSI, serão o gargalo que reduz o desempenho geral do sistema. Embora a solução seja instalar uma unidade sem peças mecânicas, como uma unidade de estado sólido, as unidades mecânicas não irão desaparecer num futuro próximo. Quando estiver otimizando discos, é aconselhável utilizar os recursos do comando man:iostat[8] para testar várias mudanças no sistema. Este comando permitirá ao usuário obter informações valiosas sobre o sistema IO. === Variáveis Sysctl ==== `vfs.vmiodirenable` A variável `vfs.vmiodirenable` man:sysctl[8] pode ser definida como `0` (off ) ou `1` (on). Está definida para `1` por padrão. Esta variável controla como os diretórios são armazenados em cache pelo sistema. A maioria dos diretórios é pequena, usando apenas um único fragmento (normalmente 1K) no sistema de arquivos e, normalmente, 512 bytes no cache de buffer. Com esta variável desativada, o cache de buffer armazenará apenas um número fixo de diretórios, mesmo que o sistema tenha uma quantidade enorme de memória. Quando ativado, este man:sysctl[8] permite que o cache de buffer use o cache de página VM para armazenar em cache os diretórios, disponibilizando toda a memória para fazer cache dos diretórios. No entanto, a memória mínima no núcleo usada para armazenar em cache um diretório é o tamanho da página física (geralmente 4K) em vez de 512 bytes. Manter esta opção ativada é recomendado se o sistema estiver executando quaisquer serviços que manipulem um grande número de arquivos. Esses serviços podem incluir caches da web, grandes sistemas de correio e sistemas de notícias. Manter essa opção geralmente não reduz o desempenho, mesmo com a memória desperdiçada, mas deve-se experimentar para descobrir. ==== `vfs.write_behind` A variável `vfs.write_behind` man:sysctl[8] é padronizada para `1` (ligada). Isso informa ao sistema de arquivos para emitir gravações de mídia à medida que clusters completos são coletados, o que normalmente ocorre ao gravar arquivos sequenciais grandes. Isso evita saturar o cache de buffer com buffers sujos quando não beneficia o desempenho de I/O. No entanto, isso pode atrasar os processos e, sob certas circunstâncias, deve ser desativado. ==== `vfs.hirunningspace` A variável `vfs.hirunningspace` man:sysctl[8] determina quanto de I/O de gravação pendente pode ser enfileirado no sistema de controladores de disco como um todo em qualquer instância. O padrão é geralmente suficiente, mas em máquinas com muitos discos, tente aumentar para quatro ou cinco _megabytes_. Definir um valor muito alto, que exceda o limite de gravação do cache de buffer, pode levar a um mau desempenho de cluster. Não defina esse valor arbitrariamente alto, pois valores de gravação mais altos podem adicionar latência a leituras que ocorrem ao mesmo tempo. Há vários outros caches de buffer e valores de cache de página VM relacionados a man:sysctl[8]. Modificar esses valores não é recomendado, pois o sistema VM faz um bom trabalho de ajuste automático. ==== `vm.swap_idle_enabled` A variável `vm.swap_idle_enabled` man:sysctl[8] é útil em grandes sistemas multiusuários com muitos usuários ativos, e muitos processos ociosos. Tais sistemas tendem a gerar pressão contínua nas reservas de memória livre. Ativar esse recurso e aprimorar a histerese de troca (em segundos ociosos) por meio de `vm.swap_idle_threshold1` e `vm.swap_idle_threshold2` reduz a prioridade das páginas de memória associadas aos processos inativos mais rapidamente do que no algoritmo de pageout normal. Isso dá uma ajuda ao daemon de pageout. Apenas ative essa opção se necessário, porque a compensação é essencialmente fazer o pre-page da memoria mais cedo, o que consome mais swap e largura de banda de disco. Em um sistema pequeno, esta opção terá um efeito determinável, mas em um sistema grande que já está paginando moderadamente, esta opção permite que o sistema VM instale processos inteiros dentro e fora da memória facilmente. ==== `hw.ata.wc` Desativar o cache de gravação IDE reduz a largura de banda de gravação em discos IDE, mas às vezes pode ser necessário devido a problemas de consistência de dados introduzidos por fornecedores de disco rígido. O problema é que algumas unidades IDE mentem sobre quando uma gravação é concluída. Com o cache de gravação IDE ativado, os discos rígidos IDE gravam os dados fora de ordem e às vezes atrasam a gravação de alguns blocos indefinidamente quando estão sob carga pesada de disco. Uma falha ou falha de energia pode causar corrupção séria do sistema de arquivos. Verifique o padrão no sistema observando a variável `hw.ata.wc` man:sysctl[8]. Se o cache de gravação IDE estiver desativado, pode-se definir essa variável somente leitura como `1` em [.filename]#/boot/loader.conf# para ativar no momento da inicialização. Para maiores informações, consulte man:ata[4]. ==== `SCSI_DELAY` (`kern.cam.scsi_delay`) A opção de configuração do kernel `SCSI_DELAY` pode ser usada para reduzir os tempos de inicialização do sistema. Os padrões são razoavelmente altos e podem ser responsáveis por `15` segundos de atraso no processo de inicialização. Reduzindo-o para `5` segundos geralmente funciona com unidades modernas. A variável de tempo de inicialização `kern.cam.scsi_delay` deve ser usada. A opção de configuração ajustável e a configuração do kernel aceitam valores em termos de _milissegundos_ e _não__segundos_. [[soft-updates]] === Soft Updates Para ajustar um sistema de arquivos, use man:tunefs[8]. Este programa tem muitas opções diferentes. Para ativar e desativar o Soft Updates, use: [source,shell] .... # tunefs -n enable /filesystem # tunefs -n disable /filesystem .... Um sistema de arquivos não pode ser modificado com man:tunefs[8] enquanto estiver montado. Um bom momento para ativar o Soft Updates é antes que qualquer partição tenha sido montada, no modo de single-user. O Soft Updates é recomendado para sistemas de arquivos UFS, pois melhora drasticamente o desempenho de metadados, principalmente a criação e exclusão de arquivos, através do uso de um cache em memória. Há duas desvantagens no Soft Updates que você deve conhecer. Primeiro, o Soft Updates garante a consistência do sistema de arquivos no caso de uma falha, mas pode facilmente levar vários segundos ou até um minuto para atualizar o disco físico. Se o sistema falhar, os dados não gravados poderão ser perdidos. Em segundo lugar, os Soft Updates atrasam a liberação de blocos do sistema de arquivos. Se o sistema de arquivos raiz estiver quase cheio, a execução de uma atualização importante, como `make installworld`, poderá causar a falta de espaço do sistema de arquivos e a atualização falhará. ==== Mais detalhes sobre soft updates As atualizações de metadados são atualizações para dados que não são de conteúdo, como inodes ou diretórios. Existem duas abordagens tradicionais para gravar os metadados de um sistema de arquivos em disco. Historicamente, o comportamento padrão era gravar atualizações de metadados de forma síncrona. Se um diretório fosse alterado, o sistema aguardava até que a alteração fosse gravada no disco. Os buffers de dados do arquivo (conteúdo do arquivo) foram passados pelo cache de buffer e foram copiados para o disco posteriormente de maneira assíncrona. A vantagem dessa implementação é que ela opera com segurança. Se houver uma falha durante uma atualização, os metadados estarão sempre em um estado consistente. Um arquivo é criado completamente ou não é de todo. Se os blocos de dados de um arquivo não encontrarem saída do cache de buffer para o disco no momento da falha, o man:fsck[8] reconhece isso e repara o sistema de arquivos definindo o comprimento do arquivo como `0`. Além disso, a implementação é clara e simples. A desvantagem é que as alterações nos metadados são lentas. Por exemplo, `rm -r` toca todos os arquivos em um diretório sequencialmente, mas cada alteração de diretório será gravada de forma síncrona no disco. Isso inclui atualizações para o próprio diretório, para a tabela de inode e possivelmente para blocos indiretos alocados pelo arquivo. Considerações semelhantes aplicam-se ao desenrolar hierarquias grandes usando `tar -x`. A segunda abordagem é usar atualizações de metadados assíncronas. Este é o padrão para um sistema de arquivos UFS montado com `mount -o async`. Como todas as atualizações de metadados também são passadas pelo cache de buffer, elas serão mescladas com as atualizações dos dados de conteúdo do arquivo. A vantagem dessa implementação é que não há necessidade de esperar até que cada atualização de metadados seja gravada no disco, portanto, todas as operações que causam grandes quantidades de atualizações de metadados funcionam muito mais rápido do que no caso síncrono. Essa implementação ainda é clara e simples, portanto, há um baixo risco de erros se infiltrarem no código. A desvantagem é que não há garantia para um estado consistente do sistema de arquivos. Se houver uma falha durante uma operação que atualizou grandes quantidades de metadados, como uma falha de energia ou alguém pressionando o botão de reinicialização, o sistema de arquivos será deixado em um estado imprevisível. Não há oportunidade de examinar o estado do sistema de arquivos quando o sistema é reativado, pois os blocos de dados de um arquivo já podem ter sido gravados no disco enquanto as atualizações da tabela de inodes ou do diretório associado não foram. É impossível implementar um man:fsck[8] que é capaz de limpar o caos resultante porque as informações necessárias não estão disponíveis no disco. Se o sistema de arquivos foi danificado além do reparo, a única opção é reformatá-lo e restaurá-lo a partir do backup. A solução usual para este problema é implementar _dirty region logging_, que também é chamado de _journaling_. As atualizações de metadados ainda são gravadas de forma síncrona, mas apenas em uma pequena região do disco. Mais tarde, eles são movidos para o local apropriado. Como a área de registro é uma região pequena e contígua no disco, não há longas distâncias para as cabeças de disco se moverem, mesmo durante operações pesadas, portanto, essas operações são mais rápidas do que as atualizações síncronas. Além disso, a complexidade da implementação é limitada, portanto, o risco de erros estarem presentes é baixo. Uma desvantagem é que todos os meta-dados são gravados duas vezes, uma vez na região de registro e uma vez no local apropriado, portanto, pode resultar em "piora" na performance. Por outro lado, em caso de falha, todas as operações de metadados pendentes podem ser rapidamente recuperadas ou concluídas a partir da área de registro depois que o sistema for ativado novamente, resultando em uma inicialização rápida do sistema de arquivos. Kirk McKusick, o desenvolvedor do Berkeley FFS, resolveu esse problema com o Soft Updates. Todas as atualizações de meta-dados pendentes são mantidas na memória e gravadas no disco em uma sequência ordenada ("atualizações de metadados ordenadas"). Isso tem o efeito de que, no caso de operações pesadas de meta-dados, atualizações posteriores em um item "catch" as anteriores que ainda estão na memória e ainda não foram gravadas no disco. Todas as operações são geralmente executadas na memória antes da atualização ser gravada no disco e os blocos de dados são classificados de acordo com sua posição, de modo que não estarão no disco antes de seus meta-dados. Se o sistema travar, um "reenvio de log" implícito faz com que todas as operações que não foram gravadas no disco apareçam como se nunca tivessem acontecido. Um estado consistente do sistema de arquivos é mantido e parece ser o de 30 a 60 segundos antes. O algoritmo usado garante que todos os recursos em uso sejam marcados como tal em seus blocos e inodes. Após uma falha, o único erro de alocação de recursos que ocorre é que os recursos são marcados como "used", que são, na verdade, "free". O man:fsck[8] reconhece essa situação e libera os recursos que não são mais usados. É seguro ignorar o estado sujo do sistema de arquivos após uma falha forçando a montagem com `mount -f`. Para liberar recursos que podem não ser utilizados, O man:fsck[8] precisa ser executado posteriormente. Esta é a idéia por trás do _man:fsck[8] em background_: no momento da inicialização do sistema, apenas um _snapshot_ do sistema de arquivos é gravado e o man:fsck[8] é executado posteriormente. Todos os sistemas de arquivos podem ser montados "sujos", para que a inicialização do sistema prossiga no modo multiusuário. Em seguida, o man:fsck[8] em background é planejado para todos os sistemas de arquivos em que isso é necessário, para liberar recursos que podem não ser utilizados. Os sistemas de arquivos que não usam Soft Updates ainda precisam executar o man:fsck[8] em primeiro plano de forma usual . A vantagem é que as operações de meta-dados são quase tão rápidas quanto as atualizações assíncronas e são mais rápidas que o _logging_, que precisa escrever os meta-dados duas vezes. As desvantagens são a complexidade do código, um maior consumo de memória e algumas idiosincrasias. Depois de uma falha, o estado do sistema de arquivos parece ser um pouco mais "velho". Em situações onde a abordagem síncrona padrão teria causado a existencia de alguns arquivos de comprimento zero após o man:fsck[8], esses arquivos sequer chegam a existir com Soft Updates porque nem os metadados e nem o conteúdo do arquivo foram gravados no disco. O espaço em disco não é liberado até que as atualizações tenham sido gravadas no disco, o que pode ocorrer algum tempo depois de executar man:rm[1]. Isso pode causar problemas ao instalar grandes quantidades de dados em um sistema de arquivos que não tenha espaço livre suficiente para armazenar todos os arquivos duas vezes. [[configtuning-kernel-limits]] == Ajustando os Limites do Kernel [[file-process-limits]] === Limites de arquivos/processos [[kern-maxfiles]] ==== `kern.maxfiles` A variável `kern.maxfiles` man:sysctl[8] pode ser aumentada ou diminuída com base nos requisitos do sistema. Essa variável indica o número máximo de descritores de arquivos no sistema. Quando a tabela do descritor de arquivos estiver cheia, o erro `file: table is full` aparecerá repetidamente no buffer de mensagem do sistema, que pode ser visualizado usando man:dmesg[8]. Cada arquivo aberto, socket ou fifo usa um descritor de arquivo. Um servidor de produção em larga escala pode facilmente exigir muitos milhares de descritores de arquivos, dependendo do tipo e número de serviços executados simultaneamente. Em versões mais antigas do FreeBSD, o valor padrão de `kern.maxfiles` é derivado do `maxusers` no arquivo de configuração do kernel. O `kern.maxfiles` cresce proporcionalmente ao valor do `maxusers`. Ao compilar um kernel personalizado, considere configurar esta opção de configuração do kernel de acordo com o uso do sistema. A partir desse número, o kernel recebe a maioria dos seus limites predefinidos. Mesmo que uma máquina de produção não tenha 256 usuários simultâneos, os recursos necessários podem ser semelhantes a um servidor da Web de alta escala. A variável read-only man:sysctl[8]`kern.maxusers` é dimensionada automaticamente na inicialização com base na quantidade de memória disponível no sistema, e pode ser determinado em tempo de execução, inspecionando o valor de `kern.maxusers`. Alguns sistemas requerem valores maiores ou menores de `kern.maxusers` e valores de `64`, `128`, e `256` não são incomuns. Ir acima de `256` não é recomendado, a menos que seja necessário um grande número de descritores de arquivos. Muitos dos valores ajustáveis definidos para seus padrões por `kern.maxusers` podem ser individualmente sobrescritos no tempo de inicialização ou em tempo de execução no [.filename]#/boot/loader.conf#. Consulte man:loader.conf[5] e [.filename]#/boot/defaults/loader.conf# para mais detalhes e algumas dicas. Em versões mais antigas, o sistema ajustará automaticamente o `maxusers` se ele estiver definido como `0`. . Ao configurar esta opção, configure o `maxusers` para pelo menos `4`, especialmente se o sistema executar o Xorg ou se for usado para compilar software. A tabela mais importante definida por `maxusers` é o número máximo de processos, que é definido como `20 + 16 * maxusers`. Se `maxusers` for definido como `1`, só podem existir `36` processos simultâneos, incluindo `18` ou mais para que o sistema seja iniciado no boot ou `15` usado pelo Xorg. Até mesmo uma tarefa simples, como ler uma página de manual, iniciará nove processos para filtrar, descompactar e visualizar. Configurar o `maxusers` para `64` permite até `1044` processos simultâneos, o que deve ser suficiente para quase todos os usos. Se, no entanto, o erro for exibido ao tentar iniciar outro programa ou se um servidor estiver sendo executado com um grande número de usuários simultâneos, aumente o número e recompile. [NOTE] ==== O `maxusers` _não_ limita o número de usuários que podem logar na máquina. Em vez disso, ele configura vários tamanhos de tabela para valores razoáveis, considerando o número máximo de usuários no sistema e quantos processos cada usuário executará. ==== ==== `kern.ipc.soacceptqueue` A variável `kern.ipc.soacceptqueue` do man:sysctl[8] limita o tamanho da fila de escuta para aceitar novas conexões `TCP`. O valor padrão de `128` é normalmente muito baixo para o manuseio robusto de novas conexões em um servidor Web com carga pesada. Para tais ambientes, recomenda-se aumentar este valor para `1024` ou superior. Um serviço como o man:sendmail[8], ou Apache pode limitar por ele mesmo o tamanho da fila de escuta, mas frequentemente terá uma diretiva em seu arquivo de configuração para ajustar o tamanho da fila. Filas de escuta grandes fazem um trabalho melhor evitando ataques de negação de serviço (Denial of Service - DoS). [[nmbclusters]] === Limites de rede A opção de configuração do kernel `NMBCLUSTERS` determina a quantidade de Mbufs de rede disponível para o sistema. Um servidor com muito tráfego e um baixo número de Mbufs prejudicará o desempenho. Cada cluster representa aproximadamente 2K de memória, portanto, um valor de `1024` representa `2` megabytes de memória do kernel reservada para buffers de rede. Um cálculo simples pode ser feito para descobrir quantos são necessários. Um servidor web que suporte um maximo de `1000` conexões simultâneas onde cada conexão usa um buffer de envio de 16K e recebe 6K, requer aproximadamente 32 MB de buffers de rede para cobrir o servidor web. Uma boa regra é multiplicar por `2`, então 2x32MB / 2KB = 64MB / 2kB = `32768`. Valores entre `4096` e `32768` são recomendados para máquinas com maiores quantidades de memória. Nunca especifique um valor arbitrariamente alto para este parâmetro, pois isso pode levar a uma falha no tempo de inicialização. Para observar o uso do cluster de rede, use a opção `-m` com o man:netstat[1]. A variável `kern.ipc.nmbclusters` deve ser usada para configurar isso no momento da inicialização. Apenas as versões mais antigas do FreeBSD irão requerer o uso da opção `NMBCLUSTERS` no man:config[8] do kernel. Para servidores ocupados que fazem uso extensivo da chamada de sistema man:sendfile[2], pode ser necessário aumentar o número de buffers man:sendfile[2] através da opção de configuração do kernel `NSFBUFS` ou definindo seu valor no [.filename]#/boot/loader.conf# (veja man:loader[8] para detalhes). Um indicador comum de que esse parâmetro precisa ser ajustado é quando os processos são vistos no estado `sfbufa`. A variável man:sysctl[8]`kern.ipc.nsfbufs` é somente de leitura. Este parâmetro nominalmente escala com o `kern.maxusers`, no entanto, pode ser necessário ajustar de acordo. [IMPORTANT] ==== Mesmo que um socket tenha sido marcado como non-blocking, chamar o man:sendfile[2] em um socket non-blocking pode resultar no bloqueio do man:sendfile[2] até que sejam disponibilizados `struct sf_buf` suficientes. ==== ==== `net.inet.ip.portrange.*` As variáveis `net.inet.ip.portrange.*` do man:sysctl[8] controlam os intervalos de números de porta automaticamente ligados a sockets `TCP` e `UDP`. Existem três intervalos: um intervalo baixo, um intervalo padrão e um intervalo alto. A maioria dos programas de rede usam o intervalo padrão que é controlado por `net.inet.ip.portrange.first` e `net.inet.ip.portrange.last`, cujo padrão é `1024` e `5000`, respectivamente. Intervalos de porta ligados são usados para conexões de saída e é possível executar o sistema fora das portas sob certas circunstâncias. Isso ocorre mais comumente ao executar um proxy web com muita carga. O intervalo de portas não é um problema ao executar um servidor que lida principalmente com conexões de entrada, como um servidor Web, ou que tenha um número limitado de conexões de saída, como um mail relay. Para situações em que há falta de portas, é recomendado aumentar modestamente o `net.inet.ip.portrange.last`. Um valor de `10000`, `20000` ou `30000` pode ser razoável. Considere os efeitos do firewall ao alterar o intervalo de portas. Alguns firewalls podem bloquear grandes intervalos de portas, geralmente portas de numeração baixa, e esperam que os sistemas usem intervalos mais altos de portas para conexões de saída. Por esta razão, não é recomendado que o valor de `net.inet.ip.portrange.first` seja diminuído. ==== Produto de atraso de largura de banda `TCP` A limitação do produto de atraso de largura de banda `TCP` pode ser ativada configurando a variável `net.inet.tcp.inflight.enable` do man:sysctl[8] para `1`. Isso instrui o sistema a tentar calcular o produto de atraso de largura de banda para cada conexão e a limitar a quantidade de dados na fila para envio à rede para a quantidade necessária para manter o rendimento ideal. Esse recurso é útil ao servir dados sobre modems, Gigabit Ethernet, links `WAN` de alta velocidade ou qualquer outro link com um produto de atraso de largura de banda alta, especialmente quando também estiver usando dimensionamento de janela ou quando uma janela de envio grande tiver sido configurado. Ao habilitar essa opção, defina também a variável `net.inet.tcp.inflight.debug` para `0` para desabilitar a depuração. Para uso em produção, definir a variável `net.inet.tcp.inflight.min` para pelo menos `6144` pode ser benéfico. Definir valores mínimos altos pode efetivamente desabilitar a limitação de largura de banda, dependendo do link. O recurso de limitação reduz a quantidade de dados acumulados nas rotas intermediárias e nas filas de pacotes de switchs e reduz a quantidade de dados acumulados na fila de interface do host local. Com menos pacotes enfileirados, as conexões interativas, especialmente os modems lentos, funcionarão com menores _Round Trip Times_. Esse recurso afeta apenas a transmissão de dados do lado do servidor, como o upload. Não tem efeito na recepção ou download de dados. Ajustar o valor da variável `net.inet.tcp.inflight.stab` _não_ é recomendado. Este parâmetro é padronizado para `20`, representando 2 pacotes máximos adicionados ao cálculo da janela de produto de atraso de largura de banda. A janela adicional é necessária para estabilizar o algoritmo e melhorar a capacidade de resposta às mudanças de condições, mas também pode resultar em um man:ping[8] mais alto em links lentos , embora ainda muito menor do que sem o algoritmo inflight. Nesses casos, tente reduzir esse parâmetro para `15`, `10` ou `5` e reduza a variável `net.inet.tcp.inflight.min` para um valor como `3500` para obter o efeito desejado. A redução desses parâmetros deve ser feita apenas como último recurso. === Memória virtual ==== `kern.maxvnodes` Um vnode é a representação interna de um arquivo ou diretório. Aumentar o número de vnodes disponíveis para o sistema operacional reduz a I/O do disco. Normalmente, isso é tratado pelo sistema operacional e não precisa ser alterado. Em alguns casos em que o I/O de disco é um gargalo e o sistema está ficando sem vnodes, essa configuração precisa ser aumentada. A quantidade de RAM inativa e livre precisará ser levada em conta. Para ver o número atual de vnodes em uso: [source,shell] .... # sysctl vfs.numvnodes vfs.numvnodes: 91349 .... Para ver o máximo de vnodes: [source,shell] .... # sysctl kern.maxvnodes kern.maxvnodes: 100000 .... Se o uso atual do vnode estiver próximo do máximo, tente aumentar o `kern.maxvnodes` por um valor de `1000`. Fique de olho no número de `vfs.numvnodes`. Se subir até o máximo novamente, o `kern.maxvnodes` precisará ser aumentado ainda mais. Caso contrário, uma mudança no uso da memória como reportado pelo man:top[1] deve estar visível e mais memória deve estar ativa. [[adding-swap-space]] == Adicionando Espaço de Swap Às vezes, um sistema requer mais espaço de swap. Esta seção descreve dois métodos para aumentar o espaço de troca: adicionar swap a uma partição existente ou em um novo disco rígido e criar um arquivo de swap em uma partição existente. Para obter informações sobre como criptografar o espaço de swap, quais opções existem e por que isso deve ser feito, consulte crossref:disks[swap-encrypting,Criptografando Swap]. [[new-drive-swap]] === Swap em um novo disco rígido ou partição existente Adicionar um novo disco rígido para swap resulta em um melhor desempenho do que usando uma partição em uma unidade existente. A configuração de partições e discos rígidos é explicada em crossref:disks[disks-adding,Adicionando Discos] enquanto crossref:bsdinstall[configtuning-initial,Criando o layout da partição] discute layouts de partições e considerações sobre o tamanho de partições de swap. Use o `swapon` para adicionar uma partição swap ao sistema. Por exemplo: [source,shell] .... # swapon /dev/ada1s1b .... [WARNING] ==== É possível usar qualquer partição que não esteja atualmente montada, mesmo que já contenha dados. O uso do `swapon` em uma partição que contém dados sobrescreverá e destruirá esses dados. Certifique-se de que a partição a ser incluída como swap seja realmente a partição pretendida antes de executar o `swapon`. ==== Para adicionar automaticamente essa partição swap na inicialização, adicione uma entrada ao [.filename]#/etc/fstab#: [.programlisting] .... /dev/ada1s1b none swap sw 0 0 .... Veja man:fstab[5] para uma explicação das entradas do [.filename]#/etc/fstab#. Maiores informações sobre `swapon` podem ser encontradas em man:swapon[8]. [[create-swapfile]] === Criando um arquivo de swap Esses exemplos criam um arquivo de swap de 512M chamado [.filename]#/usr/swap0# em vez de usar uma partição. O uso de arquivos de swap requer que o módulo necessário pelo man:md[4] tenha sido embutido no kernel ou tenha sido carregado antes do swap ser ativado. Veja crossref:kernelconfig[kernelconfig, Configurando o kernel do FreeBSD] para informações sobre como compilar um kernel customizado. [[swapfile-10-and-later]] .Criando um arquivo de swap [example] ==== [.procedure] ====== . Crie o arquivo de swap: + [source,shell] .... # dd if=/dev/zero of=/usr/swap0 bs=1m count=512 .... + . Defina as permissões adequadas no novo arquivo: + [source,shell] .... # chmod 0600 /usr/swap0 .... + . Informe o sistema sobre o arquivo de swap adicionando uma linha ao [.filename]#/etc/fstab#: + [.programlisting] .... md99 none swap sw,file=/usr/swap0,late 0 0 .... + O dispositivo [.filename]#md99# do man:md[4] é usado, deixando números de dispositivos inferiores disponíveis para uso interativo. + . O espaço de swap será adicionado na inicialização do sistema. Para adicionar espaço de swap imediatamente, use o man:swapon[8]: + [source,shell] .... # swapon -aL .... ====== ==== [[acpi-overview]] == Gerenciamento de energia e recursos É importante utilizar recursos de hardware de maneira eficiente. O gerenciamento de energia e recursos permite que o sistema operacional monitore os limites do sistema e, possivelmente, forneça um alerta se a temperatura do sistema aumentar inesperadamente. Uma especificação anterior para fornecer gerenciamento de energia foi o recurso Gerenciamento Avançado de Energia (Advanced Power Management - APM). O APM controla o uso de energia de um sistema com base em sua atividade. No entanto, era difícil e inflexível para os sistemas operacionais gerenciar o uso de energia e as propriedades térmicas de um sistema. O hardware era gerenciado pelo BIOS e o usuário tinha configuração e visibilidade limitadas nas configurações de gerenciamento de energia. O APMBIOS fornecido é específico da plataforma de hardware. Um driver APM no sistema operacional intermedia o acesso à interface do software APM, que permite o gerenciamento dos níveis de energia. Existem quatro problemas principais no APM. Primeiro, o gerenciamento de energia é feito pelo BIOS específico do fornecedor, separado do sistema operacional. Por exemplo, o usuário pode definir valores de tempo ocioso para um disco rígido no APMBIOS para que, quando excedido, o BIOS diminua o disco rígido sem o consentimento do sistema operacional. Segundo, a lógica do APM é incorporada no BIOS e opera fora do escopo do sistema operacional. Isso significa que os usuários só podem corrigir problemas no APMBIOS, fazendo o flash de um novo ROM, que é um procedimento perigoso com potencial para deixar o sistema em um estado irrecuperável se falhar. Terceiro, o APM é uma tecnologia específica do fornecedor, o que significa que há muita duplicidade de esforços e que os erros encontrados no BIOS de um fornecedor podem não serem resolvidos em outros. Por fim, o APMBIOS não tinha espaço suficiente para implementar uma política de energia sofisticada ou que pudesse se adaptar bem ao propósito da máquina. O BIOS plug and play (PNPBIOS) não era confiável em muitas situações. O PNPBIOS é uma tecnologia de 16 bits, portanto, o sistema operacional precisa usar a emulação de 16 bits para fazer interface com os métodos PNPBIOS. O FreeBSD fornece um driver APM, pois o APM ainda deve ser usado para sistemas fabricados antes do ano 2000. O driver está documentado em man:apm[4]. O sucessor do APM é a Interface Avançada de Configuração e Energia (Advanced Configuration and Power Interface - ACPI). O ACPI é um padrão escrito por uma aliança de fornecedores para fornecer uma interface para recursos de hardware e gerenciamento de energia. É um elemento-chave na _configuração direcionada do sistema operacional e gerenciamento de energia_, pois proporciona mais controle e flexibilidade ao sistema operacional. Este capítulo demonstra como configurar o ACPI no FreeBSD. Em seguida, ele oferece algumas dicas sobre como depurar o ACPI e como enviar um relatório de problemas contendo informações de depuração para que os desenvolvedores possam diagnosticar e corrigir problemas no ACPI. [[acpi-config]] === Configurando o ACPI No FreeBSD, o driver man:acpi[4] é carregado por padrão na inicialização do sistema e _não_ deve ser compilado no kernel. Este driver não pode ser descarregado após a inicialização porque o barramento do sistema o utiliza para várias interações de hardware. No entanto, se o sistema estiver com problemas, o ACPI pode ser desativado completamente ao reinicializar após a configurar `hint.acpi.0.disabled="1"` no [.filename]#/boot/loader.conf# ou definindo esta variável no prompt do loader, como descrito em crossref:boot[boot-loader,Estágio três]. [NOTE] ==== O ACPI e o APM não podem coexistir e devem ser usados separadamente. O último a ser carregado terminará se o driver perceber que o outro já está sendo executado. ==== O ACPI pode ser usado para colocar o sistema em modo de suspensão com o `acpiconf`, a opção `-s` e um número de `1` a `5`. A maioria dos usuários só precisa de `1` (suspensão rápida para RAM) ou `3` (suspender para RAM). A opção `5` executa um soft-off que é o mesmo que executar `halt -p`. Outras opções estão disponíveis usando o `sysctl`. Consulte man:acpi[4] e man:acpiconf[8] para maiores informações. [[ACPI-comprob]] === Problemas comuns O ACPI está presente em todos os computadores modernos que estão em conformidade com as arquiteturas ia32 (x86) e amd64 (AMD). O padrão completo tem muitos recursos, incluindo gerenciamento de desempenho da CPU, controle de planos de energia, zonas térmicas, vários sistemas de bateria, controladores incorporados e enumeração de barramento. A maioria dos sistemas implementa menos que o padrão completo. Por exemplo, um sistema de desktop geralmente só implementa a enumeração de barramento, enquanto um laptop também pode ter suporte a refrigeração e gerenciamento de bateria. Os laptops também têm suspensão e retomada, com sua própria complexidade associada. Um sistema compatível com ACPI possui vários componentes. Os fornecedores de BIOS e chipset fornecem várias tabelas fixas, como FADT, na memória que especificam coisas como o mapa APIC (usado para SMP), registros de configuração e valores simples de configuração. Além disso, uma tabela de bytecode, a Tabela de Descrição de Sistema Diferenciada DSDT, especifica um espaço de nome de dispositivos e métodos em forma de árvore. O driver ACPI deve analisar as tabelas fixas, implementar um interpretador para o bytecode e modificar os drivers de dispositivos e o kernel para aceitar informações do subsistema ACPI. Para o FreeBSD, a Intel(TM) forneceu um interpretador (ACPI-CA) que é compartilhado com o Linux(TM) e o NetBSD. O caminho para o código-fonte ACPI-CA é [.filename]#src/sys/contrib/dev/acpica#. O código especifico que permite que o ACPI-CA funcione no FreeBSD está em [.filename]#src/sys/dev/acpica/Osd#. Finalmente, drivers que implementam vários dispositivos ACPI são encontrados em [.filename]#src/sys/dev/acpica#. Para que o ACPI funcione corretamente, todas as partes devem funcionar corretamente. Aqui estão alguns problemas comuns, em ordem de freqüência em que ocorrem, e algumas possíveis soluções ou correções. Se uma correção não resolver o problema, consulte <> para obter instruções sobre como enviar um relatório de bug. ==== Problemas do mouse Em alguns casos, retomar a partir de uma operação de suspensão fará com que o mouse falhe. Um work around conhecido é adicionar `hint.psm.0.flags="0x3000"` ao [.filename]#/boot/loader.conf#. ==== Suspend/Resume O ACPI tem três estados de suspensão para RAM (STR), `S1`-`S3`, e um de suspensão de estado para disco (STD), chamado `S4`. O STD pode ser implementado de duas maneiras separadas. O `S4` BIOS é uma suspensão para disco auxiliada pelo BIOSe o ``S4``OS é implementado inteiramente pelo sistema operacional. O estado normal em que o sistema se encontra quando conectado, mas não ligado, é "soft off" (`S5`). Use o `sysctl hw.acpi` para verificar os itens relacionados à suspensão. Estes resultados de exemplo são de um Thinkpad: [source,shell] .... hw.acpi.supported_sleep_state: S3 S4 S5 hw.acpi.s4bios: 0 .... Use o `acpiconf -s` para testar os estados `S3`, `S4` e `S5`. Um `s4bios` de um (`1`) indica suporte ao `S4` BIOS em vez do `S4` suportado pelo sistema operacional. Ao testar as ações de suspend/resume, inicie com o `S1`, se suportado. É mais provável que esse estado funcione, pois não requer muito suporte ao driver. Ninguém implementou `S2`, que é similar ao `S1`. Em seguida, tente o `S3`. Este é o estado mais profundo do STR e requer muito suporte ao driver para reinicializar corretamente o hardware. Um problema comum com suspend/resume é que muitos drivers de dispositivo não salvam, restauram ou reinicializam seu firmware, registros ou memória do dispositivo adequadamente. Como primeira tentativa de depuração do problema, tente: [source,shell] .... # sysctl debug.bootverbose=1 # sysctl debug.acpi.suspend_bounce=1 # acpiconf -s 3 .... Esse teste emula o ciclo de suspend/resume de todos os drivers de dispositivo sem entrar realmente no estado `S3`. Em alguns casos, problemas como perder o estado do firmware, tempo limite do watchdog do dispositivo e tentar novamente para sempre podem ser capturados com esse método. Note que o sistema não entrará realmente no estado `S3`, o que significa que os dispositivos não perderão energia, e muitos funcionarão bem mesmo se os métodos suspend/resume estiverem totalmente ausentes, ao contrário do real estado `S3`. Casos mais difíceis requerem hardware adicional, como uma porta serial e um cabo para depuração através de um console serial, uma porta Firewire e um cabo para o uso do man:dcons[4] e habilidades de depuração do kernel. Para ajudar a isolar o problema, descarregue o maior número possível de drivers. Se funcionar, diminua o driver que é o problema carregando os drivers até que ele falhe novamente. Normalmente, drivers binários como [.filename]#nvidia.ko#, drivers de exibição e USB terão mais problemas, enquanto as interfaces Ethernet normalmente funcionam bem. Se os drivers puderem ser carregados e descarregados adequadamente, automatize isso colocando os comandos apropriados em [.filename]#/etc/rc.suspend# e [.filename]#/etc/rc.resume#. Tente configurar o `hw.acpi.reset_video` para `1` se a tela estiver desarrumada após a retomada. Tente definir valores mais longos ou mais curtos para `hw.acpi.sleep_delay` para ver se isso ajuda. Tente carregar uma distribuição recente do Linux(TM) para ver se o suspend/resume funciona no mesmo hardware. Se funciona no Linux(TM), é provável que seja um problema no driver do FreeBSD. Descobrir qual driver causa o problema ajudará os desenvolvedores a corrigir o problema. Como os mantenedores do ACPI raramente mantêm outros drivers, como som ou ATA, qualquer problema de driver também deve ser postado na lista http://lists.FreeBSD.org/mailman/listinfo/freebsd-current[freebsd-current] e enviada para o mantenedor do driver. Os usuários avançados podem incluir os man:printf[3]s de debug do driver problemático para rastrear onde, em sua função de reinício, ele é interrompido. Por fim, tente desativar o ACPI e ativar o APM. Se o comando suspend/resume funcionar com APM, use o APM, especialmente em hardware mais antigo (anterior a 2000). Demorou algum tempo para que os fornecedores obtivessem suporte ACPI correto e os hardwares antigos são mais prováveis de terem problemas de BIOS com ACPI. ==== Travamentos do sistema A maioria dos travamentos do sistema é resultado de interrupções perdidas ou de uma tempestade de interrupções. Chipsets podem ter problemas com base na inicialização, como o BIOS configura as interrupções antes da correção da tabela APIC (MADT) e o roteamento do sistema de controle de interrupções (SCI). Tempestades de interrupção podem ser distinguidas de interrupções perdidas, verificando a saída do `vmstat -i` e observando a linha que possui `acpi0`. Se o contador está aumentando em mais de um par por segundo, há uma tempestade de interrupção. Se o sistema parece travado, tente acessar o DDB (kbd:[CTRL+ALT+ESC] no console) e digite `show interrupts`. Ao lidar com problemas de interrupção, tente desativar o suporte ao APIC com `hint.apic.0.disabled="1"` no [.filename]#/boot/loader.conf# . ==== Panics Os panics são relativamente raros para ACPI e são a prioridade máxima a ser corrigida. O primeiro passo é isolar as etapas para reproduzir o panic, se possível, e obter um backtrace. Siga as instruções para habilitar `options DDB` e configurar um console serial em crossref:serialcomms[serialconsole-ddb,Entrando no Depurador DDB da Linha Serial] ou configurar uma partição de despejo. Para obter um backtrace no DDB, use `tr`. Ao escrever o backtrace, obtenha pelo menos as cinco últimas e as cinco principais linhas do rastro. Em seguida, tente isolar o problema inicializando com ACPI desabilitado. Se isso funcionar, isole o subsistema ACPI usando vários valores de `debug.acpi.disable`. Veja man:acpi[4] para alguns exemplos. ==== O sistema é ativado após a sua suspensão ou desligamento Primeiro, tente definir `hw.acpi.disable_on_poweroff="0"` no [.filename]#/boot/loader.conf#. Isso impede que a ACPI desative vários eventos durante o processo de desligamento. Alguns sistemas precisam desse valor definido como `1` (o padrão) pelo mesmo motivo. Isso geralmente corrige o problema de um sistema ser ativado espontaneamente após uma suspensão ou desligamento. [[ACPI-aslanddump]] ==== BIOS contém Bytecode com bugs Alguns fornecedores de BIOS fornecem bytecode incorreto ou com bugs. Isso geralmente é manifestado por mensagens do console do kernel como esta: [source,shell] .... ACPI-1287: *** Error: Method execution failed [\\_SB_.PCI0.LPC0.FIGD._STA] \\ (Node 0xc3f6d160), AE_NOT_FOUND .... Geralmente, esses problemas podem ser resolvidos com a atualização do BIOS para a revisão mais recente. A maioria das mensagens do console é inofensiva, mas se houver outros problemas, como o status da bateria não estar funcionando, essas mensagens são um bom lugar para começar a procurar por problemas. === Substituindo o padrão AML O bytecode do BIOS, conhecido como ACPI Machine Language (AML), é compilado de uma linguagem de origem chamada ACPI Source Language (ASL). O AML é encontrado na tabela conhecida como Tabela de Descrição do Sistema Diferenciado (Differentiated System Description Table - DSDT). O objetivo do FreeBSD é que todos trabalhem com ACPI sem qualquer intervenção do usuário. Soluções alternativas ainda estão sendo desenvolvidas para erros comuns feitos pelos fornecedores de BIOS. O interpretador Microsoft(TM) ([.filename]#acpi.sys# e [.filename]#acpiec.sys#) não verifica rigorosamente a conformidade com o padrão e, portanto, muitos fornecedores de BIOS que testam apenas ACPI sob Windows(TM) nunca corrigem seu ASL. Os desenvolvedores do FreeBSD continuam a identificar e documentar qual comportamento não padrão é permitido pelo interpretador da Microsoft(TM) para replicá-lo para que o FreeBSD possa funcionar sem forçar os usuários a corrigir o ASL. Para ajudar a identificar o comportamento de bugs e possivelmente corrigi-lo manualmente, uma cópia pode ser feita do ASL do sistema. Para copiar o ASL do sistema para um nome de arquivo especificado, use `acpidump` com `-t`, para mostrar o conteúdo das tabelas fixas e `-d`, para desmontar o AML: [source,shell] .... # acpidump -td > my.asl .... Algumas versões de AML assumem que o usuário está executando o Windows(TM). Para sobrescrever isto, defina `hw.acpi.osname=_"Windows 2009"_` no [.filename]#/boot/loader.conf#, usando a mais recente versão do Windows(TM) listada no ASL. Outras soluções alternativas podem exigir que o [.filename]#my.asl# seja personalizado. Se este arquivo for editado, compile o novo ASL usando o seguinte comando. Os avisos geralmente podem ser ignorados, mas erros são bugs que geralmente impedem que o ACPI funcione corretamente. [source,shell] .... # iasl -f my.asl .... Incluir `-f` força a criação do AML, mesmo que haja erros durante a compilação. Alguns erros, como a falta de declarações de retorno, são automaticamente contornados pelo interpretador do FreeBSD. O nome do arquivo de saída padrão para `iasl` é [.filename]#DSDT.aml#. Carregue este arquivo em vez da cópia com bugs do BIOS, que ainda está presente na memória flash, editando o [.filename]#/boot/loader.conf# como segue: [.programlisting] .... acpi_dsdt_load="YES" acpi_dsdt_name="/boot/DSDT.aml" .... Certifique-se de copiar o [.filename]#DSDT.aml# para [.filename]#/boot# e, em seguida, reinicialize o sistema. Se isso resolver o problema, envie um man:diff[1] do antigo e novo ASL para a lista http://lists.FreeBSD.org/mailman/listinfo/freebsd-acpi[freebsd-acpi] para que os desenvolvedores possam contornar o comportamento de bugs no [.filename]#acpica#. [[ACPI-submitdebug]] === Obtendo e enviando informações de depuração O driver ACPI possui um recurso de depuração flexível. Um conjunto de subsistemas e o nível de detalhamento podem ser especificados. Os subsistemas a serem depurados são especificados como camadas e são divididos em componentes (`ACPI_ALL_COMPONENTS`) e suporte de hardware ACPI (`ACPI_ALL_DRIVERS`). O detalhamento da saída de depuração é especificado como o nível e varia de apenas erros de relatório (`ACPI_LV_ERROR`) para tudo (`ACPI_LV_VERBOSE`). O nível é uma máscara de bits, por isso, várias opções podem ser definidas de uma só vez, separadas por espaços. Na prática, um console serial deve ser usado para registrar a saída para que ela não seja perdida quando o buffer de mensagem do console for liberado. Uma lista completa das camadas e níveis individuais é encontrada em man:acpi[4]. A saída de depuração não está ativada por padrão. Para ativá-la, adicione as opções `ACPI_DEBUG` ao arquivo de configuração do kernel personalizado se ACPI estiver compilado no kernel. Adicione `ACPI_DEBUG=1` ao [.filename]#/etc/make.conf# para ativá-lo globalmente. Se um módulo for usado em vez de um kernel personalizado, recompile apenas o módulo [.filename]#acpi.ko# como segue: [source,shell] .... # cd /sys/modules/acpi/acpi && make clean && make ACPI_DEBUG=1 .... Copie o [.filename]#acpi.ko# compilado para [.filename]#/boot/kernel# e adicione o nível e camada desejados ao [.filename]#/boot/loader.conf#. As entradas neste exemplo permitem mensagens de depuração para todos os componentes e drivers de hardware ACPI e mensagens de erro de saída no nível menos detalhado: [.programlisting] .... debug.acpi.layer="ACPI_ALL_COMPONENTS ACPI_ALL_DRIVERS" debug.acpi.level="ACPI_LV_ERROR" .... Se as informações necessárias forem acionadas por um evento específico, como suspend e resume, não modifique o [.filename]#/boot/loader.conf#. Em vez disso, use o `sysctl` para especificar o layer e o nível após inicializar e preparar o sistema para o evento específico. As variáveis que podem ser definidas usando `sysctl` são nomeadas da mesma forma que os parâmetros no [.filename]#/boot/loader.conf#. Depois que as informações de depuração forem coletadas, elas podem ser enviadas para a lista http://lists.FreeBSD.org/mailman/listinfo/freebsd-acpi[freebsd-acpi] para que possam ser usadas pelos mantenedores do FreeBSD ACPI para identificar a causa raiz do problema e desenvolver uma solução. [NOTE] ==== Antes de enviar as informações de depuração para esta lista, certifique-se de que a versão mais recente do BIOS esteja instalada e, se disponível, a versão do firmware do controlador incorporado. ==== Ao enviar um relatório de problemas, inclua as seguintes informações: * Descrição do comportamento de bugs, incluindo tipo de sistema, modelo e qualquer coisa que faça com que o erro apareça. Explique com a maior precisão possível quando o bug começou a ocorrer se for novo. * A saída do `dmesg` após executar `boot -v`, incluindo quaisquer mensagens de erro geradas pelo bug. * A saída `dmesg` do `boot -v` com o ACPI desabilitado, se a desativação do ACPI ajudar a corrigir o problema. * Saída do `sysctl hw.acpi`. Isso lista quais recursos o sistema oferece. * A URL para uma versão do ASL do sistema hospedada na web. _Não_ envie o ASL diretamente para a lista, pois pode ser muito grande. Gere uma cópia do ASL executando este comando: + [source,shell] .... # acpidump -dt > name-system.asl .... + Substitua o nome de login para _name_ e fabricante/modelo para _system_. Por exemplo, use [.filename]#njl-FooCo6000.asl#. A maioria dos desenvolvedores do FreeBSD assina a lista de discussão http://lists.FreeBSD.org/mailman/listinfo/freebsd-current[FreeBSD-CURRENT], mas deve-se enviar os problemas para a lista http://lists.FreeBSD.org/mailman/listinfo/freebsd-acpi[freebsd-acpi] para ter certeza de que ele será visto. Seja paciente ao esperar por uma resposta. Se o bug não for imediatamente aparente, envie um relatório de bug. Ao inserir um PR, inclua as mesmas informações solicitadas acima. Isso ajuda os desenvolvedores a rastrear o problema e resolvê-lo. Não envie um PR sem enviar primeiro um e-mail para a lista http://lists.FreeBSD.org/mailman/listinfo/freebsd-acpi[freebsd-acpi] pois é provável que o problema já tenha sido relatado antes. [[ACPI-References]] === Referências Mais informações sobre ACPI podem ser encontradas nos seguintes locais: * Arquivos da lista de e-mail do FreeBSD ACPI (https://lists.freebsd.org/pipermail/freebsd-acpi/[https://lists.freebsd.org/pipermail/freebsd-acpi/]) -* A especificação ACPI 2.0 (http://acpi.info/spec.htm[http://acpi.info/spec.htm]) +* A https://uefi.org/specifications#ACPI[especificação ACPI] * man:acpi[4], man:acpi_thermal[4], man:acpidump[8], man:iasl[8], e man:acpidb[8] diff --git a/documentation/content/ru/books/handbook/config/_index.adoc b/documentation/content/ru/books/handbook/config/_index.adoc index 2ca8b8ac76..a2c2020012 100644 --- a/documentation/content/ru/books/handbook/config/_index.adoc +++ b/documentation/content/ru/books/handbook/config/_index.adoc @@ -1,1298 +1,1298 @@ --- title: Глава 12. Настройка и оптимизация part: Часть III. Системное администрирование prev: books/handbook/partiii next: books/handbook/boot showBookMenu: true weight: 16 path: "/books/handbook/" --- [[config-tuning]] = Настройка и оптимизация :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 12 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/config/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[config-synopsis]] == Введение Один из важных аспектов FreeBSD это настройка системы. Правильная настройка системы поможет избежать головной боли при последующих обновлениях. Эта глава описывает большую часть процесса настройки FreeBSD, включая некоторые параметры, которые можно установить для оптимизации системы FreeBSD. После прочтения этой главы вы узнаете: * Как эффективно работать с файловыми системами и разделами подкачки. * Основы настройки [.filename]#rc.conf# и системы запуска приложений [.filename]#/usr/local/etc/rc.d#. * Как настроить и протестировать сетевую карту. * Как настроить виртуальные хосты на сетевых устройствах. * Как использовать различные файлы конфигурации в [.filename]#/etc#. * Как оптимизировать FreeBSD, используя переменные `sysctl`. * Как увеличить скорость работы дисков и изменить ограничения, накладываемые ядром. Перед прочтением этой главы вам следует: * Понять основы UNIX(R) и FreeBSD (crossref:basics[basics, Основы UNIX]). * Ознакомиться с основами конфигурации/компиляции ядра (crossref:kernelconfig[kernelconfig, Настройка ядра FreeBSD]). [[configtuning-initial]] == Начальное конфигурирование === Разделы диска ==== Основы построения разделов Во время разметки жёсткого диска с помощью man:bsdlabel[8] или man:sysinstall[8], важно помнить, что скорость чтения и записи данных уменьшается от внешних к внутренним трекам диска. Самые маленькие и самые часто используемые файловые системы (корневая и раздел подкачки) должны быть расположены в начале диска, в то время как самые большие, такие, как [.filename]#/usr#, в конце. Самым оптимальным считается следующий порядок расположения файловых систем: root, swap, [.filename]#/var#, [.filename]#/usr#. Размер файловой системы [.filename]#/var# определяется предназначением машины. [.filename]#/var# используется для хранения почтовых ящиков, очередей печати и лог файлов. Размер почтовых ящиков и лог файлов может расти неограниченно в зависимости от количества пользователей системы и от того, как долго хранятся лог-файлы. Большинству пользователей никогда не потребуется гигабайт, но помните, что [.filename]#/var/tmp# должен быть достаточно большим для пакетов. В разделе [.filename]#/usr# содержит большинство файлов, необходимых для поддержки системы, порты (man:ports[7], рекомендуется) и исходные тексты (опционально). Оба эти каталога опциональны при установке. Для этого раздела рекомендуется как минимум 2 гигабайта. При установке размера разделов, не забудьте принять во внимание рост размера требуемого системе дискового пространства. Переполнение одного раздела даже при наличии свободного места на другом может вызвать затруднения. [NOTE] ==== Многие пользователи обнаружили, что размер разделов, предлагаемый man:sysinstall[8]'ом по умолчанию, иногда меньше подходящего для разделов [.filename]#/var# и [.filename]#/#. Тщательно планируйте размер разделов и не жалейте места. ==== [[swap-design]] ==== Раздел подкачки Как правило, размер раздела подкачки должен быть равен удвоенному размеру оперативной памяти. Например, если на машине установлено 128 мегабайт памяти, раздел подкачки должен быть 256 мегабайт. Системы с меньшим количеством памяти могут работать лучше с большим объёмом раздела подкачки. Не рекомендуется устанавливать размер раздела подкачки меньше 256 мегабайт, необходимо также принять во внимание возможное наращивание объема установленной на машине памяти. Алгоритмы кэширования VM настроены на максимальное быстродействие, когда размер раздела подкачки равен как минимум удвоенному размеру памяти. Заниженный размер раздела подкачки может привести к неэффективной работе постраничного сканирования VM и вызвать проблемы при увеличении объёма памяти. На больших системах с несколькими SCSI дисками (или несколькими IDE дисками, находящимися на разных контроллерах), рекомендуется создавать раздел подкачки на каждом диске (до четырёх дисков). Разделы подкачки должны быть примерно одного размера. Ядро не накладывает ограничений на размер раздела подкачки, но внутренние структуры позволяют иметь общий размер разделов подкачки, равный наибольшему, умноженному на четыре. Выделение под разделы подкачки примерно одинакового места позволить ядру оптимально расположить разделы подкачки. Установка размера подкачки больше требуемого нормальна, даже если этот объем не используется. В этих условиях может быть проще восстановиться после зависания программы перед тем, как возникнет необходимость перезагрузки. ==== Зачем нужны разделы? Некоторые пользователи считают, что лучше использовать один большой раздел, но есть несколько причин, по которым этого лучше не делать. Во-первых, у каждого раздела свои характеристики, и отделяя их, можно выполнить соответствующие настройки. Например, корневая и файловая система и [.filename]#/usr# в основном предназначены для чтения, без большого объема записи. В то же время множество операций чтения и записи выполняется в [.filename]#/var# и [.filename]#/var/tmp#. При правильном размещении и выборе размера разделов системы, фрагментация в более маленьких разделах, куда часто записываются данные, не перенесётся на остальные разделы. Размещение самых часто используемых разделов ближе к началу диска увеличит скорость ввода/вывода там, где она нужна больше всего. Хотя производительность важна и для больших дисков, передвижение их ближе к концу диска не повлечёт значительного уменьшения быстродействия по сравнению с перемещением ближе к концу диска [.filename]#/var#. И, наконец, разделы существуют и из соображений безопасности. Наличие маленького аккуратного корневого раздела, доступного только для чтения даёт значительные шансы на "выживание" после краха системы. [[configtuning-core-configuration]] == Основные настройки Основные настройки системы располагаются в [.filename]#/etc/rc.conf#. Этот файл вмещает широкий спектр конфигурационной информации, используемой при загрузке системы. Имя этого файла прямо отражает его назначение, это файл настройки для файлов [.filename]#rc*#. Администратор должен сделать записи в [.filename]#rc.conf#, чтобы переопределить строки по умолчанию из [.filename]#/etc/defaults/rc.conf#. Файлы по умолчанию нельзя копировать в [.filename]#/etc# - они вмещают значения по умолчанию, а не примеры значений. Все специфичные для данной системы изменения должны быть сделаны в файле [.filename]#rc.conf#. Существует несколько методов для отделения общей конфигурации для группы систем от конкретной для данной системы в целях уменьшения объема работы администратора. Рекомендуемый метод - прописать общую конфигурацию в отдельный файл, например, в [.filename]#/etc/rc.conf.site#, и включить его название в [.filename]#/etc/rc.conf#, который вмещает только специфичную для данной системы информацию. Поскольку [.filename]#rc.conf# читается man:sh[1], есть тривиальный способ сделать это. Например: * rc.conf: + [.programlisting] .... . /etc/rc.conf.site hostname="node15.example.com" network_interfaces="fxp0 lo0" ifconfig_fxp0="inet 10.1.1.1" .... * rc.conf.site: + [.programlisting] .... defaultrouter="10.1.1.254" saver="daemon" blanktime="100" .... Файл [.filename]#rc.conf.site# может быть распространён на все системы, используя `rsync` или подобную ей программу, в то время, как [.filename]#rc.conf# должен остаться только на одной машине. Обновление системы с помощью man:sysinstall[8] или `make world` не повлекут за собой перезапись [.filename]#rc.conf#. Вся информация в этом файле сохранится. [[configtuning-appconfig]] == Настройка приложений Обычно, установленные приложения имеют свои конфигурационные файлы, со своим собственным синтаксисом. Важно хранить эти файлы отдельно от файлов основной системы, чтобы их можно было легко администрировать с помощью средств управления пакетами. Обычно эти файлы устанавливаются в [.filename]#/usr/local/etc#. В случае, если приложению нужно большое количество конфигурационных файлов, для их хранения будет создан подкаталог. Обычно, вместе с установкой портов и пакетов, устанавливаются и примеры конфигурационных файлов. Обычно они имеют расширение [.filename]#.default#. Если не существует конфигурационных файлов для этого приложения, они будут созданы путём копирования [.filename]#.default# файлов. Например, [.filename]#/usr/local/etc/apache#: .... -rw-r--r-- 1 root wheel 2184 May 20 1998 access.conf -rw-r--r-- 1 root wheel 2184 May 20 1998 access.conf.default -rw-r--r-- 1 root wheel 9555 May 20 1998 httpd.conf -rw-r--r-- 1 root wheel 9555 May 20 1998 httpd.conf.default -rw-r--r-- 1 root wheel 12205 May 20 1998 magic -rw-r--r-- 1 root wheel 12205 May 20 1998 magic.default -rw-r--r-- 1 root wheel 2700 May 20 1998 mime.types -rw-r--r-- 1 root wheel 2700 May 20 1998 mime.types.default -rw-r--r-- 1 root wheel 7980 May 20 1998 srm.conf -rw-r--r-- 1 root wheel 7933 May 20 1998 srm.conf.default .... Размеры файлов показывают, что только файл [.filename]#srm.conf# был изменён. При следующем обновлении Apache этот файл уже не будет перезаписан. [[configtuning-starting-services]] == Запуск сервисов Многие пользователи предпочитают устанавливать программы сторонних производителей в FreeBSD из набора портов. В подобных случаях может потребоваться сконфигурировать программы так, чтобы они запускались при инициализации системы. Сервисы, такие как package:mail/postfix[] или package:www/apache13[], - это лишь два примера множества программных пакетов, которые можно запускать при инициализации системы. В этом разделе описывается процедура, предназначенная для запуска программ сторонних разработчиков. Большинство входящих в FreeBSD сервисов, таких как man:cron[8], запускается с помощью стартовых скриптов системы. Эти скрипты могут различаться в зависимости от версии FreeBSD или ее производителя; однако важнее всего учитывать, что их начальную конфигурацию можно задать с помощью простых стартовых скриптов. До появления [.filename]#rc.d# приложения должны были помещать простой стартовый скрипт в каталог [.filename]#/usr/local/etc/rc.d#, который затем читался скриптами инициализации системы. Эти скрипты затем выполнялись в ходе последующих стадий запуска системы. Хотя много разработчиков потратили часы на попытки внедрить старый стиль конфигурирования в новую систему, остаётся фактом, что для некоторых утилит сторонних производителей по-прежнему необходим скрипт, помещённый в указанный выше каталог. Незначительные различия в скриптах зависят от того, используется ли [.filename]#rc.d#. До версии FreeBSD 5.1 использовались скрипты в старом стиле, и почти во всех случаях скрипты в новом стиле должны подойти так же хорошо. Хотя каждый скрипт должен соответствовать некоторым минимальным требованиям, в большинстве случаев эти требования не зависят от версии FreeBSD. Каждый скрипт должен иметь в конце расширение [.filename]#.sh# и каждый скрипт должен быть выполняемым. Последнее требование может быть выполнено путем установки командой `chmod` уникальных прав доступа `755`. Также, как минимум, должна быть опция `start` для запуска приложения и опция `stop` для его остановки. Простейший стартовый скрипт, пожалуй, будет похож на следующий: [.programlisting] .... #!/bin/sh echo -n ' utility' case "$1" in start) /usr/local/bin/utility ;; stop) kill -9 `cat /var/run/utility.pid` ;; *) echo "Usage: `basename $0` {start|stop}" 2 exit 64 ;; esac exit 0 .... Этот скрипт поддерживает опции `stop` и `start` для приложения, которое мы здесь называем просто - `utility`. А можно запускать его и вручную, с помощью команды: [source,shell] .... # /usr/local/etc/rc.d/utility.sh start .... Хотя и не все программы сторонних производителей требуют добавления строки в файл [.filename]#rc.conf#, практически каждый день очередной новый порт меняется так, чтобы поддерживать подобную конфигурацию. Поищите в результатах, выдаваемых после установки более детальную информацию по конкретному приложению. Некоторые программы сторонних производителей будут включать стартовые скрипты, позволяющие использовать приложение с [.filename]#rc.d#; но это мы еще обсудим в следующем разделе. === Расширенное конфигурирование приложения Теперь, когда FreeBSD включает [.filename]#rc.d#, конфигурирование запуска приложений стало более оптимальным; фактически, оно стало более тщательным. С помощью ключевых слов, рассмотренных в разделе <>, приложения теперь можно настроить для запуска после других заданных сервисов, например, DNS; можно разрешить передачу дополнительных флагов через [.filename]#rc.conf# вместо жесткого задания флагов в стартовых скриптах, и т.д. Простой скрипт может иметь следующий вид: [.programlisting] .... #!/bin/sh # # PROVIDE: utility # REQUIRE: DAEMON # KEYWORD: shutdown . /etc/rc.subr name=utility rcvar=utility_pidfile command="/usr/local/sbin/utility" load_rc_config $name # # НЕ МЕНЯЙТЕ ЗДЕСЬ ЭТИ СТАНДАРТНЫЕ ЗНАЧЕНИЯ # ЗАДАВАЙТЕ ИХ В ФАЙЛЕ /etc/rc.conf # utility_enable=${utility_enable-"NO"} pidfile=${utility_pidfile-"/var/run/utility.pid"} run_rc_command "$1" .... Этот скрипт будет гарантировать, что указанное приложение utility будет запущено после сервиса `daemon`. Он также предоставляет метод для создания и отслеживания файла идентификатора процесса, PID. Для этого приложения затем можно поместить следующую строку в файл [.filename]#/etc/rc.conf#: [.programlisting] .... utility_enable="YES" .... Этот новый метод также позволяет легко работать с аргументами командной строки, включать стандартные функции из файла [.filename]#/etc/rc.subr#, обеспечивает совместимость с утилитой man:rcorder[8] и упрощает конфигурирование с помощью файла [.filename]#rc.conf#. === Использование сервисов для запуска сервисов Другие сервисы, такие как даемоны сервера POP3, IMAP, и т.п. могут быть запущены с помощью man:inetd[8]. Для этого необходимо установить сервисную утилиту из набора портов и добавить соответствующую строчку конфигурации в файл [.filename]#/etc/inetd.conf# или раскомментировать подходящую строку конфигурации из уже имеющихся. Работа с даемоном inetd и его конфигурирование подробно описаны в разделе crossref:network-servers[network-inetd,inetd]. В некоторых случаях использование для запуска системных служб даемона man:cron[8] может оказаться более приемлемым. Этот подход имеет несколько преимуществ, поскольку даемон `cron` запускает эти процессы от имени владельца файла [.filename]#crontab#. Это позволяет обычным пользователям запускать и поддерживать некоторые приложения. Утилита `cron` поддерживает уникальную возможность, `@reboot`, - это значение можно использовать вместо спецификации времени. В результате, задание будет выполнено при запуске man:cron[8], обычно - в ходе инициализации системы. [[configtuning-cron]] == Настройка утилиты `cron` Одна из наиболее полезных утилит FreeBSD это man:cron[8]. Утилита `cron` работает в фоновом режиме и постоянно проверяет файл [.filename]#/etc/crontab#. Утилита `cron` проверяет также каталог [.filename]#/var/cron/tabs# в поиске новых файлов [.filename]#crontab#. Файлы [.filename]#crontab# содержат информацию об определенных функциях, которые `cron` выполняет в указанное время. Утилита `cron` использует два разных типа конфигурационных файлов, системный и пользовательский. Все различие между этими двумя форматами заключается в шестом поле. В системном файле шестое поля это имя пользователя, с правами которого будет запущена команда. Это позволяет запускать команды из системного crontab от любого пользователя. В пользовательском файле шестое поле указывает запускаемую команду, и все команды запускаются от пользователя, который создал crontab; это важно для безопасности. [NOTE] ==== Пользовательские crontab позволяют индивидуальным пользователям планировать задачи без привилегий суперпользователя (`root`). Команды из crontab пользователя запускаются с привилегиями этого пользователя. Пользователь `root` может использовать собственный crontab, как и любой другой пользователь. Он будет отличаться от системного crontab [.filename]#/etc/crontab#. Поскольку существует системный crontab, обычно не требуется создавать пользовательский crontab для `root`. ==== Давайте заглянем в файл [.filename]#/etc/crontab# (системный crontab): [.programlisting] .... # /etc/crontab - root's crontab for FreeBSD # # $FreeBSD: src/etc/crontab,v 1.32 2002/11/22 16:13:39 tom Exp $ ## <.> # SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin <.> HOME=/var/log # # #minute hour mday month wday who command <.> # # */5 * * * * root /usr/libexec/atrun <.> .... <.> Как и в большинстве файлов настройки FreeBSD, символы "#" означают комментарии. Комментарии нужны для напоминания о том, что означает строка и зачем она добавлена. Комментарии не могут находиться на той же строке, что и команда, или они будут восприняты как часть команды; располагайте их на новой строке. Пустые строки игнорируются. <.> Сначала должны быть заданы переменные окружения. Знак равно (`=`) используется для задания переменных окружения, в этом примере `SHELL`, `PATH`, и `HOME`. Если переменная для оболочки не задана, `cron` использует оболочку по умолчанию, `sh`. Если не задана переменная `PATH`, значение по умолчанию не устанавливается и пути к файлам должны быть полными. Если не задана переменная `HOME`, `cron` будет использовать домашний каталог соответствующего пользователя. <.> В строке всего семь полей. Их значения `minute`, `hour`, `mday`, `month`, `wday`, `who` (кто), и `command`. Значение полей почти очевидно. `minute` это время в минутах, когда будет запущена команда. `hour` означает то же самое для часов. `mday` означает день месяца. `month`, это то же самое, что час и минута, но для месяцев. Параметр `wday` это день недели. Все эти поля должны быть в числовом формате, время в двадцатичетырехчасовом исчислении. Поле `who` имеет специальное значение, и присутствует только в файле [.filename]#/etc/crontab#. Это поле определяет пользователя, с правами которого должна быть запущена команда. Когда пользователь устанавливает собственный файл [.filename]#crontab#, он не указывает этот параметр. Последний параметр `command`. Он указывает команду, которая должна быть запущена. <.> Последняя строка определяет параметры, описанные выше. Здесь задано значение `\*/5`, и несколько символов `\*`. Эти символы `*` означают "первый-последний", и могут быть интерпретированы как _каждый_. Таким образом, для этой строки соответствующая команда `atrun` вызывается под пользователем `root` каждые пять минут независимо от дня или месяца. За дополнительной информацией по команде `atrun` обращайтесь к странице справочника man:atrun[8].Команды могут принимать любое количество параметров; однако команды, состоящие из нескольких строк, должны быть объединены символом "\". Этот формат одинаков для каждого файла [.filename]#crontab#, за исключением одной детали. Шестое поле, где указано имя пользователя, присутствует только в файле [.filename]#/etc/crontab#. Это поле должно быть исключено из [.filename]#crontab# файлов пользователей. [[configtuning-installcrontab]] === Установка crontab [IMPORTANT] ==== Вы не должны использовать процедуру, описанную здесь, для установки системного crontab. Просто используйте свой любимый текстовый редактор: утилита `cron` узнает о том, что файл изменился и сразу начнет использовать обновленную версию. Обратитесь к extref:{faq}[этой части FAQ, ROOT-NOT-FOUND-CRON-ERRORS] за дальнейшей информацией. ==== Для установки готового [.filename]#crontab# пользователя, сначала создайте в вашем любимом редакторе файл соответствующего формата, а затем воспользуйтесь утилитой `crontab`. Обычно она запускается так: [source,shell] .... % crontab crontab-file .... В этом примере, [.filename]#crontab-file# это имя файла crontab, который только что был создан. Существует также параметр для просмотра установленных файлов [.filename]#crontab#: задайте `crontab` параметр `-l`. Для пользователей, составляющих crontab вручную, без временного файла, существует параметр `crontab -e`. Она вызовет редактор с пустым файлом. Когда файл будет сохранен, `crontab` автоматически установит его. Если позднее вы захотите полностью удалить свой [.filename]#crontab#, используйте `crontab` с параметром `-r`. [[configtuning-rcd]] == Использование rc во FreeBSD 5.X и последующих версиях Во FreeBSD недавно была интегрирована из NetBSD система [.filename]#rc.d#, используемая для старта системы. Многие из файлов в каталоге [.filename]#/etc/rc.d# предназначены для основных сервисов, они могут управляться параметрами `start`, `stop`, и `restart`. Например, man:sshd[8] может быть перезапущен следующей командой: [source,shell] .... # /etc/rc.d/sshd restart .... Эта процедура похожа для других сервисов. Конечно, сервисы обычно запускаются автоматически при загрузке системы, как указано в man:rc.conf[5]. Например, включение даемона Network Address Translation при запуске выполняется простым добавлением следующей строки в [.filename]#/etc/rc.conf#: [.programlisting] .... natd_enable="YES" .... Если `natd_enable="NO"` уже присутствует, просто измените `NO` на `YES`. Скрипты rc автоматически загрузят все другие зависимые сервисы, как описано ниже. Поскольку система [.filename]#rc.d# в основном предназначена для запуска/отключения сервисов во время запуска/отключения системы, стандартные параметры `start`, `stop` и `restart` будут работать только если установлена соответствующая переменная в [.filename]#/etc/rc.conf#. Например, команда выше `sshd restart` будет работать только если переменная `sshd_enable` в файле [.filename]#/etc/rc.conf# установлена в `YES`. Для выполнения скриптов независимо от установок в [.filename]#/etc/rc.conf#, параметры `start`, `stop` или `restart` необходимо задавать с префиксом "force". Например, для перезапуска `sshd` независимо от установок в [.filename]#/etc/rc.conf#, выполните следующую команду: [source,shell] .... # /etc/rc.d/sshd forcerestart .... Проверить состояние переменной в файле [.filename]#/etc/rc.conf# легко: запустите соответствующий скрипт из [.filename]#rc.d# с параметром `rcvar`. Проверка переменной для `sshd` выполняется следующей командой: [source,shell] .... # /etc/rc.d/sshd rcvar # sshd $sshd_enable=YES .... [NOTE] ==== Вторая строка (`# sshd`) это вывод команды `sshd`, а не консоль `root`. ==== Чтобы определить, запущен ли сервис, существует параметр `status`. Например для проверки того, запущен ли `sshd`, выполните: [source,shell] .... # /etc/rc.d/sshd status sshd is running as pid 433. .... В некоторых случаях возможна также перегрузка (`reload`) сервиса. Скрипт, запущенный с этим параметром, попытается отправить сервису сигнал, вызывающий перезагрузку файлов настройки. В большинстве случаев это означает отправку сервису сигнала `SIGHUP`. Следует помнить, что эту функцию поддерживают не все сервисы. Система [.filename]#rc.d# используется не только для сетевых серверов, она отвечает также за большую часть инициализации системы. Рассмотрим, к примеру, файл [.filename]#bgfsck#. Во время выполнения этот скрипт выводит следующее сообщение: [source,shell] .... Starting background file system checks in 60 seconds. .... Следовательно, этот файл используется для фоновой проверки файловых систем, которая выполняется только в процессе инициализации системы. Функционирование многих сервисов системы зависит от корректной работы других сервисов. Например, NIS и другие основанные на RPC сервисы могут не запуститься, пока не загрузится `rpcbind` (portmapper). Для разрешения этой проблемы, в начале каждого скрипта в комментарии включаются информация о зависимостях и другие метаданные. Программа man:rcorder[8] используется для разбора этих комментариев во время старта системы для определения порядка, в котором должны вызываться системные сервисы в соответствии с зависимостями. В начало каждого стартового файла должны быть включены следующие строки: * `PROVIDE`: Задает имя сервиса, предоставляемого этим файлом. * `REQUIRE`: Список сервисов, необходимых этому сервису. Этот файл будет запущен _после_ указанных сервисов. * `BEFORE`: Список сервисов, зависящих от этого сервиса. Этот файл будет запущен _до_ указанных сервисов. Используя этот метод, администратор может легко контролировать системные сервисы без использования "уровней запуска", как в некоторых других операционных системах UNIX(R). Дополнительную информацию о системе [.filename]#rc.d# можно найти на страницах справочника man:rc[8] и man:rc.subr[8]. [[config-network-setup]] == Настройка карт сетевых интерфейсов В наши дни мы не представляем себе компьютера без сетевого подключения. Добавление и настройка сетевой карты это обычная задача любого администратора FreeBSD. === Поиск подходящего драйвера В первую очередь определите тип используемой карты (PCI или ISA), модель карты и используемый в ней чип. FreeBSD поддерживает многие PCI и ISA карты. Обратитесь к Списку поддерживаемого оборудования вашего релиза чтобы узнать, поддерживается ли карта. Как только вы убедились, что карта поддерживается, потребуется определить подходящий драйвер. В файлах [.filename]#/usr/src/sys/conf/NOTES# и [.filename]#/usr/src/sys/arch/conf/NOTES# находится список драйверов сетевых интерфейсов с информацией о поддерживаемых чипсетах/картах. Если вы сомневаетесь в том, какой драйвер подойдет, прочтите страницу справочника к драйверу. Страница справочника содержит больше информации о поддерживаемом оборудовании и даже о проблемах, которые могут возникнуть. Если ваша карта широко распространена, вам скорее всего не потребуется долго искать драйвер. Драйверы для широко распространенных карт представлены в ядре [.filename]#GENERIC#, так что ваша карта должна определиться при загрузке, примерно так: [source,shell] .... dc0: <82c169 PNIC 10/100BaseTX> port 0xa000-0xa0ff mem 0xd3800000-0xd38 000ff irq 15 at device 11.0 on pci0 dc0: Ethernet address: 00:a0:cc:da:da:da miibus0: on dc0 ukphy0: on miibus0 ukphy0: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc1: <82c169 PNIC 10/100BaseTX> port 0x9800-0x98ff mem 0xd3000000-0xd30 000ff irq 11 at device 12.0 on pci0 dc1: Ethernet address: 00:a0:cc:da:da:db miibus1: on dc1 ukphy1: on miibus1 ukphy1: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto .... В этом примере две карты используют имеющийся в системе драйвер man:dc[4]. Если драйвер вашей сетевой карты отсутствует в [.filename]#GENERIC#, для ее использования потребуется загрузить подходящий драйвер. Это может быть сделано одним из двух способов: * Простейший способ - просто загрузить модуль ядра сетевой карты с помощью man:kldload[8]. Не все драйверы доступны в виде модулей; например, модули отсутствуют для ISA карт. * Вместо этого, вы можете статически включить поддержку карты, скомпилировав собственное ядро. Информацию о том, какие параметры нужно включать в ядро, можно получить из [.filename]#/usr/src/sys/conf/NOTES#, [.filename]#/usr/src/sys/arch/conf/NOTES# и страницы справочника драйвера сетевой карты. За более подробной информацией о сборке собственного ядра обращайтесь к crossref:kernelconfig[kernelconfig, Настройка ядра FreeBSD]. Если карта была обнаружена вашим ядром ([.filename]#GENERIC#) во время загрузки, собирать ядро не потребуется. === Настройка сетевой карты Как только для сетевой карты загружен подходящий драйвер, ее потребуется настроить. Как и многое другое, сетевая карта может быть настроена во время установки с помощью sysinstall. Для вывода информации о настройке сетевых интерфейсов системы, введите следующую команду: [source,shell] .... % ifconfig dc0: flags=8843 mtu 1500 inet 192.168.1.3 netmask 0xffffff00 broadcast 192.168.1.255 ether 00:a0:cc:da:da:da media: Ethernet autoselect (100baseTX ) status: active dc1: flags=8843 mtu 1500 inet 10.0.0.1 netmask 0xffffff00 broadcast 10.0.0.255 ether 00:a0:cc:da:da:db media: Ethernet 10baseT/UTP status: no carrier lp0: flags=8810 mtu 1500 lo0: flags=8049 mtu 16384 inet 127.0.0.1 netmask 0xff000000 tun0: flags=8010 mtu 1500 .... [NOTE] ==== Старые версии FreeBSD могут потребовать запуска man:ifconfig[8] с параметром `-a`, за более подробным описанием синтаксиса man:ifconfig[8] обращайтесь к странице справочника. Учтите также, что строки, относящиеся к IPv6 (`inet6` и т.п.) убраны из этого примера. ==== В этом примере были показаны следующие устройства: * [.filename]#dc0#: первый Ethernet интерфейс * [.filename]#dc1#: второй Ethernet интерфейс * [.filename]#lp0#: интерфейс параллельного порта * [.filename]#lo0#: устройство loopback * [.filename]#tun0#: туннельное устройство, используемое ppp Для присвоения имени сетевой карте FreeBSD использует имя драйвера и порядковый номер, в котором карта обнаруживается при инициализации устройств. Например, [.filename]#sis2# это третья сетевая карта, использующая драйвер man:sis[4]. В этом примере, устройство [.filename]#dc0# включено и работает. Ключевые признаки таковы: . `UP` означает, что карта настроена и готова. . У карты есть интернет (`inet`) адрес (в данном случае `192.168.1.3`). . Установлена маска подсети (`netmask`; `0xffffff00`, то же, что и `255.255.255.0`). . Широковещательный адрес (в данном случае, `192.168.1.255`). . Значение MAC адреса карты (`ether`) `00:a0:cc:da:da:da` . Выбор физической среды передачи данных в режиме автовыбора (`media: Ethernet autoselect (100baseTX full-duplex)`). Мы видим, что [.filename]#dc1# была настроена для работы с `10baseT/UTP`. За более подробной информацией о доступных драйверу типах среды обращайтесь к странице справочника. . Статус соединения (`status`) `active`, т.е. несущая обнаружена. Для [.filename]#dc1#, мы видим `status: no carrier`. Это нормально, когда Ethernet кабель не подключен к карте. Если man:ifconfig[8] показывает примерно следующее: [source,shell] .... dc0: flags=8843 mtu 1500 ether 00:a0:cc:da:da:da .... это означает, что карта не была настроена. Для настройки карты вам потребуются привилегии пользователя `root`. Настройка сетевой карты может быть выполнена из командной строки с помощью man:ifconfig[8], но вам потребуется делать это после каждой перезагрузки системы. Подходящее место для настройки сетевых карт это файл [.filename]#/etc/rc.conf#. Откройте [.filename]#/etc/rc.conf# в текстовом редакторе. Вам потребуется добавить строку для каждой сетевой карты, имеющейся в системе, например, в нашем случае, было добавлено две строки: [.programlisting] .... ifconfig_dc0="inet 192.168.1.3 netmask 255.255.255.0" ifconfig_dc1="inet 10.0.0.1 netmask 255.255.255.0 media 10baseT/UTP" .... Замените [.filename]#dc0#, [.filename]#dc1#, и так далее на соответствующие имена ваших карт, подставьте соответствующие адреса. Обратитесь к страницам справочника сетевой карты и man:ifconfig[8], за подробной информацией о доступных опциях и к странице справочника man:rc.conf[5] за дополнительной информацией о синтаксисе [.filename]#/etc/rc.conf#. Если вы настроили сетевую карту в процессе установки системы, некоторые строки, касающиеся сетевой карты, могут уже присутствовать. Внимательно проверьте [.filename]#/etc/rc.conf# перед добавлением каких-либо строк. Отредактируйте также файл [.filename]#/etc/hosts# для добавления имен и IP адресов различных компьютеров сети, если их еще там нет. За дополнительной информацией обращайтесь к man.hosts.5; и к [.filename]#/usr/shared/examples/etc/hosts#. === Тестирование и решение проблем Как только вы внесете необходимые изменения в [.filename]#/etc/rc.conf#, перегрузите компьютер. Изменения настроек интерфейсов будут применены, кроме того будет проверена правильность настроек. Как только система перезагрузится, проверьте сетевые интерфейсы. ==== Проверка Ethernet карты Для проверки правильности настройки сетевой карты, попробуйте выполнить ping для самого интерфейса, а затем для другой машины в локальной сети. Сначала проверьте локальный интерфейс: [source,shell] .... % ping -c5 192.168.1.3 PING 192.168.1.3 (192.168.1.3): 56 data bytes 64 bytes from 192.168.1.3: icmp_seq=0 ttl=64 time=0.082 ms 64 bytes from 192.168.1.3: icmp_seq=1 ttl=64 time=0.074 ms 64 bytes from 192.168.1.3: icmp_seq=2 ttl=64 time=0.076 ms 64 bytes from 192.168.1.3: icmp_seq=3 ttl=64 time=0.108 ms 64 bytes from 192.168.1.3: icmp_seq=4 ttl=64 time=0.076 ms --- 192.168.1.3 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.074/0.083/0.108/0.013 ms .... Затем проверьте другую машину в локальной сети: [source,shell] .... % ping -c5 192.168.1.2 PING 192.168.1.2 (192.168.1.2): 56 data bytes 64 bytes from 192.168.1.2: icmp_seq=0 ttl=64 time=0.726 ms 64 bytes from 192.168.1.2: icmp_seq=1 ttl=64 time=0.766 ms 64 bytes from 192.168.1.2: icmp_seq=2 ttl=64 time=0.700 ms 64 bytes from 192.168.1.2: icmp_seq=3 ttl=64 time=0.747 ms 64 bytes from 192.168.1.2: icmp_seq=4 ttl=64 time=0.704 ms --- 192.168.1.2 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.700/0.729/0.766/0.025 ms .... Вы можете также использовать имя машины вместо `192.168.1.2`, если настроен файл [.filename]#/etc/hosts#. ==== Решение проблем Решение проблем с аппаратным и программным обеспечением всегда вызывает сложности, которые можно уменьшить, проверив сначала самые простые варианты. Подключен ли сетевой кабель? Правильно ли настроены сетевые сервисы? Правильно ли настроен брандмауэр? Поддерживается ли используемая карта в FreeBSD? Всегда проверяйте информацию об оборудовании перед отправкой сообщения об ошибке. Обновите FreeBSD до последней версии STABLE. Просмотрите архивы списков рассылки, или поищите информацию в интернет. Если карта работает, но производительность низка, может помочь чтение страницы справочника man:tuning[7]. Проверьте также настройки сети, поскольку неправильные настройки могут стать причиной низкой скорости соединения. Некоторые пользователи встречаются с несколькими `device timeouts`, что нормально для некоторых сетевых карт. Если это продолжается и надоедает, убедитесь, что устройство не конфликтует с другим устройством. Внимательно проверьте подключение кабеля. Возможно также, что вам просто надо установить другую карту. Время от времени, пользователи видят несколько ошибок `watchdog timeout`. Первое, что требуется сделать, это проверить сетевой кабель. Многие карты требуют поддержки Bus Mastering слотом PCI. На некоторых старых материнских платах, только один PCI слот имеет такую поддержку (обычно слот 0). Сверьтесь с документацией на сетевую карту и материнскую плату, чтобы определить, может ли это быть проблемой. Сообщение `No route to host` появляются, если система не в состоянии доставить пакеты к хосту назначения. Это может случиться, если не определен маршрут по умолчанию, или кабель не подключен. Проверьте вывод команды `netstat -rn` и убедитесь, что к соответствующему хосту есть работающий маршрут. Если это не так, прочтите crossref:advanced-networking[advanced-networking, Сложные вопросы работы в сети]. Сообщения `ping: sendto: Permission denied` зачастую появляются при неправильно настроенном брандмауэре. Если `ipfw` включен в ядре, но правила не определены, правило по умолчанию блокирует весь трафик, даже запросы ping! Прочтите crossref:firewalls[firewalls, Межсетевые экраны] с более подробной информацией. Иногда скорость карты недостаточна, или ниже среднего. В этих случаях лучше всего изменить режим выбора типа подключения с `autoselect` на правильный тип. Обычно это работает для большинства оборудования, но не может решить проблему во всех случаях. Проверьте еще раз настройки сети и прочтите страницу справочника man:tuning[7]. [[configtuning-virtual-hosts]] == Настройка виртуальных серверов Очень часто FreeBSD используется для размещения сайтов, когда один сервер работает в сети как несколько серверов. Это достигается присвоением нескольких сетевых адресов одному интерфейсу. У сетевого интерфейса всегда есть один "настоящий" адрес, хотя он может иметь любое количество "синонимов" (alias). Эти синонимы обычно добавляются путём помещения соответствующих записей в [.filename]#/etc/rc.conf#. Синоним для интерфейса [.filename]#fxp0# выглядит следующим образом: [.programlisting] .... ifconfig_fxp0_alias0="inet xxx.xxx.xxx.xxx netmask xxx.xxx.xxx.xxx" .... Заметьте, что записи синонимов должны начинаться с `alias0` и идти далее в определенном порядке (например, `_alias1`, `_alias2`, и т.д.). Конфигурационный процесс остановится на первом по порядку отсутствующем числе. Определение маски подсети для синонима очень важно, но к счастью, так же просто. Для каждого интерфейса должен быть один адрес с истинной маской подсети. Любой другой адрес в сети должен иметь маску подсети, состоящую из всех единичек (что выражается как `255.255.255.255` или как `0xffffffff`). Например, рассмотрим случай, когда интерфейс [.filename]#fxp0# подключён к двум сетям, к сети `10.1.1.0` с маской подсети `255.255.255.0` и к сети `202.0.75.16` с маской `255.255.255.240`. Мы хотим, чтобы система была видна по IP, начиная с `10.1.1.1` по `10.1.1.5` и с `202.0.75.17` по `202.0.75.20`. Как было сказано выше, только первый адрес в заданном диапазоне (в данном случае, `10.0.1.1` и `202.0.75.17`) должен иметь реальную маску сети; все остальные (с `10.1.1.2` по `10.1.1.5` и с `202.0.75.18` по `202.0.75.20`) должны быть сконфигурированы с маской сети `255.255.255.255`. Для этого в файл [.filename]#/etc/rc.conf# должны быть внесены следующие записи: [.programlisting] .... ifconfig_fxp0="inet 10.1.1.1 netmask 255.255.255.0" ifconfig_fxp0_alias0="inet 10.1.1.2 netmask 255.255.255.255" ifconfig_fxp0_alias1="inet 10.1.1.3 netmask 255.255.255.255" ifconfig_fxp0_alias2="inet 10.1.1.4 netmask 255.255.255.255" ifconfig_fxp0_alias3="inet 10.1.1.5 netmask 255.255.255.255" ifconfig_fxp0_alias4="inet 202.0.75.17 netmask 255.255.255.240" ifconfig_fxp0_alias5="inet 202.0.75.18 netmask 255.255.255.255" ifconfig_fxp0_alias6="inet 202.0.75.19 netmask 255.255.255.255" ifconfig_fxp0_alias7="inet 202.0.75.20 netmask 255.255.255.255" .... [[configtuning-configfiles]] == Файлы настройки === Каталог [.filename]#/etc# Во FreeBSD определён ряд каталогов, предназначенных для хранения конфигурационных файлов. Это: [.informaltable] [cols="1,1", frame="none"] |=== |[.filename]#/etc# |Основные файлы конфигурации системы. Тут размещены системно-зависимые данные. |[.filename]#/etc/defaults# |Версии системных конфигурационных файлов по умолчанию. |[.filename]#/etc/mail# |Дополнительные конфигурационные файлы man:sendmail[8], другие конфигурационные файлы MTA. |[.filename]#/etc/ppp# |Настройка для user- и kernel-ppp программ. |[.filename]#/etc/namedb# |Основное место расположения данных man:named[8]. Обычно [.filename]#named.conf# и файлы зон расположены здесь. |[.filename]#/usr/local/etc# |Конфигурационные файлы установленных приложений. Могут содержать подкаталоги приложений. |[.filename]#/usr/local/etc/rc.d# |Скрипты запуска/остановки установленных приложений. |[.filename]#/var/db# |Автоматически генерируемые системно-специфичные файлы баз данных, такие как база данных пакетов, и так далее |=== === Имена хостов ==== [.filename]#/etc/resolv.conf# [.filename]#/etc/resolv.conf# определяет, как резолвер (resolver) FreeBSD получает доступ к Системе Доменных Имён (DNS). Основные записи [.filename]#resolv.conf#: [.informaltable] [cols="1,1", frame="none"] |=== |`nameserver` |IP адрес сервера имён. Сервера опрашиваются в порядке описания. Максимальное количество адресов - три. |`search` |Список доменов для поиска с помощью hostname lookup. Обычно определяется доменом, в котором находится компьютер. |`domain` |Домен, в котором находится компьютер. |=== Типичный вид [.filename]#resolv.conf#: [.programlisting] .... search example.com nameserver 147.11.1.11 nameserver 147.11.100.30 .... [NOTE] ==== Опции `search` и `domain` нельзя использовать совместно. ==== Если вы используете DHCP, man:dhclient[8] обычно перезаписывает [.filename]#resolv.conf# информацией, полученной от серверов DHCP. ==== [.filename]#/etc/hosts# [.filename]#/etc/hosts# - простая текстовая база данных, напоминающая старый Интернет. Она работает совместно с DNS и NIS, сопоставляя доменные имена IP адресу. Отдельные компьютеры, соединённые с помощью локальной сети, могут быть записаны тут вместо man:named[8] сервера с целью упрощения. Кроме того, [.filename]#/etc/hosts# используется для записи IP адресов и соответствующих им доменов, избавляя от внешнего трафика, используемого для запросов к DNS серверам. [.programlisting] .... # $FreeBSD$ # # Host Database # This file should contain the addresses and aliases # for local hosts that share this file. # In the presence of the domain name service or NIS, this file may # not be consulted at all; see /etc/nsswitch.conf for the resolution order. # # ::1 localhost localhost.my.domain myname.my.domain 127.0.0.1 localhost localhost.my.domain myname.my.domain # # Imaginary network. #10.0.0.2 myname.my.domain myname #10.0.0.3 myfriend.my.domain myfriend # # According to RFC 1918, you can use the following IP networks for # private nets which will never be connected to the Internet: # # 10.0.0.0 - 10.255.255.255 # 172.16.0.0 - 172.31.255.255 # 192.168.0.0 - 192.168.255.255 # # In case you want to be able to connect to the Internet, you need # real official assigned numbers. PLEASE PLEASE PLEASE do not try # to invent your own network numbers but instead get one from your # network provider (if any) or from the Internet Registry (ftp to # rs.internic.net, directory `/templates'). # .... Формат [.filename]#/etc/hosts#: [.programlisting] .... [IP адрес в Интернете] [имя компьютера] [alias1] [alias2] ... .... Например: [.programlisting] .... 10.0.0.1 myRealHostname.example.com myRealHostname foobar1 foobar2 .... За дополнительной информацией обращайтесь к man:hosts[5]. === Настройка лог файлов ==== [.filename]#syslog.conf# [.filename]#syslog.conf# is является файлом конфигурации для man:syslogd[8]. В нём указываются, типы сообщений генерируемые `syslog`, и лог файлы, в которые они записываются. [.programlisting] .... # $FreeBSD$ # # Spaces ARE valid field separators in this file. However, # other *nix-like systems still insist on using tabs as field # separators. If you are sharing this file between systems, you # may want to use only tabs as field separators here. # Consult the syslog.conf(5) manual page. *.err;kern.debug;auth.notice;mail.crit /dev/console *.notice;kern.debug;lpr.info;mail.crit;news.err /var/log/messages security.* /var/log/security mail.info /var/log/maillog lpr.info /var/log/lpd-errs cron.* /var/log/cron *.err root *.notice;news.err root *.alert root *.emerg * # uncomment this to log all writes to /dev/console to /var/log/console.log #console.info /var/log/console.log # uncomment this to enable logging of all log messages to /var/log/all.log #*.* /var/log/all.log # uncomment this to enable logging to a remote log host named loghost #*.* @loghost # uncomment these if you're running inn # news.crit /var/log/news/news.crit # news.err /var/log/news/news.err # news.notice /var/log/news/news.notice !startslip *.* /var/log/slip.log !ppp *.* /var/log/ppp.log .... За более полной информацией обратитесь к man:syslog.conf[5]. ==== [.filename]#newsyslog.conf# [.filename]#newsyslog.conf# - конфигурационный файл man:newsyslog[8], программы, обычно контролируемой man:cron[8]. man:newsyslog[8] определяет, когда лог-файлы нуждаются в архивировании и перегруппировке. [.filename]#logfile# перемещается в [.filename]#logfile.0#, [.filename]#logfile.0# перемещается в [.filename]#logfile.1#, и так далее. Другое именование получится при архивировании с помощью man:gzip[1]: [.filename]#logfile.0.gz#, [.filename]#logfile.1.gz#, и т.д. [.filename]#newsyslog.conf# показывает, какие лог файлы должны быть проинспектированы, сколько их должно быть сохранено, и когда они должны быть пересмотрены. Лог файлы могут быть перегруппированы и/или заархивированы, когда они либо достигнут определённого размера, либо при достижении определённых даты/времени. [.programlisting] .... # configuration file for newsyslog # $FreeBSD$ # # filename [owner:group] mode count size when [ZB] [/pid_file] [sig_num] /var/log/cron 600 3 100 * Z /var/log/amd.log 644 7 100 * Z /var/log/kerberos.log 644 7 100 * Z /var/log/lpd-errs 644 7 100 * Z /var/log/maillog 644 7 * @T00 Z /var/log/sendmail.st 644 10 * 168 B /var/log/messages 644 5 100 * Z /var/log/all.log 600 7 * @T00 Z /var/log/slip.log 600 3 100 * Z /var/log/ppp.log 600 3 100 * Z /var/log/security 600 10 100 * Z /var/log/wtmp 644 3 * @01T05 B /var/log/daily.log 640 7 * @T00 Z /var/log/weekly.log 640 5 1 $W6D0 Z /var/log/monthly.log 640 12 * $M1D0 Z /var/log/console.log 640 5 100 * Z .... За дополнительной информацией обращайтесь к man:newsyslog[8]. [[configtuning-sysctlconf]] === [.filename]#sysctl.conf# [.filename]#sysctl.conf# очень похож на [.filename]#rc.conf#. Значения устанавливаются в виде `variable=value`. Указанные значения устанавливаются после перевода системы в многопользовательский режим. Однако не все переменные могут быть установлены в этом режиме. Пример [.filename]#sysctl.conf#, настроенного для выключения протоколирования фатальных ошибок программ и разрешения Linux-программам определять, что они запускаются под FreeBSD: [.programlisting] .... kern.logsigexit=0 # Do not log fatal signal exits (e.g. sig 11) compat.linux.osname=FreeBSD compat.linux.osrelease=4.3-STABLE .... [[configtuning-sysctl]] == Настройка с помощью sysctl man:sysctl[8] - это интерфейс, позволяющий вам вносить изменения в работающую систему FreeBSD. Эти изменения касаются многих опций стека TCP/IP и виртуальной памяти; опытный системный администратор может использовать их для существенного увеличения производительности. Более пяти тысяч системных переменных могут быть прочитаны и записаны с помощью man:sysctl[8]. По своей сути, man:sysctl[8] выполняет две функции: чтение и изменение настроек системы. Для просмотра всех доступных для чтения переменных: [source,shell] .... % sysctl -a .... Чтобы прочитать определённую переменную, например, `kern.maxproc`, введите: [source,shell] .... % sysctl kern.maxproc kern.maxproc: 1044 .... Для присвоения значения переменной, используйте выражение вида _переменная_=_значение_: [source,shell] .... # sysctl kern.maxfiles=5000 kern.maxfiles: 2088 -> 5000 .... Изменяемые с помощью sysctl переменные обычно принимают значения либо строкового, либо целого, либо булевого типа. Переменные булевого типа могут принимать два значения (`1` (истина) и `0` (ложь)). Если вы хотите устанавливать некоторые переменные автоматически при каждой загрузке компьютера, добавьте их в файл [.filename]#/etc/sysctl.conf#. За дополнительной информацией обращайтесь к странице справочника man:sysctl.conf[5] и к <>. [[sysctl-readonly]] === Переменные man:sysctl[8] только для чтения В некоторых случаях желательно изменить переменные man:sysctl[8] только для чтения. Иногда другого способа решить проблему нет; при этом, результат может быть достигнут только на этапе начальной загрузки. Например, на некоторых моделях лэптопов диапазон памяти устройства man:cardbus[4] не определяется и выдается приблизительно такая ошибка: [source,shell] .... cbb0: Could not map register memory device_probe_and_attach: cbb0 attach returned 12 .... Ситуации, похожие на эту, требуют изменения некоторых значений man:sysctl[8], модификация которых запрещена. Для разрешения этой ситуации пользователь может поместить man:sysctl[8] "OID" в файл [.filename]#/boot/loader.conf#. Значения по умолчанию хранятся в файле [.filename]#/boot/defaults/loader.conf#. Решение проблемы, приведенной выше, потребует помещения строки `hw.pci.allow_unsupported_io_range=1` в вышеупомянутый файл. Теперь man:cardbus[4] будет работать нормально. [[configtuning-disk]] == Оптимизация дисков === Переменные Sysctl ==== `vfs.vmiodirenable` Значением переменной `vfs.vmiodirenable` может быть установлено в 0 (выключено) или 1 (включено); по умолчанию 1. Эта переменная отвечает за метод кэширования каталогов. Размер большинства каталогов невелик. Они могут поместиться в одном фрагменте (обычно 1K), и могут занимать ещё меньше места (обычно 512 байт) в кэше буфера. При отключении этой переменной (при установке значения 0) буфер прокэширует только заданное число каталогов даже если у вас много памяти. При включении (при установке значения 1) эта переменная sysctl позволит использовать страничное кэширование VM, делая доступным для кэширования каталогов весь объём памяти. Однако, минимальный объём памяти, используемой для кэширования каталогов стал равен объёму страницы (обычно 4 K) вместо 512 байт. Мы рекомендуем оставлять эту опцию включенной, если ваш компьютер исполняет программы, манипулирующие значительным количеством файлов. Примером таких программ могут быть кэширующие прокси-серверы, большие почтовые серверы и серверы новостей. Обычно включение этой опции не понижает производительности, однако лучше поэкспериментировать, чтобы узнать оптимальное значение для вашей машины. ==== `vfs.write_behind` Переменная sysctl `vfs.write_behind` по умолчанию установлена в `1` (включено). Она указывает системе выполнять запись на носитель по кластерам, что обычно делается для больших файлов. Идея в том, чтобы избежать заполнения кэша неполными буферами, когда это не увеличивает производительность. Однако, это может заблокировать процессы и в некоторых случаях вам может понадобиться отключить этот параметр. ==== `vfs.hirunningspace` Переменная sysctl `vfs.hirunningspace` определяет число запросов записи на диск, которые могут быть поставлены в очередь. Значение по умолчанию обычно подходит, но на компьютерах с большим количеством дисков вы можете увеличить его до четырех или пяти _мегабайт_. Учтите, что установка слишком большого значения (превышающего размер буфера записи) может привести к очень значительному падению общей производительности. Не делайте это значение произвольно большим! Большие значения могут привести к задержкам чтения, выполняемого в то же время Есть много других переменных sysctl, относящихся к кэшированию в буфер и страничному кэшированию VM. Мы не рекомендуем изменять эти значения, поскольку система VM делает отличную работу по автоматической самонастройке. ==== `vm.swap_idle_enabled` Переменная sysctl `vm.swap_idle_enabled` полезна в больших многопользовательских системах, где есть много пользователей, входящих и выходящих из системы, и множество ожидающих процессов. Такие системы обычно генерируют большое количество запросов на выделение памяти. Включение этой переменной и настройка задержки выгрузки (swapout hysteresis, в секундах) установкой переменных `vm.swap_idle_threshold1` и `vm.swap_idle_threshold2` позволит освобождать страницы памяти, занятые ожидающими процессами, более быстро, чем при нормальном алгоритме выгрузки. Это помогает даемону выгрузки страниц. Не включайте этот параметр, пока он на самом деле вам не понадобится, поскольку его действие в сущности заключается в более ранней выгрузке страниц из памяти; это повышает нагрузку на подкачку и диск. В малых системах эффект от включения этого параметра предсказуем, но в больших системах нагруженной на подкачкой этот параметр позволяет системе VM проще загружать и выгружать процессы из памяти. ==== `hw.ata.wc` Во FreeBSD 4.3 кэширование записи на IDE диски было отключено. Это понижало производительность IDE дисков в тестах, но было необходимо для лучшей сохранности данных. Проблема состоит в том, что IDE диски неправильно указывают время завершения записи на диск. При включенном кэшировании IDE диски могут не только записать данные в неправильном порядке - при большой нагрузке на диск некоторые блоки могут задержаться до бесконечности. Сбой, или отключение питания могут могут стать причиной серьёзных повреждений в файловой системе. Поэтому для безопасности системы значение по умолчанию этого параметра было изменено. К сожалению, результатом этого стало столь значительная потеря производительности, что после выхода релиза значение этого параметра было возвращено в первоначальное состояние. Вам следует проверить значение переменной sysctl `hw.ata.wc` на вашей машине. Если кэширование выключено - вы можете включить его, установив значение переменной ядра, равное 1. Это должно быть сделано при помощи загрузчика при загрузке. Если вы сделаете это позже - изменения не будут иметь силы. За более подробной информацией обращайтесь к man:ata[4]. ==== `SCSI_DELAY` (`kern.cam.scsi_delay`) Параметр настройки ядра `SCSI_DELAY` может использоваться для уменьшения времени загрузки системы. Значение по умолчанию велико и может составлять более `15` секунд в процессе загрузки. Уменьшение его до `5` секунд обычно работает (особенно с современными дисками). В новых версиях FreeBSD (5.0 и выше) должен использоваться параметр `kern.cam.scsi_delay`, настраиваемый во время загрузки. Этот параметр и параметр настройки ядра принимают значения в _миллисекундах_, а _не_ в _секундах_. [[soft-updates]] === Soft Updates Программа man:tunefs[8] используется для настройки файловой системы. Эта программа может принимать большое количество параметров, но мы рассмотрим лишь один из них - включение и выключение Soft Updates, что может быть достигнуто следующим образом: [source,shell] .... # tunefs -n enable /filesystem # tunefs -n disable /filesystem .... Нельзя изменять файловую систему с помощью man:tunefs[8] когда она смонтирована. Самое подходящее время для включения "Soft Updates" - перед монтированием разделов, в однопользовательском режиме. Soft Updates существенно увеличивают скорость создания и удаления файлов путём использования кэширования. Мы рекомендуем использовать Soft Updates на всех ваших файловых системах. Однако у Soft Updates есть и обратные стороны: во-первых, Soft Updates гарантирует целостность файловой системы в случае сбоя, но может наблюдаться задержка в несколько секунд (или даже минуту!) перед записью на жесткий диск. Если система зависнет - вы можете потерять больше, чем, если бы вы не включили Soft Updates. Во-вторых, Soft Updates задерживает освобождение блоков файловой системы. Если ваша файловая система заполнена, выполнение значительного обновления, например, `make installworld`, может вызвать переполнение. ==== Дополнительная информация о Soft Updates Есть два традиционных способа записи метаданных файловых систем на диск (пример метаданных: индексные дескрипторы и каталоги). Исторически, поведение по умолчанию заключается в синхронном обновлении метаданных. Если каталог был изменен, система ждет, пока изменение не будет физически записано на диск. Содержимое файлов проходит через кэш и записывается на диск асинхронно. Преимущество этого способа в его надежности. При сбое во время обновления метаданные остаются в нормальном состоянии. Файл либо создается целиком, либо вообще не создается. Если блоки данных не были записаны в файл из буфера во время сбоя, man:fsck[8] сможет определить это и восстановить файловую систему, установив длину файла в 0. Кроме того, реализация этого способа проста и понятна. Недостаток в том, что обновление метаданных занимает много времени. Команда `rm -r`, например, последовательно удаляет все файлы в каталоге, и каждое изменение в каталоге (удаление файла) будет синхронно записано на диск. Сюда включаются обновления самого каталога, таблицы индексных дескрипторов, и возможно блоков, занятых файлом. Те же соглашения работают при распаковке больших иерархий (`tar -x`). Другой вариант это асинхронное обновление метаданных. Это поведение по умолчанию для Linux/ext2fs и *BSD ufs с параметром `mount -o async`. Все обновления метаданных просто пропускаются через кэш буфера, как и содержимое файлов. Преимущество этой реализации в том, что нет необходимости ждать каждый раз, пока метаданные будут записаны на диск, поэтому все операции с большим объемом обновления метаданных будут происходить гораздо быстрее, чем при синхронном обновлении. Кроме того, реализация все еще проста и понятна, поэтому риск появления ошибок в коде невелик. Недостаток в том, что нет никаких гарантий исправности файловой системы. Если во время обновления большого объема метаданных произойдет сбой (например, отключение питания, или нажатие кнопки reset), файловая система останется в непредсказуемом состоянии. Нет возможности определить состояние файловой системы после такого сбоя; блоки данных файла могут быть уже записаны на диск, а обновления таблицы индексных дескрипторов нет. Невозможно реализовать `fsck`, которая могла бы исправить получившийся хаос (поскольку необходимой информации нет на диске). Если файловая система была уничтожена во время восстановления, единственный способ восстановления - запустить man:newfs[8] и воспользоваться резервной копией. Обычное решение этой проблемы состояло в реализации _протоколировании проблемной области (dirty region logging)_, известном как _журналирование_, хотя этот термин использовался неправильно и порой также применялся к другим формам протоколирования транзакций. Обновление метаданных как и прежде происходит синхронно, но в отдельную область диска. Позже они перемещаются туда, где должны быть. Поскольку область протоколирования это небольшая, последовательная область диска, головкам жесткого диска не приходится перемещаться на большие расстояния даже во время значительных обновлений, поэтому такой способ быстрее, чем синхронные обновления. Кроме того, сложность реализации довольно ограничена, поэтому риск внесения ошибок невелик. Недостаток в том, что все обновления метаданных записываются дважды (один раз в область протоколирования и один раз окончательно), поэтому при обычной работе производительность может понизиться. С другой стороны, в случае сбоя все незаконченные действия с метаданными могут быть быстро отменены, или завершены после загрузки системы, поэтому система после сбоя загружается быстрее. Kirk McKusick, разработчик Berkeley FFS, решил эту проблему с помощью Soft Updates: все незавершенные обновления метаданных находятся в памяти и записываются на диск в упорядоченном виде ("упорядоченное обновления метаданных"). При значительных обновлениях метаданных более поздние обновления "присоединяются" к предыдущим, если они все еще находятся в памяти и еще не записаны на диск. Поэтому все операции, скажем, над каталогом, обычно выполняются в памяти перед записью обновления на диск (блоки данных сортируются в соответствии с их положением, так что они не будут записаны на диск до метаданных. При крахе операционной системы выполняется "откат": считается, что все операции, не записанные на диск, никогда не происходили. Файловая система находится в том состоянии, в котором она была за 30-60 секунд до сбоя. Используемый алгоритм гарантирует, что все используемые ресурсы маркированы соответствующим образом в своих областях: блоки и индексные дескрипторы. После сбоя могут остаться только ошибки выделения ресурсов, они помечаются как "используемые", хотя на самом деле "свободны". man:fsck[8] разбирается в ситуации и освобождает более не используемые ресурсы. После сбоя система может быть безопасно смонтирована с опцией `mount -f`. Для освобождения ресурсов, которые могут не использоваться, в дальнейшем потребуется запустить man:fsck[8]. Эта идея лежит в основе _background (фоновая) fsck_: во время запуска системы записывается только _снимок_ файловой системы. Все системы могут быть смонтированы в "грязном" состоянии, и система загружается в многопользовательский режим. Затем, фоновые `fsck` ставятся в очередь для всех систем, где это требуется, чтобы освободить неиспользуемые ресурсы. (Файловые системы, где не используются Soft Updates, все еще требуют запуска `fsck` в обычном режиме). Преимущество этого способа в том, что обновления метаданных происходят почти так же быстро, как при асинхронных обновлениях (т.е. быстрее, чем при _журналировании_, когда метаданные записываются дважды). Недостаток в сложности кода (подразумевающим больший риск появления ошибок в области, где вероятность потери данных пользователя особенно высока) и в более высоких требованиях к объему памяти. К тому же могут возникнуть некоторые странные на первый взгляд ситуации. После сбоя состояние файловой системы несколько более "старое". В ситуации, когда стандартный способ синхронизации оставит несколько файлов нулевой длины после выполнения `fsck`, в файловой системе с Soft Updates их не останется вовсе, поскольку ни метаданные, ни содержимое файлов не были записаны на диск. Дисковое пространство не будет освобождено пока обновления не будут записаны на диск, что может занять некоторое время после выполнения `rm`. Это может повлечь проблемы при установке большого количества файлов на файловую систему, где не хватает места для помещения всех файлов дважды. [[configtuning-kernel-limits]] == Изменение ограничений, накладываемых ядром [[file-process-limits]] === Ограничения на Файлы/Процессы [[kern-maxfiles]] ==== `kern.maxfiles` Значение `kern.maxfiles` может быть увеличено или уменьшено в зависимости от потребностей вашей системы. Эта переменная определяет максимальное число дескрипторов файлов. Когда таблица дескрипторов файлов полна, в очереди системных сообщений появится сообщение `file: table is full`. Это сообщение может быть прочитано с помощью команды `dmesg`. Каждый открытый файл, сокет или буфер использует дескриптор файла. Широкомасштабному серверу может понадобиться много тысяч дескрипторов файлов, в зависимости от количества программ, одновременно выполняемых на сервере. Стандартное значение `kern.maxfile` определяется переменной `maxusers` в вашем файле конфигурации ядра. Значение `kern.maxfiles` увеличивается пропорционально значению `maxusers`. При компилировании ядра, нужно установить эту переменную согласно потребностям вашей системы. Исходя из значения этой переменной, ядро устанавливает значения большинства предопределённых переменных. Даже если предполагается, что к компьютеру не будут одновременно подсоединяться 256 пользователей, требуемые ресурсы могут быть такими же, как у крупномасштабного сервера. Система автоматически настроит `maxusers`, если вы явно установите его в `0`. Если вы желаете выставить значение самостоятельно, то задайте `maxusers` по меньшей мере равным 4, особенно если вы используйте X Window System или компилируйте программное обеспечение. Причина в том, что самая значимая таблица, устанавливаемая `maxusers` - это максимальное количество процессов, которая устанавливается равным `20 + 16 * maxusers`, и поэтому, если вы установите `maxusers` в 1, то вы сможете иметь только 36 одновременных процессов, включая 18 или около того, что система запустит во время загрузки и 15 или около того, что вы создадите при запуске X Window System. Даже простая задача, как чтение страницы справочника породит 9 процессов для фильтрации, декомпрессии и её просмотра. Установка `maxusers` в 64 позволит иметь вам до 1044 одновременных процессов, чего должно быть достаточно примерно для всех использований. Если, тем не менее, вы увидите пугающую ошибку при попытке запуска другой программы, или вы используйте сервер с большим количеством одновременных пользователей (как `ftp.FreeBSD.org`), то вы всегда можете увеличить значение и пересобрать систему. [NOTE] ==== `maxusers` _не_ ограничивает количество пользователей, которые могут заходить на вашу машину. Оно просто устанавливает различные размеры таблиц в разумные значения, учитывая максимальное количество пользователей, вы вероятно будете иметь на вашей системе и как много процессов каждый из них сможет запускать. Ключевое слово, которое ограничивает количество одновременных удаленных входов и терминальных X окон - это crossref:kernelconfig[kernelconfig-ptys,`pseudo-device pty 16`]. С FreeBSD 5.X вам не надо беспокоиться об этом значении, так как man:pty[4] драйвер является "автоматически клонирующим"; вы просто используйте `device pty` в вашем конфигурационном файле. ==== ==== `kern.ipc.somaxconn` Переменная sysctl `kern.ipc.somaxconn` ограничивает размер очереди для приема новых TCP соединений. Значение по умолчанию `128` слишком мало для надежной обработки новых соединений для нагруженного web сервера. Для такого сервера рекомендуется увеличить это значение до `1024` или выше. Даемон сервиса может сам ограничивать очередь приема новых соединений (например, man:sendmail[8], или Apache), но обычно в файле настройки даемона есть директива для настройки длины очереди. Более длинная очередь также помогает избежать атак Denial of Service (). [[nmbclusters]] === Сетевые Ограничения Опция ядра `NMBCLUSTERS` обуславливает количество Mbuf, доступных на машине. На сервере с большим трафиком и маленьким Mbuf производительность будет пониженной. Каждый кластер представлен двумя килобайтами памяти, поэтому значение 1024 означает 2 мегабайта памяти ядра, зарезервированной для сетевых буферов. Для определения оптимального значения необходимо провести простые вычисления. Если у вас веб сервер, который может обслуживать 1000 одновременных соединений, и каждое соединение "съедает" 16 K буфера приема и 16 K буфера отправки, вам потребуется 32 MB памяти под буферы. Хорошее правило - умножение этого значения на 2, 2x32 MB / 2 KB = 64 MB / 2 kB = 32768. Мы рекомендуем значения между 4096 и 32768 для машин с большим объемом памяти. Не указывайте произвольно большое значение параметра, это может привести к падению системы при загрузке. Используйте man:netstat[1] с опцией `-m` для определения количества используемых сетевых кластеров. Для настройки в процессе загрузки используйте в loader переменную `kern.ipc.nmbclusters`. Только в старых версиях FreeBSD потребуется пересобрать ядро (man:config[8]) с измененным параметром `NMBCLUSTERS`. Для нагруженных серверов, интенсивно использующих системный вызов man:sendfile[2], может потребоваться увеличения буферов man:sendfile[2] с помощью параметра конфигурации ядра `NSFBUFS`, или изменения значения путем установки переменной в [.filename]#/boot/loader.conf# (обратитесь к man:loader[8] за подробностями). Общий признак того, что параметр требуется изменить - состояние процессов `sfbufa`. Переменная sysctl `kern.ipc.nsfbufs` установлена только для чтения. Этот параметр увеличивается вместе с `kern.maxusers`, хотя может потребоваться увеличить его отдельно. [IMPORTANT] ==== Даже если сокет помечен как неблокирующий, вызов man:sendfile[2] на неблокирующем сокете может вызвать блокирование man:sendfile[2], пока не станет доступным достаточное количество `struct sf_buf`. ==== ==== `net.inet.ip.portrange.*` Переменные sysctl `net.inet.ip.portrange.*` контролируют диапазоны номеров портов, автоматически привязываемых к TCP и UDP сокетам. Есть три диапазона: нижний диапазон, диапазон по умолчанию и верхний диапазон. Большинство сетевых программ используют диапазон по умолчанию, контролируемый `net.inet.ip.portrange.first` и `net.inet.ip.portrange.last`, установленными соответственно в 1024 и 5000. Диапазоны портов привязки используются для исходящих соединений и при некоторых условиях портов может не хватить. Это чаще всего происходит на сильно загруженном прокси сервере. Диапазон портов не становится проблемой при работе серверов, которые обрабатывают в основном входящие соединения, или с небольшим количеством исходящих соединений, например mail relay. Для ситуаций, когда возможен недостаток портов, рекомендуется немного увеличить `net.inet.ip.portrange.last`. Может подойти значение `10000`, `20000`, или `30000`. Учтите также возможное влияние брандмауэра при изменении диапазона портов. Некоторые могут блокировать большие диапазоны портов (обычно с небольшими номерами) и вынуждают использовать более высокие диапазоны для исходящих соединений. По этой причине не рекомендуется уменьшать значение `net.inet.ip.portrange.first`. ==== TCP Bandwidth Delay Product TCP Bandwidth Delay Product Limiting похоже на TCP/Vegas в NetBSD. Оно может быть включено установкой переменной sysctl `net.inet.tcp.inflight.enable` в `1`. Система попытается вычислить задержку пакетов для каждого соединения и ограничить объем данных в очереди сети до значения, требуемого для поддержания оптимальной пропускной способности. Эта возможность полезна при передаче данных через модемы, Gigabit Ethernet, или даже через высокоскоростные WAN соединения (или любые другие соединения с большой задержкой передачи), особенно если вы также используете изменение размера окна или настроили большое окно передачи. Если вы включили этот параметр, убедитесь также, что переменная `net.inet.tcp.inflight.debug` установлена в `0` (отладка выключена), а для использования в реальных задачах может понадобиться установка переменной `net.inet.tcp.inflight.min` к значению как минимум `6144`. Но учтите, что установка большого значения этой переменной может фактически отключить ограничение в зависимости от вида соединения. Ограничение уменьшает количество данных на определенном маршруте и управляет очередью пакетов, как и уменьшает общее количество данных в очереди локального интерфейса хоста. С меньшим количеством пакетов в очереди двусторонние интерактивные соединения, особенно на медленных линиях, могут проходить быстрее. Но имейте ввиду, что эта функция работает только при передаче данных (передача данных / сторона сервера). Она не работает при получении данных (загрузке). Изменение значения переменной `net.inet.tcp.inflight.stab` _не_ рекомендуется. Этот параметр по умолчанию равен 20, что означает добавление 2 пакетов к вычислению задержки передачи. Дополнительное окно требуется для стабилизации алгоритма и улучшения ответной реакции на изменение условий, но также приводит к большему времени ping на медленных соединениях (задержка все же гораздо меньше, чем без алгоритма inflight). Вы можете попробовать уменьшить этот параметр до 15, 10 или 5; а также уменьшить `net.inet.tcp.inflight.min` (например, до 3500) для получения желаемого эффекта. Уменьшение значений этих параметров может использоваться только как крайняя мера. === Виртуальная память ==== `kern.maxvnodes` Файлы и каталоги в ядре представлены при помощи vnode (виртуальных узлов). Увеличение их числа может помочь уменьшить нагрузку на дисковую подсистему. Как правило, специальной настройки это значение не требует, однако, в некоторых случаях дисковая активность является узким местом, и система исчерпывает таблицу vnode, значение этой переменной следует увеличить. При этом необходимо оценить объем неактивной и свободной памяти. Текущее количество использованных vnode можно посмотреть при помощи команды: [.programlisting] .... # sysctl vfs.numvnodes vfs.numvnodes: 91349 .... Максимальное количество vnode, доступных системе: [.programlisting] .... # sysctl kern.maxvnodes kern.maxvnodes: 100000 .... Если количество использованных vnode близко к максимуму, значение переменной `kern.maxvnodes` следует увеличить на 1000. Следите за динамикой изменения `vfs.numvnodes`. Если оно увеличивается, приближаясь к вновь установленному максимуму, процесс следует повторить. Изменение в распределении памяти должно быть видно в выводе утилиты man:top[1]: больше памяти перейдет в разряд активной. [[adding-swap-space]] == Увеличение объема подкачки Вне зависимости от того, что вы планировали, иногда система ведет себя неожиданно. Если вам потребовался дополнительный объем подкачки, его довольно просто добавить. Есть три способа увеличения объема подкачки: добавить новый жесткий диск, включить подкачку по NFS, или создать файл подкачки на существующем разделе. За информацией о криптовании раздела подкачки обращайтесь к crossref:disks[swap-encrypting,Шифрование области подкачки] данного Руководства. [[new-drive-swap]] === Подкачка на новом жестком диске Лучший способ добавить подкачку, конечно, использовать еще один жесткий диск. Вы можете сделать это в любой момент. Если такой способ подходит, прочтите еще раз информацию по пространству подкачки в <> Руководства, где рассказывается о наилучшем способе организации раздела подкачки. [[nfs-swap]] === Подкачка через NFS Подкачка через NFS рекомендуется только в том случае, если в системе отсутствует жесткий диск; подкачка через NFS ограничена скоростью сетевого подключения и к тому же дополнительно нагружает NFS сервер. [[create-swapfile]] === Файлы подкачки Вы можете создать файл определенного размера и использовать его как файл подкачки. В нашем примере будет использован файл [.filename]#/usr/swap0# размером 64MB. Конечно, вы можете использовать любое имя. .Создание файла подкачки в FreeBSD [example] ==== . Убедитесь, что в файле настройки ядра присутствует драйвер виртуального диска (man:md[4]). Он есть в ядре [.filename]#GENERIC#. + [.programlisting] .... device md # Memory "disks" .... . Создайте файл подкачки ([.filename]#/usr/swap0#): + [source,shell] .... # dd if=/dev/zero of=/usr/swap0 bs=1024k count=64 .... . Установите подходящие права на ([.filename]#/usr/swap0#): + [source,shell] .... # chmod 0600 /usr/swap0 .... . Включите файл подкачки в [.filename]#/etc/rc.conf#: + [.programlisting] .... swapfile="/usr/swap0" # Set to name of swapfile if aux swapfile desired. .... . Перегрузите компьютер или для включения подкачки прямо сейчас введите: + [source,shell] .... # mdconfig -a -t vnode -f /usr/swap0 -u 0 swapon /dev/md0 .... ==== [[acpi-overview]] == Управление питанием и ресурсами Очень важно использовать аппаратные ресурсы эффективно. До того, как появился ACPI, управление потреблением питания и температурными характеристиками системы было очень сложной для операционной системы задачей. Аппаратное обеспечение контролировалось одним из видов встроенного интерфейса BIOS, таким как: _Plug and Play BIOS (PNPBIOS)_, _Advanced Power Management (APM)_ и так далее. Управление питанием и ресурсами это один из ключевых компонентов современной операционной системы. Например, вам может потребоваться, чтобы операционная система следила за температурными ограничениями и возможно, предупреждала при неожиданном росте температуры. В этом разделе Руководства FreeBSD, мы предоставим исчерпывающую информацию о ACPI. В конце раздела есть ссылки для дальнейшего чтения. [[acpi-intro]] === Что такое ACPI? Advanced Configuration and Power Interface (ACPI) это стандарт, написанный объединением поставщиков в целях предоставления стандартного интерфейса для аппаратных ресурсов и управления питанием (отсюда и название). Это ключевой элемент _Operating System-directed configuration and Power Management_, т.е.: он предоставляет операционной системе (OS) больше контроля и более универсален. Современные системы вышли за пределы ограничений существующих Plug and Play интерфейсов до появления ACPI. ACPI это прямой наследник APM (Advanced Power Management). [[acpi-old-spec]] === Недостатки Advanced Power Management (APM) Средства _Advanced Power Management (APM)_ управляют энергопотреблением системы в зависимости от нагрузки. APM BIOS предоставляется поставщиком системы и специфичен для данной аппаратной платформы. Драйвер APM в OS обеспечивает доступ к _APM Software Interface_, который позволяет управлять уровнями потребления питания. В APM имеется четыре основных проблемы. Во-первых, управление энергопотреблением осуществляется через зависимый от поставщика BIOS, и OS ничего не знает нем. Один пример: когда пользователь устанавливает время ожидания для жесткого диска в APM BIOS, и это время истекает, BIOS останавливает жесткий диск без согласования с OS. Во-вторых, алгоритм APM встроен в BIOS, и все действия происходят вне контроля OS. Это означает, что пользователи могут решить проблемы с APM BIOS только путем перепрошивки его ROM; это очень опасная процедура, и если она завершится неудачно, система может оказаться в невосстановимом состоянии. В-третьих, реализация технологии APM зависит от поставщика, что означает дублирование усилий и если в BIOS одного из поставщиков будет найдена и исправлена ошибка, ее могли не исправить другие поставщики. Наконец, объем APM BIOS недостаточно велик для реализации сложной политики управления питанием, или такой политики, которая может хорошо адаптироваться к потребностям компьютера. _Plug and Play BIOS (PNPBIOS)_ был неудобен во многих ситуациях. PNPBIOS это 16-битная технология, поэтому OS требовалось использовать 16-битную эмуляцию для "взаимодействия" с методами PNPBIOS. FreeBSD драйвер APM документирован в странице справочника man:apm[4]. [[acpi-config]] === Настройка ACPI man:loader[8] загружает драйвер [.filename]#acpi.ko# по умолчанию, его _не_ надо встраивать в ядро. Причина в том, что с модулями проще работать, например переключиться на другой [.filename]#acpi.ko# без пересборки ядра. Преимущество в упрощении тестирования. Другая причина в том, что запуск ACPI после старта системы не очень полезен и при некоторых условиях может приводить к краху. Если вы сомневаетесь, отключите ACPI совсем. Драйвер не должен и не может быть выгружен, поскольку системная шина используется для различных взаимодействий оборудования. ACPI может быть выключен с помощью утилиты man:acpiconf[8]. Фактически большинство взаимодействий с ACPI может быть выполнено через man:acpiconf[8]. В основном это означает, что если в выводе man:dmesg[8] есть что-то об ACPI, он скорее всего работает. [NOTE] ==== ACPI и APM не могут сосуществовать и должны использоваться раздельно. Каждый из них прервет загрузку, если обнаружит загруженный драйвер другого. ==== В простейшей форме, ACPI может использоваться для перевода системы в спящий режим с помощью man:acpiconf[8], с флагом `-s` и параметром `1-5`. Большинству пользователей нужен только параметр `1`. Параметр `5` сделает "мягкое" завершение работы, так же как и: [source,shell] .... # halt -p .... Доступны и другие параметры. Обратитесь к странице справочника man:acpiconf[8] за дополнительной информацией. [[ACPI-debug]] == Использование и отладка FreeBSD ACPI ACPI это фундаментально новый способ обнаружения устройств, управления энергопотреблением и предоставления стандартизированного доступа к различному оборудованию, ранее управлявшемуся BIOS. Был достигнут определенный прогресс в приспособлении ACPI к работе со всеми системами, но все еще встречаются ошибки в байткоде _ACPI Machine Language_ (AML) некоторых материнских плат, незавершенные участки кода в подсистемах ядра FreeBSD и ошибки в интерпретаторе Intel(R) ACPI-CA. Этот раздел предназначен для того, чтобы упростить ваше содействие разработчикам FreeBSD ACPI в определении причин наблюдаемых вами проблем, выполнении отладки и выработке решения. Спасибо за помощь и надеемся, что мы сможем помочь в решении проблем вашей системы. [[ACPI-submitdebug]] === Отправка отладочной информации [NOTE] ==== Перед отправкой сообщения об ошибке убедитесь, что у вас последняя версия BIOS, и, если доступна, последняя версия firmware встроенного контроллера. ==== Те из вас, кто желает составить сообщение о проблеме прямо сейчас, могут воспользоваться адресом link:mailto:freebsd-acpi@FreeBSD.org[ freebsd-acpi@FreeBSD.org], отправив на него следующую информацию: * Описание неправильного поведения, включая тип системы, модель и все, что приводит к появлению ошибки. Кроме того, сообщите настолько точно, насколько возможно, когда появилась ошибка, если ранее вы ее не видели. * Вывод man:dmesg[8] после "boot ``-v``", включая все сообщения, появившиеся при изучении ошибки. * Вывод man:dmesg[8] после "boot ``-v``" с выключенным ACPI, если его отключение помогает решить проблему. * Вывод `sysctl hw.acpi`. Это также хороший способ получения списка возможностей системы. * URL где можно найти ваш _ACPI Source Language_ (ASL). _Не_ отправляйте ASL непосредственно в список рассылки, поскольку он может быть очень большим. Копия ASL может быть создана командой: + [source,shell] .... # acpidump -t -d name-system.asl .... + (Замените вашим логином [.filename]#name# и производителем/моделью [.filename]#system#. Пример: [.filename]#njl-FooCo6000.asl#) Большинство разработчиков читают {freebsd-current}, но для уверенности, что проблему увидят, отправьте ее в {freebsd-acpi}. Будьте терпеливы, все мы заняты полный рабочий день где-то еще. Если ваше сообщение не заметили сразу, мы возможно попросим вас отправить PR (сообщение о проблеме) через man:send-pr[1]. При вводе PR, включайте ту же информацию, что запрошена выше. Это поможет нам отследить проблему и решить ее. Не отправляйте PR без предварительной отправки письма в {freebsd-acpi}, поскольку мы используем PR в качестве напоминаний о существующих проблемах, а не как механизм сообщений об ошибках. Вероятно, о вашей проблеме кто-то уже сообщал ранее. [[ACPI-background]] === Общие сведения ACPI представлен во всех современных компьютерах, соответствующих архитектурам ia32 (x86), ia64 (Itanium) и amd64 (AMD). Полный стандарт включает множество возможностей, в том числе управление производительностью CPU, уровнем питания, температурой, различными системами аккумуляторов, встроенными контроллерами и опросом шины. В большинстве систем стандарт реализован не полностью. Например, настольные системы обычно реализуют только опрос шины, а портативные компьютеры кроме того могут поддерживать управление охлаждением и энергопотреблением. Они также поддерживают приостановку и последующий запуск системы различного уровня сложности. ACPI-совместимые системы состоят из различных компонентов. Производители BIOS и чипсетов предоставляют различные жестко заданные таблицы, (например, FADT), которые определяют функции вроде карты APIC (используется для SMP), регистры настройки и простые значения параметров. Кроме того, предоставляется таблица байткода (_Differentiated System Description Table_, DSDT), определяющая древоподобное пространство имен устройств и методов. Драйвер ACPI должен прочесть заданные таблицы, реализовать интерпретатор для байткода, модифицировать драйвера устройств и ядро для приема информации от подсистемы ACPI. Для FreeBSD Intel(R) предоставила интерпретатор (ACPI-CA), тот же что для Linux и NetBSD. Исходный код ACPI-CA находится в каталоге [.filename]#src/sys/contrib/dev/acpica#. Код для приспособления ACPI-CA к работе в FreeBSD, находится в [.filename]#src/sys/dev/acpica/Osd#. Наконец, драйвера, реализующие различные ACPI устройства, находятся в [.filename]#src/sys/dev/acpica#. [[ACPI-comprob]] === Часто встречающиеся проблемы Для правильной работы ACPI все ее части должны работать правильно. Вот некоторые часто встречающиеся проблемы, в порядке частоты появления, и некоторые обходные пути или исправления. ==== Проблемы с мышью В некоторых случаях при возобновлении работы после приостановки перестает работать мышь. Известным решением проблемы является добавление строки `hint.psm.0.flags="0x3000"` в файл [.filename]#/boot/loader.conf#. Если это не помогло, стоит сообщить о проблеме, как описано выше. ==== Приостановка/возобновление работы ACPI поддерживает три состояния приостановки в RAM (STR), `S1`-`S3`, и одно состояние приостановки на диск (`STD`), называемое `S4`. `S5` это "мягкое выключение" и это нормальное состояние системы, когда она подключена к сети, но не включена. `S4` может быть реализован двумя различными путями. ``S4``BIOS это BIOS-поддерживаемая приостановка на диск. ``S4``OS реализуется полностью операционной системой. Начните с проверки переменных `sysctl hw.acpi`, относящихся к приостановке (suspend). Вот результат для Thinkpad: [source,shell] .... hw.acpi.supported_sleep_state: S3 S4 S5 hw.acpi.s4bios: 0 .... Это означает, что мы можем использовать `acpiconf -s` для тестирования `S3`, ``S4``OS, и `S5`. Если `s4bios` был единицей (`1`), это означает поддержку ``S4``BIOS вместо ``S4``OS. При тестировании приостановки/возобновления работы, начните с `S1`, если этот режим поддерживается. Это состояние скорее всего поддерживается, поскольку не требует слишком серьезной поддержки со стороны драйвера. Никто не реализовал `S2`, который похож на `S1`. Следующий режим для тестирования это `S3`. Это наиболее глубокое STR состояние, оно требует существенной поддержки со стороны драйвера, чтобы правильно реинициализировать оборудование. Если у вас возникли проблемы при выходе из этого состояния, отправьте письмо в рассылку {freebsd-acpi}, но не ждите, что проблема будет обязательно решена, поскольку существует множество драйверов/оборудования, нуждающихся в дальнейшем тестировании и разработке. Для изоляции проблемы удалите из ядра столько драйверов, сколько возможно. Если это работает, вы можете выяснить, какой драйвер вызывает проблему путем загрузки драйверов до тех пор, пока опять не произойдет сбой. Обычно бинарные драйвера, такие как [.filename]#nvidia.ko#, драйвера дисплея X11 и USB вызывают большинство проблем, а драйвера Ethernet интерфейсов как правило работают отлично. Если вы можете нормально загрузить/выгрузить драйвера, автоматизируйте этот процесс, поместив соответствующие команды в [.filename]#/etc/rc.suspend# и [.filename]#/etc/rc.resume#. Это закомментированные примеры выгрузки и загрузки драйверов. Попробуйте установить параметр `hw.acpi.reset_video` в нуль (`0`), если ваш дисплей не включается после возобновления работы. Попробуйте установить большие или меньшие значения для `hw.acpi.sleep_delay`, чтобы проверить, поможет ли это. Другой способ, который можно попробовать, это запуск последнего дистрибутива Linux с поддержкой ACPI и тестирование поддержки остановки/возобновления работы на том же оборудовании. Если она работает на Linux, проблема скорее всего в драйверах FreeBSD и поиск драйвера, вызывающего проблему, поможет разрешить ситуацию. Имейте ввиду, что разработчики ACPI обычно не поддерживают другие драйверы (звук, ATA, и т.п.), так что все результаты работы по поиску проблемы возможно необходимо отправить в список рассылки {freebsd-current} и человеку, поддерживающему драйвер. Если вы решитесь заняться отладкой, поместите соответствующий код (man:printf[3]) в вызывающий проблему драйвер для обнаружения места, где прерывается функция восстановления. Наконец, попробуйте отключить ACPI и включить APM. Если приостановка/возобновление работает с APM, вам возможно лучше подойдет APM, особенно на старом оборудовании (до 2000). Включение корректной поддержки ACPI поставщиками оборудования требует времени и вероятно в старом оборудовании поддержка ACPI в BIOS была некорректна. ==== Система останавливается (временно или постоянно) Большинство систем останавливаются в результате потери прерываний или "шторма" прерываний. В чипсетах существует много проблем, связанных с тем, как BIOS настраивает прерывания перед загрузкой, правильностью таблицы APIC (MADT), и маршрутизации _System Control Interrupt_ (SCI). "Шторм" прерываний может быть обнаружен по потерянным прерываниям путем проверки вывода строки с `acpi0` команды `vmstat -i`. Если счетчик увеличивается более, чем несколько раз в секунду, это "шторм" прерываний. Если система останавливается, попробуйте войти в DDB (kbd:[CTRL+ALT+ESC] на консоли) и ввести `show interrupts`. Наиболее надежный способ избавиться от проблемы с прерываниями, это отключение поддержки APIC с помощью параметра [.filename]#loader.conf#`hint.apic.0.disabled="1"`. ==== Паника Паника, связанная с ACPI, случается довольно редко и имеет наибольший приоритет исправления. Первый шаг это изоляция действий, приводящих к панике (если это возможно) и получение отладки. Следуйте инструкции по включению `options DDB` и настройке последовательной консоли (смотрите crossref:serialcomms[serialconsole-ddb,Вход в отладчик DDB с последовательной линии]) или настройке раздела man:dump[8]. Вы можете получить отладочную информацию DDB с помощью `tr`. Если вы записываете отладку вручную, убедитесь, что переписали как минимум пять (5) строк снизу и пять (5) строк сверху. Затем попробуйте изолировать проблему, загрузившись с выключенным ACPI. Если это работает, вы можете изолировать подсистему ACPI, используя различные параметры `debug.acpi.disable`. Обратитесь к странице справочника man:acpi[4] за примерами. ==== Система включается после приостановки или завершения работы Во-первых, попробуйте установить в man:loader.conf[5] параметр `hw.acpi.disable_on_poweroff="0"`. Это предотвращает отключение различных событий в ACPI во время завершения работы. В некоторых системах этот параметр необходимо установить в `1` (по умолчанию) по тем же причинам. Обычно это решает проблему, если система неожиданно включается после приостановки или отключения питания. ==== Другие проблемы Если вы наблюдаете другие проблемы с ACPI (работа с внешним оборудованием, проблемы с обнаружением устройств, и т.д.), отправьте описание проблемы в список рассылки; однако, некоторые из этих проблем могут относиться к незавершенным частям подсистемы ACPI, поэтому может потребоваться время на их реализацию. Будьте терпеливы, и подготовьтесь к тестированию исправлений, которые мы можем вам выслать. [[ACPI-aslanddump]] === ASL, `acpidump`, и IASL Наиболее часто встречается проблема, связанная с предоставлением поставщиками BIOS некорректного (или полностью ошибочного!) байткода. Это обычно проявляется появлением консольных сообщений ядра, подобных этому: [source,shell] .... ACPI-1287: *** Error: Method execution failed [\\_SB_.PCI0.LPC0.FIGD._STA] \\ (Node 0xc3f6d160), AE_NOT_FOUND .... Зачастую вы можете разрешить эти проблемы путем обновления BIOS до последней ревизии. Большинство консольных сообщений безвредны, но если существуют другие проблемы, такие как не работающий статус батареи, возможно существуют проблемы в AML. Байткод, известный как AML, компилируется из исходного текста на языке ASL. AML находится в таблице, известной как DSDT. Для получения копии ASL, используйте man:acpidump[8]. Вы можете использовать оба параметра `-t` (показывать содержимое постоянных таблиц) и `-d` (дизассемблировать AML в ASL). Обратитесь к разделу <> за примером синтаксиса. Простейшая первая проверка, которую вы можете провести, это перекомпиляция ASL для поиска ошибок. Предупреждения обычно могут быть проигнорированы, но ошибки обычно не позволяют ACPI работать правильно. Для перекомпиляции ASL, выполните следующую команду: [source,shell] .... # iasl your.asl .... [[ACPI-fixasl]] === Исправление ASL В дальней перспективе, наша задача состоит в том, чтобы обеспечить поддержку ACPI практически для каждой системы без вмешательства пользователя. Однако, на данный момент мы все еще разрабатываем обходные пути для ошибок, которые часто делают поставщики BIOS. Интерпретатор Microsoft(R) ([.filename]#acpi.sys# и [.filename]#acpiec.sys#) не занимается проверкой четкости соблюдения стандартов, поэтому многие поставщики BIOS, проверяющие ACPI только под Windows(R), никогда не исправляют ASL. Мы надеемся продолжать обнаружение и документацию нестандартных поведений, позволяемых интерпретатором Microsoft(R), и воспроизводить их, чтобы FreeBSD могла работать без необходимости исправления ASL пользователями. В качестве обходного пути для обнаружения неправильного поведения, вы можете исправить ASL вручную. Если исправления будут работать, пожалуйста отправьте man:diff[1] между старым и новым ASL, чтобы мы могли реализовать обходной путь для неправильного поведения ACPI-CA, чтобы исправление вручную больше не требовалось. Вот список наиболее часто встречающихся проблем, их причин и способы исправления: ==== OS зависимости Некоторые AML предполагают, что мир состоит из различных версий Windows(R). Вы можете настроить FreeBSD, чтобы она сообщала любое другое имя OS и посмотреть, исправит ли это имеющуюся проблему. Простой способ указания другого имени системы это установка переменной [.filename]#/boot/loader.conf#`hw.acpi.osname="Windows 2001"` или в другое подобное значение, имеющееся в ASL. ==== Отсутствие возврата значения Некоторые методы не возвращают значение явно, как того требует стандарт. Хотя ACPI-CA не обрабатывает эту ситуацию, в FreeBSD существует обходной путь, позволяющей ей явно возвращать значение. Вы можете также добавить явные операторы Return (возврат) там, где требуется, если знаете, что значение должно быть возвращено. Для принудительного компилирования ASL командой `iasl`, используйте флаг `-f`. ==== Перезапись AML по умолчанию После настройки [.filename]#your.asl# для компиляции запустите: [source,shell] .... # iasl your.asl .... Вы можете добавить флаг `-f` для создания AML даже при наличии ошибок компиляции. Помните, что некоторые ошибки (например, отсутствующие операторы Return), автоматически обходятся интерпретатором. Файл [.filename]#DSDT.aml# используется `iasl` по умолчанию. Вы можете загрузить его вместо ошибочной копии BIOS (которая остается в постоянной памяти) путем редактирования [.filename]#/boot/loader.conf#: [.programlisting] .... acpi_dsdt_load="YES" acpi_dsdt_name="/boot/DSDT.aml" .... Убедитесь, что скопировали [.filename]#DSDT.aml# в каталог [.filename]#/boot#. [[ACPI-debugoutput]] === Получение отладочной информации ACPI Возможности отладки драйвера ACPI очень гибкие. Они позволяют вам указывать набор подсистем, а также уровень отладки. Подсистемы, которые вы хотите отлаживать, указываются как "слои", и подразделяются на компоненты ACPI-CA (ACPI_ALL_COMPONENTS) и поддержку оборудования ACPI (ACPI_ALL_DRIVERS). Уровень отладки варьируется от ACPI_LV_ERROR (только сообщать об ошибках) до ACPI_LV_VERBOSE (все сообщения). Уровень отладки представляет собой битовую маску, поэтому возможна одновременная установка нескольких параметров, разделенных пробелами. На практике, при использовании для получения отладочной информации последовательной консоли, слишком большое количество информации может переполнить буфер консоли. Полный список отдельных слоев и уровней можно найти на странице справочника man:acpi[4]. Вывод отладочной информации по умолчанию не включен. Для его включения добавьте параметр `options ACPI_DEBUG` к файлу настройки ядра, если ACPI встроен в ядро. Вы можете добавить параметр `ACPI_DEBUG=1` в файл [.filename]#/etc/make.conf# для глобального включения этого параметра. Если вы используете модуль [.filename]#acpi.ko# , его можно пересобрать индивидуально: [source,shell] .... # cd /sys/modules/acpi/acpi make clean make ACPI_DEBUG=1 .... Установите [.filename]#acpi.ko# в [.filename]#/boot/kernel# и добавьте предпочитаемый уровень и слой к [.filename]#loader.conf#. Этот пример включает отладочные сообщения для всех компонентов ACPI-CA и всех драйверов оборудования ACPI (CPU, LID и т.д.). Будут выводиться только сообщения об ошибках, наименьший уровень отладки. [.programlisting] .... debug.acpi.layer="ACPI_ALL_COMPONENTS ACPI_ALL_DRIVERS" debug.acpi.level="ACPI_LV_ERROR" .... Если требуемая информация получается в результате определенного события (скажем, приостановка и восстановление), вы можете не изменять [.filename]#loader.conf# и использовать для указания слоя и уровня `sysctl` после загрузки и подготовки системы к определенному событию. Имена переменных `sysctl` те же, что и имена параметров настройки в [.filename]#loader.conf#. [[ACPI-References]] === Ссылки Дальнейшую информацию о ACPI можно найти по следующим ссылкам: * {freebsd-acpi} * Архивы списка рассылки ACPI http://lists.freebsd.org/pipermail/freebsd-acpi/[http://lists.freebsd.org/pipermail/freebsd-acpi/] * Старые архивы списка рассылки ACPI http://home.jp.FreeBSD.org/mail-list/acpi-jp/[http://home.jp.FreeBSD.org/mail-list/acpi-jp/] -* Спецификация ACPI 2.0 http://acpi.info/spec.htm[http://acpi.info/spec.htm] +* https://uefi.org/specifications#ACPI[Спецификация ACPI] * Страницы справочника FreeBSD: man:acpi[4], man:acpi_thermal[4], man:acpidump[8], man:iasl[8], man:acpidb[8] * http://www.cpqlinux.com/acpi-howto.html#fix_broken_dsdt[ Ресурс по отладке DSDT]. (Использует в качестве примера Compaq, но обычно полезен.) diff --git a/documentation/content/zh-cn/books/handbook/config/_index.adoc b/documentation/content/zh-cn/books/handbook/config/_index.adoc index dbfa9ed88d..d9e7751b1b 100644 --- a/documentation/content/zh-cn/books/handbook/config/_index.adoc +++ b/documentation/content/zh-cn/books/handbook/config/_index.adoc @@ -1,1390 +1,1390 @@ --- title: 第 12 章 设置和调整 part: 部分 III. 系统管理 prev: books/handbook/partiii next: books/handbook/boot showBookMenu: true weight: 16 path: "/books/handbook/" --- [[config-tuning]] = 设置和调整 :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 12 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/config/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[config-synopsis]] == 概述 使用 FreeBSD 的一个重要问题是系统配置。 正确地配置系统能充分地减少以后维护和升级系统所需的工作量。 这章将解释一些 FreeBSD 的配置过程,包括一些可以调整的 FreeBSD 系统的一些参数。 读完本章, 您将了解: * 如何有效地利用文件系统和交换分区。 * [.filename]#rc.conf# 的基本设置以及 [.filename]#/usr/local/etc/rc.d# 启动体系。 * 如何设置和测试网卡。 * 如何在您的网络设备上配置虚拟主机。 * 如何使用 [.filename]#/etc# 下的各配置文件。 * 如何通过 `sysctl` 变量来对 FreeBSD 系统进行调优。 * 怎样调整磁盘性能和修改内核限制。 在阅读本章之前,您应该了解: * 了解 UNIX(R) 和 FreeBSD 的基础知识 (crossref:basics[basics,UNIX 基础])。 * 熟悉内核配置编译的基础知识 (crossref:kernelconfig[kernelconfig,配置FreeBSD的内核])。 [[configtuning-initial]] == 初步配置 === 分区规划 ==== 基本分区 当使用 man:bsdlabel[8] 或者 man:sysinstall[8] 来分割您的文件系统的时候, 要记住硬盘驱动器外磁道传输数据要比从内磁道传输数据快。 因此应该将小的和经常访问的文件系统放在驱动器靠外的位置, 一些大的分区比如 [.filename]#/usr# 应该放在磁盘比较靠里的位置。 以类似这样的顺序建立分区是一个不错的主意:root,swap, [.filename]#/var#, [.filename]#/usr#。 [.filename]#/var# 分区的大小能反映您的机器使用情况。 [.filename]#/var# 文件系统用来存储邮件, 日志文件和打印队列缓存, 特别是邮箱和日志文件可能会达到无法预料的大小, 这主要取决于在您的系统上有多少用户和您的日志文件可以保存多长时间。 大多数用户很少需要 [.filename]#/var# 有 1GB 以上的闲置空间。 [NOTE] ==== 有时候 [.filename]#/var/tmp# 需要很多的磁盘空间。 在使用 man:pkg_add[1] 安装新的软件时,包管理工具会在 [.filename]#/var/tmp# 中解压出一份临时拷贝。 大的软件包,像 Firefox, OpenOffice 或者 LibreOffice 在安装时如果 [.filename]#/var/tmp# 中没有足够的空间就可能需要一些技巧了。 ==== [.filename]#/usr# 分区存储很多用来系统运行所需要的文件例如 man:ports[7] (建议这样做) 和源代码 (可选的)。 ports 和基本系统的源代码在安装时都是可选的, 但我们建议给这个分区至少保留 2GB 的可用空间。 当选择分区大小的时候,记住保留一些空间。 用完了一个分区的空间而在另一个分区上还有很多, 可能会导致出现一些错误。 [NOTE] ==== 一些用户会发现 man:sysinstall[8] 的 `Auto-defaults` 自动分区有时会分配给 [.filename]#/var# 和 [.filename]#/# 较小的分区空间。 分区应该精确一些并且大一些。 ==== [[swap-design]] ==== 交换分区 一般来讲,交换分区应该大约是系统内存 (RAM) 的两倍。 例如,如果机器有 128M 内存,交换文件应该是 256M。 较小内存的系统可以通过多一点地交换分区来提升性能。 不建议小于 256 兆的交换分区,并且扩充您的内存应该被考虑一下。 当交换分区最少是主内存的两倍的时候,内核的 VM (虚拟内存) 页面调度算法可以将性能调整到最好。如果您给机器添加更多内存, 配置太小的交换分区会导致 VM 页面扫描的代码效率低下。 在使用多块SCSI磁盘(或者不同控制器上的IDE磁盘)的大系统上, 建议在每个驱动器上建立交换分区(直到四个驱动器)。 交换分区应该大约一样大小。内核可以使用任意大小, 但内部数据结构则是最大交换分区的 4 倍。保持交换分区同样的大小, 可以允许内核最佳地调度交换空间来访问磁盘。 即使不太使用,分配大的交换分区也是好的, 在被迫重启之前它可以让您更容易的从一个失败的程序中恢复过来。 ==== 为什么要分区? 一些用户认为一个单独的大分区将会很好, 但是有很多原因会证明为什么这是个坏主意。首先, 每个分区有不同的分区特性,因此分开可以让文件系统调整它们。 例如,根系统和 [.filename]#/usr# 一般只是读取,写入很少。 很多读写频繁的被放在 [.filename]#/var# 和 [.filename]##/var/tmp##中。 适当的划分一个系统, 在其中使用较小的分区, 这样, 那些以写为主的分区将不会比以读为主的分区付出更高的代价。 将以写为主的分区放在靠近磁盘的边缘, 例如放在实际的大硬盘的前面代替放在分区表的后面,将会提高您需要的分区的 I/O 性能。现在可能也需要在比较大的分区上有很好的 I/O 性能, 把他们移动到磁盘外围不会带来多大的性能提升,反而把 [.filename]#/var# 移到外面会有很好的效果。最后涉及到安全问题。 一个主要是只读的小的、整洁的根分区可以提高从一个严重的系统崩溃中恢复过来的机会。 [[configtuning-core-configuration]] == 核心配置 系统的配置信息主要位于 [.filename]#/etc/rc.conf#。 这个文件包含了配置信息很大的一部分,主要在系统启动的时候来配置系统, 这个名字直接说明了这点;它也是 [.filename]#rc*# 文件的配置信息。 系统管理员应该在 [.filename]#rc.conf# 文件中建立记录来覆盖 [.filename]#/etc/defaults/rc.conf# 中的默认设置。 这个默认文件不应该被逐字的复制到 [.filename]#/etc# ―― 它包含的是默认值而不是一个例子。 所有特定的改变应该在 [.filename]#rc.conf# 中。 在集群应用中,为了降低管理成本, 可以采用多种策略把涉及全站范围的设置从特定于系统的设置中分离出来。 推荐的方法是把系统范围的配置放到 [.filename]#/etc/rc.conf.local# 文件中。 例如: * [.filename]#/etc/rc.conf#: + [.programlisting] .... sshd_enable="YES" keyrate="fast" defaultrouter="10.1.1.254" .... * [.filename]#/etc/rc.conf.local#: + [.programlisting] .... hostname="node1.example.org" ifconfig_fxp0="inet 10.1.1.1/8" .... [.filename]#rc.conf# 文件可以通过 `rsync` 或类似的程序来分发到所有的机器上, 而各自的 [.filename]#rc.conf.local# 文件则保持不变。 使用 man:sysinstall[8] 或者 `make world` 来升级系统不会覆盖 [.filename]#rc.conf# 文件, 所以系统配置信息不会丢失。 [TIP] ==== 配置文件 [.filename]#/etc/rc.conf# 是通过 man:sh[1] 解析的。 这使得系统管理员可以在其中添加一些逻辑, 从而创建能够适应非常复杂的场景的配置。 请参阅联机手册 man:rc.conf[5] 来了解关于这一话题的进一步信息。 ==== [[configtuning-appconfig]] == 应用程序配置 典型的,被安装的应用程序有他自己的配置文件、语法等等。 从基本系统中分开他们是很重要的以至于他们可以容易的被 package 管理工具定位和管理 一般来说,这些文件被安装在 [.filename]#/usr/local/etc#。这个例子中, 一个应用程序有很多配置文件并且创建了一个子目录来存放他们。 通常,当一个 port 或者 package 被安装的时候, 配置文件示例也同样被安装了。它们通常用 [.filename]#.default# 的后缀来标识。如果不存在这个应用程序的配置文件, 它们会通过复制 [.filename]#.default# 文件来创建。 例如,看一下这个目下的内容 [.filename]#/usr/local/etc/apache#: .... -rw-r--r-- 1 root wheel 2184 May 20 1998 access.conf -rw-r--r-- 1 root wheel 2184 May 20 1998 access.conf.default -rw-r--r-- 1 root wheel 9555 May 20 1998 httpd.conf -rw-r--r-- 1 root wheel 9555 May 20 1998 httpd.conf.default -rw-r--r-- 1 root wheel 12205 May 20 1998 magic -rw-r--r-- 1 root wheel 12205 May 20 1998 magic.default -rw-r--r-- 1 root wheel 2700 May 20 1998 mime.types -rw-r--r-- 1 root wheel 2700 May 20 1998 mime.types.default -rw-r--r-- 1 root wheel 7980 May 20 1998 srm.conf -rw-r--r-- 1 root wheel 7933 May 20 1998 srm.conf.default .... 文件大小显示了只有 [.filename]#srm.conf# 改变了。以后 Apache 的升级就不会改变这个文件。 [[configtuning-starting-services]] == 启动服务 许多用户会选择使用 Ports Collection 来在 FreeBSD 上安装第三方软件。 很多情况下这可能需要进行一些配置以便让这些软件能够在系统初始化的过程中启动。 服务, 例如 package:mail/postfix[] 或 package:www/apache13[] 就是这些需要在系统初始化时启动的软件包中的两个典型代表。 这一节解释了启动第三方软件所需要的步骤。 FreeBSD 包含的大多数服务,例如 man:cron[8], 就是通过系统启动脚本启动的。 这些脚本也许会有些不同, 这取决于 FreeBSD 版本。 但是不管怎样, 需要考虑的一个重要方面是他们的启动配置文件要能被基本启动脚本识别捕获。 === 扩展应用程序配置 现在 FreeBSD 提供了 [.filename]#rc.d#, 这使得对应用软件的启动进行配置变得更加方便, 并提供了更多的其他功能。 例如, 使用在 <> 一节中所介绍的关键字, 应用程序就可以设置在某些其他服务, 例如 DNS 之后启动; 除此之外, 还可以通过 [.filename]#rc.conf# 来指定一些额外的启动参数, 而不再需要将它们硬编码到启动脚本中。 基本的启动脚本如下所示: [.programlisting] .... #!/bin/sh # # PROVIDE: utility # REQUIRE: DAEMON # KEYWORD: shutdown . /etc/rc.subr name=utility rcvar=utility_enable command="/usr/local/sbin/utility" load_rc_config $name # # DO NOT CHANGE THESE DEFAULT VALUES HERE # SET THEM IN THE /etc/rc.conf FILE # utility_enable=${utility_enable-"NO"} pidfile=${utility_pidfile-"/var/run/utility.pid"} run_rc_command "$1" .... 这个脚本将保证 utility 能够在 `DAEMON` 服务之后启动。 它同时也提供了设置和跟踪 PID, 也就是进程 ID 文件的方法。 可以在 [.filename]#/etc/rc.conf# 中加入: [.programlisting] .... utility_enable="YES" .... 这个方法也使得命令行参数、包含 [.filename]#/etc/rc.subr# 中所提供的功能, 兼容 man:rcorder[8] 工具并提供更简单的通过 [.filename]#rc.conf# 文件来配置的方法。 === 用服务来启动服务 其他服务, 例如 POP3 服务器, IMAP, 等等, 也可以通过 man:inetd[8] 来启动。 这一过程包括从 Ports Collection 安装相应的应用程序, 并把配置加入到 [.filename]#/etc/inetd.conf# 文件, 或去掉当前配置中的某些注释。 如何使用和配置 inetd 在 crossref:network-servers[network-inetd,inetd] 一节中进行了更为深入的阐述。 一些情况下, 通过 man:cron[8] 来启动系统服务也是一种可行的选择。 这种方法有很多好处, 因为 `cron` 会以 [.filename]#crontab# 的文件属主身份执行那些进程。 这使得普通用户也能够执行他们的应用。 `cron` 工具提供了一个独有的功能, 以 `@reboot` 来指定时间。 这样的设置将在 man:cron[8] 启动时运行, 通常这也是系统初始化的时候。 [[configtuning-cron]] == 配置 `cron` FreeBSD 最有用的软件包(utilities)中的一个是 man:cron[8]。 `cron` 软件在后台运行并且经常检查 [.filename]#/etc/crontab# 文件。`cron` 软件也检查 [.filename]#/var/cron/tabs# 目录,搜索新的 [.filename]#crontab# 文件。这些 [.filename]#crontab# 文件存储一些 `cron` 在特定时间执行任务的信息。 `cron` 程序使用两种不同类型的配置文件, 即系统 crontab 和用户 crontabs。 两种格式的唯一区别是第六个字段。 在系统 crontab 中,第六个字段是用于执行命令的用户名。 这给予了系统 crontab 以任意用户身份执行命令的能力。 在用户 crontab 中, 第六个字段是要执行的命令, 所有的命令都会以这个用户自己的身份执行; 这是一项重要的安全功能。 [NOTE] ==== 同其他用户一样, `root` 用户也可以有自己的 crontab。 它不同于 [.filename]#/etc/crontab# (也就是系统 crontab)。 由于有系统 crontab 的存在, 通常并不需要给 `root` 建立单独的用户 crontab。 ==== 让我们来看一下 [.filename]#/etc/crontab# 文件: [.programlisting] .... # /etc/crontab - root's crontab for FreeBSD # # $FreeBSD: src/etc/crontab,v 1.32 2002/11/22 16:13:39 tom Exp $ ## <.> # SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin <.> HOME=/var/log # # #minute hour mday month wday who command <.> # # */5 * * * * root /usr/libexec/atrun <.> .... <.> 像大多数 FreeBSD 配置文件一样,`#` 字符是注释。 这样, 就可以编写注释来说明要执行什么操作, 以及这样做的原因。 需要注意的是, 注释应该另起一行, 而不能跟命令放在同一行上, 否则它们会被看成命令的一部分。 这个文件中的空行会被忽略。 <.> 首先应该定义环境变量。等号 (`=`) 字符用来定义任何环境变量,像这个例子用到了 `SHELL`,`PATH` 和 `HOME` 变量。如果 shell 行被忽略掉,`cron` 将会用默认值 `sh`。如果 `PATH` 变量被忽略, 那么就没有默认值并且需要指定文件绝对位置。如果 `HOME` 被忽略,`cron` 将用用执行者的 home 目录。 <.> 这一行定义了七个字段。它们是 `minute`、 `hour`、`mday`、 `month`、`wday`、 `who` 和 `command`。 它们差不多已经说明了各自的用处。Minute 是命令要运行时的分钟,Hour 跟 minute 差不多,只是用小时来表示。Mday 是每个月的天。Month 跟 hour 还有 minute 都差不多,用月份来表示。wday 字段表示星期几。 所有这些字段的值必须是数字并且用24小时制来表示。"who" 字段是特别的,并且只在 [.filename]#/etc/crontab# 文件中存在。 这个字段指定了命令应该以哪个用户的身份来运行。当一个用户添加了他(她)的 [.filename]#crontab# 文件的时候,他们就会没有这个字段选项。最后,是 `command` 字段。这是最后的一个字段, 所以自然就是它指定要运行的程序。 <.> 最后一行定义了上面所说的值。注意这里我们有一个 `*/5` 列表,紧跟着是一些 `*` 字符。`*` 字符代表"开始到最后", 也可以被解释成 _每次_。所以,根据这行, 显然表明了无论在何时每隔 5 分钟以 `root` 身份来运行 `atrun` 命令。查看 man:atrun[8] 手册页以获得 `atrun` 的更多信息。命令可以有任意多个传递给它们的标志。无论怎样, 扩展到多行的命令应该用反斜线("\")来续行。 这是每个 [.filename]#crontab# 文件的基本设置, 虽然它们有一个不同。第六行我们指定的用户名只存在于系统 [.filename]#/etc/crontab# 文件。这个字段在普通用户的 [.filename]#crontab# 文件中应该被忽略。 [[configtuning-installcrontab]] === 安装 Crontab [IMPORTANT] ==== 绝对不要用这种方法来编辑/安装系统 crontab。 您需要做的只是使用自己喜欢的编辑器: `cron` 程序会注意到文件发生了变化, 并立即开始使用新的版本。参见 extref:{faq}[这个 FAQ 项目, ROOT-NOT-FOUND-CRON-ERRORS] 以了解进一步的情况。 ==== 要安装刚写好的用户 [.filename]#crontab#, 首先使用最习惯的编辑器来创建一个符合要求格式的文件,然后用 `crontab` 程序来完成。最常见的用法是: [source,shell] .... % crontab crontab-file .... 在前面的例子中, [.filename]#crontab-file# 是一个事先写好的 [.filename]#crontab#。 还有一个选项用来列出安装的 [.filename]#crontab# 文件: 只要传递 `-l` 选项给 `crontab` 然后看一下输出。 用户想不用模板(已经存在的文件)而直接安装他的 crontab 文件,用 `crontab -e` 选项也是可以的。 它将会启动一个编辑器并且创建一个新文件,当这个文件被保存的时候, 它会自动的用 `crontab` 来安装这个文件。 如果您稍后想要彻底删除自己的用户 [.filename]#crontab# 可以使用 `crontab` 的 `-r` 选项。 [[configtuning-rcd]] == 在 FreeBSD 中使用 rc 在 2002 年, FreeBSD 整合了来自 NetBSD 的 [.filename]#rc.d# 系统, 并通过它来完成系统的初始化工作。 用户要注意在 [.filename]#/etc/rc.d# 目录下的文件。 这里面的许多文件是用来管理基础服务的, 它们可以通过 `start`、 `stop`, 以及 `restart` 选项来控制。 举例来说, man:sshd[8] 可以通过下面的命令来重启: [source,shell] .... # /etc/rc.d/sshd restart .... 对其它服务的操作与此类似。 当然, 这些服务通常是在启动时根据 man:rc.conf[5] 自动启动的。 例如, 要配置使系统启动时启动网络地址转换服务, 可以简单地通过在 [.filename]#/etc/rc.conf# 中加入如下设置来完成: [.programlisting] .... natd_enable="YES" .... 如果 `natd_enable="NO"` 行已经存在, 只要简单的把 `NO` 改成 `YES` 即可。 rc 脚本在下次重新启动的时候会自动的装载所需要的服务, 像下面所描述的那样。 由于 [.filename]#rc.d# 系统在系统启动/关闭时首先启动/停止服务,如果设置了适当的 [.filename]#/etc/rc.conf# 变量,标准的 `start`、`stop` 和 `restart` 选项将会执行他们的动作。例如 `sshd restart` 命令只在 [.filename]#/etc/rc.conf# 中的 `sshd_enable` 设置成 `YES` 的时候工作。不管是否在 [.filename]#/etc/rc.conf# 中设置了,要 `start`、`stop` 或者 `restart` 一个服务,命令前可以加上一个"one"前缀。例如要不顾当前 [.filename]#/etc/rc.conf# 的设置重新启动 `sshd`,执行下面的命令: [source,shell] .... # /etc/rc.d/sshd onerestart .... 用选项 `rcvar` 可以简单来的检查 [.filename]#/etc/rc.conf# 中用适当的 [.filename]#rc.d# 脚本启动的服务是否被启用。从而管理员可以运行这样的程序来检查 `sshd` 是否真的在 [.filename]#/etc/rc.conf# 中被启动了: [source,shell] .... # /etc/rc.d/sshd rcvar # sshd $sshd_enable=YES .... [NOTE] ==== 第二行 (`# sshd`) 是从 `sshd` 命令中输出的,而不是 `root` 控制台。 ==== 为了确定一个服务是否真的在运行,可以用 `status` 选项。例如验证 `sshd` 是否真的启动了: [source,shell] .... # /etc/rc.d/sshd status sshd is running as pid 433. .... 有些时候也可以 `reload` 服务。 这一操作实际上是向服务发送一个信号, 来强制其重新加载配置。 多数情况下, 发给服务的会是 `SIGHUP` 信号。 并非所有服务都支持这一功能。 [.filename]#rc.d# 系统不仅用于网络服务, 它也为系统初始化中的多数过程提供支持。 比如 [.filename]#bgfsck# 文件, 当它被执行时, 将会给出下述信息: [source,shell] .... Starting background file system checks in 60 seconds. .... 这个文件用做后台文件系统检查,系统初始化的时候完成。 很多系统服务依赖其他服务提供的相应功能。例如,NIS 和其他基于 RPC 的服务启动可能在 `rpcbind` 服务启动之前失败。 要解决这个问题,依赖关系信息和其他头信息当作注释被包含在每个启动脚本文件的前面。 程序在系统初始化时分析这些注释以决定调用其他系统服务来满足依赖关系。 下面的字句必须被包含在所有的启动脚本文件里, (他们都是 man:rc.subr[8] 用来 "enable" 启动脚本必需的): * `PROVIDE`: 指定此文件所提供的服务的名字。 以下的字句可以被包含在启动文件的顶部。严格来说他们不是必需的, 但作为对于 man:rcorder[8] 有一定的提示作用: * `REQUIRE`: 列出此服务启动之前所需要的其他服务。 此脚本提供的服务会在指定的那些服务 _之后_ 启动。 * `BEFORE`: 列出依赖此服务的其他服务。 此脚本提供的服务将在指定的那些服务 _之前_ 启动。 通过在启动脚本中仔细设定这些关键字, 系统管理员可以很有条理的控制脚本的启动顺序, 进而避免使用像其他 UNIX(R) 操作系统那样混乱的 "runlevels"。 更多关于 [.filename]#rc.d# 系统的信息, 可以在 man:rc[8] 和 man:rc.subr[8] 联机手册中找到。 如果您有意撰写自己的 [.filename]#rc.d# 脚本, 或对现有的脚本进行一些改进, 也可以参考 extref:{rc-scripting}[这篇文章]。 [[config-network-setup]] == 设置网卡 现在我们不可想象一台计算机没有网络连接的情况。 添加和配置一块网卡是任何 FreeBSD 系统管理员的一项基本任务。 === 查找正确的驱动程序 在开始之前,您应该知道您的网卡类型,它用的芯片和它是 PCI 还是 ISA 网卡。FreeBSD 支持很多种 PCI 和 ISA 网卡。 可以查看您的版本硬件兼容性列表以确定您的网卡被支持。 确认系统能够支持您的网卡之后, 您还需要为它选择合适的驱动程序。 [.filename]#/usr/src/sys/conf/NOTES# 和 [.filename]#/usr/src/sys/arch/conf/NOTES# 将为您提供所支持的一些网卡和芯片组的信息。 如果您怀疑驱动程序是否使所要找的那一个, 请参考驱动程序的联机手册。 联机手册将提供关于所支持的硬件更详细的信息, 甚至还包括可能发生的问题。 如果您的网卡很常见的话, 大多数时候您不需要为驱动浪费精力。 常用的网卡在 [.filename]#GENERIC# 内核中已经支持了, 所以您的网卡在启动时就会显示出来,像是: [source,shell] .... dc0: <82c169 PNIC 10/100BaseTX> port 0xa000-0xa0ff mem 0xd3800000-0xd38 000ff irq 15 at device 11.0 on pci0 miibus0: on dc0 bmtphy0: PHY 1 on miibus0 bmtphy0: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc0: Ethernet address: 00:a0:cc:da:da:da dc0: [ITHREAD] dc1: <82c169 PNIC 10/100BaseTX> port 0x9800-0x98ff mem 0xd3000000-0xd30 000ff irq 11 at device 12.0 on pci0 miibus1: on dc1 bmtphy1: PHY 1 on miibus1 bmtphy1: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc1: Ethernet address: 00:a0:cc:da:da:db dc1: [ITHREAD] .... 在这个例子中,我们看到有两块使用 man:dc[4] 驱动的网卡在系统中。 如果您的网卡没有出现在 [.filename]#GENERIC# 中, 则需要手工加载合适的驱动程序。 要完成这项工作可以使用下面两种方法之一: * 最简单的办法是用 man:kldload[8] 加载网卡对应的内核模块。 除此之外, 通过在 [.filename]#/boot/loader.conf# 文件中加入适当的设置, 也可以让系统在引导时自动加载这些模块。 不过, 并不是所有的网卡都能够通过这种方法提供支持; ISA 网卡是比较典型的例子。 * 另外, 您也可以将网卡的支持静态联编进内核。 察看 [.filename]#/usr/src/sys/conf/NOTES#, [.filename]#/usr/src/sys/arch/conf/NOTES# 以及驱动程序的联机手册以了解需要在您的内核配置文件中加一些什么。 要了解关于重新编译内核的进一步细节, 请参见 crossref:kernelconfig[kernelconfig,配置FreeBSD的内核]。 如果您的卡在引导时可以被内核 ([.filename]#GENERIC#) 识别, 您应该不需要编译新的内核。 [[config-network-ndis]] ==== 使用 Windows(R) NDIS 驱动程序 不幸的是, 许多厂商由于认为驱动程序会涉及许多敏感的商业机密, 至今仍不愿意将把驱动程序作为开放源代码形式发布列入他们的时间表。 因此, FreeBSD 和其他操作系统的开发者就只剩下了两种选择: 要么经历长时间的痛苦过程来对驱动进行逆向工程, 要么使用现存的为 Microsoft(R) Windows(R) 平台提供的预编译版本的驱动程序。 包括参与 FreeBSD 开发的绝大多数开发人员, 都选择了后一种方法。 得益于 Bill Paul (wpaul) 的工作, 已经可以 "直接地" 支持 网络驱动接口标准 (NDIS, Network Driver Interface Specification) 了。 FreeBSD NDISulator (也被称为 Project Evil) 可以支持二进制形式的 Windows(R) 驱动程序, 并让它相信正在运行的是 Windows(R)。 由于 man:ndis[4] 驱动使用的是用于 Windows(R) 的二进制形式的驱动, 因此它只能在 i386(TM) 和 amd64 系统上使用。 [NOTE] ==== man:ndis[4] 驱动在设计时主要提供了 PCI、 CardBus 和 PCMCIA 设备的支持, 而 USB 设备目前则没有提供支持。 ==== 要使用 NDISulator, 您需要三件东西: . 内核的源代码 . 二进制形式的 Windows(R) XP 驱动程序 (扩展名为 [.filename]#.SYS#) . Windows(R) XP 驱动程序配置文件 (扩展名为 [.filename]#.INF#) 您需要找到用于您的卡的这些文件。 一般而言, 这些文件可以在随卡附送的 CD 或制造商的网站上找到。 在下面的例子中, 我们用 [.filename]#W32DRIVER.SYS# 和 [.filename]#W32DRIVER.INF# 来表示这些文件。 [NOTE] ==== 不能在 FreeBSD/amd64 上使用 Windows(R)/i386 驱动程序。 必须使用 Windows(R)/amd64 驱动才能在其上正常工作。 ==== 接下来的步骤是将二进制形式的驱动程序组装成内核模块。 要完成这一任务, 需要以 `root` 用户的身份执行 man:ndisgen[8]: [source,shell] .... # ndisgen /path/to/W32DRIVER.INF /path/to/W32DRIVER.SYS .... man:ndisgen[8] 是一个交互式的程序, 它会提示您输入所需的一些其他的额外信息; 这些工作完成之后, 它会在当前目录生成一个内核模块文件, 这个文件可以通过下述命令来加载: [source,shell] .... # kldload ./W32DRIVER_SYS.ko .... 除了刚刚生成的内核模块之外, 还必须加载 [.filename]#ndis.ko# 和 [.filename]#if_ndis.ko# 这两个内核模块, 在您加载需要 man:ndis[4] 的模块时, 通常系统会自动完成这一操作。 如果希望手工加载它们, 则可以使用下列命令: [source,shell] .... # kldload ndis # kldload if_ndis .... 第一个命令会加载 NDIS 袖珍端口驱动封装模块, 而第二条命令则加载实际的网络接口。 现在请查看 man:dmesg[8] 来了解是否发生了错误。 如果一切正常, 您会看到类似下面的输出: [source,shell] .... ndis0: mem 0xf4100000-0xf4101fff irq 3 at device 8.0 on pci1 ndis0: NDIS API version: 5.0 ndis0: Ethernet address: 0a:b1:2c:d3:4e:f5 ndis0: 11b rates: 1Mbps 2Mbps 5.5Mbps 11Mbps ndis0: 11g rates: 6Mbps 9Mbps 12Mbps 18Mbps 36Mbps 48Mbps 54Mbps .... 这之后, 就可以像使用其它网络接口 (例如 [.filename]#dc0#) 一样来使用 [.filename]#ndis0# 设备了。 与任何其它模块一样, 您也可以配置系统, 令其在启动时自动加载 NDIS 模块。 首先, 将生成的模块 [.filename]#W32DRIVER_SYS.ko# 复制到 [.filename]#/boot/modules# 目录中。 接下来, 在 [.filename]#/boot/loader.conf# 中加入: [.programlisting] .... W32DRIVER_SYS_load="YES" .... === 配置网卡 现在正确的网卡驱动程序已经装载,那么就应该配置它了。 跟其他配置一样,网卡可以在安装时用 sysinstall 来配置。 要显示您系统上的网络接口的配置,输入下列命令: [source,shell] .... % ifconfig dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da inet 192.168.1.3 netmask 0xffffff00 broadcast 192.168.1.255 media: Ethernet autoselect (100baseTX ) status: active dc1: flags=8802 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:db inet 10.0.0.1 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet 10baseT/UTP status: no carrier plip0: flags=8810 metric 0 mtu 1500 lo0: flags=8049 metric 0 mtu 16384 options=3 inet6 fe80::1%lo0 prefixlen 64 scopeid 0x4 inet6 ::1 prefixlen 128 inet 127.0.0.1 netmask 0xff000000 nd6 options=3 .... 在这个例子中,显示出了下列设备: * [.filename]#dc0#: 第一个以太网接口 * [.filename]#dc1#: 第二个以太网接口 * [.filename]#plip0#: 并口 (如果系统中有并口的话) * [.filename]#lo0#: 回环设备 FreeBSD 使用内核引导时检测到的网卡驱动顺序来命名网卡。例如 [.filename]#sis2# 是系统中使用 man:sis[4] 驱动的第三块网卡。 在这个例子中,[.filename]#dc0# 设备启用了。主要表现在: . `UP` 表示这块网卡已经配置完成准备工作。 . 这块网卡有一个 Internet (`inet`) 地址 (这个例子中是 `192.168.1.3`)。 . 它有一个有效的子网掩码 (`netmask`; `0xffffff00` 等同于 `255.255.255.0`)。 . 它有一个有效的广播地址 (这个例子中是 `192.168.1.255`)。 . 网卡的 MAC (`ether`) 地址是 `00:a0:cc:da:da:da` . 物理传输媒介模式处于自动选择状态 (`media: Ethernet autoselect (100baseTX )`)。我们看到 [.filename]#dc1# 被配置成运行在 `10baseT/UTP` 模式下。 要了解驱动媒介类型的更多信息, 请查阅它们的使用手册。 . 连接状态 (`status`)是 `active`,也就是说连接信号被检测到了。对于 [.filename]#dc1#,我们看到 `status: no carrier`。 这通常是网线没有插好。 如果 man:ifconfig[8] 的输出显示了类似于: [source,shell] .... dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da media: Ethernet autoselect (100baseTX ) status: active .... 的信息,那么就是还没有配置网卡。 要配置网卡,您需要 `root` 权限。 网卡配置可以通过使用 man:ifconfig[8] 命令行方式来完成, 但是这样每次启动都要做一遍。放置网卡配置信息的文件是 [.filename]#/etc/rc.conf#。 用您自己喜欢的编辑器打开 [.filename]#/etc/rc.conf#。 并且您需要为每一块系统中存在的网卡添加一行, 在我们的例子中,添加如下几行: [.programlisting] .... ifconfig_dc0="inet 192.168.1.3 netmask 255.255.255.0" ifconfig_dc1="inet 10.0.0.1 netmask 255.255.255.0 media 10baseT/UTP" .... 用自己正确的设备名和地址来替换例子中的 [.filename]#dc0#,[.filename]#dc1# 等内容。您应该应该查阅网卡驱动和 man:ifconfig[8] 的手册页来了解各选项,也要查看一下 man:rc.conf[5] 帮助页来了解 [.filename]#/etc/rc.conf# 的语法。 如果在安装的时候配置了网络,关于网卡的一些行可能已经存在了。 所以在添加新行前仔细检查一下 [.filename]#/etc/rc.conf#。 您也可能需要编辑 [.filename]#/etc/hosts# 来添加局域网中不同的机器名称和 IP 地址, 如果它们不在那里的话。 请查看联机手册 man:hosts[5] 和 [.filename]#/usr/shared/examples/etc/hosts# 以了解更多信息。 [NOTE] ==== 如果计划通过这台机器访问 Internet, 您还需要手工配置默认网关和域名解析服务器: [source,shell] .... # echo 'defaultrouter="your_default_router"' >> /etc/rc.conf # echo 'nameserver your_DNS_server' >> /etc/resolv.conf .... ==== === 测试和调试 对 [.filename]#/etc/rc.conf# 做了必要的修改之后应该重启系统以应用对接口的修改, 并且确认系统重启后没有任何配置错误。 另外您也可以重启网络系统: [source,shell] .... # /etc/rc.d/netif restart .... [NOTE] ==== 如果在 [.filename]#/etc/rc.conf# 中配置了默认网关, 还需要运行下面的命令: [source,shell] .... # /etc/rc.d/routing restart .... ==== 网络系统重启之后, 应测试网络接口。 ==== 测试以太网卡 为了确认网卡被正确的配置了,在这里我们要做两件事情。首先, ping 自己的网络接口,接着 ping 局域网内的其他机器。 首先测试本地接口: [source,shell] .... % ping -c5 192.168.1.3 PING 192.168.1.3 (192.168.1.3): 56 data bytes 64 bytes from 192.168.1.3: icmp_seq=0 ttl=64 time=0.082 ms 64 bytes from 192.168.1.3: icmp_seq=1 ttl=64 time=0.074 ms 64 bytes from 192.168.1.3: icmp_seq=2 ttl=64 time=0.076 ms 64 bytes from 192.168.1.3: icmp_seq=3 ttl=64 time=0.108 ms 64 bytes from 192.168.1.3: icmp_seq=4 ttl=64 time=0.076 ms --- 192.168.1.3 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.074/0.083/0.108/0.013 ms .... 现在我们应该 ping 局域网内的其他机器: [source,shell] .... % ping -c5 192.168.1.2 PING 192.168.1.2 (192.168.1.2): 56 data bytes 64 bytes from 192.168.1.2: icmp_seq=0 ttl=64 time=0.726 ms 64 bytes from 192.168.1.2: icmp_seq=1 ttl=64 time=0.766 ms 64 bytes from 192.168.1.2: icmp_seq=2 ttl=64 time=0.700 ms 64 bytes from 192.168.1.2: icmp_seq=3 ttl=64 time=0.747 ms 64 bytes from 192.168.1.2: icmp_seq=4 ttl=64 time=0.704 ms --- 192.168.1.2 ping statistics --- 5 packets transmitted, 5 packets received, 0 packet loss round-trip min/avg/max/stddev = 0.700/0.729/0.766/0.025 ms .... 您如果您设置了 [.filename]#/etc/hosts# 文件,也可以用机器名来替换 `192.168.1.2`。 ==== 调试 调试硬件和软件配置一直是一件头痛的事情, 从最简单的开始可以减轻一些痛苦。 例如网线是否插好了?是否配置好了网络服务?防火墙配置正确吗? 是否使用了被 FreeBSD 支持的网卡? 在发送错误报告之前您应该查看一下硬件说明, 升级 FreeBSD 到最新的 STABLE 版本, 看一下邮件列表或者在 Internet 上搜索一下。 如果网卡工作了, 但性能低下,应该好好阅读一下 man:tuning[7] 联机手册。 您也可以检查一下网络配置, 不正确的设置会导致慢速的网络连接。 一些用户可能会在一些网卡上经历一到两次 `device timeouts`, 这通常是正常现象。 如果经常这样甚至引起麻烦, 则应确定一下它跟其他设备没有冲突。 仔细检查网线连接, 或者换一块网卡。 有时用户会看到少量 `watchdog timeout` 错误。 这种情况要做的第一件事就是检查线缆连接。 一些网卡需要支持总线控制的 PCI 插槽。 在一些老的主板上,只有一个 PCI 插槽支持 (一般是 slot 0)。 检查网卡和主板说明书来确定是不是这个问题。 `No route to host` 通常发生在如果系统不能发送一个路由到目的主机的包的时候。 这在没有指定默认路由或者网线没有插上时会发生。 检查 `netstat -rn` 的输出并确认有一个有效的路由能到达相应的主机。 如果没有,请查阅 crossref:advanced-networking[advanced-networking,高级网络应用]。 `ping: sendto: Permission denied` 错误信息经常由防火墙的配置错误引起。 如果 `ipfw` 在内核中启用了但是没有定义规则, 那么默认的规则就是拒绝所有通讯,甚至 ping 请求! 查阅 crossref:firewalls[firewalls,防火墙] 以了解更多信息。 有时网卡性能低下或者低于平均水平, 这种情况最好把传输媒介模式从 `autoselect` 改变为正确的传输介质模式。 这通常对大多数硬件有用, 但可能不会解决所有人的问题。 接着,检查所有网络设置,并且阅读 man:tuning[7] 手册页。 [[configtuning-virtual-hosts]] == 虚拟主机 FreeBSD 的一个很普通的用途是虚拟主机站点, 一个服务器虚拟成很多服务器一样提供网络服务。 这通过在一个接口上绑定多个网络地址来实现。 一个特定的网络接口有一个"真实"的地址, 也可能有一些"别名"地址。这些别名通常用 [.filename]#/etc/rc.conf# 中的记录来添加。 一个 [.filename]#fxp0# 的别名记录类似于: [.programlisting] .... ifconfig_fxp0_alias0="inet xxx.xxx.xxx.xxx netmask xxx.xxx.xxx.xxx" .... 记住别名记录必须从 `alias0` 开始并且按顺序递增(例如 `_alias1`、 `_alias2`)。 配置程序将会停止在第一个缺少的数字的地方。 f计算别名的子网掩码是很重要的,幸运的是它很简单。 对于一个接口来说,必须有一个描述子网掩码的地址。 任何在这个网段下的地址必须有一个全是 `1` 的子网掩码(通常表示为 `255.255.255.255` 或 `0xffffffff`。 举例来说, 假设使用 [.filename]#fxp0# 连接到两个网络, 分别是 `10.1.1.0`, 其子网掩码为 `255.255.255.0`, 以及 `202.0.75.16`, 其子网掩码为 `255.255.255.240`。 我们希望从 `10.1.1.1` 到 `10.1.1.5` 以及从 `202.0.75.17` 到 `202.0.75.20` 的地址能够互相访问。 如前所述, 只有两个网段中的第一个地址 (本例中, `10.0.1.1` 和 `202.0.75.17`) 应使用真实的子网掩码; 其余的 (`10.1.1.2` 到 `10.1.1.5` 以及 `202.0.75.18` 到 `202.0.75.20`) 则必须配置为使用 `255.255.255.255` 作为子网掩码。 下面是根据上述描述所进行的 [.filename]#/etc/rc.conf# 配置: [.programlisting] .... ifconfig_fxp0="inet 10.1.1.1 netmask 255.255.255.0" ifconfig_fxp0_alias0="inet 10.1.1.2 netmask 255.255.255.255" ifconfig_fxp0_alias1="inet 10.1.1.3 netmask 255.255.255.255" ifconfig_fxp0_alias2="inet 10.1.1.4 netmask 255.255.255.255" ifconfig_fxp0_alias3="inet 10.1.1.5 netmask 255.255.255.255" ifconfig_fxp0_alias4="inet 202.0.75.17 netmask 255.255.255.240" ifconfig_fxp0_alias5="inet 202.0.75.18 netmask 255.255.255.255" ifconfig_fxp0_alias6="inet 202.0.75.19 netmask 255.255.255.255" ifconfig_fxp0_alias7="inet 202.0.75.20 netmask 255.255.255.255" .... [[configtuning-configfiles]] == 配置文件 === [.filename]#/etc# 布局 在配置信息中有很多的目录,这些包括: [.informaltable] [cols="1,1", frame="none"] |=== |[.filename]#/etc# |一般的系统配置信息。这儿的数据是与特定系统相关的。 |[.filename]#/etc/defaults# |系统配置文件的默认版本。 |[.filename]#/etc/mail# |额外的 man:sendmail[8] 配置信息,其他 MTA 配置文件。 |[.filename]#/etc/ppp# |用于用户级和内核级 ppp 程序的配置。 |[.filename]#/etc/namedb# |man:named[8] 数据的默认位置。通常 [.filename]#named.conf# 和区域文件存放在这里。 |[.filename]#/usr/local/etc# |被安装的应用程序配置文件。可以参考每个应用程序的子目录。 |[.filename]#/usr/local/etc/rc.d# |被安装程序的 启动/停止 脚本。 |[.filename]#/var/db# |特定系统自动产生的数据库文件,像 package 数据库,位置数据库等等。 |=== === 主机名 ==== [.filename]#/etc/resolv.conf# [.filename]#/etc/resolv.conf# 指示了 FreeBSD 如何访问域名系统(DNS)。 [.filename]#resolv.conf# 中最常见的记录是: [.informaltable] [cols="1,1", frame="none"] |=== |`nameserver` |按顺序要查询的名字服务器的 IP 地址,最多三个。 |`search` | 搜索机器名的列表。这通常由本地机器名的域决定。 |`domain` |本地域名。 |=== 一个典型的 [.filename]#resolv.conf# 文件: [.programlisting] .... search example.com nameserver 147.11.1.11 nameserver 147.11.100.30 .... [NOTE] ==== 只能使用一个 `search` 和 `domain` 选项。 ==== 如果您在使用 DHCP,man:dhclient[8] 经常使用从 DHCP 服务器接受来的信息重写 [.filename]#resolv.conf#。 ==== [.filename]#/etc/hosts# [.filename]#/etc/hosts# 是 Internet 早期使用的一个简单文本数据库。 它结合 DNS 和 NIS 提供名字到 IP 地址的映射。 通过局域网连接的机器可以用这个简单的命名方案来替代设置一个 man:named[8] 服务器。另外,[.filename]#/etc/hosts# 也可以提供一个 Internet 名称的本地纪录以减轻需要从外部查询带来的负担。 [.programlisting] .... # $FreeBSD$ # # # Host Database # # This file should contain the addresses and aliases for local hosts that # share this file. Replace 'my.domain' below with the domainname of your # machine. # # In the presence of the domain name service or NIS, this file may # not be consulted at all; see /etc/nsswitch.conf for the resolution order. # # ::1 localhost localhost.my.domain 127.0.0.1 localhost localhost.my.domain # # Imaginary network. #10.0.0.2 myname.my.domain myname #10.0.0.3 myfriend.my.domain myfriend # # According to RFC 1918, you can use the following IP networks for # private nets which will never be connected to the Internet: # # 10.0.0.0 - 10.255.255.255 # 172.16.0.0 - 172.31.255.255 # 192.168.0.0 - 192.168.255.255 # # In case you want to be able to connect to the Internet, you need # real official assigned numbers. Do not try to invent your own network # numbers but instead get one from your network provider (if any) or # from your regional registry (ARIN, APNIC, LACNIC, RIPE NCC, or AfriNIC.) # .... [.filename]#/etc/hosts# 用简单的格式: [.programlisting] .... [Internet address] [official hostname] [alias1] [alias2] ... .... 例如: [.programlisting] .... 10.0.0.1 myRealHostname.example.com myRealHostname foobar1 foobar2 .... 参考 man:hosts[5] 以获得更多信息。 === 日志文件配置 ==== [.filename]#syslog.conf# [.filename]#syslog.conf# 是 man:syslogd[8] 程序的配置文件。 它指出了的 `syslog` 哪种信息类型被存储在特定的日志文件中。 [.programlisting] .... # $FreeBSD$ # # Spaces ARE valid field separators in this file. However, # other *nix-like systems still insist on using tabs as field # separators. If you are sharing this file between systems, you # may want to use only tabs as field separators here. # Consult the syslog.conf(5) manual page. *.err;kern.debug;auth.notice;mail.crit /dev/console *.notice;kern.debug;lpr.info;mail.crit;news.err /var/log/messages security.* /var/log/security mail.info /var/log/maillog lpr.info /var/log/lpd-errs cron.* /var/log/cron *.err root *.notice;news.err root *.alert root *.emerg * # uncomment this to log all writes to /dev/console to /var/log/console.log #console.info /var/log/console.log # uncomment this to enable logging of all log messages to /var/log/all.log #*.* /var/log/all.log # uncomment this to enable logging to a remote log host named loghost #*.* @loghost # uncomment these if you're running inn # news.crit /var/log/news/news.crit # news.err /var/log/news/news.err # news.notice /var/log/news/news.notice !startslip *.* /var/log/slip.log !ppp *.* /var/log/ppp.log .... 参考 man:syslog.conf[5] 手册页以获得更多信息 ==== [.filename]#newsyslog.conf# [.filename]#newsyslog.conf# 是一个通常用 man:cron[8] 计划运行的 man:newsyslog[8] 程序的配置文件。 man:newsyslog[8] 指出了什么时候日志文件需要打包或者重新整理。 比如 [.filename]#logfile# 被移动到 [.filename]#logfile.0#,[.filename]#logfile.0# 被移动到 [.filename]#logfile.1# 等等。另外,日志文件可以用 man:gzip[1] 来压缩,它们是这样的命名格式: [.filename]#logfile.0.gz#,[.filename]#logfile.1.gz# 等等。 [.filename]#newsyslog.conf# 指出了哪个日志文件要被管理,要保留多少和它们什么时候被创建。 日志文件可以在它们达到一定大小或者在特定的日期被重新整理。 [.programlisting] .... # configuration file for newsyslog # $FreeBSD$ # # filename [owner:group] mode count size when [ZB] [/pid_file] [sig_num] /var/log/cron 600 3 100 * Z /var/log/amd.log 644 7 100 * Z /var/log/kerberos.log 644 7 100 * Z /var/log/lpd-errs 644 7 100 * Z /var/log/maillog 644 7 * @T00 Z /var/log/sendmail.st 644 10 * 168 B /var/log/messages 644 5 100 * Z /var/log/all.log 600 7 * @T00 Z /var/log/slip.log 600 3 100 * Z /var/log/ppp.log 600 3 100 * Z /var/log/security 600 10 100 * Z /var/log/wtmp 644 3 * @01T05 B /var/log/daily.log 640 7 * @T00 Z /var/log/weekly.log 640 5 1 $W6D0 Z /var/log/monthly.log 640 12 * $M1D0 Z /var/log/console.log 640 5 100 * Z .... 参考 man:newsyslog[8] 手册页以获得更多信息。 [[configtuning-sysctlconf]] === [.filename]#sysctl.conf# [.filename]#sysctl.conf# 和 [.filename]#rc.conf# 这两个文件的风格很接近。 其中的配置均为 `变量=值` 这样的形式。 在这个文件中配置的值, 均会在系统进入多用户模式之后进行实际的修改操作。 需要注意的是, 并不是所有的变量都能够在多用户模式下修改。 如果希望关闭对收到致命的信号退出的进程进行记录, 并阻止普通用户看到其他用户的进程, 可以在 [.filename]#sysctl.conf# 中进行下列配置: [.programlisting] .... # 不记录由于致命信号导致的进程退出 (例如信号 11,访问越界) kern.logsigexit=0 # 阻止用户看到以其他用户 UID 身份执行的进程。 security.bsd.see_other_uids=0 .... [[configtuning-sysctl]] == 用 sysctl 进行调整 man:sysctl[8] 是一个允许您改变正在运行中的 FreeBSD 系统的接口。它包含一些 TCP/IP 堆栈和虚拟内存系统的高级选项, 这可以让有经验的管理员提高引人注目的系统性能。用 man:sysctl[8] 可以读取设置超过五百个系统变量。 基于这点,man:sysctl[8] 提供两个功能:读取和修改系统设置。 查看所有可读变量: [source,shell] .... % sysctl -a .... 读一个指定的变量,例如 `kern.maxproc`: [source,shell] .... % sysctl kern.maxproc kern.maxproc: 1044 .... 要设置一个指定的变量,直接用 _variable_=_value_ 这样的语法: [source,shell] .... # sysctl kern.maxfiles=5000 kern.maxfiles: 2088 -> 5000 .... sysctl 变量的设置通常是字符串、数字或者布尔型。 (布尔型用 `1` 来表示'yes',用 `0` 来表示'no')。 如果你想在每次机器启动时自动设置某些变量, 可将它们加入到文件 [.filename]#/etc/sysctl.conf# 之中。更多信息,请参阅手册页 man:sysctl.conf[5] 及 <>。 [[sysctl-readonly]] === 只读的 man:sysctl[8] 有时可能会需要修改某些只读的 man:sysctl[8] 的值。 尽管有时不得不这样做, 但只有通过(重新)启动才能达到这样的目的。 例如一些膝上型电脑的 man:cardbus[4] 设备不会探测内存范围,并且产生看似于这样的错误: [source,shell] .... cbb0: Could not map register memory device_probe_and_attach: cbb0 attach returned 12 .... 像上面的错误通常需要修改一些只读的 man:sysctl[8] 默认设置。要实现这点,用户可以在本地的 [.filename]#/boot/loader.conf.local# 里面放一个 man:sysctl[8] "OIDs"。那些设置定位在 [.filename]#/boot/defaults/loader.conf# 文件中。 修复上面的问题用户需要在刚才所说的文件中设置 `hw.pci.allow_unsupported_io_range=1`。现在 man:cardbus[4] 就会正常的工作了。 [[configtuning-disk]] == 调整磁盘 === Sysctl 变量 ==== `vfs.vmiodirenable` `vfs.vmiodirenable` sysctl 变量可以设置成0(关)或者1(开);默认是1。 这个变量控制目录是否被系统缓存。大多数目录是小的, 在系统中只使用单个片断(典型的是1K)并且在缓存中使用的更小 (典型的是512字节)。当这个变量设置为关闭 (`0`) 时, 缓存器仅仅缓存固定数量的目录,即使您有很大的内存。 而将其开启 (设置为1) 时, 则允许缓存器用 VM 页面缓存来缓存这些目录,让所有可用内存来缓存目录。 不利的是最小的用来缓存目录的核心内存是大于 512 字节的物理页面大小(通常是 4k)。 我们建议如果您在运行任何操作大量文件的程序时保持这个选项打开的默认值。 这些服务包括 web 缓存,大容量邮件系统和新闻系统。 尽管可能会浪费一些内存,但打开这个选项通常不会降低性能。 但还是应该检验一下。 ==== `vfs.write_behind` `vfs.write_behind` sysctl 变量默认是 `1` (打开)。 它告诉文件系统簇被收集满的时候把内容写进介质, 典型的是在写入大的连续的文件时。 主要的想法是, 如果可能对 I/O 性能会产生负面影响时, 应尽量避免让缓冲缓存被未同步缓冲区充满。 然而它可能降低处理速度并且在某些情况下您可能想要关闭它。 ==== `vfs.hirunningspace` `vfs.hirunningspace` sysctl 变量决定了在任何给定情况下, 有多少写 I/O 被排进队列以给系统的磁盘控制器。 默认值一般是足够的,但是对有很多磁盘的机器来说您可能需要把它设置成 4M 或 5M。注意这个设置成很高的值(超过缓存器的写极限)会导致坏的性能。 不要盲目的把它设置太高!高的数值会导致同时发生的读操作的迟延。 sysctl 中还有许多与 buffer cache 和 VM页面 cache 有关的值, 一般不推荐修改它们。 虚拟内存系统已经能够很好地进行自动调整了。 ==== `vm.swap_idle_enabled` `vm.swap_idle_enabled` sysctl 变量在有很多用户进入、离开系统和有很多空闲进程的大的多用户系统中很有用。 这些系统注重在空闲的内存中间产生连续压力的处理。通过 `vm.swap_idle_threshold1` 和 `vm.swap_idle_threshold2` 打开这个特性并且调整交换滞后 (在空闲时)允许您降低内存页中空闲进程的优先权,从而比正常的出页 (pageout)算法更快。这给出页守护进程带来了帮助。 除非您需要否则不要把这个选项打开,因为您所权衡的是更快地进入内存, 因而它会吃掉更多的交换和磁盘带宽。在小的系统上它会有决定性的效果, 但是在大的系统上它已经做了合适的页面调度这个选项允许 VM 系统容易的让全部的进程进出内存。 ==== `hw.ata.wc` FreeBSD 4.3 中默认将 IDE 的写缓存关掉了。 这会降低到 IDE 磁盘用于写入操作的带宽, 但我们认为这有助于避免硬盘厂商所引入的, 可能引致严重的数据不一致问题。 这类问题实际上是由于 IDE 硬盘就写操作完成这件事的不诚实导致的。 当启用了 IDE 写入缓存时, IDE 硬盘驱动器不但不会按顺序将数据写到盘上, 而且当磁盘承受重载时, 它甚至会自作主张地对推迟某些块的实际写操作。 这样一来, 在系统发生崩溃或掉电时, 就会导致严重的文件系统损坏。 基于这些考虑, 我们将 FreeBSD 的默认配置改成了更为安全的禁用 IDE 写入缓存。 然而不幸的是, 这样做导致了性能的大幅降低, 因此在后来的发行版中这个配置又改为默认启用了。 您可以通过观察 `hw.ata.wc` sysctl 变量, 来确认您的系统中所采用的默认值。 如果 IDE 写缓存被禁用, 您可以通过将内核变量设置为 1 来启用它。 这一操作必须在启动时通过 boot loader 来完成。 在内核启动之后尝试这么做是没有任何作用的。 要了解更多的信息,请查阅 man:ata[4]。 ==== `SCSI_DELAY` (`kern.cam.scsi_delay`) `SCSI_DELAY` 内核配置会缩短系统启动时间。 默认值在系统启动过程中有 `15` 秒的迟延时间, 这是一个足够多且可靠的值。把它减少到 `5` 通常也能工作(特别是现代的驱动器)。 您可以在系统引导时调整引导加载器变量 `kern.cam.scsi_delay` 来改变它。 需要注意的是, 此处使用的单位是 _毫秒_ 而 _不_ 是 _秒_ 。 [[soft-updates]] === Soft Updates man:tunefs[8] 程序能够用来很好的调整文件系统。 这个程序有很多不同的选项,但是现在只介绍 Soft Updates 的打开和关闭,这样做: [source,shell] .... # tunefs -n enable /filesystem # tunefs -n disable /filesystem .... 在文件系统被挂载之后不能用 man:tunefs[8] 来修改。打开 Soft Updates 的最佳时机是在单用户模式下任何分区被挂载前。 Soft Updates 极大地改善了元数据修改的性能, 主要是文件创建和删除,通过内存缓存。我们建议您在所有的文件系统上使用 Soft Updates。应该知道 Soft Updates 的两点:首先, Soft Updates 保证了崩溃后的文件系统完整性,但是很可能有几秒钟 (甚至一分钟!) 之前的数据没有写到物理磁盘。如果您的系统崩溃了您可能会丢失很多工作。 第二,SoftUpdates 推迟文件系统块的释放时间。如果在文件系统 (例如根文件系统)快满了的情况下对系统进行大规模的升级比如 `make installworld`, 可能会引起磁盘空间不足从而造成升级失败。 ==== Soft Updates 的详细资料 有两种传统的方法来把文件系统的元数据 (meta-data) 写入磁盘。 (Meta-data更新是更新类似 inodes 或者目录这些没有内容的数据) 从前,默认方法是同步更新这些元数据(meta-data)。 如果一个目录改变了,系统在真正写到磁盘之前一直等待。 文件数据缓存(文件内容)在这之后以非同步形式写入。 这么做有利的一点是操作安全。如果更新时发生错误,元数据(meta-data) 一直处于完整状态。文件要不就被完整的创建要不根本就不创建。 如果崩溃时找不到文件的数据块,man:fsck[8] 可以找到并且依靠把文件大小设置为 0 来修复文件系统。 另外,这么做既清楚又简单。缺点是元数据(meta-data)更新很慢。例如 `rm -r` 命令,依次触及目录下的所有文件, 但是每个目录的改变(删除一个文件)都要同步写入磁盘。 这包含它自己更新目录,inode 表和可能对文件分散的块的更新。 同样问题出现大的文件操作上(比如 `tar -x`)。 第二种方法是非同步元数据更新。这是 Linux/ext2fs 和 *BSD ufs 的 `mount -o async` 默认的方法。所有元数据更新也是通过缓存。 也就是它们会混合在文件内容数据更新中。 这个方法的优点是不需要等待每个元数据更新都写到磁盘上, 所以所有引起元数据更新大的操作比同步方式更快。同样, 这个方法也是清楚且简单的,所以代码中的漏洞风险很小。 缺点是不能保证文件系统的状态一致性。如果更新大量元数据时失败 (例如掉电或者按了重启按钮),文件系统会处在不可预知的状态。 系统再启动时没有机会检查文件系统的状态;inode 表更新的时候可能文件的数据块已经写入磁盘了但是相关联的目录没有,却不能用 `fsck` 命令来清理(因为磁盘上没有所需要的信息)。 如果文件系统修复后损坏了,唯一的选择是使用 man:newfs[8] 并且从备份中恢复它。 这个问题通常的解决办法是使用 _dirty region logging_ 或者 _journaling_ 尽管它不是一贯的被使用并且有时候应用到其他的事务纪录中更好。 这种方法元数据更新依然同步写入,但是只写到磁盘的一个小区域。 过后他们将会被移动到正确的位置。因为纪录区很小, 磁盘上接近的区域磁头不需要移动很长的距离,所以这些比写同步快一些。 另外这个方法的复杂性有限,所以出现错误的机会也很少。缺点是元数据要写两次 (一次写到纪录区域,一次写到正确的区域)。正常情况下, 悲观的性能可能会发生。从另一方面来讲, 崩溃的时候所有未发生的元数据操作可以很快的在系统启动之后从记录中恢复过来。 Kirk McKusick,伯克利 FFS 的开发者,用 Soft Updates 解决了这个问题:元数据更新保存在内存中并且按照排列的顺序写入到磁盘 ("有序的元数据更新")。这样的结果是,在繁重的元数据操作中, 如果先前的更新还在内存中没有被写进磁盘,后来的更新就会捕捉到。 所以所有的目录操作在写进磁盘的时候首先在内存中执行 (数据块按照它们的位置来排列,所以它们不会在元数据前被写入)。 如果系统崩溃了这将导致一个固定的 "日志回朔": 所有不知如何写入磁盘的操作都像没有发生过一样。文件系统的一致性保持在 30 到 60 秒之前。它保证了所有正在使用的资源被标记例如块和 inodes。崩溃之后, 唯一的资源分配错误是一个实际是"空闲"的资源的资源被标记为"使用"。 man:fsck[8] 可以认出这种情况并且释放不再使用的资源。它对于忽略崩溃后用 `mount -f` 强制挂上的文件系统的错误状态是安全的。 为了释放可能没有使用的资源,man:fsck[8] 需要在过后的时间运行。一个主意是用 _后台 fsck_:系统启动的时候只有一个文件系统的 _快照_ 被记录下来。`fsck` 可以在过后运行。所有文件系统可以在"有错误"的时候被挂接, 所以系统可以在多用户模式下启动。接着,后台 `fsck` 可以在所有文件系统需要的时候启动来释放可能没有使用的资源。 (尽管这样,不用 Soft Updates 的文件系统依然需要通常的 `fsck`。) f它的优点是元数据操作几乎跟非同步一样快 (也就是比需要两次元数据写操作的 _logging_ 更快)。缺点是代码的复杂性(意味着对于丢失用户敏感数据有更多的风险) 和高的内存使用量。另外它有些特点需要知道。崩溃之后, 文件系统状态会"落后"一些。同步的方法用 `fsck` 后在一些地方可能产生一些零字节的文件, 这些文件在用 Soft Updates 文件系统之后不会存在, 因为元数据和文件内容根本没有写进磁盘(可能发生在运行 `rm` 之后)。这可能在文件系统上安装大量数据时候引发问题, 没有足够的剩余空间来两次存储所有文件。 [[configtuning-kernel-limits]] == 调整内核限制 [[file-process-limits]] === 文件/进程限制 [[kern-maxfiles]] ==== `kern.maxfiles` `kern.maxfiles` 可以根据系统的需要适当增减。 这个变量用于指定在系统中允许的文件描述符的最大数量。 当文件描述符表满的时候, `file: table is full` 会在系统消息缓冲区中反复出现, 您可以使用 `dmesg` 命令来观察这一现象。 每个打开的文件、 套接字和管道, 都会占用一个文件描述符。 在大型生产服务器上, 可能会轻易地用掉数千个文件描述符, 具体用量取决于服务的类型和并行启动的服务数量。 在早期版本的 FreeBSD 中, `kern.maxfiles` 的默认值, 是根据您内核配置文件中的 `maxusers` 选项计算的。 `kern.maxfiles` 这个数值, 会随 `maxusers` 成比例地增减。 当编译定制的内核时, 按照您系统的用途来修改这个值是个好主意。 这个数字同时还决定内核的许多预设的限制值。 有时, 尽管并不会真的有 256 个用户同时连接一台生产服务器, 但对于高负载的 web 服务器而言, 却可能需要与之类似的资源。 变量 `kern.maxusers` 会在系统启动时, 根据可用内存的尺寸进行计算, 在内核开始运行之后, 可以通过只读的 `kern.maxusers` sysctl 变量值来进行观察。 有些情况下, 可能会希望使用更大或更小一些的 `kern.maxusers`, 它可以以加载器变量的形式进行配置; 类似 64、 128 和 256 这样的值都并不罕见。 我们不推荐使用超过 256 的值, 除非您需要巨量的文件描述符; 根据 `kern.maxusers` 推算默认值的那些变量, 一般都可以在引导甚至运行时通过 [.filename]#/boot/loader.conf# (请参见 man:loader.conf[5] 联机手册或 [.filename]#/boot/defaults/loader.conf# 文件来获得相关的指导) 或这篇文档的其余部分所介绍的方式来调整。 在较早的版本中, 如果您明确地将 `maxusers` 设置为 `0`, 则系统会自动地根据硬件配置来确定这个值。。 在 FreeBSD 5.X 和更高版本中, `maxusers` 如果不指定的话, 就会取默认值 `0`。 如果希望自行管理 `maxusers`, 则应配置一个不低于 4 的值, 特别是使用 X Window System 或编译软件的时候。 这样做的原因是, `maxusers` 所决定的一个最为重要的表的尺寸会影响最大进程数, 这个数值将是 `20 + 16 * maxusers`。 因此如果将 `maxusers` 设置为 1, 您就只能同时运行 36 个进程, 这还包括了 18 个左右的系统引导时启动的进程, 以及 15 个左右的, 在您启动 X Window System 时所引发的进程。 即使是简单的任务, 如阅读联机手册, 也需要启动多至九个的进程, 用以过滤、 解压缩, 并显示它。 将 `maxusers` 设为 64 将允许您同时执行最多 1044 个进程, 这几乎足以满足任何需要了。 不过, 如果您看在启动其它程序, 或运行用以支持大量用户的服务 (例如 `ftp.FreeBSD.org`) 时, 看到令人担忧的 错误, 就应该提高这一数值, 并重新联编内核。 [NOTE] ==== `maxusers` 并 _不能_ 限制实际能够登录到您系统上来的用户的数量。 它的主要作用是根据您可能支持的用户数量来为一系列系统数据表设置合理的尺寸, 以便提供支持他们所需运行的进程资源。 ==== ==== `kern.ipc.somaxconn` `kern.ipc.somaxconn` sysctl 变量 限制了接收新 TCP 连接侦听队列的大小。对于一个经常处理新连接的高负载 web服务环境来说,默认的 `128` 太小了。 大多数环境这个值建议增加到 `1024` 或者更多。 服务进程会自己限制侦听队列的大小(例如 man:sendmail[8] 或者 Apache), 常常在它们的配置文件中有设置队列大小的选项。 大的侦听队列对防止拒绝服务 攻击也会有所帮助。 [[nmbclusters]] === 网络限制 `NMBCLUSTERS` 内核配置选项指出了系统可用的网络Mbuf的数量。 一个高流量的服务器使用一个小数目的网络缓存会影响 FreeBSD 的性能。 每个 cluster 可能需要2K内存,所以一个1024的值需要在内核中给网络缓存保留2M内存。 可以用简单的方法计算出来需要多少网络缓存。 如果您有一个同时发生1000个以上连接的web服务器, 并且每个连接用掉16K接收和发送缓存, 就需要大概32M网络缓存来确保web服务器的工作。 一个好的简单计算方法是乘以2,所以2x32Mb/2Kb=64MB/2kb=32768。 我们建议在有大量内存的机器上把这个值设置在4096到32768之间。 没有必要把它设置成任意太高的值,它会在启动时引起崩溃。 man:netstat[1] 的 `-m` 选项可以用来观察网络cluster使用情况。 `kern.ipc.nmbclusters` 可以用来在启动时刻调节这个。 仅仅在旧版本的 FreeBSD 需要使用 `NMBCLUSTERS` man:config[8] 选项。 经常使用 man:sendfile[2] 系统调用的繁忙的服务器, 有必要通过 `NSFBUFS` 内核选项或者在 [.filename]#/boot/loader.conf# (查看 man:loader[8] 以获得更多细节) 中设置它的值来调节 man:sendfile[2] 缓存数量。 这个参数需要调节的普通原因是在进程中看到 `sfbufa` 状态。sysctl `kern.ipc.nsfbufs` 变量在内核配置变量中是只读的。 这个参数是由 `kern.maxusers` 决定的,然而它可能有必要因此而调整。 [IMPORTANT] ==== 即使一个套接字被标记成非阻塞,在这个非阻塞的套接字上呼叫 man:sendfile[2] 可能导致 man:sendfile[2] 呼叫阻塞直到有足够的 `struct sf_buf` 可用。 ==== ==== `net.inet.ip.portrange.*` `net.inet.ip.portrange.*` sysctl 变量自动的控制绑定在 TCP 和 UDP 套接字上的端口范围。 这里有三个范围:一个低端范围,一个默认范围和一个高端范围。 大多数网络程序分别使用由 `net.inet.ip.portrange.first` 和 `net.inet.ip.portrange.last` 控制的从 1024 到 5000 的默认范围。端口范围用作对外连接,并且某些情况可能用完系统的端口, 这经常发生在运行一个高负荷 web 代理服务器的时候。 这个端口范围不是用来限制主要的例如 web 服务器进入连接或者有固定端口例如邮件传递对外连接的。 有时您可能用完了端口,那就建议适当的增加 `net.inet.ip.portrange.last`。 `10000`、`20000` 或者 `30000` 可能是适当的值。 更改端口范围的时候也要考虑到防火墙。 一些防火墙会阻止端口的大部分范围 (通常是低范围的端口)并且用高端口进行对外连接(-)。 基于这个问题建议不要把 `net.inet.ip.portrange.first` 设的太小。 ==== TCP 带宽迟延(Bandwidth Delay Product) 限制 TCP 带宽延迟积和 NetBSD 的 TCP/Vegas 类似。 它可以通过将 sysctl 变量 `net.inet.tcp.inflight.enable` 设置成 `1` 来启用。 系统将尝试计算每一个连接的带宽延迟积, 并将排队的数据量限制在恰好能保持最优吞吐量的水平上。 这一特性在您的服务器同时向使用普通调制解调器, 千兆以太网, 乃至更高速度的光与网络连接 (或其他带宽延迟积很大的连接) 的时候尤为重要, 特别是当您同时使用滑动窗缩放, 或使用了大的发送窗口的时候。 如果启用了这个选项, 您还应该把 `net.inet.tcp.inflight.debug` 设置为 `0` (禁用调试), 对于生产环境而言, 将 `net.inet.tcp.inflight.min` 设置成至少 `6144` 会很有好处。 然而, 需要注意的是, 这个值设置过大事实上相当于禁用了连接带宽延迟积限制功能。 这个限制特性减少了在路由和交换包队列的堵塞数据数量, 也减少了在本地主机接口队列阻塞的数据的数量。在少数的等候队列中、 交互式连接,尤其是通过慢速的调制解调器,也能用低的 __往返时间__操作。但是,注意这只影响到数据发送 (上载/服务端)。对数据接收(下载)没有效果。 调整 `net.inet.tcp.inflight.stab` 是 _不_ 推荐的。 这个参数的默认值是 20, 表示把 2 个最大包加入到带宽延迟积窗口的计算中。 额外的窗口似的算法更为稳定, 并改善对于多变网络环境的相应能力, 但也会导致慢速连接下的 ping 时间增长 (尽管还是会比没有使用 inflight 算法低许多)。 对于这些情形, 您可能会希望把这个参数减少到 15, 10, 或 5; 并可能因此而不得不减少 `net.inet.tcp.inflight.min` (比如说, 3500) 来得到希望的效果。 减少这些参数的值, 只应作为最后不得已时的手段来使用。 === 虚拟内存 ==== `kern.maxvnodes` vnode 是对文件或目录的一种内部表达。 因此, 增加可以被操作系统利用的 vnode 数量将降低磁盘的 I/O。 一般而言, 这是由操作系统自行完成的, 也不需要加以修改。 但在某些时候磁盘 I/O 会成为瓶颈, 而系统的 vnode 不足, 则这一配置应被增加。 此时需要考虑是非活跃和空闲内存的数量。 要查看当前在用的 vnode 数量: [source,shell] .... # sysctl vfs.numvnodes vfs.numvnodes: 91349 .... 要查看最大可用的 vnode 数量: [source,shell] .... # sysctl kern.maxvnodes kern.maxvnodes: 100000 .... 如果当前的 vnode 用量接近最大值, 则将 `kern.maxvnodes` 值增大 1,000 可能是个好主意。 您应继续查看 `vfs.numvnodes` 的数值, 如果它再次攀升到接近最大值的程度, 仍需继续提高 `kern.maxvnodes`。 在 man:top[1] 中显示的内存用量应有显著变化, 更多内存会处于活跃 (active) 状态。 [[adding-swap-space]] == 添加交换空间 不管您计划得如何好,有时候系统并不像您所期待的那样运行。 如果您发现需要更多的交换空间,添加它很简单。 有三种方法增加交换空间:添加一块新的硬盘驱动器、通过 NFS 使用交换空间和在一个现有的分区上创建一个交换文件。 要了解关于如何加密交换区, 相关配置, 以及为什么要这样做, 请参阅手册的 crossref:disks[swap-encrypting,对交换区进行加密]。 [[new-drive-swap]] === 在新的硬盘驱动器上使用交换空间 这是添加交换空间最好的方法, 当然为了达到这个目的需要添加一块硬盘。 毕竟您总是可以使用另一块磁盘。如果能这么做, 重新阅读一下手册中关于交换空间的 <> 来了解如何最优地安排交换空间。 [[nfs-swap]] === 通过 NFS 交换 除非没有可以用作交换空间的本地硬盘时, 否则不推荐您使用 NFS 来作为交换空间使用。 NFS 交换会受到可用网络带宽限制并且增加 NFS 服务器的负担。 [[create-swapfile]] === 交换文件 您可以创建一个指定大小的文件用来当作交换文件。 在我们的例子中我们将会使用叫做 [.filename]#/usr/swap0# 的 64MB 大小的文件。当然您也可以使用任何您所希望的名字。 .在 FreeBSD 中创建交换文件 [example] ==== . 确认您的内核配置包含虚拟磁盘(Memory disk)驱动 (man:md[4])。它在 [.filename]#GENERIC# 内核中是默认的。 + [.programlisting] .... device md # Memory "disks" .... + . 创建一个交换文件([.filename]#/usr/swap0#): + [source,shell] .... # dd if=/dev/zero of=/usr/swap0 bs=1024k count=64 .... + . 赋予它([.filename]#/usr/swap0#)一个适当的权限: + [source,shell] .... # chmod 0600 /usr/swap0 .... + . 在 [.filename]#/etc/rc.conf# 中启用交换文件: + [.programlisting] .... swapfile="/usr/swap0" # Set to name of swapfile if aux swapfile desired. .... + . 通过重新启动机器或下面的命令使交换文件立刻生效: + [source,shell] .... # mdconfig -a -t vnode -f /usr/swap0 -u 0 && swapon /dev/md0 .... ==== [[acpi-overview]] == 电源和资源管理 BIOS 接口管理,例如__可插拔 BIOS (PNPBIOS)__或者__高级电源管理(APM)__ 等等。电源和资源管理是现代操作系统的关键组成部分。 例如您可能当系统温度过高的时候让您的操作系统能监视到 (并且可能提醒您)。 以有效的方式利用硬件资源是非常重要的。 在引入 ACPI 之前, 管理电源使用和系统散热对操作系统是很困难的。 硬件由 BIOS 进行管理, 因而用户对电源管理配置的控制和查看都比较困难。 一些系统通过 _高级电源管理 (APM)_ 提供了有限的配置能力。 电源和资源管理是现代操作系统的一个关键组件。 例如, 您可能希望操作系统监视系统的一些限制, 例如系统的温度是否超出了预期的增长速度 (并在需要时发出警告)。 在 FreeBSD 使用手册的这一章节,我们将提供 ACPI 全面的信息。 参考资料会在末尾给出。 [[acpi-intro]] === 什么是 ACPI? 高级配置和电源接口 (ACPI) 是一个业界标准的硬件资源和电源管理接口 (因此而得名) 。它是 _操作系统控制的配置和电源管理(Operating System-directed configuration and Power Management)_,也就是说, 它给操作系统(OS)提供了更多的控制和弹性。 在引入 ACPI 之前, 现代操作系统使得目前即插即用接口的局限性更加 "凸现" 出来。 ACPI 是 APM(高级电源管理) 的直接继承者。 [[acpi-old-spec]] === 高级电源管理 (APM) 的缺点 _高级电源管理 (APM)_ 是一种基于系统目前的活动控制其电源使用的机制。 APM BIOS 由 (系统的) 制造商提供, 并且是硬件平台专属的。 在 OS 中的 APM 驱动作为中介来访问 _APM 软件接口_, 从而实现对电源使用的管理。 在 2000 年或更早的时期生产的计算机系统, 仍需要使用 APM。 APM 有四个主要的问题。 首先, 电源管理是通过 (制造商专属的) BIOS 实现的, 而 OS 则完全不了解其细节。 例如, 用户在 APM BIOS 中设置了硬盘驱动器的空闲等待数值, 当超过这一空闲时间的限制时, 它 (BIOS) 将会减慢硬盘驱动器的速度, 而不会征求 OS 的同意。 第二, APM 逻辑是嵌入 BIOS 的, 因此它是在 OS 的控制之外运转的。 这意味着用户只能通过通过刷新他们 ROM 中的 APM BIOS 才能够解决某些问题; 而这是一个很危险的操作, 因为它可能使系统进入一个无法恢复的状态。 第三, APM 是一种制造商专属的技术, 也就是说有很多第三方的 (重复的工作) 以及 bugs, 如果在一个制造商的 BIOS 中有, 也未必会在其他的产品中解决。 最后但绝不是最小的问题, APM BIOS 没有为实现复杂的电源策略提供足够的余地, 也无法实现能够非常适合具体机器的策略。 _即插即用 BIOS (PNPBIOS)_ 在很多时候都是不可靠的。 PNPBIOS 是 16-位 的技术, 因此 OS 不得不使用 16-位 模拟才能够与 PNPBIOS 的方法 "接口"。 FreeBSD APM 驱动在 man:apm[4] 手册页中有描述。 [[acpi-config]] === 配置 ACPI 默认情况下, [.filename]#acpi.ko# 驱动, 会在系统引导时由 man:loader[8] 加载, 而 _不应_ 直接联编进内核。 这样做的原因是模块操作起来更方便, 例如, 无需重新联编内核就可以切换到另一个 [.filename]#acpi.ko# 版本。 这样可以让测试变得更简单一些。 另一个原因是, 许多时候在启动已经启动之后再启动 ACPI 可能会有些问题。 如果您遇到了问题, 可以全面禁用 ACPI。 这个驱动不应, 目前也无法卸载, 因为系统总线通过它与许多不同的硬件进行交互。 ACPI 可以通过在 [.filename]#/boot/loader.conf# 中配置或在 man:loader[8] 提示符处配置 `hint.acpi.0.disabled="1"` 来禁用。 [NOTE] ==== ACPI 和 APM 不能共存, 相反, 它们应分开使用。 后加载的驱动如果发现系统中已经执行了其中的一个, 便会停止执行。 ==== ACPI 可以用来让系统进入休眠模式, 方法是使用 man:acpiconf[8] 的 `-s` 参数, 加上一个 `1-5` 的数字。 多数用户会希望使用 `1` 或 `3` (挂起到 RAM)。 而 `5` 则会让系统执行与下列命令效果类似的软关机: [source,shell] .... # halt -p .... 除此之外, 还有一些通过 man:sysctl[8] 提供的选项。 请参见联机手册 man:acpi[4] 和 man:acpiconf[8] 以获得更多信息。 [[ACPI-debug]] == 使用和调试 FreeBSD ACPI ACPI 是一种全新的发现设备、 管理电源使用、 以及提供过去由 BIOS 管理的访问不同硬件的标准化方法。 让 ACPI 在各种系统上都能正确使用的工作一直在进行, 但许多主板的 _ACPI 机器语言_ (AML) 字节代码中的 bug, FreeBSD 的内核中子系统设计的不完善, 以及 Intel(R) ACPI-CA 解释器中的 bug 仍然不时会出现。 这份文档期望能够帮助您协助 FreeBSD ACPI 的维护人员来找到您所观察到的问题的根源, 并通过调试找到其解决方法。 感谢您阅读这份文档, 我们也希望能够解决您的系统上的问题。 [[ACPI-submitdebug]] === 提交调试信息 [NOTE] ==== 在提交问题之前, 请确认您已经在运行最新的 BIOS 版本, 此外, 也包括嵌入式控制器的固件版本。 ==== 如果您希望提交一个问题, 请确保将下述信息发到 link:mailto:freebsd-acpi@FreeBSD.org[freebsd-acpi@FreeBSD.org]: * 问题行为的描述, 包括系统类型、型号,以及任何触发问题的相关信息。 另外, 请注意尽可能准确地描述这一问题是否对您是陌生的。 * 在 "boot -v" 之后得到的 man:dmesg[8] 输出, 以及任何在重现 bug 时出现的错误信息。 * 在禁用了 ACPI 之后的 "boot -v" 的 man:dmesg[8] 输出, 如果您发现禁用 ACPI 能够帮助消除问题。 * 来自 ``fsysctl hw.acpi``的输出。 这也是找到您的系统所提供的功能的一种好办法。 * 能够得到您的 _ACPI Source Language_ (ASL) 的 URL。 _不要_ 把 ASL 直接发到邮件列表中, 因为它们可能非常大。 为了得到 ASL 您可以运行这个命令: + [source,shell] .... # acpidump -dt > name-system.asl .... + (把 _name_ 改为您的登录名, 并把 _system_ 改为您的硬件制造商及其型号。 例如: [.filename]#njl-FooCo6000.asl#) 许多开发者也会订阅 {freebsd-current} 但还是请发到 {freebsd-acpi} 这样它会被更多人看到。 请耐心等待, 因为我们都有全职的其他工作。 如果您的 bug 不是显而易见的, 我们可能会要求您通过 man:send-pr[1] 来提交一个 PR。 在输入 PR 时,请将同样的信息包含进去。 这将帮助我们来追踪和解决问题。 不要在给 {freebsd-acpi} 写信之前发送 PR 因为我们把它当作已知文体的备忘录而不是报告机制。 您的问题很可能已经被其他人报告过了。 [[ACPI-background]] === 背景 ACPI 存在于采用 ia32 (x86)、 ia64 (安腾)、 以及 amd64 (AMD) 架构的所有现代计算机上。 完整的标准具有大量的各式功能, 包括 CPU 性能管理、 电源控制、 温度监控、 电池系统、 嵌入式控制器以及总线枚举。 绝大多数系统实现比完整标准的功能要少一些。 例如, 桌面系统通常只实现总线枚举部分, 而笔记本则通常支持降温和电源管理功能。 笔记本通常还提供休眠和唤醒支持, 并提供与此适应的复杂功能。 符合 ACPI 的系统中有许多组件。 BIOS 和芯片组制造商提供一些固定的表 (例如, FADT) 在存储器中, 以提供类似 APIC 映射 (用于 SMP)、 配置寄存器、 以及简单的配置值等等。 另外, 一个字节代码 (bytecode) 表 (__系统区别描述表__DSDT) 则提供了通过树状命名空间来指定设备及其功能的方法。 ACPI 驱动必须要处理固定表, 实现字节码解释器, 并修改驱动程序和内核, 以接受来自 ACPI 子系统的信息。 对于 FreeBSD, Intel(R) 提供了一个解释器 (ACPI-CA), 它在 Linux 和 NetBSD 也可以使用。 ACPI-CA 源代码可以在 [.filename]#src/sys/contrib/dev/acpica# 找到。 用于在 FreeBSD 中允许 ACPI-CA 正确运转的代码则在 [.filename]#src/sys/dev/acpica/Osd#。 最后, 用于实现 ACPI 设备的驱动可以在 [.filename]#src/sys/dev/acpica# 找到。 [[ACPI-comprob]] === 常见问题 要让 ACPI 正常工作, 它的每一部分都必须工作正常。 下面是一些常见的问题, 按照出新的频繁程度排序, 并给出了一些绕过或修正它们的方法。 ==== 鼠标问题 某些时候, 唤醒操作会导致鼠标不再正常工作。 已知的绕过这一问题的方法, 是在 [.filename]#/boot/loader.conf# 文件中添加 `hint.psm.0.flags="0x3000"` 设置。 如果这样做不能解决问题, 请考虑按前面介绍的方法提交问题报告。 ==== 休眠/唤醒 ACPI 提供了三种休眠到 RAM (STR) 的状态, `S1`-`S3`, 以及一个休眠到磁盘的状态 (`STD`), 称作 `S4`。 `S5` 是 "软关机" 同时也是系统接好电源但没有开机时的正常状态。 `S4` 实际上可以用两种不同的方法来实现。 ``S4``BIOS 是一种由 BIOS 辅助的挂起到磁盘方法, 而 ``S4``OS 则是完全由操作系统实现的。 可以使用 `sysctl hw.acpi` 来查看与休眠有关的项目。 这里是我的 Thinkpad 上得到的结果。 [source,shell] .... hw.acpi.supported_sleep_state: S3 S4 S5 hw.acpi.s4bios: 0 .... 这表示我可以使用 `acpiconf -s` 来测试 `S3`, ``S4``OS, 以及 `S5`。 如果 `s4bios` 是一 (`1`), 则可以使用 ``S4``BIOS 来代替 ``S4``OS。 当测试休眠/唤醒时, 从 `S1` 开始, 如果它被支持的话。 这个状态是最可能正常工作的状态, 因为它不需要太多的驱动支持。 没有人实现 `S2` 但如果您有它的支持, 则应该和 `S1` 类似。 下一件值得尝试的是 `S3`。 这是最深的 STR 状态, 并需要一系列驱动的支持才能够正常地重新初始化您的硬件。 如果您在唤醒系统时遇到问题, 请不要吝惜发邮件给 {freebsd-acpi} 邮件列表, 尽管不要指望问题一定会很快解决, 因为有许多驱动程序/硬件需要进行更多的测试和改进。 休眠和唤醒操作最常见的问题是某些设备驱动程序不会保存、 恢复或正确地重新初始化其固件、 寄存器或设备内存。 尝试调试这些问题时, 首先可以尝试: [source,shell] .... # sysctl debug.bootverbose=1 # sysctl debug.acpi.suspend_bounce=1 # acpiconf -s 3 .... 这个测试会模拟休眠和恢复过程而不真的进入 `S3` 状态。 有时, 您会用这种方式很容易地抓住问题 (例如, 丢失固件状态、 设备 watchdog 超时, 以及一直重试等)。 注意系统不会真的进入 `S3` 状态, 这意味着这些设备可能不会掉电, 而许多设备在完全不提供休眠和恢复方法时仍可正常工作, 而不像使用真的 `S3` 状态那样。 较难的情况则需要更多的硬件, 例如用于串口控制台的串口/线, 以及用于 man:dcons[4] 的火线口/线和内核调试技能。 为了帮助隔离问题, 请在内核中删去尽可能多的驱动。 如果这样做能够解决问题, 请尝试逐个加载驱动直到问题再次出现。 通常预编译的驱动程序如 [.filename]#nvidia.ko#、 X11 显示驱动, 以及 USB 的问题最多, 而以太网卡的驱动则通常工作的很好。 如果您能够通过加载和卸载驱动使系统正常工作, 您可以通过将适当的命令放到 [.filename]#/etc/rc.suspend# 和 [.filename]#/etc/rc.resume# 来将这个过程自动化。 在这两个文件中有一个注释掉的卸载和加载驱动程序的例子供您参考。 另外您还可以将 `hw.acpi.reset_video` 设置为零 (`0`), 如果您的显示在唤醒之后显得很混乱。 此外您还可以尝试更长或更短的 `hw.acpi.sleep_delay` 值看看是否有所助益。 另一件值得一试的事情是使用一个比较新的包含 ACPI 支持的 Linux 发行版来试试看他们的 休眠/唤醒 功能是否在同样的硬件上能够正常工作。 如果在 Linux 下正常, 则很可能是 FreeBSD 驱动程序的问题, 而隔离问题并找到存在问题的驱动有助于解决它。 需要注意的是 ACPI 的维护人员通常并不维护其他驱动 (例如 声音、 ATA, 等等) 因此如果最终发现是驱动的问题最好还是发到 {freebsd-current} 邮件列表并发给驱动程序的维护者。 如果您喜欢冒险, 则可以加一些 man:printf[3] 到有问题的驱动中, 以找到它的恢复功能发生问题的位置。 最后, 试试看禁用 ACPI 并代之以启用 APM。 如果 休眠/唤醒 能够在 APM 下正常工作, 使用 APM 可能会更好, 特别是对于较老的硬件 (2000年以前)。 硬件制造商需要一些时间来让老硬件的 ACPI 工作正常, 而 ACPI 的问题十之八九是 BIOS 中的毛病引发的。 ==== 系统停止响应 (暂时或永久性地) 绝大多数系统停止响应是由于未能及时响应中断或发生了中断风暴导致的。 芯片组有很多问题最终会溯源到 BIOS 如何在引导系统之前配置中断, APIC (MADT) 表的正确性, 以及 _系统控制中断_ (SCI) 如何路由。 通过察看 `vmstat -i` 的输出中包括 `acpi0` 的那一行可以区分中断风暴和未能及时响应中断。 如果每秒计数器增长的速度多于一两个, 则您是遇到了中断风暴。 如果系统停止了响应, 您可以尝试停止内核并进入 DDB (在控制台上按 kbd:[CTRL+ALT+ESC]) 并输入 `show interrupts`。 处理中断问题的救命稻草是尝试禁用 APIC 支持, 这是通过在 [.filename]#loader.conf# 中加入 `hint.apic.0.disabled="1"` 完成的。 ==== 崩溃 崩溃对于 ACPI 是比较罕见的情况, 如果发现, 我们将会非常重视并很快修复它。 您要做的第一件事是设法隔离出能够重现崩溃 (如果可能的话) 的操作并获取一份调用堆栈。 请启用 `options DDB` 并设置串行控制台 (参见 crossref:serialcomms[serialconsole-ddb,通过串口线进入DDB调试器]) 或配置一个 man:dump[8] 分区。 您将在 DDB 中通过 `tr` 得到调用堆栈。 如果您只能用手抄的方法记录它, 一定要记下头五 (5) 行和最后五 (5) 行。 然后, 尝试通过在启动时禁用 ACPI 来隔离故障。 如果这样做能够正常工作, 请通过设置 `debug.acpi.disable` 的那组数值来隔离具体是哪个 ACPI 子系统的问题。 请参见 man:acpi[4] 联机手册中给出的那些例子。 ==== 系统在休眠或关机之后又启动了 首先请尝试在 man:loader.conf[5] 中设置 ``hw.acpi.disable_on_poweroff=``"0"。 这将让 ACPI 不再在关机过程中禁用一些事件。 基于同样的原因, 一些系统需要把这个值设置为 "1" (这是默认值)。 这通常能够修复在休眠或关机时立即再次启动的问题。 ==== 其他问题 如果您有 ACPI 的其他问题 (同 docking station 协同工作、 无法检测设备, 等等), 请把描述发给邮件列表; 不过, 这些问题也有可能和 ACPI 中尚未完成的部分有关, 它们可能需要时间才能被实现。 请给点耐心, 并准备测试我们可能会发给您的补丁。 [[ACPI-aslanddump]] === ASL、`acpidump`, 以及 IASL 最常见的问题是 BIOS 制造商提供的不正确 (甚至完全错误的!) 字节代码。 这通常会以类似下面这样的内核消息显示在控制台上: [source,shell] .... ACPI-1287: *** Error: Method execution failed [\\_SB_.PCI0.LPC0.FIGD._STA] \\ (Node 0xc3f6d160), AE_NOT_FOUND .... 许多时候, 您可以通过将 BIOS 升级到最新版本来解决此类问题。 绝大多数控制台消息是无害的, 但如果您有其他问题例如电池工作不正常, 则从 AML 开始查找问题将是一条捷径。 字节代码, 或常说的 AML, 是从一种叫做 ASL 的语言写成的源代码进行编译得到的结果。 AML 一般存放在 DSDT 表中。 要得到您系统的 ASL, 需要使用 man:acpidump[8]。 需要同时指定 `-t` (显示固定标的内容) 和 `-d` (将 AML 反编译成 ASL) 两个选项。 请参见 <> 一节了解如何使用它。 最方便的初步检查是尝试重新编译 ASL 来看看是否有错误。 通常可以忽略这一过程中产生的警告, 但错误一般就都是 bug, 它们通常就是导致 ACPI 无法正常工作的原因。 要重新编译您的 ASL, 可以使用下面的命令: [source,shell] .... # iasl your.asl .... [[ACPI-fixasl]] === 修复 ASL 我们的长期目标是让每一个人都能够在不需要任何用户干预的情况下使用 ACPI。 然而, 目前我们仍然在开发绕过 BIOS 制造商常见错误的方法。 Microsoft(R) 解释器 ([.filename]#acpi.sys# 和 [.filename]#acpiec.sys#) 并不会严格地检查是否遵守了标准, 因此许多只在 Windows(R) 中测试 ACPI 的 BIOS 制造商很可能永远不会修正他们的 ASL。 我们希望不断地找出并用文档说明 Microsoft(R) 的解释器到底允许那些不标准的行为, 并在 FreeBSD 进行对应的修改使它能够正常工作而不需要用户修正 ASL。 作为一项临时缓解问题的方法, 并帮助我们确认其行为, 您可以手工修正 ASL。 如果这样能够解决问题, 请把新旧 ASL 的 man:diff[1] 发给我们, 这样我们就有可能绕过 ACPI-CA 中的错误行为, 从而不再需要您来手工修正。 下面是一些常见的错误信息, 它们的原因, 以及如何修正。 ==== _OS dependencies (_OS 依赖) 某些 AML 假定世界是由不同版本的 Windows(R) 组成的。 您可以让 FreeBSD 声称自己是任意 OS 来看一看是否能够修正问题。 比较简单的办法是设置 `hw.acpi.osname`="Windows 2001" 到 [.filename]#/boot/loader.conf# 中, 或使用您在 ASL 中找到的其他字符串。 ==== Missing Return statements (缺少返回语句) 一些方法可能没按照标准要求的那样显式地返回值。 尽管 ACPI-CA 无法处理它, 但 FreeBSD 提供了一个绕过它并允许其暗含地返回值的方法。 您也可以增加一个显式的 Return 语句, 如果您知道那里需要返回一个值的话。 要强制 `iasl` 编译 ASL, 需要使用 `-f` 标志。 ==== 替换默认的 AML 在定制 [.filename]#your.asl# 之后, 您可以通过下面的命令编译它: [source,shell] .... # iasl your.asl .... 可以使用 `-f` 标志来强制创建 AML, 即使在编译过程中发生了错误。 请注意某些错误 (例如, 缺少 Return 语句) 会自动被解释器忽略掉。 [.filename]#DSDT.aml# 是 `iasl` 命令的默认输出文件名。 可以加载它来取代您 BIOS 中存在问题的副本 (它仍然存在于闪存中), 其方法是按下面的说明编辑 [.filename]#/boot/loader.conf#: [.programlisting] .... acpi_dsdt_load="YES" acpi_dsdt_name="/boot/DSDT.aml" .... 一定要把您的 [.filename]#DSDT.aml# 复制到 [.filename]#/boot# 目录中。 [[ACPI-debugoutput]] === 从 ACPI 中获取调试输出信息 ACPI 驱动程序提供了非常灵活的调试机制。 这允许您指定一组子系统, 以及所需要的详细信息。 需要调试的子系统可以按 "layers(层)" 来指定, 并分为 ACPI-CA 组件 (ACPI_ALL_COMPONENTS) 和 ACPI 硬件支持 (ACPI_ALL_DRIVERS)。 调试输出的详细程度可以通过 "level(详细度)" 来指定, 其范围是 ACPI_LV_ERROR (只报告错误) 到 ACPI_LV_VERBOSE (显示所有)。 "level" 是一个位掩码因此可以一次设置多个选项, 中间用空格分开。 实际使用中您应该考虑使用串行控制台来记录输出, 如果它太长以至于冲掉了控制台消息缓冲的话。 不同的层和输出详细度的完整列表可以在 man:acpi[4] 联机手册中找到。 调试输出默认并不开启。 要起用它, 您需要在内核设置中添加 `options ACPI_DEBUG`, 如果您的内核中编入了 ACPI 的话。 您还可以在 [.filename]#/etc/make.conf# 中加入 `ACPI_DEBUG=1` 来在全局起用它。 如果它只是模块, 您可以用下面的方法来重新编译 [.filename]#acpi.ko#: [source,shell] .... # cd /sys/modules/acpi/acpi && make clean && make ACPI_DEBUG=1 .... 安装 [.filename]#acpi.ko# 到 [.filename]#/boot/kernel# and add your 并把所需的详细度和层在 [.filename]#loader.conf# 中指定。 这个例子将启用所有 ACPI-CA 组件以及所有 ACPI 硬件驱动 (CPU、 LID, 等等) 的消息。 只输出错误信息, 也就是最低的详细度。 [.programlisting] .... debug.acpi.layer="ACPI_ALL_COMPONENTS ACPI_ALL_DRIVERS" debug.acpi.level="ACPI_LV_ERROR" .... 如果您需要的信息是由某个特定的事件触发的 (比如说, 休眠之后的唤醒), 您可以不修改 [.filename]#loader.conf# 而转而使用 `sysctl` 来在启动和为那个事件准备系统之后再指定层和详细度。 这些 `sysctl` 的名字和 [.filename]#loader.conf# 中的一致。 [[ACPI-References]] === 参考文献 关于 ACPI 的更多信息可以从下面这些地方找到: * The {freebsd-acpi} * ACPI 邮件列表存档 http://lists.freebsd.org/pipermail/freebsd-acpi/[http://lists.freebsd.org/pipermail/freebsd-acpi/] * 旧的 ACPI 邮件列表存档 http://home.jp.FreeBSD.org/mail-list/acpi-jp/[http://home.jp.FreeBSD.org/mail-list/acpi-jp/] -* The ACPI 2.0 标准 http://acpi.info/spec.htm[http://acpi.info/spec.htm] +* The https://uefi.org/specifications#ACPI[ACPI 标准] * FreeBSD 手册页: man:acpi[4], man:acpi_thermal[4], man:acpidump[8], man:iasl[8], man:acpidb[8] * http://www.cpqlinux.com/acpi-howto.html#fix_broken_dsdt[DSDT 调试资源]. (使用 Compaq 作为例子但通常情况下都很有用。) diff --git a/documentation/content/zh-tw/books/handbook/config/_index.adoc b/documentation/content/zh-tw/books/handbook/config/_index.adoc index 6a1cc4ef4f..2a3e0912ae 100644 --- a/documentation/content/zh-tw/books/handbook/config/_index.adoc +++ b/documentation/content/zh-tw/books/handbook/config/_index.adoc @@ -1,1563 +1,1563 @@ --- title: 章 11. 設定與調校 part: 部 III. 系統管理 prev: books/handbook/partiii next: books/handbook/boot showBookMenu: true weight: 15 path: "/books/handbook/" --- [[config-tuning]] = 設定與調校 :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 11 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/config/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[config-synopsis]] == 概述 在 FreeBSD 使用過程中,相當重要的環節之一就是如何正確設定系統。 本章著重於介紹 FreeBSD 的設定流程,包括一些可以調整 FreeBSD 效能的參數設定。 讀完這章,您將了解: * [.filename]#rc.conf# 設定的基礎概念及 [.filename]#/usr/local/etc/rc.d# 啟動 Script。 * 如何設定並測試網路卡。 * 如何在網路裝置上設定虛擬主機。 * 如何使用在 [.filename]#/etc# 中的各種設定檔。 * 如何使用 man:sysctl[8] 變數調校 FreeBSD。 * 如何調校磁碟效能及修改核心限制。 在開始閱讀這章之前,您需要: * 了解 UNIX(TM) 及 FreeBSD 基礎 (crossref:basics[basics,FreeBSD 基礎])。 * 熟悉核心設定與編譯的基礎 (crossref:kernelconfig[kernelconfig,設定 FreeBSD 核心])。 [[configtuning-starting-services]] == 啟動服務 許多使用者會使用 Port 套件集安裝第三方軟體到 FreeBSD 且需要安裝服務在系統初始化時可啟動該軟體。服務,例如 package:mail/postfix[] 或 package:www/apache22[] 僅只是在眾多需要在系統初始化時啟動的軟體之中的兩個。本章節將說明可用來啟動第三方軟體的程序。 在 FreeBSD 大多數內建的服務,例如 man:cron[8] 也是透過系統啟動 Script 來執行。 === 延伸應用程式設定 現在 FreeBSD 會引用 [.filename]#rc.d#,設定應用程式啟動變的更簡單且提供更多的功能。使用於 <> 所提到的關鍵字,可以設定應用程式在其他特定服務之後啟動且可以透過 [.filename]#/etc/rc.conf# 來傳遞額外的旗標來取代寫死在啟動 Script 中的旗標。一個基本的 Script 可能會如下例所示: [.programlisting] .... #!/bin/sh # # PROVIDE: utility # REQUIRE: DAEMON # KEYWORD: shutdown . /etc/rc.subr name=utility rcvar=utility_enable command="/usr/local/sbin/utility" load_rc_config $name # # DO NOT CHANGE THESE DEFAULT VALUES HERE # SET THEM IN THE /etc/rc.conf FILE # utility_enable=${utility_enable-"NO"} pidfile=${utility_pidfile-"/var/run/utility.pid"} run_rc_command "$1" .... 這個 Script 會確保要執行的 `utility` 會在虛構的服務 `DAEMON` 之後啟動,也同時提供設定與追蹤程序 ID (Process ID, PID) 的方法。 接著此應用程式便可將下行放到 [.filename]#/etc/rc.conf# 中: [.programlisting] .... utility_enable="YES" .... 使用這種方式可以簡單的處理指令列參數、引用 [.filename]#/etc/rc.subr# 所提供的預設函數、與 man:rcorder[8] 相容並可在 [.filename]#rc.conf# 簡單的設定。 === 使用服務來啟動其他服務 其他的服務可以使用 man:inetd[8] 來啟動,在 crossref:network-servers[network-inetd,inetd 超級伺服器] 有如何使用 man:inetd[8] 以及其設定的深入說明。 在某些情況更適合使用 man:cron[8] 來啟動系統服務,由於 man:cron[8] 會使用 man:crontab[5] 的擁有者來執行這些程序,所以這個方法有不少優點,這讓一般的使用者也可以啟動與維護自己的應用程式。 man:cron[8] 的 `@reboot` 功能,可用來替代指定詳細的時間,而該工作會在系統初始化時執行 man:cron[8] 後執行。 [[configtuning-cron]] == 設定 man:cron[8] 在 FreeBSD 其中最有用的其中一項工具便是 cron,這個工具會在背景執行並且定期檢查 [.filename]#/etc/crontab# 是否有要執行的工作然後搜尋 [.filename]#/var/cron/tabs# 是否有自訂的 crontab 檔案,這些檔案用來安排要讓 cron 在指定的時間執行的工作,crontab 中的每一個項目定義了一個要執行的工作,又稱作 _cron job_。 這裡使用了兩種類型的設定檔:其一是系統 crontab,系統 crontab 不應該被修改,其二為使用者 crontab,使用者 crontab 可以依需要建立與編輯。這兩種檔案的格式在 man:crontab[5] 有說明。系統 crontab [.filename]#/etc/crontab# 的格式含有在使用者 crontab 所沒有的 `who` 欄位,在系統 crontab,cron 會依據該欄位所指定的使用者來執行指令,而在使用者 crontab,會以建立 crontab 的使用者來執行指令。 使用者 crontab 讓個別使用者可以安排自己的工作,`root` 使用者也可有自己的使用者 [.filename]#crontab# 來安排不在系統 [.filename]#crontab# 中的工作。 以下為系統 crontab [.filename]#/etc/crontab# 的範例項目: [.programlisting] .... # /etc/crontab - root's crontab for FreeBSD # # $FreeBSD: head/zh_TW.UTF-8/books/handbook/book.xml 53653 2019-12-03 17:05:41Z rcyu $ ## <.> SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin <.> # #minute hour mday month wday who command <.> # */5 * * * * root /usr/libexec/atrun <.> .... <.> 以 `#` 字元為首的行代表註解。可在檔案中放置註解提醒要執行什麼動作及為何要執行。註解不可與指令同行,否則會被當做指令的一部份,註解必須在新的一行,空白行則會被忽略掉。 <.> 等號 (`=`) 字元用來定義任何環境設定。在這個例子當中,使用了等號來定義 `SHELL` 及 `PATH`。若 `SHELL` 被省略,cron 則會使用預設的 Bourne shell。若 `PATH` 被省略,則必須指定指令或 Script 的完整路徑才能執行。 <.> 此行定義了在系統 crontab 會使用到的七個欄位:`minute`, `hour`, `mday`, `month`, `wday`, `who` 以及 `command`。`minute` 欄位是指定指令要執行的時間中的分,`hour` 指定指令要執行的時,`mday` 是月裡面的日,`month` 是月,以及 `wday` 是週裡面的日。這些欄位必須數值代表 24 小時制的時間或 `\*` 來代表所有可能的值。`who` 這個欄位只有系統 crontab 才有,用來指定要用那一個使用者來執行指令。最後一個欄位則是要執行的指令。 <.> 這個項目定義了該工作所使用的數值,`\*/5` 後接著數個 `*` 字元指的是每個月的每一週的每一日的每個小時的每 5 分鐘會使用 `root` 執行 `/usr/libexec/atrun`。指令可含任何數量的參數,但若指令要使用多行則需以反斜線 "\" 連線字元換行。 [[configtuning-installcrontab]] === 建立使用者的 Crontab 要建立一個使用者 crontab 可使用編輯模式執行 `crontab`: [source,shell] .... % crontab -e .... 這樣會使用預設的文字編輯器來開啟使用者的 crontab,使用者第一次執行這個指令會開啟一個空的檔案,使用者建立 crontab 之後這個指令則會開啟已建立的 crontab 供編輯。 加入這些行到 crontab 檔的最上方來設定環境變數以及備忘在 crontab 中欄位的意思非常有用: [.programlisting] .... SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin # Order of crontab fields # minute hour mday month wday command .... 然後每一個要執行的指令或 Script 加入一行,指定要執行指令的時間。這個例子會每天在下午 2 點執行指定的自訂 Bourne shell script,由於沒有在 `PATH` 指定 Script 的路徑,所以必須給予完整的 Script 路徑: [.programlisting] .... 0 14 * * * /usr/home/dru/bin/mycustomscript.sh .... [TIP] ==== 在使用自訂的 Script 之前,請先確定該 Script 可以執行並且使用 cron 在有限的環境變數下測試。要複製一個用來執行上述 cron 項目的環境可以使用: [.programlisting] .... env -i SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin HOME=/home/dru LOGNAME=dru /usr/home/dru/bin/mycustomscript.sh .... 在 man:crontab[5] 有討論 cron 使用的環境變數,若 Script 中含有任何會使用萬用字元刪除檔案的指令,那麼檢查 Script 可正常在 cron 的環境運作非常重要。 ==== 編輯完成 crontab 之後儲存檔案,編輯完的 crontab 會被自動安裝且 cron 會讀取該 crontab 並在其指定的時指執行其 cron job。要列出 crontab 中有那一些 cron job 可以使用此指令: [source,shell] .... % crontab -l 0 14 * * * /usr/home/dru/bin/mycustomscript.sh .... 要移除使用在使用者 crontab 中的 cron job 可: [source,shell] .... % crontab -r remove crontab for dru? y .... [[configtuning-rcd]] == 管理 FreeBSD 中的服務 FreeBSD 在系統初始化時使用 man:rc[8] 系統的啟動 Script。列於 [.filename]#/etc/rc.d# 的 Script 提供了基本的服務可使用 man:service[8] 加上 `start`, `stop` 以及 `restart` 選項來控制。例如,使用以下指令可以重新啟動 man:sshd[8]: [source,shell] .... # service sshd restart .... 這個程序可以用來在執行中的系統上啟動服務,而在 man:rc.conf[5] 中有指定的服務則會在開機時自動啟動。例如,要在系統啟動時開啟 man:natd[8],可入下行到 [.filename]#/etc/rc.conf#: [.programlisting] .... natd_enable="YES" .... 若 `natd_enable="NO"` 行已存在,則將 `NO` 更改為 `YES`,在下次開機時 man:rc[8] script 便會自動載入任何相依的服務,詳細如下所述。 由於 man:rc[8] 系統主要用於在系統開機與關機時啟動與停止服務,只有當有服務的變數設定在 [.filename]#/etc/rc.conf# 時 `start`, `stop` 以及 `restart` 才會有作用。例如 `sshd restart` 只會在 [.filename]#/etc/rc.conf# 中的 `sshd_enable` 設為 `YES` 時才會運作,若要不透過 [.filename]#/etc/rc.conf# 的設定來 `start`, `stop` 或 `restart` 一個服務則需要在指令前加上 "one",例如要不透過目前在 [.filename]#/etc/rc.conf# 的設定重新啟動 man:sshd[8] 可執行以下指令: [source,shell] .... # service sshd onerestart .... 要檢查一個服務是否有在 [.filename]#/etc/rc.conf# 開啟,可執行服務的 man:rc[8] Script 加上 `rcvar`。這個例子會檢查 man:sshd[8] 是否在 [.filename]#/etc/rc.conf# 已經開啟: [source,shell] .... # service sshd rcvar # sshd # sshd_enable="YES" # (default: "") .... [NOTE] ==== 行 `# sshd` 的輸出來自上述指令,而非 `root` console。 ==== 要判斷是一個服務是否正在執行,可使用 `status`,例如要確認 man:sshd[8] 是否正常在執行: [source,shell] .... # service sshd status sshd is running as pid 433. .... 在某些情況,也可以 `reload` 一個服務。這個動作會嘗試發送一個信號給指定的服務,強制服務重新載入其設定檔,在大多數的情況下,發送給服務的信號是 `SIGHUP`。並不是每個服務都有支援此功能。 man:rc[8] 系統會用在網路服務及也應用在大多數的系統初化 。例如執行 [.filename]#/etc/rc.d/bgfsck# Script 會列印出以下訊息: [source,shell] .... Starting background file system checks in 60 seconds. .... 這個 Script 用來在背景做檔案系統檢查,只有在系統初始化時要執行。 許多系統服務會相依其他服務來運作,例如 man:yp[8] 及其他以 RPC 為基礎的服務在 man:rpcbind[8] 服務啟動前可能會啟動失敗。要解決這種問題,就必須在啟動 Script 上方的註解中加入相依及其他 meta-data。在系統初始化時會用 man:rcorder[8] 程式分析這些註解來決定要以什麼順序來執行系統服務以滿足相依。 因 man:rc.subr[8] 的需要,以下的關鍵字必須加入到所有的啟動 Script 方可 "enable" 啟動 Script: * `PROVIDE`: 設定此檔案所提供的服務。 以下關鍵字可能會在每個啟動 Script 的上方引用,雖然非必要,但是對於 man:rcorder[8] 是非常有用的提示: * `REQUIRE`: 列出此服務需要引用的服務。有使用此關鍵字的 Script 會在指定服務啟動 _之後_ 才執行。 * `BEFORE`: 列出相依此服務的服務。有使用此關鍵字的 Script 會在指定的服務啟動 _之前_ 執行。 透過仔細的設定每個啟動 Script 的這些關鍵字,管理者便可對 Script 的啟動順序進行微調,而不需使用到其他 UNIX(TM) 作業系統所使用的 "runlevels"。 額外的資訊可在 man:rc[8] 以及 man:rc.subr[8] 中找到。請參考 extref:{rc-scripting}[此文章] 來取得如何建立自訂 man:rc[8] Script 的操作說明。 [[configtuning-core-configuration]] === 管理系統特定的設定 系統設定資訊的主要位於 [.filename]#/etc/rc.conf#,這個檔案的設定資訊範圍非常廣且會在系統啟動時讀取來設定系統,它也提供設定資訊給 [.filename]#rc*# 檔案使用。 在 [.filename]#/etc/rc.conf# 中的設定項目會覆蓋在 [.filename]#/etc/defaults/rc.conf# 的預設設定,不應直接編輯該檔案中的預設設定,所有系統特定的設定應到 [.filename]#/etc/rc.conf# 所修改。 在叢集應用時要將系統特定的設定與各站特定的設定分開,藉此減少管理成本有好幾種方法,建議的方法是將系統特定的設定放置在 [.filename]#/etc/rc.conf.local#,例如以下將要套用到所有系統的設定項目放在 [.filename]#/etc/rc.conf#: [.programlisting] .... sshd_enable="YES" keyrate="fast" defaultrouter="10.1.1.254" .... 而只套用到此系統的設定放在 [.filename]#/etc/rc.conf.local#: [.programlisting] .... hostname="node1.example.org" ifconfig_fxp0="inet 10.1.1.1/8" .... 使用應用程式如 rsync 或 puppet 將 [.filename]#/etc/rc.conf# 散布到每個系統,而在各系統保留自己的 [.filename]#/etc/rc.conf.local#。 升級系統並不會覆寫 [.filename]#/etc/rc.conf#,所以系統設定資訊不會因此遺失。 [TIP] ==== [.filename]#/etc/rc.conf# 以及 [.filename]#/etc/rc.conf.local# 兩個檔案都會使用 man:sh[1] 解析,這讓系統操作者能夠建立較複雜的設定方案。請參考 man:rc.conf[5] 來取得更多有關此主題的資訊。 ==== [[config-network-setup]] == 設定網路介面卡 對 FreeBSD 管理者來說加入與設定網路介面卡 (Network Interface Card, NIC) 會是一件常見的工作。 === 找到正確的驅動程式 首先,要先確定 NIC 的型號及其使用的晶片。FreeBSD 支援各種 NIC,可檢查該 FreeBSD 發佈版本的硬體相容性清單來查看是否有支援該 NIC。 若有支援該 NIC,接著要確定該 NIC 所要需要的 FreeBSD 驅動程式名稱。請參考 [.filename]#/usr/src/sys/conf/NOTES# 及 [.filename]#/usr/src/sys/arch/conf/NOTES# 來取得 NIC 驅動程式清單及其支援的晶片組相關資訊。當有疑問是,請閱讀該驅動程式的操作手冊,會有提供更多有關支援硬體及該驅動程式已知問題的資訊。 [.filename]#GENERIC# 核心已有內含常見 NIC 的驅動程式 ,意思是在開機時應該會偵測到 NIC。可以輸入 `more /var/run/dmesg.boot` 來檢視系統的開機訊息並使用空白鍵捲動文字。在此例中,兩個乙太網路 NIC 使用系統已有的 man:dc[4] 驅動程式: [source,shell] .... dc0: <82c169 PNIC 10/100BaseTX> port 0xa000-0xa0ff mem 0xd3800000-0xd38 000ff irq 15 at device 11.0 on pci0 miibus0: on dc0 bmtphy0: PHY 1 on miibus0 bmtphy0: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc0: Ethernet address: 00:a0:cc:da:da:da dc0: [ITHREAD] dc1: <82c169 PNIC 10/100BaseTX> port 0x9800-0x98ff mem 0xd3000000-0xd30 000ff irq 11 at device 12.0 on pci0 miibus1: on dc1 bmtphy1: PHY 1 on miibus1 bmtphy1: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto dc1: Ethernet address: 00:a0:cc:da:da:db dc1: [ITHREAD] .... 若在 [.filename]#GENERIC# 中沒有該 NIC 的驅動程式,但有可用的驅動程式,那麼在設定及使用 NIC 前要先載入該驅動程式,有兩種方式可以完成這件事: * 最簡單的方式是使用 man:kldload[8] 載入 NIC 要使用的核心模組。要在開機時自動載入,可加入適當的設定到 [.filename]#/boot/loader.conf#。不是所有 NIC 驅動程式皆可當做模組使用。 * 或者,靜態編譯對 NIC 的支援到自訂核心,請參考 [.filename]#/usr/src/sys/conf/NOTES#, [.filename]#/usr/src/sys/arch/conf/NOTES# 及驅動程式的操作手冊來了解要在自訂核心設定檔中要加入那些設定。要取得更多有關重新編譯核心的資訊可參考 crossref:kernelconfig[kernelconfig,設定 FreeBSD 核心]。若在開機時有偵測到 NIC,就不需要再重新編譯核心。 [[config-network-ndis]] ==== 使用 Windows(TM)NDIS 驅動程式 很不幸的,仍有很多供應商並沒有提供它們驅動程式的技術文件給開源社群,因為這些文件有涉及商業機密。因此,FreeBSD 及其他作業系統的開發人員只剩下兩種方案可以選擇:透過長期與艱苦的過程做逆向工程來開發驅動程式或是使用現有供 Microsoft(TM) Windows(TM) 平台用的驅動程式 Binary。 FreeBSD 對 Network Driver Interface Specification (NDIS) 有提供 "原生" 的支援,這包含了 man:ndisgen[8] 可用來轉換 Windows(TM) XP 驅動程式成可在 FreeBSD 上使用的格式。由於 man:ndis[4] 驅動程式使用的是 Windows(TM) XP binary,所以只能在 i386(TM) 及 amd64 系統上執行。PCI, CardBus, PCMCIA 以及 USB 裝置也都有支援。 要使用 man:ndisgen[8] 需要三樣東西: . FreeBSD 核心原始碼。 . 一個 [.filename]#.SYS# 附檔名的 Windows(TM) XP 驅動程式 Binary。 . 一個 [.filename]#.INF# 附檔名的 Windows(TM) XP 驅動程式設定檔。 下載供指定 NIC 使用的 [.filename]#.SYS# 及 [.filename]#.INF# 檔。通常這些檔案可以在驅動程式 CD 或者供應商的網站上找到。以下範例會使用 [.filename]#W32DRIVER.SYS# 及 [.filename]#W32DRIVER.INF#。 驅動程式的位元寬度必須與 FreeBSD 的版本相符。例如 FreeBSD/i386 需要使用 Windows(TM) 32-bit 驅動程式,而 FreeBSD/amd64 則需要使用 Windows(TM) 64-bit 驅動程式。 下個步驟是編譯驅動程式 Binary 成可載入的核心模組。以 `root` 身份使用 man:ndisgen[8]: [source,shell] .... # ndisgen /path/to/W32DRIVER.INF /path/to/W32DRIVER.SYS .... 這個指令是互動式的,會提示輸入任何所需的額外資訊,新的核心模組會被產生在目前的目錄,使用 man:kldload[8] 來載入新的模組: [source,shell] .... # kldload ./W32DRIVER_SYS.ko .... 除了產生的核心模組之外,[.filename]#ndis.ko# 以及 [.filename]#if_ndis.ko# 也必須載入,會在任何有相依 man:ndis[4] 的模組被載入時一併自動載入。若沒有自動載入,則需使用以下指令手動載入: [source,shell] .... # kldload ndis # kldload if_ndis .... 第一個指令會載入 man:ndis[4] miniport 驅動程式包裝程式,而第二個指令會載入產生的 NIC 驅動程式。 檢查 man:dmesg[8] 查看是否有任何載入錯誤,若一切正常,輸出結果應會如下所示: [source,shell] .... ndis0: mem 0xf4100000-0xf4101fff irq 3 at device 8.0 on pci1 ndis0: NDIS API version: 5.0 ndis0: Ethernet address: 0a:b1:2c:d3:4e:f5 ndis0: 11b rates: 1Mbps 2Mbps 5.5Mbps 11Mbps ndis0: 11g rates: 6Mbps 9Mbps 12Mbps 18Mbps 36Mbps 48Mbps 54Mbps .... 到此之後 [.filename]#ndis0# 可以像任何其他 NIC 設定使用。 要設定系統於開機時載入 man:ndis[4] 模組,可複製產生的模組 [.filename]#W32DRIVER_SYS.ko# 到 [.filename]#/boot/modules#。然後加入下行到 [.filename]#/boot/loader.conf#: [.programlisting] .... W32DRIVER_SYS_load="YES" .... === 設定網路卡 載入正確的 NIC 驅動程式之後,接著需要設定介面卡,這個動作可能在安裝時已經使用 man:bsdinstall[8] 設定過了。 要查看 NIC 設定可輸入以下指令: [source,shell] .... % ifconfig dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da inet 192.168.1.3 netmask 0xffffff00 broadcast 192.168.1.255 media: Ethernet autoselect (100baseTX ) status: active dc1: flags=8802 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:db inet 10.0.0.1 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet 10baseT/UTP status: no carrier lo0: flags=8049 metric 0 mtu 16384 options=3 inet6 fe80::1%lo0 prefixlen 64 scopeid 0x4 inet6 ::1 prefixlen 128 inet 127.0.0.1 netmask 0xff000000 nd6 options=3 .... 在這個例子中列出了以下裝置: * [.filename]#dc0#: 第一個乙太網路介面。 * [.filename]#dc1#: 第二個乙太網路介面。 * [.filename]#lo0#: Loopback 裝置。 FreeBSD 會使用驅動程式名稱接著開機時所偵測到的介面卡順序來命名 NIC。例如 [.filename]#sis2# 是指在系統上使用 man:sis[4] 驅動程式的第三個 NIC。 在此例中,[.filename]#dc0# 已經上線並且執行中。主要的依據有: . `UP` 代表介面卡已設定好並且準備就緒。 . 介面卡有網際網路 (`inet`) 位址,`192.168.1.3`。 . 介面卡有一個有效的子網路遮罩 (`netmask`),其中 `0xffffff00` 等同於 `255.255.255.0`。 . 介面卡有一個有效的廣播位址,`192.168.1.255`。 . 介面卡 (`ether`) 的 MAC 位址是 `00:a0:cc:da:da:da`。 . 實體媒介選擇為自動選擇模式 (`media: Ethernet autoselect (100baseTX )`)。在本例中 [.filename]#dc1# 被設定使用 `10baseT/UTP` 媒介。要取得更多有關可用的驅動程式媒介類型請參考操作手冊。 . 連結的狀態 (`status`) 為使用中 (`active`),代表有偵測到載波信號 (Carrier Signal)。若 [.filename]#dc1# 所代表的介面卡未插入乙太網路線則狀態為 `status: no carrier` 是正常的。 若 man:ifconfig[8] 的輸出結果如下: [source,shell] .... dc0: flags=8843 metric 0 mtu 1500 options=80008 ether 00:a0:cc:da:da:da media: Ethernet autoselect (100baseTX ) status: active .... 則代表尚未設定介面卡。 介面卡必須以 `root` 來設定。NIC 的設定可在指令列執行 man:ifconfig[8] 來完成,但重新開機之後變會消失,除非將設定也加到 [.filename]#/etc/rc.conf#。若在 LAN 中有 DHCP 伺服器,則只需加入此行: [.programlisting] .... ifconfig_dc0="DHCP" .... 替換 _dc0_ 為該系統的正確值。 加入這行之後,接著依據 <> 指示操作。 [NOTE] ==== 若網路在安裝時已設定,可能會已經有 NIC 的設定項目。在加入任何設定前請再次檢查 [.filename]#/etc/rc.conf#。 ==== 在這個例中,沒有 DHCP 伺服器,必須手動設定 NIC。提每一個在系統上的 NIC 加入一行設定,如此例: [.programlisting] .... ifconfig_dc0="inet 192.168.1.3 netmask 255.255.255.0" ifconfig_dc1="inet 10.0.0.1 netmask 255.255.255.0 media 10baseT/UTP" .... 替換 [.filename]#dc0# 及 [.filename]#dc1# 以及 IP 位址資訊為系統的正確值。請參考驅動程式的操作手冊、man:ifconfig[8] 以及 man:rc.conf[5] 取得更多有關可用的選項及 [.filename]#/etc/rc.conf# 的語法。 若網路沒有使用 DNS,則編輯 [.filename]#/etc/hosts# 加入 LAN 上主機的名稱與 IP 位址。要取得更多資訊請參考 man:hosts[5] 及 [.filename]#/usr/shared/examples/etc/hosts#。 [NOTE] ==== 若沒有 DHCP 伺服器且需要存取網際網路,那麼需要手動設定預設閘道及名稱伺服器: [source,shell] .... # echo 'defaultrouter="your_default_router"' >> /etc/rc.conf # echo 'nameserver your_DNS_server' >> /etc/resolv.conf .... ==== [[config-network-testing]] === 測試與疑難排解 必要的變更儲存到 [.filename]#/etc/rc.conf# 之後,需要重新啟動系統來測試網路設定並檢查系統重新啟動是否沒有任何設定錯誤。或者使用這個指令將設定套用到網路系統: [source,shell] .... # service netif restart .... [NOTE] ==== 若預設的通訊閘已設定於 [.filename]#/etc/rc.conf# 也同樣要下這個指令: [source,shell] .... # service routing restart .... ==== 網路系統重新啟動後,便可接著測試 NIC。 ==== 測試乙太網路卡 要檢查乙太網路卡是否已正確設定可 man:ping[8] 介面卡自己,然後 man:ping[8] 其他於 LAN 上的主機: [source,shell] .... % ping -c5 192.168.1.3 PING 192.168.1.3 (192.168.1.3): 56 data bytes 64 bytes from 192.168.1.3: icmp_seq=0 ttl=64 time=0.082 ms 64 bytes from 192.168.1.3: icmp_seq=1 ttl=64 time=0.074 ms 64 bytes from 192.168.1.3: icmp_seq=2 ttl=64 time=0.076 ms 64 bytes from 192.168.1.3: icmp_seq=3 ttl=64 time=0.108 ms 64 bytes from 192.168.1.3: icmp_seq=4 ttl=64 time=0.076 ms --- 192.168.1.3 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.074/0.083/0.108/0.013 ms .... [source,shell] .... % ping -c5 192.168.1.2 PING 192.168.1.2 (192.168.1.2): 56 data bytes 64 bytes from 192.168.1.2: icmp_seq=0 ttl=64 time=0.726 ms 64 bytes from 192.168.1.2: icmp_seq=1 ttl=64 time=0.766 ms 64 bytes from 192.168.1.2: icmp_seq=2 ttl=64 time=0.700 ms 64 bytes from 192.168.1.2: icmp_seq=3 ttl=64 time=0.747 ms 64 bytes from 192.168.1.2: icmp_seq=4 ttl=64 time=0.704 ms --- 192.168.1.2 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 0.700/0.729/0.766/0.025 ms .... 要測試網路解析,可使用主機名稱來替代 IP 位址。若在網路上沒有 DNS 伺服器則必須先設定 [.filename]#/etc/hosts#,若主機尚未設定到 [.filename]#/etc/hosts# 中,則需編輯 [.filename]#/etc/hosts# 加入 LAN 上主機的名稱及 IP 位址,要取得更多資訊請參考 man:hosts[5] 及 [.filename]#/usr/shared/examples/etc/hosts#。 ==== 疑難排解 在排除硬體及軟體設定問題時,要先檢查幾件簡單的事。網路線插上了沒?網路的服務都正確設定了嗎?防火牆設定是否正確?FreeBSD 是否支援該 NIC?在回報問題之前,永遠要先檢查 Hardware Notes、更新 FreeBSD 到最新的 STABLE 版本、檢查郵遞論壇封存記錄以及上網查詢。 若介面卡可以運作,但是效能很差,請閱讀 man:tuning[7],同時也要檢查網路設定,因為不正確的網路設定會造成連線速度緩慢。 部份使用者會遇到一次或兩次 `device timeout` 的訊息,在對某些介面卡是正常的。若訊息持續發生或很煩的,請確認是否有與其他的裝置衝突,再次檢查網路線,或考慮使用其他介面卡。 要解決 `watchdog timeout` 錯誤,先檢查網路線。許多介面卡需要使用支援 Bus Mastering 的 PCI 插槽,在一些舊型的主機板,只會有一個 PCI 插槽支援,通常是插槽 0。檢查 NIC 以及主機板說明文件來確定是否為此問題。 若系統無法路由傳送封包到目標主機則會出現 `No route to host` 訊息,這可能是因為沒有指定預設的路由或未插上網路線。請檢查 `netstat -rn` 的輸出並確認有一個有效的路由可連線至主機,若沒有,請閱讀 crossref:advanced-networking[network-routing,通訊閘與路由]。 造成 `ping: sendto: Permission denied` 錯誤訊息的原因通常是防火牆設定錯誤。若在 FreeBSD 上有開啟防火牆,但卻未定義任何的規則,預設的原則是拒絕所有傳輸,即使是用 man:ping[8]。請參考 crossref:firewalls[firewalls,防火牆] 取得更多資訊。 有時介面卡的效能很差或低於平均值,在這種情況可嘗試設定媒介選擇模式由 `autoselect` 更改為正確的媒介選項,雖然這在大部份硬體可運作,但可能無法解決問題,同樣的,檢查所有網路設定並參考 man:tuning[7]。 [[configtuning-virtual-hosts]] == 虛擬主機 FreeBSD 最常見的用途之一就是虛擬網站代管,即以一台伺服器在網路上扮演多台伺服器,這可以透過指定多個網路位置到一個網路介面來做到。 一個網路介面會有一個 "真實 (Real)" 位址且可以有許多個 "別名 (Alias)" 位址。一般會在 [.filename]#/etc/rc.conf# 中放置別名項目來增加別名,如下例: [.programlisting] .... ifconfig_fxp0_alias0="inet xxx.xxx.xxx.xxx netmask xxx.xxx.xxx.xxx" .... 別名項目必須以 `alias__0__` 開頭,使用連續數字例如 `alias0`, `alias1` 以此類推,設定程序會在第一個遇到缺號的地方中止。 要注意別名網路遮罩 (Netmask) 的計算,使用的介面必須至少有一個正確的填寫網路遮罩的位址,而其他所有在此網路中的位址則必須使用全部 `1` 的網路遮罩,可用 `255.255.255.255` 或 `0xffffffff` 來表示。 舉例來說,有一個 [.filename]#fxp0# 介面連結到兩個網路:`10.1.1.0` 使用網路遮罩 `255.255.255.0` 以及 `202.0.75.16` 使用網路遮罩 `255.255.255.240`。而系統將要設定使用範圍 `10.1.1.1` 到 `10.1.1.5` 以及 `202.0.75.17` 到 `202.0.75.20`。在指定的網路範圍中只有第一個位址應使用真實的網路遮罩,其餘 (`10.1.1.2` 到 `10.1.1.5` 及 `202.0.75.18` 到 `202.0.75.20`) 則必須設定使用 `255.255.255.255` 的遮罩。 在此情境下正確設定網路介面的方式如下 [.filename]#/etc/rc.conf# 中的項目: [.programlisting] .... ifconfig_fxp0="inet 10.1.1.1 netmask 255.255.255.0" ifconfig_fxp0_alias0="inet 10.1.1.2 netmask 255.255.255.255" ifconfig_fxp0_alias1="inet 10.1.1.3 netmask 255.255.255.255" ifconfig_fxp0_alias2="inet 10.1.1.4 netmask 255.255.255.255" ifconfig_fxp0_alias3="inet 10.1.1.5 netmask 255.255.255.255" ifconfig_fxp0_alias4="inet 202.0.75.17 netmask 255.255.255.240" ifconfig_fxp0_alias5="inet 202.0.75.18 netmask 255.255.255.255" ifconfig_fxp0_alias6="inet 202.0.75.19 netmask 255.255.255.255" ifconfig_fxp0_alias7="inet 202.0.75.20 netmask 255.255.255.255" .... 有一種更簡單的方式可以表達這些設定,便是使用以空白分隔的 IP 位址清單。只有第一個位址會使用指定的子網路遮罩,其他的位址則會使用 `255.255.255.255` 的子網路遮罩。 [.programlisting] .... ifconfig_fxp0_aliases="inet 10.1.1.1-5/24 inet 202.0.75.17-20/28" .... [[configtuning-syslog]] == 設定系統日誌 產生與讀取系統日誌對系統管理來說是一件非常重要的事,在系統日誌中的資訊可以用來偵測硬體與軟體的問題,同樣也可以偵測應用程式與系統設定的錯誤。這些資訊在安全性稽查與事件回應也同樣扮演了重要的角色,大多數系統 Daemon 與應用程式都會產生日誌項目。 FreeBSD 提供了一個系統日誌程式 syslogd 用來管理日誌。預設 syslogd 會與系統開機時啟動。這可使用在 [.filename]#/etc/rc.conf# 中的變數 `syslogd_enable` 來控制。而且有數個應用程式參數可在 [.filename]#/etc/rc.conf# 使用 `syslogd_flags` 來設定。請參考 man:syslogd[8] 來取得更多可用參數的資訊。 此章節會介紹如何設定 FreeBSD 系統日誌程式來做本地與遠端日誌並且介紹如何執行日誌翻轉 (Log rotation) 與日誌管理。 === 設定本地日誌 設定檔 [.filename]#/etc/syslog.conf# 控制 syslogd 收到日誌項目時要做的事情,有數個參數可以用來控制接收到事件時的處理方式。_設施 (facility)_ 用來描述記錄產生訊息的子系統 (subsystem),如核心或者 Daemon,而 _層級 (level)_ 用來描述所發生的事件嚴重性。也可以依據應用程式所發出的訊息及產生日誌事件機器的主機名稱來決定後續處置的動作。 此設定檔中一行代表一個動作,每一行的格式皆為一個選擇器欄位 (Selector field) 接著一個動作欄位 (Action field)。選擇器欄位的格式為 _facility.level_ 可以用來比對來自 _facility_ 於層級 _level_ 或更高層的日誌訊息,也可以在層級前加入選擇性的比對旗標來更確切的指定記錄的內容。同樣一個動作可以使用多個選擇器欄位並使用分號 (`;`) 來分隔。用 `*` 可以比對任何東西。動作欄位可用來指定傳送日誌訊息的目標,如一個檔案或遠端日誌主機。範例為以下為 FreeBSD 預設的 [.filename]#syslog.conf#: [.programlisting] .... # $FreeBSD: head/zh_TW.UTF-8/books/handbook/book.xml 53653 2019-12-03 17:05:41Z rcyu $ # # Spaces ARE valid field separators in this file. However, # other *nix-like systems still insist on using tabs as field # separators. If you are sharing this file between systems, you # may want to use only tabs as field separators here. # Consult the syslog.conf(5) manpage. *.err;kern.warning;auth.notice;mail.crit /dev/console *.notice;authpriv.none;kern.debug;lpr.info;mail.crit;news.err /var/log/messages security.* /var/log/security auth.info;authpriv.info /var/log/auth.log mail.info /var/log/maillog lpr.info /var/log/lpd-errs ftp.info /var/log/xferlog cron.* /var/log/cron !-devd *.=debug /var/log/debug.log *.emerg * # uncomment this to log all writes to /dev/console to /var/log/console.log #console.info /var/log/console.log # uncomment this to enable logging of all log messages to /var/log/all.log # touch /var/log/all.log and chmod it to mode 600 before it will work #*.* /var/log/all.log # uncomment this to enable logging to a remote loghost named loghost #*.* @loghost # uncomment these if you're running inn # news.crit /var/log/news/news.crit # news.err /var/log/news/news.err # news.notice /var/log/news/news.notice # Uncomment this if you wish to see messages produced by devd # !devd # *.>=info !ppp *.* /var/log/ppp.log !* .... 在這個範例中: * 第 8 行會找出所有符合 `err` 或以上層級的訊息,還有 `kern.warning`, `auth.notice` 與 `mail.crit` 的訊息,然後將這些日誌訊息傳送到 Console ([.filename]#/dev/console#)。 * 第 12 行會找出所有符合 `mail` 設施中於 `info` 或以上層級的訊息,並記錄訊息至 [.filename]#/var/log/maillog#。 * 第 17 行使用了比較旗標 (`=`) 來只找出符合 `debug` 層級的訊息,並將訊息記錄至 [.filename]#/var/log/debug.log#。 * 第 33 行是指定程式的範例用法。這可以讓在該行以下的規則只對指定的程式生效。在此例中,只有由 ppp 產生的訊息會被記錄到 [.filename]#/var/log/ppp.log#。 所以可用層級從最嚴重到最不嚴重的順序為 `emerg`, `alert`, `crit`, `err`, `warning`, `notice`, `info` 以及 `debug`。 設施 (facility) 則無特定順序,可用的有 `auth`, `authpriv`, `console`, `cron`, `daemon`, `ftp`, `kern`, `lpr`, `mail`, `mark`, `news`, `security`, `syslog`, `user`, `uucp` 及 `local0` 到 `local7`。要注意在其他作業系統的設施可能會不同。 要記錄所有所有 `notice` 與以上層級的訊息到 [.filename]#/var/log/daemon.log# 可加入以下項目: [.programlisting] .... daemon.notice /var/log/daemon.log .... 要取得更多有關不同的層級與設施的資訊請參考 man:syslog[3] 及 man:syslogd[8]。要取得更多有關 [.filename]#/etc/syslog.conf#、語法以及更多進階用法範例的資訊請參考 man:syslog.conf[5]。 === 日誌管理與翻轉 日誌檔案會成長的非常快速,這會消耗磁碟空間並且會更難在日誌中找到有用的資訊,日誌管理便是為了嘗試減緩這種問題。在 FreeBSD 可以使用 newsyslog 來管理日誌檔案,這個內建的程式會定期翻轉 (Rotate) 與壓縮日誌檔案,並且可選擇性的建立遺失的日誌檔案並在日誌檔案被移動位置時通知程式。日誌檔案可能會由 syslogd 產生或由其他任何會產生日誌檔案的程式。newsyslog 正常會由 man:cron[8] 來執行,它並非一個系統 Daemon,預設會每個小時執行一次。 newsyslog 會讀取其設定檔 [.filename]#/etc/newsyslog.conf# 來決定其要採取的動作,每個要由 newsyslog 所管理的日誌檔案會在此設定檔中設定一行,每一行要說明檔案的擁有者、權限、何時要翻轉該檔案、選用的日誌翻轉旗標,如:壓縮,以及日誌翻轉時要通知的程式。以下為 FreeBSD 的預設設定: [.programlisting] .... # configuration file for newsyslog # $FreeBSD: head/zh_TW.UTF-8/books/handbook/book.xml 53653 2019-12-03 17:05:41Z rcyu $ # # Entries which do not specify the '/pid_file' field will cause the # syslogd process to be signalled when that log file is rotated. This # action is only appropriate for log files which are written to by the # syslogd process (ie, files listed in /etc/syslog.conf). If there # is no process which needs to be signalled when a given log file is # rotated, then the entry for that file should include the 'N' flag. # # The 'flags' field is one or more of the letters: BCDGJNUXZ or a '-'. # # Note: some sites will want to select more restrictive protections than the # defaults. In particular, it may be desirable to switch many of the 644 # entries to 640 or 600. For example, some sites will consider the # contents of maillog, messages, and lpd-errs to be confidential. In the # future, these defaults may change to more conservative ones. # # logfilename [owner:group] mode count size when flags [/pid_file] [sig_num] /var/log/all.log 600 7 * @T00 J /var/log/amd.log 644 7 100 * J /var/log/auth.log 600 7 100 @0101T JC /var/log/console.log 600 5 100 * J /var/log/cron 600 3 100 * JC /var/log/daily.log 640 7 * @T00 JN /var/log/debug.log 600 7 100 * JC /var/log/kerberos.log 600 7 100 * J /var/log/lpd-errs 644 7 100 * JC /var/log/maillog 640 7 * @T00 JC /var/log/messages 644 5 100 @0101T JC /var/log/monthly.log 640 12 * $M1D0 JN /var/log/pflog 600 3 100 * JB /var/run/pflogd.pid /var/log/ppp.log root:network 640 3 100 * JC /var/log/devd.log 644 3 100 * JC /var/log/security 600 10 100 * JC /var/log/sendmail.st 640 10 * 168 B /var/log/utx.log 644 3 * @01T05 B /var/log/weekly.log 640 5 1 $W6D0 JN /var/log/xferlog 600 7 100 * JC .... 每一行的開始為要翻轉的日誌名稱、接著是供翻轉與新建檔案使用的擁有者及群組 (選填)。`mode` 欄位可設定日誌檔案的權限,`count` 代表要保留多少個翻轉過的日誌檔案,而 `size` 與 `when` 欄位會告訴 newsyslog 何時要翻轉該檔案。日誌檔案會在當其檔案超過 `size` 欄位的大小或已超過 `when` 欄位指定的時間時翻轉,可使用星號 (`*`) 忽略該欄位。_flags_ 欄位可以給予進階的參數,例如:如何壓縮翻轉後檔案或建立遺失的日誌檔案。最後兩個欄位皆為選填,可指定程序的程序 ID (PID) 檔名稱以及檔案翻轉後要傳送給該程序的信號 (Signal) 編號。 要取的更多有關所有欄位、可用的旗標及如何指定翻轉時間,請參考 man:newsyslog.conf[5]。由於 newsyslog 是由 man:cron[8] 執行,因此無法比其在 man:cron[8] 中所排定的時間間距內更頻繁的執行翻轉檔案。 [[network-syslogd]] === 設定遠端日誌 Monitoring the log files of multiple hosts can become unwieldy as the number of systems increases. Configuring centralized logging can reduce some of the administrative burden of log file administration. In FreeBSD, centralized log file aggregation, merging, and rotation can be configured using syslogd and newsyslog. This section demonstrates an example configuration, where host `A`, named `logserv.example.com`, will collect logging information for the local network. Host `B`, named `logclient.example.com`, will be configured to pass logging information to the logging server. ==== 日誌伺服器設定 A log server is a system that has been configured to accept logging information from other hosts. Before configuring a log server, check the following: * If there is a firewall between the logging server and any logging clients, ensure that the firewall ruleset allows UDP port 514 for both the clients and the server. * The logging server and all client machines must have forward and reverse entries in the local DNS. If the network does not have a DNS server, create entries in each system's [.filename]#/etc/hosts#. Proper name resolution is required so that log entries are not rejected by the logging server. On the log server, edit [.filename]#/etc/syslog.conf# to specify the name of the client to receive log entries from, the logging facility to be used, and the name of the log to store the host's log entries. This example adds the hostname of `B`, logs all facilities, and stores the log entries in [.filename]#/var/log/logclient.log#. .日誌伺服器設定範例 [example] ==== [.programlisting] .... +logclient.example.com *.* /var/log/logclient.log .... ==== When adding multiple log clients, add a similar two-line entry for each client. More information about the available facilities may be found in man:syslog.conf[5]. Next, configure [.filename]#/etc/rc.conf#: [.programlisting] .... syslogd_enable="YES" syslogd_flags="-a logclient.example.com -v -v" .... The first entry starts syslogd at system boot. The second entry allows log entries from the specified client. The `-v -v` increases the verbosity of logged messages. This is useful for tweaking facilities as administrators are able to see what type of messages are being logged under each facility. Multiple `-a` options may be specified to allow logging from multiple clients. IP addresses and whole netblocks may also be specified. Refer to man:syslogd[8] for a full list of possible options. Finally, create the log file: [source,shell] .... # touch /var/log/logclient.log .... At this point, syslogd should be restarted and verified: [source,shell] .... # service syslogd restart # pgrep syslog .... If a PID is returned, the server restarted successfully, and client configuration can begin. If the server did not restart, consult [.filename]#/var/log/messages# for the error. ==== 日誌客戶端設定 A logging client sends log entries to a logging server on the network. The client also keeps a local copy of its own logs. Once a logging server has been configured, edit [.filename]#/etc/rc.conf# on the logging client: [.programlisting] .... syslogd_enable="YES" syslogd_flags="-s -v -v" .... The first entry enables syslogd on boot up. The second entry prevents logs from being accepted by this client from other hosts (`-s`) and increases the verbosity of logged messages. Next, define the logging server in the client's [.filename]#/etc/syslog.conf#. In this example, all logged facilities are sent to a remote system, denoted by the `@` symbol, with the specified hostname: [.programlisting] .... *.* @logserv.example.com .... After saving the edit, restart syslogd for the changes to take effect: [source,shell] .... # service syslogd restart .... To test that log messages are being sent across the network, use man:logger[1] on the client to send a message to syslogd: [source,shell] .... # logger "Test message from logclient" .... This message should now exist both in [.filename]#/var/log/messages# on the client and [.filename]#/var/log/logclient.log# on the log server. ==== 日誌伺服器除錯 If no messages are being received on the log server, the cause is most likely a network connectivity issue, a hostname resolution issue, or a typo in a configuration file. To isolate the cause, ensure that both the logging server and the logging client are able to `ping` each other using the hostname specified in their [.filename]#/etc/rc.conf#. If this fails, check the network cabling, the firewall ruleset, and the hostname entries in the DNS server or [.filename]#/etc/hosts# on both the logging server and clients. Repeat until the `ping` is successful from both hosts. If the `ping` succeeds on both hosts but log messages are still not being received, temporarily increase logging verbosity to narrow down the configuration issue. In the following example, [.filename]#/var/log/logclient.log# on the logging server is empty and [.filename]#/var/log/messages# on the logging client does not indicate a reason for the failure. To increase debugging output, edit the `syslogd_flags` entry on the logging server and issue a restart: [.programlisting] .... syslogd_flags="-d -a logclient.example.com -v -v" .... [source,shell] .... # service syslogd restart .... Debugging data similar to the following will flash on the console immediately after the restart: [source,shell] .... logmsg: pri 56, flags 4, from logserv.example.com, msg syslogd: restart syslogd: restarted logmsg: pri 6, flags 4, from logserv.example.com, msg syslogd: kernel boot file is /boot/kernel/kernel Logging to FILE /var/log/messages syslogd: kernel boot file is /boot/kernel/kernel cvthname(192.168.1.10) validate: dgram from IP 192.168.1.10, port 514, name logclient.example.com; rejected in rule 0 due to name mismatch. .... In this example, the log messages are being rejected due to a typo which results in a hostname mismatch. The client's hostname should be `logclient`, not `logclien`. Fix the typo, issue a restart, and verify the results: [source,shell] .... # service syslogd restart logmsg: pri 56, flags 4, from logserv.example.com, msg syslogd: restart syslogd: restarted logmsg: pri 6, flags 4, from logserv.example.com, msg syslogd: kernel boot file is /boot/kernel/kernel syslogd: kernel boot file is /boot/kernel/kernel logmsg: pri 166, flags 17, from logserv.example.com, msg Dec 10 20:55:02 logserv.example.com syslogd: exiting on signal 2 cvthname(192.168.1.10) validate: dgram from IP 192.168.1.10, port 514, name logclient.example.com; accepted in rule 0. logmsg: pri 15, flags 0, from logclient.example.com, msg Dec 11 02:01:28 trhodes: Test message 2 Logging to FILE /var/log/logclient.log Logging to FILE /var/log/messages .... At this point, the messages are being properly received and placed in the correct file. ==== 安全注意事項 As with any network service, security requirements should be considered before implementing a logging server. Log files may contain sensitive data about services enabled on the local host, user accounts, and configuration data. Network data sent from the client to the server will not be encrypted or password protected. If a need for encryption exists, consider using package:security/stunnel[], which will transmit the logging data over an encrypted tunnel. Local security is also an issue. Log files are not encrypted during use or after log rotation. Local users may access log files to gain additional insight into system configuration. Setting proper permissions on log files is critical. The built-in log rotator, newsyslog, supports setting permissions on newly created and rotated log files. Setting log files to mode `600` should prevent unwanted access by local users. Refer to man:newsyslog.conf[5] for additional information. [[configtuning-configfiles]] == 設定檔 === [.filename]#/etc# 配置 有數個目錄中儲存著設定資訊,這些目錄有: [.informaltable] [cols="1,1", frame="none"] |=== |[.filename]#/etc# |通用系統特定的設定資訊。 |[.filename]#/etc/defaults# |系統設定檔的預設版本。 |[.filename]#/etc/mail# |man:sendmail[8] 額外的設定以及其他 MTA 設定檔。 |[.filename]#/etc/ppp# |user- 及 kernel-ppp 程式的設定。 |[.filename]#/usr/local/etc# |已安裝應用程式的設定檔,可能會有以應用程式區分的子目錄。 |[.filename]#/usr/local/etc/rc.d# |已安裝應用程式的 man:rc[8] Script。 |[.filename]#/var/db# |自動產生的系統特定資料庫檔案,例如套件資料庫以及 man:locate[1] 資料庫。 |=== === 主機名稱 ==== [.filename]#/etc/resolv.conf# FreeBSD 要如何存取網際網路網域名稱系統 (Internet Domain Name System, DNS) 是由 man:resolv.conf[5] 來控制。 [.filename]#/etc/resolv.conf# 中最常用的項目為: [.informaltable] [cols="1,1", frame="none"] |=== |`nameserver` |解析程式 (Resolver) 要查詢的名稱伺服器 IP 位置,這些伺服器會依所列的順序來查詢,最多可以有三個。 |`search` |主機名稱查詢使用的搜尋清單。這通常會使用本機主機名稱所在的網域。 |`domain` |本地網域名稱。 |=== 典型的 [.filename]#/etc/resolv.conf# 會如下: [.programlisting] .... search example.com nameserver 147.11.1.11 nameserver 147.11.100.30 .... [NOTE] ==== `search` 與 `domain` 選項應擇一使用。 ==== 當使用 DHCP 時,man:dhclient[8] 通常會使用從 DHCP 伺服器所接收到的資訊覆寫 [.filename]#/etc/resolv.conf#。 ==== [.filename]#/etc/hosts# [.filename]#/etc/hosts# 是簡單的文字資料庫,會與 DNS 及 NIS 一併使用來提供主機名稱與 IP 位址的對應。可將透過 LAN 所連結的在地電腦項目加入到這個檔案做最簡單的命名,來替代設定一個 man:named[8] 伺服器。除此之外 [.filename]#/etc/hosts# 可以用來提供本地的網際網路名稱記錄,來減少常用名稱向外部 DNS 伺服器查詢的需求。 [.programlisting] .... # $FreeBSD: head/zh_TW.UTF-8/books/handbook/book.xml 53653 2019-12-03 17:05:41Z rcyu $ # # # Host Database # # This file should contain the addresses and aliases for local hosts that # share this file. Replace 'my.domain' below with the domainname of your # machine. # # In the presence of the domain name service or NIS, this file may # not be consulted at all; see /etc/nsswitch.conf for the resolution order. # # ::1 localhost localhost.my.domain 127.0.0.1 localhost localhost.my.domain # # Imaginary network. #10.0.0.2 myname.my.domain myname #10.0.0.3 myfriend.my.domain myfriend # # According to RFC 1918, you can use the following IP networks for # private nets which will never be connected to the Internet: # # 10.0.0.0 - 10.255.255.255 # 172.16.0.0 - 172.31.255.255 # 192.168.0.0 - 192.168.255.255 # # In case you want to be able to connect to the Internet, you need # real official assigned numbers. Do not try to invent your own network # numbers but instead get one from your network provider (if any) or # from your regional registry (ARIN, APNIC, LACNIC, RIPE NCC, or AfriNIC.) # .... [.filename]#/etc/hosts# 的格式如下: [.programlisting] .... [Internet address] [official hostname] [alias1] [alias2] ... .... 例如: [.programlisting] .... 10.0.0.1 myRealHostname.example.com myRealHostname foobar1 foobar2 .... 請參考 man:hosts[5] 取得更多資訊。 [[configtuning-sysctl]] == 使用 man:sysctl[8] 調校 man:sysctl[8] 可用來更改執行中的 FreeBSD 系統,這包含許多 TCP/IP 堆疊及虛擬記憶體系統的進階選項,讓有經驗的系統管理者能夠簡單的提升效能。有超過五百個系統變數可以使用 man:sysctl[8] 來讀取與設定。 man:sysctl[8] 主要提供兩個功能:讀取與修改系統設定。 檢視所有可讀取的變數: [source,shell] .... % sysctl -a .... 要讀取特定變數只要指定其名稱: [source,shell] .... % sysctl kern.maxproc kern.maxproc: 1044 .... 要設定特定變數可使用 _variable_=_value_ 語法: [source,shell] .... # sysctl kern.maxfiles=5000 kern.maxfiles: 2088 -> 5000 .... sysctl 的設定值通常為字串、數字或布林值,其中布林值的 `1` 代表是,`0` 代表否。 要在每次機器開機時自動設定一些變數可將其加入到 [.filename]#/etc/sysctl.conf#。要取得更多的資訊請參考 man:sysctl.conf[5] 及 <>。 [[configtuning-sysctlconf]] === [.filename]#sysctl.conf# man:sysctl[8] 的設定檔於 [.filename]#/etc/sysctl.conf#,內容很像 [.filename]#/etc/rc.conf#,設定數值使用 `variable=value` 格式。指定的數值會在系統進入多使用者模式時設定,但並非所有變數皆可在此模式設定。 例如,要關閉嚴重信號 (Fatal signal) 中止的記錄並避免使用者看到其他使用者所執行的程序,可加入以下設定到 [.filename]#/etc/sysctl.conf#: [.programlisting] .... # Do not log fatal signal exits (e.g., sig 11) kern.logsigexit=0 # Prevent users from seeing information about processes that # are being run under another UID. security.bsd.see_other_uids=0 .... [[sysctl-readonly]] === 唯讀 man:sysctl[8] 在有些情況可能會需要修改唯讀的 man:sysctl[8] 數值,而這會需要重新啟動系統。 例如,某些筆電型號的 man:cardbus[4] 裝置無法偵測到記憶體範圍而且會失效並有類似以下的錯誤: [source,shell] .... cbb0: Could not map register memory device_probe_and_attach: cbb0 attach returned 12 .... 這個修正需要修改唯讀的 man:sysctl[8] 設定。加入 `hw.pci.allow_unsupported_io_range=1` 到 [.filename]#/boot/loader.conf# 然後重新啟動。現在 man:cardbus[4] 應可正常運作。 [[configtuning-disk]] == 調校磁碟 接下來的章節會討論在磁碟裝置上各種可調校的機制與選項。在大多數案例中,有使用機械元件的硬碟,如 SCSI 磁碟機,會成為導致整體系統效能低下的瓶頸。雖然已經有不使用機械元件的磁碟機解決方案,如,固態硬碟,但使用機械元件的磁碟機短期內並不會消失。在調校磁碟時,建議可以利用 man:iostat[8] 指令的功能來測試各種對系統的變更,這個指令可讓使用者取得系統 IO 相關的有用資訊。 === Sysctl 變數 ==== `vfs.vmiodirenable` The `vfs.vmiodirenable` man:sysctl[8] variable may be set to either `0` (off) or `1` (on). It is set to `1` by default. This variable controls how directories are cached by the system. Most directories are small, using just a single fragment (typically 1 K) in the file system and typically 512 bytes in the buffer cache. With this variable turned off, the buffer cache will only cache a fixed number of directories, even if the system has a huge amount of memory. When turned on, this man:sysctl[8] allows the buffer cache to use the VM page cache to cache the directories, making all the memory available for caching directories. However, the minimum in-core memory used to cache a directory is the physical page size (typically 4 K) rather than 512 bytes. Keeping this option enabled is recommended if the system is running any services which manipulate large numbers of files. Such services can include web caches, large mail systems, and news systems. Keeping this option on will generally not reduce performance, even with the wasted memory, but one should experiment to find out. ==== `vfs.write_behind` The `vfs.write_behind` man:sysctl[8] variable defaults to `1` (on). This tells the file system to issue media writes as full clusters are collected, which typically occurs when writing large sequential files. This avoids saturating the buffer cache with dirty buffers when it would not benefit I/O performance. However, this may stall processes and under certain circumstances should be turned off. ==== `vfs.hirunningspace` The `vfs.hirunningspace` man:sysctl[8] variable determines how much outstanding write I/O may be queued to disk controllers system-wide at any given instance. The default is usually sufficient, but on machines with many disks, try bumping it up to four or five _megabytes_. Setting too high a value which exceeds the buffer cache's write threshold can lead to bad clustering performance. Do not set this value arbitrarily high as higher write values may add latency to reads occurring at the same time. There are various other buffer cache and VM page cache related man:sysctl[8] values. Modifying these values is not recommended as the VM system does a good job of automatically tuning itself. ==== `vm.swap_idle_enabled` The `vm.swap_idle_enabled` man:sysctl[8] variable is useful in large multi-user systems with many active login users and lots of idle processes. Such systems tend to generate continuous pressure on free memory reserves. Turning this feature on and tweaking the swapout hysteresis (in idle seconds) via `vm.swap_idle_threshold1` and `vm.swap_idle_threshold2` depresses the priority of memory pages associated with idle processes more quickly then the normal pageout algorithm. This gives a helping hand to the pageout daemon. Only turn this option on if needed, because the tradeoff is essentially pre-page memory sooner rather than later which eats more swap and disk bandwidth. In a small system this option will have a determinable effect, but in a large system that is already doing moderate paging, this option allows the VM system to stage whole processes into and out of memory easily. ==== `hw.ata.wc` Turning off IDE write caching reduces write bandwidth to IDE disks, but may sometimes be necessary due to data consistency issues introduced by hard drive vendors. The problem is that some IDE drives lie about when a write completes. With IDE write caching turned on, IDE hard drives write data to disk out of order and will sometimes delay writing some blocks indefinitely when under heavy disk load. A crash or power failure may cause serious file system corruption. Check the default on the system by observing the `hw.ata.wc` man:sysctl[8] variable. If IDE write caching is turned off, one can set this read-only variable to `1` in [.filename]#/boot/loader.conf# in order to enable it at boot time. For more information, refer to man:ata[4]. ==== `SCSI_DELAY` (`kern.cam.scsi_delay`) The `SCSI_DELAY` kernel configuration option may be used to reduce system boot times. The defaults are fairly high and can be responsible for `15` seconds of delay in the boot process. Reducing it to `5` seconds usually works with modern drives. The `kern.cam.scsi_delay` boot time tunable should be used. The tunable and kernel configuration option accept values in terms of _milliseconds_ and _not seconds_. [[soft-updates]] === 軟更新 To fine-tune a file system, use man:tunefs[8]. This program has many different options. To toggle Soft Updates on and off, use: [source,shell] .... # tunefs -n enable /filesystem # tunefs -n disable /filesystem .... A file system cannot be modified with man:tunefs[8] while it is mounted. A good time to enable Soft Updates is before any partitions have been mounted, in single-user mode. Soft Updates is recommended for UFS file systems as it drastically improves meta-data performance, mainly file creation and deletion, through the use of a memory cache. There are two downsides to Soft Updates to be aware of. First, Soft Updates guarantee file system consistency in the case of a crash, but could easily be several seconds or even a minute behind updating the physical disk. If the system crashes, unwritten data may be lost. Secondly, Soft Updates delay the freeing of file system blocks. If the root file system is almost full, performing a major update, such as `make installworld`, can cause the file system to run out of space and the update to fail. ==== 有關軟更新的更多詳細資訊 Meta-data updates are updates to non-content data like inodes or directories. There are two traditional approaches to writing a file system's meta-data back to disk. Historically, the default behavior was to write out meta-data updates synchronously. If a directory changed, the system waited until the change was actually written to disk. The file data buffers (file contents) were passed through the buffer cache and backed up to disk later on asynchronously. The advantage of this implementation is that it operates safely. If there is a failure during an update, meta-data is always in a consistent state. A file is either created completely or not at all. If the data blocks of a file did not find their way out of the buffer cache onto the disk by the time of the crash, man:fsck[8] recognizes this and repairs the file system by setting the file length to `0`. Additionally, the implementation is clear and simple. The disadvantage is that meta-data changes are slow. For example, `rm -r` touches all the files in a directory sequentially, but each directory change will be written synchronously to the disk. This includes updates to the directory itself, to the inode table, and possibly to indirect blocks allocated by the file. Similar considerations apply for unrolling large hierarchies using `tar -x`. The second approach is to use asynchronous meta-data updates. This is the default for a UFS file system mounted with `mount -o async`. Since all meta-data updates are also passed through the buffer cache, they will be intermixed with the updates of the file content data. The advantage of this implementation is there is no need to wait until each meta-data update has been written to disk, so all operations which cause huge amounts of meta-data updates work much faster than in the synchronous case. This implementation is still clear and simple, so there is a low risk for bugs creeping into the code. The disadvantage is that there is no guarantee for a consistent state of the file system. If there is a failure during an operation that updated large amounts of meta-data, like a power failure or someone pressing the reset button, the file system will be left in an unpredictable state. There is no opportunity to examine the state of the file system when the system comes up again as the data blocks of a file could already have been written to the disk while the updates of the inode table or the associated directory were not. It is impossible to implement a man:fsck[8] which is able to clean up the resulting chaos because the necessary information is not available on the disk. If the file system has been damaged beyond repair, the only choice is to reformat it and restore from backup. The usual solution for this problem is to implement _dirty region logging_, which is also referred to as _journaling_. Meta-data updates are still written synchronously, but only into a small region of the disk. Later on, they are moved to their proper location. Because the logging area is a small, contiguous region on the disk, there are no long distances for the disk heads to move, even during heavy operations, so these operations are quicker than synchronous updates. Additionally, the complexity of the implementation is limited, so the risk of bugs being present is low. A disadvantage is that all meta-data is written twice, once into the logging region and once to the proper location, so performance "pessimization" might result. On the other hand, in case of a crash, all pending meta-data operations can be either quickly rolled back or completed from the logging area after the system comes up again, resulting in a fast file system startup. Kirk McKusick, the developer of Berkeley FFS, solved this problem with Soft Updates. All pending meta-data updates are kept in memory and written out to disk in a sorted sequence ("ordered meta-data updates"). This has the effect that, in case of heavy meta-data operations, later updates to an item "catch" the earlier ones which are still in memory and have not already been written to disk. All operations are generally performed in memory before the update is written to disk and the data blocks are sorted according to their position so that they will not be on the disk ahead of their meta-data. If the system crashes, an implicit "log rewind" causes all operations which were not written to the disk appear as if they never happened. A consistent file system state is maintained that appears to be the one of 30 to 60 seconds earlier. The algorithm used guarantees that all resources in use are marked as such in their blocks and inodes. After a crash, the only resource allocation error that occurs is that resources are marked as "used" which are actually "free". man:fsck[8] recognizes this situation, and frees the resources that are no longer used. It is safe to ignore the dirty state of the file system after a crash by forcibly mounting it with `mount -f`. In order to free resources that may be unused, man:fsck[8] needs to be run at a later time. This is the idea behind the _background man:fsck[8]_: at system startup time, only a _snapshot_ of the file system is recorded and man:fsck[8] is run afterwards. All file systems can then be mounted "dirty", so the system startup proceeds in multi-user mode. Then, background man:fsck[8] is scheduled for all file systems where this is required, to free resources that may be unused. File systems that do not use Soft Updates still need the usual foreground man:fsck[8]. The advantage is that meta-data operations are nearly as fast as asynchronous updates and are faster than _logging_, which has to write the meta-data twice. The disadvantages are the complexity of the code, a higher memory consumption, and some idiosyncrasies. After a crash, the state of the file system appears to be somewhat "older". In situations where the standard synchronous approach would have caused some zero-length files to remain after the man:fsck[8], these files do not exist at all with Soft Updates because neither the meta-data nor the file contents have been written to disk. Disk space is not released until the updates have been written to disk, which may take place some time after running man:rm[1]. This may cause problems when installing large amounts of data on a file system that does not have enough free space to hold all the files twice. [[configtuning-kernel-limits]] == 調校核心限制 [[file-process-limits]] === 檔案/程序限制 [[kern-maxfiles]] ==== `kern.maxfiles` The `kern.maxfiles` man:sysctl[8] variable can be raised or lowered based upon system requirements. This variable indicates the maximum number of file descriptors on the system. When the file descriptor table is full, `file: table is full` will show up repeatedly in the system message buffer, which can be viewed using man:dmesg[8]. Each open file, socket, or fifo uses one file descriptor. A large-scale production server may easily require many thousands of file descriptors, depending on the kind and number of services running concurrently. In older FreeBSD releases, the default value of `kern.maxfiles` is derived from `maxusers` in the kernel configuration file. `kern.maxfiles` grows proportionally to the value of `maxusers`. When compiling a custom kernel, consider setting this kernel configuration option according to the use of the system. From this number, the kernel is given most of its pre-defined limits. Even though a production machine may not have 256 concurrent users, the resources needed may be similar to a high-scale web server. The read-only man:sysctl[8] variable `kern.maxusers` is automatically sized at boot based on the amount of memory available in the system, and may be determined at run-time by inspecting the value of `kern.maxusers`. Some systems require larger or smaller values of `kern.maxusers` and values of `64`, `128`, and `256` are not uncommon. Going above `256` is not recommended unless a huge number of file descriptors is needed. Many of the tunable values set to their defaults by `kern.maxusers` may be individually overridden at boot-time or run-time in [.filename]#/boot/loader.conf#. Refer to man:loader.conf[5] and [.filename]#/boot/defaults/loader.conf# for more details and some hints. In older releases, the system will auto-tune `maxusers` if it is set to `0`. . When setting this option, set `maxusers` to at least `4`, especially if the system runs Xorg or is used to compile software. The most important table set by `maxusers` is the maximum number of processes, which is set to `20 + 16 * maxusers`. If `maxusers` is set to `1`, there can only be `36` simultaneous processes, including the `18` or so that the system starts up at boot time and the `15` or so used by Xorg. Even a simple task like reading a manual page will start up nine processes to filter, decompress, and view it. Setting `maxusers` to `64` allows up to `1044` simultaneous processes, which should be enough for nearly all uses. If, however, the error is displayed when trying to start another program, or a server is running with a large number of simultaneous users, increase the number and rebuild. [NOTE] ==== `maxusers` does _not_ limit the number of users which can log into the machine. It instead sets various table sizes to reasonable values considering the maximum number of users on the system and how many processes each user will be running. ==== ==== `kern.ipc.soacceptqueue` The `kern.ipc.soacceptqueue` man:sysctl[8] variable limits the size of the listen queue for accepting new `TCP` connections. The default value of `128` is typically too low for robust handling of new connections on a heavily loaded web server. For such environments, it is recommended to increase this value to `1024` or higher. A service such as man:sendmail[8], or Apache may itself limit the listen queue size, but will often have a directive in its configuration file to adjust the queue size. Large listen queues do a better job of avoiding Denial of Service (DoS) attacks. [[nmbclusters]] === 網路限制 The `NMBCLUSTERS` kernel configuration option dictates the amount of network Mbufs available to the system. A heavily-trafficked server with a low number of Mbufs will hinder performance. Each cluster represents approximately 2 K of memory, so a value of `1024` represents `2` megabytes of kernel memory reserved for network buffers. A simple calculation can be done to figure out how many are needed. A web server which maxes out at `1000` simultaneous connections where each connection uses a 6 K receive and 16 K send buffer, requires approximately 32 MB worth of network buffers to cover the web server. A good rule of thumb is to multiply by `2`, so 2x32 MB / 2 KB = 64 MB / 2 kB = `32768`. Values between `4096` and `32768` are recommended for machines with greater amounts of memory. Never specify an arbitrarily high value for this parameter as it could lead to a boot time crash. To observe network cluster usage, use `-m` with man:netstat[1]. The `kern.ipc.nmbclusters` loader tunable should be used to tune this at boot time. Only older versions of FreeBSD will require the use of the `NMBCLUSTERS` kernel man:config[8] option. For busy servers that make extensive use of the man:sendfile[2] system call, it may be necessary to increase the number of man:sendfile[2] buffers via the `NSFBUFS` kernel configuration option or by setting its value in [.filename]#/boot/loader.conf# (see man:loader[8] for details). A common indicator that this parameter needs to be adjusted is when processes are seen in the `sfbufa` state. The man:sysctl[8] variable `kern.ipc.nsfbufs` is read-only. This parameter nominally scales with `kern.maxusers`, however it may be necessary to tune accordingly. [IMPORTANT] ==== Even though a socket has been marked as non-blocking, calling man:sendfile[2] on the non-blocking socket may result in the man:sendfile[2] call blocking until enough ``struct sf_buf``'s are made available. ==== ==== `net.inet.ip.portrange.*` The `net.inet.ip.portrange.*` man:sysctl[8] variables control the port number ranges automatically bound to `TCP` and `UDP` sockets. There are three ranges: a low range, a default range, and a high range. Most network programs use the default range which is controlled by `net.inet.ip.portrange.first` and `net.inet.ip.portrange.last`, which default to `1024` and `5000`, respectively. Bound port ranges are used for outgoing connections and it is possible to run the system out of ports under certain circumstances. This most commonly occurs when running a heavily loaded web proxy. The port range is not an issue when running a server which handles mainly incoming connections, such as a web server, or has a limited number of outgoing connections, such as a mail relay. For situations where there is a shortage of ports, it is recommended to increase `net.inet.ip.portrange.last` modestly. A value of `10000`, `20000` or `30000` may be reasonable. Consider firewall effects when changing the port range. Some firewalls may block large ranges of ports, usually low-numbered ports, and expect systems to use higher ranges of ports for outgoing connections. For this reason, it is not recommended that the value of `net.inet.ip.portrange.first` be lowered. ==== `TCP` 頻寬延遲乘積 `TCP` bandwidth delay product limiting can be enabled by setting the `net.inet.tcp.inflight.enable` man:sysctl[8] variable to `1`. This instructs the system to attempt to calculate the bandwidth delay product for each connection and limit the amount of data queued to the network to just the amount required to maintain optimum throughput. This feature is useful when serving data over modems, Gigabit Ethernet, high speed `WAN` links, or any other link with a high bandwidth delay product, especially when also using window scaling or when a large send window has been configured. When enabling this option, also set `net.inet.tcp.inflight.debug` to `0` to disable debugging. For production use, setting `net.inet.tcp.inflight.min` to at least `6144` may be beneficial. Setting high minimums may effectively disable bandwidth limiting, depending on the link. The limiting feature reduces the amount of data built up in intermediate route and switch packet queues and reduces the amount of data built up in the local host's interface queue. With fewer queued packets, interactive connections, especially over slow modems, will operate with lower _Round Trip Times_. This feature only effects server side data transmission such as uploading. It has no effect on data reception or downloading. Adjusting `net.inet.tcp.inflight.stab` is _not_ recommended. This parameter defaults to `20`, representing 2 maximal packets added to the bandwidth delay product window calculation. The additional window is required to stabilize the algorithm and improve responsiveness to changing conditions, but it can also result in higher man:ping[8] times over slow links, though still much lower than without the inflight algorithm. In such cases, try reducing this parameter to `15`, `10`, or `5` and reducing `net.inet.tcp.inflight.min` to a value such as `3500` to get the desired effect. Reducing these parameters should be done as a last resort only. === 虛擬記憶體 ==== `kern.maxvnodes` A vnode is the internal representation of a file or directory. Increasing the number of vnodes available to the operating system reduces disk I/O. Normally, this is handled by the operating system and does not need to be changed. In some cases where disk I/O is a bottleneck and the system is running out of vnodes, this setting needs to be increased. The amount of inactive and free RAM will need to be taken into account. To see the current number of vnodes in use: [source,shell] .... # sysctl vfs.numvnodes vfs.numvnodes: 91349 .... To see the maximum vnodes: [source,shell] .... # sysctl kern.maxvnodes kern.maxvnodes: 100000 .... If the current vnode usage is near the maximum, try increasing `kern.maxvnodes` by a value of `1000`. Keep an eye on the number of `vfs.numvnodes`. If it climbs up to the maximum again, `kern.maxvnodes` will need to be increased further. Otherwise, a shift in memory usage as reported by man:top[1] should be visible and more memory should be active. [[adding-swap-space]] == 增加交換空間 有時系統會需要更多的交換 (Swap) 空間,本章節會介紹兩種增加交換空間的方式:一種是在既有的分割區或新的硬碟增加交換空間,另一種則是在既有的分割區中建立一個交換檔。 要取得更多有關如何加密交換空間的資訊、有那些可用的選項以及為何要做加密,可參考 crossref:disks[swap-encrypting,交換空間加密]。 [[new-drive-swap]] === 使用新硬碟或既有分割區增加交換空間 在新的磁碟上增加交換空間比起使用既有硬碟上的分割區會有較佳的效率。設定分割區與硬碟在 crossref:disks[disks-adding,加入磁碟] 中有說明,另外 crossref:bsdinstall[configtuning-initial,規劃分割區配置] 會討論到分割區的配置與交換分割區大小需考量的事項。 使用 `swapon` 來增加交換分割區到系統,例: [source,shell] .... # swapon /dev/ada1s1b .... [WARNING] ==== 可以使用任何尚未掛載過、甚至已經有內含資料的分割區做為交換空間,但在含有資料的分割區上使用 `swapon` 會覆寫並清除該分割區上所有的資料,請在執行 `swapon` 之前確認真的要使用該分割區增加交換空間。 ==== 要在開機時自動加入此交換分割區,可加入以下項目到 [.filename]#/etc/fstab#: [.programlisting] .... /dev/ada1s1b none swap sw 0 0 .... 請參考 man:fstab[5] 來取得在 [.filename]#/etc/fstab# 中項目的說明。更多有關 `swapon` 的資訊 可以在 man:swapon[8] 找到。 [[create-swapfile]] === 建立交換檔 以下例子會建立一個 64M 的交換檔於 [.filename]#/usr/swap0# 來替代使用分割區建立交換空間。 使用交換檔開啟交換空間前需要在核心編譯或載入 man:md[4] 所需的模組,請參考 crossref:kernelconfig[kernelconfig,設定 FreeBSD 核心] 了解有關編譯自訂核心的資訊。 [[swapfile-10-and-later]] .建立交換檔於 FreeBSD 10._X_ 及以後版本 [example] ==== [.procedure] ====== . 建立交換檔: + [source,shell] .... # dd if=/dev/zero of=/usr/swap0 bs=1m count=64 .... + . 在新檔案設定適當的權限: + [source,shell] .... # chmod 0600 /usr/swap0 .... + . 加入行到 [.filename]#/etc/fstab# 以讓系統知道交換檔的資訊: + [.programlisting] .... md99 none swap sw,file=/usr/swap0,late 0 0 .... + 已使用 man:md[4] 裝置的 [.filename]#md99#,保留較低的裝置編號供互動操作時使用。 . 交換空間會於系統啟動時增加。若要立即增加交換空間,請參考 man:swapon[8]: + [source,shell] .... # swapon -aL .... ====== ==== [[swapfile-9-and-earlier]] .建立交換檔於 FreeBSD 9._X_ 及先前版本 [example] ==== [.procedure] ====== . 建立交換檔 [.filename]#/usr/swap0#: + [source,shell] .... # dd if=/dev/zero of=/usr/swap0 bs=1m count=64 .... + . 設定適當的權限於 [.filename]#/usr/swap0#: + [source,shell] .... # chmod 0600 /usr/swap0 .... + . 在 [.filename]#/etc/rc.conf# 開啟交換檔: + [.programlisting] .... swapfile="/usr/swap0" # Set to name of swap file .... + . 交換空間會於系統啟動時增加。若要立即增加交換空間,可指定一個未使用的記憶體裝置。請參考 crossref:disks[disks-virtual,記憶體磁碟] 取得更多有關記憶體裝置的資訊。 + [source,shell] .... # mdconfig -a -t vnode -f /usr/swap0 -u 0 && swapon /dev/md0 .... ====== ==== [[acpi-overview]] == 電源與資源管理 以有效率的方式運用硬體資源是很重要的,電源與資源管理讓作業系統可以監控系統的限制,並且在系統溫度意外升高時能夠發出警報。早期提供電源管理的規範是進階電源管理 (Advanced Power Management, APM),APM 可根據系統的使用狀況來來控制電源用量。然而,使用 APM 要作業系統來管理系統的電源用量和溫度屬性是困難且沒有彈性的,因為硬體是由 BIOS 所管理,使用者對電源管理設定只有有限的設定性與可見性,且 APMBIOS 是由供應商提供且特定於某些硬體平台,而作業系統中必透過 APM 驅動程式做為中介存取 APM 軟體介面才能夠管理電源等級。 在 APM 有四個主要的問題。第一,電源管理是由供應商特定的 BIOS 來完成,與作業系統是分開的。例如,使用者可在 APMBIOS 設定硬碟的閒置時間值,在超過時間時 BIOS 可在未徵得作業系統的同意下降低硬碟的轉速。第二,APM 的邏輯是內嵌在 BIOS 當中的,並且在作業系統範圍之外運作,這代表使用者只能夠透過燒錄新的韌體到 ROM 來修正 APMBIOS 中的問題,而這樣的程序是危險的,若失敗,可能會讓系統進入無法復原的狀態。第三,APM 是供應商特定的技術,這代表有許多重複的工作,在一個供應商的 BIOS 找到的問題在其他的供應商卻沒有解決。最後一點,APMBIOS 並沒有足夠的空間來實作複雜的電源管理政策或可良好適應主機用途的程式。 Plug and Play BIOS (PNPBIOS) 在很多情況下並不可靠,PNPBIOS 是 16 位元的技術,所以作業系統必須模擬 16 位元才能存取 PNPBIOS。FreeBSD 提供了一個 APM 驅動程式來做 APM,應可用在 2000 年之前所製造的系統,該驅動程式的說明於 man:apm[4]。 APM 的後繼者是進階設置與電源介面 (Advanced Configuration and Power Interface, ACPI)。ACPI 是一套由供應商聯盟所搛寫出的標準,提供了硬體資源與電源管理的介面,它是 _作業系統直接設置與電源管理 (Operating System-directed configuration and Power Management)_ 關鍵的要素,提供了作業系統更多的控制方式與彈性。 本章節將示範如何在 FreeBSD 設定 ACPI,然後提供一些如何對 ACPI 除錯的提示以及如何提交包含除錯資訊的問題回報,讓開發人員能夠診斷並修正 ACPI 的問題。 [[acpi-config]] === 設定 ACPI 在 FreeBSD man:acpi[4] 驅動程式預設會在系統開始時載入,且__不__應被編譯到核心當中。這個驅動程式在開機之後無法被卸載,因為系統匯流排會使用它做各種硬體互動。雖然如此,若系統遇到問題,ACPI 還是可以被關閉,在 [.filename]#/boot/loader.conf# 中設定 `hint.acpi.0.disabled="1"` 之後重新開機或在載入程式提示時設定這個變數,如 crossref:boot[boot-loader,階段三] 中的說明。 [NOTE] ==== ACPI 與 APM 不能同時存在且應分開使用,若有偵測到有另一個正在執行,要載入的後者將會中斷。 ==== ACPI 可以用來讓系統進入睡眠模式,使用 `acpiconf` 與 `-s` 旗標再加上由 `1` 到 `5` 的數字。大多數使用者只需使用 `1` (快速待命到 RAM) 或 `3` (待命到 RAM),選項 `5` 會執行軟關機 (Soft-off),如同執行 `halt -p` 一樣。 其他的選項可使用 `sysctl` 來設定,請參考 man:acpi[4] 以及 man:acpiconf[8] 以取得更多資訊。 [[ACPI-comprob]] === 常見問題 ACPI is present in all modern computers that conform to the ia32 (x86), ia64 (Itanium), and amd64 (AMD) architectures. The full standard has many features including CPU performance management, power planes control, thermal zones, various battery systems, embedded controllers, and bus enumeration. Most systems implement less than the full standard. For instance, a desktop system usually only implements bus enumeration while a laptop might have cooling and battery management support as well. Laptops also have suspend and resume, with their own associated complexity. An ACPI-compliant system has various components. The BIOS and chipset vendors provide various fixed tables, such as FADT, in memory that specify things like the APIC map (used for SMP), config registers, and simple configuration values. Additionally, a bytecode table, the Differentiated System Description Table DSDT, specifies a tree-like name space of devices and methods. The ACPI driver must parse the fixed tables, implement an interpreter for the bytecode, and modify device drivers and the kernel to accept information from the ACPI subsystem. For FreeBSD, Intel(TM) has provided an interpreter (ACPI-CA) that is shared with Linux(TM) and NetBSD. The path to the ACPI-CA source code is [.filename]#src/sys/contrib/dev/acpica#. The glue code that allows ACPI-CA to work on FreeBSD is in [.filename]#src/sys/dev/acpica/Osd#. Finally, drivers that implement various ACPI devices are found in [.filename]#src/sys/dev/acpica#. For ACPI to work correctly, all the parts have to work correctly. Here are some common problems, in order of frequency of appearance, and some possible workarounds or fixes. If a fix does not resolve the issue, refer to <> for instructions on how to submit a bug report. ==== 滑鼠問題 In some cases, resuming from a suspend operation will cause the mouse to fail. A known work around is to add `hint.psm.0.flags="0x3000"` to [.filename]#/boot/loader.conf#. ==== 待機/喚醒 ACPI has three suspend to RAM (STR) states, `S1`-`S3`, and one suspend to disk state (STD), called `S4`. STD can be implemented in two separate ways. The ``S4``BIOS is a BIOS-assisted suspend to disk and ``S4``OS is implemented entirely by the operating system. The normal state the system is in when plugged in but not powered up is "soft off" (`S5`). Use `sysctl hw.acpi` to check for the suspend-related items. These example results are from a Thinkpad: [source,shell] .... hw.acpi.supported_sleep_state: S3 S4 S5 hw.acpi.s4bios: 0 .... Use `acpiconf -s` to test `S3`, `S4`, and `S5`. An `s4bios` of one (`1`) indicates ``S4``BIOS support instead of `S4` operating system support. When testing suspend/resume, start with `S1`, if supported. This state is most likely to work since it does not require much driver support. No one has implemented `S2`, which is similar to `S1`. Next, try `S3`. This is the deepest STR state and requires a lot of driver support to properly reinitialize the hardware. A common problem with suspend/resume is that many device drivers do not save, restore, or reinitialize their firmware, registers, or device memory properly. As a first attempt at debugging the problem, try: [source,shell] .... # sysctl debug.bootverbose=1 # sysctl debug.acpi.suspend_bounce=1 # acpiconf -s 3 .... This test emulates the suspend/resume cycle of all device drivers without actually going into `S3` state. In some cases, problems such as losing firmware state, device watchdog time out, and retrying forever, can be captured with this method. Note that the system will not really enter `S3` state, which means devices may not lose power, and many will work fine even if suspend/resume methods are totally missing, unlike real `S3` state. Harder cases require additional hardware, such as a serial port and cable for debugging through a serial console, a Firewire port and cable for using man:dcons[4], and kernel debugging skills. To help isolate the problem, unload as many drivers as possible. If it works, narrow down which driver is the problem by loading drivers until it fails again. Typically, binary drivers like [.filename]#nvidia.ko#, display drivers, and USB will have the most problems while Ethernet interfaces usually work fine. If drivers can be properly loaded and unloaded, automate this by putting the appropriate commands in [.filename]#/etc/rc.suspend# and [.filename]#/etc/rc.resume#. Try setting `hw.acpi.reset_video` to `1` if the display is messed up after resume. Try setting longer or shorter values for `hw.acpi.sleep_delay` to see if that helps. Try loading a recent Linux(TM) distribution to see if suspend/resume works on the same hardware. If it works on Linux(TM), it is likely a FreeBSD driver problem. Narrowing down which driver causes the problem will assist developers in fixing the problem. Since the ACPI maintainers rarely maintain other drivers, such as sound or ATA, any driver problems should also be posted to the http://lists.FreeBSD.org/mailman/listinfo/freebsd-current[freebsd-current] list and mailed to the driver maintainer. Advanced users can include debugging man:printf[3]s in a problematic driver to track down where in its resume function it hangs. Finally, try disabling ACPI and enabling APM instead. If suspend/resume works with APM, stick with APM, especially on older hardware (pre-2000). It took vendors a while to get ACPI support correct and older hardware is more likely to have BIOS problems with ACPI. ==== 系統無回應 Most system hangs are a result of lost interrupts or an interrupt storm. Chipsets may have problems based on boot, how the BIOS configures interrupts before correctness of the APIC (MADT) table, and routing of the System Control Interrupt (SCI). Interrupt storms can be distinguished from lost interrupts by checking the output of `vmstat -i` and looking at the line that has `acpi0`. If the counter is increasing at more than a couple per second, there is an interrupt storm. If the system appears hung, try breaking to DDB (kbd:[CTRL+ALT+ESC] on console) and type `show interrupts`. When dealing with interrupt problems, try disabling APIC support with `hint.apic.0.disabled="1"` in [.filename]#/boot/loader.conf#. ==== 當機 Panics are relatively rare for ACPI and are the top priority to be fixed. The first step is to isolate the steps to reproduce the panic, if possible, and get a backtrace. Follow the advice for enabling `options DDB` and setting up a serial console in crossref:serialcomms[serialconsole-ddb,從序列線路 (Serial Line) 進入 DDB 除錯程式] or setting up a dump partition. To get a backtrace in DDB, use `tr`. When handwriting the backtrace, get at least the last five and the top five lines in the trace. Then, try to isolate the problem by booting with ACPI disabled. If that works, isolate the ACPI subsystem by using various values of `debug.acpi.disable`. See man:acpi[4] for some examples. ==== 系統在待機或關機後仍開機 First, try setting `hw.acpi.disable_on_poweroff="0"` in [.filename]#/boot/loader.conf#. This keeps ACPI from disabling various events during the shutdown process. Some systems need this value set to `1` (the default) for the same reason. This usually fixes the problem of a system powering up spontaneously after a suspend or poweroff. [[ACPI-aslanddump]] ==== BIOS 含有有問題的 Bytecode Some BIOS vendors provide incorrect or buggy bytecode. This is usually manifested by kernel console messages like this: [source,shell] .... ACPI-1287: *** Error: Method execution failed [\\_SB_.PCI0.LPC0.FIGD._STA] \\ (Node 0xc3f6d160), AE_NOT_FOUND .... Often, these problems may be resolved by updating the BIOS to the latest revision. Most console messages are harmless, but if there are other problems, like the battery status is not working, these messages are a good place to start looking for problems. === 覆蓋預設的 AML The BIOS bytecode, known as ACPI Machine Language (AML), is compiled from a source language called ACPI Source Language (ASL). The AML is found in the table known as the Differentiated System Description Table (DSDT). The goal of FreeBSD is for everyone to have working ACPI without any user intervention. Workarounds are still being developed for common mistakes made by BIOS vendors. The Microsoft(TM) interpreter ([.filename]#acpi.sys# and [.filename]#acpiec.sys#) does not strictly check for adherence to the standard, and thus many BIOS vendors who only test ACPI under Windows(TM) never fix their ASL. FreeBSD developers continue to identify and document which non-standard behavior is allowed by Microsoft(TM)'s interpreter and replicate it so that FreeBSD can work without forcing users to fix the ASL. To help identify buggy behavior and possibly fix it manually, a copy can be made of the system's ASL. To copy the system's ASL to a specified file name, use `acpidump` with `-t`, to show the contents of the fixed tables, and `-d`, to disassemble the AML: [source,shell] .... # acpidump -td > my.asl .... Some AML versions assume the user is running Windows(TM). To override this, set `hw.acpi.osname=_"Windows 2009"_` in [.filename]#/boot/loader.conf#, using the most recent Windows(TM) version listed in the ASL. Other workarounds may require [.filename]#my.asl# to be customized. If this file is edited, compile the new ASL using the following command. Warnings can usually be ignored, but errors are bugs that will usually prevent ACPI from working correctly. [source,shell] .... # iasl -f my.asl .... Including `-f` forces creation of the AML, even if there are errors during compilation. Some errors, such as missing return statements, are automatically worked around by the FreeBSD interpreter. The default output filename for `iasl` is [.filename]#DSDT.aml#. Load this file instead of the BIOS's buggy copy, which is still present in flash memory, by editing [.filename]#/boot/loader.conf# as follows: [.programlisting] .... acpi_dsdt_load="YES" acpi_dsdt_name="/boot/DSDT.aml" .... Be sure to copy [.filename]#DSDT.aml# to [.filename]#/boot#, then reboot the system. If this fixes the problem, send a man:diff[1] of the old and new ASL to http://lists.FreeBSD.org/mailman/listinfo/freebsd-acpi[freebsd-acpi] so that developers can work around the buggy behavior in [.filename]#acpica#. [[ACPI-submitdebug]] === 取得與回報除錯資訊 The ACPI driver has a flexible debugging facility. A set of subsystems and the level of verbosity can be specified. The subsystems to debug are specified as layers and are broken down into components (`ACPI_ALL_COMPONENTS`) and ACPI hardware support (`ACPI_ALL_DRIVERS`). The verbosity of debugging output is specified as the level and ranges from just report errors (`ACPI_LV_ERROR`) to everything (`ACPI_LV_VERBOSE`). The level is a bitmask so multiple options can be set at once, separated by spaces. In practice, a serial console should be used to log the output so it is not lost as the console message buffer flushes. A full list of the individual layers and levels is found in man:acpi[4]. Debugging output is not enabled by default. To enable it, add `options ACPI_DEBUG` to the custom kernel configuration file if ACPI is compiled into the kernel. Add `ACPI_DEBUG=1` to [.filename]#/etc/make.conf# to enable it globally. If a module is used instead of a custom kernel, recompile just the [.filename]#acpi.ko# module as follows: [source,shell] .... # cd /sys/modules/acpi/acpi && make clean && make ACPI_DEBUG=1 .... Copy the compiled [.filename]#acpi.ko# to [.filename]#/boot/kernel# and add the desired level and layer to [.filename]#/boot/loader.conf#. The entries in this example enable debug messages for all ACPI components and hardware drivers and output error messages at the least verbose level: [.programlisting] .... debug.acpi.layer="ACPI_ALL_COMPONENTS ACPI_ALL_DRIVERS" debug.acpi.level="ACPI_LV_ERROR" .... If the required information is triggered by a specific event, such as a suspend and then resume, do not modify [.filename]#/boot/loader.conf#. Instead, use `sysctl` to specify the layer and level after booting and preparing the system for the specific event. The variables which can be set using `sysctl` are named the same as the tunables in [.filename]#/boot/loader.conf#. Once the debugging information is gathered, it can be sent to http://lists.FreeBSD.org/mailman/listinfo/freebsd-acpi[freebsd-acpi] so that it can be used by the FreeBSD ACPI maintainers to identify the root cause of the problem and to develop a solution. [NOTE] ==== Before submitting debugging information to this mailing list, ensure the latest BIOS version is installed and, if available, the embedded controller firmware version. ==== When submitting a problem report, include the following information: * Description of the buggy behavior, including system type, model, and anything that causes the bug to appear. Note as accurately as possible when the bug began occurring if it is new. * The output of `dmesg` after running `boot -v`, including any error messages generated by the bug. * The `dmesg` output from `boot -v` with ACPI disabled, if disabling ACPI helps to fix the problem. * Output from `sysctl hw.acpi`. This lists which features the system offers. * The URL to a pasted version of the system's ASL. Do _not_ send the ASL directly to the list as it can be very large. Generate a copy of the ASL by running this command: + [source,shell] .... # acpidump -dt > name-system.asl .... + Substitute the login name for _name_ and manufacturer/model for _system_. For example, use [.filename]#njl-FooCo6000.asl#. Most FreeBSD developers watch the http://lists.FreeBSD.org/mailman/listinfo/freebsd-current[FreeBSD-CURRENT mailing list], but one should submit problems to http://lists.FreeBSD.org/mailman/listinfo/freebsd-acpi[freebsd-acpi] to be sure it is seen. Be patient when waiting for a response. If the bug is not immediately apparent, submit a bug report. When entering a PR, include the same information as requested above. This helps developers to track the problem and resolve it. Do not send a PR without emailing http://lists.FreeBSD.org/mailman/listinfo/freebsd-acpi[freebsd-acpi] first as it is likely that the problem has been reported before. [[ACPI-References]] === 參考文獻 More information about ACPI may be found in the following locations: * The FreeBSD ACPI Mailing List Archives (https://lists.freebsd.org/pipermail/freebsd-acpi/[https://lists.freebsd.org/pipermail/freebsd-acpi/]) -* The ACPI 2.0 Specification (http://acpi.info/spec.htm[http://acpi.info/spec.htm]) +* The https://uefi.org/specifications#ACPI[ACPI Specification] * man:acpi[4], man:acpi_thermal[4], man:acpidump[8], man:iasl[8], and man:acpidb[8]