"Después del juego es antes del juego"
Sepp Herberger

lunes, 23 de marzo de 2015

Opinión: Administración Electrónica, así no.

Se supone que el futuro es hacer multitud de trámites con la Administración usando certificados digitales. Del DNIe nos vamos a olvidar ya que usarlo es una tortura incluso en Windows: instalación manual tocando en determinados sitios del navegador, versiones de java incompatibles y petición del pin a traición.

Hoy voy a hablar de tres trámites con la Administración usando el certificado digital de la FNMT.

  • Acceso a notificaciones de la AEAT: usando el certificado digital instalado en el navegador y teniendo potra con el plugin de Java puede acceder uno a las notificaciones del ministro Montoro. Nada que objetar, excepto que te salta algún applet de Java para manejar el certificado o lo que quiera que haga.
  • Acceso a las notificaciones 060, que se supone que es la punta de lanza de la Administración Electrónica: terrible. No les basta con tener el certificado digital instalado en el navegador, hay que instalarlo en la máquina virtual de Java. ¿Cómo?: a traves del Panel de Control de Java (/usr/bin/ControlPanel). Resulta que la versión del Oracle Java que tenía instalada no tenía la pestaña para añadir un certificado digital. Tuve que probar varias versiones hasta dar con una. Una vez logré entrar, resulta que dicho sistema de notificaciones para entidades públicas lo usan cuatro y el del tambor, como diría Fedegggico.
  • Solicitud a la AEAT del modelo 143: limpio, sin Java. Usando solamente el certificado del navegador incluso para firmar la solicitud.

Y aquí está la gracia: la misma administración (la Administración General del Estado) requiere tres métodos distintos de acceso y firma para tres procedimientos, dos de los cuales se realizan ante la AEAT. Así no se puede: no puedes obligar al ciudadano a que tenga que devanarse los sesos según el trámite que vaya a hacer.

La raíz del problema no la sé, pero me la huelo: cada procedimiento se ha subcontratado a una empresa distinta, que lo ha implementado como buenamente ha podido con sus sub-sub-asalariados. El resultado final es como si se hubiese encomendado al ejército de Pancho Villa. No se puede construir un front-end heterogéneo para el ciudadano así, señores gobernantes: menos comilonas y mas sentido común.

Fin de la cita.

Listar el valor real de los parámetros de un módulo cargado por el kernel.

Normalmente, los drivers de Linux tienen diversos parámetros con los que podemos jugar al cargarlos en memoria, logrando así que funcionen mejor o, simplemente, funcionen correctamente. Cuando trabajamos con hardware diverso siempre que tenemos problemas de estabilidad o rendimiento tenemos que andar husmeando y afinando dichos parámetros. La forma de saber que parámetros tiene un driver es:

root@A99-PRO:~# modinfo radeon
filename: /lib/modules/3.16-0.bpo.2-amd64/kernel/drivers/gpu/drm/radeon/radeon.ko
license: GPL and additional rights
description: ATI Radeon
author: Gareth Hughes, Keith Whitwell, others.
firmware: radeon/R520_cp.bin
.......
firmware: radeon/BONAIRE_vce.bin
alias: pci:v00001002d000099A4sv*sd*bc*sc*i*
........
alias: pci:v00001002d00001304sv*sd*bc*sc*i*
depends: drm,drm_kms_helper,ttm,i2c-core,i2c-algo-bit
intree: Y
vermagic: 3.16-0.bpo.2-amd64 SMP mod_unload modversions
parm: no_wb:Disable AGP writeback for scratch registers (int)
parm: modeset:Disable/Enable modesetting (int)
parm: dynclks:Disable/Enable dynamic clocks (int)
parm: r4xx_atom:Enable ATOMBIOS modesetting for R4xx (int)
parm: vramlimit:Restrict VRAM for testing, in megabytes (int)
parm: agpmode:AGP Mode (-1 == PCI) (int)
parm: gartsize:Size of PCIE/IGP gart to setup in megabytes (32, 64, etc., -1 = auto) (int)
parm: benchmark:Run benchmark (int)
parm: test:Run tests (int)
parm: connector_table:Force connector table (int)
parm: tv:TV enable (0 = disable) (int)
parm: audio:Audio enable (-1 = auto, 0 = disable, 1 = enable) (int)
parm: disp_priority:Display Priority (0 = auto, 1 = normal, 2 = high) (int)
parm: hw_i2c:hw i2c engine enable (0 = disable) (int)
parm: pcie_gen2:PCIE Gen2 mode (-1 = auto, 0 = disable, 1 = enable) (int)
parm: msi:MSI support (1 = enable, 0 = disable, -1 = auto) (int)
parm: lockup_timeout:GPU lockup timeout in ms (defaul 10000 = 10 seconds, 0 = disable) (int)
parm: fastfb:Direct FB access for IGP chips (0 = disable, 1 = enable) (int)
parm: dpm:DPM support (1 = enable, 0 = disable, -1 = auto) (int)
parm: aspm:ASPM support (1 = enable, 0 = disable, -1 = auto) (int)
parm: runpm:PX runtime pm (1 = force enable, 0 = disable, -1 = PX only default) (int)
parm: hard_reset:PCI config reset (1 = force enable, 0 = disable (default)) (int)
parm: vm_size:VM address space size in gigabytes (default 4GB) (int)
parm: vm_block_size:VM page table size in bits (default 9) (int)
parm: deep_color:Deep Color support (1 = enable, 0 = disable (default)) (int)

La forma en que se da valor a esos parámetros es en /etc/modprobe.d. Por ejemplo si queremos dar un valor al parámetro mode del driver radeon haríamos (el nombre del fichero radeon-kms.conf es arbitrario):

root@A99-PRO:~# cat /etc/modprobe.d/radeon-kms.conf 
options radeon modeset=1
root@A99-PRO:~#

Otra opción es añadirlo en /boot/grub.cfg, en la línea que carga el núcleo:

....
linux /boot/vmlinuz-3.10.12-100.fc18.x86_64 root=UUID=e39b2bba-0709-4e67-89b6-c8ebcf89592f ro radeon.modeset=0
....

Hay varios sitios más desde donde dar esos valores,pero estos son los mas usuales.

Mi problema era que quería saber, con el sistema ya arrancado, que valor tenían realmente los parámetros. Lo encontré en http://stackexchange.com, pero por desgracia perdí la referencia al mensaje concreto. El script es este:

root@A99-PRO:~# cat parametros-modulo.sh 
#!/bin/bash

cat /proc/modules | grep $1 | cut -f 1 -d " " | while read module; do \
echo "Module: $module"; \
if [ -d "/sys/module/$module/parameters" ]; then \
ls /sys/module/$module/parameters/ | while read parameter; do \
echo -n " $parameter="; \
cat /sys/module/$module/parameters/$parameter; \
done; \
fi; \
echo; \
done

Ahora, si queremos saber el valor que tienen todos los parámetros de, por ejemplo, el módulo radeon y sus módulos dependientes haríamos:

root@A99-PRO:~# ./parametros-modulo.sh radeon
Module: radeon
agpmode=0
aspm=-1
audio=-1
benchmark=0
connector_table=0
deep_color=0
disp_priority=0
dpm=-1
dynclks=-1
fastfb=0
gartsize=512
hard_reset=0
hw_i2c=0
lockup_timeout=10000
modeset=1
msi=-1
no_wb=0
pcie_gen2=-1
r4xx_atom=0
runpm=-1
test=0
tv=1
vm_block_size=9
vm_size=4
vramlimit=0

Module: ttm

Module: drm_kms_helper
edid_firmware= poll=Y

Module: drm
debug=0
edid_fixup=6
rnodes=0
timestamp_monotonic=1
timestamp_precision_usec=20
universal_planes=0
vblankoffdelay=5000

Module: i2c_algo_bit
bit_test=0

Module: i2c_core

Y eso esto todo, amigos.

lunes, 16 de marzo de 2015

Montemos una webcam IP barata (y III)

Bueno, recapitulemos:

  • En la primera parte vimos como instalar el sabor OpenWrt de Linux en un router ADSL Huawei de Vodafone que estaba desahuciado. Esa entrada nos la podemos saltar en gran parte si queremos montar nuestro sistema usando una Raspberry Pi o cualquier miniordenador.
  • En la segunda parte vimos como configurar la cámara, el almacenamiento de las imágenes en una ubicación remota y, usando el software motion, hacer las primeras capturas.

Pues vamos ahora a sacar jugo a lo que tenemos montado.

1. Configurar la detección de movimiento.

Ahora vamos a detectar el movimiento, jugando con los parámetros de /etc/motion.conf. Hay muchas guías en la red explicando los distintos parámetro. A mi me han dado buenos resultados estos:

daemon on
width 352
height 288
framerate 20
snapshot_interval 60
locate_motion_mode on
locate_motion_style redbox
snapshot_filename %Y-%m-%d-%H:%M:%S-snapshot
picture_filename %Y-%m-%d-%H:%M:%S-%q
pre_capture 3
post_capture 3
output_normal on
minimum_motion_frames 1
lightswitch 20
threshold 2000

El resto de parámetros de motion.conf los dejamos igual. Básicamente decimos a motion que se ejecute de fondo, capture a resolución 352x288 y a 20 fps por segundo cuando detecte movimiento. Independientemente, cada 60 segundos toma una captura, haya movimiento o no. Cuando detecta movimiento remarca la zona con una caja roja. Los ficheros donde guarda las capturas tienen en su nombre la fecha y la hora. Defino un valor para los cambios de luz (ligthswitch) y número de pixeles cambiados (treshold) que me han funcionado bien ante falsos positivos.

El parámetro "output_normal on" indica que cuando hay movimiento capture todos los fotogramas que quiera. Otros valores que podemos dar harán que se capture el mejor fotograma, o que se grabe un vídeo en lugar de fotogramas sueltos.

Adicionalmente podemos asociar comandos o scripts a determinados eventos, por ejemplo añadiendo a motion.conf:

on_event_start echo "Detectado inicio de movimiento %H:%M:%S" >> /mnt/snapshot/log.txt
on_picture_save echo "Guardando imagen en %f %H:%M:%S" >> /mnt/snapshot/log.txt
on_event_end echo "Fin de movimiento %H:%M:%S" >> /mnt/snapshot/log.txt
on_movie_start echo "Empezando video %f %H:%M:%S" >> /mnt/snapshot/log.txt
on_movie_end echo "Finalizando video %f %H:%M:%S" >> /mnt/snapshot/log.txt

El fichero /mnt/snapshot/log.txt guardará un log de los eventos detectados. Nótese el uso de variables de sustitución, aquí estan todos. Algunos sólo pueden usarse en determinado eventos, como %f (nombre de fichero de captura) que solo aparece on_picture_save, on_movie_start y on_movie_end.

2. Aviso remoto de eventos

Para avisar remotamente de los eventos lo mas sencillo es usar correo (aunque otras opciones son usar SMS o twitter, ya que hay APIs para ello). Me he decantado por lo mas sencillo y he usado una cuenta de gmail por smpt. He probado ssmtp y mailsend, pero el primero no permite enviar adjuntos y el segundo no funciona con gmail en Barrier Breaker (no tiene activo el SSL), así que los descarté.

La opción que mejor me ha funciona es la combinación de msmtp y mutt, ya que ambos combinados permiten enviar mensajes por gmail y adjuntar ficheros (por ejemplo imágenes). Mutt compone el correo y msmtp lo envía. Los instalamos:

root@OpenWrt:~# opkg install msmtp mutt

Y configuramos msmtp:

root@OpenWrt:~# cat /etc/msmtprc
account default
host smtp.gmail.com
port 587
auth on
user mi.usuario@gmail.com
password mipassword
auto_from off
from mi.usuario@gmail.com
tls on
tls_starttls on
tls_certcheck off
logfile
syslog LOG_MAIL

Una pruebecita:

root@OpenWrt:~# echo -e "Subject: Correo de prueba\r\n\r\nEsto es un email de prueba" | sendmail destinatario@gmail.com

Ahora configuramos mutt:

root@OpenWrt:~# cat .muttrc
set sendmail="/usr/bin/msmtp"
set from="mi.usuario@gmail.com"
set realname="2Tazasdelinux"

La prueba, enviando /mnt/snapshot/lastsnap.jpg como adjunto:

root@OpenWrt:~# echo "Hola" > mensaje.txt
root@OpenWrt:~# mutt -s "Test mail" destinatario@gmail.com -a /mnt/snapshot/lastsnap.jpg < mensaje.txt

3. Juntando lo anterior.

Voy a definir un script que hará el envío de correos ante los eventos de motion. El script se disparará con 3 posibles eventos:

  • on_event_start: guarda información en el log, crea el fichero /tmp/motion.txt que hará de testigo y envia un correo de deteccion de movimiento.
  • on_picture_save:  guarda información en log y almacena el nombre del fichero con la captura en /tmp/motion.txt, siempre que dicho fichero exista.
  • on_event_end:  guarda información en el log, si existe /tmp/motion.txt coge todas las imágenes, las comprime con el comando zip y envia un correo con el fichero comprimido conteniendo todas las capturas. Finalmente, borra /tmp/motion.txt. No olvidar hacer un "opkg install zip". La idea está sacada de aquí.

Modificamos /etc/motion.conf para que tenga este contenido:

on_event_start /root/controlador.sh start "%H:%M:%S-%Y/%m/%d"
on_event_end /root/controlador.sh end "%H:%M:%S-%Y/%m/%d"
on_picture_save /root/controlador.sh picture "%H:%M:%S-%Y/%m/%d" "%f"

Y este es el script controlador.sh (no olvidar hacerlo ejecutable con "chmod +x /root/controlador.sh"):

!/bin/ash

#Parametro 1: start, picture, end
#Parametro 2: fecha
#Parametro 3: nombre fichero (opcional)

#Obtenemos fecha y hora por si queremos poner algun filtro sobre ella y solo avisar en determinados
#momentos
time=$(date +%s)
anio=$(date +%Y @$time)
mes=$(date +%m @$time)
dia=$(date +%d @$time)
hora=$(date +%H @$time)
minuto=$(date +%M @$time)
diasemana=$(date +%u @$time) #El 1 es lunes

email=0
if [ $diasemana -ge 6 -o $hora -le 7 -o $hora -ge 17 ]  # sabado/domingo o cualquier dia antes de las 8:00 o despues de las 17:00
then
   email=1
fi

case $1 in

   "start")
    echo "Detectado inicio de movimiento $2" >> /mnt/snapshot/log.txt
     test $email -eq 1 && echo -e "Subject: Evento camara\r\n\r\nDetectado inicio de movimiento $2" | sendmail destinatario@gmail.com
        touch /tmp/motion.txt
        ;;
   "picture")
    echo "Guardando imagen $2 : $3" >> /mnt/snapshot/log.txt
        test -e /tmp/motion.txt && echo $3 >> /tmp/motion.txt
    ;;
   "end")
    echo "Detectado fin de movimiento $2" >> /mnt/snapshot/log.txt
        ficheros=$(cat /tmp/motion.txt | tr '\n' ' ')
        rm /tmp/motion.txt
        echo "Historia de capturas $ficheros" >> /mnt/snapshot/log.txt
        zip -9 /mnt/escena.zip $ficheros

        echo "Detectado fin de movimiento $2" > /mnt/mensaje.txt
        test $email -eq 1 && mutt -s "Evento camara" destinatario@gmail.com -a /mnt/escena.zip < /mnt/mensaje.txt
        rm /mnt/escena.zip
    ;;
esac
#Borra fichero "sent" creado por sendmail si existe, para liberar espacio
rm -rf /root/sent

Como se puede ver, filtro las capturas para que solo avisen mediante correos los fines de semana y los días de diario entre las 17:00 y las 7:59. El resto del tiempo, no. Que cada cual adapte esto a sus circunstancias.

4. Arranque automático de motion.

Ante cualquier reinicio del router nos interesa que motion se ejecute automáticamente en el arranque. Lo mejor es ponerlo como un initscript.

root@OpenWrt:~# cat /etc/init.d/motion
#!/bin/sh /etc/rc.common

START=99
start() {
    motion -c /etc/motion.conf
}

stop() {
    killall motion
}

Lo hacemos ejecutable:

root@OpenWrt:~# chmod 755 /etc/init.d/motion

Y lo ponemos para que se ejecute en el arranque:

root@OpenWrt:~# cd /etc/rc.d
root@OpenWrt:~# ln -s ../init.d/motion S99motion

También podremos pararlo y arrancarlo a voluntad con:

root@OpenWrt:~# /etc/init.d/motion stop
root@OpenWrt:~# /etc/init.d/motion start

5. Rotación de ficheros.

Los ficheros de imágenes se acumulan en el directorio /mnt/snapshot. Lo lógico es borrar los mas antiguos con una tarea en el cron del Linux:

root@OpenWrt:~# cat /root/limpieza.sh
#!/bin/ash
find /mnt/snapshot/ -name '*.jpg' -mtime +30 -exec rm {} \;

Este script anterior (no olvidar hacerlo ejecutable) borra los ficheros jpg con mas de 30 días de antigüedad. Lo añadimos al crontab:

root@OpenWrt:~# crontab -e
00 17 * * * /root/limpieza.sh
00 16 * * * /etc/init.d/sysntpd restart

