# -*- shell-script -*-

# 27device_scsi_sg - SCSI device support using sysfs.

# This file is part of the Linux lsvpd package.

# (C) Copyright IBM Corp. 2004

# Maintained by Martin Schwenke <martins@au.ibm.com>

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
    
# $Id: 27device_scsi_sysfs,v 1.7 2004/06/04 02:08:57 martins Exp $

[ -n "$sysfs_dir" ] || return 0

# This should work with Linux >= 2.6.2.
[ -d "${sysfs_dir}/class/scsi_generic" ] || modprobe sg >/dev/null 2>&1
[ -d "${sysfs_dir}/class/scsi_generic" ] || return 0

######################################################################

device_setup_scsi ()
{
    sysfs_fake_sg_map_x >"${db_misc_dir}/sg_map-x"
}

# This gets the "kernel name", ignoring any userspace naming.
get_device_name_scsi ()
{
    local hbtl="$1"

    local d l t name

    d="${sysfs_dir}/bus/scsi/devices/${hbtl}"

    for l in "${d}/block" "${d}/generic" ; do
	if [ -L "$l" ] ; then
	    t=$(readlink "$l")
	    name="${t##*/}" # basename
	    # FIXME!  Gross hack...
	    name="${name/#sr/scd}"
	    [ -n "$name" ] && echo "/dev/${name}"
	    break
	fi
    done
}

get_major_minor_scsi ()
{
    local hbtl="$1"

    local f mm
    f="${sysfs_dir}/bus/scsi/devices/${hbtl}/generic/dev"
    [ -f "$f" ] && read mm <"$f"
    [ -n "$mm" ] && echo "$mm"
}

######################################################################

sysfs_fake_sg_map_x ()
{
    local d bn dl t hbtl tf type devlink dev
    for d in "${sysfs_dir}/class/scsi_generic/"* ; do
	bn="${d##*/}" # basename
	dl="${d}/device"
	if [ -h "$dl" ] ; then
	    t=$(readlink "$dl")
	    hbtl="${t##*/}" # basename

	    tf="${dl}/type"
	    if [ -f "$tf" ] ; then
		read type <"$tf"

		echo -n "/dev/${bn}  ${hbtl//:/ }  ${type}"

		case "$type" in
		    # FIXME!  Other types needed.
		    (0) devlink="${dl}/block" ;;
		    (*) devlink=""            ;;
		esac
		if [ -h "$devlink" ] ; then
		    t=$(readlink "$devlink")
		    dev="${t##*/}" # basename
		    echo "  /dev/${dev}"
		else
		    echo
		fi
	    fi
	fi
    done
}
