File: merge.c

package info (click to toggle)
ploop 1.15-12
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,372 kB
  • sloc: ansic: 16,133; sh: 413; makefile: 222; python: 144
file content (1349 lines) | stat: -rw-r--r-- 32,429 bytes parent folder | download
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
/*
 *  Copyright (C) 2008-2015, Parallels, Inc. All rights reserved.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <malloc.h>
#include <sys/stat.h>
#include <sys/mount.h>
#include <limits.h>
#include <getopt.h>
#include <linux/types.h>
#include <string.h>
#include <assert.h>

#include "ploop.h"

static int sync_cache(struct delta * delta)
{
	int skip = 0;

	if (!delta->l2_dirty)
		return 0;

	/* Sync data before we write out new index table. */
	if (fsync(delta->fd)) {
		ploop_err(errno, "fsync");
		return -1;
	}

	if (delta->l2_cache < 0) {
		ploop_err(0, "abort: delta->l2_cache < 0");
		return -1;
	}
	if (delta->l2_cache >= delta->l1_size) {
		ploop_err(0, "abort: delta->l2_cache >= delta->l1_size");
		return -1;
	}

	if (delta->l2_cache == 0)
		skip = sizeof(struct ploop_pvd_header);

	/* Write index table */
	if (PWRITE(delta, (__u8 *)delta->l2 + skip,
				S2B(delta->blocksize) - skip,
				(off_t)delta->l2_cache * S2B(delta->blocksize) + skip))
		return SYSEXIT_WRITE;

	/* Sync index table. We can delay this, but this does not
	 * improve performance
	 */
	if (fsync(delta->fd)) {
		ploop_err(errno, "fsync");
		return -1;
	}
	delta->l2_dirty = 0;
	return 0;
}

static int locate_l2_entry(struct delta_array *p, int level, int i, __u32 k, int *out)
{
	__u64 cluster;
	for (level++; level < p->delta_max; level++) {
		if (p->delta_arr[level].l2_cache == -1) {
			if (i >= p->delta_arr[level].l1_size)
				break; /* grow is monotonic! */
			cluster = S2B(p->delta_arr[level].blocksize);
			if (PREAD(&p->delta_arr[level], p->delta_arr[level].l2,
						cluster, (off_t)i * cluster))
				return SYSEXIT_READ;
			p->delta_arr[level].l2_cache = i;
		}
		if (p->delta_arr[level].l2[k]) {
			*out = level;
			return 0;
		}
	}
	*out = -1;
	return 0;
}

static int grow_lower_delta(const char *device, int top, int start_level, int end_level)
{
	off_t src_size = 0; /* bdsize of source delta to merge */
	off_t dst_size = 0; /* bdsize of destination delta for merge */
	char *src_image = NULL;
	char *dst_image = NULL;
	int i, devfd;
	struct ploop_pvd_header *vh;
	struct grow_maps grow_maps;
	char *fmt;
	int dst_is_raw = 0;
	void *buf = NULL;
	struct delta odelta = {};
	int ret;
	__u64 cluster;

	if (top) {
		if ((ret = ploop_get_size(device, &src_size)))
			return ret;
	} else {
		if (find_delta_names(device, end_level, end_level,
				     &src_image, &fmt)) {
			ploop_err(errno, "find_delta_names");
			ret = SYSEXIT_SYSFS;
			goto done;
		}

		if ((ret = read_size_from_image(src_image, 0, &src_size)))
			goto done;
	}

	if (find_delta_names(device, start_level, start_level,
			     &dst_image, &fmt)) {
		ploop_err(errno, "find_delta_names");
		ret = SYSEXIT_SYSFS;
		goto done;
	}

	if (strcmp(fmt, "raw") == 0)
		dst_is_raw = 1;

	if ((ret = read_size_from_image(dst_image, dst_is_raw, &dst_size)))
		goto done;

	if (src_size <= dst_size) {
		ret = 0;
		goto done;
	}

	if (dst_is_raw) {
		ret = grow_raw_delta(dst_image, S2B(src_size - dst_size));
		goto done;
	}

	/* Here we know for sure that destination delta is in ploop1 format */
	if (open_delta(&odelta, dst_image, O_RDWR, OD_NOFLAGS)) {
		ploop_err(errno, "open_delta");
		ret = SYSEXIT_OPEN;
		goto done;
	}

	if (dirty_delta(&odelta)) {
		ploop_err(errno, "dirty_delta");
		ret = SYSEXIT_WRITE;
		goto done;
	}
	cluster = S2B(odelta.blocksize);
	if (p_memalign(&buf, 4096, cluster)) {
		ret = SYSEXIT_MALLOC;
		goto done;
	}

	/* relocate blocks w/o nullifying them and changing on-disk header */
	if ((ret = grow_delta(&odelta, src_size, buf, &grow_maps)))
		goto done;

	if (clear_delta(&odelta)) {
		ploop_err(errno, "clear_delta");
		ret = SYSEXIT_WRITE;
		goto done;
	}

	devfd = open(device, O_RDONLY);
	if (devfd < 0) {
		ploop_err(errno, "open dev");
		ret = SYSEXIT_DEVICE;
		goto done;
	}

	/* update in-core map_node mappings for relocated blocks */
	grow_maps.ctl->level = start_level;
	ret = ioctl_device(devfd, PLOOP_IOC_UPDATE_INDEX, grow_maps.ctl);
	close(devfd);
	if (ret)
		goto done;

	/* nullify relocated blocks on disk */
	memset(buf, 0, cluster);
	for (i = 0; i < grow_maps.ctl->n_maps; i++)
		if (PWRITE(&odelta, buf, cluster,
			   (off_t)(grow_maps.zblks[i]) * cluster)) {
			ret = SYSEXIT_WRITE;
			goto done;
		}

	/* save new image header of destination delta on disk */
	vh = (struct ploop_pvd_header *)buf;
	generate_pvd_header(vh, src_size, odelta.blocksize, odelta.version);
	if (PREAD(&odelta, &vh->m_Flags, sizeof(vh->m_Flags),
		  offsetof(struct ploop_pvd_header, m_Flags))) {
		ret = SYSEXIT_READ;
		goto done;
	}
	if (PWRITE(&odelta, vh, sizeof(*vh), 0)) {
		ret = SYSEXIT_WRITE;
		goto done;
	}

	if (fsync(odelta.fd)) {
		ploop_err(errno, "fsync");
		ret = SYSEXIT_FSYNC;
	}

done:
	free(buf);
	free(src_image);
	free(dst_image);
	close_delta(&odelta);
	return ret;
}