Cada día a las 17:00 hacemos limpia. Nótese que a las 16:00 reiniciamos también el demonio sysntpd para sincronizar de nuevo el reloj de nuestro Linux. El fichero donde se guarda esto en OpenWrt es /etc/crontabs/root.

6. Mejoras.

Algunas mejoras que no he implementado, pero pueden ser interesantes en el futuro:

  • Grabar vídeos en lugar de capturas de fotos. Esto se hace jugando con el parámetro output_normal de motion.conf.
  • Conectarse a Internet con un dongle 3g, aqui en español, en lugar de red cableada.
  • Conectarse a Internet con conexión wifi, en lugar de red cableada.
  • Guardar las imágenes en un servidor ftp remoto.

7. Referencias.

Para montar este tinglado he tirado de muchas referencias por todo Internet, aquí van las mas útiles que no he incluido a lo largo de estas tres entradas:

Bueno, pues me ha gustado esto del OpenWrt. Ya tengo otro proyectito en mente en usarlo para solucionar un problemón de las pizarras digitales. Si me funciona, lo contaré aquí.

------------Fin de impresión------------

Addenda 13-mayo-2015: bueno, pues esto funciona como un reloj del glorioso ejército soviético y tengo vigilada una estancia con aviso de correos sin mayor problema, pero hoy me he encontrado un contratiempo. En /mnt/snapshot/ tenía mas de 100.000 ficheros .jpg, de tal manera que se hacía totalmente inmanejable el directorio. He reescrito el script controlador.sh para que guarde cada día de captura en un directorio distinto dentro /mnt/snapshot, de manera que luego sea más sencillo buscar un día concreto y analizar las capturas. Queda así la cosa:

root@OpenWrt:~# cat controlador.sh 
#!/bin/ash

#Parametro 1: start, picture, end
#Parametro 2: fecha
#Parametro 3: nombre fichero (opcional)

#Obtenemos fecha y hora por si queremos poner algun filtro sobre ella y solo avisar en determinados
#momentos
time=$(date +%s)
anio=$(date +%Y @$time)
mes=$(date +%m @$time)
dia=$(date +%d @$time)
hora=$(date +%H @$time)
minuto=$(date +%M @$time)
diasemana=$(date +%u @$time) #El 1 es lunes
destino="/mnt/snapshot/$anio-$mes-$dia"

email=0
if [ $diasemana -ge 6 -o $hora -le 7 -o $hora -ge 17 ]  # sabado/domingo o cualquier dia antes de las 8:00 o despues de las 17:00
then
   email=1
fi

test -d $destino || mkdir -p $destino

case $1 in

   "start")
 echo "Detectado inicio de movimiento $2" >> /mnt/snapshot/log.txt
  test $email -eq 1 && echo -e "Subject: Evento camara\r\n\r\nDetectado inicio de movimiento $2" | sendmail alfonso.pastor@gmail.com
        touch /tmp/motion.txt
        ;;
   "picture")
        fichero=$(basename $3)
 echo "Guardando imagen $2 : $destino/$fichero" >> /mnt/snapshot/log.txt
        test -e /tmp/motion.txt && echo "$destino/$fichero" >> /tmp/motion.txt
        #Movemos la imagen al directorio correspondiente a la fecha de hoy.
        mv "$3" "$destino/$fichero"
 ;;
   "end") 
 echo "Detectado fin de movimiento $2" >> /mnt/snapshot/log.txt
        ficheros=$(cat /tmp/motion.txt | tr '\n' ' ')
        rm /tmp/motion.txt
        echo "Historia de capturas $ficheros" >> /mnt/snapshot/log.txt
        zip -9 /mnt/escena.zip $ficheros

        echo "Detectado fin de movimiento $2" > /mnt/mensaje.txt
        test $email -eq 1 && mutt -s "Evento camara" alfonso.pastor@gmail.com -a /mnt/escena.zip < /mnt/mensaje.txt
        rm /mnt/escena.zip
 ;;
esac
#Borra fichero "sent" creado por sendmail si existe, para liberar espacio
rm -rf /root/sent
rm -rf /sent

Ahora no tendremos problema de directorios saturados.

Addenda 29-marzo-2016: Aunque en general todo va bien, con el tiempo he ido descubriendo que no está de más hacer ciertos reinicios dentro del dispositivo OpenWrt usando el servicio cron. Eso ayuda a que todo sea mas estable y se pueda recuperar de posibles errores/cuelgues. Sería así:

root@OpenWrt:~# cat /etc/crontabs/root 
#A las 4 de la tarde reinicia demonio ntp, para forzar un sincronizado de la hora.
00 16 * * * /etc/init.d/sysntpd restart
#A las 00 de cada hora reinicia el motion, por si se ha quedado colgado.
00 *  * * * /etc/init.d/motion restart
#A las 23:55 cada dia se reinicia el dispositivo
55 23 * * * /sbin/reboot
El servicio cron de OpenWrt debe estar funcionando y activo, he aquí una pequeña guía del mismo.

Esta vez si que es:

------------Fin de impreX·!#!€@------------

Addenda 22-mayo-2016: Pues no, esto no acaba. Mas cosas metidas en este post. Y esta vez no me despido.

lunes, 9 de marzo de 2015

Montemos una webcam IP barata (II)

En el anterior post instalamos OpenWrt en nuestro router ADSL Huawei desahuciado. Vamos a ver en esta segunda parte como instalar todo el sistema de manejo de la webcam y grabado de las imágenes.

1. Conectando la webcam

El firmware Barrier Breaker no trae drivers USB ni de la cámara, así que lo primero es instalarlos:

root@OpenWrt:~# opkg update
root@OpenWrt:~# opkg install usbutils kmod-usb2 kmod-usb-core kmod-usb-ohci kmod-usb-uhci kmod-video-uvc

El driver que instalamos para nuestra cámara es kmod-video-uvc, que es el usado por un buen número de webcams en Linux. Para otras cámaras habría que encontrar el driver que funciona, por ejemplo para la EyeToy de la PS2 sería kmod-video-gspca-ov51.

Puede que la postinstalación nos de errores al intentar cargar los drives en memoria. No importa, tras el reinicio cargarán bien.

root@OpenWrt:~# reboot

Conectamos la cámara a un puerto usb y hacemos:

root@OpenWrt:~# lsusb
Bus 001 Device 003: ID 0c45:62f1 Microdia
Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 001 Device 002: ID 0424:2502 Standard Microsystems Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Ahí esta: 0c45:62f1 Microdia. Veamos si ha cargado el módulo:

root@OpenWrt:~# lsmod | grep uvc
input_core             24617  6 uvcvideo
usbcore               115555  6 uvcvideo
uvcvideo               61219  0
videobuf2_core         24202  1 uvcvideo
videobuf2_vmalloc       2881  1 uvcvideo
videodev               89620  3 uvcvideo

Perfecto, ¿existirá el dispositivo de vídeo?:

root@OpenWrt:~# ls /dev/video0
/dev/video0

Genial. Vamos a hacer una fotico, sonríe please:

root@OpenWrt:~# opkg update; opkg install fswebcam
root@OpenWrt:~# fswebcam --scale "320x240" "snapshot-1.jpg"

Bueno, pues en "snapshot-1.jpg" tenemos la captura tomada. Como nuestro router no tiene entorno gráfico no podemos verla, pero podemos sacarla de allí con:

root@OpenWrt:~# scp snapshot-1.jpg usuario@mipc:/home/usuario/ruta/a/mi/escritorio

Sustituir usuario, mipc y ruta según sea tu caso. Se copiará al escritorio de nuestro PC de trabajo y podremos ver alli que tal la captura.

2. Almacenando las imágenes.

Las imágenes que capturemos no podemos guardarlas en la memoria flash del router, que solamente tiene 16Mb de capacidad. Hay varias alternativas:

-Una unidad de almacenamiento conectada a un puerto USB

-Almacenamiento remoto. Se me ocurren tres opciones:

2.1. Carpeta compartida por Samba/CIFS.

Tomado de aquí:

root@OpenWrt:~# opkg update; opkg install kmod-fs-cifs samba36-client

Suponiendo que la unidad compartida se accede con \\ip-servidor-samba\recurso, hariamos:

root@OpenWrt:~# mount -t cifs //ip-servidor-samba/recurso /mnt -o user=usuario,password=contrasena,file_mode=0777,dir_mode=0777,nounix,noserverino

Y ya tenemos en /mnt montado el recurso compartido. Si queremos un automontaje en el arranque del sistema:

root@OpenWrt:~# cat /etc/rc.local
# Put your custom commands here that should be executed once
# the system init finished. By default this file does nothing.

sleep 30 # Esperamos un rato a que haya red...
mount -t cifs //ip-servidor-samba/recurso /mnt -o user=usuario,password=contrasena,file_mode=0777,dir_mode=0777,nounix,noserverino

exit 0

Reiniciando veremos que se monta automáticamente la carpeta compartida sobre la ruta /mnt.  En general funciona muy bien, pero por desgracia tuve que abandonarla porque el software que uso para hacer las capturas de la webcam (motion) necesita crear enlaces (symbolic link) y CIFS no soporta tal funcionalidad.

2.2. Montaje de directorio remoto por NFS.

Contado aquí. No lo llegué a probar.

2.3. Montaje de directorio remoto por sshfs.

Aunque un poco mas complicado que los anteriores, es el elegido por ser sencillo de configurar en el servidor de ficheros y permitir la creación de enlaces.

El cliente/servidor ssh que viene por defecto con OpenWrt es drobpear, pero es muy limitado para lo que queremos hacer ya que no permite fácilmente conexiones mediante relaciones de confianza, ni automatización del fichero knownhosts.

root@OpenWrt:~# /usr/bin/ssh -?
WARNING: Ignoring unknown argument '-?'
Dropbear SSH client v2014.63 https://matt.ucc.asn.au/dropbear/dropbear.html

AVISO: bajo ningún concepto desinstalar dropbear, aunque no usemos su cliente ssh, el servidor ssh es el que nos permite conectarnos al router. Si lo desinstalas puedes quedarlo aislado y tener que entrar en modo rescate y tener que cargar el firmware de nuevo.

En lugar de usar dropbear usaremos el cliente openssh, instalándolo:

root@OpenWrt:~# opkg install openssh-client sshfs openssh-keygen
root@OpenWrt:~# /usr/bin/ssh -h
unknown option -- h
usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]

Prueba de montaje en carpeta:

root@OpenWrt:~# sshfs openwrt@servidor-ficheros:/home/openwrt /mnt

Previamente debemos haber creado el usuario openwrt y su home en el PC que será nuestro servidor de ficheros, donde guardaremos las fotos de la webcam.

El montaje por ssh nos pregunta la contraseña y las típicas preguntas sobre el servidor nuevo y knownhosts, si queremos evitar esto último (útil para automatizar el montaje) pondremos estos parámetros:

root@OpenWrt:~# sshfs -o ssh_command="ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no" openwrt@servidor-ficheros:/home/openwrt /mnt

Para evitar la pregunta de la clave y establecer relación de confianza al montar el directorio remoto por ssh sigo parte de este ejemplo:

root@OpenWrt:~# ssh-keygen
root@OpenWrt:~# cd /root/.ssh/
root@OpenWrt:~# scp id_rsa.pub root@servidor-ficheros:/tmp

Y metemos la clave pública en el home de openwrt en .ssh/authorized_keys:

root@servidor-ficheros:~# cat /tmp/id_rsa.pub >> .ssh/authorized_keys

Probamos que entramos sin contraseña y sin preguntitas pesadas:

root@OpenWrt:~# ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no openwrt@servidor-ficheros

Y ahora probamos el montaje:

root@OpenWrt:~# sshfs -o ssh_command="ssh -i /root/.ssh/id_rsa -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no" openwrt@servidor-ficheros:/home/openwrt /mnt
root@OpenWrt:~# ls /mnt

Por último, lo metemos en rc.local para que lo monte en el arranque:

root@OpenWrt:~# cat /etc/rc.local
# Put your custom commands here that should be executed once
# the system init finished. By default this file does nothing.

sleep 40
sshfs -o ssh_command="ssh -i /root/.ssh/id_rsa -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no" openwrt@servidor-ficheros:/home/openwrt /mnt

