Como activar correctamente TRIM para tu SSD en Linux: fstrim, lvm y dm-crypt

A diferencia de los discos duros (HDDs), las memoria flash de tipo NAND que componen los SSDs no pueden sobrescribir los datos existentes. Esto significa que primero se han de borrar los datos viejos antes de escribir los nuevos. Dicha memoria flash esta dividida en bloques, que a su vez están subdivididos en páginas. La unidad mínima de escritura es una página, pero la unidad mínima de borrado es un bloque.

¿Veis el problema? Esto significa que a medida que pasa el tiempo el disco SSD irá fragmentando internamente los bloques entre las diferentes páginas, de forma que, llegado un punto no quedará ninguna página vacía, y cuando el disco tenga que escribir un bloque en alguna de las páginas que están a medias, primero necesitará copiar los bloques actuales desde esa página a una memoria intermedia, borrar la página y a continuación volver a escribir los bloques viejos más los nuevos en dicha página. Esto significa que conforme pasa el tiempo, el rendimiento del disco SSD se degrada cada vez más y más, ya que para cada escritura se ha de pasar por un ciclo de lectura-borrado-modificación-escritura. Esto se conoce como “amplificación de escritura”.

En ausencia de TRIM, los discos desconocen cuales de los bloques están siendo usados por un fichero o cuales pertenecen a espacio libre. Esto es debido a que cuando se borra un fichero lo único que hace el sistema operativo es marcar los bloques que ocupaba dicho fichero como borrados dentro del índice del sistema de ficheros. Pero en ningún momento informa al disco duro de esta operación. Esto significa que, con el paso del tiempo el rendimiento de un disco SSD irá cada vez a peor, por mucho espacio libre que quede en el sistema de ficheros, debido a que el disco SSD desconoce esta información.

¿Que es TRIM? TRIM es la solución inventada para este problema. TRIM es el nombre de un comando que el sistema operativo puede enviar al disco SSD para informarle cuales de los bloques están libres en el sistema de ficheros. El disco SSD utiliza esta información para desfragmentar internamente los bloques y así mantener páginas libres disponibles para ser escritas de forma rápida y eficiente.

¿Como activo TRIM en Linux? Lo primero que debes saber es que TRIM debe ser activado en todas las capas de abstracción de entrada/salida. Esto significa que si tienes una partición Ext4 sobre un LVM, que a su vez esta sobre un volumen cifrado con LUKS/dm-crypt, debes activar el soporte para TRIM en esas 3 capas: El sistema de ficheros, el LVM y dm-crypt. De nada vale que lo actives a nivel de sistema de ficheros si luego no lo activas en el resto de las capas. El comando TRIM ha de pasar de una capa a otra, con la consecuente conversión de índices de bloque, hasta llegar al disco SSD.

  1. Activar el soporte TRIM en dm-crypt

  2. Simplemente hemos de añadir la opcion discard en nuestro crypttab

    • $ cat /etc/crypttab

      # <target name>    <source device>    <key file>       <options>
      sda2_crypt         /dev/sda2          none             luks,discard
      

    Nota: El uso de TRIM sobre un sistema dm-crypt puede conllevar ciertos problemas de seguridad como la revelación de que sectores del disco no están en uso.

  3. Activar el soporte TRIM en LVM

  4. Hemos de activar la opción issue_discards en la configuración del LVM

    • $ cat /etc/lvm/lvm.conf

      # [...]
      devices {
         # [...]
         issue_discards = 1
         # [...]
      }
      # [...]
      
  5. Activar el soporte en el sistema de ficheros

  6. Esta es la parte más interesante. La mayoría de la gente se limita a añadir la opción “discard” en las opciones de montaje en /etc/fstab. Sin embargo, esto significa que cada vez que borres un fichero vas a estar notificando al disco SSD en tiempo real de que los bloques que ocupaba ese fichero ya no están en uso, y entonces el disco SSD va a tener que realizar una desfragmentación y borrado interno de dichos bloques, lo cual le va a llevar un tiempo no despreciable.

    De cara a optimizar al máximo el rendimiento del disco SSD, yo os recomiendo encarecidamente que evitéis realizar la operación TRIM en tiempo real (cada vez que borráis un fichero) ya que estáis haciendo trabajar al disco SSD de forma innecesaria. Es decir: no activéis la opción discard en el fstab.

    En vez de esto, lo que os recomiendo es ejecutar un script de forma periódica que informe al SSD de los bloques que están libres mediante el comando fstrim. Con ejecutar esta operación una vez al día o a la semana es más que suficiente. De esta forma no perdemos rendimiento ninguno debido a la operación TRIM y mantenemos informado al disco SSD de los bloques libres de forma periódica.

    Otras ventajas de este método (fstrim) son:

    • En caso de que en alguna capa superior no hayas activado de forma adecuada el soporte TRIM, al ejecutar fstrim recibirás un mensaje de error. Si en vez de usar fstrim usaras la opción discard en el fstab no hubieras recibido ningún error y pensarías que todo está funcionando correctamente cuando no es así.
    • En caso de que borres un fichero por equivocación podrás recuperarlo antes de que anacron ejecute tu script fstrim. Con la otra opción de realizar TRIM en tiempo real es completamente imposible recuperar un fichero borrado ya que tan pronto lo borres, el SSD habrá destruido los bloques que ocupaba dicho fichero.

    Aquí os dejo de ejemplo un sencillo script para ejecutar fstrim en las particiones /, /boot y /home, que puede programarse para ser ejecutado de forma periódica mediante anacron:

    • $ cat /etc/cron.weekly/dofstrim

      #! /bin/sh
      for mount in / /boot /home; do
      	fstrim $mount
      done
      

    Cabe mencionar, que tanto fstrim como la opción de realizar TRIM en tiempo real solo funcionan sobre sistemas de ficheros que implementen el ioctl FITRIM. A día de hoy, dichos sistemas de ficheros son:

    ~/kernel/linux (v3.8) $ grep -lr FITRIM fs/ | cut -d/ -f2 | sort | uniq | xargs echo
    btrfs ext3 ext4 gfs2 jfs ocfs2 xfs
    