int get_delta_info(const char *device, struct merge_info *info)
{
	char *fmt;

	if (ploop_get_attr(device, "top", &info->top_level)) {
		ploop_err(0, "Can't find top delta");
		return SYSEXIT_SYSFS;
	}

	if (info->top_level == 0) {
		ploop_err(0, "Single delta, nothing to merge");
		return SYSEXIT_PARAM;
	}

	if (info->end_level == 0)
		info->end_level = info->top_level;

	if (info->end_level > info->top_level ||
	    info->start_level > info->end_level)
	{
		ploop_err(0, "Illegal top level");
		return SYSEXIT_SYSFS;
	}

	if (info->end_level == info->top_level) {
		int running;

		if (ploop_get_attr(device, "running", &running)) {
			ploop_err(0, "Can't get running attr");
			return SYSEXIT_SYSFS;
		}

		if (running) {
			int ro;

			if (ploop_get_delta_attr(device, info->top_level, "ro", &ro)) {
				ploop_err(0, "Can't get ro attr");
				return SYSEXIT_SYSFS;
			}
			if (!ro)
				info->merge_top = 1;
		}
	}
	info->names = calloc(1, (info->end_level - info->start_level + 2) * sizeof(char*));
	if (info->names == NULL) {
		ploop_err(errno, "malloc");
		return SYSEXIT_MALLOC;
	}
	if (find_delta_names(device, info->start_level, info->end_level, info->names, &fmt))
		return SYSEXIT_SYSFS;
	if (strcmp(fmt, "raw") == 0)
		info->raw = 1;

	return 0;
}

/* Merge one or more deltas (specified by **images and start/end_level).
 * Merge can be online or offline, with or without top delta, to either
 * a lowest speicifed delta or to a new_image.
 *
 * Parameters:
 *  dev		ploop device (for online merge) or NULL (for offline merge)
 *  start_level	start (lower) delta level to merge (online only)
 *  end_level	end (higher) delta level to merge (online only)
 *  raw		set to 1 if merging to base delta which is raw delta
 *  merge_top	set to 1 is top rw delta is to be merged (online only)
 *  images	list of delta files to be merged, from top to bottom
 *  new_image	new image file name to merge to (NULL to merge to lowest delta)
 *
 * Returns: 0 or SYSEXIT_* error
 */