exit 0
Actualización 25/1/2016: después de varios meses funcionando bastante bien, había un pequeño problema recurrente. Cuando el servidor remoto donde se guardan los archivos se caía, la conexión se perdía y se empezaban a guardar las capturas en el /mnt/ local del router que como disco local se llenaba pronto y colapsaba el OpenWrt. Adicionalmente, /mnt se negaba a montarse de nuevo al no estar vacío. Con este retoque en /etc/rc.local lo limpio antes de volver a montarlo y así me evito el problema:
# Put your custom commands here that should be executed once
# the system init finished. By default this file does nothing.
sleep 40
umount /mnt
rm -rf /mnt/*
sshfs -o ssh_command="ssh -i /root/.ssh/id_rsa -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no" -o nonempty openwrt@servidor-ficheros:/home/openwrt /mnt

exit 0

3. Capturando el vídeo.

La primera opción que probé es mjpg_streamer:

root@OpenWrt:~# opkg update; opkg install mjpg-streamer
root@OpenWrt:~# mjpg_streamer -i "input_uvc.so -d /dev/video0" -o "output_http.so -w /www/webcam -port 8080"

Si abrimos un navegador con http://ip-router:8080 veremos el flujo de vídeo de la cámara. Por desgracia, si queremos grabar:

root@OpenWrt:~# mkdir /mnt/snapshot
root@OpenWrt:~# root@OpenWrt:~# mjpg_streamer -i "input_uvc.so -d /dev/video0" -o "output_http.so -w /www/webcam -port 8080" -o "output_file.so -f /mnt/snapshot/ -d 5000"

Vemos que da error ya que el módulo output_file.so no está en el paquete mjpg_streamer de OpenWrt.

El siguiente candidato es motion, que además luego me doy cuenta de que tiene muchas más funcionalidades que mjpg_streamer.

root@OpenWrt:~# opkg update;  opkg install motion
root@OpenWrt:~# mkdir -p /mnt/snapshot

Configuramos el programa:

root@OpenWrt:~# nano /etc/motion/motion.conf
#Solo toco estos parámetros, el resto los quedo igual de momento:
daemon on
width 352
height 288
framerate 5
snapshot_interval 10
target_dir /mnt/snapshot
snapshot_filename %Y-%m-%d-%H:%M:%S-snapshot-%v
picture_filename %d%m%Y-%H%M%S-%q
stream_port 8081
stream_maxrate 5
stream_localhost off

Lo ejecutamos con:

root@OpenWrt:~# motion -c /etc/motion.conf

Si abrimos un navegador con http://ip-router:8081 veremos el flujo de vídeo de la cámara. Simultáneamente se graban 5 frames por segundo en /mnt/snapshot cuando la cámara detecte movimiento. Si no hay movimiento se grabará una imagen cada 10 segundos (llamada *snapshot.jpg). Esto tiene mejor pinta. Si queremos matar el proceso, que se está ejecutando como demonio, haremos:

root@OpenWrt:~# killall motion

Con esto acaba la segunda parte. Para la tercera queda:

  • Ejecución de motion como servicio.
  • Afinar la detección de movimientos.
  • Detectar eventos y conectarlos al envío de correos electrónicos de aviso.
  • Y varias sugerencias mas para ampliar esto.

Hasta la próxima......

lunes, 2 de marzo de 2015

Montemos una webcam IP barata (I)


Nota 22/febrero/2018:Este post tiene muchas continuaciones, tantas que necesito un índice que pondré aquí por ser el principio de todo:


A continuación el mensaje original:


El reto que tengo ahora es montar un sistema de videovigilancia con una cámara IP con elementos baratos o de desecho. El objetivo es:

  • Un sistema de vigilancia conectado a internet por wifi, cable o incluso 3G.
  • Que tenga posibilidad de grabar imágenes en un almacenamiento remoto (por ejemplo, un servidor).
  • Que tenga detección de movimientos.
  • Que tenga la posibilidad de mandar avisos por correo electrónico (o SMS, twitter, ...).

El hardware del que dispongo es mínimo:

  • Un router ADSL que permita instalar OpenWrt una distribución de Linux embebido para routers. En mi caso es un Huawei HG556a ofrecido por el ADSL de Vodafone que me dieron porque estaba muerto de risa en un trastero. Elegí este router por la facilidad con la que se instala OpenWrt en él (era mi primera vez con OpenWrt) y porque tiene muchas posibilidades de conectividad: 2 puertos USB, interfaz ethernet e interfaz wifi.

 

  • Una webcam USB barata de DealExtreme. En mi caso salió gratis ya que cuando me la enviaron no funcionaba (mostraba la imagen negra), asi que reclamé y me enviaron otra gratis. Al poco tiempo un usuario de DX me dijo que probase a desmontar la carcasa, lo hice y empezó a funcionar: se había desencajado por dentro y la lente del objetivo no apuntaba hacía donde debía.

Vamos a ver los pasos a seguir:

1. Instalación de OpenWrt.

Lo primero es confirmar que el router es compatible con OpenWrt, confirmándolo en la página correspondiente http://wiki.openwrt.org/toh/huawei/hg556a.

Lo segundo es saber que versión del router tenemos para descargar la imagen adecuada. En este caso se hace mirando el número de serie, en mi caso es: N/S: 30692100.... Cotejando este número en el enlace exterior veo que el modelo exacto del router es:

HG55VDFA VER.C
HG556BVDFA - HG556(B)VDFA
Wifi: Atheros AR9223
OpenWrt file (≥CC) Ver. B.

Mirando en http://wiki.openwrt.org/toh/huawei/hg556a, vemos que hay 2 opciones para instalar:

  • La versión estable, llamada Barrier Breaker.
  • La versión de testing correspondiente al la versión B de nuestro router, del snapshot diario.

Nos decantamos por la versión estable, que descargamos del enlace anterior. Para instalar seguimos estos pasos:

    • Poner en nuestro PC una direccion IP fija, la 192.168.1.35 y conectarlo por cable ethernet al router.
    • Desconectar el router de la corriente.
    • Pulsar el botón RESTART del router. Mantenerlo apretado.
    • Conectar el router a la corriente.
    • Esperar 12 segundos o más.
    • Soltar el botón del router.
    • En el navegador de nuestro PC, ir a http://192.168.1.1. Esa es la página para cargar un nuevo firmware.
    • Seleccionar el archivo .bin bajado anteriormente.
    • Seleccionar "Update Software" para iniciar el proceso de cambio del firmware.
    • Esperar a que reinicie.
    • Hacer
                # telnet 192.168.1.1

     para entrar en el router. La primera tarea es cambiar la contraseña de root con:

                root@OpenWrt:/# passwd
    • Despues de esto, podremos entrar con
                # ssh root@191.168.1.1

Con esto ya tenemos un Linux funcional con un conjunto de paquetes básicos para trabajar. Existe un interface web de configuración llamado Luci, al que podremos acceder desde el navegador en http://192.168.1.1 o la IP que posteriormente pongamos a nuestro router.

En otros router el proceso de instalación es bastante mas costoso, necesitando abrir el router y conectar un adaptador USB-TTL-serie  al puerto serie de la placa  y dar ordenes por terminal desde el programa minicom, o incluso usando soldaduras de pines y cables para acceder al puerto serie o JTAG  y escribir esotéricas ordenes de actualización del CFE (la BIOS del router) para permitir cambiar el bootloader e instalar nuevos firmwares. Por dicho motivo este router concreto es ideal para iniciarse en OpenWrt: simplemente actualizar el firmware por su página de configuración web.

Conector serie del router:

Conector JTAG del router:

2. Configuración inicial.

Bueno, ya estamos en Linux y nos sentimos como en casa, vamos a ir configurando lo básico del sistema. Podríamos usar la interfaz web Luci para la mayoría de las opciones, pero vamos a hacerlo por línea de comandos para saber mejor que pasos damos, así que hacemos un ssh a root@192.168.1.1. Lo primero es actualizar los repositorios de paquetes (esto hay que hacerlo cada vez que reiniciemos el router, ya que se guardan en memoria RAM).

Vemos los repositorios:

root@OpenWrt:/# cat /etc/opkg.conf

dest root /
dest ram /tmp
lists_dir ext /var/opkg-lists
option overlay_root /overlay
src/gz barrier_breaker_base http://downloads.openwrt.org/barrier_breaker/14.07/brcm63xx/generic/packages/base
src/gz barrier_breaker_luci http://downloads.openwrt.org/barrier_breaker/14.07/brcm63xx/generic/packages/luci
src/gz barrier_breaker_packages http://downloads.openwrt.org/barrier_breaker/14.07/brcm63xx/generic/packages/packages
src/gz barrier_breaker_routing http://downloads.openwrt.org/barrier_breaker/14.07/brcm63xx/generic/packages/routing
src/gz barrier_breaker_telephony http://downloads.openwrt.org/barrier_breaker/14.07/brcm63xx/generic/packages/telephony
src/gz barrier_breaker_management http://downloads.openwrt.org/barrier_breaker/14.07/brcm63xx/generic/packages/management
src/gz barrier_breaker_oldpackages http://downloads.openwrt.org/barrier_breaker/14.07/brcm63xx/generic/packages/oldpackages

Si tenemos la versión testing, deberá ser:

root@OpenWrt:/# cat /etc/opkg.conf

dest root /
dest ram /tmp
lists_dir ext /var/opkg-lists
option overlay_root /overlay
src/gz barrier_breaker_base http://downloads.openwrt.org/snapshots/trunk/brcm63xx/generic/packages/base/
src/gz barrier_breaker_luci http://downloads.openwrt.org/snapshots/trunk/brcm63xx/generic/packages/luci
src/gz barrier_breaker_packages http://downloads.openwrt.org/snapshots/trunk/brcm63xx/generic/packages/packages
src/gz barrier_breaker_routing http://downloads.openwrt.org/snapshots/trunk/brcm63xx/generic/packages/routing
src/gz barrier_breaker_telephony http://downloads.openwrt.org/snapshots/trunk/brcm63xx/generic/packages/telephony
src/gz barrier_breaker_management http://downloads.openwrt.org/snapshots/trunk/brcm63xx/generic/packages/management

Actualizamos la lista de paquetes e instalamos nano para tener un editor de textos posterior a la Constitución en vigor.

root@OpenWrt:/# opkg update
root@OpenWrt:/# opkg install nano

Ahora configuramos una IP fija en la tarjeta eth0, para integrarlo en nuestra red:

root@OpenWrt:/etc/config# nano /etc/config/network 

    config interface 'loopback'
        option ifname 'lo'
        option proto 'static'
        option ipaddr '127.0.0.1'
        option netmask '255.0.0.0'

    config globals 'globals'
        option ula_prefix 'fd58:01a4:b44f::/48'

    config interface 'lan'
        option ifname 'eth0.1'
        option force_link '1'
        option type 'bridge'
        option proto 'static'
        option netmask '255.255.255.0'
        option ip6assign '60'
        option ipaddr 'IP-FIJA-DEL-ROUTER'
        option gateway 'GATEWAY-DE-LA-RED'
        option broadcast 'BROADCAST-DE-LA-RED'
        option dns 'IP-DNS-DE-LA-RED 8.8.8.8'

    config switch
        option name 'eth0'
        option reset '1'
        option enable_vlan '1'

    config switch_vlan
        option device 'eth0'
        option vlan '1'
        option ports '0 1 2 3 4 5t'

Configuramos las DNS en resolv.conf:

root@OpenWrt:/# rm /etc/resolv.conf
root@OpenWrt:/# echo "search midominio
> nameserver IP-DNS-DE-LA-RED
> nameserver 8.8.8.8" > /etc/resolv.conf
root@OpenWrt:/# cat /etc/resolv.conf
search minominio
nameserver IP-DNS-DE-LA-RED
nameserver 8.8.8.8
root@OpenWrt:/#

Definimos bien la TimeZone para poner la hora correcta con el cliente ntp instalado:

root@OpenWrt:~# nano /etc/config/system 

config system
    option hostname 'OpenWrt'
    option zonename 'Europe/Madrid'
    option timezone 'CET-1CEST,M3.5.0,M10.5.0/3'

config timeserver 'ntp'
    list server '0.openwrt.pool.ntp.org'
    list server '1.openwrt.pool.ntp.org'
    list server '2.openwrt.pool.ntp.org'
    list server '3.openwrt.pool.ntp.org'
    option enabled '1'
    option enable_server '0'
............
............
............

Tras esto, reiniciamos el router con reboot y cuando esté de nuevo operativo entramos por ssh root@IP-DEL-ROUTER.

3. Por si metemos la pata: actualizaciones posteriores del firmware.

Una vez instalado OpenWrt, la recuperación/actualización del firmware si rompemos algo es ya mucho mas sencilla.

Primero editamos /etc/sysupgrade.conf y añadimos los ficheros que queremos preservar en caso de instalar de nuevo el firmware, para evitar tener que configurar todo posteriormente otra vez:

root@OpenWrt:~# nano /etc/sysupgrade.conf
## This file contains files and directories that should
## be preserved during an upgrade.

# /etc/example.conf
# /etc/openvpn/

/etc/sysupgrade.conf
/etc/resolv.conf
/etc/sysctl.conf
/etc/rc.local
/etc/profile
/etc/passwd
/etc/firewall.user
/etc/dropbear/dropbear_rsa_host_key
/etc/dropbear/dropbear_dss_host_key
/etc/config/wireless
/etc/config/system
/etc/config/network
/etc/config/firewall
/etc/config/dropbear
/etc/config/dhcp

A continuación descargamos el firmware y lanzamos su instalación:

root@OpenWrt:~# cd /tmp
root@OpenWrt:/tmp# wget https://downloads.openwrt.org/barrier_breaker/14.07/brcm63xx/generic/openwrt-HW556-squashfs-cfe.bin
root@OpenWrt:~# sysupgrade -v /tmp/openwrt-HW556-squashfs-cfe.bin

Tras un rato el router reinicia y ya tenemos el sistema como nuevo pero conservando los ficheros indicados.

NOTA: si sucede algo catastrófico y el router no arranca bien y no responde a nuestros ping, siempre se puede recurrir al modo de rescate (parecido al modo rescate de un Linux normal, con un montón de funciones capadas pero al que podemos acceder por la IP 192.168.1.1 y dar algunas órdenes)

  • Poner en nuestro PC una direccion IP fija, la 192.168.1.35 y conectarlo por cable ethernet al router.
  • Desconectar el router de la corriente.
  • Conectarlo de nuevo y pulsar el botón RESTART compulsivamente mientras se enciende.
  • El sistema arranca en modo rescate, lo sabemos porque el led de encendido parpadea furiosamente.
  • Poner el .bin de la imagen en el directorio /tmp de nuestro PC
  • Hacer
        root@(none):~# ssh root@192.168.1.1

  • Traernos el .bin de la imagen a /tmp
       root@(none):~# cd /tmp
       root@(none):/tmp# scp root@192.168.1.35:/tmp/openwrt-HW556-squashfs-cfe.bin .

  • Reinstalar:
       root@(none):/tmp# sysupgrade -v openwrt-HW556-squashfs-cfe.bin

con estos pasos he podido retomar el control de la situación cuando la he liado parda mientras enredaba probando cosas.

Bueno, pues en este punto tenemos un sistema OpenWrt actualizado, integrado dentro de nuestra red local y listo para conectar nuestra cámara USB y empezar a capturar imágenes, cosa que haremos en la siguiente entrada.....

lunes, 23 de febrero de 2015

Configuración de las Xorg en Wheezy para Fujitsu P300

Continuamos con los incombustibles Fujitsu Scenic P300. Estos equipos tienen una tarjeta gráfica VGA integrada en la placa que se identifica así:
# lspci -nn | grep -i vga
00:02.0 VGA compatible controller [0300]: Intel Corporation 82845G/GL[Brookdale-G]/GE Chipset Integrated Graphics Device [8086:2562] (rev 01)
Esta tarjeta desde tiempos de Debian Lenny nos ha dado problemas con Debian, de buena gana hubiera comprado otras tarjetas gráficas y las hubiera pinchado en todos los P300 para ahorrarme dolores de cabeza, pero era imposible: la placa base de estos equipos no tiene ranura VGA. Que bien, ¿eh?. Así que no nos ha quedado otra que coexistir con ellas y hacerlas funcionar a base de pruebas.
Tras la migración a Wheezy y como ya es tradición, la configuración por defecto empezó a fallar: lentitud del escritorio (las ventanas se mueven a cámara lenta), a veces se quedaba la pantalla en negro al cerrar sesión, bloqueos en el gdm3 o una vez dentro de la sesión al trabajar con el navegador o el LibreOffice....

Primero vemos que versión del driver xorg-video-intel trae nuestra imagen:

# dpkg -l | grep xorg-video-intel
ii  xserver-xorg-video-intel              2:2.21.15-2~bpo70+1
Mmm,.. de backports (bpo). Demasiado moderna, así que desinstalo el paquete a mano y pongo el paquete de los repositorios regulares de Wheezy:
# dpkg -l | grep xorg-video-intel
ii  xserver-xorg-video-intel              2:2.19.0-6
Después de esto, la fluidez del escritorio mejora: las ventanas se abren, cierran y mueven con alegría. Pero la inestabilidad sigue y a veces hay cuelgues. Cuando sucede eso el teclado y los botones del ratón dejan de responder, pero puedo entrar por ssh y ver que el proceso xorg está cerca del 90% todo el tiempo. Además el syslog muestra estos mensajes coincidiendo con el instante del cuelgue:
Jan 30 14:04:01 A12-O01 kernel: [ 1631.224019] [drm:i915_hangcheck_elapsed] *ERROR* Hangcheck timer elapsed... GPU hung
Jan 30 14:04:01 A12-O01 kernel: [ 1631.224030] [drm] capturing error event; look for more information in /debug/dri/0/i915_error_stateaaaaa
Como ya somos perros viejos con esta tarjeta y su driver, generamos un xorg.conf a mano tal como explicamos aquí, sin meternos en los líos de los Modelines, por supuesto. Limpiamos el xorg.conf generado de los drivers de relleno, dejando solo el driver intel  y empezamos a jugar con sus opciones de configuración. Tras varios retoques junto con la experiencia de mis compañeros Paco y Noemí se solucionan todos los problemas de estabilidad con esta configuración:
# cat /etc/X11/xorg.conf
...
...
...
Section "Device"

    Identifier  "Card0"
    Driver      "intel"
    BusID       "PCI:0:2:0"
    Option      "AccelMethod"               "SNA"
    Option      "XAANoOffscreenPixmaps"     "True"
    Option      "DRI"                       "on"
    Option      "Shadow"                    "True"

EndSection
...
...
...
En resumen: aceleración SNA, XAANoOffscreenPixmaps a True, DRI a On y Shadow a True. Con esto tenemos de nuevo nuestro Debian en los P300 a prueba de bombas. Para los thinclients de las aulas la configuración se meterá en el lts.conf, quedando:
# cat /opt/ltsp/i386/etc/lts.conf
...
...
X_OPTION_01 = "\"AccelMethod\" \"sna\""
X_OPTION_02 = "\"XAANoOffscreenPixmaps\" \"True\""
X_OPTION_03 = "\"DRI\" \"on\""
X_OPTION_04 = "\"Shadow\" \"True\""
...
...
Regenerando después la imagen NBD del thinclient con ltsp-update-image.
Bueno, pues ya tenemos funcionando el instalache hasta que Debian Jessie aparezca en nuestras vidas....

lunes, 16 de febrero de 2015

¡Desperta, ferro!

En los IES de Extremadura tenemos en funcionamiento muchísimos viejos Pentium IV de hace 13 años como puestos Linux. El sistema en funcionamiento se basa en LTSP: el ordenador del profesor hace de servidor de aula y los equipos de los alumnos son clientes LTSP suyos. El sistema nos permite ejecutar las últimas versiones de software en equipos con 256Mb-512Mb de RAM y sin necesidad de disco duro. Un estupendo ahorro para todos los contribuyentes.

Una parte muy importante del sistema es que los equipos de los alumnos puedan ser encendidos mediante WakeOnLan desde el equipo del profesor, ya que están dentro de cajas cerradas. El servidor grita "¡Desperta, ferro!" cual soldado almogávar, y los thinclients se encienden y cargan el sistema operativo por la tarjeta de red mediante el protocolo PXE.

En mi caso tengo como thinclients los incombustibles Fujitsu P300, tan duros e inmunes a la obsolescencia programada que parecen hechos en la RDA.  Estos PC siempre habían funcionado sin problema hasta la versión 2.6.32 del kernel de Linux. A partir de ahí, el WakeOnLan dejó de funcionar. Como solución temporal nos quedamos un tiempo con la versión 2.6.32, pero es una medida intolerable ya que el kernel de Linux sigue evolucionando y no podemos quedarnos atrás.

El problema venía del driver de la tarjeta ethernet de los equipos. El lspci nos dice:

02:01.0 Ethernet controller [0200]: ADMtek NC100 Network Everywhere Fast Ethernet 10/100 [1317:0985] (rev 11)
    Subsystem: Fujitsu Technology Solutions Scenic N300 ADMtek AN983 10/100 Mbps PCI Adapter [1734:100c]
    Flags: bus master, fast Back2Back, medium devsel, latency 64, IRQ 23
    I/O ports at 3000 [size=256]
    Memory at d0100000 (32-bit, non-prefetchable) [size=1K]
    [virtual] Expansion ROM at 40000000 [disabled] [size=128K]
    Capabilities: [c0] Power Management version 2
    Kernel driver in use: tulip

El driver tulip es el que maneja esta tarjeta. Una cosa curiosa que pasaba en el kernel 2.6.32 y anteriores es que dicho driver no daba soporte WOL. Es decir, si hacías:

ethtool -s eth0 wol g

Te daba un error diciendo que el driver no soportaba eso. Lo gracioso es que el WOL estaba activo por defecto y funcionaba, aun cuando el driver no lo manejase. ¿Qué pasó en las versiones posteriores a la 2.6.32?: pues que alguien metió soporte para WOL dentro del driver. Ahora:

ethtool -s eth0 wol g

si funcionaba y no daba error, pero en la práctica los equipos desoían la petición de encenderse. En ninguna de las versiones posteriores de kernels (series 2.x y 3.x) se solucionó esto. Abrí una petición en sourceforge al desarrollador del driver y no me contestó. El driver sigue casi inmutable kernel tras kernel, con el WOL sin funcionar para nuestras tarjetas. Descargando el código fuente del kernel el correspondiente driver está en drivers/net/ethernet/dec/tulip/ y dentro de allí el fichero crítico es tulip_core.c. Ese es el lugar donde se ha implementado el soporte WOL.

Hacer una depuración del driver y ver que fallaba es algo que escapa a mis conocimientos y tiempo disponible, así que se me ocurrió otra cosa: ¿por qué no quitaba del driver todo lo añadido, recompilaba y cruzaba los dedos?. Para ello comparé el tulip_core.c de la versión 2.6.32 con el de la versión 3.2.0-4, que era el kernel con el que trabajaba, usando la utilidad de comparación de ficheros meld.

La verdad es que había bastantes diferencias, pero comentando partes, compilando, probando, obteniendo diversos alarmantes avisos de kernel panic y otros (segmentation fault,  apocalypse now, Venezuela-ETA-Podemos, Winter is coming, etc....), y volviendo a empezar varias veces di con el tulip_core.c correcto. Había conseguido quitar el soporte WOL, con lo que:

ethtool -s eth0 wol g

volvía a dar error, pero el WOL funcionaba de nuevo :-). Increíble: para que funcione una feature hay que eliminar la implementación de dicha feature. Me encanta la informática.

El tulip_core.c modificado que me funcionó sería (marco en negrita las partes que considero que tienen código WOL, algunas son las comentadas):

# cat tulip_core.c
/* tulip_core.c: A DEC 21x4x-family ethernet driver for Linux.

 Copyright 2000,2001  The Linux Kernel Team
 Written/copyright 1994-2001 by Donald Becker.

 This software may be used and distributed according to the terms
 of the GNU General Public License, incorporated herein by reference.

 Please submit bugs to http://bugzilla.kernel.org/ .
*/

