target-export-device 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #!/bin/sh
  2. #
  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
  5. # backstore.
  6. #
  7. # (C) Copyright 2014 Christophe Vu-Brugier <cvubrugier@fastmail.fm>
  8. #
  9. print_usage() {
  10. cat <<EOF
  11. Usage: $(basename $0) [-p PORTAL] DEVICE|FILE
  12. Export a block device or a file as an iSCSI target with a single LUN
  13. EOF
  14. }
  15. die() {
  16. echo $1
  17. exit 1
  18. }
  19. while getopts "hp:" arg; do
  20. case $arg in
  21. h) print_usage; exit 0;;
  22. p) PORTAL=${OPTARG};;
  23. esac
  24. done
  25. shift $(($OPTIND - 1))
  26. DEVICE=$1
  27. [ -n "$DEVICE" ] || die "Missing device or file argument"
  28. [ -b $DEVICE -o -f $DEVICE ] || die "Invalid device or file: ${DEVICE}"
  29. IQN="iqn.2003-01.org.linux-iscsi.$(hostname):$(basename $DEVICE)"
  30. [ -n "$PORTAL" ] || PORTAL="0.0.0.0:3260"
  31. CONFIGFS=/sys/kernel/config
  32. CORE_DIR=$CONFIGFS/target/core
  33. ISCSI_DIR=$CONFIGFS/target/iscsi
  34. # Load the target modules and mount the config file system
  35. lsmod | grep -q configfs || modprobe configfs
  36. lsmod | grep -q target_core_mod || modprobe target_core_mod
  37. mount | grep -q ^configfs || mount -t configfs none $CONFIGFS
  38. mkdir -p $ISCSI_DIR
  39. # Create a backstore
  40. if [ -b $DEVICE ]; then
  41. BACKSTORE_DIR=$CORE_DIR/iblock_0/data
  42. mkdir -p $BACKSTORE_DIR
  43. echo "udev_path=${DEVICE}" > $BACKSTORE_DIR/control
  44. else
  45. BACKSTORE_DIR=$CORE_DIR/fileio_0/data
  46. mkdir -p $BACKSTORE_DIR
  47. DEVICE_SIZE=$(du -b $DEVICE | cut -f1)
  48. echo "fd_dev_name=${DEVICE}" > $BACKSTORE_DIR/control
  49. echo "fd_dev_size=${DEVICE_SIZE}" > $BACKSTORE_DIR/control
  50. echo 1 > $BACKSTORE_DIR/attrib/emulate_write_cache
  51. fi
  52. echo 1 > $BACKSTORE_DIR/enable
  53. # Create an iSCSI target and a target portal group (TPG)
  54. mkdir $ISCSI_DIR/$IQN
  55. mkdir $ISCSI_DIR/$IQN/tpgt_1/
  56. # Create a LUN
  57. mkdir $ISCSI_DIR/$IQN/tpgt_1/lun/lun_0
  58. ln -s $BACKSTORE_DIR $ISCSI_DIR/$IQN/tpgt_1/lun/lun_0/data
  59. echo 1 > $ISCSI_DIR/$IQN/tpgt_1/enable
  60. # Create a network portal
  61. mkdir $ISCSI_DIR/$IQN/tpgt_1/np/$PORTAL
  62. # Disable authentication
  63. echo 0 > $ISCSI_DIR/$IQN/tpgt_1/attrib/authentication
  64. echo 1 > $ISCSI_DIR/$IQN/tpgt_1/attrib/generate_node_acls
  65. # Allow write access for non authenticated initiators
  66. echo 0 > $ISCSI_DIR/$IQN/tpgt_1/attrib/demo_mode_write_protect
  67. echo "Target ${IQN}, portal ${PORTAL} has been created"