int merge_image(const char *device, int start_level, int end_level, int raw, int merge_top,
		      char **images, const char *new_image)
{
	int last_delta = 0;
	char **names = NULL;
	struct delta_array da = {};
	struct delta odelta = {};
	int i, i_end, ret = 0;
	__u32 k;
	__u32 allocated = 0;
	__u64 cluster;
	void *data_cache = NULL;
	__u32 blocksize = 0;
	__u32 prev_blocksize = 0;
	int version = PLOOP_FMT_UNDEFINED;
	const char *merged_image;

	if (new_image && access(new_image, F_OK) == 0) {
		ploop_err(EEXIST, "Can't merge to new image %s", new_image);
		return SYSEXIT_PARAM;
	}

	if (device) {
		/* Online merge */
		if (start_level >= end_level || start_level < 0) {
			ploop_err(0, "Invalid parameters: start_level %d end_level %d",
					start_level, end_level);
			return SYSEXIT_PARAM;
		}
		if (merge_top) {
			/* top delta is in running state merged
			by means of PLOOP_IOC_MERGE */
			end_level--;
			names = ++images;
			if (end_level <= start_level)
				end_level = 0;
		} else
			names = images;

		if (!new_image)
			if ((ret = grow_lower_delta(device, merge_top,
						start_level, end_level)))
				return ret;

		if (end_level == 0) {
			int lfd;

			if (new_image) {
				/* Special case: only one delta below top one:
				 * copy it to new_image and do ploop_replace()
				 */
				ret = copy_delta(names[0], new_image);
				if (ret)
					return ret;

				ret = replace_delta(device, start_level, new_image);
				if (ret)
					goto rm_delta;
			}
			ploop_log(0, "Merging top delta");
			lfd = open(device, O_RDONLY);
			if (lfd < 0) {
				ploop_err(errno, "open dev %s", device);
				ret = SYSEXIT_DEVICE;
				goto rm_delta;
			}

			ret = ioctl_device(lfd, PLOOP_IOC_MERGE, 0);
			close(lfd);

rm_delta:
			if (ret && new_image)
				unlink(new_image);

			return ret;
		}
		last_delta = end_level - start_level;
	} else {
		last_delta = get_list_size(images) - 1;
		names = images;
	}

	if (new_image) {
		last_delta++;
		merged_image = new_image;
	}
	else {
		merged_image = names[last_delta];
	}

	init_delta_array(&da);

	for (i = 0; i < last_delta; i++) {
		// FIXME: add check for blocksize
		ret = extend_delta_array(&da, names[i],
					device ? O_RDONLY|O_DIRECT : O_RDONLY,
					device ? OD_NOFLAGS : OD_OFFLINE);
		if (ret)
			goto merge_done2;

		blocksize = da.delta_arr[i].blocksize;
		if (i != 0 && blocksize != prev_blocksize) {
			ploop_err(errno, "Wrong blocksize %s bs=%d [prev bs=%d]",
					names[i], blocksize, prev_blocksize);
			ret = SYSEXIT_PLOOPFMT;
			goto merge_done2;
		}
		prev_blocksize = blocksize;

		if (i != 0 && version != da.delta_arr[i].version) {
			ploop_err(errno, "Wrong version %s %d [prev %d]",
					names[i], da.delta_arr[i].version, version);
			ret = SYSEXIT_PLOOPFMT;
			goto merge_done2;
		}
		version = da.delta_arr[i].version;
	}
	if (blocksize == 0) {
		ploop_err(errno, "Wrong blocksize 0");
		ret = SYSEXIT_PLOOPFMT;
		goto merge_done2;

	}
	cluster = S2B(blocksize);

	if (new_image) { /* Create it */
		struct ploop_pvd_header *vh;
		off_t size;
		int mode = (raw) ? PLOOP_RAW_MODE : PLOOP_EXPANDED_MODE;

		vh = (struct ploop_pvd_header *)da.delta_arr[0].hdr0;
		size = get_SizeInSectors(vh);

		ret = create_image(new_image, blocksize, size, mode, version);
		if (ret)
			goto merge_done2;
	}

	if (!raw) {
		if (open_delta(&odelta, merged_image, O_RDWR,
			       device ? OD_NOFLAGS : OD_OFFLINE)) {
			ploop_err(errno, "open_delta");
			ret = SYSEXIT_OPEN;
			goto merge_done2;
		}
		if (dirty_delta(&odelta)) {
			ploop_err(errno, "dirty_delta");
			ret = SYSEXIT_WRITE;
			goto merge_done2;
		}
	} else {
		if (open_delta_simple(&odelta, merged_image, O_RDWR,
				      device ? 0 : OD_OFFLINE)) {
			ret = SYSEXIT_WRITE;
			goto merge_done2;
		}
	}
	if (p_memalign(&data_cache, 4096, cluster)) {
		ret = SYSEXIT_MALLOC;
		goto merge_done2;
	}

	if (!device && !new_image) {
		struct ploop_pvd_header *vh;
		vh = (struct ploop_pvd_header *)da.delta_arr[0].hdr0;

		if (!raw) {
			if ((ret = grow_delta(&odelta, get_SizeInSectors(vh),
				   data_cache, NULL)))
				goto merge_done;
		} else {
			off_t src_size = get_SizeInSectors(vh);
			off_t dst_size;

			ret = read_size_from_image(merged_image, 1, &dst_size);
			if (ret)
				goto merge_done;

			if (src_size > dst_size) {
				ret = grow_raw_delta(merged_image,
					       S2B(src_size - dst_size));
				if (ret)
					goto merge_done;
			}
		}
	}

	i_end = (da.delta_arr[0].l2_size + PLOOP_MAP_OFFSET + cluster/4 - 1) /
		(cluster/4);
	for (i = 0; i < i_end; i++) {
		int k_start = 0;
		int k_end   = cluster/4;

		/* Load L2 table */
		if (PREAD(&da.delta_arr[0], da.delta_arr[0].l2,
			  cluster, (off_t)i * cluster)) {
			ret = SYSEXIT_READ;
			goto merge_done;
		}

		/* Announce L2 cache valid. This information is not used. */
		da.delta_arr[0].l2_cache = i;

		/* And invalidate L2 cache for lower delta, they will
		 * be fetched on demand.
		 */
		for (k = 1; k < last_delta; k++)
			da.delta_arr[k].l2_cache = -1;

		/* Iterate over all L2 entries */
		if (i == 0)
			k_start = PLOOP_MAP_OFFSET;
		if (i == i_end - 1)
			k_end   = da.delta_arr[0].l2_size + PLOOP_MAP_OFFSET -
				  i * cluster/4;

		for (k = k_start; k < k_end; k++) {
			int level2 = 0;

			/* If entry is not present in base level,
			 * lookup lower deltas.
			 */
			if (da.delta_arr[0].l2[k] == 0) {
				ret = locate_l2_entry(&da, 0, i, k, &level2);
				if (ret)
					goto merge_done;
				if (level2 < 0)
					continue;
			}

			if (PREAD(&da.delta_arr[level2], data_cache, cluster,
						S2B(ploop_ioff_to_sec(da.delta_arr[level2].l2[k],
								blocksize, version)))) {
				ret = SYSEXIT_READ;
				goto merge_done;
			}

			if (raw) {
				off_t opos;
				opos = i * (cluster/4) + k - PLOOP_MAP_OFFSET;
				if (PWRITE(&odelta, data_cache, cluster,
					   opos*cluster)) {
					ret = SYSEXIT_WRITE;
					goto merge_done;
				}
				continue;
			}

			if (i != odelta.l2_cache) {
				if (odelta.l2_cache >= 0)
					if ((ret = sync_cache(&odelta)))
						goto merge_done;

				odelta.l2_cache = i;
				if (PREAD(&odelta, odelta.l2, cluster,
					  (off_t)(i * cluster))) {
					ret = SYSEXIT_READ;
					goto merge_done;
				}
				odelta.l2_dirty = 0;
			}

			if (odelta.l2[k] == 0) {
				odelta.l2[k] = ploop_sec_to_ioff((off_t)odelta.alloc_head++ * B2S(cluster),
							blocksize, version);
				if (odelta.l2[k] == 0) {
					ploop_err(0, "abort: odelta.l2[k] == 0");
					ret = SYSEXIT_ABORT;
					goto merge_done;
				}
				odelta.l2_dirty = 1;
				allocated++;
			}
			if (PWRITE(&odelta, data_cache, cluster,
						S2B(ploop_ioff_to_sec(odelta.l2[k],
								blocksize, version)))) {
				ret = SYSEXIT_WRITE;
				goto merge_done;
			}
		}
	}

	if (fsync(odelta.fd)) {
		ploop_err(errno, "fsync");
		ret = SYSEXIT_FSYNC;
		goto merge_done;
	}

	if (odelta.l2_dirty) {
		int skip = 0;

		if (odelta.l2_cache < 0) {
			ploop_err(0, "abort: odelta.l2_cache < 0");
			ret = SYSEXIT_ABORT;
			goto merge_done;
		}
		if (odelta.l2_cache >= odelta.l1_size) {
			ploop_err(0, "abort: odelta.l2_cache >= odelta.l1_size");
			ret = SYSEXIT_ABORT;
			goto merge_done;
		}

		if (odelta.l2_cache == 0)
			skip = sizeof(struct ploop_pvd_header);

		if (PWRITE(&odelta, (__u8 *)odelta.l2 + skip,
					cluster - skip,
					(off_t)odelta.l2_cache * cluster + skip)) {
			ret = SYSEXIT_WRITE;
			goto merge_done;
		}
		if (fsync(odelta.fd)) {
			ploop_err(errno, "fsync");
			ret = SYSEXIT_FSYNC;
			goto merge_done;
		}
	}

	if (!raw && clear_delta(&odelta)) {
		ploop_err(errno, "clear_delta");
		ret = SYSEXIT_WRITE;
	} else {
		if (fsync(odelta.fd)) {
			ploop_err(errno, "fsync");
			ret = SYSEXIT_FSYNC;
		}
	}

merge_done:
	close_delta(&odelta);

	if (device && !ret) {
		int lfd;
		__u32 level;

		lfd = open(device, O_RDONLY);
		if (lfd < 0) {
			ploop_err(errno, "open dev");
			ret = SYSEXIT_DEVICE;
			goto merge_done2;
		}

		if (new_image) {
			int fd;

			fd = open(new_image, O_DIRECT | O_RDONLY);
			if (fd < 0) {
				ploop_err(errno, "Can't open %s", new_image);
				ret = SYSEXIT_OPEN;
				goto close_lfd;
			}
			ret = do_replace_delta(lfd, start_level, fd, blocksize, new_image);
			close(fd);
			if (ret)
				goto close_lfd;
		}

		level = start_level + 1;

		for (i = start_level + 1; i <= end_level; i++) {
			ret = ioctl_device(lfd, PLOOP_IOC_DEL_DELTA, &level);
			if (ret) {
				close(lfd);
				goto merge_done2;
			}
		}

		if (merge_top) {
			ploop_log(0, "Merging top delta");
			ret = ioctl_device(lfd, PLOOP_IOC_MERGE, 0);
		}
close_lfd:
		close(lfd);
	}
merge_done2:
	free(data_cache);
	deinit_delta_array(&da);
	return ret;
}