#define pr_fmt(fmt) "tulip: " fmt

#define DRV_NAME "tulip"
#ifdef CONFIG_TULIP_NAPI
#define DRV_VERSION    "1.1.15-NAPI" /* Keep at least for test */
#else
#define DRV_VERSION "1.1.15"
#endif
#define DRV_RELDATE "Feb 27, 2007"


#include 
#include 
#include 
#include "tulip.h"
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#ifdef CONFIG_SPARC
#include 
#endif

static char version[] =
 "Linux Tulip driver version " DRV_VERSION " (" DRV_RELDATE ")\n";

/* A few user-configurable values. */

/* Maximum events (Rx packets, etc.) to handle at each interrupt. */
static unsigned int max_interrupt_work = 25;

#define MAX_UNITS 8
/* Used to pass the full-duplex flag, etc. */
static int full_duplex[MAX_UNITS];
static int options[MAX_UNITS];
static int mtu[MAX_UNITS];   /* Jumbo MTU for interfaces. */

/*  The possible media types that can be set in options[] are: */
const char * const medianame[32] = {
 "10baseT", "10base2", "AUI", "100baseTx",
 "10baseT-FDX", "100baseTx-FDX", "100baseT4", "100baseFx",
 "100baseFx-FDX", "MII 10baseT", "MII 10baseT-FDX", "MII",
 "10baseT(forced)", "MII 100baseTx", "MII 100baseTx-FDX", "MII 100baseT4",
 "MII 100baseFx-HDX", "MII 100baseFx-FDX", "Home-PNA 1Mbps", "Invalid-19",
 "","","","", "","","","",  "","","","Transceiver reset",
};

/* Set the copy breakpoint for the copy-only-tiny-buffer Rx structure. */
#if defined(__alpha__) || defined(__arm__) || defined(__hppa__) || \
 defined(CONFIG_SPARC) || defined(__ia64__) || \
 defined(__sh__) || defined(__mips__)
static int rx_copybreak = 1518;
#else
static int rx_copybreak = 100;
#endif

/*
  Set the bus performance register.
 Typical: Set 16 longword cache alignment, no burst limit.
 Cache alignment bits 15:14      Burst length 13:8
  0000 No alignment  0x00000000 unlimited  0800 8 longwords
  4000 8  longwords  0100 1 longword  1000 16 longwords
  8000 16 longwords  0200 2 longwords 2000 32 longwords
  C000 32  longwords  0400 4 longwords
 Warning: many older 486 systems are broken and require setting 0x00A04800
    8 longword cache alignment, 8 longword burst.
 ToDo: Non-Intel setting could be better.
*/

#if defined(__alpha__) || defined(__ia64__)
static int csr0 = 0x01A00000 | 0xE000;
#elif defined(__i386__) || defined(__powerpc__) || defined(__x86_64__)
static int csr0 = 0x01A00000 | 0x8000;
#elif defined(CONFIG_SPARC) || defined(__hppa__)
/* The UltraSparc PCI controllers will disconnect at every 64-byte
 * crossing anyways so it makes no sense to tell Tulip to burst
 * any more than that.
 */
static int csr0 = 0x01A00000 | 0x9000;
#elif defined(__arm__) || defined(__sh__)
static int csr0 = 0x01A00000 | 0x4800;
#elif defined(__mips__)
static int csr0 = 0x00200000 | 0x4000;
#else
#warning Processor architecture undefined!
static int csr0 = 0x00A00000 | 0x4800;
#endif

/* Operational parameters that usually are not changed. */
/* Time in jiffies before concluding the transmitter is hung. */
#define TX_TIMEOUT  (4*HZ)


MODULE_AUTHOR("The Linux Kernel Team");
MODULE_DESCRIPTION("Digital 21*4* Tulip ethernet driver-Remarked");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
module_param(tulip_debug, int, 0);
module_param(max_interrupt_work, int, 0);
module_param(rx_copybreak, int, 0);
module_param(csr0, int, 0);
module_param_array(options, int, NULL, 0);
module_param_array(full_duplex, int, NULL, 0);

#ifdef TULIP_DEBUG
int tulip_debug = TULIP_DEBUG;
#else
int tulip_debug = 1;
#endif

static void tulip_timer(unsigned long data)
{
 struct net_device *dev = (struct net_device *)data;
 struct tulip_private *tp = netdev_priv(dev);

 if (netif_running(dev))
  schedule_work(&tp->media_work);
}

/*
 * This table use during operation for capabilities and media timer.
 *
 * It is indexed via the values in 'enum chips'
 */

struct tulip_chip_table tulip_tbl[] = {
  { }, /* placeholder for array, slot unused currently */
  { }, /* placeholder for array, slot unused currently */

  /* DC21140 */
  { "Digital DS21140 Tulip", 128, 0x0001ebef,
 HAS_MII | HAS_MEDIA_TABLE | CSR12_IN_SROM | HAS_PCI_MWI, tulip_timer,
 tulip_media_task },

  /* DC21142, DC21143 */
  { "Digital DS21142/43 Tulip", 128, 0x0801fbff,
 HAS_MII | HAS_MEDIA_TABLE | ALWAYS_CHECK_MII | HAS_ACPI | HAS_NWAY
 | HAS_INTR_MITIGATION | HAS_PCI_MWI, tulip_timer, t21142_media_task },

  /* LC82C168 */
  { "Lite-On 82c168 PNIC", 256, 0x0001fbef,
 HAS_MII | HAS_PNICNWAY, pnic_timer, },

  /* MX98713 */
  { "Macronix 98713 PMAC", 128, 0x0001ebef,
 HAS_MII | HAS_MEDIA_TABLE | CSR12_IN_SROM, mxic_timer, },

  /* MX98715 */
  { "Macronix 98715 PMAC", 256, 0x0001ebef,
 HAS_MEDIA_TABLE, mxic_timer, },

  /* MX98725 */
  { "Macronix 98725 PMAC", 256, 0x0001ebef,
 HAS_MEDIA_TABLE, mxic_timer, },

  /* AX88140 */
  { "ASIX AX88140", 128, 0x0001fbff,
 HAS_MII | HAS_MEDIA_TABLE | CSR12_IN_SROM | MC_HASH_ONLY
 | IS_ASIX, tulip_timer, tulip_media_task },

  /* PNIC2 */
  { "Lite-On PNIC-II", 256, 0x0801fbff,
 HAS_MII | HAS_NWAY | HAS_8023X | HAS_PCI_MWI, pnic2_timer, },

  /* COMET */
  { "ADMtek Comet", 256, 0x0001abef,
 HAS_MII | MC_HASH_ONLY | COMET_MAC_ADDR, comet_timer, },

  /* COMPEX9881 */
  { "Compex 9881 PMAC", 128, 0x0001ebef,
 HAS_MII | HAS_MEDIA_TABLE | CSR12_IN_SROM, mxic_timer, },

  /* I21145 */
  { "Intel DS21145 Tulip", 128, 0x0801fbff,
 HAS_MII | HAS_MEDIA_TABLE | ALWAYS_CHECK_MII | HAS_ACPI
 | HAS_NWAY | HAS_PCI_MWI, tulip_timer, tulip_media_task },

  /* DM910X */
#ifdef CONFIG_TULIP_DM910X
  { "Davicom DM9102/DM9102A", 128, 0x0001ebef,
 HAS_MII | HAS_MEDIA_TABLE | CSR12_IN_SROM | HAS_ACPI,
 tulip_timer, tulip_media_task },
#else
  { NULL },
#endif

  /* RS7112 */
  { "Conexant LANfinity", 256, 0x0001ebef,
 HAS_MII | HAS_ACPI, tulip_timer, tulip_media_task },

};


