summaryrefslogtreecommitdiffstats
path: root/modules.d/slx-dmsetup/scripts/dmsetup-slx-device
blob: f9bbdd9d52fa491f5a5f42fb419b7f821078fa72 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
#!/usr/bin/env bash
#
# Script to back given read-only device using the block device
# specified by SLX_WRITABLE_DEVICE_IDENTIFIER in the SLX config.
# If SLX_WRITABLE_DEVICE_PARTITION_TABLE is sepcified, it will
# further create device mapper devices accordingly.
#
# Example partition config:
#	<type>         <name> <size> <crypt>
#	thin-snapshot   root    10G    1
#	thin-volume     tmp     20G    0
#	linear          data0   5-10G  1
#	linear          data1   1-50%  1
#
# NOTE: Encrypting thin-snapshot will actually encrypt the
# entire pool data device used for the pool.
# TODO: Support external keys
# TODO: Put table in file in config.tgz

type -p emergency_shell || . /lib/dracut-lib.sh

# for debugging purposes
set -x
exec &> /run/openslx/dmsetup.log

# read-only device to prepare for CoW
[ -z "$1" ] && emergency_shell "Read-only device was not given!"
declare -g read_only_device="$1"
declare -g read_only_device_size="$( blockdev --getsz "$1" )"

declare -rg ntfs_list="/run/openslx/.thin-ntfs-candidates"

# global array variables storing the configuration of the partitions
declare -ag linear snapshot thin_snapshot thin_volume
parse_config() {
	[ -z "$1" ] && return 1
	while IFS= read -r line; do
		[ -z "$line" ] && continue
		read -r type name range crypt ignore <<< "$line"
		type=${type//-/_} # to use the type as variable in eval
		if ! [[ "$type" =~ \
			^(linear|snapshot|thin_snapshot|thin_volume)$ ]]; then
			echo "$0: Ignoring invalid type: $line"
			continue
		fi
		if [[ -z "$name" ]]; then
			echo "$0: Ignoring nameless entry: $line"
			continue
		fi
		unset unit min max
		# ranges can be like: 40G, 40-80G, 10-20%
		if ! [[ $range =~ ^([0-9]+-)*([0-9])+[GgMmKkBb%]$ ]]; then
			echo "$0: Ignoring invalid range: $line"
			continue
		fi
		# process ranges: convert percentages (of read_only_device!)
		# to actual sizes (in sectors!) before saving them
		local unit=${range: -1}
		local min="$(cut -d'-' -f1 <<< "${range%?}" )"
		local max="$(cut -d'-' -f2 <<< "${range%?}" )"
		if [ "$min" -gt "$max" ]; then
			echo "$0: Ignoring invalid range: $line"
			continue
		fi
		# default for bytes
		local -i potency=0
		case "$unit" in
			[%])
				if [ "$max" -gt 100 ]; then
					echo "Ignoring invalid percentages: $min/$max"
					continue
				fi
				min=$(( writable_device_size * min / 100 ))
				max=$(( writable_device_size * max / 100 ))
				;;
			[Kk])	potency=1 ;;&
			[Mm])	potency=2 ;;&
			[Gg])	potency=3 ;;&
			*)
				# => 1024 ** potency for G, M, K, etc results in bytes
				# => bytes / 512 = sectors
				min=$(( min * ( 1024 ** potency) / 512 ))
				max=$(( max * ( 1024 ** potency) / 512 ))
				;;
		esac
		if ! [[ "$crypt"  =~ ^[01]$ ]]; then
			echo "$0: Disabling encryption due to invalid crypt argument: $line"
			crypt=0
		fi
		# finally save it to the global array for this type
		case "$type" in
			linear) linear+=("${name} ${crypt} ${min} ${max}") ;;
			snapshot) snapshot+=("${name} ${crypt} ${min} ${max}") ;;
			thin_snapshot) thin_snapshot+=("${name} ${crypt} ${min} ${max}") ;;
			thin_volume) thin_volume+=("${name} ${crypt} ${min} ${max}") ;;
			*) echo "$0: SOMETHING NOT GOOT CHECK SOURCE CODE" ;;
		esac
	done <<< "$1"
}