/* Only call after ploop_di_can_merge() returned 0 */
int check_snapshot_mounts(struct ploop_disk_images_data *di,
		const char *ancestor_guid, const char *descendant_guid)
{
	const char *guid = descendant_guid;

	while (1) {
		int idx, temp, ret;
		const char *fname;

		idx = find_snapshot_by_guid(di, guid);
		if (idx == -1) {
			ploop_err(0, "Can't find snapshot by guid %s",
					guid);
			return SYSEXIT_DISKDESCR;
		}

		fname = find_image_by_guid(di, guid);
		if (!fname) {
			ploop_err(0, "Can't find image by guid %s",
					guid);
			return SYSEXIT_DISKDESCR;
		}

		temp = di->snapshots[idx]->temporary;

		ret = check_snapshot_mount(di, guid, fname, temp);
		if (ret)
			return ret;

		if (!guidcmp(guid, ancestor_guid))
			break;

		guid = di->snapshots[idx]->parent_guid;
		if (!strcmp(guid, NONE_UUID)) {
			/* can't happen */
			ploop_err(0, "Unexpectedly found %s to be base", guid);
			return SYSEXIT_DISKDESCR;
		}
	}

	return 0;
}

/* Logs a line showing deltas to merge and the merge destination,
 * that looks something like these:
 *
 *	Merging image: delta_file -> parent_delta_file
 *
 *	Merging images: delta_file_1 file_2 file_3 -> (new) new_delta
 */