static DEFINE_PCI_DEVICE_TABLE(tulip_pci_tbl) = {
 { 0x1011, 0x0009, PCI_ANY_ID, PCI_ANY_ID, 0, 0, DC21140 },
 { 0x1011, 0x0019, PCI_ANY_ID, PCI_ANY_ID, 0, 0, DC21143 },
 { 0x11AD, 0x0002, PCI_ANY_ID, PCI_ANY_ID, 0, 0, LC82C168 },
 { 0x10d9, 0x0512, PCI_ANY_ID, PCI_ANY_ID, 0, 0, MX98713 },
 { 0x10d9, 0x0531, PCI_ANY_ID, PCI_ANY_ID, 0, 0, MX98715 },
/* { 0x10d9, 0x0531, PCI_ANY_ID, PCI_ANY_ID, 0, 0, MX98725 },*/
 { 0x125B, 0x1400, PCI_ANY_ID, PCI_ANY_ID, 0, 0, AX88140 },
 { 0x11AD, 0xc115, PCI_ANY_ID, PCI_ANY_ID, 0, 0, PNIC2 },
 { 0x1317, 0x0981, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
 { 0x1317, 0x0985, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
 { 0x1317, 0x1985, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
 { 0x1317, 0x9511, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
 { 0x13D1, 0xAB02, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
 { 0x13D1, 0xAB03, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
 { 0x13D1, 0xAB08, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
 { 0x104A, 0x0981, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
 { 0x104A, 0x2774, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
 { 0x1259, 0xa120, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
 { 0x11F6, 0x9881, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMPEX9881 },
 { 0x8086, 0x0039, PCI_ANY_ID, PCI_ANY_ID, 0, 0, I21145 },
#ifdef CONFIG_TULIP_DM910X
 { 0x1282, 0x9100, PCI_ANY_ID, PCI_ANY_ID, 0, 0, DM910X },
 { 0x1282, 0x9102, PCI_ANY_ID, PCI_ANY_ID, 0, 0, DM910X },
#endif
 { 0x1113, 0x1216, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
 { 0x1113, 0x1217, PCI_ANY_ID, PCI_ANY_ID, 0, 0, MX98715 },
 { 0x1113, 0x9511, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
 { 0x1186, 0x1541, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
 { 0x1186, 0x1561, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
 { 0x1186, 0x1591, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
 { 0x14f1, 0x1803, PCI_ANY_ID, PCI_ANY_ID, 0, 0, CONEXANT },
 { 0x1626, 0x8410, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
 { 0x1737, 0xAB09, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
 { 0x1737, 0xAB08, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
 { 0x17B3, 0xAB08, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
 { 0x10b7, 0x9300, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET }, /* 3Com 3CSOHO100B-TX */
 { 0x14ea, 0xab08, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET }, /* Planex FNW-3602-TX */
 { 0x1414, 0x0001, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET }, /* Microsoft MN-120 */
 { 0x1414, 0x0002, PCI_ANY_ID, PCI_ANY_ID, 0, 0, COMET },
 { } /* terminate list */
};
MODULE_DEVICE_TABLE(pci, tulip_pci_tbl);


/* A full-duplex map for media types. */
const char tulip_media_cap[32] =
{0,0,0,16,  3,19,16,24,  27,4,7,5, 0,20,23,20,  28,31,0,0, };

static void tulip_tx_timeout(struct net_device *dev);
static void tulip_init_ring(struct net_device *dev);
static void tulip_free_ring(struct net_device *dev);
static netdev_tx_t tulip_start_xmit(struct sk_buff *skb,
       struct net_device *dev);
static int tulip_open(struct net_device *dev);
static int tulip_close(struct net_device *dev);
static void tulip_up(struct net_device *dev);
static void tulip_down(struct net_device *dev);
static struct net_device_stats *tulip_get_stats(struct net_device *dev);
static int private_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
static void set_rx_mode(struct net_device *dev);
//static void tulip_set_wolopts(struct pci_dev *pdev, u32 wolopts);
#ifdef CONFIG_NET_POLL_CONTROLLER
static void poll_tulip(struct net_device *dev);
#endif

static void tulip_set_power_state (struct tulip_private *tp,
       int sleep, int snooze)
{
 if (tp->flags & HAS_ACPI) {
  u32 tmp, newtmp;
  pci_read_config_dword (tp->pdev, CFDD, &tmp);
  newtmp = tmp & ~(CFDD_Sleep | CFDD_Snooze);
  if (sleep)
   newtmp |= CFDD_Sleep;
  else if (snooze)
   newtmp |= CFDD_Snooze;
  if (tmp != newtmp)
   pci_write_config_dword (tp->pdev, CFDD, newtmp);
 }

}


static void tulip_up(struct net_device *dev)
{
 struct tulip_private *tp = netdev_priv(dev);
 void __iomem *ioaddr = tp->base_addr;
 int next_tick = 3*HZ;
 u32 reg;
 int i;

#ifdef CONFIG_TULIP_NAPI
 napi_enable(&tp->napi);
#endif

 /* Wake the chip from sleep/snooze mode. */
 tulip_set_power_state (tp, 0, 0);

 /* Disable all WOL events */
/* pci_enable_wake(tp->pdev, PCI_D3hot, 0);
 pci_enable_wake(tp->pdev, PCI_D3cold, 0);
 tulip_set_wolopts(tp->pdev, 0);*/

 /* On some chip revs we must set the MII/SYM port before the reset!? */
 if (tp->mii_cnt  ||  (tp->mtable  &&  tp->mtable->has_mii))
  iowrite32(0x00040000, ioaddr + CSR6);

 /* Reset the chip, holding bit 0 set at least 50 PCI cycles. */
 iowrite32(0x00000001, ioaddr + CSR0);
 pci_read_config_dword(tp->pdev, PCI_COMMAND, ®);  /* flush write */
 udelay(100);

 /* Deassert reset.
    Wait the specified 50 PCI cycles after a reset by initializing
    Tx and Rx queues and the address filter list. */
 iowrite32(tp->csr0, ioaddr + CSR0);
 pci_read_config_dword(tp->pdev, PCI_COMMAND, ®);  /* flush write */
 udelay(100);

 if (tulip_debug > 1)
  netdev_dbg(dev, "tulip_up(), irq==%d\n", tp->pdev->irq);

 iowrite32(tp->rx_ring_dma, ioaddr + CSR3);
 iowrite32(tp->tx_ring_dma, ioaddr + CSR4);
 tp->cur_rx = tp->cur_tx = 0;
 tp->dirty_rx = tp->dirty_tx = 0;

 if (tp->flags & MC_HASH_ONLY) {
  u32 addr_low = get_unaligned_le32(dev->dev_addr);
  u32 addr_high = get_unaligned_le16(dev->dev_addr + 4);
  if (tp->chip_id == AX88140) {
   iowrite32(0, ioaddr + CSR13);
   iowrite32(addr_low,  ioaddr + CSR14);
   iowrite32(1, ioaddr + CSR13);
   iowrite32(addr_high, ioaddr + CSR14);
  } else if (tp->flags & COMET_MAC_ADDR) {
   iowrite32(addr_low,  ioaddr + 0xA4);
   iowrite32(addr_high, ioaddr + 0xA8);
//Nuevo:   
   iowrite32(0, ioaddr + 0xAC);
   iowrite32(0, ioaddr + 0xB0);
/*   iowrite32(0, ioaddr + CSR27);
   iowrite32(0, ioaddr + CSR28);*/
  }
 } else {
  /* This is set_rx_mode(), but without starting the transmitter. */
  u16 *eaddrs = (u16 *)dev->dev_addr;
  u16 *setup_frm = &tp->setup_frame[15*6];
  dma_addr_t mapping;

  /* 21140 bug: you must add the broadcast address. */
  memset(tp->setup_frame, 0xff, sizeof(tp->setup_frame));
  /* Fill the final entry of the table with our physical address. */
  *setup_frm++ = eaddrs[0]; *setup_frm++ = eaddrs[0];
  *setup_frm++ = eaddrs[1]; *setup_frm++ = eaddrs[1];
  *setup_frm++ = eaddrs[2]; *setup_frm++ = eaddrs[2];

  mapping = pci_map_single(tp->pdev, tp->setup_frame,
      sizeof(tp->setup_frame),
      PCI_DMA_TODEVICE);
  tp->tx_buffers[tp->cur_tx].skb = NULL;
  tp->tx_buffers[tp->cur_tx].mapping = mapping;

  /* Put the setup frame on the Tx list. */
  tp->tx_ring[tp->cur_tx].length = cpu_to_le32(0x08000000 | 192);
  tp->tx_ring[tp->cur_tx].buffer1 = cpu_to_le32(mapping);
  tp->tx_ring[tp->cur_tx].status = cpu_to_le32(DescOwned);

  tp->cur_tx++;
 }

 tp->saved_if_port = dev->if_port;
 if (dev->if_port == 0)
  dev->if_port = tp->default_port;

 /* Allow selecting a default media. */
 i = 0;
 if (tp->mtable == NULL)
  goto media_picked;
 if (dev->if_port) {
  int looking_for = tulip_media_cap[dev->if_port] & MediaIsMII ? 11 :
   (dev->if_port == 12 ? 0 : dev->if_port);
  for (i = 0; i < tp->mtable->leafcount; i++)
   if (tp->mtable->mleaf[i].media == looking_for) {
    dev_info(&dev->dev,
      "Using user-specified media %s\n",
      medianame[dev->if_port]);
    goto media_picked;
   }
 }
 if ((tp->mtable->defaultmedia & 0x0800) == 0) {
  int looking_for = tp->mtable->defaultmedia & MEDIA_MASK;
  for (i = 0; i < tp->mtable->leafcount; i++)
   if (tp->mtable->mleaf[i].media == looking_for) {
    dev_info(&dev->dev,
      "Using EEPROM-set media %s\n",
      medianame[looking_for]);
    goto media_picked;
   }
 }
 /* Start sensing first non-full-duplex media. */
 for (i = tp->mtable->leafcount - 1;
   (tulip_media_cap[tp->mtable->mleaf[i].media] & MediaAlwaysFD) && i > 0; i--)
  ;
media_picked:

 tp->csr6 = 0;
 tp->cur_index = i;
 tp->nwayset = 0;

 if (dev->if_port) {
  if (tp->chip_id == DC21143  &&
      (tulip_media_cap[dev->if_port] & MediaIsMII)) {
   /* We must reset the media CSRs when we force-select MII mode. */
   iowrite32(0x0000, ioaddr + CSR13);
   iowrite32(0x0000, ioaddr + CSR14);
   iowrite32(0x0008, ioaddr + CSR15);
  }
  tulip_select_media(dev, 1);
 } else if (tp->chip_id == DC21142) {
  if (tp->mii_cnt) {
   tulip_select_media(dev, 1);
   if (tulip_debug > 1)
    dev_info(&dev->dev,
      "Using MII transceiver %d, status %04x\n",
      tp->phys[0],
      tulip_mdio_read(dev, tp->phys[0], 1));
   iowrite32(csr6_mask_defstate, ioaddr + CSR6);
   tp->csr6 = csr6_mask_hdcap;
   dev->if_port = 11;
   iowrite32(0x0000, ioaddr + CSR13);
   iowrite32(0x0000, ioaddr + CSR14);
  } else
   t21142_start_nway(dev);
 } else if (tp->chip_id == PNIC2) {
         /* for initial startup advertise 10/100 Full and Half */
         tp->sym_advertise = 0x01E0;
                /* enable autonegotiate end interrupt */
         iowrite32(ioread32(ioaddr+CSR5)| 0x00008010, ioaddr + CSR5);
         iowrite32(ioread32(ioaddr+CSR7)| 0x00008010, ioaddr + CSR7);
  pnic2_start_nway(dev);
 } else if (tp->chip_id == LC82C168  &&  ! tp->medialock) {
  if (tp->mii_cnt) {
   dev->if_port = 11;
   tp->csr6 = 0x814C0000 | (tp->full_duplex ? 0x0200 : 0);
   iowrite32(0x0001, ioaddr + CSR15);
  } else if (ioread32(ioaddr + CSR5) & TPLnkPass)
   pnic_do_nway(dev);
  else {
   /* Start with 10mbps to do autonegotiation. */
   iowrite32(0x32, ioaddr + CSR12);
   tp->csr6 = 0x00420000;
   iowrite32(0x0001B078, ioaddr + 0xB8);
   iowrite32(0x0201B078, ioaddr + 0xB8);
   next_tick = 1*HZ;
  }
 } else if ((tp->chip_id == MX98713 || tp->chip_id == COMPEX9881) &&
     ! tp->medialock) {
  dev->if_port = 0;
  tp->csr6 = 0x01880000 | (tp->full_duplex ? 0x0200 : 0);
  iowrite32(0x0f370000 | ioread16(ioaddr + 0x80), ioaddr + 0x80);
 } else if (tp->chip_id == MX98715 || tp->chip_id == MX98725) {
  /* Provided by BOLO, Macronix - 12/10/1998. */
  dev->if_port = 0;
  tp->csr6 = 0x01a80200;
  iowrite32(0x0f370000 | ioread16(ioaddr + 0x80), ioaddr + 0x80);
  iowrite32(0x11000 | ioread16(ioaddr + 0xa0), ioaddr + 0xa0);
 } else if (tp->chip_id == COMET || tp->chip_id == CONEXANT) {
  /* Enable automatic Tx underrun recovery. */
  iowrite32(ioread32(ioaddr + 0x88) | 1, ioaddr + 0x88);
  dev->if_port = tp->mii_cnt ? 11 : 0;
  tp->csr6 = 0x00040000;
 } else if (tp->chip_id == AX88140) {
  tp->csr6 = tp->mii_cnt ? 0x00040100 : 0x00000100;
 } else
  tulip_select_media(dev, 1);

 /* Start the chip's Tx to process setup frame. */
 tulip_stop_rxtx(tp);
 barrier();
 udelay(5);
 iowrite32(tp->csr6 | TxOn, ioaddr + CSR6);

 /* Enable interrupts by setting the interrupt mask. */
 iowrite32(tulip_tbl[tp->chip_id].valid_intrs, ioaddr + CSR5);
 iowrite32(tulip_tbl[tp->chip_id].valid_intrs, ioaddr + CSR7);
 tulip_start_rxtx(tp);
 iowrite32(0, ioaddr + CSR2);  /* Rx poll demand */

 if (tulip_debug > 2) {
  netdev_dbg(dev, "Done tulip_up(), CSR0 %08x, CSR5 %08x CSR6 %08x\n",
      ioread32(ioaddr + CSR0),
      ioread32(ioaddr + CSR5),
      ioread32(ioaddr + CSR6));
 }

 /* Set the timer to switch to check for link beat and perhaps switch
    to an alternate media type. */
 tp->timer.expires = RUN_AT(next_tick);
 add_timer(&tp->timer);
#ifdef CONFIG_TULIP_NAPI
 init_timer(&tp->oom_timer);
        tp->oom_timer.data = (unsigned long)dev;
        tp->oom_timer.function = oom_timer;
#endif
}

static int
tulip_open(struct net_device *dev)
{
 struct tulip_private *tp = netdev_priv(dev);
 int retval;

 tulip_init_ring (dev);

 retval = request_irq(tp->pdev->irq, tulip_interrupt, IRQF_SHARED,
        dev->name, dev);
 if (retval)
  goto free_ring;

 tulip_up (dev);

 netif_start_queue (dev);

 return 0;

free_ring:
 tulip_free_ring (dev);
 return retval;
}


static void tulip_tx_timeout(struct net_device *dev)
{
 struct tulip_private *tp = netdev_priv(dev);
 void __iomem *ioaddr = tp->base_addr;
 unsigned long flags;

 spin_lock_irqsave (&tp->lock, flags);

 if (tulip_media_cap[dev->if_port] & MediaIsMII) {
  /* Do nothing -- the media monitor should handle this. */
  if (tulip_debug > 1)
   dev_warn(&dev->dev,
     "Transmit timeout using MII device\n");
 } else if (tp->chip_id == DC21140 || tp->chip_id == DC21142 ||
     tp->chip_id == MX98713 || tp->chip_id == COMPEX9881 ||
     tp->chip_id == DM910X) {
  dev_warn(&dev->dev,
    "21140 transmit timed out, status %08x, SIA %08x %08x %08x %08x, resetting...\n",
    ioread32(ioaddr + CSR5), ioread32(ioaddr + CSR12),
    ioread32(ioaddr + CSR13), ioread32(ioaddr + CSR14),
    ioread32(ioaddr + CSR15));
  tp->timeout_recovery = 1;
  schedule_work(&tp->media_work);
  goto out_unlock;
 } else if (tp->chip_id == PNIC2) {
  dev_warn(&dev->dev,
    "PNIC2 transmit timed out, status %08x, CSR6/7 %08x / %08x CSR12 %08x, resetting...\n",
    (int)ioread32(ioaddr + CSR5),
    (int)ioread32(ioaddr + CSR6),
    (int)ioread32(ioaddr + CSR7),
    (int)ioread32(ioaddr + CSR12));
 } else {
  dev_warn(&dev->dev,
    "Transmit timed out, status %08x, CSR12 %08x, resetting...\n",
    ioread32(ioaddr + CSR5), ioread32(ioaddr + CSR12));
  dev->if_port = 0;
 }

#if defined(way_too_many_messages)
 if (tulip_debug > 3) {
  int i;
  for (i = 0; i < RX_RING_SIZE; i++) {
   u8 *buf = (u8 *)(tp->rx_ring[i].buffer1);
   int j;
   printk(KERN_DEBUG
          "%2d: %08x %08x %08x %08x  %02x %02x %02x\n",
          i,
          (unsigned int)tp->rx_ring[i].status,
          (unsigned int)tp->rx_ring[i].length,
          (unsigned int)tp->rx_ring[i].buffer1,
          (unsigned int)tp->rx_ring[i].buffer2,
          buf[0], buf[1], buf[2]);
   for (j = 0; buf[j] != 0xee && j < 1600; j++)
    if (j < 100)
     pr_cont(" %02x", buf[j]);
   pr_cont(" j=%d\n", j);
  }
  printk(KERN_DEBUG "  Rx ring %p: ", tp->rx_ring);
  for (i = 0; i < RX_RING_SIZE; i++)
   pr_cont(" %08x", (unsigned int)tp->rx_ring[i].status);
  printk(KERN_DEBUG "  Tx ring %p: ", tp->tx_ring);
  for (i = 0; i < TX_RING_SIZE; i++)
   pr_cont(" %08x", (unsigned int)tp->tx_ring[i].status);
  pr_cont("\n");
 }
#endif

 tulip_tx_timeout_complete(tp, ioaddr);

out_unlock:
 spin_unlock_irqrestore (&tp->lock, flags);
 dev->trans_start = jiffies; /* prevent tx timeout */
 netif_wake_queue (dev);
}


/* Initialize the Rx and Tx rings, along with various 'dev' bits. */
static void tulip_init_ring(struct net_device *dev)
{
 struct tulip_private *tp = netdev_priv(dev);
 int i;

 tp->susp_rx = 0;
 tp->ttimer = 0;
 tp->nir = 0;

 for (i = 0; i < RX_RING_SIZE; i++) {
  tp->rx_ring[i].status = 0x00000000;
  tp->rx_ring[i].length = cpu_to_le32(PKT_BUF_SZ);
  tp->rx_ring[i].buffer2 = cpu_to_le32(tp->rx_ring_dma + sizeof(struct tulip_rx_desc) * (i + 1));
  tp->rx_buffers[i].skb = NULL;
  tp->rx_buffers[i].mapping = 0;
 }
 /* Mark the last entry as wrapping the ring. */
 tp->rx_ring[i-1].length = cpu_to_le32(PKT_BUF_SZ | DESC_RING_WRAP);
 tp->rx_ring[i-1].buffer2 = cpu_to_le32(tp->rx_ring_dma);

 for (i = 0; i < RX_RING_SIZE; i++) {
  dma_addr_t mapping;

  /* Note the receive buffer must be longword aligned.
     netdev_alloc_skb() provides 16 byte alignment.  But do *not*
     use skb_reserve() to align the IP header! */
  struct sk_buff *skb = netdev_alloc_skb(dev, PKT_BUF_SZ);
  tp->rx_buffers[i].skb = skb;
  if (skb == NULL)
   break;
  mapping = pci_map_single(tp->pdev, skb->data,
      PKT_BUF_SZ, PCI_DMA_FROMDEVICE);
  tp->rx_buffers[i].mapping = mapping;
  tp->rx_ring[i].status = cpu_to_le32(DescOwned); /* Owned by Tulip chip */
  tp->rx_ring[i].buffer1 = cpu_to_le32(mapping);
 }
 tp->dirty_rx = (unsigned int)(i - RX_RING_SIZE);

 /* The Tx buffer descriptor is filled in as needed, but we
    do need to clear the ownership bit. */
 for (i = 0; i < TX_RING_SIZE; i++) {
  tp->tx_buffers[i].skb = NULL;
  tp->tx_buffers[i].mapping = 0;
  tp->tx_ring[i].status = 0x00000000;
  tp->tx_ring[i].buffer2 = cpu_to_le32(tp->tx_ring_dma + sizeof(struct tulip_tx_desc) * (i + 1));
 }
 tp->tx_ring[i-1].buffer2 = cpu_to_le32(tp->tx_ring_dma);
}

static netdev_tx_t
tulip_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
 struct tulip_private *tp = netdev_priv(dev);
 int entry;
 u32 flag;
 dma_addr_t mapping;
 unsigned long flags;

 spin_lock_irqsave(&tp->lock, flags);

 /* Calculate the next Tx descriptor entry. */
 entry = tp->cur_tx % TX_RING_SIZE;

 tp->tx_buffers[entry].skb = skb;
 mapping = pci_map_single(tp->pdev, skb->data,
     skb->len, PCI_DMA_TODEVICE);
 tp->tx_buffers[entry].mapping = mapping;
 tp->tx_ring[entry].buffer1 = cpu_to_le32(mapping);

 if (tp->cur_tx - tp->dirty_tx < TX_RING_SIZE/2) {/* Typical path */
  flag = 0x60000000; /* No interrupt */
 } else if (tp->cur_tx - tp->dirty_tx == TX_RING_SIZE/2) {
  flag = 0xe0000000; /* Tx-done intr. */
 } else if (tp->cur_tx - tp->dirty_tx < TX_RING_SIZE - 2) {
  flag = 0x60000000; /* No Tx-done intr. */
 } else {  /* Leave room for set_rx_mode() to fill entries. */
  flag = 0xe0000000; /* Tx-done intr. */
  netif_stop_queue(dev);
 }
 if (entry == TX_RING_SIZE-1)
  flag = 0xe0000000 | DESC_RING_WRAP;

 tp->tx_ring[entry].length = cpu_to_le32(skb->len | flag);
 /* if we were using Transmit Automatic Polling, we would need a
  * wmb() here. */
 tp->tx_ring[entry].status = cpu_to_le32(DescOwned);
 wmb();

 tp->cur_tx++;

 /* Trigger an immediate transmit demand. */
 iowrite32(0, tp->base_addr + CSR1);

 spin_unlock_irqrestore(&tp->lock, flags);

 return NETDEV_TX_OK;
}

static void tulip_clean_tx_ring(struct tulip_private *tp)
{
 unsigned int dirty_tx;

 for (dirty_tx = tp->dirty_tx ; tp->cur_tx - dirty_tx > 0;
  dirty_tx++) {
  int entry = dirty_tx % TX_RING_SIZE;
  int status = le32_to_cpu(tp->tx_ring[entry].status);

  if (status < 0) {
   tp->dev->stats.tx_errors++; /* It wasn't Txed */
   tp->tx_ring[entry].status = 0;
  }

  /* Check for Tx filter setup frames. */
  if (tp->tx_buffers[entry].skb == NULL) {
   /* test because dummy frames not mapped */
   if (tp->tx_buffers[entry].mapping)
    pci_unmap_single(tp->pdev,
     tp->tx_buffers[entry].mapping,
     sizeof(tp->setup_frame),
     PCI_DMA_TODEVICE);
   continue;
  }

  pci_unmap_single(tp->pdev, tp->tx_buffers[entry].mapping,
    tp->tx_buffers[entry].skb->len,
    PCI_DMA_TODEVICE);

  /* Free the original skb. */
  dev_kfree_skb_irq(tp->tx_buffers[entry].skb);
  tp->tx_buffers[entry].skb = NULL;
  tp->tx_buffers[entry].mapping = 0;
 }
}

static void tulip_down (struct net_device *dev)
{
 struct tulip_private *tp = netdev_priv(dev);
 void __iomem *ioaddr = tp->base_addr;
 unsigned long flags;

 cancel_work_sync(&tp->media_work);

#ifdef CONFIG_TULIP_NAPI
 napi_disable(&tp->napi);
#endif

 del_timer_sync (&tp->timer);
#ifdef CONFIG_TULIP_NAPI
 del_timer_sync (&tp->oom_timer);
#endif
 spin_lock_irqsave (&tp->lock, flags);

 /* Disable interrupts by clearing the interrupt mask. */
 iowrite32 (0x00000000, ioaddr + CSR7);

 /* Stop the Tx and Rx processes. */
 tulip_stop_rxtx(tp);

 /* prepare receive buffers */
 tulip_refill_rx(dev);

 /* release any unconsumed transmit buffers */
 tulip_clean_tx_ring(tp);

 if (ioread32(ioaddr + CSR6) != 0xffffffff)
  dev->stats.rx_missed_errors += ioread32(ioaddr + CSR8) & 0xffff;

 spin_unlock_irqrestore (&tp->lock, flags);

 init_timer(&tp->timer);
 tp->timer.data = (unsigned long)dev;
 tp->timer.function = tulip_tbl[tp->chip_id].media_timer;

 dev->if_port = tp->saved_if_port;

 /* Leave the driver in snooze, not sleep, mode. */
 tulip_set_power_state (tp, 0, 1);
}

static void tulip_free_ring (struct net_device *dev)
{
 struct tulip_private *tp = netdev_priv(dev);
 int i;

 /* Free all the skbuffs in the Rx queue. */
 for (i = 0; i < RX_RING_SIZE; i++) {
  struct sk_buff *skb = tp->rx_buffers[i].skb;
  dma_addr_t mapping = tp->rx_buffers[i].mapping;

  tp->rx_buffers[i].skb = NULL;
  tp->rx_buffers[i].mapping = 0;

  tp->rx_ring[i].status = 0; /* Not owned by Tulip chip. */
  tp->rx_ring[i].length = 0;
  /* An invalid address. */
  tp->rx_ring[i].buffer1 = cpu_to_le32(0xBADF00D0);
  if (skb) {
   pci_unmap_single(tp->pdev, mapping, PKT_BUF_SZ,
      PCI_DMA_FROMDEVICE);
   dev_kfree_skb (skb);
  }
 }

 for (i = 0; i < TX_RING_SIZE; i++) {
  struct sk_buff *skb = tp->tx_buffers[i].skb;

  if (skb != NULL) {
   pci_unmap_single(tp->pdev, tp->tx_buffers[i].mapping,
      skb->len, PCI_DMA_TODEVICE);
   dev_kfree_skb (skb);
  }
  tp->tx_buffers[i].skb = NULL;
  tp->tx_buffers[i].mapping = 0;
 }
}

static int tulip_close (struct net_device *dev)
{
 struct tulip_private *tp = netdev_priv(dev);
 void __iomem *ioaddr = tp->base_addr;

 netif_stop_queue (dev);

 tulip_down (dev);

 if (tulip_debug > 1)
  netdev_dbg(dev, "Shutting down ethercard, status was %02x\n",
      ioread32 (ioaddr + CSR5));

 free_irq (tp->pdev->irq, dev);

 tulip_free_ring (dev);

 return 0;
}

static struct net_device_stats *tulip_get_stats(struct net_device *dev)
{
 struct tulip_private *tp = netdev_priv(dev);
 void __iomem *ioaddr = tp->base_addr;

 if (netif_running(dev)) {
  unsigned long flags;

  spin_lock_irqsave (&tp->lock, flags);

  dev->stats.rx_missed_errors += ioread32(ioaddr + CSR8) & 0xffff;

  spin_unlock_irqrestore(&tp->lock, flags);
 }

 return &dev->stats;
}


static void tulip_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
 struct tulip_private *np = netdev_priv(dev);
 strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
 strlcpy(info->version, DRV_VERSION, sizeof(info->version));
 strlcpy(info->bus_info, pci_name(np->pdev), sizeof(info->bus_info));
}

/*
static int tulip_ethtool_set_wol(struct net_device *dev,
     struct ethtool_wolinfo *wolinfo)
{
 struct tulip_private *tp = netdev_priv(dev);

    if (wolinfo->wolopts & (~tp->wolinfo.supported))
     return -EOPNOTSUPP;

 tp->wolinfo.wolopts = wolinfo->wolopts;
 device_set_wakeup_enable(&tp->pdev->dev, tp->wolinfo.wolopts);
 return 0;
}

static void tulip_ethtool_get_wol(struct net_device *dev,
      struct ethtool_wolinfo *wolinfo)
{
 struct tulip_private *tp = netdev_priv(dev);

 wolinfo->supported = tp->wolinfo.supported;
 wolinfo->wolopts = tp->wolinfo.wolopts;
 return;
}

*/
static const struct ethtool_ops ops = {
 .get_drvinfo = tulip_get_drvinfo //,
// .set_wol     = tulip_ethtool_set_wol,
// .get_wol     = tulip_ethtool_get_wol,
};


/* Provide ioctl() calls to examine the MII xcvr state. */
static int private_ioctl (struct net_device *dev, struct ifreq *rq, int cmd)
{
 struct tulip_private *tp = netdev_priv(dev);
 void __iomem *ioaddr = tp->base_addr;
 struct mii_ioctl_data *data = if_mii(rq);
 const unsigned int phy_idx = 0;
 int phy = tp->phys[phy_idx] & 0x1f;
 unsigned int regnum = data->reg_num;

 switch (cmd) {
 case SIOCGMIIPHY:  /* Get address of MII PHY in use. */
  if (tp->mii_cnt)
   data->phy_id = phy;
  else if (tp->flags & HAS_NWAY)
   data->phy_id = 32;
  else if (tp->chip_id == COMET)
   data->phy_id = 1;
  else
   return -ENODEV;

 case SIOCGMIIREG:  /* Read MII PHY register. */
  if (data->phy_id == 32 && (tp->flags & HAS_NWAY)) {
   int csr12 = ioread32 (ioaddr + CSR12);
   int csr14 = ioread32 (ioaddr + CSR14);
   switch (regnum) {
   case 0:
                                if (((csr14<<5) & 0x1000) ||
                                        (dev->if_port == 5 && tp->nwayset))
                                        data->val_out = 0x1000;
                                else
                                        data->val_out = (tulip_media_cap[dev->if_port]&MediaIs100 ? 0x2000 : 0)
                                                | (tulip_media_cap[dev->if_port]&MediaIsFD ? 0x0100 : 0);
    break;
   case 1:
                                data->val_out =
     0x1848 +
     ((csr12&0x7000) == 0x5000 ? 0x20 : 0) +
     ((csr12&0x06) == 6 ? 0 : 4);
                                data->val_out |= 0x6048;
    break;
   case 4:
                                /* Advertised value, bogus 10baseTx-FD value from CSR6. */
                                data->val_out =
     ((ioread32(ioaddr + CSR6) >> 3) & 0x0040) +
     ((csr14 >> 1) & 0x20) + 1;
                                data->val_out |= ((csr14 >> 9) & 0x03C0);
    break;
   case 5: data->val_out = tp->lpar; break;
   default: data->val_out = 0; break;
   }
  } else {
   data->val_out = tulip_mdio_read (dev, data->phy_id & 0x1f, regnum);
  }
  return 0;

 case SIOCSMIIREG:  /* Write MII PHY register. */
  if (regnum & ~0x1f)
   return -EINVAL;
  if (data->phy_id == phy) {
   u16 value = data->val_in;
   switch (regnum) {
   case 0: /* Check for autonegotiation on or reset. */
    tp->full_duplex_lock = (value & 0x9000) ? 0 : 1;
    if (tp->full_duplex_lock)
     tp->full_duplex = (value & 0x0100) ? 1 : 0;
    break;
   case 4:
    tp->advertising[phy_idx] =
    tp->mii_advertise = data->val_in;
    break;
   }
  }
  if (data->phy_id == 32 && (tp->flags & HAS_NWAY)) {
   u16 value = data->val_in;
   if (regnum == 0) {
     if ((value & 0x1200) == 0x1200) {
       if (tp->chip_id == PNIC2) {
                                   pnic2_start_nway (dev);
                            } else {
       t21142_start_nway (dev);
                            }
     }
   } else if (regnum == 4)
    tp->sym_advertise = value;
  } else {
   tulip_mdio_write (dev, data->phy_id & 0x1f, regnum, data->val_in);
  }
  return 0;
 default:
  return -EOPNOTSUPP;
 }

 return -EOPNOTSUPP;
}


/* Set or clear the multicast filter for this adaptor.
   Note that we only use exclusion around actually queueing the
   new frame, not around filling tp->setup_frame.  This is non-deterministic
   when re-entered but still correct. */

static void build_setup_frame_hash(u16 *setup_frm, struct net_device *dev)
{
 struct tulip_private *tp = netdev_priv(dev);
 u16 hash_table[32];
 struct netdev_hw_addr *ha;
 int i;
 u16 *eaddrs;

 memset(hash_table, 0, sizeof(hash_table));
 __set_bit_le(255, hash_table);   /* Broadcast entry */
 /* This should work on big-endian machines as well. */
 netdev_for_each_mc_addr(ha, dev) {
  int index = ether_crc_le(ETH_ALEN, ha->addr) & 0x1ff;

  __set_bit_le(index, hash_table);
 }
 for (i = 0; i < 32; i++) {
  *setup_frm++ = hash_table[i];
  *setup_frm++ = hash_table[i];
 }
 setup_frm = &tp->setup_frame[13*6];

 /* Fill the final entry with our physical address. */
 eaddrs = (u16 *)dev->dev_addr;
 *setup_frm++ = eaddrs[0]; *setup_frm++ = eaddrs[0];
 *setup_frm++ = eaddrs[1]; *setup_frm++ = eaddrs[1];
 *setup_frm++ = eaddrs[2]; *setup_frm++ = eaddrs[2];
}

static void build_setup_frame_perfect(u16 *setup_frm, struct net_device *dev)
{
 struct tulip_private *tp = netdev_priv(dev);
 struct netdev_hw_addr *ha;
 u16 *eaddrs;

 /* We have <= 14 addresses so we can use the wonderful
    16 address perfect filtering of the Tulip. */
 netdev_for_each_mc_addr(ha, dev) {
  eaddrs = (u16 *) ha->addr;
  *setup_frm++ = *eaddrs; *setup_frm++ = *eaddrs++;
  *setup_frm++ = *eaddrs; *setup_frm++ = *eaddrs++;
  *setup_frm++ = *eaddrs; *setup_frm++ = *eaddrs++;
 }
 /* Fill the unused entries with the broadcast address. */
 memset(setup_frm, 0xff, (15 - netdev_mc_count(dev)) * 12);
 setup_frm = &tp->setup_frame[15*6];

 /* Fill the final entry with our physical address. */
 eaddrs = (u16 *)dev->dev_addr;
 *setup_frm++ = eaddrs[0]; *setup_frm++ = eaddrs[0];
 *setup_frm++ = eaddrs[1]; *setup_frm++ = eaddrs[1];
 *setup_frm++ = eaddrs[2]; *setup_frm++ = eaddrs[2];
}


static void set_rx_mode(struct net_device *dev)
{
 struct tulip_private *tp = netdev_priv(dev);
 void __iomem *ioaddr = tp->base_addr;
 int csr6;

 csr6 = ioread32(ioaddr + CSR6) & ~0x00D5;

 tp->csr6 &= ~0x00D5;
 if (dev->flags & IFF_PROMISC) {   /* Set promiscuous. */
  tp->csr6 |= AcceptAllMulticast | AcceptAllPhys;
  csr6 |= AcceptAllMulticast | AcceptAllPhys;
 } else if ((netdev_mc_count(dev) > 1000) ||
     (dev->flags & IFF_ALLMULTI)) {
  /* Too many to filter well -- accept all multicasts. */
  tp->csr6 |= AcceptAllMulticast;
  csr6 |= AcceptAllMulticast;
 } else if (tp->flags & MC_HASH_ONLY) {
  /* Some work-alikes have only a 64-entry hash filter table. */
  /* Should verify correctness on big-endian/__powerpc__ */
  struct netdev_hw_addr *ha;
  if (netdev_mc_count(dev) > 64) {
   /* Arbitrary non-effective limit. */
   tp->csr6 |= AcceptAllMulticast;
   csr6 |= AcceptAllMulticast;
  } else {
   u32 mc_filter[2] = {0, 0};   /* Multicast hash filter */
   int filterbit;
   netdev_for_each_mc_addr(ha, dev) {
    if (tp->flags & COMET_MAC_ADDR)
     filterbit = ether_crc_le(ETH_ALEN,
         ha->addr);
    else
     filterbit = ether_crc(ETH_ALEN,
             ha->addr) >> 26;
    filterbit &= 0x3f;
    mc_filter[filterbit >> 5] |= 1 << (filterbit & 31);
    if (tulip_debug > 2)
     dev_info(&dev->dev,
       "Added filter for %pM  %08x bit %d\n",
       ha->addr,
       ether_crc(ETH_ALEN, ha->addr),
       filterbit);
   }
   if (mc_filter[0] == tp->mc_filter[0]  &&
    mc_filter[1] == tp->mc_filter[1])
    ;    /* No change. */
   else if (tp->flags & IS_ASIX) {
    iowrite32(2, ioaddr + CSR13);
    iowrite32(mc_filter[0], ioaddr + CSR14);
    iowrite32(3, ioaddr + CSR13);
    iowrite32(mc_filter[1], ioaddr + CSR14);
   } else if (tp->flags & COMET_MAC_ADDR) {
//Nuevo
                iowrite32(mc_filter[0], ioaddr + 0xAC);
    iowrite32(mc_filter[1], ioaddr + 0xB0);
    /*iowrite32(mc_filter[0], ioaddr + CSR27);
    iowrite32(mc_filter[1], ioaddr + CSR28);*/
   }
   tp->mc_filter[0] = mc_filter[0];
   tp->mc_filter[1] = mc_filter[1];
  }
 } else {
  unsigned long flags;
  u32 tx_flags = 0x08000000 | 192;

  /* Note that only the low-address shortword of setup_frame is valid!
     The values are doubled for big-endian architectures. */
  if (netdev_mc_count(dev) > 14) {
   /* Must use a multicast hash table. */
   build_setup_frame_hash(tp->setup_frame, dev);
   tx_flags = 0x08400000 | 192;
  } else {
   build_setup_frame_perfect(tp->setup_frame, dev);
  }

  spin_lock_irqsave(&tp->lock, flags);

  if (tp->cur_tx - tp->dirty_tx > TX_RING_SIZE - 2) {
   /* Same setup recently queued, we need not add it. */
  } else {
   unsigned int entry;
   int dummy = -1;

   /* Now add this frame to the Tx list. */

   entry = tp->cur_tx++ % TX_RING_SIZE;

   if (entry != 0) {
    /* Avoid a chip errata by prefixing a dummy entry. */
    tp->tx_buffers[entry].skb = NULL;
    tp->tx_buffers[entry].mapping = 0;
    tp->tx_ring[entry].length =
     (entry == TX_RING_SIZE-1) ? cpu_to_le32(DESC_RING_WRAP) : 0;
    tp->tx_ring[entry].buffer1 = 0;
    /* Must set DescOwned later to avoid race with chip */
    dummy = entry;
    entry = tp->cur_tx++ % TX_RING_SIZE;

   }

   tp->tx_buffers[entry].skb = NULL;
   tp->tx_buffers[entry].mapping =
    pci_map_single(tp->pdev, tp->setup_frame,
            sizeof(tp->setup_frame),
            PCI_DMA_TODEVICE);
   /* Put the setup frame on the Tx list. */
   if (entry == TX_RING_SIZE-1)
    tx_flags |= DESC_RING_WRAP;  /* Wrap ring. */
   tp->tx_ring[entry].length = cpu_to_le32(tx_flags);
   tp->tx_ring[entry].buffer1 =
    cpu_to_le32(tp->tx_buffers[entry].mapping);
   tp->tx_ring[entry].status = cpu_to_le32(DescOwned);
   if (dummy >= 0)
    tp->tx_ring[dummy].status = cpu_to_le32(DescOwned);
   if (tp->cur_tx - tp->dirty_tx >= TX_RING_SIZE - 2)
    netif_stop_queue(dev);

   /* Trigger an immediate transmit demand. */
   iowrite32(0, ioaddr + CSR1);
  }

  spin_unlock_irqrestore(&tp->lock, flags);
 }

 iowrite32(csr6, ioaddr + CSR6);
}

#ifdef CONFIG_TULIP_MWI
static void tulip_mwi_config(struct pci_dev *pdev, struct net_device *dev)
{
 struct tulip_private *tp = netdev_priv(dev);
 u8 cache;
 u16 pci_command;
 u32 csr0;

 if (tulip_debug > 3)
  netdev_dbg(dev, "tulip_mwi_config()\n");

 tp->csr0 = csr0 = 0;

 /* if we have any cache line size at all, we can do MRM and MWI */
 csr0 |= MRM | MWI;

 /* Enable MWI in the standard PCI command bit.
  * Check for the case where MWI is desired but not available
  */
 pci_try_set_mwi(pdev);

 /* read result from hardware (in case bit refused to enable) */
 pci_read_config_word(pdev, PCI_COMMAND, &pci_command);
 if ((csr0 & MWI) && (!(pci_command & PCI_COMMAND_INVALIDATE)))
  csr0 &= ~MWI;

 /* if cache line size hardwired to zero, no MWI */
 pci_read_config_byte(pdev, PCI_CACHE_LINE_SIZE, &cache);
 if ((csr0 & MWI) && (cache == 0)) {
  csr0 &= ~MWI;
  pci_clear_mwi(pdev);
 }

 /* assign per-cacheline-size cache alignment and
  * burst length values
  */
 switch (cache) {
 case 8:
  csr0 |= MRL | (1 << CALShift) | (16 << BurstLenShift);
  break;
 case 16:
  csr0 |= MRL | (2 << CALShift) | (16 << BurstLenShift);
  break;
 case 32:
  csr0 |= MRL | (3 << CALShift) | (32 << BurstLenShift);
  break;
 default:
  cache = 0;
  break;
 }

 /* if we have a good cache line size, we by now have a good
  * csr0, so save it and exit
  */
 if (cache)
  goto out;

 /* we don't have a good csr0 or cache line size, disable MWI */
 if (csr0 & MWI) {
  pci_clear_mwi(pdev);
  csr0 &= ~MWI;
 }

 /* sane defaults for burst length and cache alignment
  * originally from de4x5 driver
  */
 csr0 |= (8 << BurstLenShift) | (1 << CALShift);

out:
 tp->csr0 = csr0;
 if (tulip_debug > 2)
  netdev_dbg(dev, "MWI config cacheline=%d, csr0=%08x\n",
      cache, csr0);
}
#endif

/*
 * Chips that have the MRM/reserved bit quirk and the burst quirk. That
 * is the DM910X and the on chip ULi devices
 */

static int tulip_uli_dm_quirk(struct pci_dev *pdev)
{
 if (pdev->vendor == 0x1282 && pdev->device == 0x9102)
  return 1;
 return 0;
}

static const struct net_device_ops tulip_netdev_ops = {
 .ndo_open  = tulip_open,
 .ndo_start_xmit  = tulip_start_xmit,
 .ndo_tx_timeout  = tulip_tx_timeout,
 .ndo_stop  = tulip_close,
 .ndo_get_stats  = tulip_get_stats,
 .ndo_do_ioctl   = private_ioctl,
 .ndo_set_rx_mode = set_rx_mode,
 .ndo_change_mtu  = eth_change_mtu,
 .ndo_set_mac_address = eth_mac_addr,
 .ndo_validate_addr = eth_validate_addr,
#ifdef CONFIG_NET_POLL_CONTROLLER
 .ndo_poll_controller  = poll_tulip,
#endif
};

DEFINE_PCI_DEVICE_TABLE(early_486_chipsets) = {
 { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82424) },
 { PCI_DEVICE(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_496) },
 { },
};

static int tulip_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
{
 struct tulip_private *tp;
 /* See note below on the multiport cards. */
 static unsigned char last_phys_addr[6] = {0x00, 'L', 'i', 'n', 'u', 'x'};
 static int last_irq;
 static int multiport_cnt; /* For four-port boards w/one EEPROM */
 int i, irq;
 unsigned short sum;
 unsigned char *ee_data;
 struct net_device *dev;
 void __iomem *ioaddr;
 static int board_idx = -1;
 int chip_idx = ent->driver_data;
 const char *chip_name = tulip_tbl[chip_idx].chip_name;
 unsigned int eeprom_missing = 0;
 unsigned int force_csr0 = 0;

#ifndef MODULE
 if (tulip_debug > 0)
  printk_once(KERN_INFO "%s", version);
#endif

 board_idx++;

 /*
  * Lan media wire a tulip chip to a wan interface. Needs a very
  * different driver (lmc driver)
  */

        if (pdev->subsystem_vendor == PCI_VENDOR_ID_LMC) {
  pr_err("skipping LMC card\n");
  return -ENODEV;
 } else if (pdev->subsystem_vendor == PCI_VENDOR_ID_SBE &&
     (pdev->subsystem_device == PCI_SUBDEVICE_ID_SBE_T3E3 ||
      pdev->subsystem_device == PCI_SUBDEVICE_ID_SBE_2T3E3_P0 ||
      pdev->subsystem_device == PCI_SUBDEVICE_ID_SBE_2T3E3_P1)) {
  pr_err("skipping SBE T3E3 port\n");
  return -ENODEV;
 }

 /*
  * DM910x chips should be handled by the dmfe driver, except
  * on-board chips on SPARC systems.  Also, early DM9100s need
  * software CRC which only the dmfe driver supports.
  */

#ifdef CONFIG_TULIP_DM910X
 if (chip_idx == DM910X) {
  struct device_node *dp;

  if (pdev->vendor == 0x1282 && pdev->device == 0x9100 &&
      pdev->revision < 0x30) {
   pr_info("skipping early DM9100 with Crc bug (use dmfe)\n");
   return -ENODEV;
  }

  dp = pci_device_to_OF_node(pdev);
  if (!(dp && of_get_property(dp, "local-mac-address", NULL))) {
   pr_info("skipping DM910x expansion card (use dmfe)\n");
   return -ENODEV;
  }
 }
#endif

 /*
  * Looks for early PCI chipsets where people report hangs
  * without the workarounds being on.
  */

 /* 1. Intel Saturn. Switch to 8 long words burst, 8 long word cache
       aligned.  Aries might need this too. The Saturn errata are not
       pretty reading but thankfully it's an old 486 chipset.

    2. The dreaded SiS496 486 chipset. Same workaround as Intel
       Saturn.
 */

 if (pci_dev_present(early_486_chipsets)) {
  csr0 = MRL | MRM | (8 << BurstLenShift) | (1 << CALShift);
  force_csr0 = 1;
 }

 /* bugfix: the ASIX must have a burst limit or horrible things happen. */
 if (chip_idx == AX88140) {
  if ((csr0 & 0x3f00) == 0)
   csr0 |= 0x2000;
 }

 /* PNIC doesn't have MWI/MRL/MRM... */
 if (chip_idx == LC82C168)
  csr0 &= ~0xfff10000; /* zero reserved bits 31:20, 16 */

 /* DM9102A has troubles with MRM & clear reserved bits 24:22, 20, 16, 7:1 */
 if (tulip_uli_dm_quirk(pdev)) {
  csr0 &= ~0x01f100ff;
#if defined(CONFIG_SPARC)
                csr0 = (csr0 & ~0xff00) | 0xe000;
#endif
 }
 /*
  * And back to business
  */

 i = pci_enable_device(pdev);
 if (i) {
  pr_err("Cannot enable tulip board #%d, aborting\n", board_idx);
  return i;
 }

 /* The chip will fail to enter a low-power state later unless
  * first explicitly commanded into D0 */
 if (pci_set_power_state(pdev, PCI_D0)) {
  pr_notice("Failed to set power state to D0\n");
 }

 irq = pdev->irq;

 /* alloc_etherdev ensures aligned and zeroed private structures */
 dev = alloc_etherdev (sizeof (*tp));
 if (!dev)
  return -ENOMEM;

 SET_NETDEV_DEV(dev, &pdev->dev);
 if (pci_resource_len (pdev, 0) < tulip_tbl[chip_idx].io_size) {
  pr_err("%s: I/O region (0x%llx@0x%llx) too small, aborting\n",
         pci_name(pdev),
         (unsigned long long)pci_resource_len (pdev, 0),
         (unsigned long long)pci_resource_start (pdev, 0));
  goto err_out_free_netdev;
 }

 /* grab all resources from both PIO and MMIO regions, as we
  * don't want anyone else messing around with our hardware */
 if (pci_request_regions (pdev, DRV_NAME))
  goto err_out_free_netdev;

 ioaddr =  pci_iomap(pdev, TULIP_BAR, tulip_tbl[chip_idx].io_size);

 if (!ioaddr)
  goto err_out_free_res;

 /*
  * initialize private data structure 'tp'
  * it is zeroed and aligned in alloc_etherdev
  */
 tp = netdev_priv(dev);
 tp->dev = dev;

 tp->rx_ring = pci_alloc_consistent(pdev,
        sizeof(struct tulip_rx_desc) * RX_RING_SIZE +
        sizeof(struct tulip_tx_desc) * TX_RING_SIZE,
        &tp->rx_ring_dma);
 if (!tp->rx_ring)
  goto err_out_mtable;
 tp->tx_ring = (struct tulip_tx_desc *)(tp->rx_ring + RX_RING_SIZE);
 tp->tx_ring_dma = tp->rx_ring_dma + sizeof(struct tulip_rx_desc) * RX_RING_SIZE;

 tp->chip_id = chip_idx;
 tp->flags = tulip_tbl[chip_idx].flags;

 pr_info("%s: No allowed WOL support\n",__func__);
 
 /*tp->wolinfo.supported = 0;
 tp->wolinfo.wolopts = 0;*/
 
 
 /* COMET: Enable power management only for AN983B */
 /*if (chip_idx == COMET ) {
  u32 sig;
  pci_read_config_dword (pdev, 0x80, &sig);
  if (sig == 0x09811317) {
   tp->flags |= COMET_PM;
   tp->wolinfo.supported = WAKE_PHY | WAKE_MAGIC;
   pr_info("%s: Enabled WOL support for AN983B\n",
    __func__);
  }
 }*/
 
 tp->pdev = pdev;
 tp->base_addr = ioaddr;
 tp->revision = pdev->revision;
 tp->csr0 = csr0;
 spin_lock_init(&tp->lock);
 spin_lock_init(&tp->mii_lock);
 init_timer(&tp->timer);
 tp->timer.data = (unsigned long)dev;
 tp->timer.function = tulip_tbl[tp->chip_id].media_timer;

 INIT_WORK(&tp->media_work, tulip_tbl[tp->chip_id].media_task);

#ifdef CONFIG_TULIP_MWI
 if (!force_csr0 && (tp->flags & HAS_PCI_MWI))
  tulip_mwi_config (pdev, dev);
#endif

 /* Stop the chip's Tx and Rx processes. */
 tulip_stop_rxtx(tp);

 pci_set_master(pdev);

#ifdef CONFIG_GSC
 if (pdev->subsystem_vendor == PCI_VENDOR_ID_HP) {
  switch (pdev->subsystem_device) {
  default:
   break;
  case 0x1061:
  case 0x1062:
  case 0x1063:
  case 0x1098:
  case 0x1099:
  case 0x10EE:
   tp->flags |= HAS_SWAPPED_SEEPROM | NEEDS_FAKE_MEDIA_TABLE;
   chip_name = "GSC DS21140 Tulip";
  }
 }
#endif

 /* Clear the missed-packet counter. */
 ioread32(ioaddr + CSR8);

 /* The station address ROM is read byte serially.  The register must
    be polled, waiting for the value to be read bit serially from the
    EEPROM.
    */
 ee_data = tp->eeprom;
 memset(ee_data, 0, sizeof(tp->eeprom));
 sum = 0;
 if (chip_idx == LC82C168) {
  for (i = 0; i < 3; i++) {
   int value, boguscnt = 100000;
   iowrite32(0x600 | i, ioaddr + 0x98);
   do {
    value = ioread32(ioaddr + CSR9);
   } while (value < 0  && --boguscnt > 0);
   put_unaligned_le16(value, ((__le16 *)dev->dev_addr) + i);
   sum += value & 0xffff;
  }
 } else if (chip_idx == COMET) {
  /* No need to read the EEPROM. */
  put_unaligned_le32(ioread32(ioaddr + 0xA4), dev->dev_addr);
  put_unaligned_le16(ioread32(ioaddr + 0xA8), dev->dev_addr + 4);
  for (i = 0; i < 6; i ++)
   sum += dev->dev_addr[i];
 } else {
  /* A serial EEPROM interface, we read now and sort it out later. */
  int sa_offset = 0;
  int ee_addr_size = tulip_read_eeprom(dev, 0xff, 8) & 0x40000 ? 8 : 6;
  int ee_max_addr = ((1 << ee_addr_size) - 1) * sizeof(u16);

  if (ee_max_addr > sizeof(tp->eeprom))
   ee_max_addr = sizeof(tp->eeprom);

  for (i = 0; i < ee_max_addr ; i += sizeof(u16)) {
   u16 data = tulip_read_eeprom(dev, i/2, ee_addr_size);
   ee_data[i] = data & 0xff;
   ee_data[i + 1] = data >> 8;
  }

  /* DEC now has a specification (see Notes) but early board makers
     just put the address in the first EEPROM locations. */
  /* This does  memcmp(ee_data, ee_data+16, 8) */
  for (i = 0; i < 8; i ++)
   if (ee_data[i] != ee_data[16+i])
    sa_offset = 20;
  if (chip_idx == CONEXANT) {
   /* Check that the tuple type and length is correct. */
   if (ee_data[0x198] == 0x04  &&  ee_data[0x199] == 6)
    sa_offset = 0x19A;
  } else if (ee_data[0] == 0xff  &&  ee_data[1] == 0xff &&
       ee_data[2] == 0) {
   sa_offset = 2;  /* Grrr, damn Matrox boards. */
   multiport_cnt = 4;
  }
#ifdef CONFIG_MIPS_COBALT
               if ((pdev->bus->number == 0) &&
                   ((PCI_SLOT(pdev->devfn) == 7) ||
                    (PCI_SLOT(pdev->devfn) == 12))) {
                       /* Cobalt MAC address in first EEPROM locations. */
                       sa_offset = 0;
         /* Ensure our media table fixup get's applied */
         memcpy(ee_data + 16, ee_data, 8);
               }
#endif
#ifdef CONFIG_GSC
  /* Check to see if we have a broken srom */
  if (ee_data[0] == 0x61 && ee_data[1] == 0x10) {
   /* pci_vendor_id and subsystem_id are swapped */
   ee_data[0] = ee_data[2];
   ee_data[1] = ee_data[3];
   ee_data[2] = 0x61;
   ee_data[3] = 0x10;

   /* HSC-PCI boards need to be byte-swaped and shifted
    * up 1 word.  This shift needs to happen at the end
    * of the MAC first because of the 2 byte overlap.
    */
   for (i = 4; i >= 0; i -= 2) {
    ee_data[17 + i + 3] = ee_data[17 + i];
    ee_data[16 + i + 5] = ee_data[16 + i];
   }
  }
#endif

  for (i = 0; i < 6; i ++) {
   dev->dev_addr[i] = ee_data[i + sa_offset];
   sum += ee_data[i + sa_offset];
  }
 }
 /* Lite-On boards have the address byte-swapped. */
 if ((dev->dev_addr[0] == 0xA0 ||
      dev->dev_addr[0] == 0xC0 ||
      dev->dev_addr[0] == 0x02) &&
     dev->dev_addr[1] == 0x00)
  for (i = 0; i < 6; i+=2) {
   char tmp = dev->dev_addr[i];
   dev->dev_addr[i] = dev->dev_addr[i+1];
   dev->dev_addr[i+1] = tmp;
  }
 /* On the Zynx 315 Etherarray and other multiport boards only the
    first Tulip has an EEPROM.
    On Sparc systems the mac address is held in the OBP property
    "local-mac-address".
    The addresses of the subsequent ports are derived from the first.
    Many PCI BIOSes also incorrectly report the IRQ line, so we correct
    that here as well. */
 if (sum == 0  || sum == 6*0xff) {
#if defined(CONFIG_SPARC)
  struct device_node *dp = pci_device_to_OF_node(pdev);
  const unsigned char *addr;
  int len;
#endif
  eeprom_missing = 1;
  for (i = 0; i < 5; i++)
   dev->dev_addr[i] = last_phys_addr[i];
  dev->dev_addr[i] = last_phys_addr[i] + 1;
#if defined(CONFIG_SPARC)
  addr = of_get_property(dp, "local-mac-address", &len);
  if (addr && len == 6)
   memcpy(dev->dev_addr, addr, 6);
#endif
#if defined(__i386__) || defined(__x86_64__) /* Patch up x86 BIOS bug. */
  if (last_irq)
   irq = last_irq;
#endif
 }

 for (i = 0; i < 6; i++)
  last_phys_addr[i] = dev->dev_addr[i];
 last_irq = irq;

 /* The lower four bits are the media type. */
 if (board_idx >= 0  &&  board_idx < MAX_UNITS) {
  if (options[board_idx] & MEDIA_MASK)
   tp->default_port = options[board_idx] & MEDIA_MASK;
  if ((options[board_idx] & FullDuplex) || full_duplex[board_idx] > 0)
   tp->full_duplex = 1;
  if (mtu[board_idx] > 0)
   dev->mtu = mtu[board_idx];
 }
 if (dev->mem_start & MEDIA_MASK)
  tp->default_port = dev->mem_start & MEDIA_MASK;
 if (tp->default_port) {
  pr_info(DRV_NAME "%d: Transceiver selection forced to %s\n",
   board_idx, medianame[tp->default_port & MEDIA_MASK]);
  tp->medialock = 1;
  if (tulip_media_cap[tp->default_port] & MediaAlwaysFD)
   tp->full_duplex = 1;
 }
 if (tp->full_duplex)
  tp->full_duplex_lock = 1;

 if (tulip_media_cap[tp->default_port] & MediaIsMII) {
  static const u16 media2advert[] = {
   0x20, 0x40, 0x03e0, 0x60, 0x80, 0x100, 0x200
  };
  tp->mii_advertise = media2advert[tp->default_port - 9];
  tp->mii_advertise |= (tp->flags & HAS_8023X); /* Matching bits! */
 }

 if (tp->flags & HAS_MEDIA_TABLE) {
  sprintf(dev->name, DRV_NAME "%d", board_idx); /* hack */
  tulip_parse_eeprom(dev);
  strcpy(dev->name, "eth%d");   /* un-hack */
 }

 if ((tp->flags & ALWAYS_CHECK_MII) ||
  (tp->mtable  &&  tp->mtable->has_mii) ||
  ( ! tp->mtable  &&  (tp->flags & HAS_MII))) {
  if (tp->mtable  &&  tp->mtable->has_mii) {
   for (i = 0; i < tp->mtable->leafcount; i++)
    if (tp->mtable->mleaf[i].media == 11) {
     tp->cur_index = i;
     tp->saved_if_port = dev->if_port;
     tulip_select_media(dev, 2);
     dev->if_port = tp->saved_if_port;
     break;
    }
  }

  /* Find the connected MII xcvrs.
     Doing this in open() would allow detecting external xcvrs
     later, but takes much time. */
  tulip_find_mii (dev, board_idx);
 }

 /* The Tulip-specific entries in the device structure. */
 dev->netdev_ops = &tulip_netdev_ops;
 dev->watchdog_timeo = TX_TIMEOUT;
#ifdef CONFIG_TULIP_NAPI
 netif_napi_add(dev, &tp->napi, tulip_poll, 16);
#endif
 SET_ETHTOOL_OPS(dev, &ops);

 if (register_netdev(dev))
  goto err_out_free_ring;

 pci_set_drvdata(pdev, dev);

 dev_info(&dev->dev,
#ifdef CONFIG_TULIP_MMIO
   "%s rev %d at MMIO %#llx,%s %pM, IRQ %d\n",
#else
   "%s rev %d at Port %#llx,%s %pM, IRQ %d\n",
#endif
   chip_name, pdev->revision,
   (unsigned long long)pci_resource_start(pdev, TULIP_BAR),
   eeprom_missing ? " EEPROM not present," : "",
   dev->dev_addr, irq);

        if (tp->chip_id == PNIC2)
  tp->link_change = pnic2_lnk_change;
 else if (tp->flags & HAS_NWAY)
  tp->link_change = t21142_lnk_change;
 else if (tp->flags & HAS_PNICNWAY)
  tp->link_change = pnic_lnk_change;

 /* Reset the xcvr interface and turn on heartbeat. */
 switch (chip_idx) {
 case DC21140:
 case DM910X:
 default:
  if (tp->mtable)
   iowrite32(tp->mtable->csr12dir | 0x100, ioaddr + CSR12);
  break;
 case DC21142:
  if (tp->mii_cnt  ||  tulip_media_cap[dev->if_port] & MediaIsMII) {
   iowrite32(csr6_mask_defstate, ioaddr + CSR6);
   iowrite32(0x0000, ioaddr + CSR13);
   iowrite32(0x0000, ioaddr + CSR14);
   iowrite32(csr6_mask_hdcap, ioaddr + CSR6);
  } else
   t21142_start_nway(dev);
  break;
 case PNIC2:
         /* just do a reset for sanity sake */
  iowrite32(0x0000, ioaddr + CSR13);
  iowrite32(0x0000, ioaddr + CSR14);
  break;
 case LC82C168:
  if ( ! tp->mii_cnt) {
   tp->nway = 1;
   tp->nwayset = 0;
   iowrite32(csr6_ttm | csr6_ca, ioaddr + CSR6);
   iowrite32(0x30, ioaddr + CSR12);
   iowrite32(0x0001F078, ioaddr + CSR6);
   iowrite32(0x0201F078, ioaddr + CSR6); /* Turn on autonegotiation. */
  }
  break;
 case MX98713:
 case COMPEX9881:
  iowrite32(0x00000000, ioaddr + CSR6);
  iowrite32(0x000711C0, ioaddr + CSR14); /* Turn on NWay. */
  iowrite32(0x00000001, ioaddr + CSR13);
  break;
 case MX98715:
 case MX98725:
  iowrite32(0x01a80000, ioaddr + CSR6);
  iowrite32(0xFFFFFFFF, ioaddr + CSR14);
  iowrite32(0x00001000, ioaddr + CSR12);
  break;
 case COMET:
  /* No initialization necessary. */
  break;
 }

 /* put the chip in snooze mode until opened */
 tulip_set_power_state (tp, 0, 1);

 return 0;

err_out_free_ring:
 pci_free_consistent (pdev,
        sizeof (struct tulip_rx_desc) * RX_RING_SIZE +
        sizeof (struct tulip_tx_desc) * TX_RING_SIZE,
        tp->rx_ring, tp->rx_ring_dma);

err_out_mtable:
 kfree (tp->mtable);
 pci_iounmap(pdev, ioaddr);

err_out_free_res:
 pci_release_regions (pdev);

err_out_free_netdev:
 free_netdev (dev);
 return -ENODEV;
}


/* set the registers according to the given wolopts */
/*static void tulip_set_wolopts (struct pci_dev *pdev, u32 wolopts)
{
 struct net_device *dev = pci_get_drvdata(pdev);
 struct tulip_private *tp = netdev_priv(dev);
 void __iomem *ioaddr = tp->base_addr;

 if (tp->flags & COMET_PM) {
   
  unsigned int tmp;
   
  tmp = ioread32(ioaddr + CSR18);
  tmp &= ~(comet_csr18_pmes_sticky | comet_csr18_apm_mode | comet_csr18_d3a);
  tmp |= comet_csr18_pm_mode;
  iowrite32(tmp, ioaddr + CSR18);
   
  tmp = ioread32(ioaddr + CSR13);
  tmp &= ~(comet_csr13_linkoffe | comet_csr13_linkone | comet_csr13_wfre | comet_csr13_lsce | comet_csr13_mpre);
  if (wolopts & WAKE_MAGIC)
   tmp |= comet_csr13_mpre;
  if (wolopts & WAKE_PHY)
   tmp |= comet_csr13_linkoffe | comet_csr13_linkone | comet_csr13_lsce;
  tmp |= comet_csr13_wfr | comet_csr13_mpr | comet_csr13_lsc;
  iowrite32(tmp, ioaddr + CSR13);
 } 
 
}
*/

#ifdef CONFIG_PM


static int tulip_suspend (struct pci_dev *pdev, pm_message_t state)
{
 //pci_power_t pstate;
 struct net_device *dev = pci_get_drvdata(pdev);
 //struct tulip_private *tp = netdev_priv(dev);

 if (!dev)
  return -EINVAL;

 if (!netif_running(dev))
  goto save_state;

 tulip_down(dev);

 netif_device_detach(dev);
 /* FIXME: it needlessly adds an error path. */
 //Nuevo añadido: free_irq(tp->pdev->irq, dev);

save_state:
 pci_save_state(pdev);
 pci_disable_device(pdev);
//Nuevo:
    pci_set_power_state(pdev, pci_choose_state(pdev, state)); 
 
 /*pstate = pci_choose_state(pdev, state);
 if (state.event == PM_EVENT_SUSPEND && pstate != PCI_D0) {
  int rc;

  tulip_set_wolopts(pdev, tp->wolinfo.wolopts);
  rc = pci_enable_wake(pdev, pstate, tp->wolinfo.wolopts);
  if (rc)
   pr_err("pci_enable_wake failed (%d)\n", rc);
 }
 pci_set_power_state(pdev, pstate);
    */
    
 return 0;
}


static int tulip_resume(struct pci_dev *pdev)
{
 struct net_device *dev = pci_get_drvdata(pdev);
// struct tulip_private *tp = netdev_priv(dev);
// void __iomem *ioaddr = tp->base_addr;
 int retval;
// unsigned int tmp;

 if (!dev)
  return -EINVAL;

 pci_set_power_state(pdev, PCI_D0);
 pci_restore_state(pdev);

 if (!netif_running(dev))
  return 0;

 if ((retval = pci_enable_device(pdev))) {
  pr_err("pci_enable_device failed in resume\n");
  return retval;
 }

 retval = request_irq(pdev->irq, tulip_interrupt, IRQF_SHARED,
        dev->name, dev);
 if (retval) {
  pr_err("request_irq failed in resume\n");
  return retval;
 }

// if (tp->flags & COMET_PM) {
  //pci_enable_wake(pdev, PCI_D3hot, 0);
  //pci_enable_wake(pdev, PCI_D3cold, 0);

  /* Clear the PMES flag */
  //tmp = ioread32(ioaddr + CSR20);
  //tmp |= comet_csr20_pmes;
  //iowrite32(tmp, ioaddr + CSR20);

  /* Disable all wake-up events */
 // tulip_set_wolopts(pdev, 0);
 //}
 netif_device_attach(dev);

 if (netif_running(dev))
  tulip_up(dev);

 return 0;
}

#endif /* CONFIG_PM */


static void tulip_remove_one(struct pci_dev *pdev)
{
 struct net_device *dev = pci_get_drvdata (pdev);
 struct tulip_private *tp;

 if (!dev)
  return;

 tp = netdev_priv(dev);
 unregister_netdev(dev);
 pci_free_consistent (pdev,
        sizeof (struct tulip_rx_desc) * RX_RING_SIZE +
        sizeof (struct tulip_tx_desc) * TX_RING_SIZE,
        tp->rx_ring, tp->rx_ring_dma);
 kfree (tp->mtable);
 pci_iounmap(pdev, tp->base_addr);
 free_netdev (dev);
 pci_release_regions (pdev);
 pci_set_drvdata (pdev, NULL);

 /* pci_power_off (pdev, -1); */
}

#ifdef CONFIG_NET_POLL_CONTROLLER
/*
 * Polling 'interrupt' - used by things like netconsole to send skbs
 * without having to re-enable interrupts. It's not called while
 * the interrupt routine is executing.
 */

static void poll_tulip (struct net_device *dev)
{
 struct tulip_private *tp = netdev_priv(dev);
 const int irq = tp->pdev->irq;

 /* disable_irq here is not very nice, but with the lockless
    interrupt handler we have no other choice. */
 disable_irq(irq);
 tulip_interrupt (irq, dev);
 enable_irq(irq);
}
#endif

static struct pci_driver tulip_driver = {
 .name  = DRV_NAME,
 .id_table = tulip_pci_tbl,
 .probe  = tulip_init_one,
 .remove  = tulip_remove_one,
#ifdef CONFIG_PM
 .suspend = tulip_suspend,
 .resume  = tulip_resume,
#endif /* CONFIG_PM */
};


static int __init tulip_init (void)
{
#ifdef MODULE
 pr_info("%s", version);
#endif

 /* copy module parms into globals */
 tulip_rx_copybreak = rx_copybreak;
 tulip_max_interrupt_work = max_interrupt_work;

 /* probe for and init boards */
 return pci_register_driver(&tulip_driver);
}


static void __exit tulip_cleanup (void)
{
 pci_unregister_driver (&tulip_driver);
}


module_init(tulip_init);
module_exit(tulip_cleanup);
Funciona para kernels 3.2.0-4, pero sospecho que compilará sin mayor problema en kernels superiores. En cualquier caso para adaptarlo a otros kernel habría que comentar las mismas partes que he comentado en el tulip_core.c para el kernel 3.2.0-4, comparando con el tulip_core.c original. Quizá sustituyendo directamente el tulip_core.c por el que se enlaza funcione sin más, ya que es un driver que no cambia mucho.

Antes de nada, bajamos del enlace anterior el fichero tulip_core.c modificado y lo guardamos en una carpeta /root/tulip del PC donde vayamos a realizar la compilación, un equipo Fujitsu P300 en mi caso. Los pasos a dar para compilar el driver tulip son los siguientes:

1) Confirmamos la versión del kernel y bajamos las cabeceras y el código fuente:

# apt-get update
# cat /proc/version
Linux version 3.2.0-4-686-pae (debian-kernel@lists.debian.org) (gcc version 4.6.3 (Debian 4.6.3-14) ) #1 SMP Debian 3.2.65-1+deb7u1
# apt-get install linux-headers-3.2.0-4-686-pae
# apt-get install linux-source-3.2

2) Descomprimimos el kernel y antes de seguir hacemos una copia del driver original (tulip.ko) por si metemos la pata poder restaurarlo luego. La copia se hace a un directorio /root/tulip que hemos creado previamente.

# cd /usr/src/
# tar jfvx linux-source-3.2.tar.bz2
# cd /lib/modules/3.2.0-4-686-pae/kernel/drivers/net/ethernet/dec/tulip/
# cp tulip.ko /root/tulip/tulip-original.ko

3) Volvemos al código fuente y preparamos el entorno de compilación, indicamos que haremos uso de la configuración del kernel actualmente en funcionamiento:

# cd /usr/src/linux-source-3.2/
# make distclean; yes "" | make oldconfig
# make prepare
# make modules_prepare
# cp /usr/src/linux-headers-3.2.0-4-686-pae/Module.symvers .

4) Hacemos una copia del tulip_core.c original a /root/tulip/tulip_core.c.original y machacamos éste con /root/tulip/tulip_core.c, que es dónde hemos descargado el fichero modificado desde el enlace anteriormente indicado.

# cd /usr/src/linux-source-3.2/drivers/net/ethernet/dec/tulip/
# mv tulip_core.c  /root/tulip/tulip_core.c.original
# cp /root/tulip/tulip_core.c .

5) Bueno, ahora lanzamos la compilación:

# cd /usr/src/linux-source-3.2/
# make M=drivers/net/ethernet/dec/ clean
# make M=drivers/net/ethernet/dec/ modules

El parámetro M=drivers/net/ethernet/dec/ es muy útil para compilar solamente el driver tulip (ubicado en drivers/net/ethernet/dec) y no el kernel completo, ya que tarda una eternidad en hacerse.

6) Una vez compilado con éxito, guardamos el driver generado por si acaso y lanzamos la instalación del mismo:

# cp /usr/src/linux-source-3.2/drivers/net/ethernet/dec/tulip/tulip.ko /root/tulip/tulip-sinwol.ko
# make M=drivers/net/ethernet/dec/ modules_install

7) Veamos si se ha instalado:

#ls -1 /lib/modules/
3.2.0-4-686-pae
3.2.65

Bueno, pues parece que en la carpeta 3.2.0-4-686-pae está el driver antiguo y en la carpeta 3.2.65 el driver nuevo (la compilación de los drivers del kernel bajado desde fuentes se guarda en una carpeta distinta al instalarse para no colisionar con los que ya tenemos). Esto va bene.

8) Prosigamos: regeneramos las dependencias de módulos y metemos el módulo nuevo en en initramfs, reiniciando luego.

# depmod -a
# update-initramfs -u
# reboot

9) Al arrancar de nuevo hacemos:

# ethtool -s eth0 wol g

Carajo, no da error diciendo que no hay soporte ethtool, como debería ser. Se ha cargado el driver antiguo otra vez. Tranquilidad: por defecto se carga el driver tulip.ko de /lib/modules/3.2.0-4-686-pae y no el de /lib/modules/3.2.65. Tenemos dos opciones:

  • La fuerza bruta: machacar el driver antiguo con el nuevo, escribiendo:
# cp /root/tulip/tulip-sinwol.ko /lib/modules/3.2.0-4-686-pae/kernel/drivers/net/ethernet/dec/tulip/tulip.ko
# depmod -a
# update-initramfs -u
# reboot

o

# cp /lib/modules/3.2.65/extra/tulip/tulip.ko /lib/modules/3.2.0-4-686-pae/kernel/drivers/net/ethernet/dec/tulip/tulip.ko
# depmod -a
# update-initramfs -u
# reboot
  • Decirle al sistema que cargue antes los drivers actualizados que los propios del kernel. Para ello editamos /etc/depmod.conf y dejamos la primera línea así:
search updates built-in
....

y luego, otra vez:

# depmod -a
# update-initramfs -u

Pues nada, reiniciamos y el ethtool ahora debe dar nuestro esperado error. Si apagamos el equipo y mandamos un wakeonlan a su MAC desde otro PC nuestro ferro P300 despertará.

Y con esto y un bizcocho, hasta la semana que viene a las 8.

Actualización:

  • El usar /etc/depmod.conf para hacer que nuestro módulo se cargue antes que el que viene con el kernel por defecto no funciona en Debian Wheezy. Ese fichero ha desaparecido inexplicablemente. He leído algo sobre usar /etc/depmod.conf.d/* (que tampoco existe) y crear alli un fichero con el contenido de depmod.conf, pero no lo he probado. Recomiendo por tanto la primera solución: sobreescribir el driver original. A fin de cuentas tenemos copia.
  • Con un kernel de backports de wheezy, el 3.16, la compilación del driver no funciona. La orden:
# make M=drivers/net/ethernet/dec/ modules

Da un error en tulip_core.c, cuando compilaba perfectamente con kernel 3.2. La causa es que pasa a tratar como "error" cosas que antes eran "warning". Para solucionarlo hay que editar el fichero tulip_core.c y cambiar:

SET_ETHTOOL_OPS(dev, &ops);

por

dev->ethtool_ops = &ops;