]> git.proxmox.com Git - ceph.git/blob - ceph/src/librbd/ImageCtx.cc
c97b11505d7744e7c8ed6d5e1395d6b1edd5f382
[ceph.git] / ceph / src / librbd / ImageCtx.cc
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
3 #include <errno.h>
4 #include <boost/assign/list_of.hpp>
5 #include <stddef.h>
6
7 #include "common/ceph_context.h"
8 #include "common/dout.h"
9 #include "common/errno.h"
10 #include "common/perf_counters.h"
11 #include "common/WorkQueue.h"
12 #include "common/Timer.h"
13
14 #include "librbd/AsyncRequest.h"
15 #include "librbd/ExclusiveLock.h"
16 #include "librbd/internal.h"
17 #include "librbd/ImageCtx.h"
18 #include "librbd/ImageState.h"
19 #include "librbd/ImageWatcher.h"
20 #include "librbd/Journal.h"
21 #include "librbd/LibrbdAdminSocketHook.h"
22 #include "librbd/ObjectMap.h"
23 #include "librbd/Operations.h"
24 #include "librbd/operation/ResizeRequest.h"
25 #include "librbd/Utils.h"
26 #include "librbd/LibrbdWriteback.h"
27 #include "librbd/exclusive_lock/AutomaticPolicy.h"
28 #include "librbd/exclusive_lock/StandardPolicy.h"
29 #include "librbd/io/AioCompletion.h"
30 #include "librbd/io/AsyncOperation.h"
31 #include "librbd/io/ImageRequestWQ.h"
32 #include "librbd/journal/StandardPolicy.h"
33
34 #include "osdc/Striper.h"
35 #include <boost/bind.hpp>
36
37 #define dout_subsys ceph_subsys_rbd
38 #undef dout_prefix
39 #define dout_prefix *_dout << "librbd::ImageCtx: "
40
41 using std::map;
42 using std::pair;
43 using std::set;
44 using std::string;
45 using std::vector;
46
47 using ceph::bufferlist;
48 using librados::snap_t;
49 using librados::IoCtx;
50
51 namespace librbd {
52
53 namespace {
54
55 class ThreadPoolSingleton : public ThreadPool {
56 public:
57 ContextWQ *op_work_queue;
58
59 explicit ThreadPoolSingleton(CephContext *cct)
60 : ThreadPool(cct, "librbd::thread_pool", "tp_librbd", 1,
61 "rbd_op_threads"),
62 op_work_queue(new ContextWQ("librbd::op_work_queue",
63 cct->_conf->rbd_op_thread_timeout,
64 this)) {
65 start();
66 }
67 ~ThreadPoolSingleton() override {
68 op_work_queue->drain();
69 delete op_work_queue;
70
71 stop();
72 }
73 };
74
75 class SafeTimerSingleton : public SafeTimer {
76 public:
77 Mutex lock;
78
79 explicit SafeTimerSingleton(CephContext *cct)
80 : SafeTimer(cct, lock, true),
81 lock("librbd::Journal::SafeTimerSingleton::lock") {
82 init();
83 }
84 ~SafeTimerSingleton() {
85 Mutex::Locker locker(lock);
86 shutdown();
87 }
88 };
89
90 struct C_FlushCache : public Context {
91 ImageCtx *image_ctx;
92 Context *on_safe;
93
94 C_FlushCache(ImageCtx *_image_ctx, Context *_on_safe)
95 : image_ctx(_image_ctx), on_safe(_on_safe) {
96 }
97 void finish(int r) override {
98 // successful cache flush indicates all IO is now safe
99 image_ctx->flush_cache(on_safe);
100 }
101 };
102
103 struct C_ShutDownCache : public Context {
104 ImageCtx *image_ctx;
105 Context *on_finish;
106
107 C_ShutDownCache(ImageCtx *_image_ctx, Context *_on_finish)
108 : image_ctx(_image_ctx), on_finish(_on_finish) {
109 }
110 void finish(int r) override {
111 image_ctx->object_cacher->stop();
112 on_finish->complete(r);
113 }
114 };
115
116 struct C_InvalidateCache : public Context {
117 ImageCtx *image_ctx;
118 bool purge_on_error;
119 bool reentrant_safe;
120 Context *on_finish;
121
122 C_InvalidateCache(ImageCtx *_image_ctx, bool _purge_on_error,
123 bool _reentrant_safe, Context *_on_finish)
124 : image_ctx(_image_ctx), purge_on_error(_purge_on_error),
125 reentrant_safe(_reentrant_safe), on_finish(_on_finish) {
126 }
127 void finish(int r) override {
128 assert(image_ctx->cache_lock.is_locked());
129 CephContext *cct = image_ctx->cct;
130
131 if (r == -EBLACKLISTED) {
132 lderr(cct) << "Blacklisted during flush! Purging cache..." << dendl;
133 image_ctx->object_cacher->purge_set(image_ctx->object_set);
134 } else if (r != 0 && purge_on_error) {
135 lderr(cct) << "invalidate cache encountered error "
136 << cpp_strerror(r) << " !Purging cache..." << dendl;
137 image_ctx->object_cacher->purge_set(image_ctx->object_set);
138 } else if (r != 0) {
139 lderr(cct) << "flush_cache returned " << r << dendl;
140 }
141
142 loff_t unclean = image_ctx->object_cacher->release_set(
143 image_ctx->object_set);
144 if (unclean == 0) {
145 r = 0;
146 } else {
147 lderr(cct) << "could not release all objects from cache: "
148 << unclean << " bytes remain" << dendl;
149 if (r == 0) {
150 r = -EBUSY;
151 }
152 }
153
154 if (reentrant_safe) {
155 on_finish->complete(r);
156 } else {
157 image_ctx->op_work_queue->queue(on_finish, r);
158 }
159 }
160
161 };
162
163 } // anonymous namespace
164
165 const string ImageCtx::METADATA_CONF_PREFIX = "conf_";
166
167 ImageCtx::ImageCtx(const string &image_name, const string &image_id,
168 const char *snap, IoCtx& p, bool ro)
169 : cct((CephContext*)p.cct()),
170 perfcounter(NULL),
171 snap_id(CEPH_NOSNAP),
172 snap_exists(true),
173 read_only(ro),
174 flush_encountered(false),
175 exclusive_locked(false),
176 name(image_name),
177 image_watcher(NULL),
178 journal(NULL),
179 owner_lock(util::unique_lock_name("librbd::ImageCtx::owner_lock", this)),
180 md_lock(util::unique_lock_name("librbd::ImageCtx::md_lock", this)),
181 cache_lock(util::unique_lock_name("librbd::ImageCtx::cache_lock", this)),
182 snap_lock(util::unique_lock_name("librbd::ImageCtx::snap_lock", this)),
183 parent_lock(util::unique_lock_name("librbd::ImageCtx::parent_lock", this)),
184 object_map_lock(util::unique_lock_name("librbd::ImageCtx::object_map_lock", this)),
185 async_ops_lock(util::unique_lock_name("librbd::ImageCtx::async_ops_lock", this)),
186 copyup_list_lock(util::unique_lock_name("librbd::ImageCtx::copyup_list_lock", this)),
187 completed_reqs_lock(util::unique_lock_name("librbd::ImageCtx::completed_reqs_lock", this)),
188 extra_read_flags(0),
189 old_format(true),
190 order(0), size(0), features(0),
191 format_string(NULL),
192 id(image_id), parent(NULL),
193 stripe_unit(0), stripe_count(0), flags(0),
194 object_cacher(NULL), writeback_handler(NULL), object_set(NULL),
195 readahead(),
196 total_bytes_read(0),
197 state(new ImageState<>(this)),
198 operations(new Operations<>(*this)),
199 exclusive_lock(nullptr), object_map(nullptr),
200 io_work_queue(nullptr), op_work_queue(nullptr),
201 asok_hook(nullptr),
202 trace_endpoint("librbd")
203 {
204 md_ctx.dup(p);
205 data_ctx.dup(p);
206 if (snap)
207 snap_name = snap;
208
209 memset(&header, 0, sizeof(header));
210
211 ThreadPool *thread_pool;
212 get_thread_pool_instance(cct, &thread_pool, &op_work_queue);
213 io_work_queue = new io::ImageRequestWQ<>(
214 this, "librbd::io_work_queue", cct->_conf->rbd_op_thread_timeout,
215 thread_pool);
216
217 if (cct->_conf->rbd_auto_exclusive_lock_until_manual_request) {
218 exclusive_lock_policy = new exclusive_lock::AutomaticPolicy(this);
219 } else {
220 exclusive_lock_policy = new exclusive_lock::StandardPolicy(this);
221 }
222 journal_policy = new journal::StandardPolicy<ImageCtx>(this);
223 }
224
225 ImageCtx::~ImageCtx() {
226 assert(image_watcher == NULL);
227 assert(exclusive_lock == NULL);
228 assert(object_map == NULL);
229 assert(journal == NULL);
230 assert(asok_hook == NULL);
231
232 if (perfcounter) {
233 perf_stop();
234 }
235 if (object_cacher) {
236 delete object_cacher;
237 object_cacher = NULL;
238 }
239 if (writeback_handler) {
240 delete writeback_handler;
241 writeback_handler = NULL;
242 }
243 if (object_set) {
244 delete object_set;
245 object_set = NULL;
246 }
247 delete[] format_string;
248
249 md_ctx.aio_flush();
250 data_ctx.aio_flush();
251 io_work_queue->drain();
252
253 delete journal_policy;
254 delete exclusive_lock_policy;
255 delete io_work_queue;
256 delete operations;
257 delete state;
258 }
259
260 void ImageCtx::init() {
261 assert(!header_oid.empty());
262 assert(old_format || !id.empty());
263
264 asok_hook = new LibrbdAdminSocketHook(this);
265
266 string pname = string("librbd-") + id + string("-") +
267 data_ctx.get_pool_name() + string("-") + name;
268 if (!snap_name.empty()) {
269 pname += "-";
270 pname += snap_name;
271 }
272
273 trace_endpoint.copy_name(pname);
274 perf_start(pname);
275
276 if (cache) {
277 Mutex::Locker l(cache_lock);
278 ldout(cct, 20) << "enabling caching..." << dendl;
279 writeback_handler = new LibrbdWriteback(this, cache_lock);
280
281 uint64_t init_max_dirty = cache_max_dirty;
282 if (cache_writethrough_until_flush)
283 init_max_dirty = 0;
284 ldout(cct, 20) << "Initial cache settings:"
285 << " size=" << cache_size
286 << " num_objects=" << 10
287 << " max_dirty=" << init_max_dirty
288 << " target_dirty=" << cache_target_dirty
289 << " max_dirty_age="
290 << cache_max_dirty_age << dendl;
291
292 object_cacher = new ObjectCacher(cct, pname, *writeback_handler, cache_lock,
293 NULL, NULL,
294 cache_size,
295 10, /* reset this in init */
296 init_max_dirty,
297 cache_target_dirty,
298 cache_max_dirty_age,
299 cache_block_writes_upfront);
300
301 // size object cache appropriately
302 uint64_t obj = cache_max_dirty_object;
303 if (!obj) {
304 obj = MIN(2000, MAX(10, cache_size / 100 / sizeof(ObjectCacher::Object)));
305 }
306 ldout(cct, 10) << " cache bytes " << cache_size
307 << " -> about " << obj << " objects" << dendl;
308 object_cacher->set_max_objects(obj);
309
310 object_set = new ObjectCacher::ObjectSet(NULL, data_ctx.get_id(), 0);
311 object_set->return_enoent = true;
312 object_cacher->start();
313 }
314
315 readahead.set_trigger_requests(readahead_trigger_requests);
316 readahead.set_max_readahead_size(readahead_max_bytes);
317 }
318
319 void ImageCtx::shutdown() {
320 delete image_watcher;
321 image_watcher = nullptr;
322
323 delete asok_hook;
324 asok_hook = nullptr;
325 }
326
327 void ImageCtx::init_layout()
328 {
329 if (stripe_unit == 0 || stripe_count == 0) {
330 stripe_unit = 1ull << order;
331 stripe_count = 1;
332 }
333
334 vector<uint64_t> alignments;
335 alignments.push_back(stripe_count << order); // object set (in file striping terminology)
336 alignments.push_back(stripe_unit * stripe_count); // stripe
337 alignments.push_back(stripe_unit); // stripe unit
338 readahead.set_alignments(alignments);
339
340 layout = file_layout_t();
341 layout.stripe_unit = stripe_unit;
342 layout.stripe_count = stripe_count;
343 layout.object_size = 1ull << order;
344 layout.pool_id = data_ctx.get_id(); // FIXME: pool id overflow?
345
346 delete[] format_string;
347 size_t len = object_prefix.length() + 16;
348 format_string = new char[len];
349 if (old_format) {
350 snprintf(format_string, len, "%s.%%012llx", object_prefix.c_str());
351 } else {
352 snprintf(format_string, len, "%s.%%016llx", object_prefix.c_str());
353 }
354
355 ldout(cct, 10) << "init_layout stripe_unit " << stripe_unit
356 << " stripe_count " << stripe_count
357 << " object_size " << layout.object_size
358 << " prefix " << object_prefix
359 << " format " << format_string
360 << dendl;
361 }
362
363 void ImageCtx::perf_start(string name) {
364 PerfCountersBuilder plb(cct, name, l_librbd_first, l_librbd_last);
365
366 plb.add_u64_counter(l_librbd_rd, "rd", "Reads");
367 plb.add_u64_counter(l_librbd_rd_bytes, "rd_bytes", "Data size in reads");
368 plb.add_time_avg(l_librbd_rd_latency, "rd_latency", "Latency of reads");
369 plb.add_u64_counter(l_librbd_wr, "wr", "Writes");
370 plb.add_u64_counter(l_librbd_wr_bytes, "wr_bytes", "Written data");
371 plb.add_time_avg(l_librbd_wr_latency, "wr_latency", "Write latency");
372 plb.add_u64_counter(l_librbd_discard, "discard", "Discards");
373 plb.add_u64_counter(l_librbd_discard_bytes, "discard_bytes", "Discarded data");
374 plb.add_time_avg(l_librbd_discard_latency, "discard_latency", "Discard latency");
375 plb.add_u64_counter(l_librbd_flush, "flush", "Flushes");
376 plb.add_u64_counter(l_librbd_aio_flush, "aio_flush", "Async flushes");
377 plb.add_time_avg(l_librbd_aio_flush_latency, "aio_flush_latency", "Latency of async flushes");
378 plb.add_u64_counter(l_librbd_ws, "ws", "WriteSames");
379 plb.add_u64_counter(l_librbd_ws_bytes, "ws_bytes", "WriteSame data");
380 plb.add_time_avg(l_librbd_ws_latency, "ws_latency", "WriteSame latency");
381 plb.add_u64_counter(l_librbd_cmp, "cmp", "CompareAndWrites");
382 plb.add_u64_counter(l_librbd_cmp_bytes, "cmp_bytes", "Data size in cmps");
383 plb.add_time_avg(l_librbd_cmp_latency, "cmp_latency", "Latency of cmps");
384 plb.add_u64_counter(l_librbd_snap_create, "snap_create", "Snap creations");
385 plb.add_u64_counter(l_librbd_snap_remove, "snap_remove", "Snap removals");
386 plb.add_u64_counter(l_librbd_snap_rollback, "snap_rollback", "Snap rollbacks");
387 plb.add_u64_counter(l_librbd_snap_rename, "snap_rename", "Snap rename");
388 plb.add_u64_counter(l_librbd_notify, "notify", "Updated header notifications");
389 plb.add_u64_counter(l_librbd_resize, "resize", "Resizes");
390 plb.add_u64_counter(l_librbd_readahead, "readahead", "Read ahead");
391 plb.add_u64_counter(l_librbd_readahead_bytes, "readahead_bytes", "Data size in read ahead");
392 plb.add_u64_counter(l_librbd_invalidate_cache, "invalidate_cache", "Cache invalidates");
393
394 perfcounter = plb.create_perf_counters();
395 cct->get_perfcounters_collection()->add(perfcounter);
396 }
397
398 void ImageCtx::perf_stop() {
399 assert(perfcounter);
400 cct->get_perfcounters_collection()->remove(perfcounter);
401 delete perfcounter;
402 }
403
404 void ImageCtx::set_read_flag(unsigned flag) {
405 extra_read_flags |= flag;
406 }
407
408 int ImageCtx::get_read_flags(snap_t snap_id) {
409 int flags = librados::OPERATION_NOFLAG | extra_read_flags;
410 if (snap_id == LIBRADOS_SNAP_HEAD)
411 return flags;
412
413 if (balance_snap_reads)
414 flags |= librados::OPERATION_BALANCE_READS;
415 else if (localize_snap_reads)
416 flags |= librados::OPERATION_LOCALIZE_READS;
417 return flags;
418 }
419
420 int ImageCtx::snap_set(cls::rbd::SnapshotNamespace in_snap_namespace,
421 string in_snap_name)
422 {
423 assert(snap_lock.is_wlocked());
424 snap_t in_snap_id = get_snap_id(in_snap_namespace, in_snap_name);
425 if (in_snap_id != CEPH_NOSNAP) {
426 snap_id = in_snap_id;
427 snap_namespace = in_snap_namespace;
428 snap_name = in_snap_name;
429 snap_exists = true;
430 data_ctx.snap_set_read(snap_id);
431 return 0;
432 }
433 return -ENOENT;
434 }
435
436 void ImageCtx::snap_unset()
437 {
438 assert(snap_lock.is_wlocked());
439 snap_id = CEPH_NOSNAP;
440 snap_namespace = {};
441 snap_name = "";
442 snap_exists = true;
443 data_ctx.snap_set_read(snap_id);
444 }
445
446 snap_t ImageCtx::get_snap_id(cls::rbd::SnapshotNamespace in_snap_namespace,
447 string in_snap_name) const
448 {
449 assert(snap_lock.is_locked());
450 auto it = snap_ids.find({in_snap_namespace, in_snap_name});
451 if (it != snap_ids.end())
452 return it->second;
453 return CEPH_NOSNAP;
454 }
455
456 const SnapInfo* ImageCtx::get_snap_info(snap_t in_snap_id) const
457 {
458 assert(snap_lock.is_locked());
459 map<snap_t, SnapInfo>::const_iterator it =
460 snap_info.find(in_snap_id);
461 if (it != snap_info.end())
462 return &it->second;
463 return NULL;
464 }
465
466 int ImageCtx::get_snap_name(snap_t in_snap_id,
467 string *out_snap_name) const
468 {
469 assert(snap_lock.is_locked());
470 const SnapInfo *info = get_snap_info(in_snap_id);
471 if (info) {
472 *out_snap_name = info->name;
473 return 0;
474 }
475 return -ENOENT;
476 }
477
478 int ImageCtx::get_snap_namespace(snap_t in_snap_id,
479 cls::rbd::SnapshotNamespace *out_snap_namespace) const
480 {
481 assert(snap_lock.is_locked());
482 const SnapInfo *info = get_snap_info(in_snap_id);
483 if (info) {
484 *out_snap_namespace = info->snap_namespace;
485 return 0;
486 }
487 return -ENOENT;
488 }
489
490 int ImageCtx::get_parent_spec(snap_t in_snap_id,
491 ParentSpec *out_pspec) const
492 {
493 const SnapInfo *info = get_snap_info(in_snap_id);
494 if (info) {
495 *out_pspec = info->parent.spec;
496 return 0;
497 }
498 return -ENOENT;
499 }
500
501 uint64_t ImageCtx::get_current_size() const
502 {
503 assert(snap_lock.is_locked());
504 return size;
505 }
506
507 uint64_t ImageCtx::get_object_size() const
508 {
509 return 1ull << order;
510 }
511
512 string ImageCtx::get_object_name(uint64_t num) const {
513 char buf[object_prefix.length() + 32];
514 snprintf(buf, sizeof(buf), format_string, num);
515 return string(buf);
516 }
517
518 uint64_t ImageCtx::get_stripe_unit() const
519 {
520 return stripe_unit;
521 }
522
523 uint64_t ImageCtx::get_stripe_count() const
524 {
525 return stripe_count;
526 }
527
528 uint64_t ImageCtx::get_stripe_period() const
529 {
530 return stripe_count * (1ull << order);
531 }
532
533 utime_t ImageCtx::get_create_timestamp() const
534 {
535 return create_timestamp;
536 }
537
538 int ImageCtx::is_snap_protected(snap_t in_snap_id,
539 bool *is_protected) const
540 {
541 assert(snap_lock.is_locked());
542 const SnapInfo *info = get_snap_info(in_snap_id);
543 if (info) {
544 *is_protected =
545 (info->protection_status == RBD_PROTECTION_STATUS_PROTECTED);
546 return 0;
547 }
548 return -ENOENT;
549 }
550
551 int ImageCtx::is_snap_unprotected(snap_t in_snap_id,
552 bool *is_unprotected) const
553 {
554 assert(snap_lock.is_locked());
555 const SnapInfo *info = get_snap_info(in_snap_id);
556 if (info) {
557 *is_unprotected =
558 (info->protection_status == RBD_PROTECTION_STATUS_UNPROTECTED);
559 return 0;
560 }
561 return -ENOENT;
562 }
563
564 void ImageCtx::add_snap(cls::rbd::SnapshotNamespace in_snap_namespace,
565 string in_snap_name,
566 snap_t id, uint64_t in_size,
567 const ParentInfo &parent, uint8_t protection_status,
568 uint64_t flags, utime_t timestamp)
569 {
570 assert(snap_lock.is_wlocked());
571 snaps.push_back(id);
572 SnapInfo info(in_snap_name, in_snap_namespace,
573 in_size, parent, protection_status, flags, timestamp);
574 snap_info.insert({id, info});
575 snap_ids.insert({{in_snap_namespace, in_snap_name}, id});
576 }
577
578 void ImageCtx::rm_snap(cls::rbd::SnapshotNamespace in_snap_namespace,
579 string in_snap_name,
580 snap_t id)
581 {
582 assert(snap_lock.is_wlocked());
583 snaps.erase(std::remove(snaps.begin(), snaps.end(), id), snaps.end());
584 snap_info.erase(id);
585 snap_ids.erase({in_snap_namespace, in_snap_name});
586 }
587
588 uint64_t ImageCtx::get_image_size(snap_t in_snap_id) const
589 {
590 assert(snap_lock.is_locked());
591 if (in_snap_id == CEPH_NOSNAP) {
592 if (!resize_reqs.empty() &&
593 resize_reqs.front()->shrinking()) {
594 return resize_reqs.front()->get_image_size();
595 }
596 return size;
597 }
598
599 const SnapInfo *info = get_snap_info(in_snap_id);
600 if (info) {
601 return info->size;
602 }
603 return 0;
604 }
605
606 uint64_t ImageCtx::get_object_count(snap_t in_snap_id) const {
607 assert(snap_lock.is_locked());
608 uint64_t image_size = get_image_size(in_snap_id);
609 return Striper::get_num_objects(layout, image_size);
610 }
611
612 bool ImageCtx::test_features(uint64_t features) const
613 {
614 RWLock::RLocker l(snap_lock);
615 return test_features(features, snap_lock);
616 }
617
618 bool ImageCtx::test_features(uint64_t in_features,
619 const RWLock &in_snap_lock) const
620 {
621 assert(snap_lock.is_locked());
622 return ((features & in_features) == in_features);
623 }
624
625 int ImageCtx::get_flags(librados::snap_t _snap_id, uint64_t *_flags) const
626 {
627 assert(snap_lock.is_locked());
628 if (_snap_id == CEPH_NOSNAP) {
629 *_flags = flags;
630 return 0;
631 }
632 const SnapInfo *info = get_snap_info(_snap_id);
633 if (info) {
634 *_flags = info->flags;
635 return 0;
636 }
637 return -ENOENT;
638 }
639
640 int ImageCtx::test_flags(uint64_t flags, bool *flags_set) const
641 {
642 RWLock::RLocker l(snap_lock);
643 return test_flags(flags, snap_lock, flags_set);
644 }
645
646 int ImageCtx::test_flags(uint64_t flags, const RWLock &in_snap_lock,
647 bool *flags_set) const
648 {
649 assert(snap_lock.is_locked());
650 uint64_t snap_flags;
651 int r = get_flags(snap_id, &snap_flags);
652 if (r < 0) {
653 return r;
654 }
655 *flags_set = ((snap_flags & flags) == flags);
656 return 0;
657 }
658
659 int ImageCtx::update_flags(snap_t in_snap_id, uint64_t flag, bool enabled)
660 {
661 assert(snap_lock.is_wlocked());
662 uint64_t *_flags;
663 if (in_snap_id == CEPH_NOSNAP) {
664 _flags = &flags;
665 } else {
666 map<snap_t, SnapInfo>::iterator it = snap_info.find(in_snap_id);
667 if (it == snap_info.end()) {
668 return -ENOENT;
669 }
670 _flags = &it->second.flags;
671 }
672
673 if (enabled) {
674 (*_flags) |= flag;
675 } else {
676 (*_flags) &= ~flag;
677 }
678 return 0;
679 }
680
681 const ParentInfo* ImageCtx::get_parent_info(snap_t in_snap_id) const
682 {
683 assert(snap_lock.is_locked());
684 assert(parent_lock.is_locked());
685 if (in_snap_id == CEPH_NOSNAP)
686 return &parent_md;
687 const SnapInfo *info = get_snap_info(in_snap_id);
688 if (info)
689 return &info->parent;
690 return NULL;
691 }
692
693 int64_t ImageCtx::get_parent_pool_id(snap_t in_snap_id) const
694 {
695 const ParentInfo *info = get_parent_info(in_snap_id);
696 if (info)
697 return info->spec.pool_id;
698 return -1;
699 }
700
701 string ImageCtx::get_parent_image_id(snap_t in_snap_id) const
702 {
703 const ParentInfo *info = get_parent_info(in_snap_id);
704 if (info)
705 return info->spec.image_id;
706 return "";
707 }
708
709 uint64_t ImageCtx::get_parent_snap_id(snap_t in_snap_id) const
710 {
711 const ParentInfo *info = get_parent_info(in_snap_id);
712 if (info)
713 return info->spec.snap_id;
714 return CEPH_NOSNAP;
715 }
716
717 int ImageCtx::get_parent_overlap(snap_t in_snap_id, uint64_t *overlap) const
718 {
719 assert(snap_lock.is_locked());
720 const ParentInfo *info = get_parent_info(in_snap_id);
721 if (info) {
722 *overlap = info->overlap;
723 return 0;
724 }
725 return -ENOENT;
726 }
727
728 void ImageCtx::aio_read_from_cache(object_t o, uint64_t object_no,
729 bufferlist *bl, size_t len,
730 uint64_t off, Context *onfinish,
731 int fadvise_flags, ZTracer::Trace *trace) {
732 snap_lock.get_read();
733 ObjectCacher::OSDRead *rd = object_cacher->prepare_read(snap_id, bl, fadvise_flags);
734 snap_lock.put_read();
735 ObjectExtent extent(o, object_no, off, len, 0);
736 extent.oloc.pool = data_ctx.get_id();
737 extent.buffer_extents.push_back(make_pair(0, len));
738 rd->extents.push_back(extent);
739 cache_lock.Lock();
740 int r = object_cacher->readx(rd, object_set, onfinish, trace);
741 cache_lock.Unlock();
742 if (r != 0)
743 onfinish->complete(r);
744 }
745
746 void ImageCtx::write_to_cache(object_t o, const bufferlist& bl, size_t len,
747 uint64_t off, Context *onfinish,
748 int fadvise_flags, uint64_t journal_tid,
749 ZTracer::Trace *trace) {
750 snap_lock.get_read();
751 ObjectCacher::OSDWrite *wr = object_cacher->prepare_write(
752 snapc, bl, ceph::real_time::min(), fadvise_flags, journal_tid);
753 snap_lock.put_read();
754 ObjectExtent extent(o, 0, off, len, 0);
755 extent.oloc.pool = data_ctx.get_id();
756 // XXX: nspace is always default, io_ctx_impl field private
757 //extent.oloc.nspace = data_ctx.io_ctx_impl->oloc.nspace;
758 extent.buffer_extents.push_back(make_pair(0, len));
759 wr->extents.push_back(extent);
760 {
761 Mutex::Locker l(cache_lock);
762 object_cacher->writex(wr, object_set, onfinish, trace);
763 }
764 }
765
766 void ImageCtx::user_flushed() {
767 if (object_cacher && cache_writethrough_until_flush) {
768 md_lock.get_read();
769 bool flushed_before = flush_encountered;
770 md_lock.put_read();
771
772 uint64_t max_dirty = cache_max_dirty;
773 if (!flushed_before && max_dirty > 0) {
774 md_lock.get_write();
775 flush_encountered = true;
776 md_lock.put_write();
777
778 ldout(cct, 10) << "saw first user flush, enabling writeback" << dendl;
779 Mutex::Locker l(cache_lock);
780 object_cacher->set_max_dirty(max_dirty);
781 }
782 }
783 }
784
785 void ImageCtx::flush_cache(Context *onfinish) {
786 cache_lock.Lock();
787 object_cacher->flush_set(object_set, onfinish);
788 cache_lock.Unlock();
789 }
790
791 void ImageCtx::shut_down_cache(Context *on_finish) {
792 if (object_cacher == NULL) {
793 on_finish->complete(0);
794 return;
795 }
796
797 cache_lock.Lock();
798 object_cacher->release_set(object_set);
799 cache_lock.Unlock();
800
801 C_ShutDownCache *shut_down = new C_ShutDownCache(this, on_finish);
802 flush_cache(new C_InvalidateCache(this, true, false, shut_down));
803 }
804
805 int ImageCtx::invalidate_cache(bool purge_on_error) {
806 flush_async_operations();
807 if (object_cacher == NULL) {
808 return 0;
809 }
810
811 cache_lock.Lock();
812 object_cacher->release_set(object_set);
813 cache_lock.Unlock();
814
815 C_SaferCond ctx;
816 flush_cache(new C_InvalidateCache(this, purge_on_error, true, &ctx));
817
818 int result = ctx.wait();
819 return result;
820 }
821
822 void ImageCtx::invalidate_cache(bool purge_on_error, Context *on_finish) {
823 if (object_cacher == NULL) {
824 op_work_queue->queue(on_finish, 0);
825 return;
826 }
827
828 cache_lock.Lock();
829 object_cacher->release_set(object_set);
830 cache_lock.Unlock();
831
832 flush_cache(new C_InvalidateCache(this, purge_on_error, false, on_finish));
833 }
834
835 void ImageCtx::clear_nonexistence_cache() {
836 assert(cache_lock.is_locked());
837 if (!object_cacher)
838 return;
839 object_cacher->clear_nonexistence(object_set);
840 }
841
842 bool ImageCtx::is_cache_empty() {
843 Mutex::Locker locker(cache_lock);
844 return object_cacher->set_is_empty(object_set);
845 }
846
847 void ImageCtx::register_watch(Context *on_finish) {
848 assert(image_watcher == NULL);
849 image_watcher = new ImageWatcher<>(*this);
850 image_watcher->register_watch(on_finish);
851 }
852
853 uint64_t ImageCtx::prune_parent_extents(vector<pair<uint64_t,uint64_t> >& objectx,
854 uint64_t overlap)
855 {
856 // drop extents completely beyond the overlap
857 while (!objectx.empty() && objectx.back().first >= overlap)
858 objectx.pop_back();
859
860 // trim final overlapping extent
861 if (!objectx.empty() && objectx.back().first + objectx.back().second > overlap)
862 objectx.back().second = overlap - objectx.back().first;
863
864 uint64_t len = 0;
865 for (vector<pair<uint64_t,uint64_t> >::iterator p = objectx.begin();
866 p != objectx.end();
867 ++p)
868 len += p->second;
869 ldout(cct, 10) << "prune_parent_extents image overlap " << overlap
870 << ", object overlap " << len
871 << " from image extents " << objectx << dendl;
872 return len;
873 }
874
875 void ImageCtx::flush_async_operations() {
876 C_SaferCond ctx;
877 flush_async_operations(&ctx);
878 ctx.wait();
879 }
880
881 void ImageCtx::flush_async_operations(Context *on_finish) {
882 {
883 Mutex::Locker l(async_ops_lock);
884 if (!async_ops.empty()) {
885 ldout(cct, 20) << "flush async operations: " << on_finish << " "
886 << "count=" << async_ops.size() << dendl;
887 async_ops.front()->add_flush_context(on_finish);
888 return;
889 }
890 }
891 on_finish->complete(0);
892 }
893
894 int ImageCtx::flush() {
895 C_SaferCond cond_ctx;
896 flush(&cond_ctx);
897 return cond_ctx.wait();
898 }
899
900 void ImageCtx::flush(Context *on_safe) {
901 // ensure no locks are held when flush is complete
902 on_safe = util::create_async_context_callback(*this, on_safe);
903
904 if (object_cacher != NULL) {
905 // flush cache after completing all in-flight AIO ops
906 on_safe = new C_FlushCache(this, on_safe);
907 }
908 flush_async_operations(on_safe);
909 }
910
911 void ImageCtx::cancel_async_requests() {
912 C_SaferCond ctx;
913 cancel_async_requests(&ctx);
914 ctx.wait();
915 }
916
917 void ImageCtx::cancel_async_requests(Context *on_finish) {
918 {
919 Mutex::Locker async_ops_locker(async_ops_lock);
920 if (!async_requests.empty()) {
921 ldout(cct, 10) << "canceling async requests: count="
922 << async_requests.size() << dendl;
923 for (auto req : async_requests) {
924 ldout(cct, 10) << "canceling async request: " << req << dendl;
925 req->cancel();
926 }
927 async_requests_waiters.push_back(on_finish);
928 return;
929 }
930 }
931
932 on_finish->complete(0);
933 }
934
935 void ImageCtx::clear_pending_completions() {
936 Mutex::Locker l(completed_reqs_lock);
937 ldout(cct, 10) << "clear pending AioCompletion: count="
938 << completed_reqs.size() << dendl;
939 completed_reqs.clear();
940 }
941
942 bool ImageCtx::_filter_metadata_confs(const string &prefix,
943 map<string, bool> &configs,
944 const map<string, bufferlist> &pairs,
945 map<string, bufferlist> *res) {
946 size_t conf_prefix_len = prefix.size();
947
948 for (auto it : pairs) {
949 if (it.first.compare(0, MIN(conf_prefix_len, it.first.size()), prefix) > 0)
950 return false;
951
952 if (it.first.size() <= conf_prefix_len)
953 continue;
954
955 string key = it.first.substr(conf_prefix_len, it.first.size() - conf_prefix_len);
956 auto cit = configs.find(key);
957 if (cit != configs.end()) {
958 cit->second = true;
959 res->insert(make_pair(key, it.second));
960 }
961 }
962 return true;
963 }
964
965 void ImageCtx::apply_metadata(const std::map<std::string, bufferlist> &meta) {
966 ldout(cct, 20) << __func__ << dendl;
967 std::map<string, bool> configs = boost::assign::map_list_of(
968 "rbd_non_blocking_aio", false)(
969 "rbd_cache", false)(
970 "rbd_cache_writethrough_until_flush", false)(
971 "rbd_cache_size", false)(
972 "rbd_cache_max_dirty", false)(
973 "rbd_cache_target_dirty", false)(
974 "rbd_cache_max_dirty_age", false)(
975 "rbd_cache_max_dirty_object", false)(
976 "rbd_cache_block_writes_upfront", false)(
977 "rbd_concurrent_management_ops", false)(
978 "rbd_balance_snap_reads", false)(
979 "rbd_localize_snap_reads", false)(
980 "rbd_balance_parent_reads", false)(
981 "rbd_localize_parent_reads", false)(
982 "rbd_readahead_trigger_requests", false)(
983 "rbd_readahead_max_bytes", false)(
984 "rbd_readahead_disable_after_bytes", false)(
985 "rbd_clone_copy_on_read", false)(
986 "rbd_blacklist_on_break_lock", false)(
987 "rbd_blacklist_expire_seconds", false)(
988 "rbd_request_timed_out_seconds", false)(
989 "rbd_journal_order", false)(
990 "rbd_journal_splay_width", false)(
991 "rbd_journal_commit_age", false)(
992 "rbd_journal_object_flush_interval", false)(
993 "rbd_journal_object_flush_bytes", false)(
994 "rbd_journal_object_flush_age", false)(
995 "rbd_journal_pool", false)(
996 "rbd_journal_max_payload_bytes", false)(
997 "rbd_journal_max_concurrent_object_sets", false)(
998 "rbd_mirroring_resync_after_disconnect", false)(
999 "rbd_mirroring_replay_delay", false)(
1000 "rbd_skip_partial_discard", false);
1001
1002 md_config_t local_config_t;
1003 std::map<std::string, bufferlist> res;
1004
1005 _filter_metadata_confs(METADATA_CONF_PREFIX, configs, meta, &res);
1006 for (auto it : res) {
1007 std::string val(it.second.c_str(), it.second.length());
1008 int j = local_config_t.set_val(it.first.c_str(), val);
1009 if (j < 0) {
1010 lderr(cct) << __func__ << " failed to set config " << it.first
1011 << " with value " << it.second.c_str() << ": " << j
1012 << dendl;
1013 }
1014 }
1015
1016 #define ASSIGN_OPTION(config) \
1017 do { \
1018 string key = "rbd_"; \
1019 key = key + #config; \
1020 if (configs[key]) \
1021 config = local_config_t.rbd_##config; \
1022 else \
1023 config = cct->_conf->rbd_##config; \
1024 } while (0);
1025
1026 ASSIGN_OPTION(non_blocking_aio);
1027 ASSIGN_OPTION(cache);
1028 ASSIGN_OPTION(cache_writethrough_until_flush);
1029 ASSIGN_OPTION(cache_size);
1030 ASSIGN_OPTION(cache_max_dirty);
1031 ASSIGN_OPTION(cache_target_dirty);
1032 ASSIGN_OPTION(cache_max_dirty_age);
1033 ASSIGN_OPTION(cache_max_dirty_object);
1034 ASSIGN_OPTION(cache_block_writes_upfront);
1035 ASSIGN_OPTION(concurrent_management_ops);
1036 ASSIGN_OPTION(balance_snap_reads);
1037 ASSIGN_OPTION(localize_snap_reads);
1038 ASSIGN_OPTION(balance_parent_reads);
1039 ASSIGN_OPTION(localize_parent_reads);
1040 ASSIGN_OPTION(readahead_trigger_requests);
1041 ASSIGN_OPTION(readahead_max_bytes);
1042 ASSIGN_OPTION(readahead_disable_after_bytes);
1043 ASSIGN_OPTION(clone_copy_on_read);
1044 ASSIGN_OPTION(blacklist_on_break_lock);
1045 ASSIGN_OPTION(blacklist_expire_seconds);
1046 ASSIGN_OPTION(request_timed_out_seconds);
1047 ASSIGN_OPTION(enable_alloc_hint);
1048 ASSIGN_OPTION(journal_order);
1049 ASSIGN_OPTION(journal_splay_width);
1050 ASSIGN_OPTION(journal_commit_age);
1051 ASSIGN_OPTION(journal_object_flush_interval);
1052 ASSIGN_OPTION(journal_object_flush_bytes);
1053 ASSIGN_OPTION(journal_object_flush_age);
1054 ASSIGN_OPTION(journal_pool);
1055 ASSIGN_OPTION(journal_max_payload_bytes);
1056 ASSIGN_OPTION(journal_max_concurrent_object_sets);
1057 ASSIGN_OPTION(mirroring_resync_after_disconnect);
1058 ASSIGN_OPTION(mirroring_replay_delay);
1059 ASSIGN_OPTION(skip_partial_discard);
1060 }
1061
1062 ExclusiveLock<ImageCtx> *ImageCtx::create_exclusive_lock() {
1063 return new ExclusiveLock<ImageCtx>(*this);
1064 }
1065
1066 ObjectMap<ImageCtx> *ImageCtx::create_object_map(uint64_t snap_id) {
1067 return new ObjectMap<ImageCtx>(*this, snap_id);
1068 }
1069
1070 Journal<ImageCtx> *ImageCtx::create_journal() {
1071 return new Journal<ImageCtx>(*this);
1072 }
1073
1074 void ImageCtx::set_image_name(const std::string &image_name) {
1075 // update the name so rename can be invoked repeatedly
1076 RWLock::RLocker owner_locker(owner_lock);
1077 RWLock::WLocker snap_locker(snap_lock);
1078 name = image_name;
1079 if (old_format) {
1080 header_oid = util::old_header_name(image_name);
1081 }
1082 }
1083
1084 void ImageCtx::notify_update() {
1085 state->handle_update_notification();
1086 ImageWatcher<>::notify_header_update(md_ctx, header_oid);
1087 }
1088
1089 void ImageCtx::notify_update(Context *on_finish) {
1090 state->handle_update_notification();
1091 image_watcher->notify_header_update(on_finish);
1092 }
1093
1094 exclusive_lock::Policy *ImageCtx::get_exclusive_lock_policy() const {
1095 assert(owner_lock.is_locked());
1096 assert(exclusive_lock_policy != nullptr);
1097 return exclusive_lock_policy;
1098 }
1099
1100 void ImageCtx::set_exclusive_lock_policy(exclusive_lock::Policy *policy) {
1101 assert(owner_lock.is_wlocked());
1102 assert(policy != nullptr);
1103 delete exclusive_lock_policy;
1104 exclusive_lock_policy = policy;
1105 }
1106
1107 journal::Policy *ImageCtx::get_journal_policy() const {
1108 assert(snap_lock.is_locked());
1109 assert(journal_policy != nullptr);
1110 return journal_policy;
1111 }
1112
1113 void ImageCtx::set_journal_policy(journal::Policy *policy) {
1114 assert(snap_lock.is_wlocked());
1115 assert(policy != nullptr);
1116 delete journal_policy;
1117 journal_policy = policy;
1118 }
1119
1120 void ImageCtx::get_thread_pool_instance(CephContext *cct,
1121 ThreadPool **thread_pool,
1122 ContextWQ **op_work_queue) {
1123 ThreadPoolSingleton *thread_pool_singleton;
1124 cct->lookup_or_create_singleton_object<ThreadPoolSingleton>(
1125 thread_pool_singleton, "librbd::thread_pool");
1126 *thread_pool = thread_pool_singleton;
1127 *op_work_queue = thread_pool_singleton->op_work_queue;
1128 }
1129
1130 void ImageCtx::get_timer_instance(CephContext *cct, SafeTimer **timer,
1131 Mutex **timer_lock) {
1132 SafeTimerSingleton *safe_timer_singleton;
1133 cct->lookup_or_create_singleton_object<SafeTimerSingleton>(
1134 safe_timer_singleton, "librbd::journal::safe_timer");
1135 *timer = safe_timer_singleton;
1136 *timer_lock = &safe_timer_singleton->lock;
1137 }
1138 }