static void log_merge_images_info(struct ploop_disk_images_data *di,
		char **names, const char *new_delta)
{
	char basedir[PATH_MAX];
	char imglist[LOG_BUF_SIZE];
	char merged_image[PATH_MAX];
	int i, pos = 0, nimg;

	get_basedir(di->runtime->xml_fname, basedir, sizeof(basedir));

	nimg = get_list_size(names) - 1;
	if (new_delta) {
		nimg++;
		// merged_image = new_delta;
		normalize_image_name(basedir, new_delta,
				merged_image, sizeof(merged_image));
	}
	else {
		// merged_image = names[nimg];
		normalize_image_name(basedir, names[nimg],
				merged_image, sizeof(merged_image));
	}

	for (i = 0; i < nimg; i++) {
		int n;
		char img[PATH_MAX];

		normalize_image_name(basedir, names[i], img, sizeof(img));
		n = snprintf(imglist + pos, sizeof(imglist) - pos, "%s ", img);
		if (n <= 0)
			// error?
			break;
		pos += n;
		if (pos >= sizeof(imglist))
			// output truncated!
			break;
	}

	ploop_log(0, "Merging image%s: %s-> %s%s",
			nimg > 1 ? "s" : "",
			imglist,
			new_delta ? "(new) " : "", merged_image);
}

