Monday, March 31, 2014

[Tutorial] Economizar energía en Linux


Si pueden y quieren no olviden hacer una Donación (por Paypal) para el blog chimbo así podré seguir haciendo gran contenido.


En este post les voy a mostrar algunos consejos que yo uso para poder reducir el consumo de energía en Linux

Bumblebee & Bbswitch (si tienen una tarjeta gráfica con tecnología Optimus)


Primero, antes que nada, si tienen una tarjeta gráfica NVIDIA con tecnología Optimus deben instalar bumblebee y bbswitch.

Estos programas les va a permitir apagar la tarjeta gráfica cuando no está en uso. También les va a permitir prenderla cuando quieran, por ejemplo cuando quieren lanzar juegos.

Por defecto, cuando instalan Linux es su máquina la tarjeta siempre está prendida aunque no esté en uso. Entonces luego de instalar Bumblebee van a ver una gran mejora en el tiempo que dura la carga de su batería (en mi caso fue por lo menos ganar un 50% más).

bumblebee es un "daemon" es decir un programa que se ejecuta cada vez que es llamado automáticamente por el sistema operativo y bbswitch es el módulo del núcleo que es el que se encarga de apagar o prender la tarjeta gráfica. Asegúrense de ver la página de Github sobre el proyecto bbswitch  si les interesa saber como funciona exactamente.

Para instalar los paquetes:

Desde Ubuntu 13.10, bumblebee está en los paquetes oficiales ( las dependencias van a hacer que bbswitch y el driver de NVIDIA se instalen también):

$ sudo apt-get install bumblebee

Si están en Arch deben instalar todo manualmente:

# pacman -S bumblebee bbswitch nvidia

Si tienen intel-dri y xf86-video-intel instalados, deben reinstalar todo junto para que no hayan problemas de conflictos entre intel-dri y nvidia.

También pueden escoger si quieren usar el driver privativo hecho por  NVIDIA o el driver libre Nouveau (xf86-video-nouveau). Puede ser interesante instalar bbswitch-dkms en vez de bbswitch en Arch, de esta forma el módulo del núcleo va a sobrevivir cuando se haga una actualización del núcleo linux.

Si quieren probar que su tarjeta está apagada o prendida pueden usar este comando:

# cat /proc/acpi/bbswitch


Si están en Arch asegúrense de ver la página del ArchWiki sobre Bumblebee, necesitan terminar de configurar bumblebee manualmente para poder usarlo correctamente.

Hace algunos meses hice un post mostrando como se puede usar Bumblebee y como pueden configurar el "bridge" que se usa para lanzar los programas. Si quieren pueden verlo aquí.

Gráficos Intel (jugando con Kernel Mode Settings)


Si no tienen una tarjeta gráfica pero quieren hacer unos pequeños cambios en su sistema, también hay algunas opciones para los gráficos de Intel.

Lo primero que tienen que hacer es cargar el módulo i915 manualmente editando el archivo /etc/mkinitcpio.conf:

# nano /etc/mkinitcpio.conf

Hay una línea donde encontrarán la palabra "MODULES", ahí van a añadir i915.
No estoy muy seguro si esto va a cambiar mucho en su sistema, ya que lo único que hace es iniciar este módulo durante lo que se llama "bootstrap" y no después. A lo mejor ganen milésimas de segundo de arranque.

MODULES="i915"

Luego de que hicieron eso deben regenerar el initramfs:

# mkinitcpio -p linux

Ahora los cambios para poder mejorar el rendimiento: creen o editen el archivo /etc/modprobe.d/i915.conf y añadan esta línea:

options i915 i915_enable_rc6=7 i915_enable_fbc=1 lvds_downclock=1

PowerTOP (analizar su consumo de energía)


PowerTOP es una herramienta interesante que les muestra qué programa o que proceso está consumiendo más energía en su computador.

Pueden instalarlo desde los paquetes oficiales de su distribución seguramente:

$ sudo apt-get install powertop

# pacman -S powertop

Necesitan tener derechos de super usuario para usar esta herramienta:

# powertop