Nota: Lo más probable es que tengas que regenerar tu initramfs con update-initramfs -u (Debian y derivados) o dracut -f (Redhat y derivados) y reiniciar después de efectuar cambios los cambios en la configuración de LVM o dm-crypt

Actualización 25-Feb-2013: Parece ser que los usuarios de Fedora con un volumen dm-crypt estarán afectados por este problema: https://bugzilla.redhat.com/890533

Actualización 14-Ago-2014: El siguiente script puede ser usado para detectar automáticamente los sistemas de ficheros que tienen TRIM activado y hacer la operación de fstrim sobre los mismos:

  • #!/bin/sh
    #
    # To find which FS support trim, we check that DISC-MAX (discard max bytes)
    # is great than zero. Check discard_max_bytes documentation at
    # https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt
    #
    for fs in $(lsblk -o MOUNTPOINT,DISC-MAX,FSTYPE | grep -E '^/.* [1-9]+.* ' | awk '{print $1}'); do
    	fstrim "$fs"
    done
    
Dejar un comentario?

53 Comentarios.

  1. the default install with encryption sets /boot as ext2. and i guess that doesn’t support Trim. what will the ramifications be to leave /boot as ext2 and not be able to Trim?

  2. thank you! excellent blog you have!

  3. Thanks for your great information. 😀
    I used to add discard in fstab before. When I switched to LVM, I needed to implement another way to set the Trim in my SSD. I have followed the blog information to setup the Trim, is there any method to check my setup is correct? Just like
    https://sites.google.com/site/lightrush/random-1/checkiftrimonext4isenabledandworking
    or
    http://howto.unixdev.net/Test_LVM_Trim_Ext4.html

  4. Excellent article thanks!

  5. Is this still true? (from http://askubuntu.com/a/191945/178920)

    However, these ‘discards’ will only trigger on remove or reduce operations on LVs. Discards on the filesystem on top of a LV will not propagate! From the same LVM changelog: “Issue discards on lvremove and lvreduce etc. if enabled and supported.”

    • Yes. Not sure about Ubuntu 12.04, but at least on Debian 6 (Squeeze) is true.

      The support for TRIM to LVM was added in the version 2.02.85 (see changelog)

      So, if your Linux distribution ships an older version of LVM you may get no support for TRIM.

      • But doesn’t that mean the “discard” option in fstab is useless? Or does fstrim work around LVM2?

        • If your filesystem is on top of a LVM volume, and your version of LVM is older than 2.02.85 you won’t get TRIM support. Neither with the discard option nor the fstrim one.

          The good thing about fstrim is that it will report the errors. However discard option in fstab will fail silently..

          So the best advice to check if your FS has TRIM support enabled on all the required layers is to run fstrim. If fstrim works, then you have TRIM enabled correctly, otherwise you will get an error.

  6. Not being much of a bash person a couple of things confuse me on this.

    My machine is set up with system files on SSD and /tmp /var and /home on hard drives to avoid writes to the ssd. This leaves me wondering what to fstrim as all of these come off /.

    The other aspect comes from reading about using ssd disks in redhat docs. They suggest trimming when the ssd has run out of “fresh space”. Makes sense as this would ensure wear levelling. There doesn’t seem to be a command available to check how much “fresh space” is left though. All not helped by the fact that there seems to be little info about on what exactly goes on inside these disks.

    Thanks for the info by the way. Best I have found.

    John

  7. How can I fstrim swap partition?

  8. I have this bash snippet for the cron.weekly job that gets the mountpoints based on the mounted devices info instead of hard coding them. Maybe it is useful to somebody else:


    #!/bin/sh

    # this cronjob will discard unused blocks on the ssd mounted filesystems

    # get the locally mounted block devices - those starting with "/dev:
    # run df -k, pipe the result through grep and save the sixth field in
    # in the mountpoint array
    mountpoint=( $(df -k | grep ^/dev | awk '{print $6}') )

    # loop through the array and run fstrim on every mountpoint
    for i in "${mountpoint[@]}"
    do
    /usr/sbin/fstrim -v $i;
    done

  9. Fantastic write-up! Really well written and organized. One of the most useful howto’s I’ve seen. ever.

  10. Great blog! The only problem I encountered in my Ubuntu 12.04 where / is on lvm is the “fstrim /” command can still be run without any error raised even if I added ‘issue_discard = 0’ in lvm.conf, then ‘update-initramfs -u’ and reboot performed. This is not expected. Any comment? Thanks!

  11. It seems that openSUSE 13.1 is currently not prepared for proper handling of the “discard” option in /etc/crypttab. The initrd does not contain the proper command.

    Workaround: In order to activate discard on boot time, I just hard-coded the “cryptsetup” commands in /lib/mkinitrd/boot/71-luks.sh to contain “luksOpen –allow-discards”. Works fine so far.

  12. Hi,

    it seems that trim is now activated by default on ubuntu 14.04 lts and its derivatives. However, if you are using LVM (not encrypted) and have snapshots of logical volumes, then the system is unable to trim. I can confirm this behaviour. Any ideas?

  13. On Debian (and the like) you can also do


    #! /bin/sh
    for mount in / /boot /home; do
    fstrim $mount
    done



  14. for fs in $(lsblk -o MOUNTPOINT,DISC-MAX,FSTYPE | grep -E '^/.* [1-9]+.* ' | awk '{print $1}'); do
    fstrim "$fs"
    done

    I think, better, will be:

    fstrim -a -v

    use “man fstrim” for more info :smile:

  15. OMG, Sorry, my bug)) :roll:

    That must be correct


    cron::weekly { 'fstrim_weekly':
    minute => '30',
    hour => '12',
    weekday => '0',
    user => 'root',
    command => "fstrim -a -v >> /var/log/fstrim.log";
    }

  16. No need for looping scripts anymore, there is fstrim -a now.

    Thanks for this nice article! :)

  17. Muchas gracias por este tutorial, mi configuración de portátil es exactamente esta (dm-crypt, LVM, ext4) y es justo lo que necesitaba 😉

  18. Hello, I’ve tried doing the same thing (taking into consideration that my architecture is the same, I have a VG encrypted with luks, and then multiple lvs) but unfortunatelly I still get the error of fstrim: /usr: FITRIM ioctl failed: Operation not supported

    I am using RHEL 6.6

    Do you have any idea how can I get it work? Thanks

  19. I’d like to thank you for the effort put into this excellent and clearly written tutorial. Good work and much appreciated

  20. Great writeup, especially in view of the following suspected bug: https://blog.algolia.com/when-solid-state-drives-are-not-that-solid/.

    So you know wanna be sure that trim is NOT enabled… 👿

  21. Thank you for this excellently written tutorial and guide. Not only did it explain everything it needed to, but when it made conclusions, it cited why! I recently migrated our Ubuntu (w/ LUKS) machine to an SSD and then came here to figure out all the complex trim stuff. Excellent article and thanks again!

  22. The script from August 2014 update emits every fs name twice on Debian 8.1 resulting in two calls to fstrim.

    I use the following script (reduced commands, we have awk already and I’m a traditional UNIX “saving resources” guy):


    eval $(lsblk -o MOUNTPOINT,DISC-MAX,FSTYPE | awk '
    $1 ~ /^\// && $2 ~ /^[1-9]+/ { fs[$1] = $1; }
    END { for (var in fs) { print "fstrim " var ";"; }
    }')

    To test just replace ‘eval’ by ‘echo’ or place the ‘echo’ inside the printf statement just before ‘fstrim’.

  23. Or, even better:

    fstrim –all

    😀

  24. Just wanted to thank you for this very useful article, particularly the explanation of why it is not so wise to enable discard in /etc/fstab.

  25. Muy bien explicado, claro y sin enrollarse con conceptos técnicos que no son de interés alguno para quienes el ordenador es una herramienta y no un fin en sí mismo.
    Gracias por compartir la información en castellano, algo muy necesario y que por desgracia no es tan habitual como debería (información como esta, de calidad y clara, quiero decir, que hay muchos blogs linuxeros hispanos pero con un nivel bastante mejorable, normalmente), carencia que es motivo de que mucha gente interesada en pasarse al “mundo libre” huya despavorida al ver que tiene que etar haciendo esfuerzos para entender artículos en inglés técnico cada vez que tiene algún problemilla y al final acabaen volviendo a Windows.

    Saludos.

  26. hi, is it possible to benefit Trim function with a liveUSB linux attached to an windowsXP-SSD laptop, in order to trim that SSD ?
    (please no remarks about why I’m using XP etc..Thanks!)

Deje un comentario


*


NOTA - Puede usar estosHTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>