int ploop_merge_snapshot_by_guid(struct ploop_disk_images_data *di,
		const char *guid, const char *new_delta)
{
	char conf[PATH_MAX-4];
	char conf_tmp[PATH_MAX];
	char dev[64];
	char *device = NULL;
	char *parent_fname = NULL;
	char *child_fname = NULL;
	char *delete_fname = NULL;
	const char *child_guid = NULL;
	const char *parent_guid = NULL;
	char *names[3] = {};
	int ret;
	int start_level = -1;
	int end_level = -1;
	int merge_top = 0;
	int raw = 0;
	int online = 0;
	int parent_idx, child_idx; /* parent and child snapshot ids */
	struct merge_info info = {};
	int i, nelem;

	ret = SYSEXIT_PARAM;

	child_guid = guid;
	parent_guid = ploop_find_parent_by_guid(di, guid);
	if (!parent_guid) {
		ploop_err(0, "Can't find parent of uuid %s "
				"(is that a base image?)", guid);
		goto err;
	}

	child_fname = find_image_by_guid(di, child_guid);
	if (child_fname == NULL) {
		ploop_err(0, "Can't find image by uuid %s",
				child_guid);
		goto err;
	}
	parent_fname = find_image_by_guid(di, parent_guid);
	if (parent_fname == NULL) {
		ploop_err(0, "Can't find image by uuid %s",
				parent_guid);
		goto err;
	}
	parent_idx = find_snapshot_by_guid(di, parent_guid);
	if (parent_idx == -1) {
		ploop_err(0, "Can't find snapshot by uuid %s",
				parent_guid);

		goto err;
	}
	child_idx = find_snapshot_by_guid(di, child_guid);
	if (child_idx == -1) {
		ploop_err(0, "Can't find snapshot by uuid %s",
				child_guid);

		goto err;
	}

	nelem = ploop_get_child_count_by_uuid(di, parent_guid);
	if (nelem > 1) {
		ploop_err(0, "Can't merge to snapshot %s: it has %d children",
				parent_guid, nelem);
		ret = SYSEXIT_PARAM;
		goto err;
	}

	ret = ploop_find_dev_by_dd(di, dev, sizeof(dev));
	if (ret == -1) {
		ret = SYSEXIT_SYS;
		goto err;
	}
	else if (ret == 0)
		online = 1;

	if (online) {
		ret = complete_running_operation(di, dev);
		if (ret)
			goto err;
		if ((ret = get_delta_info(dev, &info)))
			goto err;
		nelem = get_list_size(info.names);
		for (i = 0; info.names[i] != NULL; i++) {
			ret = ploop_fname_cmp(info.names[i], child_fname);
			if (ret == -1) {
				goto err;
			} else if (ret == 0) {
				child_fname = info.names[i];
				end_level = nelem - i - 1;
				continue;
			}
			ret = ploop_fname_cmp(info.names[i], parent_fname);
			if (ret == -1)
				goto err;
			else if (ret == 0) {
				parent_fname = info.names[i];
				start_level = nelem - i - 1;
			}
		}

		if (end_level != -1 && start_level != -1) {
			if (end_level != start_level + 1) {
				ploop_err(0, "Inconsistency detected %s [%d] %s [%d]",
						parent_fname, end_level, child_fname, start_level);
				ret = SYSEXIT_PARAM;
				goto err;
			}
			device = dev;
			if (start_level == 0)
				raw = info.raw;
			merge_top = (info.top_level == end_level);
		} else if (end_level == -1 && start_level == -1) {
			online = 0;
		} else {
			ploop_err(0, "Inconsistency detected %s [%d] %s [%d]",
					parent_fname, end_level, child_fname, start_level);
			ret = SYSEXIT_PARAM;
			goto err;
		}
	}

	if (!online) {
		start_level = 0;
		end_level = 1;
		/* Only base image could be in RAW format */
		if (di->mode == PLOOP_RAW_MODE &&
				!guidcmp(di->snapshots[parent_idx]->parent_guid, NONE_UUID))
			raw = 1;
	}

	names[0] = delete_fname = strdup(child_fname);
	if (names[0] == NULL) {
		ret = SYSEXIT_MALLOC;
		goto err;
	}
	names[1] = strdup(parent_fname);
	if (names[1] == NULL) {
		ret = SYSEXIT_MALLOC;
		goto err;
	}
	names[2] = NULL;

	ret = check_snapshot_mount(di, parent_guid, parent_fname,
			di->snapshots[parent_idx]->temporary);
	if (ret)
		goto err;
	ret = check_snapshot_mount(di, child_guid, child_fname,
			di->snapshots[child_idx]->temporary);
	if (ret)
		goto err;

	ploop_log(0, "%sline %s merge %s -> %s%s",
			online ? "On": "Off",
			get_snap_str(di->snapshots[parent_idx]->temporary),
			child_guid, parent_guid,
			raw ? " (raw)" : "");

	log_merge_images_info(di, names, new_delta);

	/* make validation before real merge */
	ret = ploop_di_merge_image(di, child_guid);
	if (ret)
		goto err;
	/* We can't use parent_guid and child_guid below, since one of them
	 * is already free()'d in ploop_di_merge_image().
	 * Hint the compiler/static analyser to error out if they are used.
	 */
	parent_guid = child_guid = NULL;

	get_disk_descriptor_fname(di, conf, sizeof(conf));
	snprintf(conf_tmp, sizeof(conf_tmp), "%s.tmp", conf);
	ret = ploop_store_diskdescriptor(conf_tmp, di);
	if (ret)
		goto err;

	ret = merge_image(device, start_level, end_level, raw, merge_top, names, new_delta);
	if (ret)
		goto err;

	if (new_delta) {
		/* Write new delta name to dd.xml, and remove the old file.
		 * Note we can only write new delta now after merge_image()
		 * as the file is created and we can use realpath() on it.
		 */
		int idx;
		char *oldimg, *newimg;

		newimg = realpath(new_delta, NULL);
		if (!newimg) {
			ploop_err(errno, "Error in realpath(%s)", new_delta);
			ret = SYSEXIT_PARAM;
			goto err;
		}

		idx = find_image_idx_by_guid(di, child_guid);
		if (idx == -1) {
			ploop_err(0, "Unable to find image by uuid %s",
					child_guid ? child_guid : "NULL");
			ret = SYSEXIT_PARAM;
			goto err;
		}

		oldimg = di->images[idx]->file;
		di->images[idx]->file = newimg;

		ret = ploop_store_diskdescriptor(conf_tmp, di);
		if (ret)
			goto err;

		ploop_log(0, "Removing %s", oldimg);
		ret = unlink(oldimg);
		if (ret) {
			ploop_err(errno, "unlink %s", oldimg);
			ret = SYSEXIT_UNLINK;
		}

		free(oldimg);
	}

	if (rename(conf_tmp, conf)) {
		ploop_err(errno, "Can't rename %s %s",
				conf_tmp, conf);
		ret = SYSEXIT_RENAME;
		goto err;
	}

	ploop_log(0, "Removing %s", delete_fname);
	if (unlink(delete_fname)) {
		ploop_err(errno, "unlink %s", delete_fname);
		ret = SYSEXIT_UNLINK;
	}

	if (ret == 0)
		ploop_log(0, "ploop snapshot has been successfully merged");
	else
		ploop_err(0, "failed to merge ploop snapshot");

err:
	for (i = 0; names[i] != NULL; i++)
		free(names[i]);

	ploop_free_array(info.names);

	return ret;
}