# Helper to call 'dmsetup setup' without syncing with udev
# and then actively create the devices with the mknodes command.
# dmsetup_create_noudevsync <name> <table>
dmsetup_create_noudevsync() {
	(
		set -o errexit
		printf "%s\n" "$2" | dmsetup create "$1" --noudevsync
		dmsetup mknodes --noudevsync "$1"
	)
	local ret=$?
	[ $ret -ne 0 ] && dmsetup remove --noudevsync "$1"
	return $ret
}

# encrypt_device <dev_path> <encrypted_name> [<size>]
encrypt_device() {
	modprobe dm-crypt || echo "$0: dm-crypt loading failed, maybe builtin?"
	[ -b "$1" ] || return 1
	[ -n "$2" ] || return 1
	[ -z "$3" ] && local size="$( blockdev --getsz "$1" )"
	local key="$(head -c32 /dev/random | xxd -c32 -p)"
	if ! dmsetup_create_noudevsync "$2" \
		"0 ${3:-${size}} crypt aes-xts-plain64 $key 0 $1 0 1 allow_discards"; then
		echo "$0: Failed to encrypt $1."
		return 1
	fi
	return 0
}
# create_snapshot "<name> <persist>"
create_snapshot() {
	modprobe dm-snapshot || echo "$0: dm-snapshot loading failed, maybe builtin?"
	read -r name persist ignore <<< "$1"
	if ! dmsetup_create_noudevsync "$name" \
		"0 $read_only_device_size snapshot $read_only_device $writable_device ${persist:-N} 8"; then
		echo "$0: Failed to create snapshot on '$writable_device' for '$read_only_device'."
		return 1
	fi
	return 0
}

# This function is called if no ID44 partition could be found or anoother kind
# of critical error occurs during the CoW layer setup. It will combine the
# the read-only device with a DM zero device to increase its virtual size
# by half the RAM size. A sparse file of that size will then be created and
# placed on a dedicated tmpfs.
ramdisk_fallback() {
	echo "$0: Falling back to regular dm-snapshot on a RAMdisk."

	# RAM size in kb, note that this is equal to half
	# of the entire RAM in 512-bytes sectors.
	local ram_size_in_kb="$(awk '/^MemTotal:/ { printf("%d\n", $2 ); exit }' /proc/meminfo)"

	#	try to prepare the zero extension device
	local extended_device="/dev/mapper/${read_only_device##*/}-extended"
	(
		set -e
		lsmod | grep -q dm-zero || modprobe dm-zero
		dmsetup_create_noudevsync zero "0 $ram_size_in_kb zero"
		dmsetup_create_noudevsync "${extended_device##*/}" \
			"0 $read_only_device_size linear $read_only_device 0
		  $read_only_device_size $ram_size_in_kb linear /dev/mapper/zero 0"
	)
	if [ "$?" -eq 0 ]; then
		read_only_device="$extended_device"
		read_only_device_size="$(( read_only_device_size + ram_size_in_kb ))"
	else
		echo "$0: Failed to setup the fake larger '$read_only_device'."
		echo "$0: Continuing with its original size."
	fi

	# prepare dedicated tmpfs mount point
	local cow_tmpfs="/run/openslx/cow"
	if ! mkdir -p "$cow_tmpfs"; then
		cow_tmpfs="${cow_tmpfs}.$$"
		if ! mkdir -p "$cow_tmpfs"; then
			# ultimate fallback on regular /run/openslx
			cow_tmpfs="/run/openslx"
		fi
	fi
	if ! mount -t tmpfs cow-tmpfs -o size="$(( read_only_device_size / 2 ))k" "$cow_tmpfs"; then
		echo "$0: Failed to mount tmpfs in '$cow_tmpfs' of size '$(( read_only_device_size / 2 ))'."
	fi

	# create sparse file there
	local file="$(mktemp -u -p "$cow_tmpfs" dnbd_cow.XXX)"
	if ! dd if=/dev/null of="$file" seek="$(( read_only_device_size / 2 ))" bs=1k 2> /dev/null; then
		emergency_shell "Failed to allocate CoW file $file."
	fi
	declare -rg writable_device="$(losetup --show --find "$file")"
	local cow_device_candidate="root"
	while [ -b "/dev/mapper/$cow_device_candidate" ]; do
		cow_device_candidate="root.$RANDOM"
	done
	if [ -z "$writable_device" ] || ! create_snapshot "$cow_device_candidate N"; then
		emergency_shell "CRITICAL: failed to setup RAMdisk fallback."
	fi
	finish_setup "$cow_device_candidate" "0" "$read_only_device_size"
}

