1#!/bin/sh -e
2
3# $NetBSD: block-nbsd,v 1.1.1.1 2008/08/07 20:26:57 cegger Exp $
4# Called by xenbackendd
5# Usage: block xsdir_backend_path state
6
7DIR=$(dirname "$0")
8. "${DIR}/hotplugpath.sh"
9
10PATH=${bindir}:${sbindir}:${LIBEXEC_BIN}:/bin:/usr/bin:/sbin:/usr/sbin
11export PATH
12
13error() {
14	echo "$@" >&2
15	xenstore-write $xpath/hotplug-status error \
16	               $xpath/hotplug-error "$@"
17	exit 1
18}
19
20
21xpath=$1
22xstatus=$2
23xparams=$(xenstore-read "$xpath/params")
24if [ -b "$xparams" ]; then
25	xtype="phy"
26elif [ -f "$xparams" ]; then
27	xtype="file"
28elif [ -z "$xparams" ]; then
29	error "$xpath/params is empty, unable to attach block device."
30else
31	error "$xparams is not a valid file type to use as block device." \
32	      "Only block and regular image files accepted."
33fi
34
35case $xstatus in
366)
37	# device removed
38	case $xtype in
39	file)
40		vnd=$(xenstore-read "$xpath/vnd" || echo none)
41		if [ $vnd != none ]; then
42			vnconfig -u $vnd
43		fi
44		;;
45	phy)
46		;;
47	*)
48		echo "unknown type $xtype" >&2
49		;;
50	esac
51	xenstore-rm $xpath
52	exit 0
53	;;
542)
55	case $xtype in
56	file)
57		# Store the list of available vnd(4) devices in
58		#``available_disks'', and mark them as ``free''.
59		list=`ls -1 /dev/vnd[0-9]*d | sed "s,/dev/vnd,,;s,d,," | sort -n`
60		for i in $list; do
61			disk="vnd$i"
62			available_disks="$available_disks $disk"
63			eval $disk=free
64		done
65		# Mark the used vnd(4) devices as ``used''.
66		for disk in `sysctl hw.disknames`; do
67			case $disk in
68			vnd[0-9]*) eval $disk=used ;;
69			esac
70		done
71		# Configure the first free vnd(4) device.
72		for disk in $available_disks; do
73			eval status=\$$disk
74			if [ "$status" = "free" ] && \
75			    vnconfig /dev/${disk}d $xparams >/dev/null; then
76				device=/dev/${disk}d
77				break
78			fi
79		done
80		if [ x$device = x ] ; then
81			error "no available vnd device"
82		fi
83		xenstore-write $xpath/vnd $device
84		;;
85	phy)
86		device=$xparams
87		;;
88	esac
89	physical_device=$(stat -f '%r' "$device")
90	xenstore-write $xpath/physical-device $physical_device
91	xenstore-write $xpath/hotplug-status connected
92	exit 0
93	;;
94*)
95	exit 0
96	;;
97esac
98