Sin argumentos esta aplicación se parece a la interfaz de top, les muestra en una lista todos los servicios y programas en orden. Pueden cambiar de tabs para ver otras estadísticas como Idle, Device y Frequency.
La interfaz de PowerTOP

Hay algunas opciones interesantes en PowerTOP. Pueden crear un archivo html en el cual habrá un reporte sobre su consumo de energía, pero lo más interesante de esto es que les va a generar una página con todos los scripts que pueden utilizar para mejorar el rendimiento de su batería.

Pero antes de que PowerTOP pueda generar este reporte necesita recolectar datos. Así pueden calibrar esta herramienta con

# powertop --calibrate

Asegúrense de que su laptop está utilizando la batería y dejen a PowerTOP correr por un rato. Cuando el programa muestre la interfaz normal pueden salir de esta y volver a usar su computador. La calibración debería haberse terminado.

Después de que hicieron eso pueden generar el reporte con:

# powertop --html=report.html

Luego pueden consultar el archivo con su navegador favorito.
Un ejemplo del archivo HTML creado por PowerTOP
La primera vez que usen PowerTOP es muy probable que vean que PulseAudio está consumiendo bastante energía.

Pueden crear un archivo de configuración para remediar esto

$ sudo nano /etc/modprobe.d/audio_powersave.conf

Añadan la línea:

options snd_hda_intel power_save=1

Si usan Intel, o : 

options snd_ac97_codec power_save=1

Para ac97.

PowerTOP tiene la habilidad de hacer cambios en sus preferencias para mejorar el rendimiento de su batería. Para eso solo deben usar el comando:

# powertop --auto-tune

Pueden crear un servicio SystemD por ejemplo:

$ sudo nano /etc/systemd/system/powertop.service

[Unit]
Description=Powertop tunings
[Service]
Type=oneshot
RemainAfterExit=no
ExecStart=/usr/bin/powertop --auto-tune
Environment="TERM=xterm"

[Install]
WantedBy=multi-user.target

Después de que lo crearon solo deben habilitarlo:

# systemctl enable powertop.service

TLP


Si no usan SystemD o si su distribución no tiene la última versión de PowerTOP con la opción de "auto tune", pueden usar TLP. Hice un post anterior sobre como instalar TLP en Ubuntu.

Entonces, qué hace TLP? Es una herramienta para gestionar su consumo de energía. Va a cambiar sus preferencias dependiendo de la fuente de poder de su computador. Por ejemplo va a cambiar el gobernador de su CPU cuando estén usando su computador con su batería.

Cuando lo instalen van a tener algunas opciones por defectom que son bastante buenas y van a funcionar. Pero pueden editar las configuraciones como quieran en realidad. Asegúrense de ver la página explicando las diferentes opciones que pueden utilizar. (Requiere un gran conocimiento de Linux en general)

Si quieren instalar TLP en Arch

# pacman -S tlp tlp-rdw 

Si usan un Thinkpad (IBM/Lenovo) necesitan unos paquetes extra

# pacman -S tp_smapi acpi_call

Y para finalizar habilitan los servicios con SystemD

# systemctl enable tlp
# systemctl enable tlp-sleep

Si quieren usar tlp-rdw, necesitan habilitar el dispatcher de Network Manager

# systemctl enable NetworkManager-dispatcher

Si están en Ubuntu:

$ sudo add-apt-repository ppa:linrunner/tlp
$ sudo apt-get update 


Luego instalen los paquetes que necesiten

$ sudo apt-get install tlp tlp-rdw

(si usan un Thinkpad)

$ sudo apt-get install tp-smapi-dkms acpi-call-tools 

Aquí pueden ver como instalar TLP en otras distribuciones.

Si quieren ver las configuraciones de su sistema pueden usar TLP (necesita derechos root)

# tlp stat

Va a hacer un log enorme con toda la información que les puede interesar.
Tal vez sea interesante redirigir la salida hacia un archivo:

# tlp stat > tlpoutput.data

O pueden usar grep para encontrar una línea específica, como por ejemplo saber en qué modo está TLP en este momento?

# tlp stat | grep "TLP power save"
La primeras líneas de TLP stat