# finish_setup <device> <type> [<size>]
# <device> is the device name only, /dev/mapper will be prepended automatically.
# <type> denotes if the created device lies in a RAMdisk (0) or is backed by a disk (1).
# <size> is given in sectors.
finish_setup() {
	if [ -z "$1" ] || [ ! -b "/dev/mapper/$1" ]; then
		emergency_shell "'/dev/mapper/$1' not a block device. Failed to setup CoW layer."
		exit 1
	fi
	if ! [[ "$2" =~ ^[0-9]$ ]]; then
		emergency_shell "'$2' not a valid type, 0 or 1 expected."
	fi
	# <size> optional?
	{
	echo "# Generated by '$0'."
	echo "SLX_DNBD3_DEVICE_COW=/dev/mapper/$1"
	} >> /etc/openslx
	save_partition_info "$1" "/" "$2" "$3"
	exit 0
}

# path to save the achieved setup to
declare -rg partitions_config="/run/openslx/dmsetup.state"
cat <<-EOF > "$partitions_config"
# Generated by '$0'.
# Format: <device_mapper_dev> <mount_point> <options>
# Options can be:
# * type -> CoW layer type: 0 is RAMdisk, 1 is disk, 2 is network
# * size -> in 512 byte sectors
EOF

# save_partition_info <dm_dev> <mount_point> <type> [<size>]
save_partition_info() {
	[ -b "/dev/mapper/$1" ] || return 1
	[ -n "$2" ] || return 1
	[[ "$3" =~ ^[0-9]$ ]] || return 1
	local opts="type=$3"
	# plain size given
	[[ "$4" =~ ^[0-9]+$ ]] && opts="$opts,physical_size=$4"
	# <physical_backing_dev_size>-<virtual_size>
	[[ "$4" =~ ^[0-9]+-[0-9]+$ ]] && opts="$opts,shared_physical_size=${4%-*},virtual_size=${4#*-}"
	echo "/dev/mapper/$1 $2 ${opts}" >> "$partitions_config"
}

###
##	MAIN
###

. /etc/openslx
# This is the main variable driving this script
declare -g writable_device=
if [ -z "$SLX_WRITABLE_DEVICE_IDENTIFIER" ]; then
	SLX_WRITABLE_DEVICE_IDENTIFIER=("44" "87f86132-ff94-4987-b250-444444444444")
	# TODO make scripts reading this variable compatible with list of IDs
	echo "SLX_WRITABLE_DEVICE_IDENTIFIER='${SLX_WRITABLE_DEVICE_IDENTIFIER[0]}'" >> /etc/openslx
	echo "SLX_WRITABLE_DEVICE_IDENTIFIERS='${SLX_WRITABLE_DEVICE_IDENTIFIER[*]}'" >> /etc/openslx
fi
# XXX The fuck? This may or may not be an array? Shit will defintely break some day...
if [ -n "$SLX_WRITABLE_DEVICE_IDENTIFIER" ]; then
	# only first one for now TODO create linear devices of all ID44s
	writable_device="$(slx-tools dev_find_partitions "${SLX_WRITABLE_DEVICE_IDENTIFIER[@]}" | head -n 1)"
fi
if [ -z "$writable_device" ]; then
	echo "$0: Could not find writable device with id '$SLX_WRITABLE_DEVICE_IDENTIFIER'."
	ramdisk_fallback
fi

# NOTE: from here on out, every value related to size is in 512 bytes sectors!
declare -g writable_device_size="$( blockdev --getsz "$writable_device" )"

# If SLX_WRITABLE_DEVICE_PARTITION_TABLE is not set, just do
# regular thin-snapshot for the CoW layer, else parse it.
if [ -n "$SLX_WRITABLE_DEVICE_PARTITION_TABLE" ]; then
	parse_config "$SLX_WRITABLE_DEVICE_PARTITION_TABLE"
fi
# Default to thin-snapshot, if none were configured
if [ "${#snapshot[@]}" = 0 ] && [ "${#thin_snapshot[@]}" = 0 ]; then
	parse_config "thin-snapshot root 100% 0"
fi

# Sanity checks for weird configurations
# XXX These were declared array and now turn into strings...
if [ "${#snapshot[@]}" -gt 1 ]; then
	echo "Multiple snapshots specified, using first one: ${snapshot[0]}"
