# $FreeBSD$ # Danilo G. Baio , 2018. #zanata # Edson Brandi , 2018. #zanata # Silvio Ap Silva , 2018. #zanata msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "POT-Creation-Date: 2018-09-06 00:46+0000\n" "PO-Revision-Date: 2018-09-03 02:06+0000\n" "Last-Translator: Edson Brandi \n" "Language-Team: \n" "Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "X-Generator: Zanata 4.6.2\n" "Plural-Forms: nplurals=2; plural=(n != 1)\n" #. Put one translator per line, in the form NAME , YEAR1, YEAR2 msgctxt "_" msgid "translator-credits" msgstr "" "Edson Brandi, ebrandi@FreeBSD.org, 2018\n" "Kanazuchi, contato@kanazuchi.com, 2018\n" "Danilo G. Baio, dbaio@FreeBSD.org, 2018" #. (itstool) path: info/title #: article.translate.xml:7 msgid "Linux emulation in FreeBSD" msgstr "" "Emulação de Linux no FreeBSD" #. (itstool) path: affiliation/address #: article.translate.xml:15 #, no-wrap msgid "" "\n" "\t rdivacky@FreeBSD.org\n" "\t" msgstr "" "\n" "\t rdivacky@FreeBSD.org\n" "\t" #. (itstool) path: info/author #: article.translate.xml:9 msgid "" " Roman Divacky <_:address-1/> " msgstr "" " Roman Divacky <_:address-1/> " #. (itstool) path: legalnotice/para #: article.translate.xml:22 msgid "" "Adobe, Acrobat, Acrobat Reader, Flash and PostScript are either registered " "trademarks or trademarks of Adobe Systems Incorporated in the United States " "and/or other countries." msgstr "" "Adobe, Acrobat, Acrobat Reader, Flash and PostScript are either registered " "trademarks or trademarks of Adobe Systems Incorporated in the United States " "and/or other countries." #. (itstool) path: legalnotice/para #: article.translate.xml:26 msgid "" "IBM, AIX, OS/2, PowerPC, PS/2, S/390, and ThinkPad are trademarks of " "International Business Machines Corporation in the United States, other " "countries, or both." msgstr "" "IBM, AIX, OS/2, PowerPC, PS/2, S/390, and ThinkPad are trademarks of " "International Business Machines Corporation in the United States, other " "countries, or both." #. (itstool) path: legalnotice/para #: article.translate.xml:30 msgid "FreeBSD is a registered trademark of the FreeBSD Foundation." msgstr "FreeBSD is a registered trademark of the FreeBSD Foundation." #. (itstool) path: legalnotice/para #: article.translate.xml:32 msgid "Linux is a registered trademark of Linus Torvalds." msgstr "Linux is a registered trademark of Linus Torvalds." #. (itstool) path: legalnotice/para #: article.translate.xml:34 msgid "NetBSD is a registered trademark of the NetBSD Foundation." msgstr "NetBSD is a registered trademark of the NetBSD Foundation." #. (itstool) path: legalnotice/para #: article.translate.xml:36 msgid "" "RealNetworks, RealPlayer, and RealAudio are the registered trademarks of " "RealNetworks, Inc." msgstr "" "RealNetworks, RealPlayer, and RealAudio are the registered trademarks of " "RealNetworks, Inc." #. (itstool) path: legalnotice/para #: article.translate.xml:39 msgid "Oracle is a registered trademark of Oracle Corporation." msgstr "Oracle is a registered trademark of Oracle Corporation." #. (itstool) path: legalnotice/para #: article.translate.xml:41 msgid "" "Sun, Sun Microsystems, Java, Java Virtual Machine, JDK, JRE, JSP, JVM, " "Netra, OpenJDK, Solaris, StarOffice, SunOS and VirtualBox are trademarks or " "registered trademarks of Sun Microsystems, Inc. in the United States and " "other countries." msgstr "" "Sun, Sun Microsystems, Java, Java Virtual Machine, JDK, JRE, JSP, JVM, " "Netra, OpenJDK, Solaris, StarOffice, SunOS and VirtualBox are trademarks or " "registered trademarks of Sun Microsystems, Inc. in the United States and " "other countries." #. (itstool) path: legalnotice/para #: article.translate.xml:46 msgid "" "Many of the designations used by manufacturers and sellers to distinguish " "their products are claimed as trademarks. Where those designations appear in " "this document, and the FreeBSD Project was aware of the trademark claim, the " "designations have been followed by the or the ® symbol." msgstr "" "Many of the designations used by manufacturers and sellers to distinguish " "their products are claimed as trademarks. Where those designations appear in " "this document, and the FreeBSD Project was aware of the trademark claim, the " "designations have been followed by the or the ® symbol." #. (itstool) path: info/pubdate #. (itstool) path: info/releaseinfo #: article.translate.xml:54 article.translate.xml:56 msgid "" "$FreeBSD: head/en_US.ISO8859-1/articles/linux-emulation/article.xml 51904 " "2018-06-23 14:55:54Z bcr $" msgstr "" "$FreeBSD: head/en_US.ISO8859-1/articles/linux-emulation/article.xml 51904 " "2018-06-23 14:55:54Z bcr $" #. (itstool) path: abstract/para #: article.translate.xml:59 msgid "" "This masters thesis deals with updating the Linux emulation layer (the so called Linuxulator). The task was to update the layer to match the functionality of " "Linux 2.6. As a reference " "implementation, the Linux 2.6.16 " "kernel was chosen. The concept is loosely based on the NetBSD " "implementation. Most of the work was done in the summer of 2006 as a part of " "the Google Summer of Code students program. The focus was on bringing the " "NPTL (new POSIX thread library) support into the emulation layer, including " "TLS (thread local storage), futexes (fast user space mutexes), PID mangling, " "and some other minor things. Many small problems were identified and fixed " "in the process. My work was integrated into the main FreeBSD source " "repository and will be shipped in the upcoming 7.0R release. We, the " "emulation development team, are working on making the Linux 2.6 emulation the default emulation layer " "in FreeBSD." msgstr "" "Essa tese master lida com a atualização da camada de emulação do Linux (o chamado Linuxulator). A tarefa foi atualizar a camada para casar com a funcionalidade " "do Linux 2.6. Como uma " "referencia a implementação, o kernel Linux 2.6.16 foi escolhido. O conceito é perdidamente baseado na " "implementação do NetBSD. Maior parte do trabalho foi feito no verão de 2006 " "como parte de um programa de estudante do Google Summer of Code. O foco foi " "trazer o suporte do NPTL (nova biblioteca de threads " "POSIX) pra dentro da camada de " "emulação, incluindo TLS (thread local storage), " "futexes (mutexes rapidos na camada de usuario), " "PID mangling, e algumas outras coisas menores. Muitos " "pequenos problemas foram identificados e corrigidos. Meu trabalho foi " "integrado dentro do repositório de principal do FreeBSD e vai ser ligado ao " "7.0R release. Nós, o time de desenvolvimento de emulação estamos trabalhando " "na emulação do Linux 2.6 a " "camada de emulação padr\n" "ão do FreeBSD." #. (itstool) path: sect1/title #: article.translate.xml:82 msgid "Introduction" msgstr "Introdução" #. (itstool) path: sect1/para #: article.translate.xml:84 msgid "" "In the last few years the open source UNIX based operating systems started to be widely deployed on server " "and client machines. Among these operating systems I would like to point out " "two: FreeBSD, for its BSD heritage, time proven code base and many " "interesting features and Linux " "for its wide user base, enthusiastic open developer community and support " "from large companies. FreeBSD tends to be used on server class machines " "serving heavy duty networking tasks with less usage on desktop class " "machines for ordinary users. While Linux has the same usage on servers, but it is used much more by home " "based users. This leads to a situation where there are many binary only " "programs available for Linux " "that lack support for FreeBSD." msgstr "" "Nos últimos anos, os sistemas operacionais baseados em código aberto " "UNIX começaram a ser amplamente " "implantados em máquinas servidores e clientes. Entre esses sistemas " "operacionais eu gostaria de destacar dois: FreeBSD, por sua herança BSD, " "base de código comprovada pelo tempo e muitos recursos interessantes e " "Linux por sua ampla base de " "usuários, entusiasta comunidade aberta de desenvolvedores e apoio de grandes " "empresas. O FreeBSD tende a ser usado em máquinas de classe servidor, " "tarefas de rede pesadas com menos uso em máquinas de classe desktop para " "usuários comuns. Embora o Linux " "tenha o mesmo uso em servidores, mas é muito mais usado por usuários " "domésticos. Isto leva a uma situação onde existem muitos programas binários " "disponíveis apenas para Linux " "que não suportam o FreeBSD." #. (itstool) path: sect1/para #: article.translate.xml:98 msgid "" "Naturally, a need for the ability to run Linux binaries on a FreeBSD system arises and this is what " "this thesis deals with: the emulation of the Linux kernel in the FreeBSD operating system." msgstr "" "Naturalmente, surge a necessidade da habilidade de executar binários " "Linux em um sistema FreeBSD e é " "com isso que esta tese trata: a emulação do kernel do Linux no sistema operacional FreeBSD." #. (itstool) path: sect1/para #: article.translate.xml:103 msgid "" "During the Summer of 2006 Google Inc. sponsored a project which focused on " "extending the Linux emulation " "layer (the so called Linuxulator) in FreeBSD to include Linux 2.6 facilities. This thesis is written as a " "part of this project." msgstr "" "Durante o verão de 2006, a Google Inc. patrocinou um projeto que se " "concentrava em estender a camada de emulação do Linux (o chamado Linuxulator) no FreeBSD para incluir " "necessidades do Linux 2.6. Esta " "tese é escrita como parte deste projeto." #. (itstool) path: sect1/title #: article.translate.xml:110 msgid "A look inside…" msgstr "Um olhar para dentro ..." #. (itstool) path: sect1/para #: article.translate.xml:112 msgid "" "In this section we are going to describe every operating system in question. " "How they deal with syscalls, trapframes etc., all the low-level stuff. We " "also describe the way they understand common UNIX primitives like what a PID is, what a thread is, etc. In " "the third subsection we talk about how UNIX on UNIX emulation " "could be done in general." msgstr "" "Nesta seção vamos descrever cada sistema operacional em questão. Como eles " "lidam com syscalls, trapframes etc., todo o material de baixo nível. Também " "descrevemos a maneira como eles entendem primitivas comuns UNIX, como o que é um PID, o que é uma thread, " "etc. Na terceira subseção, falamos sobre como UNIX em emuladores UNIX pode ser feita em geral." #. (itstool) path: sect2/title #: article.translate.xml:120 msgid "What is UNIX" msgstr "O que é o UNIX ?" #. (itstool) path: sect2/para #: article.translate.xml:122 msgid "" "UNIX is an operating system with " "a long history that has influenced almost every other operating system " "currently in use. Starting in the 1960s, its development continues to this " "day (although in different projects). UNIX development soon forked into two main ways: the BSDs and System " "III/V families. They mutually influenced themselves by growing a common " "UNIX standard. Among the " "contributions originated in BSD we can name virtual memory, TCP/IP " "networking, FFS, and many others. The System V branch contributed to SysV " "interprocess communication primitives, copy-on-write, etc. UNIX itself does not exist any more but its ideas " "have been used by many other operating systems world wide thus forming the " "so called UNIX-like operating " "systems. These days the most influential ones are Linux, Solaris, and possibly (to some extent) " "FreeBSD. There are in-company UNIX derivatives (AIX, HP-UX etc.), but these have been more and more " "migrated to the aforementioned systems. Let us summarize typical UNIX characteristics." msgstr "" "UNIX é um sistema operacional " "com um longo histórico que influenciou quase todos os outros sistemas " "operacionais atualmente em uso. Começando na década de 1960, seu " "desenvolvimento continua até hoje (embora em projetos diferentes). O " "desenvolvimento de UNIX logo se " "bifurcou em duas formas principais: as famílias BSDs e System III/V. Eles se " "influenciaram mutuamente ao desenvolver um padrão UNIX comum. Entre as contribuições originadas no " "BSD, podemos nomear memória virtual, rede TCP/IP, FFS e muitas outras. A " "ramificação SystemV contribuiu para as primitivas de comunicação entre " "processos SysV, copy-on-write, etc. UNIX em si não existe mais, mas suas idéias têm sido usadas por muitos " "outros sistemas operacionais amplos formando assim os chamados sistemas " "operacionais como UNIX. Hoje em " "dia os mais influentes são Linux, Solaris e possivelmente (até certo ponto) FreeBSD. Existem " "sistemas UNIX de companhias " "derivados como (AIX, HP-UX etc.), mas estas foram cada vez mais migrados " "para os sistemas acima mencionados. Vamos resumir as características típicas " "do UNIX." #. (itstool) path: sect2/title #. (itstool) path: sect3/title #: article.translate.xml:143 article.translate.xml:312 #: article.translate.xml:491 msgid "Technical details" msgstr "Detalhes técnicos" #. (itstool) path: sect2/para #: article.translate.xml:145 msgid "" "Every running program constitutes a process that represents a state of the " "computation. Running process is divided between kernel-space and user-space. " "Some operations can be done only from kernel space (dealing with hardware " "etc.), but the process should spend most of its lifetime in the user space. " "The kernel is where the management of the processes, hardware, and low-level " "details take place. The kernel provides a standard unified UNIX API to the user space. The most important " "ones are covered below." msgstr "" "Todo programa em execução constitui um processo que representa um estado da " "computação. O processo de execução é dividido entre o espaço do kernel e o " "espaço do usuário. Algumas operações podem ser feitas somente a partir do " "espaço do kernel (lidando com hardware, etc.), mas o processo deve passar a " "maior parte de sua vida útil no espaço do usuário. O kernel é onde o " "gerenciamento dos processos, hardware e detalhes de baixo nível acontecem. O " "kernel fornece uma API unificada padrão UNIX para o espaço do usuário. Os mais importantes são " "abordados abaixo." #. (itstool) path: sect3/title #: article.translate.xml:156 msgid "Communication between kernel and user space process" msgstr "Comunicação entre o kernel e o processo de espaço do usuário" #. (itstool) path: sect3/para #: article.translate.xml:159 msgid "" "Common UNIX API defines a " "syscall as a way to issue commands from a user space process to the kernel. " "The most common implementation is either by using an interrupt or " "specialized instruction (think of SYSENTER/" "SYSCALL instructions for ia32). Syscalls are defined by a " "number. For example in FreeBSD, the syscall number 85 is the " "swapon2 syscall and the syscall number 132 is " "mkfifo2. Some syscalls need parameters, which are passed from the user-" "space to the kernel-space in various ways (implementation dependant). " "Syscalls are synchronous." msgstr "" "A API comum do UNIX define uma " "syscall como uma forma de emitir comandos de um processo do espaço do " "usuário para o kernel. A implementação mais comum é usando uma instrução de " "interrupção ou especializada (pense em instruções SYSENTER/SYSCALL para ia32). Syscalls são definidos por " "um número. Por exemplo, no FreeBSD, a syscall número 85 é a syscall " "swapon2 e a syscall número 132 é a syscall " "mkfifo2. Algumas syscalls precisam de parâmetros, que são passados ​​do " "espaço do usuário para o espaço do kernel de várias maneiras (dependente da " "implementação). Syscalls são síncronas." #. (itstool) path: sect3/para #: article.translate.xml:172 msgid "" "Another possible way to communicate is by using a trap. Traps occur asynchronously after some event occurs (division by " "zero, page fault etc.). A trap can be transparent for a process (page fault) " "or can result in a reaction like sending a signal " "(division by zero)." msgstr "" "Outra maneira possível de se comunicar é usando uma trap. As traps ocorrem de forma assíncrona após a ocorrência de algum " "evento (divisão por zero, falha de página, etc.). Uma trap pode ser " "transparente para um processo (falha de página) ou pode resultar em uma " "reação como o envio de um signal (divisão por zero)." #. (itstool) path: sect3/title #: article.translate.xml:181 msgid "Communication between processes" msgstr "Comunicação entre processos" #. (itstool) path: sect3/para #: article.translate.xml:183 msgid "" "There are other APIs (System V IPC, shared memory etc.) but the single most " "important API is signal. Signals are sent by processes or by the kernel and " "received by processes. Some signals can be ignored or handled by a user " "supplied routine, some result in a predefined action that cannot be altered " "or ignored." msgstr "" "Existem outras APIs (System V IPC, memória compartilhada, etc.), mas a API " "mais importante é o signal. Os signals são enviados por processos ou pelo " "kernel e recebidos por processos. Alguns signals podem ser ignorados ou " "manipulados por uma rotina fornecida pelo usuário, alguns resultam em uma " "ação predefinida que não pode ser alterada ou ignorada." #. (itstool) path: sect3/title #: article.translate.xml:192 msgid "Process management" msgstr "Gerenciamento de processos" #. (itstool) path: sect3/para #: article.translate.xml:194 msgid "" "Kernel instances are processed first in the system (so called init). Every " "running process can create its identical copy using the " "fork2 syscall. Some slightly modified versions of this syscall were " "introduced but the basic semantic is the same. Every running process can " "morph into some other process using the exec3 syscall. Some " "modifications of this syscall were introduced but all serve the same basic " "purpose. Processes end their lives by calling the " "exit2 syscall. Every process is identified by a unique number called " "PID. Every process has a defined parent (identified by its PID)." msgstr "" "As instâncias do kernel são processadas primeiro no sistema (chamado init). " "Todo processo em execução pode criar sua cópia idêntica usando a syscall " "fork2 . Algumas versões ligeiramente modificadas desta syscall foram " "introduzidas, mas a semântica básica é a mesma. Todo processo em execução " "pode se transformar em algum outro processo usando a syscall " "exec3. Algumas modificações desta syscall foram introduzidas, mas " "todas servem ao mesmo propósito básico. Os processos terminam suas vidas " "chamando a syscall exit2. Todo processo é " "identificado por um número único chamado PID. Todo processo tem um processo " "pai definido (identificado pelo seu PID)." #. (itstool) path: sect3/title #: article.translate.xml:208 msgid "Thread management" msgstr "Gerenciamento de threads" #. (itstool) path: sect3/para #: article.translate.xml:210 msgid "" "Traditional UNIX does not define " "any API nor implementation for threading, while POSIX defines its threading API but the implementation is " "undefined. Traditionally there were two ways of implementing threads. " "Handling them as separate processes (1:1 threading) or envelope the whole " "thread group in one process and managing the threading in userspace (1:N " "threading). Comparing main features of each approach:" msgstr "" "O UNIX tradicional não define " "nenhuma API nem implementação para threading, enquanto POSIX define sua API de threading, mas a " "implementação é indefinida. Tradicionalmente, havia duas maneiras de " "implementar threads. Manipulando-as como processos separados (threading 1:1) " "ou envolver todo o grupo de thread em um processo e gerenciando a threading " "no espaço do usuário (threading 1:N). Comparando as principais " "características de cada abordagem:" #. (itstool) path: sect3/para #: article.translate.xml:219 msgid "1:1 threading" msgstr "1:1 threading" #. (itstool) path: listitem/para #: article.translate.xml:223 msgid "- heavyweight threads" msgstr "- threads pesadas" #. (itstool) path: listitem/para #: article.translate.xml:226 msgid "" "- the scheduling cannot be altered by the user (slightly mitigated by the " "POSIX API)" msgstr "" "- o agendamento não pode ser alterado pelo usuário (ligeiramente mitigado " "pela API POSIX )" #. (itstool) path: listitem/para #: article.translate.xml:230 msgid "+ no syscall wrapping necessary" msgstr "+ não necessita de envolvimento do syscall" #. (itstool) path: listitem/para #: article.translate.xml:233 msgid "+ can utilize multiple CPUs" msgstr "+ pode utilizar várias CPUs" #. (itstool) path: sect3/para #: article.translate.xml:237 msgid "1:N threading" msgstr "1: N threading" #. (itstool) path: listitem/para #: article.translate.xml:241 msgid "+ lightweight threads" msgstr "+ threads leves" #. (itstool) path: listitem/para #: article.translate.xml:244 msgid "+ scheduling can be easily altered by the user" msgstr "+ agendamento pode ser facilmente alterado pelo usuário" #. (itstool) path: listitem/para #: article.translate.xml:248 msgid "- syscalls must be wrapped" msgstr "- syscalls devem ser acondicionadas" #. (itstool) path: listitem/para #: article.translate.xml:251 msgid "- cannot utilize more than one CPU" msgstr "- não pode utilizar mais de uma CPU" #. (itstool) path: sect2/title #: article.translate.xml:258 msgid "What is FreeBSD?" msgstr "O que é o FreeBSD?" #. (itstool) path: sect2/para #: article.translate.xml:260 msgid "" "The FreeBSD project is one of the oldest open source operating systems " "currently available for daily use. It is a direct descendant of the genuine " "UNIX so it could be claimed that " "it is a true UNIX although " "licensing issues do not permit that. The start of the project dates back to " "the early 1990's when a crew of fellow BSD users patched the 386BSD " "operating system. Based on this patchkit a new operating system arose named " "FreeBSD for its liberal license. Another group created the NetBSD operating " "system with different goals in mind. We will focus on FreeBSD." msgstr "" "O projeto FreeBSD é um dos mais antigos sistemas operacionais de código " "aberto atualmente disponíveis para uso diário. É um descendente direto do " "verdadeiro UNIX, portanto, pode-" "se afirmar que ele é um verdadeiro UNIX embora os problemas de licenciamento não permitam isso. O início " "do projeto remonta ao início dos anos 90, quando uma equipe de usuários BSD " "corrigiu o sistema operacional 386BSD. Baseado neste patchkit surgiu um novo " "sistema operacional, chamado FreeBSD por sua licença liberal. Outro grupo " "criou o sistema operacional NetBSD com diferentes objetivos em mente. Vamos " "nos concentrar no FreeBSD." #. (itstool) path: sect2/para #: article.translate.xml:271 msgid "" "FreeBSD is a modern UNIX-based " "operating system with all the features of UNIX. Preemptive multitasking, multiuser facilities, TCP/IP " "networking, memory protection, symmetric multiprocessing support, virtual " "memory with merged VM and buffer cache, they are all there. One of the " "interesting and extremely useful features is the ability to emulate other " "UNIX-like operating systems. As " "of December 2006 and 7-CURRENT development, the following emulation " "functionalities are supported:" msgstr "" "O FreeBSD é um sistema operacional baseado no UNIX com todos os recursos do UNIX. Multitarefa preemptiva, necessidades de multiusuário, " "rede TCP/IP, proteção de memória, suporte a multiprocessamento simétrico, " "memória virtual com VM mesclada e cache de buffer, todos eles estão lá. Um " "dos recursos interessantes e extremamente úteis é a capacidade de emular " "outros sistemas operacionais UNIX-like. A partir de dezembro de 2006 e do desenvolvimento do 7-" "CURRENT, as seguintes funcionalidades de emulação são suportadas:" #. (itstool) path: listitem/para #: article.translate.xml:283 msgid "FreeBSD/i386 emulation on FreeBSD/amd64" msgstr "Emulação FreeBSD/i386 no FreeBSD/amd64" #. (itstool) path: listitem/para #: article.translate.xml:286 msgid "FreeBSD/i386 emulation on FreeBSD/ia64" msgstr "Emulação de FreeBSD/i386 no FreeBSD/ia64" #. (itstool) path: listitem/para #: article.translate.xml:289 msgid "" "Linux-emulation of Linux operating system on FreeBSD" msgstr "" "Emulação-Linux do sistema " "operacional Linux no FreeBSD" #. (itstool) path: listitem/para #: article.translate.xml:293 msgid "NDIS-emulation of Windows networking drivers interface" msgstr "Emulação de NDIS da interface de drivers de rede do Windows" #. (itstool) path: listitem/para #: article.translate.xml:297 msgid "NetBSD-emulation of NetBSD operating system" msgstr "Emulação de NetBSD do sistema operacional NetBSD" #. (itstool) path: listitem/para #: article.translate.xml:300 msgid "PECoff-support for PECoff FreeBSD executables" msgstr "Suporte PECoff para executáveis PECoff ​​do FreeBSD" #. (itstool) path: listitem/para #: article.translate.xml:303 msgid "" "SVR4-emulation of System V revision 4 UNIX" msgstr "" "Emulação SVR4 do UNIX System V " "revisão 4 " #. (itstool) path: sect2/para #: article.translate.xml:307 msgid "" "Actively developed emulations are the Linux layer and various FreeBSD-on-FreeBSD layers. Others are not " "supposed to work properly nor be usable these days." msgstr "" "Emulações ativamente desenvolvidas são a camada Linux e várias camadas FreeBSD-on-FreeBSD. Outros não devem " "funcionar corretamente nem ser utilizáveis ​​nos dias de hoje." #. (itstool) path: sect3/para #: article.translate.xml:314 msgid "" "FreeBSD is traditional flavor of UNIX in the sense of dividing the run of processes into two halves: " "kernel space and user space run. There are two types of process entry to the " "kernel: a syscall and a trap. There is only one way to return. In the " "subsequent sections we will describe the three gates to/from the kernel. The " "whole description applies to the i386 architecture as the Linuxulator only " "exists there but the concept is similar on other architectures. The " "information was taken from [1] and the source code." msgstr "" "O FreeBSD é o gostinho tradicional de UNIX no sentido de dividir a execução dos processos em duas metades: " "espaço do kernel e execução do espaço do usuário. Existem dois tipos de " "entrada de processo no kernel: uma syscall e uma trap. Há apenas uma maneira " "de retornar. Nas seções subseqüentes, descreveremos as três portas de/para o " "kernel. Toda a descrição se aplica à arquitetura i386, pois o Linuxulator só " "existe lá, mas o conceito é semelhante em outras arquiteturas. A informação " "foi retirada de [1] e do código fonte." #. (itstool) path: sect4/title #: article.translate.xml:326 msgid "System entries" msgstr "Entradas do sistema" #. (itstool) path: sect4/para #: article.translate.xml:328 msgid "" "FreeBSD has an abstraction called an execution class loader, which is a " "wedge into the execve2 syscall. This employs " "a structure sysentvec, which describes an executable ABI. " "It contains things like errno translation table, signal translation table, " "various functions to serve syscall needs (stack fixup, coredumping, etc.). " "Every ABI the FreeBSD kernel wants to support must define this structure, as " "it is used later in the syscall processing code and at some other places. " "System entries are handled by trap handlers, where we can access both the " "kernel-space and the user-space at once." msgstr "" "O FreeBSD tem uma abstração chamada loader de classes de execução, que é uma " "entrada na syscall execve2. Isto emprega uma " "estrutura sysentvec, que descreve uma ABI executável. Ele " "contém coisas como tabela de tradução de errno, tabela de tradução de " "sinais, várias funções para atender às necessidades da syscall (correção de " "pilha, coredumping, etc.). Toda ABI que o kernel do FreeBSD deseja suportar " "deve definir essa estrutura, como é usado posteriormente no código de " "processamento da syscall e em alguns outros lugares. As entradas do sistema " "são tratadas pelos manipuladores de traps, onde podemos acessar o espaço do " "kernel e o espaço do usuário de uma só vez." #. (itstool) path: sect4/title #: article.translate.xml:343 article.translate.xml:502 msgid "Syscalls" msgstr "Syscalls" #. (itstool) path: sect4/para #: article.translate.xml:345 msgid "" "Syscalls on FreeBSD are issued by executing interrupt 0x80 with register %eax set to a desired syscall " "number with arguments passed on the stack." msgstr "" "Syscalls no FreeBSD são emitidos executando a interrupção 0x80 com o registrador %eax definido para um número " "de syscall desejado com argumentos passados ​​na pilha." #. (itstool) path: sect4/para #: article.translate.xml:350 msgid "" "When a process issues an interrupt 0x80, the " "int0x80 syscall trap handler is issued (defined in " "sys/i386/i386/exception.s), which prepares arguments (i." "e. copies them on to the stack) for a call to a C function " "syscall2 (defined in sys/i386/i386/trap.c), which processes the passed in trapframe. The processing consists " "of preparing the syscall (depending on the sysvec entry), " "determining if the syscall is 32-bit or 64-bit one (changes size of the " "parameters), then the parameters are copied, including the syscall. Next, " "the actual syscall function is executed with processing of the return code " "(special cases for ERESTART and EJUSTRETURN errors). Finally an userret() is scheduled, " "switching the process back to the users-pace. The parameters to the actual " "syscall handler are passed in the form of struct thread *td, struct syscall args * arguments where the " "second parameter is a pointer to the copied in structure of parameters." msgstr "" "Quando um processo emite uma interrupção 0x80, a syscall " "manipuladora de trap int0x80 é proclamada (definida em " "sys/i386/i386/exception.s), que prepara argumentos (ou " "seja, copia-os para a pilha) para uma chamada para uma função C " "syscall2 (definida em sys/i386/i386/trap.c), que processa o trapframe passado. O processamento consiste em " "preparar a syscall (dependendo da entrada sysvec), " "determinando se a syscall é de 32 ou 64 bits (muda o tamanho dos " "parâmetros), então os parâmetros são copiados, incluindo a syscall. Em " "seguida, a função syscall real é executada com o processamento do código de " "retorno (casos especiais para erros ERESTART e " "EJUSTRETURN). Finalmente, um userret() " "é agendado, trocando o processo de volta ao ritmo do usuário. Os parâmetros " "para a syscall manipuladora atual são passados ​​na forma de argumentos " "struct thread *td , struct syscall args* onde o segundo parâmetro é um ponteiro para o copiado na estrutura " "de parâmetros." #. (itstool) path: sect4/title #. (itstool) path: sect2/title #: article.translate.xml:376 article.translate.xml:548 #: article.translate.xml:1482 msgid "Traps" msgstr "Armadilhas (Traps)" #. (itstool) path: sect4/para #: article.translate.xml:378 msgid "" "Handling of traps in FreeBSD is similar to the handling of syscalls. " "Whenever a trap occurs, an assembler handler is called. It is chosen between " "alltraps, alltraps with regs pushed or calltrap depending on the type of the " "trap. This handler prepares arguments for a call to a C function " "trap() (defined in sys/i386/i386/trap.c), which then processes the occurred trap. After the processing it " "might send a signal to the process and/or exit to userland using " "userret()." msgstr "" "O manuseio de traps no FreeBSD é similar ao manuseio de syscalls. Sempre que " "ocorre uma trap, um manipulador de assembler é chamado. É escolhido entre " "alltraps, alltraps com regs push ou calltrap, dependendo do tipo de trap. " "Este manipulador prepara argumentos para uma chamada para uma função C " "trap() (definida em sys/i386/i386/trap.c), que então processa a trap ocorrida. Após o processamento, ele " "pode enviar um sinal para o processo e/ou sair para o espaço do usuário " "usando userret()." #. (itstool) path: sect4/title #: article.translate.xml:391 article.translate.xml:558 msgid "Exits" msgstr "Saídas" #. (itstool) path: sect4/para #: article.translate.xml:393 msgid "" "Exits from kernel to userspace happen using the assembler routine " "doreti regardless of whether the kernel was entered via a " "trap or via a syscall. This restores the program status from the stack and " "returns to the userspace." msgstr "" "As saídas do kernel para o userspace acontecem usando a rotina assembler " "doreti, independentemente de o kernel ter sido acessado " "por meio de uma trap ou via syscall. Isso restaura o status do programa da " "pilha e retorna ao espaço do usuário." #. (itstool) path: sect4/title #: article.translate.xml:401 article.translate.xml:569 msgid "UNIX primitives" msgstr "primitivas UNIX" #. (itstool) path: sect4/para #: article.translate.xml:403 msgid "" "FreeBSD operating system adheres to the traditional UNIX scheme, where every process has a unique " "identification number, the so called PID (Process " "ID). PID numbers are allocated either linearly or randomly ranging from " "0 to PID_MAX. The allocation of PID " "numbers is done using linear searching of PID space. Every thread in a " "process receives the same PID number as result of the " "getpid2 call." msgstr "" "O sistema operacional FreeBSD adere ao esquema tradicional UNIX, onde cada processo possui um número de " "identificação único, o chamado PID (ID do processo). " "Números PID são alocados de forma linear ou aleatória variando de " "0 para PID_MAX. A alocação de números " "PID é feita usando pesquisa linear de espaço PID. Cada thread em um processo " "recebe o mesmo número PID como resultado da chamada " "getpid2." #. (itstool) path: sect4/para #: article.translate.xml:413 msgid "" "There are currently two ways to implement threading in FreeBSD. The first " "way is M:N threading followed by the 1:1 threading model. The default " "library used is M:N threading (libpthread) and you can " "switch at runtime to 1:1 threading (libthr). The plan is " "to switch to 1:1 library by default soon. Although those two libraries use " "the same kernel primitives, they are accessed through different API(es). The " "M:N library uses the kse_* family of syscalls while the " "1:1 library uses the thr_* family of syscalls. Because of " "this, there is no general concept of thread ID shared between kernel and " "userspace. Of course, both threading libraries implement the pthread thread " "ID API. Every kernel thread (as described by struct thread) has td tid identifier but this is not directly accessible from " "userland and solely serves the kernel's needs. It is also used for 1:1 " "threading library as pthread's thread ID but handling of this is internal to " "the library and cannot be relied on." msgstr "" "Atualmente existem duas maneiras de implementar o threading no FreeBSD. A " "primeira maneira é o threading M:N seguido pelo modelo de threading 1:1. A " "biblioteca padrão usada é o threading M:N (libpthread) e " "você pode alternar no tempo de execução para threading 1:1 (libthr). O plano é mudar para a biblioteca 1:1 por padrão em breve. Embora " "essas duas bibliotecas usem as mesmas primitivas do kernel, elas são " "acessadas por API(s) diferentes. A biblioteca M:N usa a família " "kse_* das syscalls enquanto a biblioteca 1:1 usa a " "família thr_* das syscalls. Por causa disso, não existe " "um conceito geral de ID de threading compartilhado entre o kernel e o espaço " "do usuário. Obviamente, as duas bibliotecas de threads implementam a API de " "ID de threading pthread. Todo threading do kernel (como descrito por " "struct thread) possui identificadores td tid, mas isso " "não é diretamente acessível a partir do espaço do usuário e serve apenas as " "necessidades do kernel. Ele também é usado para a biblioteca de threading " "1:1 como o ID de threading do pthread, mas a manipulação desta é interna à " "biblioteca e não pode ser confiável." #. (itstool) path: sect4/para #: article.translate.xml:434 msgid "" "As stated previously there are two implementations of threading in FreeBSD. " "The M:N library divides the work between kernel space and userspace. Thread " "is an entity that gets scheduled in the kernel but it can represent various " "number of userspace threads. M userspace threads get mapped to N kernel " "threads thus saving resources while keeping the ability to exploit " "multiprocessor parallelism. Further information about the implementation can " "be obtained from the man page or [1]. The 1:1 library directly maps a " "userland thread to a kernel thread thus greatly simplifying the scheme. None " "of these designs implement a fairness mechanism (such a mechanism was " "implemented but it was removed recently because it caused serious slowdown " "and made the code more difficult to deal with)." msgstr "" "Como dito anteriormente, existem duas implementações de threads no FreeBSD. " "A biblioteca M:N divide o trabalho entre o espaço do kernel e o espaço do " "usuário. Thread é uma entidade que é agendada no kernel, mas pode " "representar vários números de threads do userspace. Threads M do userspace " "são mapeadas para threads N do kernel, economizando recursos e mantendo a " "capacidade de explorar o paralelismo de multiprocessadores. Mais informações " "sobre a implementação podem ser obtidas na página do manual ou [1]. A " "biblioteca 1:1 mapeia diretamente um segmento userland para uma thread do " "kernel, simplificando muito o esquema. Nenhum desses designs implementa um " "mecanismo justo (tal mecanismo foi implementado, mas foi removido " "recentemente porque causou séria lentidão e tornou o código mais difícil de " "lidar)." #. (itstool) path: sect2/title #: article.translate.xml:454 msgid "What is Linux" msgstr "O que é Linux" #. (itstool) path: sect2/para #: article.translate.xml:456 msgid "" "Linux is a UNIX-like kernel originally developed by Linus " "Torvalds, and now being contributed to by a massive crowd of programmers all " "around the world. From its mere beginnings to today, with wide support from " "companies such as IBM or Google, Linux is being associated with its fast development pace, full hardware " "support and benevolent dictator model of organization." msgstr "" "Linux é um kernel do tipo " "UNIX originalmente desenvolvido " "por Linus Torvalds, e agora está sendo contribuído por uma grande quantidade " "de programadores em todo o mundo. De seu simples começo até hoje, com amplo " "suporte de empresas como IBM ou Google, o Linux está sendo associado ao seu rápido ritmo de " "desenvolvimento, suporte completo a hardware e seu benevolente modelo " "despota de organização." #. (itstool) path: sect2/para #: article.translate.xml:464 msgid "" "Linux development started in " "1991 as a hobbyist project at University of Helsinki in Finland. Since then " "it has obtained all the features of a modern UNIX-like OS: multiprocessing, multiuser support, virtual " "memory, networking, basically everything is there. There are also highly " "advanced features like virtualization etc." msgstr "" "O desenvolvimento do Linux " "começou em 1991 como um projeto amador na Universidade de Helsinque na " "Finlândia. Desde então, ele obteve todos os recursos de um sistema " "operacional semelhante ao UNIX: multiprocessamento, suporte multiusuário, " "memória virtual, rede, basicamente tudo está lá. Também há recursos " "altamente avançados, como virtualização, etc." #. (itstool) path: sect2/para #: article.translate.xml:471 msgid "" "As of 2006 Linux seems to be the " "most widely used open source operating system with support from independent " "software vendors like Oracle, RealNetworks, Adobe, etc. Most of the " "commercial software distributed for Linux can only be obtained in a binary form so recompilation for other " "operating systems is impossible." msgstr "" "A partir de 2006, o Linux parece ser o sistema operacional de código aberto " "mais utilizado com o apoio de fornecedores independentes de software como " "Oracle, RealNetworks, Adobe, etc. A maioria dos softwares comerciais " "distribuídos para Linux só pode " "ser obtido de forma binária, portanto a recompilação para outros sistemas " "operacionais é impossível." #. (itstool) path: sect2/para #: article.translate.xml:478 msgid "" "Most of the Linux development " "happens in a Git version control system. " "Git is a distributed system so there is no " "central source of the Linux " "code, but some branches are considered prominent and official. The version " "number scheme implemented by Linux consists of four numbers A.B.C.D. Currently development happens " "in 2.6.C.D, where C represents major version, where new features are added " "or changed while D is a minor version for bugfixes only." msgstr "" "A maior parte do desenvolvimento do Linux acontece em um sistema de controle de versão Git. O Git é um sistema distribuído, de " "modo que não existe uma fonte central do código Linux, mas algumas ramificações são consideradas proeminentes " "e oficiais. O esquema de número de versão implementado pelo Linux consiste em quatro números A.B.C.D. " "Atualmente, o desenvolvimento acontece em 2.6.C.D, onde C representa a " "versão principal, onde novos recursos são adicionados ou alterados, enquanto " "D é uma versão secundária somente para correções de bugs." #. (itstool) path: sect2/para #: article.translate.xml:488 msgid "More information can be obtained from [3]." msgstr "Mais informações podem ser obtidas em [3]." #. (itstool) path: sect3/para #: article.translate.xml:493 msgid "" "Linux follows the traditional " "UNIX scheme of dividing the run " "of a process in two halves: the kernel and user space. The kernel can be " "entered in two ways: via a trap or via a syscall. The return is handled only " "in one way. The further description applies to Linux 2.6 on the i386 architecture. " "This information was taken from [2]." msgstr "" "O Linux segue o esquema " "tradicional do UNIX de dividir a " "execução de um processo em duas metades: o kernel e o espaço do usuário. O " "kernel pode ser inserido de duas maneiras: via trap ou via syscall. O " "retorno é tratado apenas de uma maneira. A descrição mais detalhada aplica-" "se ao Linux 2.6 na arquitetura " "i386. Esta informação foi retirada de [2]." #. (itstool) path: sect4/para #: article.translate.xml:504 msgid "" "Syscalls in Linux are performed " "(in userspace) using syscallX macros where X substitutes " "a number representing the number of parameters of the given syscall. This " "macro translates to a code that loads %eax register with " "a number of the syscall and executes interrupt 0x80. " "After this syscall return is called, which translates negative return values " "to positive errno values and sets res " "to -1 in case of an error. Whenever the interrupt " "0x80 is called the process enters the kernel in system " "call trap handler. This routine saves all registers on the stack and calls " "the selected syscall entry. Note that the Linux calling convention expects parameters to the syscall to " "be passed via registers as shown here:" msgstr "" "Syscalls em Linux são executados " "(no espaço de usuário) usando macros syscallX onde X " "substitui um número que representa o número de parâmetros da syscall dada. " "Essa macro traduz um código que carrega o registro % eax " "com um número da syscall e executa a interrupção 0x80. " "Depois disso, um retorn da syscall é chamado, o que traduz valores de " "retorno negativos para valores errno positivos e define " "res para -1 em caso de erro. Sempre " "que a interrupção 0x80 é chamada, o processo entra no " "kernel no manipulador de trap das syscalls. Essa rotina salva todos os " "registros na pilha e chama a entrada syscall selecionada. Note que a " "convenção de chamadas Linux " "espera que os parâmetros para o syscall sejam passados ​​pelos registradores " "como mostrado aqui:" #. (itstool) path: listitem/para #: article.translate.xml:523 msgid "parameter -> %ebx" msgstr "parameter -> %ebx" #. (itstool) path: listitem/para #: article.translate.xml:526 msgid "parameter -> %ecx" msgstr "parameter -> %ecx" #. (itstool) path: listitem/para #: article.translate.xml:529 msgid "parameter -> %edx" msgstr "parameter -> %edx" #. (itstool) path: listitem/para #: article.translate.xml:532 msgid "parameter -> %esi" msgstr "parameter -> %esi" #. (itstool) path: listitem/para #: article.translate.xml:535 msgid "parameter -> %edi" msgstr "parameter -> %edi" #. (itstool) path: listitem/para #: article.translate.xml:538 msgid "parameter -> %ebp" msgstr "parameter -> %ebp" #. (itstool) path: sect4/para #: article.translate.xml:542 msgid "" "There are some exceptions to this, where Linux uses different calling convention (most notably the " "clone syscall)." msgstr "" "Existem algumas exceções, onde Linux usa diferentes convenções de chamada (mais notavelmente a syscall " "clone)." #. (itstool) path: sect4/para #: article.translate.xml:550 msgid "" "The trap handlers are introduced in arch/i386/kernel/traps.c and most of these handlers live in arch/i386/kernel/" "entry.S, where handling of the traps happens." msgstr "" "Os manipuladores de traps são apresentados em arch/i386/kernel/" "traps.c e a maioria desses manipuladores vive em arch/" "i386/kernel/entry.S, onde a manipulação das traps acontecem." #. (itstool) path: sect4/para #: article.translate.xml:560 msgid "" "Return from the syscall is managed by syscall " "exit3, which checks for the process having unfinished work, then " "checks whether we used user-supplied selectors. If this happens stack fixing " "is applied and finally the registers are restored from the stack and the " "process returns to the userspace." msgstr "" "O retorno da syscall é gerenciado pela syscall " "exit3, que verifica se o processo não está concluído e verifica se " "usamos seletores fornecidos pelo usuário . Se isso acontecer, a correção da " "pilha é aplicada e, finalmente, os registros são restaurados da pilha e o " "processo retorna ao espaço do usuário." #. (itstool) path: sect4/para #: article.translate.xml:571 msgid "" "In the 2.6 version, the Linux " "operating system redefined some of the traditional UNIX primitives, notably PID, TID and thread. PID " "is defined not to be unique for every process, so for some processes " "(threads) getppid2 returns the same value. Unique identification of " "process is provided by TID. This is because NPTL (New " "POSIX Thread Library) defines " "threads to be normal processes (so called 1:1 threading). Spawning a new " "process in Linux 2.6 happens " "using the clone syscall (fork variants are reimplemented " "using it). This clone syscall defines a set of flags that affect behavior of " "the cloning process regarding thread implementation. The semantic is a bit " "fuzzy as there is no single flag telling the syscall to create a thread." msgstr "" "Na versão 2.6, o sistema operacional Linux redefiniu algumas das primitivas tradicionais do UNIX, especialmente PID, TID e thread. O PID é " "definido para não ser exclusivo para cada processo, portanto, para alguns " "processos (threading) getppid2 retorna o mesmo valor. " "A identificação exclusiva do processo é fornecida pelo TID. Isso ocorre " "porque o NPTL (Nova Biblioteca de threading " "POSIX) define threading para " "serem processos normais (assim chamado threading 1:1). Gerar um novo " "processo no Linux 2.6 acontece " "usando a syscall clone (as variantes do fork são " "reimplementadas usando-o). Esta syscall clone define um conjunto de " "sinalizadores que afetam o comportamento do processo de clonagem em relação " "à implementação do threading. A semântica é um pouco confusa, pois não " "existe uma única bandeira dizendo a syscall para criar uma thread." #. (itstool) path: sect4/para #: article.translate.xml:588 msgid "Implemented clone flags are:" msgstr "Flags de clone implementados são:" #. (itstool) path: listitem/para #: article.translate.xml:592 msgid "CLONE_VM - processes share their memory space" msgstr "" "CLONE_VM - os processos compartilham seu espaço de memória" #. (itstool) path: listitem/para #: article.translate.xml:596 msgid "CLONE_FS - share umask, cwd and namespace" msgstr "CLONE_FS - compartilha umask, cwd e namespace" #. (itstool) path: listitem/para #: article.translate.xml:600 msgid "CLONE_FILES - share open files" msgstr "CLONE_FILES - compartilham arquivos abertos" #. (itstool) path: listitem/para #: article.translate.xml:604 msgid "" "CLONE_SIGHAND - share signal handlers and blocked signals" msgstr "" "CLONE_SIGHAND - compartilha manipuladores de sinais e " "bloqueia sinais" #. (itstool) path: listitem/para #: article.translate.xml:608 msgid "CLONE_PARENT - share parent" msgstr "CLONE_PARENT - compartilha processo pai" #. (itstool) path: listitem/para #: article.translate.xml:612 msgid "CLONE_THREAD - be thread (further explanation below)" msgstr "" "CLONE_THREAD - ser a thread (mais explicações abaixo)" #. (itstool) path: listitem/para #: article.translate.xml:616 msgid "CLONE_NEWNS - new namespace" msgstr "CLONE_NEWNS - novo namespace" #. (itstool) path: listitem/para #: article.translate.xml:620 msgid "CLONE_SYSVSEM - share SysV undo structures" msgstr "CLONE_SYSVSEM - compartilha SysV sob estruturas" #. (itstool) path: listitem/para #: article.translate.xml:624 msgid "CLONE_SETTLS - setup TLS at supplied address" msgstr "" "CLONE_SETTLS - configura o TLS no endereço fornecido" #. (itstool) path: listitem/para #: article.translate.xml:628 msgid "CLONE_PARENT_SETTID - set TID in the parent" msgstr "CLONE_PARENT_SETTID - define o TID no processo pai" #. (itstool) path: listitem/para #: article.translate.xml:632 msgid "CLONE_CHILD_CLEARTID - clear TID in the child" msgstr "" "CLONE_CHILD_CLEARTID - limpe o TID no processo filho" #. (itstool) path: listitem/para #: article.translate.xml:636 msgid "CLONE_CHILD_SETTID - set TID in the child" msgstr "CLONE_CHILD_SETTID - define o TID no processo filho" #. (itstool) path: sect4/para #: article.translate.xml:641 msgid "" "CLONE_PARENT sets the real parent to the parent of the " "caller. This is useful for threads because if thread A creates thread B we " "want thread B to be parented to the parent of the whole thread group. " "CLONE_THREAD does exactly the same thing as " "CLONE_PARENT, CLONE_VM and " "CLONE_SIGHAND, rewrites PID to be the same as PID of the " "caller, sets exit signal to be none and enters the thread group. " "CLONE_SETTLS sets up GDT entries for TLS handling. The " "CLONE_*_*TID set of flags sets/clears user supplied " "address to TID or 0." msgstr "" "CLONE_PARENT define o processo real para o processo pai " "do requisitante. Isso é útil para threads porque, se a thread A criar a " "thread B, queremos que a thread B parenteada para o processo pai de todo o " "grupo de threads. CLONE_THREAD faz exatamente a mesma " "coisa que CLONE_PARENT, CLONE_VM e " "CLONE_SIGHAND, reescreve o PID para ser o mesmo que PID " "do requisitante, define o sinal de saída como none e entra no grupo de " "threads. CLONE_SETTLS configura entradas GDT para " "tratamento de TLS. O conjunto de flags CLONE_*_*TID " "define/limpa o endereço fornecido pelo usuário para TID ou 0." #. (itstool) path: sect4/para #: article.translate.xml:655 msgid "" "As you can see the CLONE_THREAD does most of the work and " "does not seem to fit the scheme very well. The original intention is unclear " "(even for authors, according to comments in the code) but I think originally " "there was one threading flag, which was then parcelled among many other " "flags but this separation was never fully finished. It is also unclear what " "this partition is good for as glibc does not use that so only hand-written " "use of the clone permits a programmer to access this features." msgstr "" "Como você pode ver, o CLONE_THREAD faz a maior parte do " "trabalho e não parece se encaixar muito bem no esquema. A intenção original " "não é clara (mesmo para autores, de acordo com comentários no código), mas " "acho que originalmente havia uma flag de thread, que foi então dividida " "entre muitas outras flags, mas essa separação nunca foi totalmente " "concluída. Também não está claro para que serve esta partição, uma vez que a " "glibc não usa isso, portanto, apenas o uso do clone escrito à mão permite " "que um programador acesse esses recursos." #. (itstool) path: sect4/para #: article.translate.xml:666 msgid "" "For non-threaded programs the PID and TID are the same. For threaded " "programs the first thread PID and TID are the same and every created thread " "shares the same PID and gets assigned a unique TID (because " "CLONE_THREAD is passed in) also parent is shared for all " "processes forming this threaded program." msgstr "" "Para programas não segmentados, o PID e o TID são os mesmos. Para programas " "em threadings, os primeiros PID e TID da thread são os mesmos e todos os " "threading criados compartilham o mesmo PID e são atribuídos a um TID " "exclusivo (porque CLONE_THREAD é passado), o processo pai " "também é compartilhado para todos os processos que formam esse threading do " "programa." #. (itstool) path: sect4/para #: article.translate.xml:674 msgid "" "The code that implements pthread_create3 in NPTL defines the " "clone flags like this:" msgstr "" "O código que implementa pthread_create3 no NPTL define as " "flags de clone como este:" #. (itstool) path: sect4/programlisting #: article.translate.xml:677 #, no-wrap msgid "" "int clone_flags = (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGNAL\n" "\n" " | CLONE_SETTLS | CLONE_PARENT_SETTID\n" "\n" "| CLONE_CHILD_CLEARTID | CLONE_SYSVSEM\n" "#if __ASSUME_NO_CLONE_DETACHED == 0\n" "\n" "| CLONE_DETACHED\n" "#endif\n" "\n" "| 0);" msgstr "" "int clone_flags = (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGNAL\n" "\n" " | CLONE_SETTLS | CLONE_PARENT_SETTID\n" "\n" "| CLONE_CHILD_CLEARTID | CLONE_SYSVSEM\n" "#if __ASSUME_NO_CLONE_DETACHED == 0\n" "\n" "| CLONE_DETACHED\n" "#endif\n" "\n" "| 0);" #. (itstool) path: sect4/para #: article.translate.xml:689 msgid "The CLONE_SIGNAL is defined like" msgstr "O CLONE_SIGNAL é definido como" #. (itstool) path: sect4/programlisting #: article.translate.xml:692 #, no-wrap msgid "#define CLONE_SIGNAL (CLONE_SIGHAND | CLONE_THREAD)" msgstr "#define CLONE_SIGNAL (CLONE_SIGHAND | CLONE_THREAD)" #. (itstool) path: sect4/para #: article.translate.xml:694 msgid "the last 0 means no signal is sent when any of the threads exits." msgstr "" "o último 0 significa que nenhum sinal é enviado quando qualquer uma das " "threads finaliza." #. (itstool) path: sect2/title #: article.translate.xml:701 msgid "What is emulation" msgstr "O que é emulação" #. (itstool) path: sect2/para #: article.translate.xml:703 msgid "" "According to a dictionary definition, emulation is the ability of a program " "or device to imitate another program or device. This is achieved by " "providing the same reaction to a given stimulus as the emulated object. In " "practice, the software world mostly sees three types of emulation - a " "program used to emulate a machine (QEMU, various game console emulators " "etc.), software emulation of a hardware facility (OpenGL emulators, floating " "point units emulation etc.) and operating system emulation (either in kernel " "of the operating system or as a userspace program)." msgstr "" "De acordo com uma definição de dicionário, emulação é a capacidade de um " "programa ou dispositivo de imitar um outro programa ou dispositivo. Isto é " "conseguido fornecendo a mesma reação a um determinado estímulo que o objeto " "emulado. Na prática, o mundo do software vê três tipos de emulação - um " "programa usado para emular uma máquina (QEMU, vários emuladores de consoles " "de jogos etc.), emulação de software de uma instalação de hardware " "(emuladores OpenGL, emulação de unidades de ponto flutuante etc.) e emulação " "do sistema (no kernel do sistema operacional ou como um programa de espaço " "do usuário)." #. (itstool) path: sect2/para #: article.translate.xml:714 msgid "" "Emulation is usually used in a place, where using the original component is " "not feasible nor possible at all. For example someone might want to use a " "program developed for a different operating system than they use. Then " "emulation comes in handy. Sometimes there is no other way but to use " "emulation - e.g. when the hardware device you try to use does not exist (yet/" "anymore) then there is no other way but emulation. This happens often when " "porting an operating system to a new (non-existent) platform. Sometimes it " "is just cheaper to emulate." msgstr "" "Emulação é geralmente usada em um lugar, onde o uso do componente original " "não é viável nem possível a todos. Por exemplo, alguém pode querer usar um " "programa desenvolvido para um sistema operacional diferente do que eles " "usam. Então a emulação vem a calhar. Por vezes, não há outra maneira senão " "usar emulação - por ex. Quando o dispositivo de hardware que você tenta usar " "não existe (ainda/mais), então não há outro caminho além da emulação. Isso " "acontece com frequência ao transferir um sistema operacional para uma nova " "plataforma (inexistente). Às vezes é mais barato emular." #. (itstool) path: sect2/para #: article.translate.xml:725 msgid "" "Looking from an implementation point of view, there are two main approaches " "to the implementation of emulation. You can either emulate the whole thing - " "accepting possible inputs of the original object, maintaining inner state " "and emitting correct output based on the state and/or input. This kind of " "emulation does not require any special conditions and basically can be " "implemented anywhere for any device/program. The drawback is that " "implementing such emulation is quite difficult, time-consuming and error-" "prone. In some cases we can use a simpler approach. Imagine you want to " "emulate a printer that prints from left to right on a printer that prints " "from right to left. It is obvious that there is no need for a complex " "emulation layer but simply reversing of the printed text is sufficient. " "Sometimes the emulating environment is very similar to the emulated one so " "just a thin layer of some translation is necessary to provide fully working " "emulation! As you can see this is much less demanding to implement, so less " "time-consuming and error-prone than the previous approach. But the necessary " "condition is that the two environments must be similar enough. The third " "approach combines the two previous. Most of the time the objects do not " "provide the same capabilities so in a case of emulating the more powerful " "one on the less powerful we have to emulate the missing features with full " "emulation described above." msgstr "" "Olhando do ponto de vista da implementação, existem duas abordagens " "principais para a implementação da emulação. Você pode emular a coisa toda - " "aceitando possíveis entradas do objeto original, mantendo o estado interno e " "emitindo a saída correta com base no estado e/ou na entrada. Este tipo de " "emulação não requer condições especiais e basicamente pode ser implementado " "em qualquer lugar para qualquer dispositivo/programa. A desvantagem é que a " "implementação de tal emulação é bastante difícil, demorada e propensa a " "erros. Em alguns casos, podemos usar uma abordagem mais simples. Imagine que " "você deseja emular uma impressora que imprime da esquerda para a direita em " "uma impressora que imprime da direita para a esquerda. É óbvio que não há " "necessidade de uma camada de emulação complexa, mas a simples reversão do " "texto impresso é suficiente. Às vezes, o ambiente de emulação é muito " "semelhante ao emulado, portanto, apenas uma camada fina de alguma tradução é " "necessária para fornecer uma emulação totalmente funcional! Como você pode " "ver, isso é muito menos exigente de implementar, portanto, menos demorado e " "propenso a erros do que a abordagem anterior. Mas a condição necessária é " "que os dois ambientes sejam semelhantes o suficiente. A terceira abordagem " "combina os dois anteriores. Na maioria das vezes, os objetos não fornecem os " "mesmos recursos, portanto, em um caso de emulação, o mais poderoso é o menos " "poderoso que temos para emular os recursos ausentes com a emulação completa " "descrita acima." #. (itstool) path: sect2/para #: article.translate.xml:751 msgid "" "This master thesis deals with emulation of UNIX on UNIX, " "which is exactly the case, where only a thin layer of translation is " "sufficient to provide full emulation. The UNIX API consists of a set of syscalls, which are usually " "self contained and do not affect some global kernel state." msgstr "" "Esta tese de mestrado lida com a emulação de UNIX em UNIX, que " "é exatamente o caso, onde apenas uma camada fina de tradução é suficiente " "para fornecer emulação completa. A API do UNIX consiste em um conjunto de syscalls, que geralmente são " "autônomas e não afetam algum estado global do kernel." #. (itstool) path: sect2/para #: article.translate.xml:758 msgid "" "There are a few syscalls that affect inner state but this can be dealt with " "by providing some structures that maintain the extra state." msgstr "" "Existem algumas syscalls que afetam o estado interno, mas isso pode ser " "resolvido fornecendo algumas estruturas que mantêm o estado extra." #. (itstool) path: sect2/para #: article.translate.xml:762 msgid "" "No emulation is perfect and emulations tend to lack some parts but this " "usually does not cause any serious drawbacks. Imagine a game console " "emulator that emulates everything but music output. No doubt that the games " "are playable and one can use the emulator. It might not be that comfortable " "as the original game console but its an acceptable compromise between price " "and comfort." msgstr "" "Nenhuma emulação é perfeita e as emulações tendem a não ter algumas partes, " "mas isso geralmente não causa nenhuma desvantagem séria. Imagine um emulador " "de console de jogos que emula tudo, menos a saída de música. Não há dúvida " "de que os jogos são jogáveis ​​e pode-se usar o emulador. Pode não ser tão " "confortável quanto o console original, mas é um compromisso aceitável entre " "preço e conforto." #. (itstool) path: sect2/para #: article.translate.xml:770 msgid "" "The same goes with the UNIX API. " "Most programs can live with a very limited set of syscalls working. Those " "syscalls tend to be the oldest ones (read2/" "write2, fork2 family, " "signal3 handling, exit3, " "socket2 API) hence it is easy to emulate because their semantics is " "shared among all UNIXes, which " "exist todays." msgstr "" "O mesmo acontece com a API do UNIX. A maioria dos programas pode viver com um conjunto muito " "limitado de syscalls funcionando. Essas syscalls tendem a ser as mais " "antigas (read2/write2," "fork2family, signal3handling, " "exit3, socket2 API), portanto, é " "fácil emular porque sua semântica é compartilhada entre todos os UNIX, que existem hoje." #. (itstool) path: sect1/title #: article.translate.xml:781 msgid "Emulation" msgstr "Emulação" #. (itstool) path: sect2/title #: article.translate.xml:784 msgid "How emulation works in FreeBSD" msgstr "Como funciona a emulação no FreeBSD" #. (itstool) path: sect2/para #: article.translate.xml:786 msgid "" "As stated earlier, FreeBSD supports running binaries from several other " "UNIXes. This works because " "FreeBSD has an abstraction called the execution class loader. This wedges " "into the execve2 syscall, so when " "execve2 is about to execute a binary it examines its type." msgstr "" "Como dito anteriormente, o FreeBSD suporta a execução de binários a partir " "de vários outros UNIX. Isso " "funciona porque o FreeBSD tem uma abstração chamada loader de classes de " "execução. Isso se encaixa na syscall execve2, então quando " "execve2 está prestes a executar um binário que examina seu tipo." #. (itstool) path: sect2/para #: article.translate.xml:792 msgid "" "There are basically two types of binaries in FreeBSD. Shell-like text " "scripts which are identified by #! as their first two " "characters and normal (typically ELF) binaries, which " "are a representation of a compiled executable object. The vast majority (one " "could say all of them) of binaries in FreeBSD are from type ELF. ELF files " "contain a header, which specifies the OS ABI for this ELF file. By reading " "this information, the operating system can accurately determine what type of " "binary the given file is." msgstr "" "Existem basicamente dois tipos de binários no FreeBSD. Scripts de texto " "semelhantes a shell que são identificados por #! como " "seus dois primeiros caracteres e binários normais (normalmente " "ELF), que são uma representação de um objeto " "executável compilado. A grande maioria (pode-se dizer todos eles) de " "binários no FreeBSD é do tipo ELF. Os arquivos ELF contêm um cabeçalho, que " "especifica a ABI do OS para este arquivo ELF. Ao ler essas informações, o " "sistema operacional pode determinar com precisão o tipo de binário do " "arquivo fornecido." #. (itstool) path: sect2/para #: article.translate.xml:803 msgid "" "Every OS ABI must be registered in the FreeBSD kernel. This applies to the " "FreeBSD native OS ABI, as well. So when execve2 executes a binary it " "iterates through the list of registered APIs and when it finds the right one " "it starts to use the information contained in the OS ABI description (its " "syscall table, errno translation table, etc.). So every " "time the process calls a syscall, it uses its own set of syscalls instead of " "some global one. This effectively provides a very elegant and easy way of " "supporting execution of various binary formats." msgstr "" "Toda ABI de OS deve ser registrada no kernel do FreeBSD. Isso também se " "aplica ao sistema operacional nativo do FreeBSD. Então, quando " "execve2 executa um binário, ele itera através da lista de APIs " "registradas e quando ele encontra a correta, ele começa a usar as " "informações contidas na descrição da ABI do OS (sua tabela syscall, tabela " "de tradução errno, etc.). Assim, toda vez que o processo " "chama uma syscall, ele usa seu próprio conjunto de syscalls em vez de uma " "global. Isso efetivamente fornece uma maneira muito elegante e fácil de " "suportar a execução de vários formatos binários." #. (itstool) path: sect2/para #: article.translate.xml:814 msgid "" "The nature of emulation of different OSes (and also some other subsystems) " "led developers to invite a handler event mechanism. There are various places " "in the kernel, where a list of event handlers are called. Every subsystem " "can register an event handler and they are called accordingly. For example, " "when a process exits there is a handler called that possibly cleans up " "whatever the subsystem needs to be cleaned." msgstr "" "A natureza da emulação de diferentes sistemas operacionais (e também alguns " "outros subsistemas) levou os desenvolvedores a invitar um mecanismo de " "evento manipulador. Existem vários locais no kernel, onde uma lista de " "manipuladores de eventos é chamada. Cada subsistema pode registrar um " "manipulador de eventos e eles são chamados de acordo com sua necessidade. " "Por exemplo, quando um processo é encerrado, há um manipulador chamado que " "possivelmente limpa o que o subsistema que ele precisa de limpeza." #. (itstool) path: sect2/para #: article.translate.xml:823 msgid "" "Those simple facilities provide basically everything that is needed for the " "emulation infrastructure and in fact these are basically the only things " "necessary to implement the Linux " "emulation layer." msgstr "" "Essas facilidades simples fornecem basicamente tudo o que é necessário para " "a infra-estrutura de emulação e, de fato, essas são basicamente as únicas " "coisas necessárias para implementar a camada de emulação do Linux." #. (itstool) path: sect2/title #: article.translate.xml:830 msgid "Common primitives in the FreeBSD kernel" msgstr "Primitivas comuns no kernel do FreeBSD" #. (itstool) path: sect2/para #: article.translate.xml:832 msgid "" "Emulation layers need some support from the operating system. I am going to " "describe some of the supported primitives in the FreeBSD operating system." msgstr "" "Camadas de emulação precisam de algum suporte do sistema operacional. Eu vou " "descrever algumas das primitivas suportadas no sistema operacional FreeBSD." #. (itstool) path: sect3/title #: article.translate.xml:837 msgid "Locking primitives" msgstr "Primitivas de Bloqueio" #. (itstool) path: sect3/para #: article.translate.xml:839 msgid "Contributed by: Attilio Rao attilio@FreeBSD.org" msgstr "Contribuído por: Attilio Rao attilio@FreeBSD.org" #. (itstool) path: sect3/para #: article.translate.xml:841 msgid "" "The FreeBSD synchronization primitive set is based on the idea to supply a " "rather huge number of different primitives in a way that the better one can " "be used for every particular, appropriate situation." msgstr "" "O conjunto de primitivas de sincronização do FreeBSD é baseado na idéia de " "fornecer um grande número de diferentes primitivas de uma maneira que a " "melhor possa ser usada para cada situação específica e apropriada." #. (itstool) path: sect3/para #: article.translate.xml:846 msgid "" "To a high level point of view you can consider three kinds of " "synchronization primitives in the FreeBSD kernel:" msgstr "" "Para um ponto de vista de alto nível, você pode considerar três tipos de " "primitivas de sincronização no kernel do FreeBSD:" #. (itstool) path: listitem/para #: article.translate.xml:852 msgid "atomic operations and memory barriers" msgstr "operações atômicas e barreiras de memória" #. (itstool) path: listitem/para #: article.translate.xml:855 msgid "locks" msgstr "locks" #. (itstool) path: listitem/para #: article.translate.xml:858 msgid "scheduling barriers" msgstr "barreiras de agendamento" #. (itstool) path: sect3/para #: article.translate.xml:862 msgid "" "Below there are descriptions for the 3 families. For every lock, you should " "really check the linked manpage (where possible) for more detailed " "explanations." msgstr "" "Abaixo, há descrições para as 3 famílias. Para cada bloqueio, você deve " "verificar a página de manual vinculada (onde for possível) para obter " "explicações mais detalhadas." #. (itstool) path: sect4/title #: article.translate.xml:867 msgid "Atomic operations and memory barriers" msgstr "Operações atômicas e barreiras de memória" #. (itstool) path: sect4/para #: article.translate.xml:869 msgid "" "Atomic operations are implemented through a set of functions performing " "simple arithmetics on memory operands in an atomic way with respect to " "external events (interrupts, preemption, etc.). Atomic operations can " "guarantee atomicity just on small data types (in the magnitude order of the " ".long. architecture C data type), so should be rarely " "used directly in the end-level code, if not only for very simple operations " "(like flag setting in a bitmap, for example). In fact, it is rather simple " "and common to write down a wrong semantic based on just atomic operations " "(usually referred as lock-less). The FreeBSD kernel offers a way to perform " "atomic operations in conjunction with a memory barrier. The memory barriers " "will guarantee that an atomic operation will happen following some specified " "ordering with respect to other memory accesses. For example, if we need that " "an atomic operation happen just after all other pending writes (in terms of " "instructions reordering buffers activities) are completed, we need to " "explicitly use a memory barrier in conjunction to this atomic operation. So " "it is simple to understand why memory barriers play a key role for higher-" "level locks building (just as refcounts, mutexes, etc.). For a detailed " "explanatory on atomic operations, please refer to " "atomic9. It is far, however, noting that atomic operations (and memory " "barriers as well) should ideally only be used for building front-ending " "locks (as mutexes)." msgstr "" "Operações atômicas são implementadas através de um conjunto de funções que " "executam aritmética simples em operandos de memória de maneira atômica com " "relação a eventos externos (interrupções, preempção, etc.). Operações " "atômicas podem garantir atomicidade apenas em pequenos tipos de dados (na " "ordem de magnitude do tipo de dados C da arquitetura .long.), portanto raramente devem ser usados ​​diretamente no código de " "nível final, se não apenas para operações muito simples (como configuração " "de flags em um bitmap, por exemplo). De fato, é bastante simples e comum " "escrever uma semântica errada baseada apenas em operações atômicas " "(geralmente referidas como lock-less). O kernel do FreeBSD oferece uma " "maneira de realizar operações atômicas em conjunto com uma barreira de " "memória. As barreiras de memória garantirão que uma operação atômica " "ocorrerá seguindo alguma ordem especificas em relação a outros acessos à " "memória. Por exemplo, se precisarmos que uma operação atômica aconteça logo " "depois que todas as outras gravações pendentes (em termos de instruções " "reordenando atividades de buffers) forem concluídas, precisamos usar " "explicitamente uma barreira de memória em conjunto com essa operação " "atômica. Portanto, é simples entender por que as barreiras de memória " "desempenham um papel fundamental na construção de bloqueios de alto nível " "(assim como referências, exclusões mútuas, etc.). Para uma explicação " "detalhada sobre operações atômicas, consulte " "atomic9. É muito, no entanto, notar que as operações atômicas (e as " "barreiras de memória também) devem, idealmente, ser usadas apenas para " "construir bloqueios front-ending (como mutexes)." #. (itstool) path: sect4/title #: article.translate.xml:900 msgid "Refcounts" msgstr "Refcounts" #. (itstool) path: sect4/para #: article.translate.xml:902 msgid "" "Refcounts are interfaces for handling reference counters. They are " "implemented through atomic operations and are intended to be used just for " "cases, where the reference counter is the only one thing to be protected, so " "even something like a spin-mutex is deprecated. Using the refcount interface " "for structures, where a mutex is already used is often wrong since we should " "probably close the reference counter in some already protected paths. A " "manpage discussing refcount does not exist currently, just check " "sys/refcount.h for an overview of the existing API." msgstr "" "Refcounts são interfaces para manipular contadores de referência. Eles são " "implementados por meio de operações atômicas e destinam-se a ser usados ​​" "apenas para casos em que o contador de referência é a única coisa a ser " "protegida, portanto, até mesmo algo como um spin-mutex é obsoleto. Usar a " "interface de recontagem para estruturas, onde um mutex já é usado, " "geralmente está errado, pois provavelmente devemos fechar o contador de " "referência em alguns caminhos já protegidos. Uma manpage discutindo refcount " "não existe atualmente, apenas verifique sys/refcount.h " "para uma visão geral da API existente." #. (itstool) path: sect4/title #: article.translate.xml:916 msgid "Locks" msgstr "Locks" #. (itstool) path: sect4/para #: article.translate.xml:918 msgid "" "FreeBSD kernel has huge classes of locks. Every lock is defined by some " "peculiar properties, but probably the most important is the event linked to " "contesting holders (or in other terms, the behavior of threads unable to " "acquire the lock). FreeBSD's locking scheme presents three different " "behaviors for contenders:" msgstr "" "O kernel do FreeBSD tem enormes classes de bloqueios. Cada bloqueio é " "definido por algumas propriedades peculiares, mas provavelmente o mais " "importante é o evento vinculado a detentores de contestação (ou, em outros " "termos, o comportamento de threading incapazes de adquirir o bloqueio). O " "esquema de bloqueio do FreeBSD apresenta três comportamentos diferentes para " "contendores:" #. (itstool) path: listitem/para #: article.translate.xml:927 msgid "spinning" msgstr "spinning" #. (itstool) path: listitem/para #: article.translate.xml:930 msgid "blocking" msgstr "blocking" #. (itstool) path: listitem/para #: article.translate.xml:933 msgid "sleeping" msgstr "sleeping" #. (itstool) path: note/para #: article.translate.xml:938 msgid "numbers are not casual" msgstr "números não são casuais" #. (itstool) path: sect4/title #: article.translate.xml:943 msgid "Spinning locks" msgstr "Spinning locks" #. (itstool) path: sect4/para #: article.translate.xml:945 msgid "" "Spin locks let waiters to spin until they cannot acquire the lock. An " "important matter do deal with is when a thread contests on a spin lock if it " "is not descheduled. Since the FreeBSD kernel is preemptive, this exposes " "spin lock at the risk of deadlocks that can be solved just disabling " "interrupts while they are acquired. For this and other reasons (like lack of " "priority propagation support, poorness in load balancing schemes between " "CPUs, etc.), spin locks are intended to protect very small paths of code, or " "ideally not to be used at all if not explicitly requested (explained later)." msgstr "" "Spin locks permitem que os acumuladores rotacionarem até que eles não " "consigam adquirir um lock. Uma questão importante é quando um segmento " "contesta em um spin lock se não for desmarcado. Uma vez que o kernel do " "FreeBSD é preventivo, isto expõe o spin lock ao risco de deadlocks que podem " "ser resolvidos apenas desabilitando as interrupções enquanto elas são " "adquiridas. Por essa e outras razões (como falta de suporte à propagação de " "prioridade, falta de esquemas de balanceamento de carga entre CPUs, etc.), " "os spin locks têm a finalidade de proteger endereçamentos muito pequenos de " "código ou, idealmente, não serem usados ​​se não solicitados explicitamente " "( explicado posteriormente)." #. (itstool) path: sect4/title #: article.translate.xml:959 msgid "Blocking" msgstr "Bloqueio" #. (itstool) path: sect4/para #: article.translate.xml:961 msgid "" "Block locks let waiters to be descheduled and blocked until the lock owner " "does not drop it and wakes up one or more contenders. In order to avoid " "starvation issues, blocking locks do priority propagation from the waiters " "to the owner. Block locks must be implemented through the turnstile " "interface and are intended to be the most used kind of locks in the kernel, " "if no particular conditions are met." msgstr "" "Os locks em blocos permitem que as tarefas dos acumuladores sejam removidas " "e bloqueados até que o proprietário do bloqueio não os libere e ative um ou " "mais contendores. Para evitar problemas de fome, os locks em bloco fazem a " "propagação de prioridade dos acumuladores para o proprietário. Os locks em " "bloco devem ser implementados por meio da interface turnstile e devem ser o " "tipo mais usado de bloqueios no kernel, se nenhuma condição específica for " "atendida." #. (itstool) path: sect4/title #: article.translate.xml:972 msgid "Sleeping" msgstr "Sleeping" #. (itstool) path: sect4/para #: article.translate.xml:974 msgid "" "Sleep locks let waiters to be descheduled and fall asleep until the lock " "holder does not drop it and wakes up one or more waiters. Since sleep locks " "are intended to protect large paths of code and to cater asynchronous " "events, they do not do any form of priority propagation. They must be " "implemented through the sleepqueue9 interface." msgstr "" "Sleep locks permitem que as tarefas dos waiters sejam removidas e eles " "adormecem até que o suporte do lock não os deixe cair e desperte um ou mais " "waiters. Como os sleep locks se destinam a proteger grandes endereçamentos " "de código e a atender a eventos assíncronos, eles não fazem nenhuma forma de " "propagação de prioridade. Eles devem ser implementados por meio da interface " "sleepqueue9." #. (itstool) path: sect4/para #: article.translate.xml:982 msgid "" "The order used to acquire locks is very important, not only for the " "possibility to deadlock due at lock order reversals, but even because lock " "acquisition should follow specific rules linked to locks natures. If you " "give a look at the table above, the practical rule is that if a thread holds " "a lock of level n (where the level is the number listed close to the kind of " "lock) it is not allowed to acquire a lock of superior levels, since this " "would break the specified semantic for a path. For example, if a thread " "holds a block lock (level 2), it is allowed to acquire a spin lock (level 1) " "but not a sleep lock (level 3), since block locks are intended to protect " "smaller paths than sleep lock (these rules are not about atomic operations " "or scheduling barriers, however)." msgstr "" "A ordem usada para adquirir locks é muito importante, não apenas pela " "possibilidade de deadlock devido a reversões de ordem de bloqueio, mas " "também porque a aquisição de lock deve seguir regras específicas vinculadas " "a naturezas de bloqueios. Se você der uma olhada na tabela acima, a regra " "prática é que, se um segmento contiver um lock de nível n (onde o nível é o " "número listado próximo ao tipo de bloqueio), não é permitido adquirir um " "lock de níveis superiores , pois isso quebraria a semântica especificada " "para um caminho. Por exemplo, se uma thread contiver um lock em bloco (nível " "2), ele poderá adquirir um spin lock (nível 1), mas não um sleep lock (nível " "3), pois os locks em bloco são destinados a proteger caminhos menores que o " "sleep lock ( essas regras não são sobre operações atômicas ou agendamento de " "barreiras, no entanto)." #. (itstool) path: sect4/para #: article.translate.xml:997 msgid "This is a list of lock with their respective behaviors:" msgstr "Esta é uma lista de bloqueio com seus respectivos comportamentos:" #. (itstool) path: listitem/para #: article.translate.xml:1002 msgid "" "spin mutex - spinning - mutex9" msgstr "" "spin mutex - spinning - mutex9" #. (itstool) path: listitem/para #: article.translate.xml:1005 msgid "" "sleep mutex - blocking - mutex9" msgstr "" "sleep mutex - blocking - mutex9" #. (itstool) path: listitem/para #: article.translate.xml:1008 msgid "" "pool mutex - blocking - mtx_pool9" msgstr "" "pool mutex - blocking - mtx_pool9" #. (itstool) path: listitem/para #: article.translate.xml:1011 msgid "" "sleep family - sleeping - sleep9 pause tsleep msleep " "msleep spin msleep rw msleep sx" msgstr "" "família sleep - sleeping - sleep9 pausa tsleep msleep " "msleep spin msleep rw msleep sx" #. (itstool) path: listitem/para #: article.translate.xml:1015 msgid "" "condvar - sleeping - condvar9" msgstr "" "condvar - sleeping - condvar9" #. (itstool) path: listitem/para #: article.translate.xml:1018 msgid "" "rwlock - blocking - rwlock9" msgstr "" "wlock - blocking - rwlock9" #. (itstool) path: listitem/para #: article.translate.xml:1021 msgid "" "sxlock - sleeping - sx9" msgstr "" "sxlock - sleeping - sx9" #. (itstool) path: listitem/para #: article.translate.xml:1024 msgid "" "lockmgr - sleeping - lockmgr9" msgstr "" "lockmgr - sleeping - lockmgr9" #. (itstool) path: listitem/para #: article.translate.xml:1027 msgid "" "semaphores - sleeping - sema9" msgstr "" "semáforos - sleeping - sema9" #. (itstool) path: sect4/para #: article.translate.xml:1031 msgid "" "Among these locks only mutexes, sxlocks, rwlocks and lockmgrs are intended " "to handle recursion, but currently recursion is only supported by mutexes " "and lockmgrs." msgstr "" "Entre esses bloqueios, apenas mutexes, sxlocks, rwlocks e lockmgrs são " "destinados a tratar recursão, mas atualmente a recursão é suportada apenas " "por mutexes e lockmgrs." #. (itstool) path: sect4/title #: article.translate.xml:1038 msgid "Scheduling barriers" msgstr "Barreiras de agendamento" #. (itstool) path: sect4/para #: article.translate.xml:1040 msgid "" "Scheduling barriers are intended to be used in order to drive scheduling of " "threading. They consist mainly of three different stubs:" msgstr "" "As barreiras de agendamento devem ser usadas para orientar o agendamento de " "threads. Eles consistem principalmente de três diferentes stubs:" #. (itstool) path: listitem/para #: article.translate.xml:1046 msgid "critical sections (and preemption)" msgstr "seções críticas (e preempção)" #. (itstool) path: listitem/para #: article.translate.xml:1049 msgid "sched_bind" msgstr "sched_bind" #. (itstool) path: listitem/para #: article.translate.xml:1052 msgid "sched_pin" msgstr "sched_pin" #. (itstool) path: sect4/para #: article.translate.xml:1056 msgid "" "Generally, these should be used only in a particular context and even if " "they can often replace locks, they should be avoided because they do not let " "the diagnose of simple eventual problems with locking debugging tools (as " "witness4)." msgstr "" "Geralmente, eles devem ser usados ​​apenas em um contexto específico e, mesmo " "que possam substituir bloqueios, eles devem ser evitados porque eles não " "permitem o diagnóstico de problemas simples com ferramentas de depuração de " "bloqueio (como witness4)." #. (itstool) path: sect4/title #: article.translate.xml:1064 msgid "Critical sections" msgstr "Seções críticas" #. (itstool) path: sect4/para #: article.translate.xml:1066 msgid "" "The FreeBSD kernel has been made preemptive basically to deal with interrupt " "threads. In fact, in order to avoid high interrupt latency, time-sharing " "priority threads can be preempted by interrupt threads (in this way, they do " "not need to wait to be scheduled as the normal path previews). Preemption, " "however, introduces new racing points that need to be handled, as well. " "Often, in order to deal with preemption, the simplest thing to do is to " "completely disable it. A critical section defines a piece of code " "(borderlined by the pair of functions " "critical_enter9 and critical_exit9, where preemption is " "guaranteed to not happen (until the protected code is fully executed). This " "can often replace a lock effectively but should be used carefully in order " "to not lose the whole advantage that preemption brings." msgstr "" "O kernel do FreeBSD foi feito basicamente para lidar com threads de " "interrupção. De fato, para evitar latência de interrupção alta, os segmentos " "de prioridade de compartilhamento de tempo podem ser precedidos por threads " "de interrupção (dessa forma, eles não precisam aguardar para serem agendados " "como as visualizações de caminho normais). Preempção, no entanto, introduz " "novos pontos de corrida que precisam ser manipulados também. Muitas vezes, " "para lidar com a preempção, a coisa mais simples a fazer é desativá-la " "completamente. Uma seção crítica define um pedaço de código (delimitado pelo " "par de funções critical_enter9 e " "critical_exit9, onde é garantido que a preempção não aconteça " "(até que o código protegido seja totalmente executado) Isso pode substituir " "um bloqueio efetivamente, mas deve ser usado com cuidado para não perder " "toda a vantagem essa preempção traz." #. (itstool) path: sect4/title #: article.translate.xml:1085 msgid "sched_pin/sched_unpin" msgstr "sched_pin/sched_unpin" #. (itstool) path: sect4/para #: article.translate.xml:1087 msgid "" "Another way to deal with preemption is the sched_pin() " "interface. If a piece of code is closed in the sched_pin() and sched_unpin() pair of functions it is " "guaranteed that the respective thread, even if it can be preempted, it will " "always be executed on the same CPU. Pinning is very effective in the " "particular case when we have to access at per-cpu datas and we assume other " "threads will not change those data. The latter condition will determine a " "critical section as a too strong condition for our code." msgstr "" "Outra maneira de lidar com a preempção é a interface sched_pin(). Se um trecho de código é fechado no par de funções " "sched_pin() e sched_unpin(), é " "garantido que a respectiva thread, mesmo que possa ser antecipada, sempre " "ser executada na mesma CPU. Fixar é muito eficaz no caso particular quando " "temos que acessar por dados do cpu e assumimos que outras threads não irão " "alterar esses dados. A última condição determinará uma seção crítica como " "uma condição muito forte para o nosso código." #. (itstool) path: sect4/title #: article.translate.xml:1101 msgid "sched_bind/sched_unbind" msgstr "sched_bind/sched_unbind" #. (itstool) path: sect4/para #: article.translate.xml:1103 msgid "" "sched_bind is an API used in order to bind a thread to " "a particular CPU for all the time it executes the code, until a " "sched_unbind function call does not unbind it. This " "feature has a key role in situations where you cannot trust the current " "state of CPUs (for example, at very early stages of boot), as you want to " "avoid your thread to migrate on inactive CPUs. Since sched_bind and sched_unbind manipulate internal " "scheduler structures, they need to be enclosed in sched_lock acquisition/releasing when used." msgstr "" "sched_bind é uma API usada para vincular uma thread a " "uma CPU em particular durante todo o tempo em que ele executa o código, até " "que uma chamada de função sched_unbind não a " "desvincule. Esse recurso tem um papel importante em situações em que você " "não pode confiar no estado atual das CPUs (por exemplo, em estágios iniciais " "de inicialização), já que você deseja evitar que sua thread migre em CPUs " "inativas. Como sched_bind e sched_unbind manipulam as estruturas internas do agendador, elas precisam estar " "entre a aquisição/liberação de sched_lock quando usadas." #. (itstool) path: sect3/title #: article.translate.xml:1120 msgid "Proc structure" msgstr "Estrutura Proc" #. (itstool) path: sect3/para #: article.translate.xml:1122 msgid "" "Various emulation layers sometimes require some additional per-process data. " "It can manage separate structures (a list, a tree etc.) containing these " "data for every process but this tends to be slow and memory consuming. To " "solve this problem the FreeBSD proc structure contains " "p_emuldata, which is a void pointer to some emulation " "layer specific data. This proc entry is protected by the " "proc mutex." msgstr "" "Várias camadas de emulação exigem alguns dados adicionais por processo. Ele " "pode gerenciar estruturas separadas (uma lista, uma árvore etc.) contendo " "esses dados para cada processo, mas isso tende a ser lento e consumir " "memória. Para resolver este problema, a estrutura proc do " "FreeBSD contém p_emuldata, que é um ponteiro vazio para " "alguns dados específicos da camada de emulação. Esta entrada proc é protegida pelo mutex proc." #. (itstool) path: sect3/para #: article.translate.xml:1133 msgid "" "The FreeBSD proc structure contains a p_sysent entry that identifies, which ABI this process is running. In fact, " "it is a pointer to the sysentvec described above. So by " "comparing this pointer to the address where the sysentvec " "structure for the given ABI is stored we can effectively determine whether " "the process belongs to our emulation layer. The code typically looks like:" msgstr "" "A estrutura proc do FreeBSD contém uma entrada " "p_sysent que identifica, qual ABI este processo está " "executando. Na verdade, é um ponteiro para o sysentvec " "descrito acima. Portanto, comparando esse ponteiro com o endereço em que a " "estrutura sysentvec da ABI especificada está armazenada, " "podemos efetivamente determinar se o processo pertence à nossa camada de " "emulação. O código normalmente se parece com:" #. (itstool) path: sect3/programlisting #: article.translate.xml:1143 #, no-wrap msgid "" "if (__predict_true(p->p_sysent != &elf_Linux_sysvec))\n" "\t return;" msgstr "" "if (__predict_true(p->p_sysent != &elf_Linux_sysvec))\n" "\t return;" #. (itstool) path: sect3/para #: article.translate.xml:1146 msgid "" "As you can see, we effectively use the __predict_true " "modifier to collapse the most common case (FreeBSD process) to a simple " "return operation thus preserving high performance. This code should be " "turned into a macro because currently it is not very flexible, i.e. we do " "not support Linux64 emulation " "nor A.OUT Linux processes on " "i386." msgstr "" "Como você pode ver, usamos efetivamente o modificador " "__predict_true para recolher o caso mais comum (processo " "do FreeBSD) para uma operação de retorno simples, preservando assim o alto " "desempenho. Este código deve ser transformado em uma macro porque atualmente " "não é muito flexível, ou seja, não suportamos emulação Linux64 nem processa A.OUT Linux em i386." #. (itstool) path: sect3/title #: article.translate.xml:1156 msgid "VFS" msgstr "VFS" #. (itstool) path: sect3/para #: article.translate.xml:1158 msgid "" "The FreeBSD VFS subsystem is very complex but the Linux emulation layer uses just a small subset " "via a well defined API. It can either operate on vnodes or file handlers. " "Vnode represents a virtual vnode, i.e. representation of a node in VFS. " "Another representation is a file handler, which represents an opened file " "from the perspective of a process. A file handler can represent a socket or " "an ordinary file. A file handler contains a pointer to its vnode. More then " "one file handler can point to the same vnode." msgstr "" "O subsistema FreeBSD VFS é muito complexo, mas a camada de emulação " "Linux usa apenas um pequeno " "subconjunto através de uma API bem definida. Ele pode operar em vnodes ou " "manipuladores de arquivos. Vnode representa um vnode virtual, isto é, " "representação de um nó no VFS. Outra representação é um manipulador de " "arquivos, que representa um arquivo aberto da perspectiva de um processo. Um " "manipulador de arquivos pode representar um socket ou um arquivo comum. Um " "manipulador de arquivos contém um ponteiro para seu vnode. Mais de um " "manipulador de arquivos pode apontar para o mesmo vnode." #. (itstool) path: sect4/title #: article.translate.xml:1170 msgid "namei" msgstr "namei" #. (itstool) path: sect4/para #: article.translate.xml:1172 msgid "" "The namei9 routine is a central entry point to pathname " "lookup and translation. It traverses the path point by point from the " "starting point to the end point using lookup function, which is internal to " "VFS. The namei9 syscall can cope with symlinks, absolute and " "relative paths. When a path is looked up using " "namei9 it is inputed to the name cache. This behavior can be " "suppressed. This routine is used all over the kernel and its performance is " "very critical." msgstr "" "A rotina namei9 é um ponto de entrada central para a pesquisa e o " "nome do caminho. Ele percorre o caminho ponto a ponto do ponto inicial até o " "ponto final usando a função de pesquisa, que é interna ao VFS. A syscall " "namei9 pode lidar com links simbólicos, absolutos e relativos. Quando " "um caminho é procurado usando namei9 ele é inserido no " "cache de nomes. Esse comportamento pode ser suprimido. Essa rotina é usada " "em todo o kernel e seu desempenho é muito crítico." #. (itstool) path: sect4/title #: article.translate.xml:1184 msgid "vn_fullpath" msgstr "vn_fullpath" #. (itstool) path: sect4/para #: article.translate.xml:1186 msgid "" "The vn_fullpath9 function takes the best effort to traverse VFS " "name cache and returns a path for a given (locked) vnode. This process is " "unreliable but works just fine for the most common cases. The unreliability " "is because it relies on VFS cache (it does not traverse the on medium " "structures), it does not work with hardlinks, etc. This routine is used in " "several places in the Linuxulator." msgstr "" "A função vn_fullpath9 faz o melhor esforço " "para percorrer o cache de nomes do VFS e retorna um caminho para um " "determinado vnode (bloqueado). Esse processo não é confiável, mas funciona " "bem nos casos mais comuns. A falta de confiabilidade é porque ela depende do " "cache do VFS (ele não atravessa as estruturas intermediárias), não funciona " "com hardlinks, etc. Essa rotina é usada em vários locais no Linuxulator." #. (itstool) path: sect4/title #: article.translate.xml:1197 msgid "Vnode operations" msgstr "Operações de vnode" #. (itstool) path: listitem/para #: article.translate.xml:1201 msgid "" "fgetvp - given a thread and a file descriptor number it " "returns the associated vnode" msgstr "" "fgetvp - dado um encadeamento e um número de descritor " "de arquivo, ele retorna o vnode associado" #. (itstool) path: listitem/para #: article.translate.xml:1206 msgid "" "vn_lock9 - locks a vnode" msgstr "" "vn_lock9 - bloqueia um vnode" #. (itstool) path: listitem/para #: article.translate.xml:1209 msgid "vn_unlock - unlocks a vnode" msgstr "vn_unlock - desbloqueia um vnode" #. (itstool) path: listitem/para #: article.translate.xml:1213 msgid "" "VOP_READDIR9 - reads a directory referenced by a vnode" msgstr "" "VOP_READDIR9 - lê um diretório referenciado por um vnode" #. (itstool) path: listitem/para #: article.translate.xml:1217 msgid "" "VOP_GETATTR9 - gets attributes of a file or a directory " "referenced by a vnode" msgstr "" "VOP_GETATTR9 - obtém atributos de um arquivo ou diretório " "referenciado por um vnode" #. (itstool) path: listitem/para #: article.translate.xml:1221 msgid "" "VOP_LOOKUP9 - looks up a path to a given directory" msgstr "" "VOP_LOOKUP9 - procura um caminho para um determinado diretório" #. (itstool) path: listitem/para #: article.translate.xml:1225 msgid "" "VOP_OPEN9 - opens a file referenced by a vnode" msgstr "" "VOP_OPEN9 - abre um arquivo referenciado por um vnode" #. (itstool) path: listitem/para #: article.translate.xml:1229 msgid "" "VOP_CLOSE9 - closes a file referenced by a vnode" msgstr "" "VOP_CLOSE9 - fecha um arquivo referenciado por um vnode" #. (itstool) path: listitem/para #: article.translate.xml:1233 msgid "" "vput9 - decrements the use count for a vnode and unlocks it" msgstr "" "vput9 - decrementa a contagem de uso para um vnode e o desbloqueia" #. (itstool) path: listitem/para #: article.translate.xml:1237 msgid "" "vrele9 - decrements the use count for a vnode" msgstr "" "vrele9 - diminui a contagem de uso para um vnode" #. (itstool) path: listitem/para #: article.translate.xml:1241 msgid "" "vref9 - increments the use count for a vnode" msgstr "" "vref9 - incrementa a contagem de uso para um vnode" #. (itstool) path: sect4/title #: article.translate.xml:1248 msgid "File handler operations" msgstr "Operações do manipulador de arquivos" #. (itstool) path: listitem/para #: article.translate.xml:1252 msgid "" "fget - given a thread and a file descriptor number it " "returns associated file handler and references it" msgstr "" "fget - dado uma thread e um número de file descriptor, " "ele retorna o manipulador de arquivos associado e faz referência a ele" #. (itstool) path: listitem/para #: article.translate.xml:1257 msgid "fdrop - drops a reference to a file handler" msgstr "" "fdrop - elimina uma referência a um manipulador de " "arquivos" #. (itstool) path: listitem/para #: article.translate.xml:1261 msgid "fhold - references a file handler" msgstr "" "fhold - faz referência a um manipulador de arquivos" #. (itstool) path: sect1/title #: article.translate.xml:1271 msgid "" "Linux emulation layer -MD part" msgstr "" "Parte da camada de emulação -MD do Linux" #. (itstool) path: sect1/para #: article.translate.xml:1273 msgid "" "This section deals with implementation of Linux emulation layer in FreeBSD operating system. It first " "describes the machine dependent part talking about how and where interaction " "between userland and kernel is implemented. It talks about syscalls, " "signals, ptrace, traps, stack fixup. This part discusses i386 but it is " "written generally so other architectures should not differ very much. The " "next part is the machine independent part of the Linuxulator. This section " "only covers i386 and ELF handling. A.OUT is obsolete and untested." msgstr "" "Esta seção trata da implementação da camada de emulação do Linux no sistema operacional FreeBSD. Ele " "primeiro descreve a parte dependente da máquina falando sobre como e onde a " "interação entre o usuário e o kernel é implementada. Ele fala sobre " "syscalls, signals, ptrace, traps, correção de pilha. Esta parte discute o " "i386, mas ele é escrito geralmente para que outras arquiteturas não sejam " "muito diferentes. A próxima parte é a parte independente da máquina do " "Linuxulator. Esta seção abrange apenas o tratamento de i386 e ELF. A.OUT " "está obsoleto e não foi testado." #. (itstool) path: sect2/title #: article.translate.xml:1284 msgid "Syscall handling" msgstr "Manipulação de Syscall" #. (itstool) path: sect2/para #: article.translate.xml:1286 msgid "" "Syscall handling is mostly written in linux_sysvec.c, " "which covers most of the routines pointed out in the sysentvec structure. When a Linux " "process running on FreeBSD issues a syscall, the general syscall routine " "calls linux prepsyscall routine for the Linux ABI." msgstr "" "A manipulação de Syscall é principalmente escrita em linux_sysvec." "c, que cobre a maioria das rotinas apontadas na estrutura " "sysentvec. Quando um processo Linux executado no FreeBSD emite um syscall, a " "rotina syscall geral chama a rotina prepsyscall do linux para a ABI do " "Linux." #. (itstool) path: sect3/title #: article.translate.xml:1294 msgid "Linux prepsyscall" msgstr "Linux prepsyscall" #. (itstool) path: sect3/para #: article.translate.xml:1296 msgid "" "Linux passes arguments to " "syscalls via registers (that is why it is limited to 6 parameters on i386) " "while FreeBSD uses the stack. The Linux prepsyscall routine must copy parameters from registers to the " "stack. The order of the registers is: %ebx, " "%ecx, %edx, %esi, " "%edi, %ebp. The catch is that this is true for " "only most of the syscalls. Some (most notably " "clone) uses a different order but it is luckily easy to " "fix by inserting a dummy parameter in the linux_clone " "prototype." msgstr "" "Linux passa argumentos via " "registradores de syscalls (isso porque ele é limitado a 6 parametros no " "i386) enquanto o FreeBSD usa uma pilha. A rotina prepsyscall do Linux deve copiar parametros dos " "registradores para a pilha. A ordem dos registradores é: %ebx, %ecx, %edx, %esi, %edi, %ebp. O fato é que " "isso é verdadeiro apenas para a maioria das syscalls. " "Algumas (mais provavelmente clone) usam uma ordem " "diferente, mas é demasiadamente facil de arrumar inserindo um parametro " "dummy no prototype linux_clone." #. (itstool) path: sect3/title #: article.translate.xml:1311 msgid "Syscall writing" msgstr "Escrevendo syscall" #. (itstool) path: sect3/para #: article.translate.xml:1313 msgid "" "Every syscall implemented in the Linuxulator must have its prototype with " "various flags in syscalls.master. The form of the file " "is:" msgstr "" "Cada syscall implementada no Linuxulator deve ter seu protótipo com vários " "flags no syscalls.master. A forma do arquivo é:" #. (itstool) path: sect3/programlisting #: article.translate.xml:1318 #, no-wrap msgid "" "...\n" "\tAUE_FORK STD\t\t{ int linux_fork(void); }\n" "...\n" "\tAUE_CLOSE NOPROTO\t{ int close(int fd); }\n" "..." msgstr "" "...\n" "\tAUE_FORK STD\t\t{ int linux_fork(void); }\n" "...\n" "\tAUE_CLOSE NOPROTO\t{ int close(int fd); }\n" "..." #. (itstool) path: sect3/para #: article.translate.xml:1324 msgid "" "The first column represents the syscall number. The second column is for " "auditing support. The third column represents the syscall type. It is either " "STD, OBSOL, NOPROTO " "and UNIMPL. STD is a standard syscall " "with full prototype and implementation. OBSOL is obsolete " "and defines just the prototype. NOPROTO means that the " "syscall is implemented elsewhere so do not prepend ABI prefix, etc. " "UNIMPL means that the syscall will be substituted with " "the nosys syscall (a syscall just printing out a " "message about the syscall not being implemented and returning " "ENOSYS)." msgstr "" "A primeira coluna representa o número da syscall. A segunda coluna é para " "suporte de auditoria. A terceira coluna representa o tipo da syscall. É " "STD, OBSOL, NOPROTO " "e UNIMPL. STD é uma syscall padrão com " "protótipo e implementação completos. OBSOL é obsoleto e " "define apenas o protótipo. NOPROTO significa que a " "syscall é implementado em outro lugar, portanto, não precede o prefixo da " "ABI, etc. UNIMPL significa que a syscall será substituída " "pela syscall nosys (uma syscall apenas imprime uma " "mensagem sobre a syscall não sendo implementado e retornando " "ENOSYS)." #. (itstool) path: sect3/para #: article.translate.xml:1340 msgid "" "From syscalls.master a script generates three files: " "linux_syscall.h, linux_proto.h and " "linux_sysent.c. The linux_syscall.h contains definitions of syscall names and their numerical value, e." "g.:" msgstr "" "De um script syscalls.master, gera três arquivos: " "linux_syscall.h, linux_proto.h e " "linux_sysent.c. O linux_syscall.h " "contém definições de nomes de syscall e seus valores numéricos, por exemplo:" #. (itstool) path: sect3/programlisting #: article.translate.xml:1347 #, no-wrap msgid "" "...\n" "#define LINUX_SYS_linux_fork 2\n" "...\n" "#define LINUX_SYS_close 6\n" "..." msgstr "" "...\n" "#define LINUX_SYS_linux_fork 2\n" "...\n" "#define LINUX_SYS_close 6\n" "..." #. (itstool) path: sect3/para #: article.translate.xml:1353 msgid "" "The linux_proto.h contains structure definitions of " "arguments to every syscall, e.g.:" msgstr "" "O linux_proto.h contém definições de estrutura de " "argumentos para cada syscall, por exemplo:" #. (itstool) path: sect3/programlisting #: article.translate.xml:1357 #, no-wrap msgid "" "struct linux_fork_args {\n" " register_t dummy;\n" "};" msgstr "" "struct linux_fork_args {\n" " register_t dummy;\n" "};" #. (itstool) path: sect3/para #: article.translate.xml:1361 msgid "" "And finally, linux_sysent.c contains structure " "describing the system entry table, used to actually dispatch a syscall, e.g.:" msgstr "" "E finalmente, linux_sysent.c contém uma estrutura " "descrevendo a tabela de entrada do sistema, usada para realmente enviar um " "syscall, por exemplo:" #. (itstool) path: sect3/programlisting #: article.translate.xml:1365 #, no-wrap msgid "" "{ 0, (sy_call_t *)linux_fork, AUE_FORK, NULL, 0, 0 }, /* 2 = linux_fork */\n" "{ AS(close_args), (sy_call_t *)close, AUE_CLOSE, NULL, 0, 0 }, /* 6 = close */" msgstr "" "{ 0, (sy_call_t *)linux_fork, AUE_FORK, NULL, 0, 0 }, /* 2 = linux_fork */\n" "{ AS(close_args), (sy_call_t *)close, AUE_CLOSE, NULL, 0, 0 }, /* 6 = close */" #. (itstool) path: sect3/para #: article.translate.xml:1368 msgid "" "As you can see linux_fork is implemented in Linuxulator " "itself so the definition is of STD type and has no " "argument, which is exhibited by the dummy argument structure. On the other " "hand close is just an alias for real FreeBSD " "close2 so it has no linux arguments structure associated and in the " "system entry table it is not prefixed with linux as it calls the real " "close2 in the kernel." msgstr "" "Como você pode ver, linux_fork é implementado no " "próprio Linuxulator, então a definição é do tipo STD e " "não possui argumento, que é exibido pela estrutura de argumento fictícia. " "Por outro lado, close é apenas um apelido para o " "verdadeiro close2 do FreeBSD para que ele não possua estrutura de " "argumentos do linux associada e na tabela de entrada do sistema ele não é " "prefixado com linux, pois ele chama o verdadeiro " "close2 no kernel." #. (itstool) path: sect3/title #: article.translate.xml:1380 msgid "Dummy syscalls" msgstr "Dummy syscalls" #. (itstool) path: sect3/para #: article.translate.xml:1382 msgid "" "The Linux emulation layer is not " "complete, as some syscalls are not implemented properly and some are not " "implemented at all. The emulation layer employs a facility to mark " "unimplemented syscalls with the DUMMY macro. These dummy " "definitions reside in linux_dummy.c in a form of " "DUMMY(syscall);, which is then translated to various " "syscall auxiliary files and the implementation consists of printing a " "message saying that this syscall is not implemented. The UNIMPL prototype is not used because we want to be able to identify the " "name of the syscall that was called in order to know what syscalls are more " "important to implement." msgstr "" "A camada de emulação do Linux " "não está completa, pois algumas syscalls não estão implementadas " "corretamente e algumas não estão implementadas. A camada de emulação emprega " "um recurso para marcar syscalls não implementadas com a macro " "DUMMY. Estas definições fictícias residem em " "linux_dummy.c em uma forma de DUMMY(syscall); " ", que é então traduzido para vários arquivos auxiliares de syscall " "e a implementação consiste em imprimir uma mensagem dizendo que esta syscall " "não está implementada. O protótipo UNIMPL não é usado " "porque queremos ser capazes de identificar o nome da syscall que foi chamado " "para saber o que é mais importante implementar na syscalls." #. (itstool) path: sect2/title #: article.translate.xml:1399 msgid "Signal handling" msgstr "Manuseio de signals" #. (itstool) path: sect2/para #: article.translate.xml:1401 msgid "" "Signal handling is done generally in the FreeBSD kernel for all binary " "compatibilities with a call to a compat-dependent layer. Linux compatibility layer defines " "linux_sendsig routine for this purpose." msgstr "" "A manipulação de sinais é feita geralmente no kernel do FreeBSD para todas " "as compatibilidades binárias com uma chamada para uma camada dependente de " "compatibilidade. A camada de compatibilidade do Linux define a rotina linux_sendsig " "para essa finalidade." #. (itstool) path: sect3/title #: article.translate.xml:1408 msgid "Linux sendsig" msgstr "Linux sendsig" #. (itstool) path: sect3/para #: article.translate.xml:1410 msgid "" "This routine first checks whether the signal has been installed with a " "SA_SIGINFO in which case it calls " "linux_rt_sendsig routine instead. Furthermore, it " "allocates (or reuses an already existing) signal handle context, then it " "builds a list of arguments for the signal handler. It translates the signal " "number based on the signal translation table, assigns a handler, translates " "sigset. Then it saves context for the sigreturn routine " "(various registers, translated trap number and signal mask). Finally, it " "copies out the signal context to the userspace and prepares context for the " "actual signal handler to run." msgstr "" "Esta rotina primeiro verifica se o signal foi instalado com um " "SA_SIGINFO, caso em que chama a rotina " "linux_rt_sendsig. Além disso, ele aloca (ou reutiliza " "um contexto de identificador de sinal já existente) e cria uma lista de " "argumentos para o manipulador de signal. Ele traduz o número do signal " "baseado na tabela de tradução do signal, atribui um manipulador, traduz o " "sigset. Em seguida, ele salva o contexto para a rotina sigreturn (vários registradores, número da trap traduzida e máscara de " "signal). Finalmente, copia o contexto do signal para o espaço do usuário e " "prepara o contexto para que o manipulador de sinal real seja executado." #. (itstool) path: sect3/title #: article.translate.xml:1425 msgid "linux_rt_sendsig" msgstr "linux_rt_sendsig" #. (itstool) path: sect3/para #: article.translate.xml:1427 msgid "" "This routine is similar to linux_sendsig just the " "signal context preparation is different. It adds siginfo, " "ucontext, and some POSIX parts. It might be worth considering whether those two functions " "could not be merged with a benefit of less code duplication and possibly " "even faster execution." msgstr "" "Esta rotina é similar a linux_sendsig apenas a " "preparação do contexto do sinal é diferente. Adiciona siginfo, ucontext e algumas partes do POSIX. Pode valer a pena considerar se essas duas " "funções não poderiam ser mescladas com um benefício de menos duplicação de " "código e, possivelmente, até mesmo execução mais rápida." #. (itstool) path: sect3/title #: article.translate.xml:1438 msgid "linux_sigreturn" msgstr "linux_sigreturn" #. (itstool) path: sect3/para #: article.translate.xml:1440 msgid "" "This syscall is used for return from the signal handler. It does some " "security checks and restores the original process context. It also unmasks " "the signal in process signal mask." msgstr "" "Esta syscall é usada para retornar do manipulador de sinal. Ela faz algumas " "verificações de segurança e restaura o contexto do processo original. Também " "desmascara o sinal na máscara de sinal do processo." #. (itstool) path: sect2/title #: article.translate.xml:1448 msgid "Ptrace" msgstr "Ptrace" #. (itstool) path: sect2/para #: article.translate.xml:1450 msgid "" "Many UNIX derivates implement " "the ptrace2 syscall in order to allow various tracking and " "debugging features. This facility enables the tracing process to obtain " "various information about the traced process, like register dumps, any " "memory from the process address space, etc. and also to trace the process " "like in stepping an instruction or between system entries (syscalls and " "traps). ptrace2 also lets you set various information in the " "traced process (registers etc.). ptrace2 is a UNIX-wide standard implemented in most UNIXes around the world." msgstr "" "Muitos derivados do UNIX " "implementam a syscall ptrace2 para permitir vários " "recursos de rastreamento e depuração . Esse recurso permite que o processo " "de rastreamento obtenha várias informações sobre o processo rastreado, como " "registros de despejos, qualquer memória do espaço de endereço do processo, " "etc. e também para rastrear o processo, como em uma instrução ou entre " "entradas do sistema (syscalls e traps). ptrace2 também permite definir " "várias informações no processo de rastreamento (registros, etc.). " "ptrace2 é um padrão de toda o UNIX implementado na maioria dos UNIXes em todo o mundo." #. (itstool) path: sect2/para #: article.translate.xml:1461 msgid "" "Linux emulation in FreeBSD " "implements the ptrace2 facility in " "linux_ptrace.c. The routines for converting registers " "between Linux and FreeBSD and " "the actual ptrace2 syscall emulation syscall. The syscall is a long " "switch block that implements its counterpart in FreeBSD for every " "ptrace2 command. The ptrace2 commands are mostly " "equal between Linux and FreeBSD " "so usually just a small modification is needed. For example, " "PT_GETREGS in Linux operates on direct data while FreeBSD uses a pointer to the data " "so after performing a (native) ptrace2 syscall, a copyout " "must be done to preserve Linux " "semantics." msgstr "" "Emulação do Linux no FreeBSD " "implementa a habilidade ptrace2 em " "linux_ptrace.c. As rotinas para converter registradores " "entre Linux and FreeBSD e a " "atual emulação de syscall, syscall ptrace2. A syscall é um longo " "bloco de trocas que implementa em contraparte no FreeBSD para todo comando " "ptrace2. Os comandos ptrace2 são em sua maioria " "igual entre Linux e FreeBSD " "então uma pequena modificação é necessária. Por exemplo, " "PT_GETREGS em Linux opera diretamente dos dados enquanto o FreeBSD usa um ponteiro " "para o dado e depois performa a syscall ptrace2 (nativa), uma cópia " "deve ser feita pra preservar a semantica do Linux." #. (itstool) path: sect2/para #: article.translate.xml:1474 msgid "" "The ptrace2 implementation in Linuxulator has some known " "weaknesses. There have been panics seen when using strace " "(which is a ptrace2 consumer) in the Linuxulator environment. Also " "PT_SYSCALL is not implemented." msgstr "" "A implementação de ptrace2 no Linuxulator tem " "algumas fraquezas conhecidas. Houve pânico ao usar o strace (que é um consumidor ptrace2) no ambiente " "Linuxulator. PT_SYSCALL também não está implementado." #. (itstool) path: sect2/para #: article.translate.xml:1484 msgid "" "Whenever a Linux process running " "in the emulation layer traps the trap itself is handled transparently with " "the only exception of the trap translation. Linux and FreeBSD differs in opinion on what a trap is so " "this is dealt with here. The code is actually very short:" msgstr "" "Sempre que um processo Linux " "executado na camada de emulação captura a própria trap, ela é tratada de " "forma transparente com a única exceção da tradução de trap. Linux e o FreeBSD difere de opinião sobre o que é " "uma trap, então isso é tratado aqui. O código é realmente muito curto:" #. (itstool) path: sect2/programlisting #: article.translate.xml:1490 #, no-wrap msgid "" "static int\n" "translate_traps(int signal, int trap_code)\n" "{\n" "\n" " if (signal != SIGBUS)\n" " return signal;\n" "\n" " switch (trap_code) {\n" "\n" " case T_PROTFLT:\n" " case T_TSSFLT:\n" " case T_DOUBLEFLT:\n" " case T_PAGEFLT:\n" " return SIGSEGV;\n" "\n" " default:\n" " return signal;\n" " }\n" "}" msgstr "" "static int\n" "translate_traps(int signal, int trap_code)\n" "{\n" "\n" " if (signal != SIGBUS)\n" " return signal;\n" "\n" " switch (trap_code) {\n" "\n" " case T_PROTFLT:\n" " case T_TSSFLT:\n" " case T_DOUBLEFLT:\n" " case T_PAGEFLT:\n" " return SIGSEGV;\n" "\n" " default:\n" " return signal;\n" " }\n" "}" #. (itstool) path: sect2/title #: article.translate.xml:1512 msgid "Stack fixup" msgstr "Correção de pilha" #. (itstool) path: sect2/para #: article.translate.xml:1514 msgid "" "The RTLD run-time link-editor expects so called AUX tags on stack during an " "execve so a fixup must be done to ensure this. Of " "course, every RTLD system is different so the emulation layer must provide " "its own stack fixup routine to do this. So does Linuxulator. The " "elf_linux_fixup simply copies out AUX tags to the stack " "and adjusts the stack of the user space process to point right after those " "tags. So RTLD works in a smart way." msgstr "" "O editor de links em tempo de execução do RTLD espera as chamadas tags AUX " "na pilha durante uma execve, portanto, uma correção " "deve ser feita para garantir isso. Naturalmente, cada sistema RTLD é " "diferente, portanto, a camada de emulação deve fornecer sua própria rotina " "de correção de pilha para fazer isso. O mesmo acontece com o Linuxulator. O " "elf_linux_fixup simplesmente copia tags AUX para a " "pilha e ajusta a pilha do processo de espaço do usuário para apontar logo " "após essas tags. Então, a RTLD funciona de maneira inteligente." #. (itstool) path: sect2/title #: article.translate.xml:1526 msgid "A.OUT support" msgstr "Suporte para A.OUT" #. (itstool) path: sect2/para #: article.translate.xml:1528 msgid "" "The Linux emulation layer on " "i386 also supports Linux A.OUT " "binaries. Pretty much everything described in the previous sections must be " "implemented for A.OUT support (beside traps translation and signals " "sending). The support for A.OUT binaries is no longer maintained, especially " "the 2.6 emulation does not work with it but this does not cause any problem, " "as the linux-base in ports probably do not support A.OUT binaries at all. " "This support will probably be removed in future. Most of the stuff necessary " "for loading Linux A.OUT binaries " "is in imgact_linux.c file." msgstr "" "A camada de emulação Linux em " "i386 também suporta os binários Linux A.OUT. Praticamente tudo o que foi descrito nas seções anteriores " "deve ser implementado para o suporte A.OUT (além da tradução de traps e o " "envio de sinais). O suporte para binários A.OUT não é mais mantido, " "especialmente a emulação 2.6 não funciona com ele, mas isso não causa nenhum " "problema, já que os ports linux-base provavelmente não suportam binários A." "OUT. Esse suporte provavelmente será removido no futuro. A maioria das " "coisas necessárias para carregar os binários Linux A.OUT está no arquivo imgact_linux.c." #. (itstool) path: sect1/title #: article.translate.xml:1543 msgid "" "Linux emulation layer -MI part" msgstr "" "Parte da amada de emulação -MI do Linux " #. (itstool) path: sect1/para #: article.translate.xml:1545 msgid "" "This section talks about machine independent part of the Linuxulator. It " "covers the emulation infrastructure needed for Linux 2.6 emulation, the thread local storage (TLS) " "implementation (on i386) and futexes. Then we talk briefly about some " "syscalls." msgstr "" "Esta seção fala sobre parte independente de máquina do Linuxulator. Ele " "cobre a infra-estrutura de emulação necessária para a emulação do Linux 2.6, a implementação do TLS (thread " "local storage) (no i386) e os futexes. Então falamos brevemente sobre " "algumas syscalls." #. (itstool) path: sect2/title #: article.translate.xml:1552 msgid "Description of NPTL" msgstr "Descrição do NPTL" #. (itstool) path: sect2/para #: article.translate.xml:1554 msgid "" "One of the major areas of progress in development of Linux 2.6 was threading. Prior to 2.6, the " "Linux threading support was " "implemented in the linuxthreads library. The " "library was a partial implementation of POSIX threading. The threading was implemented using separate " "processes for each thread using the clone syscall to " "let them share the address space (and other things). The main weaknesses of " "this approach was that every thread had a different PID, signal handling was " "broken (from the pthreads perspective), etc. Also the performance was not " "very good (use of SIGUSR signals for threads " "synchronization, kernel resource consumption, etc.) so to overcome these " "problems a new threading system was developed and named NPTL." msgstr "" "Uma das principais áreas de progresso no desenvolvimento do Linux 2.6 foi o threading. Antes do 2.6, o " "suporte ao threading Linux era " "implementado na biblioteca linuxthreads. A " "biblioteca foi uma implementação parcial do threading POSIX. A segmentação foi implementada usando " "processos separados para cada threading usando a syscall clone para permitir que eles compartilhem o espaço de endereço (e outras " "coisas). A principal fraqueza desta abordagem era que cada thread tinha um " "PID diferente, o tratamento de sinal era quebrado (da perspectiva pthreads), " "etc. O desempenho também não era muito bom (uso de sinais SIGUSR para sincronização de threads) , consumo de recursos do kernel, " "etc.) para superar esses problemas, um novo sistema de threading foi " "desenvolvido e denominado NPTL." #. (itstool) path: sect2/para #: article.translate.xml:1570 msgid "" "The NPTL library focused on two things but a third thing came along so it is " "usually considered a part of NPTL. Those two things were embedding of " "threads into a process structure and futexes. The additional third thing was " "TLS, which is not directly required by NPTL but the whole NPTL userland " "library depends on it. Those improvements yielded in much improved " "performance and standards conformance. NPTL is a standard threading library " "in Linux systems these days." msgstr "" "A biblioteca NPTL focou em duas coisas, mas uma terceira coisa apareceu, " "então é normalmente considerada parte do NPTL. Essas duas coisas eram a " "incorporação de threads em uma estrutura de processo e futexes. A terceira " "coisa adicional foi o TLS, que não é diretamente exigido pelo NPTL, mas toda " "a biblioteca de usuário do NPTL depende dele. Essas melhorias resultaram em " "muito melhor desempenho e conformidade com os padrões. O NPTL é uma " "biblioteca de threading padrão nos sistemas Linux atualmente." #. (itstool) path: sect2/para #: article.translate.xml:1579 msgid "" "The FreeBSD Linuxulator implementation approaches the NPTL in three main " "areas. The TLS, futexes and PID mangling, which is meant to simulate the " "Linux threads. Further sections " "describe each of these areas." msgstr "" "A implementação do FreeBSD Linuxulator se aproxima do NPTL em três áreas " "principais. O TLS, futexes e PID mangling, que serve para simular as " "threadings Linux. Outras seções " "descrevem cada uma dessas áreas." #. (itstool) path: sect2/title #: article.translate.xml:1586 msgid "" "Linux 2.6 emulation " "infrastructure" msgstr "" "Infra-estrutura de emulação do Linux 2.6" #. (itstool) path: sect2/para #: article.translate.xml:1588 msgid "" "These sections deal with the way Linux threads are managed and how we simulate that in FreeBSD." msgstr "" "Estas seções tratam da maneira como as threadings Linux são gerenciadas e como nós simulamos isso " "no FreeBSD." #. (itstool) path: sect3/title #: article.translate.xml:1592 msgid "Runtime determining of 2.6 emulation" msgstr "Determinação de tempo de execução de emulação 2.6" #. (itstool) path: sect3/para #: article.translate.xml:1594 msgid "" "The Linux emulation layer in " "FreeBSD supports runtime setting of the emulated version. This is done via " "sysctl8, namely compat.linux.osrelease. Setting " "this sysctl8 affects runtime behavior of the emulation layer. " "When set to 2.6.x it sets the value of linux_use_linux26 " "while setting to something else keeps it unset. This variable (plus per-" "prison variables of the very same kind) determines whether 2.6 " "infrastructure (mainly PID mangling) is used in the code or not. The version " "setting is done system-wide and this affects all Linux processes. The " "sysctl8 should not be changed when running any Linux binary as it might harm things." msgstr "" "A camada de emulação do Linux no " "FreeBSD suporta a configuração de tempo de execução da versão emulada. Isso " "é feito via sysctl8, a saber compat.linux.osrelease. A configuração dessa sysctl8 afeta o comportamento " "de tempo de execução da camada de emulação. Quando definido como 2.6.x, ele " "configura o valor de linux_use_linux26 enquanto a " "configuração para algo mais o mantém não definido. Essa variável (mais " "variáveis ​​por prisão do mesmo tipo) determina se a infraestrutura 2.6 " "(principalmente o PID) é usada no código ou não. A configuração da versão é " "feita em todo o sistema e isso afeta todos os processos Linux. A sysctl8 não deve ser alterada " "ao executar qualquer binário do Linux, pois pode causar danos ." #. (itstool) path: sect3/title #: article.translate.xml:1611 msgid "" "Linux processes and thread " "identifiers" msgstr "" "Processos e identificadores de threading Linux" #. (itstool) path: sect3/para #: article.translate.xml:1613 msgid "" "The semantics of Linux threading " "are a little confusing and uses entirely different nomenclature to FreeBSD. " "A process in Linux consists of a " "struct task embedding two identifier fields - PID and " "TGID. PID is not a process ID but it is a thread ID. " "The TGID identifies a thread group in other words a process. For single-" "threaded process the PID equals the TGID." msgstr "" "A semântica de threading Linux é " "um pouco confusa e usa uma nomenclatura inteiramente diferente do FreeBSD. " "Um processo em Linux consiste em " "uma struct task incorporando dois campos identificadores " "- PID e TGID. O PID não é um ID de processo, mas é um " "ID de thread. O TGID identifica um grupo de threads em outras palavras, um " "processo. Para o processo single-threaded, o PID é igual ao TGID." #. (itstool) path: sect3/para #: article.translate.xml:1622 msgid "" "The thread in NPTL is just an ordinary process that happens to have TGID not " "equal to PID and have a group leader not equal to itself (and shared VM etc. " "of course). Everything else happens in the same way as to an ordinary " "process. There is no separation of a shared status to some external " "structure like in FreeBSD. This creates some duplication of information and " "possible data inconsistency. The Linux kernel seems to use task -> group information in some places " "and task information elsewhere and it is really not very consistent and " "looks error-prone." msgstr "" "A thread no NPTL é apenas um processo comum que acontece de ter TGID " "diferente de PID e ter um líder de grupo diferente de si mesmo (e VM " "compartilhada, é claro). Tudo o mais acontece da mesma maneira que em um " "processo comum. Não há separação de um status compartilhado para alguma " "estrutura externa como no FreeBSD. Isso cria alguma duplicação de " "informações e possível inconsistência de dados. O kernel Linux parece usar a tarefa -> grupo de " "informações em alguns lugares e informações de tarefas em outros lugares e " "isso não é muito consistente e parece propenso a erros." #. (itstool) path: sect3/para #: article.translate.xml:1633 msgid "" "Every NPTL thread is created by a call to the clone " "syscall with a specific set of flags (more in the next subsection). The NPTL " "implements strict 1:1 threading." msgstr "" "Cada threading NPTL é criada por uma chamada a syscall clone com um conjunto específico de flags (mais na próxima subseção). O " "NPTL implementa segmentação rígida de 1:1." #. (itstool) path: sect3/para #: article.translate.xml:1638 msgid "" "In FreeBSD we emulate NPTL threads with ordinary FreeBSD processes that " "share VM space, etc. and the PID gymnastic is just mimicked in the emulation " "specific structure attached to the process. The structure attached to the " "process looks like:" msgstr "" "No FreeBSD nós emulamos threads NPTL com processos comuns do FreeBSD que " "compartilham espaço de VM, etc. e a ginástica PID é apenas imitada na " "estrutura específica de emulação anexada ao processo. A estrutura anexada ao " "processo se parece com:" #. (itstool) path: sect3/programlisting #: article.translate.xml:1644 #, no-wrap msgid "" "struct linux_emuldata {\n" " pid_t pid;\n" "\n" " int *child_set_tid; /* in clone(): Child.s TID to set on clone */\n" " int *child_clear_tid;/* in clone(): Child.s TID to clear on exit */\n" "\n" " struct linux_emuldata_shared *shared;\n" "\n" " int pdeath_signal; /* parent death signal */\n" "\n" " LIST_ENTRY(linux_emuldata) threads; /* list of linux threads */\n" "};" msgstr "" "struct linux_emuldata {\n" " pid_t pid;\n" "\n" " int *child_set_tid; /* in clone(): Child.s TID to set on clone */\n" " int *child_clear_tid;/* in clone(): Child.s TID to clear on exit */\n" "\n" " struct linux_emuldata_shared *shared;\n" "\n" " int pdeath_signal; /* parent death signal */\n" "\n" " LIST_ENTRY(linux_emuldata) threads; /* list of linux threads */\n" "};" #. (itstool) path: sect3/para #: article.translate.xml:1657 msgid "" "The PID is used to identify the FreeBSD process that attaches this " "structure. The child_se_tid and " "child_clear_tid are used for TID address copyout when a " "process exits and is created. The shared pointer points " "to a structure shared among threads. The pdeath_signal " "variable identifies the parent death signal and the threads pointer is used to link this structure to the list of threads. The " "linux_emuldata_shared structure looks like:" msgstr "" "O PID é usado para identificar o processo do FreeBSD que liga esta " "estrutura. child_se_tid e child_clear_tid " " são usadas para cópia do endereço TID quando um processo existe " "e é criado. O ponteiro shared aponta para uma estrutura " "compartilhada entre as threads. A variável pdeath_signal " "identifica o sinal de morte do processo pai e o ponteiro threads é usado para vincular essa estrutura à lista de threads. A " "estrutura linux_emuldata_shared se parece com:" #. (itstool) path: sect3/programlisting #: article.translate.xml:1670 #, no-wrap msgid "" "struct linux_emuldata_shared {\n" "\n" " int refs;\n" "\n" " pid_t group_pid;\n" "\n" " LIST_HEAD(, linux_emuldata) threads; /* head of list of linux threads */\n" "};" msgstr "" "struct linux_emuldata_shared {\n" "\n" " int refs;\n" "\n" " pid_t group_pid;\n" "\n" " LIST_HEAD(, linux_emuldata) threads; /* head of list of linux threads */\n" "};" #. (itstool) path: sect3/para #: article.translate.xml:1679 msgid "" "The refs is a reference counter being used to determine " "when we can free the structure to avoid memory leaks. The " "group_pid is to identify PID ( = TGID) of the whole " "process ( = thread group). The threads pointer is the " "head of the list of threads in the process." msgstr "" "O refs é um contador de referência sendo usado para " "determinar quando podemos liberar a estrutura para evitar vazamentos de " "memória. O group_pid é para identificar o PID (=TGID) de " "todo o processo (=grupo de threads). O ponteiro threads é " "o cabeçalho da lista de threading no processo." #. (itstool) path: sect3/para #: article.translate.xml:1686 msgid "" "The linux_emuldata structure can be obtained from the " "process using em_find. The prototype of the function is:" msgstr "" "A estrutura linux_emuldata pode ser obtida a partir do " "processo usando em_find. O protótipo da função é:" #. (itstool) path: sect3/programlisting #: article.translate.xml:1691 #, no-wrap msgid "struct linux_emuldata *em_find(struct proc *, int locked);" msgstr "struct linux_emuldata * em_find (struct proc *, int bloqueado);" #. (itstool) path: sect3/para #: article.translate.xml:1693 msgid "" "Here, proc is the process we want the emuldata structure " "from and the locked parameter determines whether we want to lock or not. The " "accepted values are EMUL_DOLOCK and " "EMUL_DOUNLOCK. More about locking later." msgstr "" "Aqui, proc é o processo em que queremos a estrutura " "emuldata e o parâmetro locked determina se queremos ou não bloquear. Os " "valores aceitos são EMUL_DOLOCK e EMUL_DOUNLOCK. Mais sobre o bloqueio mais tarde." #. (itstool) path: sect3/title #: article.translate.xml:1702 msgid "PID mangling" msgstr "Maqueando PID" #. (itstool) path: sect3/para #: article.translate.xml:1704 msgid "" "Because of the described different view knowing what a process ID and thread " "ID is between FreeBSD and Linux " "we have to translate the view somehow. We do it by PID mangling. This means " "that we fake what a PID (=TGID) and TID (=PID) is between kernel and " "userland. The rule of thumb is that in kernel (in Linuxulator) PID = PID and " "TGID = shared -> group pid and to userland we present PID = " "shared -> group_pid and TID = proc -> p_pid. The PID member of linux_emuldata structure is a " "FreeBSD PID." msgstr "" "Por causa da visão diferente descrita sabendo o que é um ID de processo e ID " "de thread entre o FreeBSD e o Linux nós temos que traduzir a view de alguma forma. Nós fazemos isso " "pelo manuseio do PID. Isto significa que nós falsificamos o que um PID " "(=TGID) e um TID (=PID) é entre o kernel e o userland. A regra é que no " "kernel (no Linuxulator) PID=PID e TGID=grupo de id -> compartilhado e " "para userland nós apresentamos PID=shared -> group_pid e TID=proc -> p_pid. O membro PID da " "estrutura linux_emuldata é um PID do FreeBSD." #. (itstool) path: sect3/para #: article.translate.xml:1716 msgid "" "The above affects mainly getpid, getppid, gettid syscalls. Where we use PID/" "TGID respectively. In copyout of TIDs in child_clear_tid and child_set_tid we copy out FreeBSD PID." msgstr "" "O acima afeta principalmente syscalls getyscl, getppid, gettid. Onde usamos " "PID/TGID, respectivamente. Em cópia de TIDs em child_clear_tid e child_set_tid copiamos o PID FreeBSD." #. (itstool) path: sect3/title #: article.translate.xml:1724 msgid "Clone syscall" msgstr "syscall Clone" #. (itstool) path: sect3/para #: article.translate.xml:1726 msgid "" "The clone syscall is the way threads are created in " "Linux. The syscall prototype " "looks like this:" msgstr "" "A syscall clone é o modo como as threads são criadas no " "Linux. O protótipo syscall é " "assim:" #. (itstool) path: sect3/programlisting #: article.translate.xml:1730 #, no-wrap msgid "" "int linux_clone(l_int flags, void *stack, void *parent_tidptr, int dummy,\n" "void * child_tidptr);" msgstr "" "int linux_clone(l_int flags, void *stack, void *parent_tidptr, int dummy,\n" "void * child_tidptr);" #. (itstool) path: sect3/para #: article.translate.xml:1733 msgid "" "The flags parameter tells the syscall how exactly the " "processes should be cloned. As described above, Linux can create processes sharing various things " "independently, for example two processes can share file descriptors but not " "VM, etc. Last byte of the flags parameter is the exit " "signal of the newly created process. The stack parameter " "if non-NULL tells, where the thread stack is and if it is " "NULL we are supposed to copy-on-write the calling process " "stack (i.e. do what normal fork2 routine does). The " "parent_tidptr parameter is used as an address for copying " "out process PID (i.e. thread id) once the process is sufficiently " "instantiated but is not runnable yet. The dummy parameter " "is here because of the very strange calling convention of this syscall on " "i386. It uses the registers directly and does not let the compiler do it " "what results in the need of a dummy syscall. The child_tidptr parameter is used as an address for copying out PID once the " "process has finished forking and when the process exits." msgstr "" "O parâmetro flags informa a syscall como exatamente os " "processos devem ser clonados. Como descrito acima, o Linux pode criar processos compartilhando várias " "coisas independentemente, por exemplo, dois processos podem compartilhar " "file descriptors, mas não VM, etc. Ultimo byte do parametro flags é o sinal de saída do processo recém-criado. O parâmetro " "stack se não NULL diz, onde está a " "pilha de threading e se é NULL nós devemos copiar-na-" "escrita chamando a pilha de processos (isto é, faz a rotina normal de " "fork2). O parâmetro parent_tidptr é usado como um " "endereço para copiar o PID do processo (ou seja, o id do thread), uma vez " "que o processo esteja suficientemente instanciado, mas ainda não seja " "executável. O parâmetro dummy está aqui devido à " "convenção de chamada muito estranha desta syscall em i386. Ele usa os " "registradores diretamente e não deixa o compilador fazer o que resulta na " "necessidade de uma syscall falsa. O parâmetro child_tidptr é usado como um endereço para copiar o PID assim que o processo " "terminar de bifurcar e quando o processo terminar." #. (itstool) path: sect3/para #: article.translate.xml:1755 msgid "" "The syscall itself proceeds by setting corresponding flags depending on the " "flags passed in. For example, CLONE_VM maps to RFMEM " "(sharing of VM), etc. The only nit here is CLONE_FS and " "CLONE_FILES because FreeBSD does not allow setting this " "separately so we fake it by not setting RFFDG (copying of fd table and other " "fs information) if either of these is defined. This does not cause any " "problems, because those flags are always set together. After setting the " "flags the process is forked using the internal fork1 " "routine, the process is instrumented not to be put on a run queue, i.e. not " "to be set runnable. After the forking is done we possibly reparent the newly " "created process to emulate CLONE_PARENT semantics. Next " "part is creating the emulation data. Threads in Linux does not signal their parents so we set exit signal to " "be 0 to disable this. After that setting of child_set_tid " "and child_clear_tid is performed enabling the " "functionality later in the code. At this point we copy out the PID to the " "address specified by parent_tidptr. The setting of " "process stack is done by simply rewriting thread frame %esp register (%rsp on amd64). Next part is setting " "up TLS for the newly created process. After this " "vfork2 semantics might be emulated and finally the newly created " "process is put on a run queue and copying out its PID to the parent process " "via clone return value is done." msgstr "" "O syscall prossegue definindo flags correspondentes dependendo dos flags " "passadas. Por exemplo, mapas CLONE_VM para RFMEM " "(compartilhamento de VM), etc. O único nit aqui é CLONE_FS e CLONE_FILES porque o FreeBSD não permite " "configurar isso separadamente, então nós o falsificamos não configurando " "RFFDG (copiando a tabela fd e outras informações fs) se qualquer uma delas " "estiver definida. Isso não causa nenhum problema, porque essas flags são " "sempre definidas juntas. Depois de definir as flags, o processo é bifurcado " "usando a rotina fork1 interna, o processo é " "instrumentado para não ser colocado em uma fila de execução, ou seja, não " "deve ser definido como executável. Depois que a bifurcação é feita, " "possivelmente reparamos o processo recém-criado para emular a semântica " "CLONE_PARENT. A próxima parte está criando os dados de " "emulação. Threads no Linux não " "sinalizam seus processos pais, então nós definimos o sinal de saída como 0 " "para desabilitar isso. Depois que a configuração de child_set_tid e child_clear_tid é executada, habilitando a " "funcionalidade posteriormente no código. Neste ponto, copiamos o PID para o " "endereço especificado por parent_tidptr. A configuração " "da pilha de processos é feita simplesmente reescrevendo o registro do quadro " "de linha % esp (% rsp no amd64). A " "próxima parte é configurar o TLS para o processo recém-criado. Depois disso, " "a semântica vfork2 pode ser emulada e, finalmente, o processo recém-" "criado é colocado em uma fila de execução e copiando seu PID para o processo " "pai através do valor de retorno clone é feito." #. (itstool) path: sect3/para #: article.translate.xml:1786 msgid "" "The clone syscall is able and in fact is used for " "emulating classic fork2 and " "vfork2 syscalls. Newer glibc in a case of 2.6 kernel uses " "clone to implement fork2 and " "vfork2 syscalls." msgstr "" "A syscall clone é capaz e de fato é usado para emulação " "de syscalls fork e vfork2. O glibc mais novo em " "um caso de kernel 2.6 usa o clone para implementar " "syscalls fork2 e vfork2." #. (itstool) path: sect3/title #: article.translate.xml:1794 msgid "Locking" msgstr "Bloqueio" #. (itstool) path: sect3/para #: article.translate.xml:1796 msgid "" "The locking is implemented to be per-subsystem because we do not expect a " "lot of contention on these. There are two locks: emul_lock used to protect manipulating of linux_emuldata " "and emul_shared_lock used to manipulate " "linux_emuldata_shared. The emul_lock " "is a nonsleepable blocking mutex while emul_shared_lock " "is a sleepable blocking sx_lock. Because of the per-" "subsystem locking we can coalesce some locks and that is why the em find " "offers the non-locking access." msgstr "" "O bloqueio é implementado como per-subsystem porque não esperamos muita " "disputa sobre eles. Existem dois bloqueios: emul_lock " "usado para proteger a manipulação de linux_emuldata e " "emul_shared_lock usado para manipular " "linux_emuldata_shared. O emul_lock é " "um mutex bloqueador não tolerável, enquanto emul_shared_lock é um bloqueio travável sx_lock. Devido ao " "bloqueio por subsistema, podemos unir alguns bloqueios e é por isso que o em-" "find oferece o acesso sem bloqueio." #. (itstool) path: sect2/title #: article.translate.xml:1812 msgid "TLS" msgstr "TLS" #. (itstool) path: sect2/para #: article.translate.xml:1814 msgid "This section deals with TLS also known as thread local storage." msgstr "" "Esta seção trata do TLS também conhecido como armazenamento local de thread." #. (itstool) path: sect3/title #: article.translate.xml:1818 msgid "Introduction to threading" msgstr "Introdução ao threading" #. (itstool) path: sect3/para #: article.translate.xml:1820 msgid "" "Threads in computer science are entities within a process that can be " "scheduled independently from each other. The threads in the process share " "process wide data (file descriptors, etc.) but also have their own stack for " "their own data. Sometimes there is a need for process-wide data specific to " "a given thread. Imagine a name of the thread in execution or something like " "that. The traditional UNIX " "threading API, pthreads provides a way to do it " "via pthread_key_create3, " "pthread_setspecific3 and " "pthread_getspecific3 where a thread can " "create a key to the thread local data and using " "pthread_getspecific3 or " "pthread_getspecific3 to manipulate those " "data. You can easily see that this is not the most comfortable way this " "could be accomplished. So various producers of C/C++ compilers introduced a " "better way. They defined a new modifier keyword thread that specifies that a " "variable is thread specific. A new method of accessing such variables was " "developed as well (at least on i386). The pthreads method tends to be implemented in userspace as a trivial lookup " "table. The performance of such a solution is not very good. So the new " "method uses (on i386) segment registers to address a segment, where TLS area " "is stored so the actual accessing of a thread variable is just appending the " "segment register to the address thus addressing via it. The segment " "registers are usually %gs and %fs " "acting like segment selectors. Every thread has its own area where the " "thread local data are stored and the segment must be loaded on every context " "switch. This method is very fast and used almost exclusively in the whole " "i386 UNIX world. Both FreeBSD " "and Linux implement this " "approach and it yields very good results. The only drawback is the need to " "reload the segment on every context switch which can slowdown context " "switches. FreeBSD tries to avoid this overhead by using only 1 segment " "descriptor for this while Linux " "uses 3. Interesting thing is that almost nothing uses more than 1 descriptor " "(only Wine seems to use 2) so Linux pays this unnecessary price for context " "switches." msgstr "" "Threads na ciência da computação são entidades com um processo que podem ser " "agendados independentemente de qualquer outro. As threads nos processos " "compartilham amplos dados de processos (file descriptors, etc.) mas também " "tem sua prŕopria pilha para seus próprios dados. Algumas vezes é preciso " "para um processamento amplo de dados dado uma thread. Imagine um nome de uma " "thread algo assim. A tradicional API de threading do UNIX, pthreads prove " "um caminho para isso em pthread_key_create3, " "pthread_setspecific3 and " "pthread_getspecific3 onde a thread pode " "criar uma chave para os dados da thread local " "pthread_getspecific3 ou " "pthread_getspecific3 para manipular esses " "dados. Você pode ver que esse não é o caminho mais confortavel que poderia " "ser usado. Então varios produtores de compiladores C/C++ introduziram um " "caminho melhor. Eles definiram uma nova chave modificadora de thread que " "especifica que a variavel é especifica de uma thread. Um novo método de " "acessar as variaveis foi desenvolvio como (ao menos no i386). O método " "pthreads tende a ser implementado no espaço de " "usuário como uma tabela de lookup trivial. A performance como uma solução " "não é muito boa. Então o novo método (no i386) registradores de segmentos " "para endereçar um segmento, onde a área do TLS é armazenada, então o atual " "acesso da variável de uma thread é apenas adicionada ao registrador de " "segmentos para o endereçamento via it. Os registradores de segmentos são " "usualmente %gs e %fs agindo como " "seletores de segmento. Toda thread tem sua própria área onde os dados da " "thread local são armazenados e o segmento deve ser carregado em toda troca " "de contexto. Esse método é muito rapido e usado em todo mundo em volta do " "UNIX i386. Ambos FreeBSD e " "Linux Implementam sua abordagem " "e seus resultados tem sido muito bons. Unico ponto negativo é ter que " "recarregar o segmento em toda troca de contexto que pode deixar o processo " "lento. FreeBSD tenta evitar essa sobrecarga usando apenas 1 descritor de " "segmento enquanto Linux usa 3. " "Interessante que isso quase nunca usa mais que 1 descritor (apenas o " "Wine parece usar 2) então o Linux paga esse preço desnecessário na troca de " "contexto." #. (itstool) path: sect3/title #: article.translate.xml:1864 msgid "Segments on i386" msgstr "Segmentos em i386" #. (itstool) path: sect3/para #: article.translate.xml:1866 msgid "" "The i386 architecture implements the so called segments. A segment is a " "description of an area of memory. The base address (bottom) of the memory " "area, the end of it (ceiling), type, protection, etc. The memory described " "by a segment can be accessed using segment selector registers (%cs, %ds, %ss, %es, %fs, %gs). For example let " "us suppose we have a segment which base address is 0x1234 and length and " "this code:" msgstr "" "A arquitetura i386 implementa os então chamados segmentos.Um segmento é uma " "descrição de um espaço na memória. A base de endereço (baixa) na area da " "memória, o fim disso (teto), tipo, proteção, etc. A memória descrita por um " "segmento pode ser acessada usando um seletor de segmento (%cs, %ds, %ss, %es, %fs, %gs). Por exemplo, " "deixe nos supor que temos um segmento com base no endereço 0x1234 e " "comprimento e esse codigo:" #. (itstool) path: sect3/programlisting #: article.translate.xml:1877 #, no-wrap msgid "mov %edx,%gs:0x10" msgstr "mov %edx,%gs:0x10" #. (itstool) path: sect3/para #: article.translate.xml:1879 msgid "" "This will load the content of the %edx register into " "memory location 0x1244. Some segment registers have a special use, for " "example %cs is used for code segment and %ss is used for stack segment but %fs and " "%gs are generally unused. Segments are either stored in a global " "GDT table or in a local LDT table. LDT is accessed via an entry in the GDT. " "The LDT can store more types of segments. LDT can be per process. Both " "tables define up to 8191 entries." msgstr "" "Isso carregará o conteúdo do registro % edx na " "localização da memória 0x1244. Alguns registradores de segmento têm um uso " "especial, por exemplo % cs é usado para segmento de " "código e % ss é usado para o segmento de pilha, mas " "% fs e % gs geralmente não são usados. " "Os segmentos são armazenados em uma tabela GDT global ou em uma tabela LDT " "local. O LDT é acessado por meio de uma entrada no GDT. O LDT pode armazenar " "mais tipos de segmentos. LDT pode ser por processo. Ambas as tabelas definem " "até 8191 entradas." #. (itstool) path: sect3/title #: article.translate.xml:1893 msgid "" "Implementation on Linux i386" msgstr "" "Implementação no Linux i386" #. (itstool) path: sect3/para #: article.translate.xml:1895 msgid "" "There are two main ways of setting up TLS in Linux. It can be set when cloning a process using the " "clone syscall or it can call set_thread_area. When a process passes CLONE_SETTLS flag to " "clone, the kernel expects the memory pointed to by the " "%esi register a Linux user space representation of a segment, which gets translated to " "the machine representation of a segment and loaded into a GDT slot. The GDT " "slot can be specified with a number or -1 can be used meaning that the " "system itself should choose the first free slot. In practice, the vast " "majority of programs use only one TLS entry and does not care about the " "number of the entry. We exploit this in the emulation and in fact depend on " "it." msgstr "" "Existem duas maneiras principais de configurar o TLS no Linux. Pode ser definido ao clonar um processo " "usando a syscall clone ou ele pode chamar " "set_thread_area. Quando um processo passa a flag " "CLONE_SETTLS para clone, o kernel " "espera que a memória apontada pelo registrador % esi uma " "representação Linux do espaço " "do usuário de um segmento, que é traduzido para a representação da máquina " "de um segmento e carregado em um slot GDT. O slot GDT pode ser especificado " "com um número ou -1 pode ser usado, o que significa que o próprio sistema " "deve escolher o primeiro slot livre. Na prática, a grande maioria dos " "programas usa apenas uma entrada de TLS e não se importa com o número da " "entrada. Nós exploramos isso na emulação e dependemos disso." #. (itstool) path: sect3/title #: article.translate.xml:1913 msgid "Emulation of Linux TLS" msgstr "Emulação de TLS do Linux" #. (itstool) path: sect4/title #: article.translate.xml:1916 msgid "i386" msgstr "i386" #. (itstool) path: sect4/para #: article.translate.xml:1918 msgid "" "Loading of TLS for the current thread happens by calling " "set_thread_area while loading TLS for a second process " "in clone is done in the separate block in " "clone. Those two functions are very similar. The only " "difference being the actual loading of the GDT segment, which happens on the " "next context switch for the newly created process while " "set_thread_area must load this directly. The code " "basically does this. It copies the Linux form segment descriptor from the userland. The code checks for " "the number of the descriptor but because this differs between FreeBSD and " "Linux we fake it a little. We " "only support indexes of 6, 3 and -1. The 6 is genuine Linux number, 3 is genuine FreeBSD one and -1 " "means autoselection. Then we set the descriptor number to constant 3 and " "copy out this to the userspace. We rely on the userspace process using the " "number from the descriptor but this works most of the time (have never seen " "a case where this did not work) as the userspace process typically passes in " "1. Then we convert the descriptor from the Linux form to a machine dependant form (i.e. operating system " "independent form) and copy this to the FreeBSD defined segment descriptor. " "Finally we can load it. We assign the descriptor to threads PCB (process " "control block) and load the %gs segment using " "load_gs. This loading must be done in a critical " "section so that nothing can interrupt us. The CLONE_SETTLS case works exactly like this just the loading using " "load_gs is not performed. The segment used for this " "(segment number 3) is shared for this use between FreeBSD processes and " "Linux processes so the " "Linux emulation layer does not " "add any overhead over plain FreeBSD." msgstr "" "O carregamento de TLS para o segmento atual acontece chamando " "set_thread_area enquanto o TLS é carregado para um " "segundo processo em clone é feito no bloco separado em " "clone. Essas duas funções são muito semelhantes. A " "única diferença é o carregamento real do segmento GDT, que acontece na " "próxima troca de contexto para o processo recém-criado, enquanto " "set_thread_area deve carregar isso diretamente. O " "código basicamente faz isso. Ele copia o descritor de segmento de formulário " "Linux da área de usuário. O " "código verifica o número do descritor, mas como isso difere entre o FreeBSD " "e o Linux, maquiamos um pouco. " "Nós suportamos apenas índices de 6, 3 e -1. O número 6 é genuíno do " "Linux, 3 é genuíno do FreeBSD " "one e -1 significa uma auto seleção. Em seguida, definimos o número do " "descritor como constante 3 e copiamos isso para o espaço do usuário. " "Contamos com o processo em espaço de usuário usando o número do descritor, " "mas isso funciona na maior parte do tempo (nunca vi um caso em que isso não " "funcionou), como o processo em espaço de usuário normalmente passa em 1. " "Então, convertemos o descritor da classe do Linux para um formulário dependente da máquina (isto é, " "independente do sistema operacional) e copie isto para o descritor de " "segmento definido pelo FreeBSD. Finalmente podemos carregá-lo. Atribuímos o " "descritor às threads PCB (bloco de controle de processo) e carregamos o " "segmento % gs usando load_gs. Este " "carregamento deve ser feito em uma seção crítica para que nada possa nos " "interromper. O caso CLONE_SETTLS funciona exatamente como " "este, apenas o carregamento usando load_gs não é " "executado. O segmento usado para isso (segmento número 3) é compartilhado " "para este uso entre os processos do FreeBSD e do Linux para que a camada de emulação Linux não adicione nenhuma sobrecarga sobre " "o FreeBSD." #. (itstool) path: sect4/title #: article.translate.xml:1955 msgid "amd64" msgstr "amd64" #. (itstool) path: sect4/para #: article.translate.xml:1957 msgid "" "The amd64 implementation is similar to the i386 one but there was initially " "no 32bit segment descriptor used for this purpose (hence not even native " "32bit TLS users worked) so we had to add such a segment and implement its " "loading on every context switch (when a flag signaling use of 32bit is set). " "Apart from this the TLS loading is exactly the same just the segment numbers " "are different and the descriptor format and the loading differs slightly." msgstr "" "A implementação do amd64 é semelhante à do i386, mas inicialmente não havia " "um descritor de segmento de 32 bits usado para esse propósito (por isso nem " "usuários nativos de TLB de 32 bits trabalhavam), então tivemos que adicionar " "esse segmento e implementar seu carregamento em cada troca de contexto " "(quando a flag sinalizando uso de 32 bits está definida). Além disso, o " "carregamento de TLS é exatamente o mesmo, apenas os números de segmento são " "diferentes e o formato do descritor e o carregamento diferem ligeiramente." #. (itstool) path: sect2/title #: article.translate.xml:1971 msgid "Futexes" msgstr "Futexes" #. (itstool) path: sect3/title #: article.translate.xml:1974 msgid "Introduction to synchronization" msgstr "Introdução à sincronização" #. (itstool) path: sect3/para #: article.translate.xml:1976 msgid "" "Threads need some kind of synchronization and POSIX provides some of them: mutexes for mutual exclusion, " "read-write locks for mutual exclusion with biased ratio of reads and writes " "and condition variables for signaling a status change. It is interesting to " "note that POSIX threading API " "lacks support for semaphores. Those synchronization routines implementations " "are heavily dependant on the type threading support we have. In pure 1:M " "(userspace) model the implementation can be solely done in userspace and " "thus be very fast (the condition variables will probably end up being " "implemented using signals, i.e. not fast) and simple. In 1:1 model, the " "situation is also quite clear - the threads must be synchronized using " "kernel facilities (which is very slow because a syscall must be performed). " "The mixed M:N scenario just combines the first and second approach or rely " "solely on kernel. Threads synchronization is a vital part of thread-enabled " "programming and its performance can affect resulting program a lot. Recent " "benchmarks on FreeBSD operating system showed that an improved sx_lock " "implementation yielded 40% speedup in ZFS (a heavy sx " "user), this is in-kernel stuff but it shows clearly how important the " "performance of synchronization primitives is." msgstr "" "Threads precisam de algum tipo de sincronização e POSIX fornece alguns deles: mutexes para exclusão " "mútua, bloqueios de leitura/gravação para exclusão mútua com relação de " "polarização de leituras e gravações e variáveis ​​de condição para sinalizar " "um mudança de status. É interessante observar que a API de thread POSIX não tem suporte para semáforos. Essas " "implementações de rotinas de sincronização são altamente dependentes do tipo " "de suporte a threading que temos. No modelo puro 1:M (espaço de usuário), a " "implementação pode ser feita apenas no espaço do usuário e, portanto, ser " "muito rápida (as variáveis ​​de condição provavelmente serão implementadas " "usando sinais, ou seja, não rápido) e simples. No modelo 1:1, a situação " "também é bastante clara - as threading devem ser sincronizadas usando as " "facilidades do kernel (o que é muito lento porque uma syscall deve ser " "executada). O cenário M:N misto combina apenas a primeira e a segunda " "abordagem ou depende apenas do kernel. A sincronização de threads é uma " "parte vital da programação ativada por threads e seu desempenho pode afetar " "muito o programa resultante. Benchmarks recentes no sistema operacional " "FreeBSD mostraram que uma implementação sx_lock melhorada gerou 40% de " "aceleração no ZFS (um usuário sx pesado), isso é algo " "in-kernel, mas mostra claramente quão importante é o desempenho das " "primitivas de sincronização. ." #. (itstool) path: sect3/para #: article.translate.xml:2000 msgid "" "Threaded programs should be written with as little contention on locks as " "possible. Otherwise, instead of doing useful work the thread just waits on a " "lock. Because of this, the most well written threaded programs show little " "locks contention." msgstr "" "Os programas em threading devem ser escritos com o mínimo de contenção " "possível em bloqueios. Caso contrário, em vez de fazer um trabalho útil, a " "threading apenas espera em um bloqueio. Devido a isso, os programas " "encadeados mais bem escritos mostram pouca contenção de bloqueios." #. (itstool) path: sect3/title #: article.translate.xml:2008 msgid "Futexes introduction" msgstr "Introdução a Futexes" #. (itstool) path: sect3/para #: article.translate.xml:2010 msgid "" "Linux implements 1:1 threading, " "i.e. it has to use in-kernel synchronization primitives. As stated earlier, " "well written threaded programs have little lock contention. So a typical " "sequence could be performed as two atomic increase/decrease mutex reference " "counter, which is very fast, as presented by the following example:" msgstr "" "O Linux implementa a segmentação " "1:1, ou seja, tem de utilizar primitivas de sincronização no kernel. Como " "afirmado anteriormente, programas encadeados bem escritos possuem pouca " "contenção de bloqueio. Assim, uma sequência típica poderia ser executada " "como dois contador de referência de mutex de aumento/redução atômico, que é " "muito rápido, conforme apresentado pelo exemplo a seguir:" #. (itstool) path: sect3/programlisting #: article.translate.xml:2017 #, no-wrap msgid "" "pthread_mutex_lock(&mutex);\n" "....\n" "pthread_mutex_unlock(&mutex);" msgstr "" "pthread_mutex_lock(&mutex);\n" "....\n" "pthread_mutex_unlock(&mutex);" #. (itstool) path: sect3/para #: article.translate.xml:2021 msgid "" "1:1 threading forces us to perform two syscalls for those mutex calls, which " "is very slow." msgstr "" "O threading 1:1 nos força a executar dois syscalls para as chamadas mutex, o " "que é muito lento." #. (itstool) path: sect3/para #: article.translate.xml:2024 msgid "" "The solution Linux 2.6 " "implements is called futexes. Futexes implement the check for contention in " "userspace and call kernel primitives only in a case of contention. Thus the " "typical case takes place without any kernel intervention. This yields " "reasonably fast and flexible synchronization primitives implementation." msgstr "" "A solução que o Linux 2.6 " "implementa é chamada de futexes. Futexes implementam a verificação de " "contenção no espaço do usuário e chama primitivas do kernel apenas em um " "caso de contenção. Assim, o caso típico ocorre sem qualquer intervenção do " "kernel. Isso produz uma implementação de primitivas de sincronização " "razoavelmente rápida e flexível." #. (itstool) path: sect3/title #: article.translate.xml:2033 msgid "Futex API" msgstr "API do Futex" #. (itstool) path: sect3/para #: article.translate.xml:2035 msgid "The futex syscall looks like this:" msgstr "A syscall do futex é assim:" #. (itstool) path: sect3/programlisting #: article.translate.xml:2037 #, no-wrap msgid "int futex(void *uaddr, int op, int val, struct timespec *timeout, void *uaddr2, int val3);" msgstr "int futex(void *uaddr, int op, int val, struct timespec *timeout, void *uaddr2, int val3);" #. (itstool) path: sect3/para #: article.translate.xml:2039 msgid "" "In this example uaddr is an address of the mutex in " "userspace, op is an operation we are about to perform and " "the other parameters have per-operation meaning." msgstr "" "Neste exemplo uaddr é um endereço do mutex no espaço do " "usuário, op é uma operação que estamos prestes a executar " "e os outros parâmetros têm significado por operação." #. (itstool) path: sect3/para #: article.translate.xml:2044 msgid "Futexes implement the following operations:" msgstr "Futexes implementam as seguintes operações:" #. (itstool) path: listitem/para #: article.translate.xml:2048 msgid "FUTEX_WAIT" msgstr "FUTEX_WAIT" #. (itstool) path: listitem/para #: article.translate.xml:2051 msgid "FUTEX_WAKE" msgstr "FUTEX_WAKE" #. (itstool) path: listitem/para #: article.translate.xml:2054 msgid "FUTEX_FD" msgstr "FUTEX_FD" #. (itstool) path: listitem/para #: article.translate.xml:2057 msgid "FUTEX_REQUEUE" msgstr "FUTEX_REQUEUE" #. (itstool) path: listitem/para #: article.translate.xml:2060 msgid "FUTEX_CMP_REQUEUE" msgstr "FUTEX_CMP_REQUEUE" #. (itstool) path: listitem/para #: article.translate.xml:2063 msgid "FUTEX_WAKE_OP" msgstr "FUTEX_WAKE_OP" #. (itstool) path: sect4/title #: article.translate.xml:2068 msgid "FUTEX_WAIT" msgstr "FUTEX_WAIT" #. (itstool) path: sect4/para #: article.translate.xml:2070 msgid "" "This operation verifies that on address uaddr the value " "val is written. If not, EWOULDBLOCK is " "returned, otherwise the thread is queued on the futex and gets suspended. If " "the argument timeout is non-zero it specifies the maximum " "time for the sleeping, otherwise the sleeping is infinite." msgstr "" "Esta operação verifica que no endereço uaddr o valor " "val é gravado. Se não, EWOULDBLOCK é " "retornado, caso contrário, a thread é enfileirada no futex e é suspensa. Se " "o argumento timeout for diferente de zero, ele " "especificará o tempo máximo para a suspensão, caso contrário, a suspensão " "será infinita." #. (itstool) path: sect4/title #: article.translate.xml:2081 msgid "FUTEX_WAKE" msgstr "FUTEX_WAKE" #. (itstool) path: sect4/para #: article.translate.xml:2083 msgid "" "This operation takes a futex at uaddr and wakes up " "val first futexes queued on this futex." msgstr "" "Esta operação tem um futex em uaddr e acorda os primeiros " "futexes val enfileirados neste futex. " #. (itstool) path: sect4/title #: article.translate.xml:2090 msgid "FUTEX_FD" msgstr "FUTEX_FD" #. (itstool) path: sect4/para #: article.translate.xml:2092 msgid "This operations associates a file descriptor with a given futex." msgstr "" "Esta operação associa um descritor de arquivo com um determinado futex." #. (itstool) path: sect4/title #: article.translate.xml:2097 msgid "FUTEX_REQUEUE" msgstr "FUTEX_REQUEUE" #. (itstool) path: sect4/para #: article.translate.xml:2099 msgid "" "This operation takes val threads queued on futex at " "uaddr, wakes them up, and takes val2 " "next threads and requeues them on futex at uaddr2." msgstr "" "Esta operação pega threads val enfileirados no futex em " "uaddr, acorda-os e pega as próximas threads " "val2 e enfileira-os no futex em uaddr2." #. (itstool) path: sect4/title #: article.translate.xml:2107 msgid "FUTEX_CMP_REQUEUE" msgstr "FUTEX_CMP_REQUEUE" #. (itstool) path: sect4/para #: article.translate.xml:2109 msgid "" "This operation does the same as FUTEX_REQUEUE but it " "checks that val3 equals to val first." msgstr "" "Essa operação faz o mesmo que FUTEX_REQUEUE, mas verifica " "se val3 é igual a val primeiro." #. (itstool) path: sect4/title #: article.translate.xml:2116 msgid "FUTEX_WAKE_OP" msgstr "FUTEX_WAKE_OP" #. (itstool) path: sect4/para #: article.translate.xml:2118 msgid "" "This operation performs an atomic operation on val3 " "(which contains coded some other value) and uaddr. Then " "it wakes up val threads on futex at uaddr and if the atomic operation returned a positive number it wakes up " "val2 threads on futex at uaddr2." msgstr "" "Esta operação executa uma operação atômica em val3 (que " "contém algum outro valor codificado) e uaddr. Então, ele " "acorda threads val em futex em uaddr e " "se a operação atômica retornar um número positivo, ele ativa os threadings " "val2 em futex em uaddr2." #. (itstool) path: sect4/para #: article.translate.xml:2127 msgid "The operations implemented in FUTEX_WAKE_OP:" msgstr "As operações implementadas em FUTEX_WAKE_OP:" #. (itstool) path: listitem/para #: article.translate.xml:2132 msgid "FUTEX_OP_SET" msgstr "FUTEX_OP_SET" #. (itstool) path: listitem/para #: article.translate.xml:2135 msgid "FUTEX_OP_ADD" msgstr "FUTEX_OP_ADD" #. (itstool) path: listitem/para #: article.translate.xml:2138 msgid "FUTEX_OP_OR" msgstr "FUTEX_OP_OR" #. (itstool) path: listitem/para #: article.translate.xml:2141 msgid "FUTEX_OP_AND" msgstr "FUTEX_OP_AND" #. (itstool) path: listitem/para #: article.translate.xml:2144 msgid "FUTEX_OP_XOR" msgstr "FUTEX_OP_XOR" #. (itstool) path: note/para #: article.translate.xml:2149 msgid "" "There is no val2 parameter in the futex prototype. The " "val2 is taken from the struct timespec *timeout parameter for operations FUTEX_REQUEUE, " "FUTEX_CMP_REQUEUE and FUTEX_WAKE_OP." msgstr "" "Não existe um parâmetro val2 no protótipo do futex. O " "val2 é obtido do parâmetro struct timespec " "*timeout para as operações FUTEX_REQUEUE, " "FUTEX_CMP_REQUEUE e FUTEX_WAKE_OP." #. (itstool) path: sect3/title #: article.translate.xml:2161 msgid "Futex emulation in FreeBSD" msgstr "Emulação de Futex no FreeBSD" #. (itstool) path: sect3/para #: article.translate.xml:2163 msgid "" "The futex emulation in FreeBSD is taken from NetBSD and further extended by " "us. It is placed in linux_futex.c and " "linux_futex.h files. The futex " "structure looks like:" msgstr "" "A emulação de futex no FreeBSD é retirada do NetBSD e posteriormente " "estendida por nós. Ele é colocado nos arquivos linux_futex.c e linux_futex.h. A estrutura futex se parece com:" #. (itstool) path: sect3/programlisting #: article.translate.xml:2169 #, no-wrap msgid "" "struct futex {\n" " void *f_uaddr;\n" " int f_refcount;\n" "\n" " LIST_ENTRY(futex) f_list;\n" "\n" " TAILQ_HEAD(lf_waiting_paroc, waiting_proc) f_waiting_proc;\n" "};" msgstr "" "struct futex {\n" " void *f_uaddr;\n" " int f_refcount;\n" "\n" " LIST_ENTRY(futex) f_list;\n" "\n" " TAILQ_HEAD(lf_waiting_paroc, waiting_proc) f_waiting_proc;\n" "};" #. (itstool) path: sect3/para #: article.translate.xml:2178 msgid "And the structure waiting_proc is:" msgstr "E a estrutura waiting_proc é:" #. (itstool) path: sect3/programlisting #: article.translate.xml:2181 #, no-wrap msgid "" "struct waiting_proc {\n" "\n" " struct thread *wp_t;\n" "\n" " struct futex *wp_new_futex;\n" "\n" " TAILQ_ENTRY(waiting_proc) wp_list;\n" "};" msgstr "" "struct waiting_proc {\n" "\n" " struct thread *wp_t;\n" "\n" " struct futex *wp_new_futex;\n" "\n" " TAILQ_ENTRY(waiting_proc) wp_list;\n" "};" #. (itstool) path: sect4/title #: article.translate.xml:2191 msgid "futex_get / futex_put" msgstr "futex_get / futex_put" #. (itstool) path: sect4/para #: article.translate.xml:2193 msgid "" "A futex is obtained using the futex_get function, which " "searches a linear list of futexes and returns the found one or creates a new " "futex. When releasing a futex from the use we call the futex_put function, which decreases a reference counter of the futex and if " "the refcount reaches zero it is released." msgstr "" "Um futex é obtido usando a função futex_get, que busca " "uma lista linear de futexes e retorna o encontrado ou cria um novo futex. Ao " "liberar um futex do uso, chamamos a função futex_put, " "que diminui um contador de referência do futex e, se o refcount chegar a " "zero, ele é liberado." #. (itstool) path: sect4/title #: article.translate.xml:2203 msgid "futex_sleep" msgstr "futex_sleep" #. (itstool) path: sect4/para #: article.translate.xml:2205 msgid "" "When a futex queues a thread for sleeping it creates a " "working_proc structure and puts this structure to the " "list inside the futex structure then it just performs a " "tsleep9 to suspend the thread. The sleep can be timed out. After " "tsleep9 returns (the thread was woken up or it timed out) the " "working_proc structure is removed from the list and is " "destroyed. All this is done in the futex_sleep " "function. If we got woken up from futex_wake we have " "wp_new_futex set so we sleep on it. This way the actual " "requeueing is done in this function." msgstr "" "Quando um futex enfileira uma thread para dormir, ele cria uma estrutura " "working_proc e coloca essa estrutura na lista dentro da " "estrutura do futex, então apenas executa um " "tsleep9 para suspender a threading. O sleep pode ser expirado. Depois " "de tsleep9 retornar (a thread foi acordada ou expirou) a " "estrutura working_proc é removida da lista e é destruído. " "Tudo isso é feito na função futex_sleep. Se nós formos " "acordados de futex_wake nós temos " "wp_new_futex setado então nós dormimos nele. Desta forma, " "um novo enfileiramento é feito nesta função." #. (itstool) path: sect4/title #: article.translate.xml:2221 msgid "futex_wake" msgstr "futex_wake" #. (itstool) path: sect4/para #: article.translate.xml:2223 msgid "" "Waking up a thread sleeping on a futex is performed in the " "futex_wake function. First in this function we mimic " "the strange Linux behavior, " "where it wakes up N threads for all operations, the only exception is that " "the REQUEUE operations are performed on N+1 threads. But this usually does " "not make any difference as we are waking up all threads. Next in the " "function in the loop we wake up n threads, after this we check if there is a " "new futex for requeueing. If so, we requeue up to n2 threads on the new " "futex. This cooperates with futex_sleep." msgstr "" "Acordar uma thread em sleep em uma futex é performado na função " "futex_wake. Primeiro nesta função nós imitamos o " "comportamento estranho do Linux, " "onde ele acorda N threads para todas as operações, a única exceção é que as " "operações REQUEUE são executadas em threads N+1. Mas isso geralmente não faz " "diferença, pois estamos acordando todos as threads. Em seguida na função no " "loop nós acordamos n threads, depois disso nós checamos se existe um novo " "futex para requeuering. Se assim for, nós enfileiramos novamente até n2 " "threads no novo futex. Isso coopera com o futex_sleep." #. (itstool) path: sect4/title #: article.translate.xml:2237 msgid "futex_wake_op" msgstr "futex_wake_op" #. (itstool) path: sect4/para #: article.translate.xml:2239 msgid "" "The FUTEX_WAKE_OP operation is quite complicated. First " "we obtain two futexes at addresses uaddr and " "uaddr2 then we perform the atomic operation using " "val3 and uaddr2. Then val waiters on the first futex is woken up and if the atomic operation " "condition holds we wake up val2 (i.e. timeout) waiter on the second futex." msgstr "" "A operação FUTEX_WAKE_OP é bastante complicada. Primeiro " "nós obtemos dois futexes nos endereços uaddr e " "uaddr2 e então executamos a operação atômica usando " "val3 e uaddr2. Então os waiters " "val no primeiro futex são acordados e se a condição de " "operação atômica se mantém, nós acordamos o waiter val2 " "(ex timeout) no segundo futex." #. (itstool) path: sect4/title #: article.translate.xml:2252 msgid "futex atomic operation" msgstr "operação atômica futex" #. (itstool) path: sect4/para #: article.translate.xml:2254 msgid "" "The atomic operation takes two parameters encoded_op and " "uaddr. The encoded operation encodes the operation " "itself, comparing value, operation argument, and comparing argument. The " "pseudocode for the operation is like this one:" msgstr "" "A operação atômica usa dois parâmetros encoded_op e " "uaddr. A operação codificada, codifica a operação em si, " "comparando valor, argumento de operação e argumento de comparação. O " "pseudocódigo da operação é como este:" #. (itstool) path: sect4/programlisting #: article.translate.xml:2261 #, no-wrap msgid "" "oldval = *uaddr2\n" "*uaddr2 = oldval OP oparg" msgstr "" "oldval = *uaddr2\n" "*uaddr2 = oldval OP oparg" #. (itstool) path: sect4/para #: article.translate.xml:2264 msgid "" "And this is done atomically. First a copying in of the number at " "uaddr is performed and the operation is done. The code " "handles page faults and if no page fault occurs oldval is " "compared to cmparg argument with cmp comparator." msgstr "" "E isso é feito atomicamente. Primeiro, uma cópia do número em " "uaddr é executada e a operação é concluída. O código " "manipula falhas de página e, se nenhuma falha de página ocorrer, " "oldval é comparado ao argumento cmparg " "com o comparador cmp." #. (itstool) path: sect4/title #: article.translate.xml:2273 msgid "Futex locking" msgstr "Bloqueio Futex" #. (itstool) path: sect4/para #: article.translate.xml:2275 msgid "" "Futex implementation uses two lock lists protecting sx_lock and global locks (either Giant or another sx_lock). Every operation is performed locked from the start to the very " "end." msgstr "" "A implementação do Futex usa duas listas de lock que protegndo " "sx_lock e locks globais (Giant ou outra " "sx_lock). Cada operação é executada bloqueada desde o " "início até o final." #. (itstool) path: sect2/title #: article.translate.xml:2285 msgid "Various syscalls implementation" msgstr "Implementação de várias syscalls" #. (itstool) path: sect2/para #: article.translate.xml:2287 msgid "" "In this section I am going to describe some smaller syscalls that are worth " "mentioning because their implementation is not obvious or those syscalls are " "interesting from other point of view." msgstr "" "Nesta seção, descreverei algumas syscalls menores que merecem destaque, pois " "sua implementação não é óbvia ou as syscalls são interessantes de outro " "ponto de vista." #. (itstool) path: sect3/title #: article.translate.xml:2293 msgid "*at family of syscalls" msgstr "*na família de syscalls" #. (itstool) path: sect3/para #: article.translate.xml:2295 msgid "" "During development of Linux " "2.6.16 kernel, the *at syscalls were added. Those syscalls " "(openat for example) work exactly like their at-less " "counterparts with the slight exception of the dirfd " "parameter. This parameter changes where the given file, on which the syscall " "is to be performed, is. When the filename parameter is " "absolute dirfd is ignored but when the path to the file " "is relative, it comes to the play. The dirfd parameter is " "a directory relative to which the relative pathname is checked. The " "dirfd parameter is a file descriptor of some directory or " "AT_FDCWD. So for example the openat " "syscall can be like this:" msgstr "" "Durante o desenvolvimento do kernel 2.6.16 do Linux, os *at syscalls foram adicionados. Essas syscalls " "(openat, por exemplo) funcionam exatamente como suas " "contrapartes sem-menos, com a pequena exceção do parâmetro dirfd. Este parâmetro muda onde o arquivo dado, no qual a syscall deve " "ser executado, está. Quando o parâmetro filename é " "absoluto dirfd é ignorado, mas quando o caminho para o " "arquivo é relativo, ele é checado. O parâmetro dirfd é um " "diretório relativo ao qual o nome do caminho relativo é verificado. O " "parâmetro dirfd é um file descriptor de algum diretório " "ou AT_FDCWD. Então, por exemplo, a syscall " "openat pode ser assim:" #. (itstool) path: sect3/programlisting #: article.translate.xml:2311 #, no-wrap msgid "" "file descriptor 123 = /tmp/foo/, current working directory = /tmp/\n" "\n" "openat(123, /tmp/bah\\, flags, mode)\t/* opens /tmp/bah */\n" "openat(123, bah\\, flags, mode)\t\t/* opens /tmp/foo/bah */\n" "openat(AT_FDWCWD, bah\\, flags, mode)\t/* opens /tmp/bah */\n" "openat(stdio, bah\\, flags, mode)\t/* returns error because stdio is not a directory */" msgstr "" "file descriptor 123 = /tmp/foo/, current working directory = /tmp/\n" "\n" "openat(123, /tmp/bah\\, flags, mode)\t/* opens /tmp/bah */\n" "openat(123, bah\\, flags, mode)\t\t/* opens /tmp/foo/bah */\n" "openat(AT_FDWCWD, bah\\, flags, mode)\t/* opens /tmp/bah */\n" "openat(stdio, bah\\, flags, mode)\t/* returns error because stdio is not a directory */" #. (itstool) path: sect3/para #: article.translate.xml:2318 msgid "" "This infrastructure is necessary to avoid races when opening files outside " "the working directory. Imagine that a process consists of two threads, " "thread A and thread B. Thread A issues open(./tmp/foo/bah., flags, " "mode) and before returning it gets preempted and thread B runs. " "Thread B does not care about the needs of thread A and renames or removes " "/tmp/foo/. We got a race. To avoid this we can open " "/tmp/foo and use it as dirfd for " "openat syscall. This also enables user to implement per-" "thread working directories." msgstr "" "Esta infra-estrutura é necessária para evitar corridas ao abrir arquivos " "fora do diretório de trabalho. Imagine que um processo consiste em duas " "threads, thread A e thread B. Thread A emite open (./tmp/foo/bah., " "Flags, mode) e antes de retornar ele se antecipa e a thread B é " "executada. A thread B não se preocupa com as necessidades da thread A e " "renomeia ou remove o /tmp/foo/. Nós temos uma corrida. " "Para evitar isso, podemos abrir o /tmp/foo e usá-lo " "como dirfd para a syscall openat. " "Isso também permite que o usuário implemente diretórios de trabalho por " "thread." #. (itstool) path: sect3/para #: article.translate.xml:2332 msgid "" "Linux family of *at syscalls " "contains: linux_openat, linux_mkdirat, linux_mknodat, linux_fchownat, linux_futimesat, linux_fstatat64, linux_unlinkat, linux_renameat, linux_linkat, linux_symlinkat, linux_readlinkat, linux_fchmodat and linux_faccessat. All these are " "implemented using the modified namei9 routine and simple " "wrapping layer." msgstr "" "A família do Linux de *at " "syscalls contém: linux_openat, linux_mkdirat, linux_mknodat, linux_fchownat, linux_futimesat, linux_fstatat64, linux_unlinkat, linux_renameat, linux_linkat , linux_symlinkat, linux_readlinkat, linux_fchmodat e linux_faccessat. Tudo isso é implementado " "usando a rotina modificada namei9 e a simples camada de " "quebra automática." #. (itstool) path: sect4/title #: article.translate.xml:2350 msgid "Implementation" msgstr "Implementação" #. (itstool) path: sect4/para #: article.translate.xml:2352 msgid "" "The implementation is done by altering the " "namei9 routine (described above) to take additional parameter " "dirfd in its nameidata structure, " "which specifies the starting point of the pathname lookup instead of using " "the current working directory every time. The resolution of dirfd from file descriptor number to a vnode is done in native *at " "syscalls. When dirfd is AT_FDCWD the " "dvp entry in nameidata structure is " "NULL but when dirfd is a different " "number we obtain a file for this file descriptor, check whether this file is " "valid and if there is vnode attached to it then we get a vnode. Then we " "check this vnode for being a directory. In the actual " "namei9 routine we simply substitute the dvp vnode " "for dp variable in the " "namei9 function, which determines the starting point. The " "namei9 is not used directly but via a trace of different functions on " "various levels. For example the openat goes like this:" msgstr "" "A implementação é feita alterando a rotina " "namei9 (descrita acima) para obter o parâmetro adicional " "dirfd no sua estrutura nameidata , que " "especifica o ponto inicial da pesquisa do nome do caminho, em vez de usar o " "diretório de trabalho atual todas as vezes. A resolução de dirfd do número do file descriptor para um vnode é feita em *at syscalls " "nativo. Quando dirfd é AT_FDCWD, a " "entrada dvp na estrutura nameidata é " "NULL, mas dirfd é um número diferente, " "obtemos um arquivo para este file descriptor, verificamos se este arquivo é " "válido e se há vnode anexado a ele, então obtemos um vnode. Então nós " "verificamos este vnode por ser um diretório. Na rotina real " "namei9 simplesmente substituímos a variável dvp " "vnode pela variável dp na função " "namei9, que determina o ponto de partida. O " "namei9 não é usado diretamente, mas através de um rastreamento de " "diferentes funções em vários níveis. Por exemplo, o openat é assim:" #. (itstool) path: sect4/programlisting #: article.translate.xml:2376 #, no-wrap msgid "openat() --> kern_openat() --> vn_open() -> namei()" msgstr "openat() --> kern_openat() --> vn_open() -> namei()" #. (itstool) path: sect4/para #: article.translate.xml:2378 msgid "" "For this reason kern_open and vn_open must be altered to incorporate the additional dirfd parameter. No compat layer is created for those because there are " "not many users of this and the users can be easily converted. This general " "implementation enables FreeBSD to implement their own *at syscalls. This is " "being discussed right now." msgstr "" "Por esse motivo, kern_open e vn_open devem ser alterados para incorporar o parâmetro dirfd adicional. Nenhuma camada de compatibilidade é criada para esses, " "porque não há muitos usuários disso e os usuários podem ser facilmente " "convertidos. Esta implementação geral permite ao FreeBSD implementar suas " "próprias *at syscalls. Isso está sendo discutido agora." #. (itstool) path: sect3/title #: article.translate.xml:2390 msgid "Ioctl" msgstr "Ioctl" #. (itstool) path: sect3/para #: article.translate.xml:2392 msgid "" "The ioctl interface is quite fragile due to its generality. We have to bear " "in mind that devices differ between Linux and FreeBSD so some care must be applied to do ioctl emulation " "work right. The ioctl handling is implemented in linux_ioctl.c, where linux_ioctl function is defined. This " "function simply iterates over sets of ioctl handlers to find a handler that " "implements a given command. The ioctl syscall has three parameters, the file " "descriptor, command and an argument. The command is a 16-bit number, which " "in theory is divided into high 8 bits determining class of the ioctl command " "and low 8 bits, which are the actual command within the given set. The " "emulation takes advantage of this division. We implement handlers for each " "set, like sound_handler or disk_handler. Each handler has a maximum command and a minimum command defined, " "which is used for determining what handler is used. There are slight " "problems with this approach because Linux does not use the set division consistently so sometimes ioctls " "for a different set are inside a set they should not belong to (SCSI generic " "ioctls inside cdrom set, etc.). FreeBSD currently does not implement many " "Linux ioctls (compared to " "NetBSD, for example) but the plan is to port those from NetBSD. The trend is " "to use Linux ioctls even in the " "native FreeBSD drivers because of the easy porting of applications." msgstr "" "A interface ioctl é bastante frágil devido à sua generalidade. Nós temos que " "ter em mente que os dispositivos diferem entre Linux e FreeBSD, então alguns cuidados devem ser aplicados " "para fazer o trabalho de emulação de ioctl corretamente. O manuseio ioctl é " "implementado em linux_ioctl.c, onde a função " "linux_ioctl é definida. Esta função simplesmente itera " "sobre conjuntos de manipuladores ioctl para encontrar um manipulador que " "implementa um dado comando. A syscall ioctl tem três parâmetros, o file " "descriptor, comando e um argumento. O comando é um número de 16 bits, que, " "em teoria, é dividido em alta classe determinante de 8 bits do comando ioctl " "e 8 bits baixos, que são o comando real dentro do conjunto dado. A emulação " "aproveita essa divisão. Implementamos manipuladores para cada conjunto, como " "sound_handler ou disk_handler. " "Cada manipulador tem um comando máximo e um comando mínimo definido, que é " "usado para determinar qual manipulador é usado. Existem pequenos problemas " "com esta abordagem porque Linux " "não usa a divisão definida consistentemente, por isso as ioctls para um " "conjunto diferente estão dentro de um conjunto ao qual não devem pertencer " "(ioctls genéricos SCSI dentro do cdrom conjunto, etc.). O FreeBSD atualmente " "não implementa muitos ioctls do Linux (comparado ao NetBSD, por exemplo), mas o plano é portar os do " "NetBSD. A tendência é usar o ioctls Linux mesmo nos drivers nativos do FreeBSD, devido à fácil " "portabilidade dos aplicativos." #. (itstool) path: sect3/title #: article.translate.xml:2422 msgid "Debugging" msgstr "Depuração" #. (itstool) path: sect3/para #: article.translate.xml:2424 msgid "" "Every syscall should be debuggable. For this purpose we introduce a small " "infrastructure. We have the ldebug facility, which tells whether a given " "syscall should be debugged (settable via a sysctl). For printing we have " "LMSG and ARGS macros. Those are used for altering a printable string for " "uniform debugging messages." msgstr "" "Cada syscall deve ser debugável. Para isso, introduzimos uma pequena infra-" "estrutura. Nós temos o recurso ldebug, que informa se uma dada syscall deve " "ser depurada (configurável através de um sysctl). Para impressão, temos as " "macros LMSG e ARGS. Essas são usadas ​​para alterar uma string imprimível para " "mensagens uniformes de depuração." #. (itstool) path: sect1/title #: article.translate.xml:2435 msgid "Conclusion" msgstr "Conclusão" #. (itstool) path: sect2/title #: article.translate.xml:2438 msgid "Results" msgstr "Resultados" #. (itstool) path: sect2/para #: article.translate.xml:2440 msgid "" "As of April 2007 the Linux " "emulation layer is capable of emulating the Linux 2.6.16 kernel quite well. The remaining problems " "concern futexes, unfinished *at family of syscalls, problematic signals " "delivery, missing epoll and inotify and probably some bugs we have not discovered yet. Despite this we " "are capable of running basically all the Linux programs included in FreeBSD Ports Collection with " "Fedora Core 4 at 2.6.16 and there are some rudimentary reports of success " "with Fedora Core 6 at 2.6.16. The Fedora Core 6 linux_base was recently " "committed enabling some further testing of the emulation layer and giving us " "some more hints where we should put our effort in implementing missing stuff." msgstr "" "Em abril de 2007, a camada de emulação do Linux é capaz de emular o kernel Linux 2.6.16 muito bem. Os problemas remanescentes dizem " "respeito a futexes, inacabado na família de syscalls *at, entrega de sinais " "problemáticos, falta de epoll e inotify e provavelmente alguns bugs que ainda não descobrimos. Apesar " "disso, somos capazes de executar basicamente todos os programas Linux incluídos na coleção de ports do " "FreeBSD com o Fedora Core 4 em 2.6.16 e há alguns relatos rudimentares de " "sucesso com o Fedora Core 6 em 2.6.16. O linux_base do Fedora Core 6 foi " "recentemente comprometido permitindo alguns testes adicionais da camada de " "emulação e nos dando mais algumas dicas onde devemos nos esforçar para " "implementar o material que está faltando." #. (itstool) path: sect2/para #: article.translate.xml:2455 msgid "" "We are able to run the most used applications like www/linux-" "firefox, www/linux-opera, net-im/" "skype and some games from the Ports Collection. Some of the " "programs exhibit bad behavior under 2.6 emulation but this is currently " "under investigation and hopefully will be fixed soon. The only big " "application that is known not to work is the Linux Java Development Kit and this is " "because of the requirement of epoll facility which is " "not directly related to the Linux kernel 2.6." msgstr "" "Nós podemos rodar os aplicativos mais usados ​​como o www/linux-" "firefox, www/linux-opera, net-im/" "skype e alguns jogos da coleção dos ports. Alguns dos programas " "exibem mau comportamento na emulação 2.6, mas isso está atualmente sob " "investigação e, espera-se, será corrigido em breve. A única grande aplicação " "que se sabe que não funciona é o Java Development Kit " "do Linux e isto é devido ao " "requisito de epoll habilidade que não está diretamente " "relacionada ao kernel do Linux " "2.6." #. (itstool) path: sect2/para #: article.translate.xml:2467 msgid "" "We hope to enable 2.6.16 emulation by default some time after FreeBSD 7.0 is " "released at least to expose the 2.6 emulation parts for some wider testing. " "Once this is done we can switch to Fedora Core 6 linux_base, which is the " "ultimate plan." msgstr "" "Esperamos habilitar a emulação 2.6.16 por padrão algum tempo depois que o " "FreeBSD 7.0 for lançado pelo menos para expor as partes da emulação 2.6 para " "alguns testes mais amplos. Feito isso, podemos mudar para o Fedora Core 6 " "linux_base, que é o plano final." #. (itstool) path: sect2/title #: article.translate.xml:2475 msgid "Future work" msgstr "Trabalho futuro" #. (itstool) path: sect2/para #: article.translate.xml:2477 msgid "" "Future work should focus on fixing the remaining issues with futexes, " "implement the rest of the *at family of syscalls, fix the signal delivery " "and possibly implement the epoll and inotify facilities." msgstr "" "O trabalho futuro deve focar na correção dos problemas remanescentes com " "futexes, implementar o restante da família de syscalls, corrigir a entrega " "de sinal e possivelmente implementar os recursos de epoll e inotify." #. (itstool) path: sect2/para #: article.translate.xml:2483 msgid "" "We hope to be able to run the most important programs flawlessly soon, so we " "will be able to switch to the 2.6 emulation by default and make the " "Fedora Core 6 the default linux_base because our currently used " "Fedora Core 4 is not supported any more." msgstr "" "Esperamos poder executar os programas mais importantes com perfeição em " "breve, por isso poderemos alternar para a emulação 2.6 por padrão e fazer do " "Fedora Core 6 o linux_base padrão porque o nosso atualmente usado Fedora " "Core 4 não é mais suportado." #. (itstool) path: sect2/para #: article.translate.xml:2489 msgid "" "The other possible goal is to share our code with NetBSD and DragonflyBSD. " "NetBSD has some support for 2.6 emulation but its far from finished and not " "really tested. DragonflyBSD has expressed some interest in porting the 2.6 " "improvements." msgstr "" "O outro objetivo possível é compartilhar nosso código com o NetBSD e o " "DragonflyBSD. O NetBSD tem algum suporte para emulação 2.6, mas está longe " "de ser concluído e não foi realmente testado. O DragonflyBSD manifestou " "algum interesse em portar as melhorias do 2.6." #. (itstool) path: sect2/para #: article.translate.xml:2495 msgid "" "Generally, as Linux develops we " "would like to keep up with their development, implementing newly added " "syscalls. Splice comes to mind first. Some already implemented syscalls are " "also heavily crippled, for example mremap and others. " "Some performance improvements can also be made, finer grained locking and " "others." msgstr "" "Geralmente, como o Linux se " "desenvolve, gostaríamos de acompanhar seu desenvolvimento, implementando a " "syscalls recém-adicionado. Splice vem em mente primeiro. Algumas syscalls já " "implementadas também são altamente danificadas, por exemplo " "mremap e outras. Alguns aprimoramentos de desempenho " "também podem ser feitos, um lock mais refinado e outros." #. (itstool) path: sect2/title #: article.translate.xml:2505 msgid "Team" msgstr "Equipe" #. (itstool) path: sect2/para #: article.translate.xml:2507 msgid "I cooperated on this project with (in alphabetical order):" msgstr "Eu colaborei neste projeto com (em ordem alfabética):" #. (itstool) path: listitem/para #: article.translate.xml:2512 msgid "John Baldwin jhb@FreeBSD.org" msgstr "John Baldwin jhb@FreeBSD.org" #. (itstool) path: listitem/para #: article.translate.xml:2515 msgid "Konstantin Belousov kib@FreeBSD.org" msgstr "Konstantin Belousov kib@FreeBSD.org" #. (itstool) path: listitem/para #: article.translate.xml:2518 msgid "Emmanuel Dreyfus" msgstr "Emmanuel Dreyfus" #. (itstool) path: listitem/para #: article.translate.xml:2521 msgid "Scot Hetzel" msgstr "Scot Hetzel" #. (itstool) path: listitem/para #: article.translate.xml:2524 msgid "Jung-uk Kim jkim@FreeBSD.org" msgstr "Jung-uk Kim jkim@FreeBSD.org" #. (itstool) path: listitem/para #: article.translate.xml:2527 msgid "Alexander Leidinger netchild@FreeBSD.org" msgstr "Alexander Leidinger netchild@FreeBSD.org" #. (itstool) path: listitem/para #: article.translate.xml:2530 msgid "Suleiman Souhlal ssouhlal@FreeBSD.org" msgstr "Suleiman Souhlal ssouhlal@FreeBSD.org" #. (itstool) path: listitem/para #: article.translate.xml:2533 msgid "Li Xiao" msgstr "Li Xiao" #. (itstool) path: listitem/para #: article.translate.xml:2536 msgid "David Xu davidxu@FreeBSD.org" msgstr "David Xu davidxu@FreeBSD.org" #. (itstool) path: sect2/para #: article.translate.xml:2540 msgid "" "I would like to thank all those people for their advice, code reviews and " "general support." msgstr "" "Gostaria de agradecer a todas as pessoas por seus conselhos, revisões de " "código e apoio geral." #. (itstool) path: sect1/title #: article.translate.xml:2546 msgid "Literatures" msgstr "Literaturas" #. (itstool) path: listitem/para #: article.translate.xml:2550 msgid "" "Marshall Kirk McKusick - George V. Nevile-Neil. Design and Implementation of " "the FreeBSD operating system. Addison-Wesley, 2005." msgstr "" "Marshall Kirk McKusick - George V. Nevile-Neil. Design and Implementation of " "the FreeBSD operating system. Addison-Wesley, 2005." #. (itstool) path: listitem/para #: article.translate.xml:2555 msgid "https://tldp.org" msgstr "https://tldp.org" #. (itstool) path: listitem/para #: article.translate.xml:2558 msgid "https://www.kernel.org" msgstr "" "https://www.kernel.org"