/* Given a device and any two deltas, figure out if a merge between these
 * is online or offline. For online case, fill in the merge parameters.
 *
 * Parameters:
 *   dev	ploop device
 *   anc_fname	ancestor (grand parent) image file name
 *   dsc_fname	descentant (grand child) image file name
 *
 * Returns:
 *   0 or SYSEXIT_* error
 *
 * Returned data:
 *   *online		1 if this is online merge and the following data:
 *   mi->start_level	start level to merge
 *   mi->end_level	end level to merge
 *   mi->raw		whether base delta is raw
 *   mi->top_level	device top level
 *   mi->merge_top	whether top level is affected
 *   mi->names		list of deltas to merge, from descendant to ancestor
 */
static int prepare_online_merge(const char *dev,
		const char *anc_fname, const char *dsc_fname,
		int *online, struct merge_info *mi)
{
	struct merge_info info = {};
	int i;
	int anc_idx = -1, dsc_idx = -1; /* indexes in info */
	int ret;

	ret = get_delta_info(dev, &info);
	if (ret)
		return ret;

	ret = SYSEXIT_FSTAT;
	/* Try to find both images among deltas in running ploop */
	for (i = 0; info.names[i] != NULL; i++) {
		int r;

		if (dsc_idx == -1) {
			r = ploop_fname_cmp(info.names[i], dsc_fname);
			if (r == -1)
				goto out;
			else if (r == 0) {
				dsc_idx = i;
				continue;
			}
		}
		if (anc_idx == -1) {
			r = ploop_fname_cmp(info.names[i], anc_fname);
			if (r == -1)
				goto out;
			else if (r == 0) {
				anc_idx = i;
				continue;
			}
		}
	}

	/* Figure out if it's online, offline, or mixed case */
	if (anc_idx != -1 && dsc_idx != -1) {
		/* found both deltas: ONLINE */
		int nelem, i, idx;

		*online = 1;
		nelem = get_list_size(info.names);
		mi->start_level = nelem - anc_idx - 1;
		mi->end_level = nelem - dsc_idx - 1;
		if (mi->end_level <= mi->start_level) {
			ploop_err(0, "Inconsistency: end_level <= start_level"
					" (%d <= %d)",
					mi->end_level, mi->start_level);
			ret = SYSEXIT_PARAM;
			goto out;
		}

		mi->names = calloc(mi->end_level - mi->start_level + 2,
				sizeof(char *));
		if (!mi->names) {
			ploop_err(errno, "Can't malloc");
			ret = SYSEXIT_MALLOC;
			goto out;
		}
		/* Copy part of names we are interested in */
		for (i = 0, idx = dsc_idx; idx <= anc_idx; idx++, i++)
			mi->names[i] = strdup(info.names[idx]);

		/* set the needed flags */
		mi->raw = (mi->start_level == 0) ? info.raw : 0;
		mi->top_level = info.top_level;
		mi->merge_top = (info.top_level == mi->end_level);

		ret = 0;
	}
	else if (anc_idx == -1 && dsc_idx == -1) {
		/* no used deltas found: OFFLINE */
		*online = 0;
		ret = 0;
	}
	else {
		/* Some deltas found: mixed case */
		ploop_err(0, "Can't do mixed merge (some deltas "
				"are online, some are offline)");
		ret = SYSEXIT_PARAM;
	}
out:
	ploop_free_array(info.names);

	return ret;
}

/* Given two snapshot guids, fill in the merge info (for offline case)
 *
 * Parameters:
 *   di			disk descriptor info
 *   ancestor_guid	ancestor (grand parent, lower) guid
 *   descendant_guid	descentant (grand child, higher) guid
 *
 * Returns:
 *   0 or SYSEXIT_* error
 *
 * Returned data:
 *   mi->raw		whether base delta is raw
 *   mi->names		list of deltas to merge, from descentant to ancestor
 */
static int prepare_offline_merge(struct ploop_disk_images_data *di,
		const char *ancestor_guid, const char *descendant_guid,
		struct merge_info *mi)
{
	int ret = 0;

	mi->names = make_images_list_by_guids(di,
			descendant_guid, ancestor_guid, 1);
	if (!mi->names)
		/* error is printed by make_images_list_by_guids */
		return SYSEXIT_SYS;

	if (di->mode == PLOOP_RAW_MODE) {
		int i;

		/* We should set raw=1 if merging down to base image */
		i = find_snapshot_by_guid(di, ancestor_guid);
		if (i == -1) { /* should not ever happen */
			ploop_err(0, "Can't find snapshot by guid %s",
					ancestor_guid);
			ret = SYSEXIT_PARAM;
			goto out;
		}
		if (strcmp(di->snapshots[i]->parent_guid, NONE_UUID) == 0)
			mi->raw = 1;
	}

out:
	if (ret && mi->names)
		ploop_free_array(mi->names);

	return ret;
}