fi
snapshot="${snapshot[0]}"
if [ "${#thin_snapshot[@]}" -gt 1 ]; then
	echo "Multiple thin-snapshots specified, using first one: ${thin_snapshot[0]}"
fi
thin_snapshot="${thin_snapshot[0]}"
if [ -n "$snapshot" ] && [ -n "$thin_snapshot" ]; then
	echo "$0: Both snapshot and thin-snapshot specified, prefering thin-snapshot."
	snapshot=
fi

###
##	LINEAR SLICES
###

# start allocating spaces to the configured devices
declare -g writable_device_allocated=0
# reserve the space for the snapshot (of either type)...
read -r name crypt min max ignore <<< "${thin_snapshot:-${snapshot}}"

declare -g scratch_device_size=0
if (( min <= writable_device_size )); then
	scratch_device_size=$max
	while (( scratch_device_size >= 0 )) && (( scratch_device_size > writable_device_size )); do
		(( scratch_device_size -= 2097152 )) # 1G steps => 2097152 sectors
	done
	(( scratch_device_size < min )) && scratch_device_size="$min"
else
	# minimum snapshot size is bigger than physical device size
	echo "$0: Minimum snapshot size is too big for the scratch partition."
	echo "$0: You probably need to use a more conservative value."
	echo "$0: Using this client maximum scratch space ($writable_device_size sectors)."
	scratch_device_size="$writable_device_size"
fi

# ... and slice it from the start of the writable device (for performance).
declare -g scratch_device="/dev/mapper/scratch"
if ! dmsetup_create_noudevsync "${scratch_device##*/}" \
	"0 $scratch_device_size linear $writable_device $writable_device_allocated"; then
		echo "$0: Failed to create scratch space for the CoW layer."
		# TODO do not bail directly, but try to to create the linear devices at least?
		ramdisk_fallback
fi
save_partition_info "${scratch_device##*/}" "*" "1" "$scratch_device_size"

# encrypt the scratch device, if configured
if [ "$crypt" -ne 0 ] && encrypt_device \
	"$scratch_device" "${scratch_device##*/}-crypt" "$scratch_device_size"; then
	scratch_device="${scratch_device}-crypt"
fi

writable_device_allocated="$scratch_device_size"

# first setup linear slices of the writable device
for line in "${linear[@]}"; do
	[ -z "$line" ] && continue
	read -r name crypt min max ignore <<< "$line"
	free_space="$(( writable_device_size - writable_device_allocated ))"
	if [ "$min" -gt "$free_space" ]; then
		echo "$0: Not enough space left for linear devices: '$line'"
		break
	fi
	# allocate its max if it fits within the free space, otherwise use the space left.
	to_allocate="$max"
	[ "$to_allocate" -gt "$free_space" ] && to_allocate="$free_space"

	if ! dmsetup_create_noudevsync "$name" "0 $to_allocate linear $writable_device $writable_device_allocated"; then
		echo "$0: Failed to create linear device: $line"
		continue
	fi
	# TODO sane?
	save_partition_info "$name" "*" "1" "$to_allocate"
	if [ "$crypt" -ne 0 ] && \
		! encrypt_device "/dev/mapper/$name" "${name}-crypt" "$to_allocate"; then
		echo "$0: Failed to encrypt '$name'."
	fi
	writable_device_allocated=$(( to_allocate + writable_device_allocated ))
done

# we are done with the physical device, use the scratch space from now on
writable_device="$scratch_device"
writable_device_size="$scratch_device_size"