Les gustó este post? No se olviden de agregarme a sus círculos en G+ o de seguirme en Twitter: @RobertoXMed

Si pueden y quieren no olviden hacer una Donación (por Paypal) para el blog chimbo así podré seguir haciendo gran contenido.

Monday, March 24, 2014

[Tutorial] Energy saving in Linux


In this post I will show you some tips that I use in order to reduce my power consumption in Linux.

Bumblebee & Bbswitch (if you have an Optimus GPU)


First thing first, if you have a NVIDIA graphics card with Optimus technology you should install bumblebee and bbswitch.

This piece of software will actually turn off the dedicated video card when it is not in use. And turn it on when you want to use it.

By default, when you install Linux in you machine the card will always be on. So after installing Bumblebee you will see a real improvement in battery life (almost a 50% increase).

bumblebee is the daemon and bbswitch is the kernel module that actually turns the card on and off. Make sure you take a look at the Github page of the bbswitch project if you are interested to know how this actually works.

To install the packages:

Since Ubuntu 13.10, bumblebee is in the official packages (dependencies should pull bbswitch and the NVIDIA driver too):

$ sudo apt-get install bumblebee

If you are in Arch you install the packages manually:

# pacman -S bumblebee bbswitch nvidia

If you have intel-dri and xf86-video-intel installed, you will have to reinstall them together with the rest to avoid a dependency conflict between intel-dri and nvidia.

You can also choose if you want to use the binary blob made by NVIDIA or the Nouveau driver (xf86-video-nouveau) that is Open Source. It can be interesting to install bbswitch-dkms instead of bbswitch in Arch so the kernel module will survive kernel updates.

If you want to test if the card is actually off you can run the command:

# cat /proc/acpi/bbswitch


If you are in Arch make sure you check the Arch Wiki page about Bumbeblee, you will need to do some other configuration in order to use bumblebee correctly.

I made a post some months ago showing how to run some tests using the dedicated graphic card and how to configure the "bridges" used by Bumblebee. Make sure you check it here.

Intel Graphics (playing with Kernel Mode Settings)


If you don't have a dedicated graphic card or if you want to tweak a little more in your system you can do some things about intel graphics.

First of all you can load the i915 module manually using the configuration file in /etc/mkinitcpio.conf:

# nano /etc/mkinitcpio.conf

There is a line that contains the word MODULES, add the module i915. Actually I'm not really sure that this is really necessary, this will initialize the module during bootstrap and not after that is the normal behavior of the kernel.

MODULES="i915"

After you did that you need to regenerate the initramfs:

# mkinitcpio -p linux

You can gain some energy editing (or creating) the file /etc/modprobe.d/i915.conf and adding the line:

options i915 i915_enable_rc6=7 i915_enable_fbc=1 lvds_downclock=1

PowerTOP (analyzing power usage of your machine)


PowerTop is an interesting tool that shows you what is the most consuming program or process of your computer.

You can install it from the official packages of your distribution:

$ sudo apt-get install powertop

# pacman -S powertop

You will need root privileges to run powertop

# powertop

Without arguments the application will show a top-like interface showing applications and services. You can switch tabs and check some stats like Idle, Device and Frequency.
The PowerTOP interface

There are some interesting features in PowerTOP. You can make a html file that will be like a report of your power consumption and what is interesting is that it will show you the preferences that you should if some configuration files.

But before you do that, PowerTOP needs to collect data about your machine. So you can calibrate this tool using

# powertop --calibrate

Make sure you are using your laptop's battery and leave it for a while. The program will change your backlight and preferences. And when the interface of powertop will appear again you can exit it. The calibration should be done by then.

After you have done that you can generate the report with:

# powertop --html=report.html

Then you can check it with your favorite browser.
Example of the HTML file created by PowerTOP
The first time you run PowerTOP it is very likely that you will see that PulseAudio is draining a lot of power.

You can create a config file to solve this

$ sudo nano /etc/modprobe.d/audio_powersave.conf

Insert the line

options snd_hda_intel power_save=1

If you are using Intel, or