/* Merge multiple snapshots by a range of GUIDs */
int ploop_merge_snapshots_by_guids(struct ploop_disk_images_data *di,
		const char *descendant_guid, const char *ancestor_guid,
		const char *new_delta)
{
	int i, ret;
	int online;
	char dev[64] = "";
	struct merge_info info = {};
	char conf[PATH_MAX-4];
	char conf_tmp[PATH_MAX];

	/* Can we merge these? */
	ret = ploop_di_can_merge_images(di, ancestor_guid, descendant_guid);
	if (ret)
		return ret;

	/* Is it online or offline merge? */
	ret = ploop_find_dev_by_dd(di, dev, sizeof(dev));
	if (ret == -1)
		return SYSEXIT_SYS;
	online = !ret;
	if (online) {
		const char *anc_fname, *dsc_fname;

		anc_fname = find_image_by_guid(di, ancestor_guid);
		dsc_fname = find_image_by_guid(di, descendant_guid);
		/* Can be online, offline, or mixed */
		ret = prepare_online_merge(dev, anc_fname, dsc_fname,
				&online, &info);
		if (ret)
			return ret;
	}

	if (!online) {
		ret = prepare_offline_merge(di,
				ancestor_guid, descendant_guid, &info);
		if (ret)
			goto out;
	}

	/* FIXME: check if any snapshots are mounted */
	ret = check_snapshot_mounts(di,
			ancestor_guid, descendant_guid);
	if (ret)
		goto out;

	i = get_list_size(info.names);
	ploop_log(0, "%s merge of %d snapshot%s",
			online ? "Online" : "Offline",
			i - 1, i < 3 ? "" : "s");
	log_merge_images_info(di, info.names, new_delta);

	/* First, merge in dd.xml (and do some extra checks */
	ret = ploop_di_merge_images(di, descendant_guid, i - 1);
	if (ret)
		goto out;

	get_disk_descriptor_fname(di, conf, sizeof(conf));
	snprintf(conf_tmp, sizeof(conf_tmp), "%s.tmp", conf);
	ret = ploop_store_diskdescriptor(conf_tmp, di);
	if (ret)
		goto out;

	/* Do the actual merge */
	ret = merge_image(online ? dev : NULL,
			info.start_level, info.end_level,
			info.raw, info.merge_top, info.names, new_delta);
	if (ret)
		goto out;

	if (new_delta) {
		/* Write new delta name to dd.xml, and remove the old file.
		 * Note we can only write new delta now after merge_image()
		 * as the file is created and we can use realpath() on it.
		 */
		int idx;
		char *oldimg, *newimg;

		newimg = realpath(new_delta, NULL);
		if (!newimg) {
			ploop_err(errno, "Error in realpath(%s)", new_delta);
			ret = SYSEXIT_PARAM;
			goto out;
		}

		idx = find_image_idx_by_guid(di, descendant_guid);
		if (idx == -1) {
			ploop_err(0, "Can't find image by uuid %s",
					descendant_guid);
			ret = SYSEXIT_PARAM;
			goto out;
		}

		oldimg = di->images[idx]->file;
		di->images[idx]->file = newimg;

		ret = ploop_store_diskdescriptor(conf_tmp, di);
		if (ret)
			goto out;

		ploop_log(0, "Removing %s", oldimg);
		ret = unlink(oldimg);
		if (ret) {
			ploop_err(errno, "Can't remove %s", oldimg);
			ret = SYSEXIT_UNLINK;
		}

		free(oldimg);
	}

	/* Put a new dd.xml */
	if (rename(conf_tmp, conf)) {
		ploop_err(errno, "Can't rename %s %s", conf_tmp, conf);
		ret = SYSEXIT_RENAME;
		goto out;
	}

	/* Remove images which were merged, i.e. all but the lowest one */
	for (i = 0; info.names[i+1]; i++) {
		const char *file = info.names[i];

		ploop_log(0, "Removing %s", file);
		if (unlink(file)) {
			ploop_err(errno, "Can't remove %s", file);
			ret = SYSEXIT_UNLINK;
		}
	}

	if (ret == 0)
		ploop_log(0, "Snapshots successfully merged");

out:
	ploop_free_array(info.names);

	return ret;
}

int ploop_merge_snapshot(struct ploop_disk_images_data *di, struct ploop_merge_param *param)
{
	int ret = SYSEXIT_PARAM;
	const char *guid = NULL;

	if (ploop_lock_dd(di))
		return SYSEXIT_LOCK;

	if (param->guid2 != NULL) {
		/* merge multiple snapshots at once */
		ret = ploop_merge_snapshots_by_guids(di, param->guid, param->guid2, param->new_delta);
		goto unlock;
	}
	else if (param->guid != NULL)
		guid = param->guid;
	else if (!param->merge_all)
		guid = di->top_guid;

	if (guid != NULL) {
		ret = ploop_merge_snapshot_by_guid(di, guid, param->new_delta);
	} else {
		/* merge all from top to base */
		guid = get_base_delta_uuid(di);
		ret =  ploop_merge_snapshots_by_guids(di, di->top_guid, guid, param->new_delta);
	}
unlock:
	ploop_unlock_dd(di);

	return ret;
}