###
##	THIN-PROVISIONING
###
declare -rg pool_data_dev="/dev/mapper/pool-data"
declare -rg pool_dev="/dev/mapper/pool"
declare -gi root_ntfs_extra=0 # Extra blocks to provision to root fs for later expansion
create_pool() {
	declare -r data_block_size=256 # Desired Block size (number of 512byte sectors)
	declare -r wanted_low_mb=100 # Free space below this will trigger a dm event
	# create external snapshot for read-only device
	# create remaining thin volumes
	modprobe dm-thin-pool || echo "$0: dm-thin-pool load failed, maybe builtin?"
	# create temporary metadata device
	# calculate number of sectors needed and check boundaries:
	# XXX Formula from thin-pool.txt calculates size in *bytes*, we want 512b blocks
	metadata_dev_size="$(( 48 * writable_device_size / data_block_size / 512 ))"
	# If we want NTFS as a backup plan to extend the pool, check if the current size
	# is less than 100GB, and only then consider this feature.
	# Maybe make that thresold configurable one day, but the the desktop client
	# use case this is sensible for now.
	if [ "$SLX_NTFSFREE" = "backup" ] && (( writable_device_size < 209715200 )) \
			&& [ -z "$metadata_persistent" ]; then
		find_ntfs_partitions
		if [ -s "$ntfs_list" ]; then
			# Look what size we end up if we want at least 50GB
			local sum="$( awk -v sum=0 \
				'{sum+=$1; if (sum >= 104857600) exit}END{printf "%.0f", sum}' \
				"$ntfs_list" )"
			if (( sum > 0 )); then
				(( sum > 209715200 )) && sum=209715200 # Max 100GB
				# Account for this potential growth in the metadata device size for future expansion
				metadata_dev_size="$(( metadata_dev_size + 48 * sum / data_block_size / 512 ))"
				echo "$sum" > "/run/openslx/.thin-ntfs-growsize"
				root_ntfs_extra="$sum"
			fi
		fi
	fi
	# Min 2MB -> 4096 sectors, max 16GB -> 33554432 sectors
	[ "$metadata_dev_size" -lt 4096 ] && metadata_dev_size="4096"
	# TODO handle the exotic case of a too large metadata device to fit within RAM.
	[ "$metadata_dev_size" -gt 33554432 ] && metadata_dev_size="33554432"
	local writable_device_offset=0
	local metadata_dev=
	local metadata_persistent=
	if [ -n "$metadata_persistent" ]; then
		# create persistent slice of the writable device for the pool metadata
		if ! dmsetup_create_noudevsync "pool-metadata" \
			"0 $metadata_dev_size linear $writable_device $writable_device_offset"; then
			echo "$0: Failed to create linear device for pool metadata device."
		else
			writable_device_offset="$metadata_dev_size"
			writable_device_size=$(( writable_device_size - metadata_dev_size ))
			declare -r metadata_dev="/dev/mapper/pool-metadata"
			# TODO configurable wipe: dd if=/dev/zero of="$metadata_dev" count=1 bs=4096
		fi
	fi
	if [ -z "$metadata_dev" ]; then
		# create RAMdisk in /run for metadata device
		metadata_dev="$(mktemp -p /run/openslx .pool-metadata.XXX)"
		# Create sparse file of required size
		dd if=/dev/null of="$metadata_dev" bs=512 seek="$metadata_dev_size" 2> /dev/null
		declare -r metadata_dev="$( losetup --show --find "$metadata_dev" )"
	fi

	# Create linear device of the writable device, in case we have an offset from
	# the on-disk meta data. Also this way we can easily extend it later.
	if ! dmsetup_create_noudevsync "${pool_data_dev##*/}" \
		"0 $writable_device_size linear $writable_device $writable_device_offset"; then
		echo "$0: Failed to create pool data device on '$writable_device'."
		return 1
	fi
	local low_water_mark
	# Convert MB to blocks
	low_water_mark=$(( wanted_low_mb * 2048 / data_block_size ))
	if ! dmsetup_create_noudevsync "${pool_dev##*/}" \
		"0 $writable_device_size thin-pool $metadata_dev $pool_data_dev $data_block_size $low_water_mark 1 skip_block_zeroing"; then
		echo "$0: Failed to create thin-pool device on '$writable_device'."
		return 1
	fi
	return 0
}