options snd_ac97_codec power_save=1

For ac97.

PowerTOP has the ability to tune your preferences in order to save power. You just need to run:

# powertop --auto-tune

You can even create a simple SystemD service (if you are using SystemD in your distribution)

$ sudo nano /etc/systemd/system/powertop.service

[Unit]
Description=Powertop tunings
[Service]
Type=oneshot
RemainAfterExit=no
ExecStart=/usr/bin/powertop --auto-tune
Environment="TERM=xterm"

[Install]
WantedBy=multi-user.target

After you created the service just enable it:

# systemctl enable powertop.service

TLP


If you don't run SystemD or if your distribution doesn't have the latest PowerTOP version with the "Auto tune" feature you can use TLP. I did a post about how to install TLP in Ubuntu.

So what does TLP does? It is a power management tool that will change the default option of your system depending in the power source of your computer. For example it will change the CPU governor when you are using your battery.

When you install it you will have a default configuration file, that is pretty good and will work. But you can edit the configuration as you want, the problem is that you actually need to know what you want. Make sure you check the page explaining the different settings that you can use.

If you want to install TLP, in Arch:

# pacman -S tlp tlp-rdw 

If you are using a Thinkpad (IBM/Lenovo) you will need this extra packages

# pacman -S tp_smapi acpi_call

Then you need to start the SystemD service

# systemctl enable tlp
# systemctl enable tlp-sleep

Then if you want to use tlp-rdw, the radio device wizard you need to enable the Network Manager dispatcher

# systemctl enable NetworkManager-dispatcher

If you are using Ubuntu:

$ sudo add-apt-repository ppa:linrunner/tlp
$ sudo apt-get update 


Then install the packages that you need

$ sudo apt-get install tlp tlp-rdw

(if you are using a Thinkpad)

$ sudo apt-get install tp-smapi-dkms acpi-call-tools 

Here you can check how to install it in other distributions.

If you want to check all the parameters used in the configuration files you can use TLP (needs root privileges)

# tlp stat

It will make an enormous log with all the information that you may want. Maybe you can redirect the output to a file:

# tlp stat > tlpoutput.data

Or you can grep the output to find an specific line, like is TLP actually in power saving mode right now?

# tlp stat | grep "TLP power save"
The first lines of the TLP stat output

Did you like this post? Don't forget to add me to your circles in G+ or to follow me on Twitter: @RobertoXMed

Please consider donating to the Blog it will be of great help! Thank you.

Wednesday, March 12, 2014

Wow 200mil visitas, gracias!

Wow!! ¡¡Muchísimas gracias!!

Pues mi blog llegó a las 200 mil visitas hoy! Y pues, siento que es un número muy importante así que haré este post para decirles cuanto los aprecio.
Celebration mood : ON
Déjenme les cuento un poquito sobre este blog:

Pues todo esto comenzó porque sentía que había una falta de blogs/foros/páginas en español que hablen sobre Linux. En el último año he ido descubriendo más y más, sin embargo siempre quise tener este pequeño (pequeñisisisisisísimo) espacio en el Internet para poder expresarme sobre el tan amado y sensual LINUX, Gnu/Linux, o como quieran llamarlo, depende de su filosofía sobre eso jajaja.

Creo que el número de visitas que recibo al día (un promedio de 500~600 con records de hasta 4000, si no me equivoco) prueban de que este pequeño espacio ha funcionado, además de que la mayoría de la audiencia, como el 65% viene de países como España y México. Sin olvidar que los records de artículos más vistos son los que están en español.

Pero quería que mi contenido sea un poco más accesible para todo el mundo, y es por eso que todos [bueno casi] mis posts están escritos en inglés y en español. De hecho el segundo país que más visita el Blog de Bob son los Estados Unidos.

Entonces... ¿Qué pueden esperar de ahora en adelante?

