# SOME DESCRIPTIVE TITLE # Copyright (C) YEAR The FreeBSD Project # This file is distributed under the same license as the FreeBSD Documentation package. # Fernando Apesteguía , 2021. msgid "" msgstr "" "Project-Id-Version: FreeBSD Documentation VERSION\n" "POT-Creation-Date: 2021-06-03 17:02-0300\n" "PO-Revision-Date: 2021-09-03 18:10+0000\n" "Last-Translator: Fernando Apesteguía \n" "Language-Team: Spanish \n" "Language: es\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=n != 1;\n" "X-Generator: Weblate 4.8\n" #. type: YAML Front Matter: description #: documentation/content/en/articles/vm-design/_index.adoc:1 #, no-wrap msgid "An easy to follow description of the design of the FreeBSD virtual memory system" msgstr "" "Una descripción fácil de seguir del diseño del sistema de memoria virtual de " "FreeBSD" #. type: Title = #: documentation/content/en/articles/vm-design/_index.adoc:1 #: documentation/content/en/articles/vm-design/_index.adoc:11 #, no-wrap msgid "Design elements of the FreeBSD VM system" msgstr "Elementos de diseño del sistema de Memoria Virtual de FreeBSD" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:35 msgid "Abstract" msgstr "Resumen" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:42 msgid "" "The title is really just a fancy way of saying that I am going to attempt to " "describe the whole VM enchilada, hopefully in a way that everyone can " "follow. For the last year I have concentrated on a number of major kernel " "subsystems within FreeBSD, with the VM and Swap subsystems being the most " "interesting and NFS being \"a necessary chore\". I rewrote only small " "portions of the code. In the VM arena the only major rewrite I have done is " "to the swap subsystem. Most of my work was cleanup and maintenance, with " "only moderate code rewriting and no major algorithmic adjustments within the " "VM subsystem. The bulk of the VM subsystem's theoretical base remains " "unchanged and a lot of the credit for the modernization effort in the last " "few years belongs to John Dyson and David Greenman. Not being a historian " "like Kirk I will not attempt to tag all the various features with peoples " "names, since I will invariably get it wrong." msgstr "" "El título es sólo una forma elegante de decir que voy a intentar describir " "la enchilada de la Memoria Virtual, espero que de un modo que todo el mundo " "pueda seguir. Durante el último año me he concentrado en un número de " "subsistemas principales del kernel de FreeBSD, con los subsistemas de " "Memoria Virtual e Intercambio siendo los más interesantes y NFS siendo \"una " "tarea necesaria\". Reescribí sólo pequeñas porciones del código. En el área " "de Memoria Virtual la única reescritura importante que he hecho es el " "subsistema de intercambio. La mayor parte de mi trabajo fue de limpieza y " "mantenimiento, con tan sólo reescrituras moderadas de código y sin ajustes " "algorítmicos importantes en el subsistema de Memoria Virtual. El grueso de " "la base teórica del subsistema de Memoria Virtual permanece sin cambios y " "mucho del crédito del esfuerzo de modernización en los últimos años es para " "John Dyson y David Greenman. Como no soy un historiador como Kirk no " "intentaré etiquetar todas las características con nombres de personas, ya " "que me equivocaría irremediablemente." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:44 msgid "'''" msgstr "'''" #. type: Title == #: documentation/content/en/articles/vm-design/_index.adoc:48 #, no-wrap msgid "Introduction" msgstr "Introducción" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:64 msgid "" "Before moving along to the actual design let's spend a little time on the " "necessity of maintaining and modernizing any long-living codebase. In the " "programming world, algorithms tend to be more important than code and it is " "precisely due to BSD's academic roots that a great deal of attention was " "paid to algorithm design from the beginning. More attention paid to the " "design generally leads to a clean and flexible codebase that can be fairly " "easily modified, extended, or replaced over time. While BSD is considered " "an \"old\" operating system by some people, those of us who work on it tend " "to view it more as a \"mature\" codebase which has various components " "modified, extended, or replaced with modern code. It has evolved, and " "FreeBSD is at the bleeding edge no matter how old some of the code might " "be. This is an important distinction to make and one that is unfortunately " "lost to many people. The biggest error a programmer can make is to not " "learn from history, and this is precisely the error that many other modern " "operating systems have made. Windows NT(R) is the best example of this, and " "the consequences have been dire. Linux also makes this mistake to some " "degree-enough that we BSD folk can make small jokes about it every once in a " "while, anyway. Linux's problem is simply one of a lack of experience and " "history to compare ideas against, a problem that is easily and rapidly being " "addressed by the Linux community in the same way it has been addressed in " "the BSD community-by continuous code development. The Windows NT(R) folk, " "on the other hand, repeatedly make the same mistakes solved by UNIX(R) " "decades ago and then spend years fixing them. Over and over again. They " "have a severe case of \"not designed here\" and \"we are always right " "because our marketing department says so\". I have little tolerance for " "anyone who cannot learn from history." msgstr "" "Antes de avanzar con el diseño real dediquemos un poco de tiempo a la " "necesidad de mantener y modernizar cualquier base de código de larga " "duración. En el mundo de la programación, los algoritmos tienen a se más " "importantes que el código y es precisamente debido a las raíces académicas " "de BSD que una gran parte de la atención se puso desde el comienzo en el " "diseño algorítmico. Prestar más atención al diseño generalmente lleva a una " "base de código limpio y flexible que puede ser modificado fácilmente, " "extendido o reemplazado a lo largo del tiempo. Aunque BSD es considerado por " "alguna gente como un sistema operativo\"viejo\", aquellos de nosotros que " "trabajamos en él solemos verlo más como una base de código\"madura\" la cual " "tiene varios componentes modificados, extendidos, o reemplazados con código " "moderno. Ha evolucionado, y FreeBSD está a la vanguardia independientemente " "de cómo de viejo sea parte del código. Es importante hacer esta distinción y " "que mucha gente pasa por alto. El mayor error que puede cometer un " "programador es no aprender de la historia, y es precisamente este error el " "que han cometido muchos otros sistemas operativos modernos. Windows NT(R) es " "el mejor ejemplo, y las consecuencias han sido nefastas. Linux también " "comete este error hasta cierto punto—lo suficiente para que nosotros la " "gente de BSD hagamos pequeñas bromas de vez en cuando, por lo menos. El " "problema de Linux es simplemente la falta de experiencia y de una historia " "contra la que comparar ideas, un problema que está siendo tratado " "rápidamente por la comunidad Linux de la misma forma que ha sido tratado en " "la comunidad BSD—mediante el desarrollo continuo de código. La gente de " "Windows NT(R), por otro lado, repiten los mismos errores solucionados por " "UNIX(R) hace décadas y pasan años arreglándolos. Una y otra vez. Sufren un " "caso severo de \"no diseñado aquí\" y \"siempre tenemos la razón porque " "nuestro departamento de marketing así lo dice\". Tengo poca tolerancia hacia " "cualquiera que no puede aprender de la historia." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:69 msgid "" "Much of the apparent complexity of the FreeBSD design, especially in the VM/" "Swap subsystem, is a direct result of having to solve serious performance " "issues that occur under various conditions. These issues are not due to bad " "algorithmic design but instead rise from environmental factors. In any " "direct comparison between platforms, these issues become most apparent when " "system resources begin to get stressed. As I describe FreeBSD's VM/Swap " "subsystem the reader should always keep two points in mind:" msgstr "" "Mucha de la aparente complejidad del diseño de FreeBSD, especialmente en el " "subsistema de Memoria Virtual/Intercambio, es un resultado directo de tener " "que resolver serios problemas de rendimiento que ocurren bajo condiciones " "variadas. Estos problemas no se deben aun mal diseño algorítmico sino que " "surgen de factores ambientales. En cualquier comparación directa entre " "plataformas, estos problemas se hacen más evidentes cuando los recursos del " "sistema empiezan a sufrir estrés. Como describo en el subsistema de Memoria " "Virtual/Intercambio de FreeBSD el lector siempre debería tener en mente dos " "puntos:" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:71 msgid "" "The most important aspect of performance design is what is known as " "\"Optimizing the Critical Path\". It is often the case that performance " "optimizations add a little bloat to the code in order to make the critical " "path perform better." msgstr "" "El aspecto más importante del diseño de rendimiento es lo que se conoce como " "\"Optimización del Camino Crítico\". Es común que las optimizaciones de " "rendimiento inflen algo el código con el fin de mejorar el rendimiento del " "camino crítico." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:72 msgid "" "A solid, generalized design outperforms a heavily-optimized design over the " "long run. While a generalized design may end up being slower than an heavily-" "optimized design when they are first implemented, the generalized design " "tends to be easier to adapt to changing conditions and the heavily-optimized " "design winds up having to be thrown away." msgstr "" "Un diseño sólido, generalizado tiene mejor rendimiento a largo plazo que un " "diseño altamente optimizado. Mientras que un diseño generalizado puede " "terminar siendo más lento que un diseño altamente optimizado cuando se " "implementan inicialmente, el diseño generalizado tiende a ser más fácil de " "adaptar a condiciones cambiantes y el diseño altamente optimizado termina " "siendo desechado." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:76 msgid "" "Any codebase that will survive and be maintainable for years must therefore " "be designed properly from the beginning even if it costs some performance. " "Twenty years ago people were still arguing that programming in assembly was " "better than programming in a high-level language because it produced code " "that was ten times as fast. Today, the fallibility of that argument is " "obvious - as are the parallels to algorithmic design and code generalization." msgstr "" "Cualquier base de código que sobrevivirá y será mantenible durante años debe " "por lo tanto ser diseñada adecuadamente desde el comienzo incluso si tiene " "algo de coste en rendimiento. Hace veinte años la gente todavía discutía si " "la programación en ensamblador era mejor que programar en un lenguaje de " "alto nivel porque producía código que era diez veces más rápido. Hoy, la " "falibilidad de ese argumento es obvio — de modo paralelo al diseño " "algorítmico y la generalización de código." #. type: Title == #: documentation/content/en/articles/vm-design/_index.adoc:78 #, no-wrap msgid "VM Objects" msgstr "Objetos de Memoria Virtual" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:88 msgid "" "The best way to begin describing the FreeBSD VM system is to look at it from " "the perspective of a user-level process. Each user process sees a single, " "private, contiguous VM address space containing several types of memory " "objects. These objects have various characteristics. Program code and " "program data are effectively a single memory-mapped file (the binary file " "being run), but program code is read-only while program data is copy-on-" "write. Program BSS is just memory allocated and filled with zeros on " "demand, called demand zero page fill. Arbitrary files can be memory-mapped " "into the address space as well, which is how the shared library mechanism " "works. Such mappings can require modifications to remain private to the " "process making them. The fork system call adds an entirely new dimension to " "the VM management problem on top of the complexity already given." msgstr "" "La mejor manera de empezar describiendo el sistema de Memoria Virtual de " "FreeBSD is mirarlo desde la perspectiva de un proceso de usuario. Cada " "proceso de usuario ve una espacio de direcciones de Memoria Virtual único, " "privado y contiguo que contiene diversos tipos de objetos de memoria. Estos " "objetos tienen diversas características. Código de programa y datos de " "programa son de forma efectiva un solo fichero mapeado en memoria (el " "fichero binario que se está ejecutando), pero el código del programa es de " "solo lectura mientras que los datos de programa son copy-on-write. El BSS " "del programa es sólo memoria asignada y rellenada con ceros bajo demanda, " "llamada rellenado de página cero bajo demanda. Ficheros arbitrarios pueden " "ser mapeados en memoria en el espacio de direcciones también, que es como " "funciona el mecanismo de librerías compartidas. Dichos mapeos pueden " "requerir modificaciones para permanecer privados al proceso que los realiza. " "La llamada al sistema fork añade una nueva dimensión a al problema de la " "gestión de la Memoria Virtual a añadir a la complejidad ya existente." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:94 msgid "" "A program binary data page (which is a basic copy-on-write page) illustrates " "the complexity. A program binary contains a preinitialized data section " "which is initially mapped directly from the program file. When a program is " "loaded into a process's VM space, this area is initially memory-mapped and " "backed by the program binary itself, allowing the VM system to free/reuse " "the page and later load it back in from the binary. The moment a process " "modifies this data, however, the VM system must make a private copy of the " "page for that process. Since the private copy has been modified, the VM " "system may no longer free it, because there is no longer any way to restore " "it later on." msgstr "" "Una página de datos binarios de un programa (que es una página copy-on-write " "básica) ilustra esta complejidad. Un programa binario contiene una sección " "de datos preinicializados que es inicialmente mapeado directamente por el " "fichero del programa. Cuando un programa se carga en el espacio de " "direcciones de Memoria Virtual del proceso, este área es inicialmente " "mapeado en memoria y respaldado por el programa binario mismo, permitiendo " "al sistema de Memoria Virtual liberar/reutilizar la página y después " "cargarla de nuevo desde el binario. Sin embargo, en el momento en que un " "proceso modifica estos datos, el sistema de Memoria Virtual debe hacer una " "copia privada para ese proceso. Puesto que la copia privada ha sido " "modificada, el sistema de Memoria Virtual podría no ser capaz de liberarla, " "porque no hay forma de restaurarla posteriormente." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:101 msgid "" "You will notice immediately that what was originally a simple file mapping " "has become much more complex. Data may be modified on a page-by-page basis " "whereas the file mapping encompasses many pages at once. The complexity " "further increases when a process forks. When a process forks, the result is " "two processes-each with their own private address spaces, including any " "modifications made by the original process prior to the call to `fork()`. " "It would be silly for the VM system to make a complete copy of the data at " "the time of the `fork()` because it is quite possible that at least one of " "the two processes will only need to read from that page from then on, " "allowing the original page to continue to be used. What was a private page " "is made copy-on-write again, since each process (parent and child) expects " "their own personal post-fork modifications to remain private to themselves " "and not effect the other." msgstr "" "Notarás inmediatamente que lo que originalmente era un simple mapeo de un " "fichero se ha convertido en algo más complejo. Los datos pueden ser " "modificados página a página mientras que el mapeo de ficheros engloba varias " "páginas a la vez. La complejidad aumenta más cuando un proceso se bifurca. " "Cuando un proceso se bifurca, el resultado son dos procesos—cada uno con su " "propio espacio de direcciones privado que incluye cualquier modificación " "hecha por el proceso original antes de la llamada a `fork()`. Sería tonto " "para el sistema de Memoria Virtual hacer una copia completa de los datos en " "el momento de llamar a `fork()` porque es bastante posible que al menos uno " "de los dos procesos solamente necesite leer de esa página a partir de este " "momento, permitiendo así que se use la página original. Lo que era una " "página privada se ha convertido en una página copy-on-write de nuevo, puesto " "que cada proceso (padre y hijo) espera que sus propias modificaciones " "personales después del fork permanezcan privadas para ellos y que afecten al " "otro." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:110 msgid "" "FreeBSD manages all of this with a layered VM Object model. The original " "binary program file winds up being the lowest VM Object layer. A copy-on-" "write layer is pushed on top of that to hold those pages which had to be " "copied from the original file. If the program modifies a data page " "belonging to the original file the VM system takes a fault and makes a copy " "of the page in the higher layer. When a process forks, additional VM Object " "layers are pushed on. This might make a little more sense with a fairly " "basic example. A `fork()` is a common operation for any *BSD system, so " "this example will consider a program that starts up, and forks. When the " "process starts, the VM system creates an object layer, let's call this A:" msgstr "" "FreeBSD gestiona todo esto con un modelo de Objetos de Memoria Virtual en " "capas. El fichero del programa binario original termina siendo la capa de " "Objetos de Memoria Virtual más baja. Una capa copy-on-write se sitúa encima " "de ella para mantener aquellas páginas que han sido copiadas del fichero " "original. Si el programa modifica una página de datos que pertenece al " "fichero original el sistema de Memoria Virtual recibe un fallo de página y " "hace una copia de la página en la capa superior. Cuando un proceso bifurca, " "se empujan nuevas capas de Objetos de Memoria Virtual. Esto puede cobrar más " "sentido con un ejemplo bastante básico. Un `fork()` es una operación común " "para cualquier sistema *BSD, así que este ejemplo considerará un programa " "que arranca, y bifurca. Cuando el proceso arranca, el sistema de Memoria " "Virtual crea una capa de objetos, llamémosla A:" #. type: Positional ($1) AttributeList argument for macro 'image' #: documentation/content/en/articles/vm-design/_index.adoc:111 #, no-wrap msgid "A picture" msgstr "Una imagen" #. type: Target for macro image #: documentation/content/en/articles/vm-design/_index.adoc:111 #, no-wrap msgid "fig1.png" msgstr "fig1.png" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:116 msgid "" "A represents the file-pages may be paged in and out of the file's physical " "media as necessary. Paging in from the disk is reasonable for a program, " "but we really do not want to page back out and overwrite the executable. " "The VM system therefore creates a second layer, B, that will be physically " "backed by swap space:" msgstr "" "A representa el fichero—las páginas pueden ser paginadas hacia o desde el " "medio físico del fichero según sea necesario. Paginar desde el disco es " "razonable para un programa, pero en realidad no queremos paginar de vuelta y " "sobrescribir el ejecutable. Por tanto, el sistema de Memoria Virtual crea " "una segunda capa, B, que estará respaldada físicamente por espacio de " "intercambio:" #. type: Target for macro image #: documentation/content/en/articles/vm-design/_index.adoc:117 #, no-wrap msgid "fig2.png" msgstr "fig2.png" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:122 msgid "" "On the first write to a page after this, a new page is created in B, and its " "contents are initialized from A. All pages in B can be paged in or out to a " "swap device. When the program forks, the VM system creates two new object " "layers-C1 for the parent, and C2 for the child-that rest on top of B:" msgstr "" "En la primera escritura a una página después de esto, se crea una nueva " "página en B, y su contenido es inicializado desde A. Todas las páginas en B " "pueden ser paginadas a o desde el dispositivo de intercambio. Cuando el " "programa bifurca, el sistema de Memoria Virtual crea dos capas de objetos " "nuevas—C1 para el padre, y C2 para el hijo—que descansan sobre B:" #. type: Target for macro image #: documentation/content/en/articles/vm-design/_index.adoc:123 #, no-wrap msgid "fig3.png" msgstr "fig3.png" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:134 msgid "" "In this case, let's say a page in B is modified by the original parent " "process. The process will take a copy-on-write fault and duplicate the page " "in C1, leaving the original page in B untouched. Now, let's say the same " "page in B is modified by the child process. The process will take a copy-on-" "write fault and duplicate the page in C2. The original page in B is now " "completely hidden since both C1 and C2 have a copy and B could theoretically " "be destroyed if it does not represent a \"real\" file; however, this sort of " "optimization is not trivial to make because it is so fine-grained. FreeBSD " "does not make this optimization. Now, suppose (as is often the case) that " "the child process does an `exec()`. Its current address space is usually " "replaced by a new address space representing a new file. In this case, the " "C2 layer is destroyed:" msgstr "" "En este caso, digamos que una página en B es modificada por el proceso padre " "original. El proceso recibirá un fallo de copy-on-write y duplicará la " "página en C1, dejando la página original en B sin tocar. Ahora, digamos que " "la misma página en B es modificada por el proceso hijo. El proceso recibirá " "un fallo de copy-on-write y duplicará la página en C2. La página original en " "B está ahora completamente oculta ya que tanto C1 como C2 tienen una copia y " "B podría teóricamente ser destruida si no representa un fichero \"real\"; " "sin embargo, este tipo de optimización no es trivial de hacer porque es muy " "fina. FreeBSD no hace esta optimización. Ahora, supón (como suele ser el " "caso) que el proceso hijo hace un `exec()`. Su espacio de direcciones actual " "es habitualmente remplazado por un nuevo espacio de direcciones que " "representa un nuevo fichero. En este caso, la capa C2 es destruida:" #. type: Target for macro image #: documentation/content/en/articles/vm-design/_index.adoc:135 #, no-wrap msgid "fig4.png" msgstr "fig4.png" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:141 msgid "" "In this case, the number of children of B drops to one, and all accesses to " "B now go through C1. This means that B and C1 can be collapsed together. " "Any pages in B that also exist in C1 are deleted from B during the " "collapse. Thus, even though the optimization in the previous step could not " "be made, we can recover the dead pages when either of the processes exit or " "`exec()`." msgstr "" "En este caso, el número de hijos de B ha bajado a uno, y todos los accesos a " "B van ahora a través de C1. Esto significa que B y C1 pueden colapsarse " "juntas. Cualquier página en B que también existe en C1 se borran de B " "durante el colapso. Por lo tanto, incluso aunque la optimización en el paso " "anterior no se pudo hacer, podemos recuperar las páginas muertas bien cuando " "el proceso sale o cuando llama a `exec()`." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:148 msgid "" "This model creates a number of potential problems. The first is that you " "can wind up with a relatively deep stack of layered VM Objects which can " "cost scanning time and memory when you take a fault. Deep layering can " "occur when processes fork and then fork again (either parent or child). The " "second problem is that you can wind up with dead, inaccessible pages deep in " "the stack of VM Objects. In our last example if both the parent and child " "processes modify the same page, they both get their own private copies of " "the page and the original page in B is no longer accessible by anyone. That " "page in B can be freed." msgstr "" "Este modelo crea un número de problemas potenciales. El primero es que " "puedes terminar con una pila de Objetos de Memoria Virtual relativamente " "profunda que puede tener un coste de tiempo de escaneo y de memoria cuando " "recibes un fallo. Capas muy profundas pueden ocurrir cuando los procesos se " "bifurcan y se bifurcan de nuevo (en el padre o en el hijo). El segundo " "problema es que puedes terminar con páginas muertas, inaccesibles en lo " "profundo de la pila de Objetos de Memoria Virtual. En nuestro último ejemplo " "si tanto los el proceso padre como el hijo modifican la misma página, ambos " "obtienen su propia copia privada de la página y la página original en B ya " "no es accesible por nadie. Esa página en B puede ser liberada." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:159 msgid "" "FreeBSD solves the deep layering problem with a special optimization called " "the \"All Shadowed Case\". This case occurs if either C1 or C2 take " "sufficient COW faults to completely shadow all pages in B. Lets say that C1 " "achieves this. C1 can now bypass B entirely, so rather then have C1->B->A " "and C2->B->A we now have C1->A and C2->B->A. But look what also happened-" "now B has only one reference (C2), so we can collapse B and C2 together. " "The end result is that B is deleted entirely and we have C1->A and C2->A. " "It is often the case that B will contain a large number of pages and neither " "C1 nor C2 will be able to completely overshadow it. If we fork again and " "create a set of D layers, however, it is much more likely that one of the D " "layers will eventually be able to completely overshadow the much smaller " "dataset represented by C1 or C2. The same optimization will work at any " "point in the graph and the grand result of this is that even on a heavily " "forked machine VM Object stacks tend to not get much deeper then 4. This is " "true of both the parent and the children and true whether the parent is " "doing the forking or whether the children cascade forks." msgstr "" "FreeBSD soluciona el problema de capas profundas con una optimización " "especial llamada \"Caso de Todo Sombreado\". Este caso ocurre si C1 o C2 " "generan suficientes fallos COW como para sombrear (ocultar) todas las " "páginas en B. Digamos que C1 lo consigue. C1 puede ahora puentear B " "completamente, así que en lugar de tener C1->B->A y C2->B->A ahora tenemos " "C1->A y C2->B->A. Pero mira lo que ha pasado también—ahora B tiene sólo una " "referencia (C1), así que podemos colapsar B y C2 juntas. El resultado final " "es que B se borra completamente y tenemos C1->A y C2->A. Habitualmente el " "caso es que B contendrá un gran número de páginas y ni C1 ni C2 serán " "capaces de ocultarla completamente. Si bifurcamos de nuevo y creamos un " "conjunto de capas D, sin embargo, es mucho más probable que una de las capas " "de D eventualmente sea capaz de ocultar el conjunto mucho menor representado " "por C1 o C2. La misma optimización funcionará en cualquier punto del grafo y " "el resultado total de esto es que incluso en una máquina con muchas " "bifurcaciones las pilas de Objetos de Memoria Virtual tienen a no ser mucho " "más profundas de 4. Esto es verdad tanto para el padre como para los hijos y " "es así tanto si el padre hace la bifurcación como si los hijos bifurcan en " "cascada." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:163 msgid "" "The dead page problem still exists in the case where C1 or C2 do not " "completely overshadow B. Due to our other optimizations this case does not " "represent much of a problem and we simply allow the pages to be dead. If " "the system runs low on memory it will swap them out, eating a little swap, " "but that is it." msgstr "" "El problema de la página muerta todavía existe en el caso en el que C1 o C2 " "no ocultan completamente B. Debido a otras optimizaciones este caso no es " "demasiado problema y simplemente permitimos que haya páginas muertas. Si el " "sistema se queda sin memoria las intercambiará a disco, utilizando un poco " "de espacio de intercambio, pero eso es todo." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:167 msgid "" "The advantage to the VM Object model is that `fork()` is extremely fast, " "since no real data copying need take place. The disadvantage is that you " "can build a relatively complex VM Object layering that slows page fault " "handling down a little, and you spend memory managing the VM Object " "structures. The optimizations FreeBSD makes proves to reduce the problems " "enough that they can be ignored, leaving no real disadvantage." msgstr "" "La ventaja del modelo de Objetos de Memoria Virtual es que `fork()` es " "extremadamente rápido, ya que no se necesita realizar una copia real de " "datos. La desventaja es que puedes construir un conjunto de capas de Objetos " "de Memoria Virtual relativamente complejo que haga un poco más lento el " "manejo de fallos de página, y que tienes que gastar memoria en la gestión de " "las estructuras de los Objetos de Memoria Virtual. Las optimizaciones que " "hace FreeBSD demuestran que reducen los problemas lo suficiente de forma que " "pueden ser ignorados, eliminando prácticamente la desventaja." #. type: Title == #: documentation/content/en/articles/vm-design/_index.adoc:169 #, no-wrap msgid "SWAP Layers" msgstr "Capas de Intercambio" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:177 msgid "" "Private data pages are initially either copy-on-write or zero-fill pages. " "When a change, and therefore a copy, is made, the original backing object " "(usually a file) can no longer be used to save a copy of the page when the " "VM system needs to reuse it for other purposes. This is where SWAP comes " "in. SWAP is allocated to create backing store for memory that does not " "otherwise have it. FreeBSD allocates the swap management structure for a VM " "Object only when it is actually needed. However, the swap management " "structure has had problems historically:" msgstr "" "Las páginas de datos privadas se crean como páginas copy-on-write o rellenas " "con ceros. Cuando se hace un cambio, y por lo tanto una copia, el objeto de " "respaldo original (normalmente un fichero) ya no puede ser utilizado para " "guardar una copia de la página cuando el sistema de Memoria Virtual necesita " "reutilizarla para otros fines. Aquí es donde aparece el Intercambio. El " "Intercambio se asigna para crear almacenamiento de respaldo para memoria que " "de otra forma no la tendría. FreeBSD asigna la estructura de gestión del " "intercambio para un Objeto de Memoria Virtual solo cuando se necesita " "realmente. Sin embargo históricamente, la estructura de gestión del " "intercambio ha tenido problemas:" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:179 msgid "" "Under FreeBSD 3.X the swap management structure preallocates an array that " "encompasses the entire object requiring swap backing store-even if only a " "few pages of that object are swap-backed. This creates a kernel memory " "fragmentation problem when large objects are mapped, or processes with large " "runsizes (RSS) fork." msgstr "" "En FreeBSD 3.X la estructura de gestión de intercambio preasigna un array " "que engloba todo el objeto que requiere almacenamiento de respaldo de " "intercambio—incluso si solo unas pocas páginas de ese objeto están " "respaldadas en el área de intercambio. Esto crea un problema de " "fragmentación de la memoria del núcleo cuando se mapean objetos grandes, o " "cuando procesos con tamaños de ejecución grandes (RSS) bifurcan." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:180 msgid "" "Also, in order to keep track of swap space, a \"list of holes\" is kept in " "kernel memory, and this tends to get severely fragmented as well. Since the " "\"list of holes\" is a linear list, the swap allocation and freeing " "performance is a non-optimal O(n)-per-page." msgstr "" "Además, para llevar la cuenta del espacio de intercambio, una \"lista de " "huecos\" es mantenida en la memoria del núcleo, y esta tiende a fragmentarse " "de forma severa también. Puesto que la \"lista de huecos\" es una lista " "lineal, el rendimiento de asignación y liberación de intercambio es de un " "orden subóptimo de O(n) por página." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:181 msgid "" "It requires kernel memory allocations to take place during the swap freeing " "process, and that creates low memory deadlock problems." msgstr "" "Requiere que se lleven a cabo asignaciones de memoria del núcleo durante el " "proceso de liberación de espacio de intercambio, y eso crea problemas de " "bloqueo por baja memoria." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:182 msgid "" "The problem is further exacerbated by holes created due to the interleaving " "algorithm." msgstr "" "El problema se exacerba debido a los huecos creados por el algoritmo de " "entrelazado." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:183 msgid "" "Also, the swap block map can become fragmented fairly easily resulting in " "non-contiguous allocations." msgstr "" "Además, el mapa de bloques de intercambio se puede fragmentar fácilmente " "dando como resultado asignaciones no contiguas." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:184 msgid "" "Kernel memory must also be allocated on the fly for additional swap " "management structures when a swapout occurs." msgstr "" "La memoria del núcleo se debe asignar al vuelo para las estructuras " "adicionales de gestión de intercambio cuando se escribe en el área de " "intercambio." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:187 msgid "" "It is evident from that list that there was plenty of room for improvement. " "For FreeBSD 4.X, I completely rewrote the swap subsystem:" msgstr "" "De esa lista se hace evidente que había mucho margen de mejora. Para FreeBSD " "4.X, reescribí completamente el subsistema de intercambio:" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:189 msgid "" "Swap management structures are allocated through a hash table rather than a " "linear array giving them a fixed allocation size and much finer granularity." msgstr "" "Las estructuras de gestión de intercambio se asignan mediante una tabla has " "en lugar de un array lineal dándoles un tamaño de asignación fijo y mucha " "mayor granularidad." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:190 msgid "" "Rather then using a linearly linked list to keep track of swap space " "reservations, it now uses a bitmap of swap blocks arranged in a radix tree " "structure with free-space hinting in the radix node structures. This " "effectively makes swap allocation and freeing an O(1) operation." msgstr "" "En lugar de utilizar una lista enlazada linear para llevar la cuenta de las " "reservas de espacio de intercambio, ahora usa un mapa de bits de bloques de " "intercambio dispuestos en una estructura tipo árbol radix con anotaciones " "sobre el espacio libre en las estructuras de nodos del radix." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:191 msgid "" "The entire radix tree bitmap is also preallocated in order to avoid having " "to allocate kernel memory during critical low memory swapping operations. " "After all, the system tends to swap when it is low on memory so we should " "avoid allocating kernel memory at such times in order to avoid potential " "deadlocks." msgstr "" "El mapa de bits entero para el árbol radix también se preasigna para evitar " "tener que asignar memoria del núcleo durante operaciones de intercambio con " "un nivel crítico de memoria baja. Después de todo, el sistema tiende a " "utilizar intercambio cuando está bajo en memoria de forma que deberíamos " "evitar asignar memoria del núcleo en esas situaciones para evitar " "potenciales bloqueos." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:192 msgid "" "To reduce fragmentation the radix tree is capable of allocating large " "contiguous chunks at once, skipping over smaller fragmented chunks." msgstr "" "Para reducir la fragmentación el árbol radix es capaz de asignar de una sola " "vez grandes trozos contiguos, saltándose pequeños trozos fragmentados." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:194 msgid "" "I did not take the final step of having an \"allocating hint pointer\" that " "would trundle through a portion of swap as allocations were made in order to " "further guarantee contiguous allocations or at least locality of reference, " "but I ensured that such an addition could be made." msgstr "" "No realicé el paso final de tener un \"puntero de anotaciones para las " "asignaciones\" que recorrería una porción del espacio de intercambio según " "se hicieran las asignaciones para así garantizar asignaciones contiguas o al " "menos localidad de referencia, pero aseguré que esa condición no podría " "darse." #. type: Title == #: documentation/content/en/articles/vm-design/_index.adoc:196 #, no-wrap msgid "When to free a page" msgstr "Cuando liberar una página" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:201 msgid "" "Since the VM system uses all available memory for disk caching, there are " "usually very few truly-free pages. The VM system depends on being able to " "properly choose pages which are not in use to reuse for new allocations. " "Selecting the optimal pages to free is possibly the single-most important " "function any VM system can perform because if it makes a poor selection, the " "VM system may be forced to unnecessarily retrieve pages from disk, seriously " "degrading system performance." msgstr "" "Como el sistema de Memoria Virtual usa toda la memoria disponible para " "cachear disco, normalmente hay pocas páginas que estén realmente libres. El " "sistema de Memoria Virtual depende de su habilidad para adecuadamente " "escoger las páginas que no están en uso para reutilizarlas en nuevas " "asignaciones. Seleccionar las páginas óptimas para liberar es posiblemente " "la función más importante que cualquier sistema de Memoria Virtual puede " "realizar porque si la elección no es buena, el sistema de Memoria Virtual " "puede verse forzada a recuperar páginas de disco innecesariamente, " "degradando seriamente el rendimiento del sistema." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:204 msgid "" "How much overhead are we willing to suffer in the critical path to avoid " "freeing the wrong page? Each wrong choice we make will cost us hundreds of " "thousands of CPU cycles and a noticeable stall of the affected processes, so " "we are willing to endure a significant amount of overhead in order to be " "sure that the right page is chosen. This is why FreeBSD tends to outperform " "other systems when memory resources become stressed." msgstr "" "¿Cuánto trabajo extra estamos dispuestos a sufrir en el camino crítico para " "evitar liberar la página equivocada? Cada decisión errónea que hacemos " "costará cientos de miles de ciclos de CPU y una parada notable de los " "procesos afectados, así que estamos dispuestos a soportar una cantidad " "significativa de trabajo extra para estar seguros que se escoge la página " "adecuada. Por esto es por lo que FreeBSD tiende a superar en rendimiento a " "otros sistemas cuando se estresan los recursos de memoria." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:207 msgid "" "The free page determination algorithm is built upon a history of the use of " "memory pages. To acquire this history, the system takes advantage of a page-" "used bit feature that most hardware page tables have." msgstr "" "El algoritmo que determina la página libre se construye en base al histórico " "de uso de las páginas de memoria. Para adquirir este histórico, el sistema " "se aprovecha de la característica del bit de página utilizada que la mayoría " "del hardware de tablas de página posee." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:213 msgid "" "In any case, the page-used bit is cleared and at some later point the VM " "system comes across the page again and sees that the page-used bit has been " "set. This indicates that the page is still being actively used. If the bit " "is still clear it is an indication that the page is not being actively " "used. By testing this bit periodically, a use history (in the form of a " "counter) for the physical page is developed. When the VM system later needs " "to free up some pages, checking this history becomes the cornerstone of " "determining the best candidate page to reuse." msgstr "" "En cualquier caso, el bit de página utilizada se blanquea y en algún momento " "posterior el sistema de Memoria Virtual se encuentra con la página de nuevo " "y ve que el bit de página utilizada ha sido marcado. Esto indica que la " "página todavía se está utilizando activamente. Si el bit está blanqueado eso " "indica que la página no se usa activamente. Mediante el chequeo periódico de " "este bit, se desarrollo (en forma de contador) un histórico de uso . Cuando " "posteriormente el sistema de Memoria Virtual necesita liberar algunas " "páginas, examinar este histórico se convierte en la piedra de toque para " "determinar la mejor página candidata para reutilizar." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:218 msgid "" "For those platforms that do not have this feature, the system actually " "emulates a page-used bit. It unmaps or protects a page, forcing a page " "fault if the page is accessed again. When the page fault is taken, the " "system simply marks the page as having been used and unprotects the page so " "that it may be used. While taking such page faults just to determine if a " "page is being used appears to be an expensive proposition, it is much less " "expensive than reusing the page for some other purpose only to find that a " "process needs it back and then have to go to disk." msgstr "" "Para esas plataformas que no tienen esta característica, el sistema en " "realidad emula un bit de página utilizada. Desmapea o protege una página, " "forzando un fallo de página si ésta es accedida de nuevo. Cuando se maneja " "el fallo de página, el sistema simplemente marca la página como usada y " "desprotege la página de forma que puede ser utilizada. Aunque realizar este " "fallo de página tan solo para determinar si una página está siendo usada " "puede parecer una proposición cara, es mucho menos cara que reutilizar la " "página para otro propósito para darse cuenta después de que otro proceso la " "necesita y tener que ir al disco." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:228 msgid "" "FreeBSD makes use of several page queues to further refine the selection of " "pages to reuse as well as to determine when dirty pages must be flushed to " "their backing store. Since page tables are dynamic entities under FreeBSD, " "it costs virtually nothing to unmap a page from the address space of any " "processes using it. When a page candidate has been chosen based on the page-" "use counter, this is precisely what is done. The system must make a " "distinction between clean pages which can theoretically be freed up at any " "time, and dirty pages which must first be written to their backing store " "before being reusable. When a page candidate has been found it is moved to " "the inactive queue if it is dirty, or the cache queue if it is clean. A " "separate algorithm based on the dirty-to-clean page ratio determines when " "dirty pages in the inactive queue must be flushed to disk. Once this is " "accomplished, the flushed pages are moved from the inactive queue to the " "cache queue. At this point, pages in the cache queue can still be " "reactivated by a VM fault at relatively low cost. However, pages in the " "cache queue are considered to be \"immediately freeable\" and will be reused " "in an LRU (least-recently used) fashion when the system needs to allocate " "new memory." msgstr "" "FreeBSD utiliza varias colas de páginas para refinar aún más la selección de " "páginas a reutilizar así como para determinar cuando se deben llevar las " "páginas sucias a su almacenamiento de respaldo. Puesto que las tablas de " "páginas en FreeBSD son entidades dinámicas, cuesta virtualmente nada " "desmapear una página del espacio de direcciones de cualquier proceso que la " "esté usando. Cuando se ha escogido una página candidata basándose en el " "contador de página utilizada, esto es precisamente lo que se hace. El " "sistema debe distinguir entre páginas limpias que pueden en teoría ser " "liberadas en cualquier momento, y páginas sucias que deben ser escritas " "primero en el almacenamiento de respaldo antes de ser reutilizadas. Cuando " "se encuentra una página candidata se mueve a la cola inactiva si está sucia, " "o a la cola de caché si está limpia. In algoritmo separado que se bajas en " "el ratio de páginas sucias respecto de las limpias determina cuándo se " "tienen que escribir a disco las páginas sucias de la cola inactiva. Una vez " "hecho esto, las páginas escritas se mueven de la cola inactiva a la cola de " "caché. En este punto, las páginas en la cola de caché todavía pueden ser " "reactivadas por un fallo de Memoria Virtual con un coste relativamente bajo. " "Sin embargo, las páginas de la cola de caché se consideran como " "\"inmediatamente liberables\" y serán reutilizadas de modo LRU (Usada Menos " "Recientemente) cuando el sistema necesita asignar nueva memoria." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:232 msgid "" "It is important to note that the FreeBSD VM system attempts to separate " "clean and dirty pages for the express reason of avoiding unnecessary flushes " "of dirty pages (which eats I/O bandwidth), nor does it move pages between " "the various page queues gratuitously when the memory subsystem is not being " "stressed. This is why you will see some systems with very low cache queue " "counts and high active queue counts when doing a `systat -vm` command. As " "the VM system becomes more stressed, it makes a greater effort to maintain " "the various page queues at the levels determined to be the most effective." msgstr "" "Es importante señalar que el sistema de Memoria Virtual de FreeBSD intenta " "separar páginas limpias y sucias para expresar la razón de evitar la " "escritura innecesaria de páginas sucias (que come ancho de banda de E/S), y " "tampoco mueve de forma gratuita páginas entre distintas colas de páginas " "cuando el sistema de memoria no está bajo estrés. Este es el motivo por el " "que verás algunos sistemas con contadores de cola de caché muy bajos y " "contadores de cola de páginas activa altos cuando se ejecuta el comando " "`systat -vm`. Según el sistema de Memoria Virtual va sufriendo más estrés, " "hace un gran esfuerzo por mantener varias colas de páginas en los niveles " "que determina que son más efectivos." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:236 msgid "" "An urban myth has circulated for years that Linux did a better job avoiding " "swapouts than FreeBSD, but this in fact is not true. What was actually " "occurring was that FreeBSD was proactively paging out unused pages in order " "to make room for more disk cache while Linux was keeping unused pages in " "core and leaving less memory available for cache and process pages. I do " "not know whether this is still true today." msgstr "" "Durante años ha circulado una leyenda urbana acerca de que Linux hacía un " "mejor trabajo que FreeBSD evitando escribir en intercambio, pero de hecho " "esto no es cierto. Lo que ocurría en realidad era que FreeBSD estaba " "llevando a intercambio de forma proactiva páginas no utilizadas para hacer " "sitio para más caché de disco mientras que Linux estaba manteniendo las " "páginas sin utilizar y dejando menos memoria disponible para la caché y para " "páginas de procesos. No sé si esto sigue siendo cierto a día de hoy." #. type: Title == #: documentation/content/en/articles/vm-design/_index.adoc:238 #, no-wrap msgid "Pre-Faulting and Zeroing Optimizations" msgstr "Optimizaciones de Prefallo y de Rellenado con Ceros" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:248 msgid "" "Taking a VM fault is not expensive if the underlying page is already in core " "and can simply be mapped into the process, but it can become expensive if " "you take a whole lot of them on a regular basis. A good example of this is " "running a program such as man:ls[1] or man:ps[1] over and over again. If " "the program binary is mapped into memory but not mapped into the page table, " "then all the pages that will be accessed by the program will have to be " "faulted in every time the program is run. This is unnecessary when the " "pages in question are already in the VM Cache, so FreeBSD will attempt to " "pre-populate a process's page tables with those pages that are already in " "the VM Cache. One thing that FreeBSD does not yet do is pre-copy-on-write " "certain pages on exec. For example, if you run the man:ls[1] program while " "running `vmstat 1` you will notice that it always takes a certain number of " "page faults, even when you run it over and over again. These are zero-fill " "faults, not program code faults (which were pre-faulted in already). Pre-" "copying pages on exec or fork is an area that could use more study." msgstr "" "Realizar un fallo de Memoria Virtual no es costoso y la página subyacente ya " "está cargada y simplemente puede ser mapeada en el proceso, pero puede ser " "costoso si hay muchas de ellas de forma regular. Un buen ejemplo de esto es " "ejecutar un programa como man:ls[1] o man:ps[1] una y otra vez. Si el " "programa binario está mapeado en la memoria pero no lo está en la tabla de " "páginas, entonces todas las páginas que serán accedidas por el programa " "generarán un fallo cada vez que el programa se ejecute. Esto es innecesario " "cuando las páginas en cuestión ya están en la Caché de Memoria Virtual, de " "modo que FreeBSD intentará pre-poblar las tablas de páginas de un proceso " "con aquellas páginas que ya están en la Caché de Memoria Virtual. Algo que " "FreeBSD no hace todavía es un pre-copy-on-write de ciertas páginas al hacer " "exec. Por ejemplo, si ejecutas el programa man:ls[1] mientras ejecutas " "`vmstat 1` notarás que siempre produce un cierto número de fallos de página, " "incluso cuando lo ejecutas una y otra vez. Estos son fallos de página de " "rellenados de ceros, no fallos de código de programa (que ya han sido pre-" "fallados). Realizar una pre-copia de páginas en un exec o fork es un área en " "el que ser sujeto de más estudio." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:257 msgid "" "A large percentage of page faults that occur are zero-fill faults. You can " "usually see this by observing the `vmstat -s` output. These occur when a " "process accesses pages in its BSS area. The BSS area is expected to be " "initially zero but the VM system does not bother to allocate any memory at " "all until the process actually accesses it. When a fault occurs the VM " "system must not only allocate a new page, it must zero it as well. To " "optimize the zeroing operation the VM system has the ability to pre-zero " "pages and mark them as such, and to request pre-zeroed pages when zero-fill " "faults occur. The pre-zeroing occurs whenever the CPU is idle but the " "number of pages the system pre-zeros is limited in order to avoid blowing " "away the memory caches. This is an excellent example of adding complexity " "to the VM system in order to optimize the critical path." msgstr "" "Un gran porcentaje de los fallos de página que se producen son fallos de " "rellenado de ceros. Habitualmente puedes verlo observando la salida del " "comando `vmstat -s`. Esto ocurre cuando un proceso accede a páginas de su " "área de BSS. Se espera que el área de BSS esté inicializada a cero pero el " "sistema de Memoria Virtual no se molesta en asignar ninguna memoria en " "absoluto hasta el momento en el que el proceso accede de verdad. Cuando se " "produce un fallo el sistema de Memoria Virtual no solo debe asignar una " "nueva página, tiene que inicializarla a cero también. Para optimizar la " "operación de rellenado de ceros el sistema de Memoria Virtual tiene la " "capacidad de pre-inicializar páginas a cero y marcarlas como tal, y " "solicitar páginas pre-inicializadas a cero cuando ocurre un fallo de " "rellenado de ceros. La pre-inicialización a cero ocurren cuando la CPU está " "ociosa pero el número de páginas que el sistema pre-inicializa a cero está " "limitado para evitar destrozar las cachés de memoria. Este es un ejemplo " "excelente de cómo añadir complejidad al sistema de Memoria Virtual para " "optimizar el camino crítico." #. type: Title == #: documentation/content/en/articles/vm-design/_index.adoc:259 #, no-wrap msgid "Page Table Optimizations" msgstr "Optimizaciones de la Tabla de Páginas" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:269 msgid "" "The page table optimizations make up the most contentious part of the " "FreeBSD VM design and they have shown some strain with the advent of serious " "use of `mmap()`. I think this is actually a feature of most BSDs though I " "am not sure when it was first introduced. There are two major " "optimizations. The first is that hardware page tables do not contain " "persistent state but instead can be thrown away at any time with only a " "minor amount of management overhead. The second is that every active page " "table entry in the system has a governing `pv_entry` structure which is tied " "into the `vm_page` structure. FreeBSD can simply iterate through those " "mappings that are known to exist while Linux must check all page tables that " "_might_ contain a specific mapping to see if it does, which can achieve " "O(n^2) overhead in certain situations. It is because of this that FreeBSD " "tends to make better choices on which pages to reuse or swap when memory is " "stressed, giving it better performance under load. However, FreeBSD " "requires kernel tuning to accommodate large-shared-address-space situations " "such as those that can occur in a news system because it may run out of " "`pv_entry` structures." msgstr "" "Las optimizaciones de la tabla de páginas constituyen la parte más " "controvertida del diseño de la Memoria Virtual de FreeBSD y ha mostrado " "cierta tensión con la llegada de uso serio de `mmap()`. Creo que esto en " "realidad es una característica de la mayor parte de los BSDS aunque no estoy " "seguro de cuándo se introdujo por primera vez. Hay dos optimizaciones " "principales. La primar es que las tablas de páginas hardware no contienen un " "estado persistente sino que pueden descartarse en cualquier momento con solo " "un pequeño sobre coste en la gestión. La segunda es que cada entrada en la " "tabla de páginas activas en el sistema tiene una estructura `pv_entry` que " "lo gobierna la cual está enlazada a la estructura `vm_page`. FreeBSD puede " "simplemente iterar sobre esos mapeos que se sabe que existen mientras Linux " "tiene que comprobar todas las tablas de páginas que _podrían_ contener un " "mapeo específico para ver si es así, lo que puede provocar un sobre coste de " "O(n^2) en algunas situaciones. Por esto FreeBSD tiene a tomar mejores " "decisiones sobre qué páginas reutilizar o intercambiar cuando la memoria " "está bajo estrés, resultando en un mejor rendimiento bajo carga. Sin " "embargo, FreeBSD requiere ajustes del núcleo para acomodar situaciones con " "grandes espacios de direcciones compartidos como los que pueden darse en " "sistemas nuevos porque podría agotar las estructuras `pv_entry`." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:274 msgid "" "Both Linux and FreeBSD need work in this area. FreeBSD is trying to " "maximize the advantage of a potentially sparse active-mapping model (not all " "processes need to map all pages of a shared library, for example), whereas " "Linux is trying to simplify its algorithms. FreeBSD generally has the " "performance advantage here at the cost of wasting a little extra memory, but " "FreeBSD breaks down in the case where a large file is massively shared " "across hundreds of processes. Linux, on the other hand, breaks down in the " "case where many processes are sparsely-mapping the same shared library and " "also runs non-optimally when trying to determine whether a page can be " "reused or not." msgstr "" "Tanto Linux como FreeBSD necesitan trabajar en este área. FreeBSD trata de " "maximizar la ventaja de un modelo de mapeo activo potencialmente disperso " "(no todos los procesos necesitan mapear todas las páginas de una biblioteca " "compartida por ejemplo), mientras que Linux trata de simplificar sus " "algoritmos. FreeBSD en general tiene la venta del rendimiento a costa de " "gastar algo más de memoria extra, pero FreeBSD se desmorona en el caso donde " "un fichero grande está compartido de forma masiva entre cientos de procesos. " "Linux, por otro lado, se desmorona en el caso donde muchos procesos mapean " "pocas porciones de la misma biblioteca compartida y también se ejecuta de " "forma no-óptima cuando intenta determinar si una página puede ser " "reutilizada o no." #. type: Title == #: documentation/content/en/articles/vm-design/_index.adoc:276 #, no-wrap msgid "Page Coloring" msgstr "Coloreado de Páginas" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:286 msgid "" "We will end with the page coloring optimizations. Page coloring is a " "performance optimization designed to ensure that accesses to contiguous " "pages in virtual memory make the best use of the processor cache. In " "ancient times (i.e. 10+ years ago) processor caches tended to map virtual " "memory rather than physical memory. This led to a huge number of problems " "including having to clear the cache on every context switch in some cases, " "and problems with data aliasing in the cache. Modern processor caches map " "physical memory precisely to solve those problems. This means that two side-" "by-side pages in a processes address space may not correspond to two side-by-" "side pages in the cache. In fact, if you are not careful side-by-side pages " "in virtual memory could wind up using the same page in the processor cache-" "leading to cacheable data being thrown away prematurely and reducing CPU " "performance. This is true even with multi-way set-associative caches " "(though the effect is mitigated somewhat)." msgstr "" "Terminaremos con las optimizaciones de coloreado de páginas. El coloreado de " "páginas es una optimización de rendimiento diseñada para asegurar que el " "acceso a páginas contiguas en memoria virtual hacen el mejor uso posible de " "la caché del procesador. Hace mucho tiempo (es decir, más de 10 años) las " "cachés de los procesadores solían mapear memoria virtual en lugar de memoria " "física. Esto produjo un gran número de problemas que incluyen tener que " "limpiar la caché en cada cambio de contexto en algunos casos, y problemas " "con los alias de datos en la caché. De hecho, si no tienes cuidado, páginas " "contiguas en memoria virtual podrían terminar utilizando la misma página en " "la caché del procesador—llevando a desechar prematuramente datos cacheables " "y reduciendo el rendimiento de la CPU. Esto es cierto incluso en cachés " "asociativas multi direccionales (aunque el efecto se mitiga algo)." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:293 msgid "" "FreeBSD's memory allocation code implements page coloring optimizations, " "which means that the memory allocation code will attempt to locate free " "pages that are contiguous from the point of view of the cache. For example, " "if page 16 of physical memory is assigned to page 0 of a process's virtual " "memory and the cache can hold 4 pages, the page coloring code will not " "assign page 20 of physical memory to page 1 of a process's virtual memory. " "It would, instead, assign page 21 of physical memory. The page coloring " "code attempts to avoid assigning page 20 because this maps over the same " "cache memory as page 16 and would result in non-optimal caching. This code " "adds a significant amount of complexity to the VM memory allocation " "subsystem as you can well imagine, but the result is well worth the effort. " "Page Coloring makes VM memory as deterministic as physical memory in regards " "to cache performance." msgstr "" "El código de asignación de memoria de FreeBSD implementa optimizaciones de " "coloreado de páginas, lo que significa que el código se asignación de " "memoria intentará localizar páginas libres que son contiguas desde el punto " "de vista de la caché. Por ejemplo, si la página 16 de memoria física está " "asignada a la página 0 de la memoria virtual del proceso y la caché puede " "mantener 4 páginas, el código de coloreado de páginas no asignará la página " "20 de memoria física a la página 1 de la memoria virtual de un proceso. En " "su lugar, asignaría la página 21 de memoria física. El código de coloreado " "de páginas intenta evitar la asignación de la página 20 porque esto mapea " "sobre la misma memoria cacheada que la página 16 y resultaría en un cacheo " "no óptimo. Este código añade una significativa complejidad al subsistema de " "asignación de memoria de la Memoria Virtual como puedes imaginar, pero el " "resultado merece la pena. El Coloreado de Páginas hace que la memoria de la " "Memoria Virtual sea tan determinista como la memoria física en términos de " "rendimiento de caché." #. type: Title == #: documentation/content/en/articles/vm-design/_index.adoc:295 #, no-wrap msgid "Conclusion" msgstr "Conclusión" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:300 msgid "" "Virtual memory in modern operating systems must address a number of " "different issues efficiently and for many different usage patterns. The " "modular and algorithmic approach that BSD has historically taken allows us " "to study and understand the current implementation as well as relatively " "cleanly replace large sections of the code. There have been a number of " "improvements to the FreeBSD VM system in the last several years, and work is " "ongoing." msgstr "" "La Memoria Virtual en lo sistemas operativos modernos deben afrontar " "diversas situaciones de forma eficiente y para muchos patrones de uso " "distintos. La aproximación modular y algorítmica que históricamente ha " "tomado BSD nos permite estudiar y entender la implementación actual así como " "reemplazar piezas de código relativamente grandes de forma también " "relativamente limpia. Ha habido una serie de mejoras en el sistema e Memoria " "Virtual de FreeBSD en los últimos años, y el trabajo continua." #. type: Title == #: documentation/content/en/articles/vm-design/_index.adoc:302 #, no-wrap msgid "Bonus QA session by Allen Briggs" msgstr "Sesión extra de Preguntas y Respuestas por Allen Briggs" #. type: Title === #: documentation/content/en/articles/vm-design/_index.adoc:304 #, no-wrap msgid "What is the interleaving algorithm that you refer to in your listing of the ills of the FreeBSD 3.X swap arrangements?" msgstr "¿Qué es el algoritmo de entrelazado al que hiciste referencia en la lista de problemas del sistema de intercambio de FreeBSD 3.X?" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:310 msgid "" "FreeBSD uses a fixed swap interleave which defaults to 4. This means that " "FreeBSD reserves space for four swap areas even if you only have one, two, " "or three. Since swap is interleaved the linear address space representing " "the \"four swap areas\" will be fragmented if you do not actually have four " "swap areas. For example, if you have two swap areas A and B FreeBSD's " "address space representation for that swap area will be interleaved in " "blocks of 16 pages:" msgstr "" "FreeBSD utiliza un entrelazado de intercambio fijo con un valor por defecto " "de 4. Esto significa que FreeBSD reserva espacio para cuatro áreas de " "intercambio incluso si solo tienes una, dos o tres. Puesto que el espacio de " "intercambio está entrelazado el espacio lineal de direcciones que representa " "las \"cuatro áreas de intercambio\" estará fragmentado si en realidad no " "tienes cuatro áreas de intercambio. Por ejemplo, si tienes dos áreas de " "intercambio A y B la representación del espacio de direcciones en FreeBSD " "para ese área de intercambio estará entrelazada en bloques de 16 páginas:" #. type: delimited block . 4 #: documentation/content/en/articles/vm-design/_index.adoc:313 #, no-wrap msgid "A B C D A B C D A B C D A B C D\n" msgstr "A B C D A B C D A B C D A B C D\n" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:320 msgid "" "FreeBSD 3.X uses a \"sequential list of free regions\" approach to " "accounting for the free swap areas. The idea is that large blocks of free " "linear space can be represented with a single list node ([.filename]#kern/" "subr_rlist.c#). But due to the fragmentation the sequential list winds up " "being insanely fragmented. In the above example, completely unused swap " "will have A and B shown as \"free\" and C and D shown as \"all allocated\". " "Each A-B sequence requires a list node to account for because C and D are " "holes, so the list node cannot be combined with the next A-B sequence." msgstr "" "FreeBSD 3.X utiliza una aproximación de \"lista secuencial de regiones libres" "\" para contabilizar las áreas de intercambio libres. La idea es que grandes " "bloques de espacio lineal libre puede ser representado con un único nodo en " "la lista ([.filename]#kern/subr_rlist.c#). Pero debido a la fragmentación la " "lista termina estando completamente fragmentada. En el ejemplo superior, " "espacio de intercambio completamente sin utilizar hará que A y B se muestren " "como \"libre\" y C y D como \"todo asignado\". Cada secuencia A-B requiere " "un nodo en la lista para ser contabilizado porque C y D son huecos, así que " "el nodo de la lista no puede ser combinado junto con la siguiente secuencia " "A-B." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:322 msgid "" "Why do we interleave our swap space instead of just tack swap areas onto the " "end and do something fancier? It is a whole lot easier to allocate linear " "swaths of an address space and have the result automatically be interleaved " "across multiple disks than it is to try to put that sophistication elsewhere." msgstr "" "¿Por qué entrelazamos nuestro espacio de intercambio en lugar de mover las " "áreas hacia el final y hacer algo más interesante? Es mucho más fácil " "asignar rondas lineales de un espacio de direcciones y luego entrelazar " "automáticamente el resultado en múltiples discos en lugar de tratar de poner " "toda esa sofisticación en otro lado." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:327 msgid "" "The fragmentation causes other problems. Being a linear list under 3.X, and " "having such a huge amount of inherent fragmentation, allocating and freeing " "swap winds up being an O(N) algorithm instead of an O(1) algorithm. " "Combined with other factors (heavy swapping) and you start getting into " "O(N^2) and O(N^3) levels of overhead, which is bad. The 3.X system may also " "need to allocate KVM during a swap operation to create a new list node which " "can lead to a deadlock if the system is trying to pageout pages in a low-" "memory situation." msgstr "" "La fragmentación causa otros problemas. Al utilizar una lista lineal en 3.X, " "y tener una cantidad tan grande de fragmentación, asignar y liberar " "intercambio termina siendo un algoritmo O(N) en lugar de un algoritmo O(1). " "Junto con otros factores (mucho acceso al intercambio) y empiezas a tener " "niveles de sobrecarga de orden O(N^2) y O(N^3), lo que es malo. El sistema 3." "X puede necesitar además asignar Memoria Virtual del Núcleo durante una " "operación de intercambio para crear un nuevo nodo en la lista lo que puede " "producir un bloqueo si el sistema está intentando desalojar páginas en una " "situación de memoria baja." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:332 msgid "" "Under 4.X we do not use a sequential list. Instead we use a radix tree and " "bitmaps of swap blocks rather than ranged list nodes. We take the hit of " "preallocating all the bitmaps required for the entire swap area up front but " "it winds up wasting less memory due to the use of a bitmap (one bit per " "block) instead of a linked list of nodes. The use of a radix tree instead " "of a sequential list gives us nearly O(1) performance no matter how " "fragmented the tree becomes." msgstr "" "En 4.X no utilizamos una lista secuencial. En su lugar utilizamos un árbol " "radix y mapas de bits de bloques de intercambio en lugar de nodos de listas " "por rangos. Sufrimos la penalización de preasignar todos los mapas de bits " "necesarios para todo el área de intercambio pero esto al final desaprovecha " "menos memoria debido al uso de un mapa de bits (un bit por bloque) en lugar " "de una lista enlazada de nodos. El uso del árbol radix en lugar de una lista " "secuencia nos proporciona un rendimiento de casi O(1) independientemente de " "cómo de fragmentado esté el árbol." #. type: Title === #: documentation/content/en/articles/vm-design/_index.adoc:333 #, no-wrap msgid "How is the separation of clean and dirty (inactive) pages related to the situation where you see low cache queue counts and high active queue counts in systat -vm? Do the systat stats roll the active and dirty pages together for the active queue count?" msgstr "¿Cómo se relaciona la separación de páginas limpias y sucias (inactivas) con la situación donde puedes ver contadores bajos de la lista de cache y contadores altos de la lista activa en `systat -vm`? ¿Las estadísticas de systat cuentan las páginas activas y las sucias de forma conjunta en el contador de la cola activa?" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:338 msgid "" "Yes, that is confusing. The relationship is \"goal\" verses \"reality\". " "Our goal is to separate the pages but the reality is that if we are not in a " "memory crunch, we do not really have to." msgstr "" "Sí, eso es confuso. La relación es \"objetivo\" versus \"realidad\". Nuestro " "objeto es separar las páginas pero la realidad es que si no estamos en una " "crisis de memoria, en realidad no necesitamos hacerlo." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:340 msgid "" "What this means is that FreeBSD will not try very hard to separate out dirty " "pages (inactive queue) from clean pages (cache queue) when the system is not " "being stressed, nor will it try to deactivate pages (active queue -> " "inactive queue) when the system is not being stressed, even if they are not " "being used." msgstr "" "Esto significa que FreeBSD no intentará demasiado fuerte separar las páginas " "sucias (cola inactiva) de las limpias (cola de caché ) cuando el sistema no " "está bajo estrés, ni intentará desactivar páginas (cola activa -> cola " "inactiva) cuando el sistema no está bajo estrés, incluso si no están siendo " "utilizadas." #. type: Title === #: documentation/content/en/articles/vm-design/_index.adoc:341 #, no-wrap msgid "In man:ls[1] the / vmstat 1 example, would not some of the page faults be data page faults (COW from executable file to private page)? I.e., I would expect the page faults to be some zero-fill and some program data. Or are you implying that FreeBSD does do pre-COW for the program data?" msgstr "En el ejemplo de man:ls[1] / `vmstat 1`, algunos de los fallos de página no serían fallos de páginas de datos (COW del fichero del ejecutable a una página privada)? Es decir, esperaría algunos fallos de página fueran de rellenado de ceros y otros de datos de programa. ¿O te refieres a que FreeBSD hace pre-COW para los datos de programa?" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:347 msgid "" "A COW fault can be either zero-fill or program-data. The mechanism is the " "same either way because the backing program-data is almost certainly already " "in the cache. I am indeed lumping the two together. FreeBSD does not pre-" "COW program data or zero-fill, but it _does_ pre-map pages that exist in its " "cache." msgstr "" "Un fallo COW puede ser de rellenado de ceros o de datos de programa. El " "mecanismo es el mismo en cualquier caso porque el los datos de respaldo del " "programa ya estarán en la caché. De hecho estoy mezclando los dos. FreeBSD " "no hace pre-COW de los datos de programa o de rellenado de ceros, pero _sí_ " "premapea páginas que existen en la caché." #. type: Title === #: documentation/content/en/articles/vm-design/_index.adoc:348 #, no-wrap msgid "In your section on page table optimizations, can you give a little more detail about pv_entry and vm_page (or should vm_page be vm_pmap-as in 4.4, cf. pp. 180-181 of McKusick, Bostic, Karel, Quarterman)? Specifically, what kind of operation/reaction would require scanning the mappings?" msgstr "En la sección de optimizaciones de la tabla de páginas, puedes dar algo más de detalle acerca de `pv_entry` y `vm_page` (o debería vm_page ser `vm_pmap`—como en 4.4, cf. pp. 180-181 de McKusick, Bostic, Karel, Quarterman)? Específicamente, ¿qué tipo de operación/reacción requeriría un escaneo de los mapas?" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:352 msgid "" "A `vm_page` represents an (object,index#) tuple. A `pv_entry` represents a " "hardware page table entry (pte). If you have five processes sharing the " "same physical page, and three of those processes's page tables actually map " "the page, that page will be represented by a single `vm_page` structure and " "three `pv_entry` structures." msgstr "" "Un `vm_page` representa una tupla (objeto,índice#). Un `pv_entry` representa " "una entrada de la tabla de páginas hardware (pte). Si tienes cinco procesos " "compartiendo la misma página física y la tabla de páginas de tres de esos " "procesos mapean la página, ésta será representada mediante una sola " "estructura `vm_page` y tres estructuras `pv_entry`." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:355 msgid "" "`pv_entry` structures only represent pages mapped by the MMU (one `pv_entry` " "represents one pte). This means that when we need to remove all hardware " "references to a `vm_page` (in order to reuse the page for something else, " "page it out, clear it, dirty it, and so forth) we can simply scan the linked " "list of pv_entry's associated with that vm_page to remove or modify the " "pte's from their page tables." msgstr "" "Las estructuras `pv_entry` sólo representan páginas mapeadas por la MMU (una " "`pv_entry` representa una pte). Esto significa que cuando necesitamos " "eliminar todas las referencias hardware a la `vm_page` (para reutilizar la " "página para otra cosa, pasarla a disco, borrarla, marcarla como sucia y " "demás) podemos simplemente escanear la lista enlazada de estructuras " "`pv_entry` asociadas con esa `vm_page` y eliminar o modificar la pte de sus " "tablas de páginas." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:362 msgid "" "Under Linux there is no such linked list. In order to remove all the " "hardware page table mappings for a `vm_page` linux must index into every VM " "object that _might_ have mapped the page. For example, if you have 50 " "processes all mapping the same shared library and want to get rid of page X " "in that library, you need to index into the page table for each of those 50 " "processes even if only 10 of them have actually mapped the page. So Linux " "is trading off the simplicity of its design against performance. Many VM " "algorithms which are O(1) or (small N) under FreeBSD wind up being O(N), " "O(N^2), or worse under Linux. Since the pte's representing a particular " "page in an object tend to be at the same offset in all the page tables they " "are mapped in, reducing the number of accesses into the page tables at the " "same pte offset will often avoid blowing away the L1 cache line for that " "offset, which can lead to better performance." msgstr "" "En Linux no existe dicha lista enlazada. Para eliminar todos los mapeos de " "tablas de páginas hardware para una `vm_page` linux debe acceder a cada " "objeto de Memoria Virtual que _podría_ haber mapeado la página. Por ejemplo, " "si tienes 50 procesos todos mapeando la misma biblioteca compartida y " "quieres eliminar la página X de esa biblioteca, necesitas acceder a la tabla " "de páginas de cada uno de esos 50 procesos incluso si sólo 10 de ellos han " "mapeado la página. Así que Linux está favoreciendo la simplicidad en el " "diseño por el rendimiento. Muchos algoritmos de Memoria Virtual que son O(1) " "o (una N pequeña) en FreeBSD terminan siendo O(N), O(N^2), o peor en Linux. " "Puesto que los pte que representan una página concreta en un objeto suelen " "estar en el mismo desplazamiento en todas las tablas de páginas en las que " "están mapeadas, reducir el número de accesos a las tablas de páginas en el " "mismo desplazamiento del pte evitará por lo general que se destruya la línea " "de caché L1 para ese desplazamiento, lo que puede conllevar un mejor " "rendimiento." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:364 msgid "" "FreeBSD has added complexity (the `pv_entry` scheme) in order to increase " "performance (to limit page table accesses to _only_ those pte's that need to " "be modified)." msgstr "" "FreeBSD tiene más complejidad (el esquema de `pv_entry`) para mejorar el " "rendimiento (para limitar los accesos a la tabla de páginas _sólo_ a " "aquellos pte que necesitan ser modificados)." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:368 msgid "" "But FreeBSD has a scaling problem that Linux does not in that there are a " "limited number of `pv_entry` structures and this causes problems when you " "have massive sharing of data. In this case you may run out of `pv_entry` " "structures even though there is plenty of free memory available. This can " "be fixed easily enough by bumping up the number of `pv_entry` structures in " "the kernel config, but we really need to find a better way to do it." msgstr "" "Pero FreeBSD tiene un problema de escalado que Linux no tiene en cuento a " "que hay un número limitado de estructuras `pv_entry` y esto causa problemas " "cuando tienes datos masivamente compartidos. En esta caso podrías agotar las " "estructuras `pv_entry` incluso si hay memoria libre disponible de sobra. " "Esto se puede solucionar bastante fácilmente aumentando el número de " "estructuras `pv_entry` en la configuración del núcleo, pero necesitamos " "encontrar una forma mejor de hacerlo." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:372 msgid "" "In regards to the memory overhead of a page table verses the `pv_entry` " "scheme: Linux uses \"permanent\" page tables that are not throw away, but " "does not need a `pv_entry` for each potentially mapped pte. FreeBSD uses " "\"throw away\" page tables but adds in a `pv_entry` structure for each " "actually-mapped pte. I think memory utilization winds up being about the " "same, giving FreeBSD an algorithmic advantage with its ability to throw away " "page tables at will with very low overhead." msgstr "" "Respecto a la sobrecarga de memoria de una tabla de páginas versus el " "esquema de `pv_entry`: Linux utiliza tablas de páginas \"permanentes\" que " "no se descartan, pero no necesita una `pv_entry` para cada pte " "potencialmente mapeado. FreeBSD utiliza tablas de páginas \"desechables\" " "pero añade una estructura `pv_entry` para cada pte que esté realmente " "mapeado. Creo que la utilización de memoria termina siendo la misma, dándole " "a FreeBSD una ventaja algorítmica con su habilidad para desechar tablas de " "páginas a voluntad con muy poca sobrecarga." #. type: Title === #: documentation/content/en/articles/vm-design/_index.adoc:373 #, no-wrap msgid "Finally, in the page coloring section, it might help to have a little more description of what you mean here. I did not quite follow it." msgstr "Por último, en la sección de coloreado de páginas, podría ayudar describir un poco más a lo que te refieres. No lo seguí del todo." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:378 msgid "" "Do you know how an L1 hardware memory cache works? I will explain: Consider " "a machine with 16MB of main memory but only 128K of L1 cache. Generally the " "way this cache works is that each 128K block of main memory uses the _same_ " "128K of cache. If you access offset 0 in main memory and then offset 128K " "in main memory you can wind up throwing away the cached data you read from " "offset 0!" msgstr "" "¿Sabes cómo funciona una memoria caché hardware L1? Lo explicaré: Imagina " "una máquina con 16MB de memoria principal pero sólo 128K de caché L1. " "Normalmente esta caché funciona de modo que cada bloque de 128K de memoria " "principal utiliza _los mismos_ 128K de caché. Si accedes al desplazamiento 0 " "en memoria principal y luego al desplazamiento 128L en memoria principal " "¡terminas descartando los datos cacheados que leíste del desplazamiento 0!" #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:384 msgid "" "Now, I am simplifying things greatly. What I just described is what is " "called a \"direct mapped\" hardware memory cache. Most modern caches are " "what are called 2-way-set-associative or 4-way-set-associative caches. The " "set-associatively allows you to access up to N different memory regions that " "overlap the same cache memory without destroying the previously cached " "data. But only N." msgstr "" "Ahora bien, esto simplificando mucho las cosas. Lo que he descrito es lo que " "se llama una caché de memoria hardware de \"mapeo directo\". La mayoría de " "cachés modernas son lo que se llaman cachés asociativas de conjuntos de " "doble sentido o cachés asociativas de conjuntos de cuádruple sentido. La " "asociación por conjuntos te permite acceder hasta N regiones de memoria " "distintas que se solapan en la misma memoria de caché sin destruir los datos " "cacheados previamente. Pero sólo N." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:387 msgid "" "So if I have a 4-way set associative cache I can access offset 0, offset " "128K, 256K and offset 384K and still be able to access offset 0 again and " "have it come from the L1 cache. If I then access offset 512K, however, one " "of the four previously cached data objects will be thrown away by the cache." msgstr "" "Así que si tenemos una caché de conjuntos asociativa de cuádruple sentido " "puedo acceder los desplazamientos 0, 128K, 256K y 384K y todavía ser capaz " "de acceder al desplazamiento 0 de nuevo y que me lo devuelva de la caché L1. " "Se luego accedo al desplazamiento 512K, sin embargo, uno de loas cuatro " "objetos de datos cacheados previamente será descartado por la caché." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:391 msgid "" "It is extremely important... _extremely_ important for most of a processor's " "memory accesses to be able to come from the L1 cache, because the L1 cache " "operates at the processor frequency. The moment you have an L1 cache miss " "and have to go to the L2 cache or to main memory, the processor will stall " "and potentially sit twiddling its fingers for _hundreds_ of instructions " "worth of time waiting for a read from main memory to complete. Main memory " "(the dynamic ram you stuff into a computer) is __slow__, when compared to " "the speed of a modern processor core." msgstr "" "Es extremadamente importante... _extremadamente_ importante que la mayoría " "de accesos a memoria del procesador vengan de la caché L1, porque la caché " "L1 opera a la frecuencia del procesador. En el momento en el que tienes una " "pérdida en la caché L1 y tienes que ir a la caché L2 o a la memoria " "principal, el procesador parará y potencialmente se sentaría a esperar " "durante un tiempo equivalente a _cientos_ de instrucciones hasta que la " "lectura de memoria principal se complete. La memoria principal (la memoria " "dinámica que pones en tu ordenador) es _lenta_, cuando se compara con la " "velocidad del procesador." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:395 msgid "" "Ok, so now onto page coloring: All modern memory caches are what are known " "as _physical_ caches. They cache physical memory addresses, not virtual " "memory addresses. This allows the cache to be left alone across a process " "context switch, which is very important." msgstr "" "Ok, ahora vamos con el coloreado de páginas: Todas las memorias caché " "modernas con lo que se conoce como cachés _físicas_. Cachean direcciones de " "memoria física, no direcciones de memoria virtual. Esto permite no molestar " "a la caché durante un cambio de contexto de procesos, lo que es muy " "importante." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:400 msgid "" "But in the UNIX(R) world you are dealing with virtual address spaces, not " "physical address spaces. Any program you write will see the virtual address " "space given to it. The actual _physical_ pages underlying that virtual " "address space are not necessarily physically contiguous! In fact, you might " "have two pages that are side by side in a processes address space which wind " "up being at offset 0 and offset 128K in _physical_ memory." msgstr "" "Pero en el mundo UNIX(R) tú tratas con espacios de direcciones virtuales, no " "espacios de direcciones físicas. Cualquier programa que escribas verá un " "espacio de direcciones virtuales que se le ha proporcionado. Las páginas " "virtuales _reales_ que están por debajo del espacio de direcciones virtuales " "¡no están necesariamente contiguas físicamente! De hecho, podrías tener dos " "páginas que están pegadas una a la otra en el espacio de direcciones del " "proceso y que terminan estando en el desplazamiento 0 y el desplazamiento " "128K en memoria _física_." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:404 msgid "" "A program normally assumes that two side-by-side pages will be optimally " "cached. That is, that you can access data objects in both pages without " "having them blow away each other's cache entry. But this is only true if " "the physical pages underlying the virtual address space are contiguous " "(insofar as the cache is concerned)." msgstr "" "Un programa normalmente asume que dos páginas que están una al lado de la " "otra serán cacheadas de forma óptima. Es decir, que puedes acceder a objetos " "de datos en ambas páginas sin tener que destrozar las entradas de caché de " "la otra página. Pero esto sólo es cierto si las páginas físicas bajo el " "espacio de memoria virtual son contiguas (en lo que a la caché se refiere)." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:408 msgid "" "This is what Page coloring does. Instead of assigning _random_ physical " "pages to virtual addresses, which may result in non-optimal cache " "performance, Page coloring assigns _reasonably-contiguous_ physical pages to " "virtual addresses. Thus programs can be written under the assumption that " "the characteristics of the underlying hardware cache are the same for their " "virtual address space as they would be if the program had been run directly " "in a physical address space." msgstr "" "Esto es lo que hace el coloreado de páginas. En lugar de asignar páginas " "físicas de forma _aleatoria_, lo que podría resultar en un rendimiento de " "caché no óptimo, el coloreado de Páginas asigna páginas físicas " "_razonablemente contiguas_ a direcciones virtuales. Por lo tanto los " "programas se pueden escribir asumiendo que las características de la caché " "hardware subyacente son las mismas para el espacio de direcciones virtuales " "a como serían si el programa estuviera ejecutándose directamente en un " "espacio de direcciones físicas." #. type: Plain text #: documentation/content/en/articles/vm-design/_index.adoc:412 msgid "" "Note that I say \"reasonably\" contiguous rather than simply \"contiguous" "\". From the point of view of a 128K direct mapped cache, the physical " "address 0 is the same as the physical address 128K. So two side-by-side " "pages in your virtual address space may wind up being offset 128K and offset " "132K in physical memory, but could also easily be offset 128K and offset 4K " "in physical memory and still retain the same cache performance " "characteristics. So page-coloring does _not_ have to assign truly " "contiguous pages of physical memory to contiguous pages of virtual memory, " "it just needs to make sure it assigns contiguous pages from the point of " "view of cache performance and operation." msgstr "" "Nótese que digo \"razonablemente\" contiguas en lugar de simplemente " "\"contiguas\". Desde el punto de vista de una caché de mapeo directo de " "128K, la dirección física 0 es la misma que la dirección física 128K. De " "modo que dos páginas una al lado de la otra en tu espacio de memoria virtual " "podrían terminar siendo el desplazamiento 128K y 132K en memoria física, " "pero podría fácilmente ser también el desplazamiento 128K y 4K en memoria " "física y mantener todavía las mismas características de rendimiento de la " "caché. Así que el coloreado de páginas _no_ tiene que asignar páginas de " "memoria física realmente contiguas a páginas de memoria virtual que sí lo " "son, sólo necesita asegurarse de que asigna páginas contiguas desde el punto " "de vista del rendimiento y la operativa de la caché."