# -*- shell-script -*-

# 07device_scsi_sg_scan - SCSI device listing support using sg3_utils.

# This file is part of the Linux lsvpd package.

# (C) Copyright IBM Corp. 2002, 2003, 2004, 2005

# 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: 07device_scsi_sg_scan,v 1.13 2005/02/09 05:58:47 martins Exp $

sg_map=$(type -p sg_map)
[ -n "$sg_map" ] || return 0

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

device_setup_scsi ()
{
    # First ensure there's the maximum number of available sg device nodes.
    local i=0
    while [ $i -lt 256 ] ; do
	node="/dev/sg$i"
	[ -c "$node" ] || mknod "$node" "c" 21 $i
	i=$(($i + 1))
    done

    debug_cmd "$sg_map" -x | grep -v '^#' >"${db_misc_dir}/sg_map-x"
}

list_devices_functions="${list_devices_functions} basic_list_devices_scsi"

basic_list_devices_scsi ()
{
    device_setup_scsi

    local h b t l x
    while read x h b t l x  ; do
	device_list="${device_list} scsi/${h}:${b}:${t}:${l}"
    done <"${db_misc_dir}/sg_map-x"
}

get_kernel_device_name_scsi ()
{
    local hbtl="$1"

    local host bus target lun
    scsi_parse_addr_hook "$hbtl"

    local sg_device_name h b t l x
    # Use device_name if available, otherwise sg_device_name
    while read sg_device_name h b t l x device_name  ; do
	if [ "${host}:${bus}:${target}:${lun}" = "${h}:${b}:${t}:${l}" ] ; then
	    [ -n "$device_name" ] || device_name="$sg_device_name"
	    return
	fi
    done <"${db_misc_dir}/sg_map-x"
    device_name=""
}

get_major_minor_scsi ()
{
    local hbtl="$1"

    local host bus target lun
    scsi_parse_addr_hook "$hbtl"

    local sg_device_name h b t l x
    # Use device_name if available, otherwise sg_device_name
    while read sg_device_name h b t l x  ; do
	if [ "${host}:${bus}:${target}:${lun}" = "${h}:${b}:${t}:${l}" ] ; then
	    echo "21:${sg_device_name#/dev/sg}"
	    return
	fi
    done <"${db_misc_dir}/sg_map-x"
}

