3 # This script illustrates the sequence of operations in configfs to
4 # create a very simple LIO iSCSI target with a file or block device
7 # (C) Copyright 2014 Christophe Vu-Brugier <cvubrugier@fastmail.fm>
12 Usage: $(basename $0) [-p PORTAL] DEVICE|FILE
13 Export a block device or a file as an iSCSI target with a single LUN
22 while getopts "hp:" arg; do
24 h) print_usage; exit 0;;
28 shift $(($OPTIND - 1))
31 [ -n "$DEVICE" ] || die "Missing device or file argument"
32 [ -b $DEVICE -o -f $DEVICE ] || die "Invalid device or file: ${DEVICE}"
33 IQN="iqn.2003-01.org.linux-iscsi.$(hostname):$(basename $DEVICE)"
34 [ -n "$PORTAL" ] || PORTAL="0.0.0.0:3260"
36 CONFIGFS=/sys/kernel/config
37 CORE_DIR=$CONFIGFS/target/core
38 ISCSI_DIR=$CONFIGFS/target/iscsi
40 # Load the target modules and mount the config file system
41 lsmod | grep -q configfs || modprobe configfs
42 lsmod | grep -q target_core_mod || modprobe target_core_mod
43 mount | grep -q ^configfs || mount -t configfs none $CONFIGFS
47 if [ -b $DEVICE ]; then
48 BACKSTORE_DIR=$CORE_DIR/iblock_0/data
49 mkdir -p $BACKSTORE_DIR
50 echo "udev_path=${DEVICE}" > $BACKSTORE_DIR/control
52 BACKSTORE_DIR=$CORE_DIR/fileio_0/data
53 mkdir -p $BACKSTORE_DIR
54 DEVICE_SIZE=$(du -b $DEVICE | cut -f1)
55 echo "fd_dev_name=${DEVICE}" > $BACKSTORE_DIR/control
56 echo "fd_dev_size=${DEVICE_SIZE}" > $BACKSTORE_DIR/control
57 echo 1 > $BACKSTORE_DIR/attrib/emulate_write_cache
59 echo 1 > $BACKSTORE_DIR/enable
61 # Create an iSCSI target and a target portal group (TPG)
63 mkdir $ISCSI_DIR/$IQN/tpgt_1/
66 mkdir $ISCSI_DIR/$IQN/tpgt_1/lun/lun_0
67 ln -s $BACKSTORE_DIR $ISCSI_DIR/$IQN/tpgt_1/lun/lun_0/data
68 echo 1 > $ISCSI_DIR/$IQN/tpgt_1/enable
70 # Create a network portal
71 mkdir $ISCSI_DIR/$IQN/tpgt_1/np/$PORTAL
73 # Disable authentication
74 echo 0 > $ISCSI_DIR/$IQN/tpgt_1/attrib/authentication
75 echo 1 > $ISCSI_DIR/$IQN/tpgt_1/attrib/generate_node_acls
77 # Allow write access for non authenticated initiators
78 echo 0 > $ISCSI_DIR/$IQN/tpgt_1/attrib/demo_mode_write_protect
80 echo "Target ${IQN}, portal ${PORTAL} has been created"