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