¡Más posts! (Un par de traducciones que creo que me faltan) Lo siento por la falta de publicaciones pero los últimos meses en la universidad me han tenido muy ocupado :(

Quisiera poder hacer otro tipo de artículos, es decir ya no solo tutoriales sobre las 64986846518 cosas que hacer luego de instalar inserte su distro favorita aquí. Sé que han sido de mucha ayuda para mucha gente y lo seguiré haciendo pero también hay cosas muy interesantes de las cuales me gustaría hablar.

Tal vez comience a hacer algunos reviews de juegos (Steam se está poniendo cada vez más bueno), tal vez un poco de benchmarking, pero bueno no creo que pueda competir con Phoronix nunca! :P, y me encantaría hacer un poco de artículos de discusión. Por ejemplo me encantaría dar mi punto de vista sobre SystemD vs Upstart.

Pero debo admitir que a veces es un poco difícil seguir todo lo que está pasando en la comunidad.

Por otro lado lo que se viene sí o sí:
  1. ¿Qué hacer luego de instalar Ubuntu 14.04?
  2. Reseña de Ubuntu 14.04
  3. Todo sobre economizar energía en Linux
¡De nuevo muchas gracias!

Yo hago todo esto por diversión/pasión y espero haber sido de ayuda para algunas personas. Lo siento mucho si su sistema murió por mi culpa cuando hicieron un Copy/Paste de algún comando :S

Este blog genera 0 $/€/¥ pero no me importa! (Aunque cualquier tipo de contribución es más que bienvenida, de hecho no sé si el botón de PayPal sigue funcionando :/ )

De todas formas, seguiré haciendo esto mientras la gente siga usando mis posts. Me motiva mucho cuando dejan comentarios así que no duden en hacerlo, los leo todo el tiempo :D
Él es Bob, vestido para la ocasión

OMG 200K views, thank you!

Wow!! Thank you very much!

So my blog hit the 200k mark today! And I think is a very impressive number so this little post is here to thank you all, for making this happen.
Celebration mood : ON
Let me tell you a little bit about this blog:

I started this blog because I realized/thought that there aren't many blogs/forums for Linux in Spanish. I have discovered some in the past year, but I still wanted to have my place in the Internet where I could express myself.
I think the number of visits I receive a day (an average of 500~600) proves that it has actually worked, since my audience is like 65% based in Spanish speaking countries like Spain or Mexico.

But I wanted to make my content more accessible to everybody, so every post [or almost] is written in Spanish and English. The second country that visits the most my post is the United States actually.

So what can you expect from now on:

More posts!! (An a couple translations that are missing) Sorry about the lack of posts for the last months but college keeps me very occupied. :(

And I want to do other kind of articles, not only to-do lists although they seems to be very helpful for a lot of people.
Maybe some game reviews (Steam is getting more awesome every week) and some benchmarking, but I will just admit that I could never beat Phoronix :P, maybe some discussions.

But I'll admit that sometimes is very hard to follow everything that is happening in the Linux community.

In the other hand stuff that you will most certainly see:
  1. Top things to do after Installing Ubuntu 14.04
  2. Review Ubuntu 14.04
  3. All about power saving in Linux
Again thank you very much

I do this for fun/passion and I hope I have been of some help for some people.I'm really sorry if I broke your system when you did a Copy/Paste to the terminal.

This blog generates 0 $/€/¥ but I don't really care!! (although contributions are welcomed :P , I wonder if the PayPal button is still working :/ )

Anyway! I'll keep doing it as long as it is fun and as long as people are using my articles. It's very motivational guys, so don't hesitate to leave comments with questions, I read them all the time :D

This Bob, dressed for the occasion :D

Wednesday, March 5, 2014

[Tutorial] Personalizar las herramientas básicas en Linux

Personalizar las herramientas básicas en Linux

Si como a mí, les gusta cambiar el aspecto de las herramientas que usan todos los días: como el Terminal, su editor de texto y cosas de ese estilo... pueden ver algunas opciones que dejaré en este post.

Personalizar su Shell


Antes que nada, yo prefiero utilizar zsh en vez de bash porque tiene algunas mejoras y funcionalidades más interesantes. Es un shell un poco más evolucionado, pero uno necesita escribir su propio archivo de configuración o conseguir uno en línea.

Yo no escribí mi propio archivo de configuración para zsh. Lo sé, qué decepción.. Pero si alguien ya lo hizo y lo hizo mejor que yo, pues voy a usar lo que hizo. :)

Hay un montón de opciones que se pueden encontrar en internet. El que yo uso y me gusta mucho se llama grml zsh rc.
Este es el archivo de configuración es el que se usa cuando uno instala Arch en una máquina, y tiene muchas funcionalidades interesantes. Por ejemplo la compleción para las páginas del manual, archivos o carpetas... básicamente para todo lo que puedan usar la Tabulación. Les mostrará todas las opciones que haya y creará un menú dinámicamente en la pantalla de su terminal.
Un ejemplo de la compleción cuando busco una página del manual. La tabulación me permite navegar entre las selecciones.
Inclusive hay una página de manual para el archivo de configuración. Pueden agregar muchas cosas interesantes en su prompt como el estado de su batería, o pueden cambiar el look de su prompt muy fácilmente con algunas opciones predeterminadas.

Si quieren instalar esto (asegúrense de hacer una copia de respaldo de su archivo de configuración si desean conservarlo):

$ wget -O .zshrc http://git.grml.org/f/grml-etc-core/etc/zsh/zshrc

Si estan usando Arch pueden instalarlo directamente desde los paquetes extra:

# pacman -S grml-zsh-config

Otra opción que probé no hace mucho se llama oh-my-zsh.
Tienen un montón de archivos de configuración creados por la comunidad y pueden pasar de uno a otro muy fácilmente, cambiando una sola línea de su archivo .zshrc .

Asegúrense de ver las opciones en la página Github del proyecto.

Si prefieren usar bash pueden chequear el Arch wiki sobre Color Bash Prompt.

¿Cansados de la apariencia de ls


Recientemente vi un screenshot en una comunidad de Linux en G+ que mostraba colores diferentes para el comando ls. Luego comencé a buscar sobre cómo cambiar los colores para los diferentes tipos de archivos y me encontré con el tema Solarized que al parecer es bastante popular.
Todos los tipos de archivos con los diferentes colores.
Si quieren cambiar los colores para el comando ls, pueden ir a este proyecto Github y descargar el tema que quieran utilizar. Yo uso el tema 256.

Cambien el nombre del archivo que descargaron y pónganlo donde quieran (en mi caso lo puse en el home):

$ mv dircolors.256dark ~/.dircolors

Luego necesitan ejecutar el comando siguiente cada vez en su terminal:

$ eval `dircolors ~/.dircolors`

Entonces la mejor manera de hacerlo es editando su archivo de configuración, dependiendo de su shell va a ser.bashrc para bash, .zshrc para zsh.

PERO si usan grml config para la configuración de su zsh no pueden editar el archivo.zshrc directamente porque es muy arriesgado.
La manera correcta de hacer esto es editando/creando el archivo .zshrc.local en el cual van a añadir la línea siguiente:

eval `dircolors ~/.dircolors`

Si quieren hacer unos cambios extras pueden intentar el comando llamado ls++ (ls on steroids).

Pueden instalarlo directamente desde AUR si están en Arch o compilarlo con las fuentes. Aquí está la la página Github.

Terminator, usando zsh con GRML config, Solarized como dircolors y ls en esteroides.


Instalar el tema Solarized en VIM


En esta última parte les voy a mostrar como instalar el tema Solarized en VIM.

(G)VIM con Solarized como tema
La página Github del proyecto explica cómo hacerlo.

Yo instale el bundle en .vim/bundle y copié el archivo solarized.vim en .vim/colors. Si no tienen estas carpetas simplemente deben crearlas con mkdir.

Una vez que copiaron el archivo y el bundle lo único que les queda por hacer es cambiar el colorscheme:

:colorscheme solarized

Si quieren hacer esto de manera permanente necesitan crear/editar el archivo .vimrc añadiendo la línea

colorscheme solarized

Les gustó este post? No se olviden de agregarme a sus círculos en G+ o de seguirme en Twitter: @RobertoXMed

Si pueden y quieren no olviden hacer una Donación (por Paypal) para el blog chimbo así podré seguir haciendo gran contenido.