summaryrefslogtreecommitdiffstats
path: root/job.c
blob: 72d57f09345b00e07f5a2762982036c453f1234d (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
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
/*
 * Background jobs (long-running operations)
 *
 * Copyright (c) 2011 IBM Corp.
 * Copyright (c) 2012, 2018 Red Hat, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "qemu/osdep.h"
#include "qapi/error.h"
#include "qemu/job.h"
#include "qemu/id.h"
#include "qemu/main-loop.h"
#include "block/aio-wait.h"
#include "trace/trace-root.h"
#include "qapi/qapi-events-job.h"

/*
 * The job API is composed of two categories of functions.
 *
 * The first includes functions used by the monitor.  The monitor is
 * peculiar in that it accesses the job list with job_get, and
 * therefore needs consistency across job_get and the actual operation
 * (e.g. job_user_cancel). To achieve this consistency, the caller
 * calls job_lock/job_unlock itself around the whole operation.
 *
 *
 * The second includes functions used by the job drivers and sometimes
 * by the core block layer. These delegate the locking to the callee instead.
 */

/*
 * job_mutex protects the jobs list, but also makes the
 * struct job fields thread-safe.
 */
QemuMutex job_mutex;

/* Protected by job_mutex */
static QLIST_HEAD(, Job) jobs = QLIST_HEAD_INITIALIZER(jobs);

/* Job State Transition Table */
bool JobSTT[JOB_STATUS__MAX][JOB_STATUS__MAX] = {
                                    /* U, C, R, P, Y, S, W, D, X, E, N */
    /* U: */ [JOB_STATUS_UNDEFINED] = {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
    /* C: */ [JOB_STATUS_CREATED]   = {0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1},
    /* R: */ [JOB_STATUS_RUNNING]   = {0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0},
    /* P: */ [JOB_STATUS_PAUSED]    = {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
    /* Y: */ [JOB_STATUS_READY]     = {0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0},
    /* S: */ [JOB_STATUS_STANDBY]   = {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0},
    /* W: */ [JOB_STATUS_WAITING]   = {0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0},
    /* D: */ [JOB_STATUS_PENDING]   = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0},
    /* X: */ [JOB_STATUS_ABORTING]  = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0},
    /* E: */ [JOB_STATUS_CONCLUDED] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
    /* N: */ [JOB_STATUS_NULL]      = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
};

bool JobVerbTable[JOB_VERB__MAX][JOB_STATUS__MAX] = {
                                    /* U, C, R, P, Y, S, W, D, X, E, N */
    [JOB_VERB_CANCEL]               = {0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0},
    [JOB_VERB_PAUSE]                = {0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0},
    [JOB_VERB_RESUME]               = {0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0},
    [JOB_VERB_SET_SPEED]            = {0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0},
    [JOB_VERB_COMPLETE]             = {0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0},
    [JOB_VERB_FINALIZE]             = {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0},
    [JOB_VERB_DISMISS]              = {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0},
};

/* Transactional group of jobs */
struct JobTxn {

    /* Is this txn being cancelled? */
    bool aborting;

    /* List of jobs */
    QLIST_HEAD(, Job) jobs;

    /* Reference count */
    int refcnt;
};

void job_lock(void)
{
    qemu_mutex_lock(&job_mutex);
}

void job_unlock(void)
{
    qemu_mutex_unlock(&job_mutex);
}

static void __attribute__((__constructor__)) job_init(void)
{
    qemu_mutex_init(&job_mutex);
}

JobTxn *job_txn_new(void)
{
    JobTxn *txn = g_new0(JobTxn, 1);
    QLIST_INIT(&txn->jobs);
    txn->refcnt = 1;
    return txn;
}

/* Called with job_mutex held. */
static void job_txn_ref_locked(JobTxn *txn)
{
    txn->refcnt++;
}

void job_txn_unref_locked(JobTxn *txn)
{
    if (txn && --txn->refcnt == 0) {
        g_free(txn);
    }
}

void job_txn_unref(JobTxn *txn)
{
    JOB_LOCK_GUARD();
    job_txn_unref_locked(txn);
}

/**
 * @txn: The transaction (may be NULL)
 * @job: Job to add to the transaction
 *
 * Add @job to the transaction.  The @job must not already be in a transaction.
 * The caller must call either job_txn_unref() or job_completed() to release
 * the reference that is automatically grabbed here.
 *
 * If @txn is NULL, the function does nothing.
 *
 * Called with job_mutex held.
 */
static void job_txn_add_job_locked(JobTxn *txn, Job *job)
{
    if (!txn) {
        return;
    }

    assert(!job->txn);
    job->txn = txn;

    QLIST_INSERT_HEAD(&txn->jobs, job, txn_list);
    job_txn_ref_locked(txn);
}

/* Called with job_mutex held. */
static void job_txn_del_job_locked(Job *job)
{
    if (job->txn) {
        QLIST_REMOVE(job, txn_list);
        job_txn_unref_locked(job->txn);
        job->txn = NULL;
    }
}

/* Called with job_mutex held, but releases it temporarily. */
static int job_txn_apply_locked(Job *job, int fn(Job *))
{
    Job *other_job, *next;
    JobTxn *txn = job->txn;
    int rc = 0;

    /*
     * Similar to job_completed_txn_abort, we take each job's lock before
     * applying fn, but since we assume that outer_ctx is held by the caller,
     * we need to release it here to avoid holding the lock twice - which would
     * break AIO_WAIT_WHILE from within fn.
     */
    job_ref_locked(job);

    QLIST_FOREACH_SAFE(other_job, &txn->jobs, txn_list, next) {
        rc = fn(other_job);
        if (rc) {
            break;
        }
    }

    job_unref_locked(job);
    return rc;
}

bool job_is_internal(Job *job)
{
    return (job->id == NULL);
}

/* Called with job_mutex held. */
static void job_state_transition_locked(Job *job, JobStatus s1)
{
    JobStatus s0 = job->status;
    assert(s1 >= 0 && s1 < JOB_STATUS__MAX);
    trace_job_state_transition(job, job->ret,
                               JobSTT[s0][s1] ? "allowed" : "disallowed",
                               JobStatus_str(s0), JobStatus_str(s1));
    assert(JobSTT[s0][s1]);
    job->status = s1;

    if (!job_is_internal(job) && s1 != s0) {
        qapi_event_send_job_status_change(job->id, job->status);
    }
}

int job_apply_verb_locked(Job *job, JobVerb verb, Error **errp)
{
    JobStatus s0 = job->status;
    assert(verb >= 0 && verb < JOB_VERB__MAX);
    trace_job_apply_verb(job, JobStatus_str(s0), JobVerb_str(verb),
                         JobVerbTable[verb][s0] ? "allowed" : "prohibited");
    if (JobVerbTable[verb][s0]) {
        return 0;
    }
    error_setg(errp, "Job '%s' in state '%s' cannot accept command verb '%s'",
               job->id, JobStatus_str(s0), JobVerb_str(verb));
    return -EPERM;
}

JobType job_type(const Job *job)
{
    return job->driver->job_type;
}

const char *job_type_str(const Job *job)
{
    return JobType_str(job_type(job));
}

bool job_is_cancelled_locked(Job *job)
{
    /* force_cancel may be true only if cancelled is true, too */
    assert(job->cancelled || !job->force_cancel);
    return job->force_cancel;
}

bool job_is_cancelled(Job *job)
{
    JOB_LOCK_GUARD();
    return job_is_cancelled_locked(job);
}

/* Called with job_mutex held. */
static bool job_cancel_requested_locked(Job *job)
{
    return job->cancelled;
}

bool job_cancel_requested(Job *job)
{
    JOB_LOCK_GUARD();
    return job_cancel_requested_locked(job);
}

bool job_is_ready_locked(Job *job)
{
    switch (job->status) {
    case JOB_STATUS_UNDEFINED:
    case JOB_STATUS_CREATED:
    case JOB_STATUS_RUNNING:
    case JOB_STATUS_PAUSED:
    case JOB_STATUS_WAITING:
    case JOB_STATUS_PENDING:
    case JOB_STATUS_ABORTING:
    case JOB_STATUS_CONCLUDED:
    case JOB_STATUS_NULL:
        return false;
    case JOB_STATUS_READY:
    case JOB_STATUS_STANDBY:
        return true;
    default:
        g_assert_not_reached();
    }
    return false;
}

bool job_is_ready(Job *job)
{
    JOB_LOCK_GUARD();
    return job_is_ready_locked(job);
}

bool job_is_completed_locked(Job *job)
{
    switch (job->status) {
    case JOB_STATUS_UNDEFINED:
    case JOB_STATUS_CREATED:
    case JOB_STATUS_RUNNING:
    case JOB_STATUS_PAUSED:
    case JOB_STATUS_READY:
    case JOB_STATUS_STANDBY:
        return false;
    case JOB_STATUS_WAITING:
    case JOB_STATUS_PENDING:
    case JOB_STATUS_ABORTING:
    case JOB_STATUS_CONCLUDED:
    case JOB_STATUS_NULL:
        return true;
    default:
        g_assert_not_reached();
    }
    return false;
}

static bool job_is_completed(Job *job)
{
    JOB_LOCK_GUARD();
    return job_is_completed_locked(job);
}

static bool job_started_locked(Job *job)
{
    return job->co;
}

/* Called with job_mutex held. */
static bool job_should_pause_locked(Job *job)
{
    return job->pause_count > 0;
}

Job *job_next_locked(Job *job)
{
    if (!job) {
        return QLIST_FIRST(&jobs);
    }
    return QLIST_NEXT(job, job_list);
}

Job *job_next(Job *job)
{
    JOB_LOCK_GUARD();
    return job_next_locked(job);
}

Job *job_get_locked(const char *id)
{
    Job *job;

    QLIST_FOREACH(job, &jobs, job_list) {
        if (job->id && !strcmp(id, job->id)) {
            return job;
        }
    }

    return NULL;
}

void job_set_aio_context(Job *job, AioContext *ctx)
{
    /* protect against read in job_finish_sync_locked and job_start */
    GLOBAL_STATE_CODE();
    /* protect against read in job_do_yield_locked */
    JOB_LOCK_GUARD();
    /* ensure the job is quiescent while the AioContext is changed */
    assert(job->paused || job_is_completed_locked(job));
    job->aio_context = ctx;
}

/* Called with job_mutex *not* held. */
static void job_sleep_timer_cb(void *opaque)
{
    Job *job = opaque;

    job_enter(job);
}

void *job_create(const char *job_id, const JobDriver *driver, JobTxn *txn,
                 AioContext *ctx, int flags, BlockCompletionFunc *cb,
                 void *opaque, Error **errp)
{
    Job *job;

    JOB_LOCK_GUARD();

    if (job_id) {
        if (flags & JOB_INTERNAL) {
            error_setg(errp, "Cannot specify job ID for internal job");
            return NULL;
        }
        if (!id_wellformed(job_id)) {
            error_setg(errp, "Invalid job ID '%s'", job_id);
            return NULL;
        }
        if (job_get_locked(job_id)) {
            error_setg(errp, "Job ID '%s' already in use", job_id);
            return NULL;
        }
    } else if (!(flags & JOB_INTERNAL)) {
        error_setg(errp, "An explicit job ID is required");
        return NULL;
    }

    job = g_malloc0(driver->instance_size);
    job->driver        = driver;
    job->id            = g_strdup(job_id);
    job->refcnt        = 1;
    job->aio_context   = ctx;
    job->busy          = false;
    job->paused        = true;
    job->pause_count   = 1;
    job->auto_finalize = !(flags & JOB_MANUAL_FINALIZE);
    job->auto_dismiss  = !(flags & JOB_MANUAL_DISMISS);
    job->cb            = cb;
    job->opaque        = opaque;

    progress_init(&job->progress);

    notifier_list_init(&job->on_finalize_cancelled);
    notifier_list_init(&job->on_finalize_completed);
    notifier_list_init(&job->on_pending);
    notifier_list_init(&job->on_ready);
    notifier_list_init(&job->on_idle);

    job_state_transition_locked(job, JOB_STATUS_CREATED);
    aio_timer_init(qemu_get_aio_context(), &job->sleep_timer,
                   QEMU_CLOCK_REALTIME, SCALE_NS,
                   job_sleep_timer_cb, job);

    QLIST_INSERT_HEAD(&jobs, job, job_list);

    /* Single jobs are modeled as single-job transactions for sake of
     * consolidating the job management logic */
    if (!txn) {
        txn = job_txn_new();
        job_txn_add_job_locked(txn, job);
        job_txn_unref_locked(txn);
    } else {
        job_txn_add_job_locked(txn, job);
    }

    return job;
}

void job_ref_locked(Job *job)
{
    ++job->refcnt;
}

void job_unref_locked(Job *job)
{
    GLOBAL_STATE_CODE();

    if (--job->refcnt == 0) {
        assert(job->status == JOB_STATUS_NULL);
        assert(!timer_pending(&job->sleep_timer));
        assert(!job->txn);

        if (job->driver->free) {
            AioContext *aio_context = job->aio_context;
            job_unlock();
            /* FIXME: aiocontext lock is required because cb calls blk_unref */
            aio_context_acquire(aio_context);
            job->driver->free(job);
            aio_context_release(aio_context);
            job_lock();
        }

        QLIST_REMOVE(job, job_list);

        progress_destroy(&job->progress);
        error_free(job->err);
        g_free(job->id);
        g_free(job);
    }
}

void job_progress_update(Job *job, uint64_t done)
{
    progress_work_done(&job->progress, done);
}

void job_progress_set_remaining(Job *job, uint64_t remaining)
{
    progress_set_remaining(&job->progress, remaining);
}

void job_progress_increase_remaining(Job *job, uint64_t delta)
{
    progress_increase_remaining(&job->progress, delta);
}

/**
 * To be called when a cancelled job is finalised.
 * Called with job_mutex held.
 */
static void job_event_cancelled_locked(Job *job)
{
    notifier_list_notify(&job->on_finalize_cancelled, job);
}

/**
 * To be called when a successfully completed job is finalised.
 * Called with job_mutex held.
 */
static void job_event_completed_locked(Job *job)
{
    notifier_list_notify(&job->on_finalize_completed, job);
}

/* Called with job_mutex held. */
static void job_event_pending_locked(Job *job)
{
    notifier_list_notify(&job->on_pending, job);
}

/* Called with job_mutex held. */
static void job_event_ready_locked(Job *job)
{
    notifier_list_notify(&job->on_ready, job);
}

/* Called with job_mutex held. */
static void job_event_idle_locked(Job *job)
{
    notifier_list_notify(&job->on_idle, job);
}

void job_enter_cond_locked(Job *job, bool(*fn)(Job *job))
{
    if (!job_started_locked(job)) {
        return;
    }
    if (job->deferred_to_main_loop) {
        return;
    }

    if (job->busy) {
        return;
    }

    if (fn && !fn(job)) {
        return;
    }

    assert(!job->deferred_to_main_loop);
    timer_del(&job->sleep_timer);
    job->busy = true;
    job_unlock();
    aio_co_wake(job->co);
    job_lock();
}

void job_enter(Job *job)
{
    JOB_LOCK_GUARD();
    job_enter_cond_locked(job, NULL);
}

/* Yield, and schedule a timer to reenter the coroutine after @ns nanoseconds.
 * Reentering the job coroutine with job_enter() before the timer has expired
 * is allowed and cancels the timer.
 *
 * If @ns is (uint64_t) -1, no timer is scheduled and job_enter() must be
 * called explicitly.
 *
 * Called with job_mutex held, but releases it temporarily.
 */
static void coroutine_fn job_do_yield_locked(Job *job, uint64_t ns)
{
    AioContext *next_aio_context;

    if (ns != -1) {
        timer_mod(&job->sleep_timer, ns);
    }
    job->busy = false;
    job_event_idle_locked(job);
    job_unlock();
    qemu_coroutine_yield();
    job_lock();

    next_aio_context = job->aio_context;
    /*
     * Coroutine has resumed, but in the meanwhile the job AioContext
     * might have changed via bdrv_try_change_aio_context(), so we need to move
     * the coroutine too in the new aiocontext.
     */
    while (qemu_get_current_aio_context() != next_aio_context) {
        job_unlock();
        aio_co_reschedule_self(next_aio_context);
        job_lock();
        next_aio_context = job->aio_context;
    }

    /* Set by job_enter_cond_locked() before re-entering the coroutine.  */
    assert(job->busy);
}

/* Called with job_mutex held, but releases it temporarily. */
static void coroutine_fn job_pause_point_locked(Job *job)
{
    assert(job && job_started_locked(job));

    if (!job_should_pause_locked(job)) {
        return;
    }
    if (job_is_cancelled_locked(job)) {
        return;
    }

    if (job->driver->pause) {
        job_unlock();
        job->driver->pause(job);
        job_lock();
    }

    if (job_should_pause_locked(job) && !job_is_cancelled_locked(job)) {
        JobStatus status = job->status;
        job_state_transition_locked(job, status == JOB_STATUS_READY
                                    ? JOB_STATUS_STANDBY
                                    : JOB_STATUS_PAUSED);
        job->paused = true;
        job_do_yield_locked(job, -1);
        job->paused = false;
        job_state_transition_locked(job, status);
    }

    if (job->driver->resume) {
        job_unlock();
        job->driver->resume(job);
        job_lock();
    }
}

void coroutine_fn job_pause_point(Job *job)
{
    JOB_LOCK_GUARD();
    job_pause_point_locked(job);
}

void coroutine_fn job_yield(Job *job)
{
    JOB_LOCK_GUARD();
    assert(job->busy);

    /* Check cancellation *before* setting busy = false, too!  */
    if (job_is_cancelled_locked(job)) {
        return;
    }

    if (!job_should_pause_locked(job)) {
        job_do_yield_locked(job, -1);
    }

    job_pause_point_locked(job);
}

void coroutine_fn job_sleep_ns(Job *job, int64_t ns)
{
    JOB_LOCK_GUARD();
    assert(job->busy);

    /* Check cancellation *before* setting busy = false, too!  */
    if (job_is_cancelled_locked(job)) {
        return;
    }

    if (!job_should_pause_locked(job)) {
        job_do_yield_locked(job, qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + ns);
    }

    job_pause_point_locked(job);
}

/* Assumes the job_mutex is held */
static bool job_timer_not_pending_locked(Job *job)
{
    return !timer_pending(&job->sleep_timer);
}

void job_pause_locked(Job *job)
{
    job->pause_count++;
    if (!job->paused) {
        job_enter_cond_locked(job, NULL);
    }
}

void job_pause(Job *job)
{
    JOB_LOCK_GUARD();
    job_pause_locked(job);
}

void job_resume_locked(Job *job)
{
    assert(job->pause_count > 0);
    job->pause_count--;
    if (job->pause_count) {
        return;
    }

    /* kick only if no timer is pending */
    job_enter_cond_locked(job, job_timer_not_pending_locked);
}

void job_resume(Job *job)
{
    JOB_LOCK_GUARD();
    job_resume_locked(job);
}

void job_user_pause_locked(Job *job, Error **errp)
{
    if (job_apply_verb_locked(job, JOB_VERB_PAUSE, errp)) {
        return;
    }
    if (job->user_paused) {
        error_setg(errp, "Job is already paused");
        return;
    }
    job->user_paused = true;
    job_pause_locked(job);
}

bool job_user_paused_locked(Job *job)
{
    return job->user_paused;
}

void job_user_resume_locked(Job *job, Error **errp)
{
    assert(job);
    GLOBAL_STATE_CODE();
    if (!job->user_paused || job->pause_count <= 0) {
        error_setg(errp, "Can't resume a job that was not paused");
        return;
    }
    if (job_apply_verb_locked(job, JOB_VERB_RESUME, errp)) {
        return;
    }
    if (job->driver->user_resume) {
        job_unlock();
        job->driver->user_resume(job);
        job_lock();
    }
    job->user_paused = false;
    job_resume_locked(job);
}

/* Called with job_mutex held, but releases it temporarily. */
static void job_do_dismiss_locked(Job *job)
{
    assert(job);
    job->busy = false;
    job->paused = false;
    job->deferred_to_main_loop = true;

    job_txn_del_job_locked(job);

    job_state_transition_locked(job, JOB_STATUS_NULL);
    job_unref_locked(job);
}

void job_dismiss_locked(Job **jobptr, Error **errp)
{
    Job *job = *jobptr;
    /* similarly to _complete, this is QMP-interface only. */
    assert(job->id);
    if (job_apply_verb_locked(job, JOB_VERB_DISMISS, errp)) {
        return;
    }

    job_do_dismiss_locked(job);
    *jobptr = NULL;
}

void job_early_fail(Job *job)
{
    JOB_LOCK_GUARD();
    assert(job->status == JOB_STATUS_CREATED);
    job_do_dismiss_locked(job);
}

/* Called with job_mutex held. */
static void job_conclude_locked(Job *job)
{
    job_state_transition_locked(job, JOB_STATUS_CONCLUDED);
    if (job->auto_dismiss || !job_started_locked(job)) {
        job_do_dismiss_locked(job);
    }
}

/* Called with job_mutex held. */
static void job_update_rc_locked(Job *job)
{
    if (!job->ret && job_is_cancelled_locked(job)) {
        job->ret = -ECANCELED;
    }
    if (job->ret) {
        if (!job->err) {
            error_setg(&job->err, "%s", strerror(-job->ret));
        }
        job_state_transition_locked(job, JOB_STATUS_ABORTING);
    }
}

static void job_commit(Job *job)
{
    assert(!job->ret);
    GLOBAL_STATE_CODE();
    if (job->driver->commit) {
        job->driver->commit(job);
    }
}

static void job_abort(Job *job)
{
    assert(job->ret);
    GLOBAL_STATE_CODE();
    if (job->driver->abort) {
        job->driver->abort(job);
    }
}

static void job_clean(Job *job)
{
    GLOBAL_STATE_CODE();
    if (job->driver->clean) {
        job->driver->clean(job);
    }
}

/*
 * Called with job_mutex held, but releases it temporarily.
 * Takes AioContext lock internally to invoke a job->driver callback.
 */
static int job_finalize_single_locked(Job *job)
{
    int job_ret;
    AioContext *ctx = job->aio_context;

    assert(job_is_completed_locked(job));

    /* Ensure abort is called for late-transactional failures */
    job_update_rc_locked(job);

    job_ret = job->ret;
    job_unlock();
    aio_context_acquire(ctx);

    if (!job_ret) {
        job_commit(job);
    } else {
        job_abort(job);
    }
    job_clean(job);

    if (job->cb) {
        job->cb(job->opaque, job_ret);
    }

    aio_context_release(ctx);
    job_lock();

    /* Emit events only if we actually started */
    if (job_started_locked(job)) {
        if (job_is_cancelled_locked(job)) {
            job_event_cancelled_locked(job);
        } else {
            job_event_completed_locked(job);
        }
    }

    job_txn_del_job_locked(job);
    job_conclude_locked(job);
    return 0;
}

/*
 * Called with job_mutex held, but releases it temporarily.
 * Takes AioContext lock internally to invoke a job->driver callback.
 */
static void job_cancel_async_locked(Job *job, bool force)
{
    AioContext *ctx = job->aio_context;
    GLOBAL_STATE_CODE();
    if (job->driver->cancel) {
        job_unlock();
        aio_context_acquire(ctx);
        force = job->driver->cancel(job, force);
        aio_context_release(ctx);
        job_lock();
    } else {
        /* No .cancel() means the job will behave as if force-cancelled */
        force = true;
    }

    if (job->user_paused) {
        /* Do not call job_enter here, the caller will handle it.  */
        if (job->driver->user_resume) {
            job_unlock();
            job->driver->user_resume(job);
            job_lock();
        }
        job->user_paused = false;
        assert(job->pause_count > 0);
        job->pause_count--;
    }

    /*
     * Ignore soft cancel requests after the job is already done
     * (We will still invoke job->driver->cancel() above, but if the
     * job driver supports soft cancelling and the job is done, that
     * should be a no-op, too.  We still call it so it can override
     * @force.)
     */
    if (force || !job->deferred_to_main_loop) {
        job->cancelled = true;
        /* To prevent 'force == false' overriding a previous 'force == true' */
        job->force_cancel |= force;
    }
}

/*
 * Called with job_mutex held, but releases it temporarily.
 * Takes AioContext lock internally to invoke a job->driver callback.
 */
static void job_completed_txn_abort_locked(Job *job)
{
    JobTxn *txn = job->txn;
    Job *other_job;

    if (txn->aborting) {
        /*
         * We are cancelled by another job, which will handle everything.
         */
        return;
    }
    txn->aborting = true;
    job_txn_ref_locked(txn);

    job_ref_locked(job);

    /* Other jobs are effectively cancelled by us, set the status for
     * them; this job, however, may or may not be cancelled, depending
     * on the caller, so leave it. */
    QLIST_FOREACH(other_job, &txn->jobs, txn_list) {
        if (other_job != job) {
            /*
             * This is a transaction: If one job failed, no result will matter.
             * Therefore, pass force=true to terminate all other jobs as quickly
             * as possible.
             */
            job_cancel_async_locked(other_job, true);
        }
    }
    while (!QLIST_EMPTY(&txn->jobs)) {
        other_job = QLIST_FIRST(&txn->jobs);
        if (!job_is_completed_locked(other_job)) {
            assert(job_cancel_requested_locked(other_job));
            job_finish_sync_locked(other_job, NULL, NULL);
        }
        job_finalize_single_locked(other_job);
    }

    job_unref_locked(job);
    job_txn_unref_locked(txn);
}

/* Called with job_mutex held, but releases it temporarily */
static int job_prepare_locked(Job *job)
{
    int ret;
    AioContext *ctx = job->aio_context;

    GLOBAL_STATE_CODE();

    if (job->ret == 0 && job->driver->prepare) {
        job_unlock();
        aio_context_acquire(ctx);
        ret = job->driver->prepare(job);
        aio_context_release(ctx);
        job_lock();
        job->ret = ret;
        job_update_rc_locked(job);
    }

    return job->ret;
}

/* Called with job_mutex held */
static int job_needs_finalize_locked(Job *job)
{
    return !job->auto_finalize;
}

/* Called with job_mutex held */
static void job_do_finalize_locked(Job *job)
{
    int rc;
    assert(job && job->txn);

    /* prepare the transaction to complete */
    rc = job_txn_apply_locked(job, job_prepare_locked);
    if (rc) {
        job_completed_txn_abort_locked(job);
    } else {
        job_txn_apply_locked(job, job_finalize_single_locked);
    }
}

void job_finalize_locked(Job *job, Error **errp)
{
    assert(job && job->id);
    if (job_apply_verb_locked(job, JOB_VERB_FINALIZE, errp)) {
        return;
    }
    job_do_finalize_locked(job);
}

/* Called with job_mutex held. */
static int job_transition_to_pending_locked(Job *job)
{
    job_state_transition_locked(job, JOB_STATUS_PENDING);
    if (!job->auto_finalize) {
        job_event_pending_locked(job);
    }
    return 0;
}

void job_transition_to_ready(Job *job)
{
    JOB_LOCK_GUARD();
    job_state_transition_locked(job, JOB_STATUS_READY);
    job_event_ready_locked(job);
}

/* Called with job_mutex held. */
static void job_completed_txn_success_locked(Job *job)
{
    JobTxn *txn = job->txn;
    Job *other_job;

    job_state_transition_locked(job, JOB_STATUS_WAITING);

    /*
     * Successful completion, see if there are other running jobs in this
     * txn.
     */
    QLIST_FOREACH(other_job, &txn->jobs, txn_list) {
        if (!job_is_completed_locked(other_job)) {
            return;
        }
        assert(other_job->ret == 0);
    }

    job_txn_apply_locked(job, job_transition_to_pending_locked);

    /* If no jobs need manual finalization, automatically do so */
    if (job_txn_apply_locked(job, job_needs_finalize_locked) == 0) {
        job_do_finalize_locked(job);
    }
}

/* Called with job_mutex held. */
static void job_completed_locked(Job *job)
{
    assert(job && job->txn && !job_is_completed_locked(job));

    job_update_rc_locked(job);
    trace_job_completed(job, job->ret);
    if (job->ret) {
        job_completed_txn_abort_locked(job);
    } else {
        job_completed_txn_success_locked(job);
    }
}

/**
 * Useful only as a type shim for aio_bh_schedule_oneshot.
 * Called with job_mutex *not* held.
 */
static void job_exit(void *opaque)
{
    Job *job = (Job *)opaque;
    JOB_LOCK_GUARD();
    job_ref_locked(job);

    /* This is a lie, we're not quiescent, but still doing the completion
     * callbacks. However, completion callbacks tend to involve operations that
     * drain block nodes, and if .drained_poll still returned true, we would
     * deadlock. */
    job->busy = false;
    job_event_idle_locked(job);

    job_completed_locked(job);
    job_unref_locked(job);
}

/**
 * All jobs must allow a pause point before entering their job proper. This
 * ensures that jobs can be paused prior to being started, then resumed later.
 */
static void coroutine_fn job_co_entry(void *opaque)
{
    Job *job = opaque;
    int ret;

    assert(job && job->driver && job->driver->run);
    WITH_JOB_LOCK_GUARD() {
        assert(job->aio_context == qemu_get_current_aio_context());
        job_pause_point_locked(job);
    }
    ret = job->driver->run(job, &job->err);
    WITH_JOB_LOCK_GUARD() {
        job->ret = ret;
        job->deferred_to_main_loop = true;
        job->busy = true;
    }
    aio_bh_schedule_oneshot(qemu_get_aio_context(), job_exit, job);
}

void job_start(Job *job)
{
    assert(qemu_in_main_thread());

    WITH_JOB_LOCK_GUARD() {
        assert(job && !job_started_locked(job) && job->paused &&
            job->driver && job->driver->run);
        job->co = qemu_coroutine_create(job_co_entry, job);
        job->pause_count--;
        job->busy = true;
        job->paused = false;
        job_state_transition_locked(job, JOB_STATUS_RUNNING);
    }
    aio_co_enter(job->aio_context, job->co);
}

void job_cancel_locked(Job *job, bool force)
{
    if (job->status == JOB_STATUS_CONCLUDED) {
        job_do_dismiss_locked(job);
        return;
    }
    job_cancel_async_locked(job, force);
    if (!job_started_locked(job)) {
        job_completed_locked(job);
    } else if (job->deferred_to_main_loop) {
        /*
         * job_cancel_async() ignores soft-cancel requests for jobs
         * that are already done (i.e. deferred to the main loop).  We
         * have to check again whether the job is really cancelled.
         * (job_cancel_requested() and job_is_cancelled() are equivalent
         * here, because job_cancel_async() will make soft-cancel
         * requests no-ops when deferred_to_main_loop is true.  We
         * choose to call job_is_cancelled() to show that we invoke
         * job_completed_txn_abort() only for force-cancelled jobs.)
         */
        if (job_is_cancelled_locked(job)) {
            job_completed_txn_abort_locked(job);
        }
    } else {
        job_enter_cond_locked(job, NULL);
    }
}

void job_user_cancel_locked(Job *job, bool force, Error **errp)
{
    if (job_apply_verb_locked(job, JOB_VERB_CANCEL, errp)) {
        return;
    }
    job_cancel_locked(job, force);
}

/* A wrapper around job_cancel_locked() taking an Error ** parameter so it may
 * be used with job_finish_sync_locked() without the need for (rather nasty)
 * function pointer casts there.
 *
 * Called with job_mutex held.
 */
static void job_cancel_err_locked(Job *job, Error **errp)
{
    job_cancel_locked(job, false);
}

/**
 * Same as job_cancel_err(), but force-cancel.
 * Called with job_mutex held.
 */
static void job_force_cancel_err_locked(Job *job, Error **errp)
{
    job_cancel_locked(job, true);
}

int job_cancel_sync_locked(Job *job, bool force)
{
    if (force) {
        return job_finish_sync_locked(job, &job_force_cancel_err_locked, NULL);
    } else {
        return job_finish_sync_locked(job, &job_cancel_err_locked, NULL);
    }
}

int job_cancel_sync(Job *job, bool force)
{
    JOB_LOCK_GUARD();
    return job_cancel_sync_locked(job, force);
}

void job_cancel_sync_all(void)
{
    Job *job;
    JOB_LOCK_GUARD();

    while ((job = job_next_locked(NULL))) {
        job_cancel_sync_locked(job, true);
    }
}

int job_complete_sync_locked(Job *job, Error **errp)
{
    return job_finish_sync_locked(job, job_complete_locked, errp);
}

void job_complete_locked(Job *job, Error **errp)
{
    /* Should not be reachable via external interface for internal jobs */
    assert(job->id);
    GLOBAL_STATE_CODE();
    if (job_apply_verb_locked(job, JOB_VERB_COMPLETE, errp)) {
        return;
    }
    if (job_cancel_requested_locked(job) || !job->driver->complete) {
        error_setg(errp, "The active block job '%s' cannot be completed",
                   job->id);
        return;
    }

    job_unlock();
    job->driver->complete(job, errp);
    job_lock();
}

int job_finish_sync_locked(Job *job,
                           void (*finish)(Job *, Error **errp),
                           Error **errp)
{
    Error *local_err = NULL;
    int ret;
    GLOBAL_STATE_CODE();

    job_ref_locked(job);

    if (finish) {
        finish(job, &local_err);
    }
    if (local_err) {
        error_propagate(errp, local_err);
        job_unref_locked(job);
        return -EBUSY;
    }

    job_unlock();
    AIO_WAIT_WHILE_UNLOCKED(job->aio_context,
                            (job_enter(job), !job_is_completed(job)));
    job_lock();

    ret = (job_is_cancelled_locked(job) && job->ret == 0)
          ? -ECANCELED : job->ret;
    job_unref_locked(job);
    return ret;
}
n> } } ret = 0; out: /* there is at most one request for this sockfd, so it is safe to * set each handler to NULL. */ aio_set_fd_handler(srco->aio_context, sockfd, false, NULL, NULL, NULL); srco->ret = ret; srco->finished = true; } /* * Send the request to the sheep in a synchronous manner. * * Return 0 on success, -errno in case of error. */ static int do_req(int sockfd, AioContext *aio_context, SheepdogReq *hdr, void *data, unsigned int *wlen, unsigned int *rlen) { Coroutine *co; SheepdogReqCo srco = { .sockfd = sockfd, .aio_context = aio_context, .hdr = hdr, .data = data, .wlen = wlen, .rlen = rlen, .ret = 0, .finished = false, }; if (qemu_in_coroutine()) { do_co_req(&srco); } else { co = qemu_coroutine_create(do_co_req, &srco); qemu_coroutine_enter(co); while (!srco.finished) { aio_poll(aio_context, true); } } return srco.ret; } static void coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req, struct iovec *iov, int niov, enum AIOCBState aiocb_type); static void coroutine_fn resend_aioreq(BDRVSheepdogState *s, AIOReq *aio_req); static int reload_inode(BDRVSheepdogState *s, uint32_t snapid, const char *tag); static int get_sheep_fd(BDRVSheepdogState *s, Error **errp); static void co_write_request(void *opaque); static coroutine_fn void reconnect_to_sdog(void *opaque) { BDRVSheepdogState *s = opaque; AIOReq *aio_req, *next; aio_set_fd_handler(s->aio_context, s->fd, false, NULL, NULL, NULL); close(s->fd); s->fd = -1; /* Wait for outstanding write requests to be completed. */ while (s->co_send != NULL) { co_write_request(opaque); } /* Try to reconnect the sheepdog server every one second. */ while (s->fd < 0) { Error *local_err = NULL; s->fd = get_sheep_fd(s, &local_err); if (s->fd < 0) { DPRINTF("Wait for connection to be established\n"); error_report_err(local_err); co_aio_sleep_ns(bdrv_get_aio_context(s->bs), QEMU_CLOCK_REALTIME, 1000000000ULL); } }; /* * Now we have to resend all the request in the inflight queue. However, * resend_aioreq() can yield and newly created requests can be added to the * inflight queue before the coroutine is resumed. To avoid mixing them, we * have to move all the inflight requests to the failed queue before * resend_aioreq() is called. */ QLIST_FOREACH_SAFE(aio_req, &s->inflight_aio_head, aio_siblings, next) { QLIST_REMOVE(aio_req, aio_siblings); QLIST_INSERT_HEAD(&s->failed_aio_head, aio_req, aio_siblings); } /* Resend all the failed aio requests. */ while (!QLIST_EMPTY(&s->failed_aio_head)) { aio_req = QLIST_FIRST(&s->failed_aio_head); QLIST_REMOVE(aio_req, aio_siblings); QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings); resend_aioreq(s, aio_req); } } /* * Receive responses of the I/O requests. * * This function is registered as a fd handler, and called from the * main loop when s->fd is ready for reading responses. */ static void coroutine_fn aio_read_response(void *opaque) { SheepdogObjRsp rsp; BDRVSheepdogState *s = opaque; int fd = s->fd; int ret; AIOReq *aio_req = NULL; SheepdogAIOCB *acb; uint64_t idx; /* read a header */ ret = qemu_co_recv(fd, &rsp, sizeof(rsp)); if (ret != sizeof(rsp)) { error_report("failed to get the header, %s", strerror(errno)); goto err; } /* find the right aio_req from the inflight aio list */ QLIST_FOREACH(aio_req, &s->inflight_aio_head, aio_siblings) { if (aio_req->id == rsp.id) { break; } } if (!aio_req) { error_report("cannot find aio_req %x", rsp.id); goto err; } acb = aio_req->aiocb; switch (acb->aiocb_type) { case AIOCB_WRITE_UDATA: /* this coroutine context is no longer suitable for co_recv * because we may send data to update vdi objects */ s->co_recv = NULL; if (!is_data_obj(aio_req->oid)) { break; } idx = data_oid_to_idx(aio_req->oid); if (aio_req->create) { /* * If the object is newly created one, we need to update * the vdi object (metadata object). min_dirty_data_idx * and max_dirty_data_idx are changed to include updated * index between them. */ if (rsp.result == SD_RES_SUCCESS) { s->inode.data_vdi_id[idx] = s->inode.vdi_id; acb->max_dirty_data_idx = MAX(idx, acb->max_dirty_data_idx); acb->min_dirty_data_idx = MIN(idx, acb->min_dirty_data_idx); } } break; case AIOCB_READ_UDATA: ret = qemu_co_recvv(fd, acb->qiov->iov, acb->qiov->niov, aio_req->iov_offset, rsp.data_length); if (ret != rsp.data_length) { error_report("failed to get the data, %s", strerror(errno)); goto err; } break; case AIOCB_FLUSH_CACHE: if (rsp.result == SD_RES_INVALID_PARMS) { DPRINTF("disable cache since the server doesn't support it\n"); s->cache_flags = SD_FLAG_CMD_DIRECT; rsp.result = SD_RES_SUCCESS; } break; case AIOCB_DISCARD_OBJ: switch (rsp.result) { case SD_RES_INVALID_PARMS: error_report("sheep(%s) doesn't support discard command", s->host_spec); rsp.result = SD_RES_SUCCESS; s->discard_supported = false; break; default: break; } } switch (rsp.result) { case SD_RES_SUCCESS: break; case SD_RES_READONLY: if (s->inode.vdi_id == oid_to_vid(aio_req->oid)) { ret = reload_inode(s, 0, ""); if (ret < 0) { goto err; } } if (is_data_obj(aio_req->oid)) { aio_req->oid = vid_to_data_oid(s->inode.vdi_id, data_oid_to_idx(aio_req->oid)); } else { aio_req->oid = vid_to_vdi_oid(s->inode.vdi_id); } resend_aioreq(s, aio_req); goto out; default: acb->ret = -EIO; error_report("%s", sd_strerror(rsp.result)); break; } free_aio_req(s, aio_req); if (!acb->nr_pending) { /* * We've finished all requests which belong to the AIOCB, so * we can switch back to sd_co_readv/writev now. */ acb->aio_done_func(acb); } out: s->co_recv = NULL; return; err: s->co_recv = NULL; reconnect_to_sdog(opaque); } static void co_read_response(void *opaque) { BDRVSheepdogState *s = opaque; if (!s->co_recv) { s->co_recv = qemu_coroutine_create(aio_read_response, opaque); } qemu_coroutine_enter(s->co_recv); } static void co_write_request(void *opaque) { BDRVSheepdogState *s = opaque; qemu_coroutine_enter(s->co_send); } /* * Return a socket descriptor to read/write objects. * * We cannot use this descriptor for other operations because * the block driver may be on waiting response from the server. */ static int get_sheep_fd(BDRVSheepdogState *s, Error **errp) { int fd; fd = connect_to_sdog(s, errp); if (fd < 0) { return fd; } aio_set_fd_handler(s->aio_context, fd, false, co_read_response, NULL, s); return fd; } static int sd_parse_uri(BDRVSheepdogState *s, const char *filename, char *vdi, uint32_t *snapid, char *tag) { URI *uri; QueryParams *qp = NULL; int ret = 0; uri = uri_parse(filename); if (!uri) { return -EINVAL; } /* transport */ if (!strcmp(uri->scheme, "sheepdog")) { s->is_unix = false; } else if (!strcmp(uri->scheme, "sheepdog+tcp")) { s->is_unix = false; } else if (!strcmp(uri->scheme, "sheepdog+unix")) { s->is_unix = true; } else { ret = -EINVAL; goto out; } if (uri->path == NULL || !strcmp(uri->path, "/")) { ret = -EINVAL; goto out; } pstrcpy(vdi, SD_MAX_VDI_LEN, uri->path + 1); qp = query_params_parse(uri->query); if (qp->n > 1 || (s->is_unix && !qp->n) || (!s->is_unix && qp->n)) { ret = -EINVAL; goto out; } if (s->is_unix) { /* sheepdog+unix:///vdiname?socket=path */ if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) { ret = -EINVAL; goto out; } s->host_spec = g_strdup(qp->p[0].value); } else { /* sheepdog[+tcp]://[host:port]/vdiname */ s->host_spec = g_strdup_printf("%s:%d", uri->server ?: SD_DEFAULT_ADDR, uri->port ?: SD_DEFAULT_PORT); } /* snapshot tag */ if (uri->fragment) { *snapid = strtoul(uri->fragment, NULL, 10); if (*snapid == 0) { pstrcpy(tag, SD_MAX_VDI_TAG_LEN, uri->fragment); } } else { *snapid = CURRENT_VDI_ID; /* search current vdi */ } out: if (qp) { query_params_free(qp); } uri_free(uri); return ret; } /* * Parse a filename (old syntax) * * filename must be one of the following formats: * 1. [vdiname] * 2. [vdiname]:[snapid] * 3. [vdiname]:[tag] * 4. [hostname]:[port]:[vdiname] * 5. [hostname]:[port]:[vdiname]:[snapid] * 6. [hostname]:[port]:[vdiname]:[tag] * * You can boot from the snapshot images by specifying `snapid` or * `tag'. * * You can run VMs outside the Sheepdog cluster by specifying * `hostname' and `port' (experimental). */ static int parse_vdiname(BDRVSheepdogState *s, const char *filename, char *vdi, uint32_t *snapid, char *tag) { char *p, *q, *uri; const char *host_spec, *vdi_spec; int nr_sep, ret; strstart(filename, "sheepdog:", (const char **)&filename); p = q = g_strdup(filename); /* count the number of separators */ nr_sep = 0; while (*p) { if (*p == ':') { nr_sep++; } p++; } p = q; /* use the first two tokens as host_spec. */ if (nr_sep >= 2) { host_spec = p; p = strchr(p, ':'); p++; p = strchr(p, ':'); *p++ = '\0'; } else { host_spec = ""; } vdi_spec = p; p = strchr(vdi_spec, ':'); if (p) { *p++ = '#'; } uri = g_strdup_printf("sheepdog://%s/%s", host_spec, vdi_spec); ret = sd_parse_uri(s, uri, vdi, snapid, tag); g_free(q); g_free(uri); return ret; } static int find_vdi_name(BDRVSheepdogState *s, const char *filename, uint32_t snapid, const char *tag, uint32_t *vid, bool lock, Error **errp) { int ret, fd; SheepdogVdiReq hdr; SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr; unsigned int wlen, rlen = 0; char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN]; fd = connect_to_sdog(s, errp); if (fd < 0) { return fd; } /* This pair of strncpy calls ensures that the buffer is zero-filled, * which is desirable since we'll soon be sending those bytes, and * don't want the send_req to read uninitialized data. */ strncpy(buf, filename, SD_MAX_VDI_LEN); strncpy(buf + SD_MAX_VDI_LEN, tag, SD_MAX_VDI_TAG_LEN); memset(&hdr, 0, sizeof(hdr)); if (lock) { hdr.opcode = SD_OP_LOCK_VDI; hdr.type = LOCK_TYPE_NORMAL; } else { hdr.opcode = SD_OP_GET_VDI_INFO; } wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN; hdr.proto_ver = SD_PROTO_VER; hdr.data_length = wlen; hdr.snapid = snapid; hdr.flags = SD_FLAG_CMD_WRITE; ret = do_req(fd, s->aio_context, (SheepdogReq *)&hdr, buf, &wlen, &rlen); if (ret) { error_setg_errno(errp, -ret, "cannot get vdi info"); goto out; } if (rsp->result != SD_RES_SUCCESS) { error_setg(errp, "cannot get vdi info, %s, %s %" PRIu32 " %s", sd_strerror(rsp->result), filename, snapid, tag); if (rsp->result == SD_RES_NO_VDI) { ret = -ENOENT; } else if (rsp->result == SD_RES_VDI_LOCKED) { ret = -EBUSY; } else { ret = -EIO; } goto out; } *vid = rsp->vdi_id; ret = 0; out: closesocket(fd); return ret; } static void coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req, struct iovec *iov, int niov, enum AIOCBState aiocb_type) { int nr_copies = s->inode.nr_copies; SheepdogObjReq hdr; unsigned int wlen = 0; int ret; uint64_t oid = aio_req->oid; unsigned int datalen = aio_req->data_len; uint64_t offset = aio_req->offset; uint8_t flags = aio_req->flags; uint64_t old_oid = aio_req->base_oid; bool create = aio_req->create; if (!nr_copies) { error_report("bug"); } memset(&hdr, 0, sizeof(hdr)); switch (aiocb_type) { case AIOCB_FLUSH_CACHE: hdr.opcode = SD_OP_FLUSH_VDI; break; case AIOCB_READ_UDATA: hdr.opcode = SD_OP_READ_OBJ; hdr.flags = flags; break; case AIOCB_WRITE_UDATA: if (create) { hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ; } else { hdr.opcode = SD_OP_WRITE_OBJ; } wlen = datalen; hdr.flags = SD_FLAG_CMD_WRITE | flags; break; case AIOCB_DISCARD_OBJ: hdr.opcode = SD_OP_WRITE_OBJ; hdr.flags = SD_FLAG_CMD_WRITE | flags; s->inode.data_vdi_id[data_oid_to_idx(oid)] = 0; offset = offsetof(SheepdogInode, data_vdi_id[data_oid_to_idx(oid)]); oid = vid_to_vdi_oid(s->inode.vdi_id); wlen = datalen = sizeof(uint32_t); break; } if (s->cache_flags) { hdr.flags |= s->cache_flags; } hdr.oid = oid; hdr.cow_oid = old_oid; hdr.copies = s->inode.nr_copies; hdr.data_length = datalen; hdr.offset = offset; hdr.id = aio_req->id; qemu_co_mutex_lock(&s->lock); s->co_send = qemu_coroutine_self(); aio_set_fd_handler(s->aio_context, s->fd, false, co_read_response, co_write_request, s); socket_set_cork(s->fd, 1); /* send a header */ ret = qemu_co_send(s->fd, &hdr, sizeof(hdr)); if (ret != sizeof(hdr)) { error_report("failed to send a req, %s", strerror(errno)); goto out; } if (wlen) { ret = qemu_co_sendv(s->fd, iov, niov, aio_req->iov_offset, wlen); if (ret != wlen) { error_report("failed to send a data, %s", strerror(errno)); } } out: socket_set_cork(s->fd, 0); aio_set_fd_handler(s->aio_context, s->fd, false, co_read_response, NULL, s); s->co_send = NULL; qemu_co_mutex_unlock(&s->lock); } static int read_write_object(int fd, AioContext *aio_context, char *buf, uint64_t oid, uint8_t copies, unsigned int datalen, uint64_t offset, bool write, bool create, uint32_t cache_flags) { SheepdogObjReq hdr; SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr; unsigned int wlen, rlen; int ret; memset(&hdr, 0, sizeof(hdr)); if (write) { wlen = datalen; rlen = 0; hdr.flags = SD_FLAG_CMD_WRITE; if (create) { hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ; } else { hdr.opcode = SD_OP_WRITE_OBJ; } } else { wlen = 0; rlen = datalen; hdr.opcode = SD_OP_READ_OBJ; } hdr.flags |= cache_flags; hdr.oid = oid; hdr.data_length = datalen; hdr.offset = offset; hdr.copies = copies; ret = do_req(fd, aio_context, (SheepdogReq *)&hdr, buf, &wlen, &rlen); if (ret) { error_report("failed to send a request to the sheep"); return ret; } switch (rsp->result) { case SD_RES_SUCCESS: return 0; default: error_report("%s", sd_strerror(rsp->result)); return -EIO; } } static int read_object(int fd, AioContext *aio_context, char *buf, uint64_t oid, uint8_t copies, unsigned int datalen, uint64_t offset, uint32_t cache_flags) { return read_write_object(fd, aio_context, buf, oid, copies, datalen, offset, false, false, cache_flags); } static int write_object(int fd, AioContext *aio_context, char *buf, uint64_t oid, uint8_t copies, unsigned int datalen, uint64_t offset, bool create, uint32_t cache_flags) { return read_write_object(fd, aio_context, buf, oid, copies, datalen, offset, true, create, cache_flags); } /* update inode with the latest state */ static int reload_inode(BDRVSheepdogState *s, uint32_t snapid, const char *tag) { Error *local_err = NULL; SheepdogInode *inode; int ret = 0, fd; uint32_t vid = 0; fd = connect_to_sdog(s, &local_err); if (fd < 0) { error_report_err(local_err); return -EIO; } inode = g_malloc(SD_INODE_HEADER_SIZE); ret = find_vdi_name(s, s->name, snapid, tag, &vid, false, &local_err); if (ret) { error_report_err(local_err); goto out; } ret = read_object(fd, s->aio_context, (char *)inode, vid_to_vdi_oid(vid), s->inode.nr_copies, SD_INODE_HEADER_SIZE, 0, s->cache_flags); if (ret < 0) { goto out; } if (inode->vdi_id != s->inode.vdi_id) { memcpy(&s->inode, inode, SD_INODE_HEADER_SIZE); } out: g_free(inode); closesocket(fd); return ret; } static void coroutine_fn resend_aioreq(BDRVSheepdogState *s, AIOReq *aio_req) { SheepdogAIOCB *acb = aio_req->aiocb; aio_req->create = false; /* check whether this request becomes a CoW one */ if (acb->aiocb_type == AIOCB_WRITE_UDATA && is_data_obj(aio_req->oid)) { int idx = data_oid_to_idx(aio_req->oid); if (is_data_obj_writable(&s->inode, idx)) { goto out; } if (s->inode.data_vdi_id[idx]) { aio_req->base_oid = vid_to_data_oid(s->inode.data_vdi_id[idx], idx); aio_req->flags |= SD_FLAG_CMD_COW; } aio_req->create = true; } out: if (is_data_obj(aio_req->oid)) { add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov, acb->aiocb_type); } else { struct iovec iov; iov.iov_base = &s->inode; iov.iov_len = sizeof(s->inode); add_aio_request(s, aio_req, &iov, 1, AIOCB_WRITE_UDATA); } } static void sd_detach_aio_context(BlockDriverState *bs) { BDRVSheepdogState *s = bs->opaque; aio_set_fd_handler(s->aio_context, s->fd, false, NULL, NULL, NULL); } static void sd_attach_aio_context(BlockDriverState *bs, AioContext *new_context) { BDRVSheepdogState *s = bs->opaque; s->aio_context = new_context; aio_set_fd_handler(new_context, s->fd, false, co_read_response, NULL, s); } /* TODO Convert to fine grained options */ static QemuOptsList runtime_opts = { .name = "sheepdog", .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head), .desc = { { .name = "filename", .type = QEMU_OPT_STRING, .help = "URL to the sheepdog image", }, { /* end of list */ } }, }; static int sd_open(BlockDriverState *bs, QDict *options, int flags, Error **errp) { int ret, fd; uint32_t vid = 0; BDRVSheepdogState *s = bs->opaque; char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN]; uint32_t snapid; char *buf = NULL; QemuOpts *opts; Error *local_err = NULL; const char *filename; s->bs = bs; s->aio_context = bdrv_get_aio_context(bs); opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort); qemu_opts_absorb_qdict(opts, options, &local_err); if (local_err) { error_propagate(errp, local_err); ret = -EINVAL; goto out; } filename = qemu_opt_get(opts, "filename"); QLIST_INIT(&s->inflight_aio_head); QLIST_INIT(&s->failed_aio_head); QLIST_INIT(&s->inflight_aiocb_head); s->fd = -1; memset(vdi, 0, sizeof(vdi)); memset(tag, 0, sizeof(tag)); if (strstr(filename, "://")) { ret = sd_parse_uri(s, filename, vdi, &snapid, tag); } else { ret = parse_vdiname(s, filename, vdi, &snapid, tag); } if (ret < 0) { error_setg(errp, "Can't parse filename"); goto out; } s->fd = get_sheep_fd(s, errp); if (s->fd < 0) { ret = s->fd; goto out; } ret = find_vdi_name(s, vdi, snapid, tag, &vid, true, errp); if (ret) { goto out; } /* * QEMU block layer emulates writethrough cache as 'writeback + flush', so * we always set SD_FLAG_CMD_CACHE (writeback cache) as default. */ s->cache_flags = SD_FLAG_CMD_CACHE; if (flags & BDRV_O_NOCACHE) { s->cache_flags = SD_FLAG_CMD_DIRECT; } s->discard_supported = true; if (snapid || tag[0] != '\0') { DPRINTF("%" PRIx32 " snapshot inode was open.\n", vid); s->is_snapshot = true; } fd = connect_to_sdog(s, errp); if (fd < 0) { ret = fd; goto out; } buf = g_malloc(SD_INODE_SIZE); ret = read_object(fd, s->aio_context, buf, vid_to_vdi_oid(vid), 0, SD_INODE_SIZE, 0, s->cache_flags); closesocket(fd); if (ret) { error_setg(errp, "Can't read snapshot inode"); goto out; } memcpy(&s->inode, buf, sizeof(s->inode)); bs->total_sectors = s->inode.vdi_size / BDRV_SECTOR_SIZE; pstrcpy(s->name, sizeof(s->name), vdi); qemu_co_mutex_init(&s->lock); qemu_co_queue_init(&s->overlapping_queue); qemu_opts_del(opts); g_free(buf); return 0; out: aio_set_fd_handler(bdrv_get_aio_context(bs), s->fd, false, NULL, NULL, NULL); if (s->fd >= 0) { closesocket(s->fd); } qemu_opts_del(opts); g_free(buf); return ret; } static int sd_reopen_prepare(BDRVReopenState *state, BlockReopenQueue *queue, Error **errp) { BDRVSheepdogState *s = state->bs->opaque; BDRVSheepdogReopenState *re_s; int ret = 0; re_s = state->opaque = g_new0(BDRVSheepdogReopenState, 1); re_s->cache_flags = SD_FLAG_CMD_CACHE; if (state->flags & BDRV_O_NOCACHE) { re_s->cache_flags = SD_FLAG_CMD_DIRECT; } re_s->fd = get_sheep_fd(s, errp); if (re_s->fd < 0) { ret = re_s->fd; return ret; } return ret; } static void sd_reopen_commit(BDRVReopenState *state) { BDRVSheepdogReopenState *re_s = state->opaque; BDRVSheepdogState *s = state->bs->opaque; if (s->fd) { aio_set_fd_handler(s->aio_context, s->fd, false, NULL, NULL, NULL); closesocket(s->fd); } s->fd = re_s->fd; s->cache_flags = re_s->cache_flags; g_free(state->opaque); state->opaque = NULL; return; } static void sd_reopen_abort(BDRVReopenState *state) { BDRVSheepdogReopenState *re_s = state->opaque; BDRVSheepdogState *s = state->bs->opaque; if (re_s == NULL) { return; } if (re_s->fd) { aio_set_fd_handler(s->aio_context, re_s->fd, false, NULL, NULL, NULL); closesocket(re_s->fd); } g_free(state->opaque); state->opaque = NULL; return; } static int do_sd_create(BDRVSheepdogState *s, uint32_t *vdi_id, int snapshot, Error **errp) { SheepdogVdiReq hdr; SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr; int fd, ret; unsigned int wlen, rlen = 0; char buf[SD_MAX_VDI_LEN]; fd = connect_to_sdog(s, errp); if (fd < 0) { return fd; } /* FIXME: would it be better to fail (e.g., return -EIO) when filename * does not fit in buf? For now, just truncate and avoid buffer overrun. */ memset(buf, 0, sizeof(buf)); pstrcpy(buf, sizeof(buf), s->name); memset(&hdr, 0, sizeof(hdr)); hdr.opcode = SD_OP_NEW_VDI; hdr.base_vdi_id = s->inode.vdi_id; wlen = SD_MAX_VDI_LEN; hdr.flags = SD_FLAG_CMD_WRITE; hdr.snapid = snapshot; hdr.data_length = wlen; hdr.vdi_size = s->inode.vdi_size; hdr.copy_policy = s->inode.copy_policy; hdr.copies = s->inode.nr_copies; hdr.block_size_shift = s->inode.block_size_shift; ret = do_req(fd, s->aio_context, (SheepdogReq *)&hdr, buf, &wlen, &rlen); closesocket(fd); if (ret) { error_setg_errno(errp, -ret, "create failed"); return ret; } if (rsp->result != SD_RES_SUCCESS) { error_setg(errp, "%s, %s", sd_strerror(rsp->result), s->inode.name); return -EIO; } if (vdi_id) { *vdi_id = rsp->vdi_id; } return 0; } static int sd_prealloc(const char *filename, Error **errp) { BlockBackend *blk = NULL; BDRVSheepdogState *base = NULL; unsigned long buf_size; uint32_t idx, max_idx; uint32_t object_size; int64_t vdi_size; void *buf = NULL; int ret; blk = blk_new_open(filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL, errp); if (blk == NULL) { ret = -EIO; goto out_with_err_set; } blk_set_allow_write_beyond_eof(blk, true); vdi_size = blk_getlength(blk); if (vdi_size < 0) { ret = vdi_size; goto out; } base = blk_bs(blk)->opaque; object_size = (UINT32_C(1) << base->inode.block_size_shift); buf_size = MIN(object_size, SD_DATA_OBJ_SIZE); buf = g_malloc0(buf_size); max_idx = DIV_ROUND_UP(vdi_size, buf_size); for (idx = 0; idx < max_idx; idx++) { /* * The created image can be a cloned image, so we need to read * a data from the source image. */ ret = blk_pread(blk, idx * buf_size, buf, buf_size); if (ret < 0) { goto out; } ret = blk_pwrite(blk, idx * buf_size, buf, buf_size, 0); if (ret < 0) { goto out; } } ret = 0; out: if (ret < 0) { error_setg_errno(errp, -ret, "Can't pre-allocate"); } out_with_err_set: if (blk) { blk_unref(blk); } g_free(buf); return ret; } /* * Sheepdog support two kinds of redundancy, full replication and erasure * coding. * * # create a fully replicated vdi with x copies * -o redundancy=x (1 <= x <= SD_MAX_COPIES) * * # create a erasure coded vdi with x data strips and y parity strips * -o redundancy=x:y (x must be one of {2,4,8,16} and 1 <= y < SD_EC_MAX_STRIP) */ static int parse_redundancy(BDRVSheepdogState *s, const char *opt) { struct SheepdogInode *inode = &s->inode; const char *n1, *n2; long copy, parity; char p[10]; pstrcpy(p, sizeof(p), opt); n1 = strtok(p, ":"); n2 = strtok(NULL, ":"); if (!n1) { return -EINVAL; } copy = strtol(n1, NULL, 10); if (copy > SD_MAX_COPIES || copy < 1) { return -EINVAL; } if (!n2) { inode->copy_policy = 0; inode->nr_copies = copy; return 0; } if (copy != 2 && copy != 4 && copy != 8 && copy != 16) { return -EINVAL; } parity = strtol(n2, NULL, 10); if (parity >= SD_EC_MAX_STRIP || parity < 1) { return -EINVAL; } /* * 4 bits for parity and 4 bits for data. * We have to compress upper data bits because it can't represent 16 */ inode->copy_policy = ((copy / 2) << 4) + parity; inode->nr_copies = copy + parity; return 0; } static int parse_block_size_shift(BDRVSheepdogState *s, QemuOpts *opt) { struct SheepdogInode *inode = &s->inode; uint64_t object_size; int obj_order; object_size = qemu_opt_get_size_del(opt, BLOCK_OPT_OBJECT_SIZE, 0); if (object_size) { if ((object_size - 1) & object_size) { /* not a power of 2? */ return -EINVAL; } obj_order = ctz32(object_size); if (obj_order < 20 || obj_order > 31) { return -EINVAL; } inode->block_size_shift = (uint8_t)obj_order; } return 0; } static int sd_create(const char *filename, QemuOpts *opts, Error **errp) { int ret = 0; uint32_t vid = 0; char *backing_file = NULL; char *buf = NULL; BDRVSheepdogState *s; char tag[SD_MAX_VDI_TAG_LEN]; uint32_t snapid; uint64_t max_vdi_size; bool prealloc = false; s = g_new0(BDRVSheepdogState, 1); memset(tag, 0, sizeof(tag)); if (strstr(filename, "://")) { ret = sd_parse_uri(s, filename, s->name, &snapid, tag); } else { ret = parse_vdiname(s, filename, s->name, &snapid, tag); } if (ret < 0) { error_setg(errp, "Can't parse filename"); goto out; } s->inode.vdi_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0), BDRV_SECTOR_SIZE); backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE); buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC); if (!buf || !strcmp(buf, "off")) { prealloc = false; } else if (!strcmp(buf, "full")) { prealloc = true; } else { error_setg(errp, "Invalid preallocation mode: '%s'", buf); ret = -EINVAL; goto out; } g_free(buf); buf = qemu_opt_get_del(opts, BLOCK_OPT_REDUNDANCY); if (buf) { ret = parse_redundancy(s, buf); if (ret < 0) { error_setg(errp, "Invalid redundancy mode: '%s'", buf); goto out; } } ret = parse_block_size_shift(s, opts); if (ret < 0) { error_setg(errp, "Invalid object_size." " obect_size needs to be power of 2" " and be limited from 2^20 to 2^31"); goto out; } if (backing_file) { BlockBackend *blk; BDRVSheepdogState *base; BlockDriver *drv; /* Currently, only Sheepdog backing image is supported. */ drv = bdrv_find_protocol(backing_file, true, NULL); if (!drv || strcmp(drv->protocol_name, "sheepdog") != 0) { error_setg(errp, "backing_file must be a sheepdog image"); ret = -EINVAL; goto out; } blk = blk_new_open(backing_file, NULL, NULL, BDRV_O_PROTOCOL, errp); if (blk == NULL) { ret = -EIO; goto out; } base = blk_bs(blk)->opaque; if (!is_snapshot(&base->inode)) { error_setg(errp, "cannot clone from a non snapshot vdi"); blk_unref(blk); ret = -EINVAL; goto out; } s->inode.vdi_id = base->inode.vdi_id; blk_unref(blk); } s->aio_context = qemu_get_aio_context(); /* if block_size_shift is not specified, get cluster default value */ if (s->inode.block_size_shift == 0) { SheepdogVdiReq hdr; SheepdogClusterRsp *rsp = (SheepdogClusterRsp *)&hdr; Error *local_err = NULL; int fd; unsigned int wlen = 0, rlen = 0; fd = connect_to_sdog(s, &local_err); if (fd < 0) { error_report_err(local_err); ret = -EIO; goto out; } memset(&hdr, 0, sizeof(hdr)); hdr.opcode = SD_OP_GET_CLUSTER_DEFAULT; hdr.proto_ver = SD_PROTO_VER; ret = do_req(fd, s->aio_context, (SheepdogReq *)&hdr, NULL, &wlen, &rlen); closesocket(fd); if (ret) { error_setg_errno(errp, -ret, "failed to get cluster default"); goto out; } if (rsp->result == SD_RES_SUCCESS) { s->inode.block_size_shift = rsp->block_size_shift; } else { s->inode.block_size_shift = SD_DEFAULT_BLOCK_SIZE_SHIFT; } } max_vdi_size = (UINT64_C(1) << s->inode.block_size_shift) * MAX_DATA_OBJS; if (s->inode.vdi_size > max_vdi_size) { error_setg(errp, "An image is too large." " The maximum image size is %"PRIu64 "GB", max_vdi_size / 1024 / 1024 / 1024); ret = -EINVAL; goto out; } ret = do_sd_create(s, &vid, 0, errp); if (ret) { goto out; } if (prealloc) { ret = sd_prealloc(filename, errp); } out: g_free(backing_file); g_free(buf); g_free(s); return ret; } static void sd_close(BlockDriverState *bs) { Error *local_err = NULL; BDRVSheepdogState *s = bs->opaque; SheepdogVdiReq hdr; SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr; unsigned int wlen, rlen = 0; int fd, ret; DPRINTF("%s\n", s->name); fd = connect_to_sdog(s, &local_err); if (fd < 0) { error_report_err(local_err); return; } memset(&hdr, 0, sizeof(hdr)); hdr.opcode = SD_OP_RELEASE_VDI; hdr.type = LOCK_TYPE_NORMAL; hdr.base_vdi_id = s->inode.vdi_id; wlen = strlen(s->name) + 1; hdr.data_length = wlen; hdr.flags = SD_FLAG_CMD_WRITE; ret = do_req(fd, s->aio_context, (SheepdogReq *)&hdr, s->name, &wlen, &rlen); closesocket(fd); if (!ret && rsp->result != SD_RES_SUCCESS && rsp->result != SD_RES_VDI_NOT_LOCKED) { error_report("%s, %s", sd_strerror(rsp->result), s->name); } aio_set_fd_handler(bdrv_get_aio_context(bs), s->fd, false, NULL, NULL, NULL); closesocket(s->fd); g_free(s->host_spec); } static int64_t sd_getlength(BlockDriverState *bs) { BDRVSheepdogState *s = bs->opaque; return s->inode.vdi_size; } static int sd_truncate(BlockDriverState *bs, int64_t offset) { Error *local_err = NULL; BDRVSheepdogState *s = bs->opaque; int ret, fd; unsigned int datalen; uint64_t max_vdi_size; max_vdi_size = (UINT64_C(1) << s->inode.block_size_shift) * MAX_DATA_OBJS; if (offset < s->inode.vdi_size) { error_report("shrinking is not supported"); return -EINVAL; } else if (offset > max_vdi_size) { error_report("too big image size"); return -EINVAL; } fd = connect_to_sdog(s, &local_err); if (fd < 0) { error_report_err(local_err); return fd; } /* we don't need to update entire object */ datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id); s->inode.vdi_size = offset; ret = write_object(fd, s->aio_context, (char *)&s->inode, vid_to_vdi_oid(s->inode.vdi_id), s->inode.nr_copies, datalen, 0, false, s->cache_flags); close(fd); if (ret < 0) { error_report("failed to update an inode."); } return ret; } /* * This function is called after writing data objects. If we need to * update metadata, this sends a write request to the vdi object. * Otherwise, this switches back to sd_co_readv/writev. */ static void coroutine_fn sd_write_done(SheepdogAIOCB *acb) { BDRVSheepdogState *s = acb->common.bs->opaque; struct iovec iov; AIOReq *aio_req; uint32_t offset, data_len, mn, mx; mn = acb->min_dirty_data_idx; mx = acb->max_dirty_data_idx; if (mn <= mx) { /* we need to update the vdi object. */ offset = sizeof(s->inode) - sizeof(s->inode.data_vdi_id) + mn * sizeof(s->inode.data_vdi_id[0]); data_len = (mx - mn + 1) * sizeof(s->inode.data_vdi_id[0]); acb->min_dirty_data_idx = UINT32_MAX; acb->max_dirty_data_idx = 0; iov.iov_base = &s->inode; iov.iov_len = sizeof(s->inode); aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id), data_len, offset, 0, false, 0, offset); QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings); add_aio_request(s, aio_req, &iov, 1, AIOCB_WRITE_UDATA); acb->aio_done_func = sd_finish_aiocb; acb->aiocb_type = AIOCB_WRITE_UDATA; return; } sd_finish_aiocb(acb); } /* Delete current working VDI on the snapshot chain */ static bool sd_delete(BDRVSheepdogState *s) { Error *local_err = NULL; unsigned int wlen = SD_MAX_VDI_LEN, rlen = 0; SheepdogVdiReq hdr = { .opcode = SD_OP_DEL_VDI, .base_vdi_id = s->inode.vdi_id, .data_length = wlen, .flags = SD_FLAG_CMD_WRITE, }; SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr; int fd, ret; fd = connect_to_sdog(s, &local_err); if (fd < 0) { error_report_err(local_err); return false; } ret = do_req(fd, s->aio_context, (SheepdogReq *)&hdr, s->name, &wlen, &rlen); closesocket(fd); if (ret) { return false; } switch (rsp->result) { case SD_RES_NO_VDI: error_report("%s was already deleted", s->name); /* fall through */ case SD_RES_SUCCESS: break; default: error_report("%s, %s", sd_strerror(rsp->result), s->name); return false; } return true; } /* * Create a writable VDI from a snapshot */ static int sd_create_branch(BDRVSheepdogState *s) { Error *local_err = NULL; int ret, fd; uint32_t vid; char *buf; bool deleted; DPRINTF("%" PRIx32 " is snapshot.\n", s->inode.vdi_id); buf = g_malloc(SD_INODE_SIZE); /* * Even If deletion fails, we will just create extra snapshot based on * the working VDI which was supposed to be deleted. So no need to * false bail out. */ deleted = sd_delete(s); ret = do_sd_create(s, &vid, !deleted, &local_err); if (ret) { error_report_err(local_err); goto out; } DPRINTF("%" PRIx32 " is created.\n", vid); fd = connect_to_sdog(s, &local_err); if (fd < 0) { error_report_err(local_err); ret = fd; goto out; } ret = read_object(fd, s->aio_context, buf, vid_to_vdi_oid(vid), s->inode.nr_copies, SD_INODE_SIZE, 0, s->cache_flags); closesocket(fd); if (ret < 0) { goto out; } memcpy(&s->inode, buf, sizeof(s->inode)); s->is_snapshot = false; ret = 0; DPRINTF("%" PRIx32 " was newly created.\n", s->inode.vdi_id); out: g_free(buf); return ret; } /* * Send I/O requests to the server. * * This function sends requests to the server, links the requests to * the inflight_list in BDRVSheepdogState, and exits without * waiting the response. The responses are received in the * `aio_read_response' function which is called from the main loop as * a fd handler. * * Returns 1 when we need to wait a response, 0 when there is no sent * request and -errno in error cases. */ static int coroutine_fn sd_co_rw_vector(void *p) { SheepdogAIOCB *acb = p; int ret = 0; unsigned long len, done = 0, total = acb->nb_sectors * BDRV_SECTOR_SIZE; unsigned long idx; uint32_t object_size; uint64_t oid; uint64_t offset; BDRVSheepdogState *s = acb->common.bs->opaque; SheepdogInode *inode = &s->inode; AIOReq *aio_req; if (acb->aiocb_type == AIOCB_WRITE_UDATA && s->is_snapshot) { /* * In the case we open the snapshot VDI, Sheepdog creates the * writable VDI when we do a write operation first. */ ret = sd_create_branch(s); if (ret) { acb->ret = -EIO; goto out; } } object_size = (UINT32_C(1) << inode->block_size_shift); idx = acb->sector_num * BDRV_SECTOR_SIZE / object_size; offset = (acb->sector_num * BDRV_SECTOR_SIZE) % object_size; /* * Make sure we don't free the aiocb before we are done with all requests. * This additional reference is dropped at the end of this function. */ acb->nr_pending++; while (done != total) { uint8_t flags = 0; uint64_t old_oid = 0; bool create = false; oid = vid_to_data_oid(inode->data_vdi_id[idx], idx); len = MIN(total - done, object_size - offset); switch (acb->aiocb_type) { case AIOCB_READ_UDATA: if (!inode->data_vdi_id[idx]) { qemu_iovec_memset(acb->qiov, done, 0, len); goto done; } break; case AIOCB_WRITE_UDATA: if (!inode->data_vdi_id[idx]) { create = true; } else if (!is_data_obj_writable(inode, idx)) { /* Copy-On-Write */ create = true; old_oid = oid; flags = SD_FLAG_CMD_COW; } break; case AIOCB_DISCARD_OBJ: /* * We discard the object only when the whole object is * 1) allocated 2) trimmed. Otherwise, simply skip it. */ if (len != object_size || inode->data_vdi_id[idx] == 0) { goto done; } break; default: break; } if (create) { DPRINTF("update ino (%" PRIu32 ") %" PRIu64 " %" PRIu64 " %ld\n", inode->vdi_id, oid, vid_to_data_oid(inode->data_vdi_id[idx], idx), idx); oid = vid_to_data_oid(inode->vdi_id, idx); DPRINTF("new oid %" PRIx64 "\n", oid); } aio_req = alloc_aio_req(s, acb, oid, len, offset, flags, create, old_oid, acb->aiocb_type == AIOCB_DISCARD_OBJ ? 0 : done); QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings); add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov, acb->aiocb_type); done: offset = 0; idx++; done += len; } out: if (!--acb->nr_pending) { return acb->ret; } return 1; } static bool check_overlapping_aiocb(BDRVSheepdogState *s, SheepdogAIOCB *aiocb) { SheepdogAIOCB *cb; QLIST_FOREACH(cb, &s->inflight_aiocb_head, aiocb_siblings) { if (AIOCBOverlapping(aiocb, cb)) { return true; } } QLIST_INSERT_HEAD(&s->inflight_aiocb_head, aiocb, aiocb_siblings); return false; } static coroutine_fn int sd_co_writev(BlockDriverState *bs, int64_t sector_num, int nb_sectors, QEMUIOVector *qiov) { SheepdogAIOCB *acb; int ret; int64_t offset = (sector_num + nb_sectors) * BDRV_SECTOR_SIZE; BDRVSheepdogState *s = bs->opaque; if (offset > s->inode.vdi_size) { ret = sd_truncate(bs, offset); if (ret < 0) { return ret; } } acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors); acb->aio_done_func = sd_write_done; acb->aiocb_type = AIOCB_WRITE_UDATA; retry: if (check_overlapping_aiocb(s, acb)) { qemu_co_queue_wait(&s->overlapping_queue); goto retry; } ret = sd_co_rw_vector(acb); if (ret <= 0) { QLIST_REMOVE(acb, aiocb_siblings); qemu_co_queue_restart_all(&s->overlapping_queue); qemu_aio_unref(acb); return ret; } qemu_coroutine_yield(); QLIST_REMOVE(acb, aiocb_siblings); qemu_co_queue_restart_all(&s->overlapping_queue); return acb->ret; } static coroutine_fn int sd_co_readv(BlockDriverState *bs, int64_t sector_num, int nb_sectors, QEMUIOVector *qiov) { SheepdogAIOCB *acb; int ret; BDRVSheepdogState *s = bs->opaque; acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors); acb->aiocb_type = AIOCB_READ_UDATA; acb->aio_done_func = sd_finish_aiocb; retry: if (check_overlapping_aiocb(s, acb)) { qemu_co_queue_wait(&s->overlapping_queue); goto retry; } ret = sd_co_rw_vector(acb); if (ret <= 0) { QLIST_REMOVE(acb, aiocb_siblings); qemu_co_queue_restart_all(&s->overlapping_queue); qemu_aio_unref(acb); return ret; } qemu_coroutine_yield(); QLIST_REMOVE(acb, aiocb_siblings); qemu_co_queue_restart_all(&s->overlapping_queue); return acb->ret; } static int coroutine_fn sd_co_flush_to_disk(BlockDriverState *bs) { BDRVSheepdogState *s = bs->opaque; SheepdogAIOCB *acb; AIOReq *aio_req; if (s->cache_flags != SD_FLAG_CMD_CACHE) { return 0; } acb = sd_aio_setup(bs, NULL, 0, 0); acb->aiocb_type = AIOCB_FLUSH_CACHE; acb->aio_done_func = sd_finish_aiocb; aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id), 0, 0, 0, false, 0, 0); QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings); add_aio_request(s, aio_req, NULL, 0, acb->aiocb_type); qemu_coroutine_yield(); return acb->ret; } static int sd_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info) { Error *local_err = NULL; BDRVSheepdogState *s = bs->opaque; int ret, fd; uint32_t new_vid; SheepdogInode *inode; unsigned int datalen; DPRINTF("sn_info: name %s id_str %s s: name %s vm_state_size %" PRId64 " " "is_snapshot %d\n", sn_info->name, sn_info->id_str, s->name, sn_info->vm_state_size, s->is_snapshot); if (s->is_snapshot) { error_report("You can't create a snapshot of a snapshot VDI, " "%s (%" PRIu32 ").", s->name, s->inode.vdi_id); return -EINVAL; } DPRINTF("%s %s\n", sn_info->name, sn_info->id_str); s->inode.vm_state_size = sn_info->vm_state_size; s->inode.vm_clock_nsec = sn_info->vm_clock_nsec; /* It appears that inode.tag does not require a NUL terminator, * which means this use of strncpy is ok. */ strncpy(s->inode.tag, sn_info->name, sizeof(s->inode.tag)); /* we don't need to update entire object */ datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id); inode = g_malloc(datalen); /* refresh inode. */ fd = connect_to_sdog(s, &local_err); if (fd < 0) { error_report_err(local_err); ret = fd; goto cleanup; } ret = write_object(fd, s->aio_context, (char *)&s->inode, vid_to_vdi_oid(s->inode.vdi_id), s->inode.nr_copies, datalen, 0, false, s->cache_flags); if (ret < 0) { error_report("failed to write snapshot's inode."); goto cleanup; } ret = do_sd_create(s, &new_vid, 1, &local_err); if (ret < 0) { error_reportf_err(local_err, "failed to create inode for snapshot: "); goto cleanup; } ret = read_object(fd, s->aio_context, (char *)inode, vid_to_vdi_oid(new_vid), s->inode.nr_copies, datalen, 0, s->cache_flags); if (ret < 0) { error_report("failed to read new inode info. %s", strerror(errno)); goto cleanup; } memcpy(&s->inode, inode, datalen); DPRINTF("s->inode: name %s snap_id %x oid %x\n", s->inode.name, s->inode.snap_id, s->inode.vdi_id); cleanup: g_free(inode); closesocket(fd); return ret; } /* * We implement rollback(loadvm) operation to the specified snapshot by * 1) switch to the snapshot * 2) rely on sd_create_branch to delete working VDI and * 3) create a new working VDI based on the specified snapshot */ static int sd_snapshot_goto(BlockDriverState *bs, const char *snapshot_id) { BDRVSheepdogState *s = bs->opaque; BDRVSheepdogState *old_s; char tag[SD_MAX_VDI_TAG_LEN]; uint32_t snapid = 0; int ret = 0; old_s = g_new(BDRVSheepdogState, 1); memcpy(old_s, s, sizeof(BDRVSheepdogState)); snapid = strtoul(snapshot_id, NULL, 10); if (snapid) { tag[0] = 0; } else { pstrcpy(tag, sizeof(tag), snapshot_id); } ret = reload_inode(s, snapid, tag); if (ret) { goto out; } ret = sd_create_branch(s); if (ret) { goto out; } g_free(old_s); return 0; out: /* recover bdrv_sd_state */ memcpy(s, old_s, sizeof(BDRVSheepdogState)); g_free(old_s); error_report("failed to open. recover old bdrv_sd_state."); return ret; } #define NR_BATCHED_DISCARD 128 static bool remove_objects(BDRVSheepdogState *s) { int fd, i = 0, nr_objs = 0; Error *local_err = NULL; int ret = 0; bool result = true; SheepdogInode *inode = &s->inode; fd = connect_to_sdog(s, &local_err); if (fd < 0) { error_report_err(local_err); return false; } nr_objs = count_data_objs(inode); while (i < nr_objs) { int start_idx, nr_filled_idx; while (i < nr_objs && !inode->data_vdi_id[i]) { i++; } start_idx = i; nr_filled_idx = 0; while (i < nr_objs && nr_filled_idx < NR_BATCHED_DISCARD) { if (inode->data_vdi_id[i]) { inode->data_vdi_id[i] = 0; nr_filled_idx++; } i++; } ret = write_object(fd, s->aio_context, (char *)&inode->data_vdi_id[start_idx], vid_to_vdi_oid(s->inode.vdi_id), inode->nr_copies, (i - start_idx) * sizeof(uint32_t), offsetof(struct SheepdogInode, data_vdi_id[start_idx]), false, s->cache_flags); if (ret < 0) { error_report("failed to discard snapshot inode."); result = false; goto out; } } out: closesocket(fd); return result; } static int sd_snapshot_delete(BlockDriverState *bs, const char *snapshot_id, const char *name, Error **errp) { unsigned long snap_id = 0; char snap_tag[SD_MAX_VDI_TAG_LEN]; Error *local_err = NULL; int fd, ret; char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN]; BDRVSheepdogState *s = bs->opaque; unsigned int wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN, rlen = 0; uint32_t vid; SheepdogVdiReq hdr = { .opcode = SD_OP_DEL_VDI, .data_length = wlen, .flags = SD_FLAG_CMD_WRITE, }; SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr; if (!remove_objects(s)) { return -1; } memset(buf, 0, sizeof(buf)); memset(snap_tag, 0, sizeof(snap_tag)); pstrcpy(buf, SD_MAX_VDI_LEN, s->name); ret = qemu_strtoul(snapshot_id, NULL, 10, &snap_id); if (ret || snap_id > UINT32_MAX) { error_setg(errp, "Invalid snapshot ID: %s", snapshot_id ? snapshot_id : "<null>"); return -EINVAL; } if (snap_id) { hdr.snapid = (uint32_t) snap_id; } else { pstrcpy(snap_tag, sizeof(snap_tag), snapshot_id); pstrcpy(buf + SD_MAX_VDI_LEN, SD_MAX_VDI_TAG_LEN, snap_tag); } ret = find_vdi_name(s, s->name, snap_id, snap_tag, &vid, true, &local_err); if (ret) { return ret; } fd = connect_to_sdog(s, &local_err); if (fd < 0) { error_report_err(local_err); return -1; } ret = do_req(fd, s->aio_context, (SheepdogReq *)&hdr, buf, &wlen, &rlen); closesocket(fd); if (ret) { return ret; } switch (rsp->result) { case SD_RES_NO_VDI: error_report("%s was already deleted", s->name); case SD_RES_SUCCESS: break; default: error_report("%s, %s", sd_strerror(rsp->result), s->name); return -1; } return ret; } static int sd_snapshot_list(BlockDriverState *bs, QEMUSnapshotInfo **psn_tab) { Error *local_err = NULL; BDRVSheepdogState *s = bs->opaque; SheepdogReq req; int fd, nr = 1024, ret, max = BITS_TO_LONGS(SD_NR_VDIS) * sizeof(long); QEMUSnapshotInfo *sn_tab = NULL; unsigned wlen, rlen; int found = 0; static SheepdogInode inode; unsigned long *vdi_inuse; unsigned int start_nr; uint64_t hval; uint32_t vid; vdi_inuse = g_malloc(max); fd = connect_to_sdog(s, &local_err); if (fd < 0) { error_report_err(local_err); ret = fd; goto out; } rlen = max; wlen = 0; memset(&req, 0, sizeof(req)); req.opcode = SD_OP_READ_VDIS; req.data_length = max; ret = do_req(fd, s->aio_context, (SheepdogReq *)&req, vdi_inuse, &wlen, &rlen); closesocket(fd); if (ret) { goto out; } sn_tab = g_new0(QEMUSnapshotInfo, nr); /* calculate a vdi id with hash function */ hval = fnv_64a_buf(s->name, strlen(s->name), FNV1A_64_INIT); start_nr = hval & (SD_NR_VDIS - 1); fd = connect_to_sdog(s, &local_err); if (fd < 0) { error_report_err(local_err); ret = fd; goto out; } for (vid = start_nr; found < nr; vid = (vid + 1) % SD_NR_VDIS) { if (!test_bit(vid, vdi_inuse)) { break; } /* we don't need to read entire object */ ret = read_object(fd, s->aio_context, (char *)&inode, vid_to_vdi_oid(vid), 0, SD_INODE_SIZE - sizeof(inode.data_vdi_id), 0, s->cache_flags); if (ret) { continue; } if (!strcmp(inode.name, s->name) && is_snapshot(&inode)) { sn_tab[found].date_sec = inode.snap_ctime >> 32; sn_tab[found].date_nsec = inode.snap_ctime & 0xffffffff; sn_tab[found].vm_state_size = inode.vm_state_size; sn_tab[found].vm_clock_nsec = inode.vm_clock_nsec; snprintf(sn_tab[found].id_str, sizeof(sn_tab[found].id_str), "%" PRIu32, inode.snap_id); pstrcpy(sn_tab[found].name, MIN(sizeof(sn_tab[found].name), sizeof(inode.tag)), inode.tag); found++; } } closesocket(fd); out: *psn_tab = sn_tab; g_free(vdi_inuse); if (ret < 0) { return ret; } return found; } static int do_load_save_vmstate(BDRVSheepdogState *s, uint8_t *data, int64_t pos, int size, int load) { Error *local_err = NULL; bool create; int fd, ret = 0, remaining = size; unsigned int data_len; uint64_t vmstate_oid; uint64_t offset; uint32_t vdi_index; uint32_t vdi_id = load ? s->inode.parent_vdi_id : s->inode.vdi_id; uint32_t object_size = (UINT32_C(1) << s->inode.block_size_shift); fd = connect_to_sdog(s, &local_err); if (fd < 0) { error_report_err(local_err); return fd; } while (remaining) { vdi_index = pos / object_size; offset = pos % object_size; data_len = MIN(remaining, object_size - offset); vmstate_oid = vid_to_vmstate_oid(vdi_id, vdi_index); create = (offset == 0); if (load) { ret = read_object(fd, s->aio_context, (char *)data, vmstate_oid, s->inode.nr_copies, data_len, offset, s->cache_flags); } else { ret = write_object(fd, s->aio_context, (char *)data, vmstate_oid, s->inode.nr_copies, data_len, offset, create, s->cache_flags); } if (ret < 0) { error_report("failed to save vmstate %s", strerror(errno)); goto cleanup; } pos += data_len; data += data_len; remaining -= data_len; } ret = size; cleanup: closesocket(fd); return ret; } static int sd_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos) { BDRVSheepdogState *s = bs->opaque; void *buf; int ret; buf = qemu_blockalign(bs, qiov->size); qemu_iovec_to_buf(qiov, 0, buf, qiov->size); ret = do_load_save_vmstate(s, (uint8_t *) buf, pos, qiov->size, 0); qemu_vfree(buf); return ret; } static int sd_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos) { BDRVSheepdogState *s = bs->opaque; void *buf; int ret; buf = qemu_blockalign(bs, qiov->size); ret = do_load_save_vmstate(s, buf, pos, qiov->size, 1); qemu_iovec_from_buf(qiov, 0, buf, qiov->size); qemu_vfree(buf); return ret; } static coroutine_fn int sd_co_pdiscard(BlockDriverState *bs, int64_t offset, int count) { SheepdogAIOCB *acb; BDRVSheepdogState *s = bs->opaque; int ret; QEMUIOVector discard_iov; struct iovec iov; uint32_t zero = 0; if (!s->discard_supported) { return 0; } memset(&discard_iov, 0, sizeof(discard_iov)); memset(&iov, 0, sizeof(iov)); iov.iov_base = &zero; iov.iov_len = sizeof(zero); discard_iov.iov = &iov; discard_iov.niov = 1; assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0); assert((count & (BDRV_SECTOR_SIZE - 1)) == 0); acb = sd_aio_setup(bs, &discard_iov, offset >> BDRV_SECTOR_BITS, count >> BDRV_SECTOR_BITS); acb->aiocb_type = AIOCB_DISCARD_OBJ; acb->aio_done_func = sd_finish_aiocb; retry: if (check_overlapping_aiocb(s, acb)) { qemu_co_queue_wait(&s->overlapping_queue); goto retry; } ret = sd_co_rw_vector(acb); if (ret <= 0) { QLIST_REMOVE(acb, aiocb_siblings); qemu_co_queue_restart_all(&s->overlapping_queue); qemu_aio_unref(acb); return ret; } qemu_coroutine_yield(); QLIST_REMOVE(acb, aiocb_siblings); qemu_co_queue_restart_all(&s->overlapping_queue); return acb->ret; } static coroutine_fn int64_t sd_co_get_block_status(BlockDriverState *bs, int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file) { BDRVSheepdogState *s = bs->opaque; SheepdogInode *inode = &s->inode; uint32_t object_size = (UINT32_C(1) << inode->block_size_shift); uint64_t offset = sector_num * BDRV_SECTOR_SIZE; unsigned long start = offset / object_size, end = DIV_ROUND_UP((sector_num + nb_sectors) * BDRV_SECTOR_SIZE, object_size); unsigned long idx; int64_t ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | offset; for (idx = start; idx < end; idx++) { if (inode->data_vdi_id[idx] == 0) { break; } } if (idx == start) { /* Get the longest length of unallocated sectors */ ret = 0; for (idx = start + 1; idx < end; idx++) { if (inode->data_vdi_id[idx] != 0) { break; } } } *pnum = (idx - start) * object_size / BDRV_SECTOR_SIZE; if (*pnum > nb_sectors) { *pnum = nb_sectors; } if (ret > 0 && ret & BDRV_BLOCK_OFFSET_VALID) { *file = bs; } return ret; } static int64_t sd_get_allocated_file_size(BlockDriverState *bs) { BDRVSheepdogState *s = bs->opaque; SheepdogInode *inode = &s->inode; uint32_t object_size = (UINT32_C(1) << inode->block_size_shift); unsigned long i, last = DIV_ROUND_UP(inode->vdi_size, object_size); uint64_t size = 0; for (i = 0; i < last; i++) { if (inode->data_vdi_id[i] == 0) { continue; } size += object_size; } return size; } static QemuOptsList sd_create_opts = { .name = "sheepdog-create-opts", .head = QTAILQ_HEAD_INITIALIZER(sd_create_opts.head), .desc = { { .name = BLOCK_OPT_SIZE, .type = QEMU_OPT_SIZE, .help = "Virtual disk size" }, { .name = BLOCK_OPT_BACKING_FILE, .type = QEMU_OPT_STRING, .help = "File name of a base image" }, { .name = BLOCK_OPT_PREALLOC, .type = QEMU_OPT_STRING, .help = "Preallocation mode (allowed values: off, full)" }, { .name = BLOCK_OPT_REDUNDANCY, .type = QEMU_OPT_STRING, .help = "Redundancy of the image" }, { .name = BLOCK_OPT_OBJECT_SIZE, .type = QEMU_OPT_SIZE, .help = "Object size of the image" }, { /* end of list */ } } }; static BlockDriver bdrv_sheepdog = { .format_name = "sheepdog", .protocol_name = "sheepdog", .instance_size = sizeof(BDRVSheepdogState), .bdrv_needs_filename = true, .bdrv_file_open = sd_open, .bdrv_reopen_prepare = sd_reopen_prepare, .bdrv_reopen_commit = sd_reopen_commit, .bdrv_reopen_abort = sd_reopen_abort, .bdrv_close = sd_close, .bdrv_create = sd_create, .bdrv_has_zero_init = bdrv_has_zero_init_1, .bdrv_getlength = sd_getlength, .bdrv_get_allocated_file_size = sd_get_allocated_file_size, .bdrv_truncate = sd_truncate, .bdrv_co_readv = sd_co_readv, .bdrv_co_writev = sd_co_writev, .bdrv_co_flush_to_disk = sd_co_flush_to_disk, .bdrv_co_pdiscard = sd_co_pdiscard, .bdrv_co_get_block_status = sd_co_get_block_status, .bdrv_snapshot_create = sd_snapshot_create, .bdrv_snapshot_goto = sd_snapshot_goto, .bdrv_snapshot_delete = sd_snapshot_delete, .bdrv_snapshot_list = sd_snapshot_list, .bdrv_save_vmstate = sd_save_vmstate, .bdrv_load_vmstate = sd_load_vmstate, .bdrv_detach_aio_context = sd_detach_aio_context, .bdrv_attach_aio_context = sd_attach_aio_context, .create_opts = &sd_create_opts, }; static BlockDriver bdrv_sheepdog_tcp = { .format_name = "sheepdog", .protocol_name = "sheepdog+tcp", .instance_size = sizeof(BDRVSheepdogState), .bdrv_needs_filename = true, .bdrv_file_open = sd_open, .bdrv_reopen_prepare = sd_reopen_prepare, .bdrv_reopen_commit = sd_reopen_commit, .bdrv_reopen_abort = sd_reopen_abort, .bdrv_close = sd_close, .bdrv_create = sd_create, .bdrv_has_zero_init = bdrv_has_zero_init_1, .bdrv_getlength = sd_getlength, .bdrv_get_allocated_file_size = sd_get_allocated_file_size, .bdrv_truncate = sd_truncate, .bdrv_co_readv = sd_co_readv, .bdrv_co_writev = sd_co_writev, .bdrv_co_flush_to_disk = sd_co_flush_to_disk, .bdrv_co_pdiscard = sd_co_pdiscard, .bdrv_co_get_block_status = sd_co_get_block_status, .bdrv_snapshot_create = sd_snapshot_create, .bdrv_snapshot_goto = sd_snapshot_goto, .bdrv_snapshot_delete = sd_snapshot_delete, .bdrv_snapshot_list = sd_snapshot_list, .bdrv_save_vmstate = sd_save_vmstate, .bdrv_load_vmstate = sd_load_vmstate, .bdrv_detach_aio_context = sd_detach_aio_context, .bdrv_attach_aio_context = sd_attach_aio_context, .create_opts = &sd_create_opts, }; static BlockDriver bdrv_sheepdog_unix = { .format_name = "sheepdog", .protocol_name = "sheepdog+unix", .instance_size = sizeof(BDRVSheepdogState), .bdrv_needs_filename = true, .bdrv_file_open = sd_open, .bdrv_reopen_prepare = sd_reopen_prepare, .bdrv_reopen_commit = sd_reopen_commit, .bdrv_reopen_abort = sd_reopen_abort, .bdrv_close = sd_close, .bdrv_create = sd_create, .bdrv_has_zero_init = bdrv_has_zero_init_1, .bdrv_getlength = sd_getlength, .bdrv_get_allocated_file_size = sd_get_allocated_file_size, .bdrv_truncate = sd_truncate, .bdrv_co_readv = sd_co_readv, .bdrv_co_writev = sd_co_writev, .bdrv_co_flush_to_disk = sd_co_flush_to_disk, .bdrv_co_pdiscard = sd_co_pdiscard, .bdrv_co_get_block_status = sd_co_get_block_status, .bdrv_snapshot_create = sd_snapshot_create, .bdrv_snapshot_goto = sd_snapshot_goto, .bdrv_snapshot_delete = sd_snapshot_delete, .bdrv_snapshot_list = sd_snapshot_list, .bdrv_save_vmstate = sd_save_vmstate, .bdrv_load_vmstate = sd_load_vmstate, .bdrv_detach_aio_context = sd_detach_aio_context, .bdrv_attach_aio_context = sd_attach_aio_context, .create_opts = &sd_create_opts, }; static void bdrv_sheepdog_init(void) { bdrv_register(&bdrv_sheepdog); bdrv_register(&bdrv_sheepdog_tcp); bdrv_register(&bdrv_sheepdog_unix); } block_init(bdrv_sheepdog_init);