# create_volume <name> <id> <size> [backing_dev]
create_volume() {
	if [ -z "$pool_dev" ] || ! [ -b "$pool_dev" ]; then
		echo "$0: Global pool device not set or present."
		return 1
	fi
	if [ $# -lt 3 ] || [ -z "$1" ]; then
		echo "$0: create_volume: not enough arguments."
		return 1
	fi
	local name="$1"
	local id="$2"
	local size="$3"
	local backing_dev="$4" # Optional, internal if empty

	if ! dmsetup message "$pool_dev" 0 "create_thin $id"; then
		echo "$0: Failed to create thin volume with id '$id' in pool '$pool_dev'."
		echo "$0: It might already exists, trying anyway..."
	fi
	if ! dmsetup_create_noudevsync "$name" "0 $size thin $pool_dev $id $backing_dev"; then
		echo "$0: Failed to create external snapshot named '$name':"
		echo "  Size:           $size"
		echo "  Backing device: $backing_dev"
		echo "  Thin volume id: $id"
		return 1
	fi
	return 0
}

# Find NTFS partitions with decently sized ranges of
# free space. We can use these as our writable layer
# for our thin-pool, if configured.
# If suitable, this will create the file $ntfs_list with
# one line per suitable partition, format
# total_size_blocks devpath
# Results are sorted by size, descending order
find_ntfs_partitions() {
	[ -z "$SLX_NTFSFREE" ] && return
	[ "$SLX_NTFSFREE" = "never" ] && return
	[ -e "$ntfs_list" ] && return
	if ! command -v ntfsfree &> /dev/null; then
		echo "$0: ntfsfree not found, cannot use NTFS partitions as RW layer"
		return
	fi
	local part sum
	for part in /dev/disk/by-partuuid/*; do
		# Only count ranges >= 256MB, sum will be in number of 512b blocks
		sum="$( ntfsfree --block-size 512 --min-size "$(( 256 * 1024 * 1024 ))" "$part" \
			| awk -v sum=0 '{if ($1 == "Range") sum += $4}END{printf "%.0f", sum}' )"
		# Only consider volume if sum of these ranges > 1GB (this is BLOCKS, not bytes)
		(( "$sum" > 2 * 1024 * 1024 )) || continue
		echo "$sum $part" # only thing in loop going to stdout
	done | sort -nr > "$ntfs_list"
}

# Now decide what to do for the writable layer

if [ -n "$thin_snapshot" ] || [ -n "$thin_volume" ]; then
	if ! create_pool ; then
		echo "Failed to create thin pool. Will ignore:"
		echo -e "\tThin snapshot: $(declare -p thin_snapshot)"
		echo -e "\tThin volumes: $(declare -p thin_volume)"
		ramdisk_fallback
	fi
	# the order in which pool devices are created does not matter
	# so start with thin volumes starting with id 2 and end with
	# the thin-snapshot with id 1 which needs to call finish_setup.
	volume_id=2
	# go over thin-volumes
	for line in "${thin_volume[@]}"; do
		[ -z "$line" ] && continue
		read -r name crypt min max ignore <<< "$line"
		# thin-volume can be created with max size,
		# since they are overprovisioned anyway.
		if ! create_volume "$name" "$(( volume_id++ ))" "$max"; then
			echo "Failed to create thin volume '$name'."
		fi
		save_partition_info "$name" "*" "1" "${writable_device_size}-${max}"
		if [ "$crypt" -ne 0 ] && ! encrypt_device \
			"/dev/mapper/$name" "$name-crypt" "$max"; then
			echo "Failed to encrypt thin volume '$name'."
		fi
	done

	if [ -n "$thin_snapshot" ]; then
		# create thin-snapshot, use first one
		read -r name crypt min max ignore <<< "$thin_snapshot"
		# min/max was used for the pool data device, ignore it here!
		# NOTE: the filesystem will most likely malfunction if the size of the
		# thin-snapshot is smaller than what it was upon creation.
		# As such, the size of the thin-snapshot can only be $writable_device_size
		# if it is larger than $read_only_device_size, otherwise we should only
		# use $read_only_device_size. While live-shrinking the filesystem might be
		# an option, it is not supported throughout all fileystems (xfs can't).
		if (( writable_device_size >= read_only_device_size )); then
			thin_snapshot_size="$writable_device_size"
		else
			thin_snapshot_size="$read_only_device_size"
		fi
		# For later on-demand growing
		if (( root_ntfs_extra > 0 )); then
			thin_snapshot_size="$(( thin_snapshot_size + root_ntfs_extra ))"
		fi
		if ! create_volume "$name" 1 "$thin_snapshot_size" "$read_only_device"; then
			echo "Failed to create external snapshot for '$read_only_device'."
			ramdisk_fallback
		fi
		finish_setup "$name" "1" "$thin_snapshot_size"
	fi
fi

###
##	SNAPSHOT (OLD FUNCTIONALITY)
###
if [ -n "$snapshot" ]; then
	read -r name crypt min max ignore <<< "$snapshot"
	if ! create_snapshot "$name $persist"; then
		echo "Failed to create regular snapshot for '$read_only_device' on '$writable_device'."
		ramdisk_fallback
	fi
	finish_setup "$name" "1" "$writable_device_size"
fi

# ultimate fallback
ramdisk_fallback
exit 1