Merge tag 'ceph-for-4.9-rc1' of git://github.com/ceph/ceph-client
[cascardo/linux.git] / drivers / block / rbd.c
1
2 /*
3    rbd.c -- Export ceph rados objects as a Linux block device
4
5
6    based on drivers/block/osdblk.c:
7
8    Copyright 2009 Red Hat, Inc.
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program; see the file COPYING.  If not, write to
21    the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
22
23
24
25    For usage instructions, please refer to:
26
27                  Documentation/ABI/testing/sysfs-bus-rbd
28
29  */
30
31 #include <linux/ceph/libceph.h>
32 #include <linux/ceph/osd_client.h>
33 #include <linux/ceph/mon_client.h>
34 #include <linux/ceph/cls_lock_client.h>
35 #include <linux/ceph/decode.h>
36 #include <linux/parser.h>
37 #include <linux/bsearch.h>
38
39 #include <linux/kernel.h>
40 #include <linux/device.h>
41 #include <linux/module.h>
42 #include <linux/blk-mq.h>
43 #include <linux/fs.h>
44 #include <linux/blkdev.h>
45 #include <linux/slab.h>
46 #include <linux/idr.h>
47 #include <linux/workqueue.h>
48
49 #include "rbd_types.h"
50
51 #define RBD_DEBUG       /* Activate rbd_assert() calls */
52
53 /*
54  * The basic unit of block I/O is a sector.  It is interpreted in a
55  * number of contexts in Linux (blk, bio, genhd), but the default is
56  * universally 512 bytes.  These symbols are just slightly more
57  * meaningful than the bare numbers they represent.
58  */
59 #define SECTOR_SHIFT    9
60 #define SECTOR_SIZE     (1ULL << SECTOR_SHIFT)
61
62 /*
63  * Increment the given counter and return its updated value.
64  * If the counter is already 0 it will not be incremented.
65  * If the counter is already at its maximum value returns
66  * -EINVAL without updating it.
67  */
68 static int atomic_inc_return_safe(atomic_t *v)
69 {
70         unsigned int counter;
71
72         counter = (unsigned int)__atomic_add_unless(v, 1, 0);
73         if (counter <= (unsigned int)INT_MAX)
74                 return (int)counter;
75
76         atomic_dec(v);
77
78         return -EINVAL;
79 }
80
81 /* Decrement the counter.  Return the resulting value, or -EINVAL */
82 static int atomic_dec_return_safe(atomic_t *v)
83 {
84         int counter;
85
86         counter = atomic_dec_return(v);
87         if (counter >= 0)
88                 return counter;
89
90         atomic_inc(v);
91
92         return -EINVAL;
93 }
94
95 #define RBD_DRV_NAME "rbd"
96
97 #define RBD_MINORS_PER_MAJOR            256
98 #define RBD_SINGLE_MAJOR_PART_SHIFT     4
99
100 #define RBD_MAX_PARENT_CHAIN_LEN        16
101
102 #define RBD_SNAP_DEV_NAME_PREFIX        "snap_"
103 #define RBD_MAX_SNAP_NAME_LEN   \
104                         (NAME_MAX - (sizeof (RBD_SNAP_DEV_NAME_PREFIX) - 1))
105
106 #define RBD_MAX_SNAP_COUNT      510     /* allows max snapc to fit in 4KB */
107
108 #define RBD_SNAP_HEAD_NAME      "-"
109
110 #define BAD_SNAP_INDEX  U32_MAX         /* invalid index into snap array */
111
112 /* This allows a single page to hold an image name sent by OSD */
113 #define RBD_IMAGE_NAME_LEN_MAX  (PAGE_SIZE - sizeof (__le32) - 1)
114 #define RBD_IMAGE_ID_LEN_MAX    64
115
116 #define RBD_OBJ_PREFIX_LEN_MAX  64
117
118 #define RBD_NOTIFY_TIMEOUT      5       /* seconds */
119 #define RBD_RETRY_DELAY         msecs_to_jiffies(1000)
120
121 /* Feature bits */
122
123 #define RBD_FEATURE_LAYERING    (1<<0)
124 #define RBD_FEATURE_STRIPINGV2  (1<<1)
125 #define RBD_FEATURE_EXCLUSIVE_LOCK (1<<2)
126 #define RBD_FEATURES_ALL        (RBD_FEATURE_LAYERING |         \
127                                  RBD_FEATURE_STRIPINGV2 |       \
128                                  RBD_FEATURE_EXCLUSIVE_LOCK)
129
130 /* Features supported by this (client software) implementation. */
131
132 #define RBD_FEATURES_SUPPORTED  (RBD_FEATURES_ALL)
133
134 /*
135  * An RBD device name will be "rbd#", where the "rbd" comes from
136  * RBD_DRV_NAME above, and # is a unique integer identifier.
137  */
138 #define DEV_NAME_LEN            32
139
140 /*
141  * block device image metadata (in-memory version)
142  */
143 struct rbd_image_header {
144         /* These six fields never change for a given rbd image */
145         char *object_prefix;
146         __u8 obj_order;
147         __u8 crypt_type;
148         __u8 comp_type;
149         u64 stripe_unit;
150         u64 stripe_count;
151         u64 features;           /* Might be changeable someday? */
152
153         /* The remaining fields need to be updated occasionally */
154         u64 image_size;
155         struct ceph_snap_context *snapc;
156         char *snap_names;       /* format 1 only */
157         u64 *snap_sizes;        /* format 1 only */
158 };
159
160 /*
161  * An rbd image specification.
162  *
163  * The tuple (pool_id, image_id, snap_id) is sufficient to uniquely
164  * identify an image.  Each rbd_dev structure includes a pointer to
165  * an rbd_spec structure that encapsulates this identity.
166  *
167  * Each of the id's in an rbd_spec has an associated name.  For a
168  * user-mapped image, the names are supplied and the id's associated
169  * with them are looked up.  For a layered image, a parent image is
170  * defined by the tuple, and the names are looked up.
171  *
172  * An rbd_dev structure contains a parent_spec pointer which is
173  * non-null if the image it represents is a child in a layered
174  * image.  This pointer will refer to the rbd_spec structure used
175  * by the parent rbd_dev for its own identity (i.e., the structure
176  * is shared between the parent and child).
177  *
178  * Since these structures are populated once, during the discovery
179  * phase of image construction, they are effectively immutable so
180  * we make no effort to synchronize access to them.
181  *
182  * Note that code herein does not assume the image name is known (it
183  * could be a null pointer).
184  */
185 struct rbd_spec {
186         u64             pool_id;
187         const char      *pool_name;
188
189         const char      *image_id;
190         const char      *image_name;
191
192         u64             snap_id;
193         const char      *snap_name;
194
195         struct kref     kref;
196 };
197
198 /*
199  * an instance of the client.  multiple devices may share an rbd client.
200  */
201 struct rbd_client {
202         struct ceph_client      *client;
203         struct kref             kref;
204         struct list_head        node;
205 };
206
207 struct rbd_img_request;
208 typedef void (*rbd_img_callback_t)(struct rbd_img_request *);
209
210 #define BAD_WHICH       U32_MAX         /* Good which or bad which, which? */
211
212 struct rbd_obj_request;
213 typedef void (*rbd_obj_callback_t)(struct rbd_obj_request *);
214
215 enum obj_request_type {
216         OBJ_REQUEST_NODATA, OBJ_REQUEST_BIO, OBJ_REQUEST_PAGES
217 };
218
219 enum obj_operation_type {
220         OBJ_OP_WRITE,
221         OBJ_OP_READ,
222         OBJ_OP_DISCARD,
223 };
224
225 enum obj_req_flags {
226         OBJ_REQ_DONE,           /* completion flag: not done = 0, done = 1 */
227         OBJ_REQ_IMG_DATA,       /* object usage: standalone = 0, image = 1 */
228         OBJ_REQ_KNOWN,          /* EXISTS flag valid: no = 0, yes = 1 */
229         OBJ_REQ_EXISTS,         /* target exists: no = 0, yes = 1 */
230 };
231
232 struct rbd_obj_request {
233         const char              *object_name;
234         u64                     offset;         /* object start byte */
235         u64                     length;         /* bytes from offset */
236         unsigned long           flags;
237
238         /*
239          * An object request associated with an image will have its
240          * img_data flag set; a standalone object request will not.
241          *
242          * A standalone object request will have which == BAD_WHICH
243          * and a null obj_request pointer.
244          *
245          * An object request initiated in support of a layered image
246          * object (to check for its existence before a write) will
247          * have which == BAD_WHICH and a non-null obj_request pointer.
248          *
249          * Finally, an object request for rbd image data will have
250          * which != BAD_WHICH, and will have a non-null img_request
251          * pointer.  The value of which will be in the range
252          * 0..(img_request->obj_request_count-1).
253          */
254         union {
255                 struct rbd_obj_request  *obj_request;   /* STAT op */
256                 struct {
257                         struct rbd_img_request  *img_request;
258                         u64                     img_offset;
259                         /* links for img_request->obj_requests list */
260                         struct list_head        links;
261                 };
262         };
263         u32                     which;          /* posn image request list */
264
265         enum obj_request_type   type;
266         union {
267                 struct bio      *bio_list;
268                 struct {
269                         struct page     **pages;
270                         u32             page_count;
271                 };
272         };
273         struct page             **copyup_pages;
274         u32                     copyup_page_count;
275
276         struct ceph_osd_request *osd_req;
277
278         u64                     xferred;        /* bytes transferred */
279         int                     result;
280
281         rbd_obj_callback_t      callback;
282         struct completion       completion;
283
284         struct kref             kref;
285 };
286
287 enum img_req_flags {
288         IMG_REQ_WRITE,          /* I/O direction: read = 0, write = 1 */
289         IMG_REQ_CHILD,          /* initiator: block = 0, child image = 1 */
290         IMG_REQ_LAYERED,        /* ENOENT handling: normal = 0, layered = 1 */
291         IMG_REQ_DISCARD,        /* discard: normal = 0, discard request = 1 */
292 };
293
294 struct rbd_img_request {
295         struct rbd_device       *rbd_dev;
296         u64                     offset; /* starting image byte offset */
297         u64                     length; /* byte count from offset */
298         unsigned long           flags;
299         union {
300                 u64                     snap_id;        /* for reads */
301                 struct ceph_snap_context *snapc;        /* for writes */
302         };
303         union {
304                 struct request          *rq;            /* block request */
305                 struct rbd_obj_request  *obj_request;   /* obj req initiator */
306         };
307         struct page             **copyup_pages;
308         u32                     copyup_page_count;
309         spinlock_t              completion_lock;/* protects next_completion */
310         u32                     next_completion;
311         rbd_img_callback_t      callback;
312         u64                     xferred;/* aggregate bytes transferred */
313         int                     result; /* first nonzero obj_request result */
314
315         u32                     obj_request_count;
316         struct list_head        obj_requests;   /* rbd_obj_request structs */
317
318         struct kref             kref;
319 };
320
321 #define for_each_obj_request(ireq, oreq) \
322         list_for_each_entry(oreq, &(ireq)->obj_requests, links)
323 #define for_each_obj_request_from(ireq, oreq) \
324         list_for_each_entry_from(oreq, &(ireq)->obj_requests, links)
325 #define for_each_obj_request_safe(ireq, oreq, n) \
326         list_for_each_entry_safe_reverse(oreq, n, &(ireq)->obj_requests, links)
327
328 enum rbd_watch_state {
329         RBD_WATCH_STATE_UNREGISTERED,
330         RBD_WATCH_STATE_REGISTERED,
331         RBD_WATCH_STATE_ERROR,
332 };
333
334 enum rbd_lock_state {
335         RBD_LOCK_STATE_UNLOCKED,
336         RBD_LOCK_STATE_LOCKED,
337         RBD_LOCK_STATE_RELEASING,
338 };
339
340 /* WatchNotify::ClientId */
341 struct rbd_client_id {
342         u64 gid;
343         u64 handle;
344 };
345
346 struct rbd_mapping {
347         u64                     size;
348         u64                     features;
349         bool                    read_only;
350 };
351
352 /*
353  * a single device
354  */
355 struct rbd_device {
356         int                     dev_id;         /* blkdev unique id */
357
358         int                     major;          /* blkdev assigned major */
359         int                     minor;
360         struct gendisk          *disk;          /* blkdev's gendisk and rq */
361
362         u32                     image_format;   /* Either 1 or 2 */
363         struct rbd_client       *rbd_client;
364
365         char                    name[DEV_NAME_LEN]; /* blkdev name, e.g. rbd3 */
366
367         spinlock_t              lock;           /* queue, flags, open_count */
368
369         struct rbd_image_header header;
370         unsigned long           flags;          /* possibly lock protected */
371         struct rbd_spec         *spec;
372         struct rbd_options      *opts;
373         char                    *config_info;   /* add{,_single_major} string */
374
375         struct ceph_object_id   header_oid;
376         struct ceph_object_locator header_oloc;
377
378         struct ceph_file_layout layout;         /* used for all rbd requests */
379
380         struct mutex            watch_mutex;
381         enum rbd_watch_state    watch_state;
382         struct ceph_osd_linger_request *watch_handle;
383         u64                     watch_cookie;
384         struct delayed_work     watch_dwork;
385
386         struct rw_semaphore     lock_rwsem;
387         enum rbd_lock_state     lock_state;
388         struct rbd_client_id    owner_cid;
389         struct work_struct      acquired_lock_work;
390         struct work_struct      released_lock_work;
391         struct delayed_work     lock_dwork;
392         struct work_struct      unlock_work;
393         wait_queue_head_t       lock_waitq;
394
395         struct workqueue_struct *task_wq;
396
397         struct rbd_spec         *parent_spec;
398         u64                     parent_overlap;
399         atomic_t                parent_ref;
400         struct rbd_device       *parent;
401
402         /* Block layer tags. */
403         struct blk_mq_tag_set   tag_set;
404
405         /* protects updating the header */
406         struct rw_semaphore     header_rwsem;
407
408         struct rbd_mapping      mapping;
409
410         struct list_head        node;
411
412         /* sysfs related */
413         struct device           dev;
414         unsigned long           open_count;     /* protected by lock */
415 };
416
417 /*
418  * Flag bits for rbd_dev->flags.  If atomicity is required,
419  * rbd_dev->lock is used to protect access.
420  *
421  * Currently, only the "removing" flag (which is coupled with the
422  * "open_count" field) requires atomic access.
423  */
424 enum rbd_dev_flags {
425         RBD_DEV_FLAG_EXISTS,    /* mapped snapshot has not been deleted */
426         RBD_DEV_FLAG_REMOVING,  /* this mapping is being removed */
427 };
428
429 static DEFINE_MUTEX(client_mutex);      /* Serialize client creation */
430
431 static LIST_HEAD(rbd_dev_list);    /* devices */
432 static DEFINE_SPINLOCK(rbd_dev_list_lock);
433
434 static LIST_HEAD(rbd_client_list);              /* clients */
435 static DEFINE_SPINLOCK(rbd_client_list_lock);
436
437 /* Slab caches for frequently-allocated structures */
438
439 static struct kmem_cache        *rbd_img_request_cache;
440 static struct kmem_cache        *rbd_obj_request_cache;
441 static struct kmem_cache        *rbd_segment_name_cache;
442
443 static int rbd_major;
444 static DEFINE_IDA(rbd_dev_id_ida);
445
446 static struct workqueue_struct *rbd_wq;
447
448 /*
449  * Default to false for now, as single-major requires >= 0.75 version of
450  * userspace rbd utility.
451  */
452 static bool single_major = false;
453 module_param(single_major, bool, S_IRUGO);
454 MODULE_PARM_DESC(single_major, "Use a single major number for all rbd devices (default: false)");
455
456 static int rbd_img_request_submit(struct rbd_img_request *img_request);
457
458 static ssize_t rbd_add(struct bus_type *bus, const char *buf,
459                        size_t count);
460 static ssize_t rbd_remove(struct bus_type *bus, const char *buf,
461                           size_t count);
462 static ssize_t rbd_add_single_major(struct bus_type *bus, const char *buf,
463                                     size_t count);
464 static ssize_t rbd_remove_single_major(struct bus_type *bus, const char *buf,
465                                        size_t count);
466 static int rbd_dev_image_probe(struct rbd_device *rbd_dev, int depth);
467 static void rbd_spec_put(struct rbd_spec *spec);
468
469 static int rbd_dev_id_to_minor(int dev_id)
470 {
471         return dev_id << RBD_SINGLE_MAJOR_PART_SHIFT;
472 }
473
474 static int minor_to_rbd_dev_id(int minor)
475 {
476         return minor >> RBD_SINGLE_MAJOR_PART_SHIFT;
477 }
478
479 static bool rbd_is_lock_supported(struct rbd_device *rbd_dev)
480 {
481         return (rbd_dev->header.features & RBD_FEATURE_EXCLUSIVE_LOCK) &&
482                rbd_dev->spec->snap_id == CEPH_NOSNAP &&
483                !rbd_dev->mapping.read_only;
484 }
485
486 static bool __rbd_is_lock_owner(struct rbd_device *rbd_dev)
487 {
488         return rbd_dev->lock_state == RBD_LOCK_STATE_LOCKED ||
489                rbd_dev->lock_state == RBD_LOCK_STATE_RELEASING;
490 }
491
492 static bool rbd_is_lock_owner(struct rbd_device *rbd_dev)
493 {
494         bool is_lock_owner;
495
496         down_read(&rbd_dev->lock_rwsem);
497         is_lock_owner = __rbd_is_lock_owner(rbd_dev);
498         up_read(&rbd_dev->lock_rwsem);
499         return is_lock_owner;
500 }
501
502 static BUS_ATTR(add, S_IWUSR, NULL, rbd_add);
503 static BUS_ATTR(remove, S_IWUSR, NULL, rbd_remove);
504 static BUS_ATTR(add_single_major, S_IWUSR, NULL, rbd_add_single_major);
505 static BUS_ATTR(remove_single_major, S_IWUSR, NULL, rbd_remove_single_major);
506
507 static struct attribute *rbd_bus_attrs[] = {
508         &bus_attr_add.attr,
509         &bus_attr_remove.attr,
510         &bus_attr_add_single_major.attr,
511         &bus_attr_remove_single_major.attr,
512         NULL,
513 };
514
515 static umode_t rbd_bus_is_visible(struct kobject *kobj,
516                                   struct attribute *attr, int index)
517 {
518         if (!single_major &&
519             (attr == &bus_attr_add_single_major.attr ||
520              attr == &bus_attr_remove_single_major.attr))
521                 return 0;
522
523         return attr->mode;
524 }
525
526 static const struct attribute_group rbd_bus_group = {
527         .attrs = rbd_bus_attrs,
528         .is_visible = rbd_bus_is_visible,
529 };
530 __ATTRIBUTE_GROUPS(rbd_bus);
531
532 static struct bus_type rbd_bus_type = {
533         .name           = "rbd",
534         .bus_groups     = rbd_bus_groups,
535 };
536
537 static void rbd_root_dev_release(struct device *dev)
538 {
539 }
540
541 static struct device rbd_root_dev = {
542         .init_name =    "rbd",
543         .release =      rbd_root_dev_release,
544 };
545
546 static __printf(2, 3)
547 void rbd_warn(struct rbd_device *rbd_dev, const char *fmt, ...)
548 {
549         struct va_format vaf;
550         va_list args;
551
552         va_start(args, fmt);
553         vaf.fmt = fmt;
554         vaf.va = &args;
555
556         if (!rbd_dev)
557                 printk(KERN_WARNING "%s: %pV\n", RBD_DRV_NAME, &vaf);
558         else if (rbd_dev->disk)
559                 printk(KERN_WARNING "%s: %s: %pV\n",
560                         RBD_DRV_NAME, rbd_dev->disk->disk_name, &vaf);
561         else if (rbd_dev->spec && rbd_dev->spec->image_name)
562                 printk(KERN_WARNING "%s: image %s: %pV\n",
563                         RBD_DRV_NAME, rbd_dev->spec->image_name, &vaf);
564         else if (rbd_dev->spec && rbd_dev->spec->image_id)
565                 printk(KERN_WARNING "%s: id %s: %pV\n",
566                         RBD_DRV_NAME, rbd_dev->spec->image_id, &vaf);
567         else    /* punt */
568                 printk(KERN_WARNING "%s: rbd_dev %p: %pV\n",
569                         RBD_DRV_NAME, rbd_dev, &vaf);
570         va_end(args);
571 }
572
573 #ifdef RBD_DEBUG
574 #define rbd_assert(expr)                                                \
575                 if (unlikely(!(expr))) {                                \
576                         printk(KERN_ERR "\nAssertion failure in %s() "  \
577                                                 "at line %d:\n\n"       \
578                                         "\trbd_assert(%s);\n\n",        \
579                                         __func__, __LINE__, #expr);     \
580                         BUG();                                          \
581                 }
582 #else /* !RBD_DEBUG */
583 #  define rbd_assert(expr)      ((void) 0)
584 #endif /* !RBD_DEBUG */
585
586 static void rbd_osd_copyup_callback(struct rbd_obj_request *obj_request);
587 static int rbd_img_obj_request_submit(struct rbd_obj_request *obj_request);
588 static void rbd_img_parent_read(struct rbd_obj_request *obj_request);
589 static void rbd_dev_remove_parent(struct rbd_device *rbd_dev);
590
591 static int rbd_dev_refresh(struct rbd_device *rbd_dev);
592 static int rbd_dev_v2_header_onetime(struct rbd_device *rbd_dev);
593 static int rbd_dev_header_info(struct rbd_device *rbd_dev);
594 static int rbd_dev_v2_parent_info(struct rbd_device *rbd_dev);
595 static const char *rbd_dev_v2_snap_name(struct rbd_device *rbd_dev,
596                                         u64 snap_id);
597 static int _rbd_dev_v2_snap_size(struct rbd_device *rbd_dev, u64 snap_id,
598                                 u8 *order, u64 *snap_size);
599 static int _rbd_dev_v2_snap_features(struct rbd_device *rbd_dev, u64 snap_id,
600                 u64 *snap_features);
601
602 static int rbd_open(struct block_device *bdev, fmode_t mode)
603 {
604         struct rbd_device *rbd_dev = bdev->bd_disk->private_data;
605         bool removing = false;
606
607         if ((mode & FMODE_WRITE) && rbd_dev->mapping.read_only)
608                 return -EROFS;
609
610         spin_lock_irq(&rbd_dev->lock);
611         if (test_bit(RBD_DEV_FLAG_REMOVING, &rbd_dev->flags))
612                 removing = true;
613         else
614                 rbd_dev->open_count++;
615         spin_unlock_irq(&rbd_dev->lock);
616         if (removing)
617                 return -ENOENT;
618
619         (void) get_device(&rbd_dev->dev);
620
621         return 0;
622 }
623
624 static void rbd_release(struct gendisk *disk, fmode_t mode)
625 {
626         struct rbd_device *rbd_dev = disk->private_data;
627         unsigned long open_count_before;
628
629         spin_lock_irq(&rbd_dev->lock);
630         open_count_before = rbd_dev->open_count--;
631         spin_unlock_irq(&rbd_dev->lock);
632         rbd_assert(open_count_before > 0);
633
634         put_device(&rbd_dev->dev);
635 }
636
637 static int rbd_ioctl_set_ro(struct rbd_device *rbd_dev, unsigned long arg)
638 {
639         int ret = 0;
640         int val;
641         bool ro;
642         bool ro_changed = false;
643
644         /* get_user() may sleep, so call it before taking rbd_dev->lock */
645         if (get_user(val, (int __user *)(arg)))
646                 return -EFAULT;
647
648         ro = val ? true : false;
649         /* Snapshot doesn't allow to write*/
650         if (rbd_dev->spec->snap_id != CEPH_NOSNAP && !ro)
651                 return -EROFS;
652
653         spin_lock_irq(&rbd_dev->lock);
654         /* prevent others open this device */
655         if (rbd_dev->open_count > 1) {
656                 ret = -EBUSY;
657                 goto out;
658         }
659
660         if (rbd_dev->mapping.read_only != ro) {
661                 rbd_dev->mapping.read_only = ro;
662                 ro_changed = true;
663         }
664
665 out:
666         spin_unlock_irq(&rbd_dev->lock);
667         /* set_disk_ro() may sleep, so call it after releasing rbd_dev->lock */
668         if (ret == 0 && ro_changed)
669                 set_disk_ro(rbd_dev->disk, ro ? 1 : 0);
670
671         return ret;
672 }
673
674 static int rbd_ioctl(struct block_device *bdev, fmode_t mode,
675                         unsigned int cmd, unsigned long arg)
676 {
677         struct rbd_device *rbd_dev = bdev->bd_disk->private_data;
678         int ret = 0;
679
680         switch (cmd) {
681         case BLKROSET:
682                 ret = rbd_ioctl_set_ro(rbd_dev, arg);
683                 break;
684         default:
685                 ret = -ENOTTY;
686         }
687
688         return ret;
689 }
690
691 #ifdef CONFIG_COMPAT
692 static int rbd_compat_ioctl(struct block_device *bdev, fmode_t mode,
693                                 unsigned int cmd, unsigned long arg)
694 {
695         return rbd_ioctl(bdev, mode, cmd, arg);
696 }
697 #endif /* CONFIG_COMPAT */
698
699 static const struct block_device_operations rbd_bd_ops = {
700         .owner                  = THIS_MODULE,
701         .open                   = rbd_open,
702         .release                = rbd_release,
703         .ioctl                  = rbd_ioctl,
704 #ifdef CONFIG_COMPAT
705         .compat_ioctl           = rbd_compat_ioctl,
706 #endif
707 };
708
709 /*
710  * Initialize an rbd client instance.  Success or not, this function
711  * consumes ceph_opts.  Caller holds client_mutex.
712  */
713 static struct rbd_client *rbd_client_create(struct ceph_options *ceph_opts)
714 {
715         struct rbd_client *rbdc;
716         int ret = -ENOMEM;
717
718         dout("%s:\n", __func__);
719         rbdc = kmalloc(sizeof(struct rbd_client), GFP_KERNEL);
720         if (!rbdc)
721                 goto out_opt;
722
723         kref_init(&rbdc->kref);
724         INIT_LIST_HEAD(&rbdc->node);
725
726         rbdc->client = ceph_create_client(ceph_opts, rbdc, 0, 0);
727         if (IS_ERR(rbdc->client))
728                 goto out_rbdc;
729         ceph_opts = NULL; /* Now rbdc->client is responsible for ceph_opts */
730
731         ret = ceph_open_session(rbdc->client);
732         if (ret < 0)
733                 goto out_client;
734
735         spin_lock(&rbd_client_list_lock);
736         list_add_tail(&rbdc->node, &rbd_client_list);
737         spin_unlock(&rbd_client_list_lock);
738
739         dout("%s: rbdc %p\n", __func__, rbdc);
740
741         return rbdc;
742 out_client:
743         ceph_destroy_client(rbdc->client);
744 out_rbdc:
745         kfree(rbdc);
746 out_opt:
747         if (ceph_opts)
748                 ceph_destroy_options(ceph_opts);
749         dout("%s: error %d\n", __func__, ret);
750
751         return ERR_PTR(ret);
752 }
753
754 static struct rbd_client *__rbd_get_client(struct rbd_client *rbdc)
755 {
756         kref_get(&rbdc->kref);
757
758         return rbdc;
759 }
760
761 /*
762  * Find a ceph client with specific addr and configuration.  If
763  * found, bump its reference count.
764  */
765 static struct rbd_client *rbd_client_find(struct ceph_options *ceph_opts)
766 {
767         struct rbd_client *client_node;
768         bool found = false;
769
770         if (ceph_opts->flags & CEPH_OPT_NOSHARE)
771                 return NULL;
772
773         spin_lock(&rbd_client_list_lock);
774         list_for_each_entry(client_node, &rbd_client_list, node) {
775                 if (!ceph_compare_options(ceph_opts, client_node->client)) {
776                         __rbd_get_client(client_node);
777
778                         found = true;
779                         break;
780                 }
781         }
782         spin_unlock(&rbd_client_list_lock);
783
784         return found ? client_node : NULL;
785 }
786
787 /*
788  * (Per device) rbd map options
789  */
790 enum {
791         Opt_queue_depth,
792         Opt_last_int,
793         /* int args above */
794         Opt_last_string,
795         /* string args above */
796         Opt_read_only,
797         Opt_read_write,
798         Opt_lock_on_read,
799         Opt_err
800 };
801
802 static match_table_t rbd_opts_tokens = {
803         {Opt_queue_depth, "queue_depth=%d"},
804         /* int args above */
805         /* string args above */
806         {Opt_read_only, "read_only"},
807         {Opt_read_only, "ro"},          /* Alternate spelling */
808         {Opt_read_write, "read_write"},
809         {Opt_read_write, "rw"},         /* Alternate spelling */
810         {Opt_lock_on_read, "lock_on_read"},
811         {Opt_err, NULL}
812 };
813
814 struct rbd_options {
815         int     queue_depth;
816         bool    read_only;
817         bool    lock_on_read;
818 };
819
820 #define RBD_QUEUE_DEPTH_DEFAULT BLKDEV_MAX_RQ
821 #define RBD_READ_ONLY_DEFAULT   false
822 #define RBD_LOCK_ON_READ_DEFAULT false
823
824 static int parse_rbd_opts_token(char *c, void *private)
825 {
826         struct rbd_options *rbd_opts = private;
827         substring_t argstr[MAX_OPT_ARGS];
828         int token, intval, ret;
829
830         token = match_token(c, rbd_opts_tokens, argstr);
831         if (token < Opt_last_int) {
832                 ret = match_int(&argstr[0], &intval);
833                 if (ret < 0) {
834                         pr_err("bad mount option arg (not int) at '%s'\n", c);
835                         return ret;
836                 }
837                 dout("got int token %d val %d\n", token, intval);
838         } else if (token > Opt_last_int && token < Opt_last_string) {
839                 dout("got string token %d val %s\n", token, argstr[0].from);
840         } else {
841                 dout("got token %d\n", token);
842         }
843
844         switch (token) {
845         case Opt_queue_depth:
846                 if (intval < 1) {
847                         pr_err("queue_depth out of range\n");
848                         return -EINVAL;
849                 }
850                 rbd_opts->queue_depth = intval;
851                 break;
852         case Opt_read_only:
853                 rbd_opts->read_only = true;
854                 break;
855         case Opt_read_write:
856                 rbd_opts->read_only = false;
857                 break;
858         case Opt_lock_on_read:
859                 rbd_opts->lock_on_read = true;
860                 break;
861         default:
862                 /* libceph prints "bad option" msg */
863                 return -EINVAL;
864         }
865
866         return 0;
867 }
868
869 static char* obj_op_name(enum obj_operation_type op_type)
870 {
871         switch (op_type) {
872         case OBJ_OP_READ:
873                 return "read";
874         case OBJ_OP_WRITE:
875                 return "write";
876         case OBJ_OP_DISCARD:
877                 return "discard";
878         default:
879                 return "???";
880         }
881 }
882
883 /*
884  * Get a ceph client with specific addr and configuration, if one does
885  * not exist create it.  Either way, ceph_opts is consumed by this
886  * function.
887  */
888 static struct rbd_client *rbd_get_client(struct ceph_options *ceph_opts)
889 {
890         struct rbd_client *rbdc;
891
892         mutex_lock_nested(&client_mutex, SINGLE_DEPTH_NESTING);
893         rbdc = rbd_client_find(ceph_opts);
894         if (rbdc)       /* using an existing client */
895                 ceph_destroy_options(ceph_opts);
896         else
897                 rbdc = rbd_client_create(ceph_opts);
898         mutex_unlock(&client_mutex);
899
900         return rbdc;
901 }
902
903 /*
904  * Destroy ceph client
905  *
906  * Caller must hold rbd_client_list_lock.
907  */
908 static void rbd_client_release(struct kref *kref)
909 {
910         struct rbd_client *rbdc = container_of(kref, struct rbd_client, kref);
911
912         dout("%s: rbdc %p\n", __func__, rbdc);
913         spin_lock(&rbd_client_list_lock);
914         list_del(&rbdc->node);
915         spin_unlock(&rbd_client_list_lock);
916
917         ceph_destroy_client(rbdc->client);
918         kfree(rbdc);
919 }
920
921 /*
922  * Drop reference to ceph client node. If it's not referenced anymore, release
923  * it.
924  */
925 static void rbd_put_client(struct rbd_client *rbdc)
926 {
927         if (rbdc)
928                 kref_put(&rbdc->kref, rbd_client_release);
929 }
930
931 static bool rbd_image_format_valid(u32 image_format)
932 {
933         return image_format == 1 || image_format == 2;
934 }
935
936 static bool rbd_dev_ondisk_valid(struct rbd_image_header_ondisk *ondisk)
937 {
938         size_t size;
939         u32 snap_count;
940
941         /* The header has to start with the magic rbd header text */
942         if (memcmp(&ondisk->text, RBD_HEADER_TEXT, sizeof (RBD_HEADER_TEXT)))
943                 return false;
944
945         /* The bio layer requires at least sector-sized I/O */
946
947         if (ondisk->options.order < SECTOR_SHIFT)
948                 return false;
949
950         /* If we use u64 in a few spots we may be able to loosen this */
951
952         if (ondisk->options.order > 8 * sizeof (int) - 1)
953                 return false;
954
955         /*
956          * The size of a snapshot header has to fit in a size_t, and
957          * that limits the number of snapshots.
958          */
959         snap_count = le32_to_cpu(ondisk->snap_count);
960         size = SIZE_MAX - sizeof (struct ceph_snap_context);
961         if (snap_count > size / sizeof (__le64))
962                 return false;
963
964         /*
965          * Not only that, but the size of the entire the snapshot
966          * header must also be representable in a size_t.
967          */
968         size -= snap_count * sizeof (__le64);
969         if ((u64) size < le64_to_cpu(ondisk->snap_names_len))
970                 return false;
971
972         return true;
973 }
974
975 /*
976  * Fill an rbd image header with information from the given format 1
977  * on-disk header.
978  */
979 static int rbd_header_from_disk(struct rbd_device *rbd_dev,
980                                  struct rbd_image_header_ondisk *ondisk)
981 {
982         struct rbd_image_header *header = &rbd_dev->header;
983         bool first_time = header->object_prefix == NULL;
984         struct ceph_snap_context *snapc;
985         char *object_prefix = NULL;
986         char *snap_names = NULL;
987         u64 *snap_sizes = NULL;
988         u32 snap_count;
989         int ret = -ENOMEM;
990         u32 i;
991
992         /* Allocate this now to avoid having to handle failure below */
993
994         if (first_time) {
995                 size_t len;
996
997                 len = strnlen(ondisk->object_prefix,
998                                 sizeof (ondisk->object_prefix));
999                 object_prefix = kmalloc(len + 1, GFP_KERNEL);
1000                 if (!object_prefix)
1001                         return -ENOMEM;
1002                 memcpy(object_prefix, ondisk->object_prefix, len);
1003                 object_prefix[len] = '\0';
1004         }
1005
1006         /* Allocate the snapshot context and fill it in */
1007
1008         snap_count = le32_to_cpu(ondisk->snap_count);
1009         snapc = ceph_create_snap_context(snap_count, GFP_KERNEL);
1010         if (!snapc)
1011                 goto out_err;
1012         snapc->seq = le64_to_cpu(ondisk->snap_seq);
1013         if (snap_count) {
1014                 struct rbd_image_snap_ondisk *snaps;
1015                 u64 snap_names_len = le64_to_cpu(ondisk->snap_names_len);
1016
1017                 /* We'll keep a copy of the snapshot names... */
1018
1019                 if (snap_names_len > (u64)SIZE_MAX)
1020                         goto out_2big;
1021                 snap_names = kmalloc(snap_names_len, GFP_KERNEL);
1022                 if (!snap_names)
1023                         goto out_err;
1024
1025                 /* ...as well as the array of their sizes. */
1026                 snap_sizes = kmalloc_array(snap_count,
1027                                            sizeof(*header->snap_sizes),
1028                                            GFP_KERNEL);
1029                 if (!snap_sizes)
1030                         goto out_err;
1031
1032                 /*
1033                  * Copy the names, and fill in each snapshot's id
1034                  * and size.
1035                  *
1036                  * Note that rbd_dev_v1_header_info() guarantees the
1037                  * ondisk buffer we're working with has
1038                  * snap_names_len bytes beyond the end of the
1039                  * snapshot id array, this memcpy() is safe.
1040                  */
1041                 memcpy(snap_names, &ondisk->snaps[snap_count], snap_names_len);
1042                 snaps = ondisk->snaps;
1043                 for (i = 0; i < snap_count; i++) {
1044                         snapc->snaps[i] = le64_to_cpu(snaps[i].id);
1045                         snap_sizes[i] = le64_to_cpu(snaps[i].image_size);
1046                 }
1047         }
1048
1049         /* We won't fail any more, fill in the header */
1050
1051         if (first_time) {
1052                 header->object_prefix = object_prefix;
1053                 header->obj_order = ondisk->options.order;
1054                 header->crypt_type = ondisk->options.crypt_type;
1055                 header->comp_type = ondisk->options.comp_type;
1056                 /* The rest aren't used for format 1 images */
1057                 header->stripe_unit = 0;
1058                 header->stripe_count = 0;
1059                 header->features = 0;
1060         } else {
1061                 ceph_put_snap_context(header->snapc);
1062                 kfree(header->snap_names);
1063                 kfree(header->snap_sizes);
1064         }
1065
1066         /* The remaining fields always get updated (when we refresh) */
1067
1068         header->image_size = le64_to_cpu(ondisk->image_size);
1069         header->snapc = snapc;
1070         header->snap_names = snap_names;
1071         header->snap_sizes = snap_sizes;
1072
1073         return 0;
1074 out_2big:
1075         ret = -EIO;
1076 out_err:
1077         kfree(snap_sizes);
1078         kfree(snap_names);
1079         ceph_put_snap_context(snapc);
1080         kfree(object_prefix);
1081
1082         return ret;
1083 }
1084
1085 static const char *_rbd_dev_v1_snap_name(struct rbd_device *rbd_dev, u32 which)
1086 {
1087         const char *snap_name;
1088
1089         rbd_assert(which < rbd_dev->header.snapc->num_snaps);
1090
1091         /* Skip over names until we find the one we are looking for */
1092
1093         snap_name = rbd_dev->header.snap_names;
1094         while (which--)
1095                 snap_name += strlen(snap_name) + 1;
1096
1097         return kstrdup(snap_name, GFP_KERNEL);
1098 }
1099
1100 /*
1101  * Snapshot id comparison function for use with qsort()/bsearch().
1102  * Note that result is for snapshots in *descending* order.
1103  */
1104 static int snapid_compare_reverse(const void *s1, const void *s2)
1105 {
1106         u64 snap_id1 = *(u64 *)s1;
1107         u64 snap_id2 = *(u64 *)s2;
1108
1109         if (snap_id1 < snap_id2)
1110                 return 1;
1111         return snap_id1 == snap_id2 ? 0 : -1;
1112 }
1113
1114 /*
1115  * Search a snapshot context to see if the given snapshot id is
1116  * present.
1117  *
1118  * Returns the position of the snapshot id in the array if it's found,
1119  * or BAD_SNAP_INDEX otherwise.
1120  *
1121  * Note: The snapshot array is in kept sorted (by the osd) in
1122  * reverse order, highest snapshot id first.
1123  */
1124 static u32 rbd_dev_snap_index(struct rbd_device *rbd_dev, u64 snap_id)
1125 {
1126         struct ceph_snap_context *snapc = rbd_dev->header.snapc;
1127         u64 *found;
1128
1129         found = bsearch(&snap_id, &snapc->snaps, snapc->num_snaps,
1130                                 sizeof (snap_id), snapid_compare_reverse);
1131
1132         return found ? (u32)(found - &snapc->snaps[0]) : BAD_SNAP_INDEX;
1133 }
1134
1135 static const char *rbd_dev_v1_snap_name(struct rbd_device *rbd_dev,
1136                                         u64 snap_id)
1137 {
1138         u32 which;
1139         const char *snap_name;
1140
1141         which = rbd_dev_snap_index(rbd_dev, snap_id);
1142         if (which == BAD_SNAP_INDEX)
1143                 return ERR_PTR(-ENOENT);
1144
1145         snap_name = _rbd_dev_v1_snap_name(rbd_dev, which);
1146         return snap_name ? snap_name : ERR_PTR(-ENOMEM);
1147 }
1148
1149 static const char *rbd_snap_name(struct rbd_device *rbd_dev, u64 snap_id)
1150 {
1151         if (snap_id == CEPH_NOSNAP)
1152                 return RBD_SNAP_HEAD_NAME;
1153
1154         rbd_assert(rbd_image_format_valid(rbd_dev->image_format));
1155         if (rbd_dev->image_format == 1)
1156                 return rbd_dev_v1_snap_name(rbd_dev, snap_id);
1157
1158         return rbd_dev_v2_snap_name(rbd_dev, snap_id);
1159 }
1160
1161 static int rbd_snap_size(struct rbd_device *rbd_dev, u64 snap_id,
1162                                 u64 *snap_size)
1163 {
1164         rbd_assert(rbd_image_format_valid(rbd_dev->image_format));
1165         if (snap_id == CEPH_NOSNAP) {
1166                 *snap_size = rbd_dev->header.image_size;
1167         } else if (rbd_dev->image_format == 1) {
1168                 u32 which;
1169
1170                 which = rbd_dev_snap_index(rbd_dev, snap_id);
1171                 if (which == BAD_SNAP_INDEX)
1172                         return -ENOENT;
1173
1174                 *snap_size = rbd_dev->header.snap_sizes[which];
1175         } else {
1176                 u64 size = 0;
1177                 int ret;
1178
1179                 ret = _rbd_dev_v2_snap_size(rbd_dev, snap_id, NULL, &size);
1180                 if (ret)
1181                         return ret;
1182
1183                 *snap_size = size;
1184         }
1185         return 0;
1186 }
1187
1188 static int rbd_snap_features(struct rbd_device *rbd_dev, u64 snap_id,
1189                         u64 *snap_features)
1190 {
1191         rbd_assert(rbd_image_format_valid(rbd_dev->image_format));
1192         if (snap_id == CEPH_NOSNAP) {
1193                 *snap_features = rbd_dev->header.features;
1194         } else if (rbd_dev->image_format == 1) {
1195                 *snap_features = 0;     /* No features for format 1 */
1196         } else {
1197                 u64 features = 0;
1198                 int ret;
1199
1200                 ret = _rbd_dev_v2_snap_features(rbd_dev, snap_id, &features);
1201                 if (ret)
1202                         return ret;
1203
1204                 *snap_features = features;
1205         }
1206         return 0;
1207 }
1208
1209 static int rbd_dev_mapping_set(struct rbd_device *rbd_dev)
1210 {
1211         u64 snap_id = rbd_dev->spec->snap_id;
1212         u64 size = 0;
1213         u64 features = 0;
1214         int ret;
1215
1216         ret = rbd_snap_size(rbd_dev, snap_id, &size);
1217         if (ret)
1218                 return ret;
1219         ret = rbd_snap_features(rbd_dev, snap_id, &features);
1220         if (ret)
1221                 return ret;
1222
1223         rbd_dev->mapping.size = size;
1224         rbd_dev->mapping.features = features;
1225
1226         return 0;
1227 }
1228
1229 static void rbd_dev_mapping_clear(struct rbd_device *rbd_dev)
1230 {
1231         rbd_dev->mapping.size = 0;
1232         rbd_dev->mapping.features = 0;
1233 }
1234
1235 static void rbd_segment_name_free(const char *name)
1236 {
1237         /* The explicit cast here is needed to drop the const qualifier */
1238
1239         kmem_cache_free(rbd_segment_name_cache, (void *)name);
1240 }
1241
1242 static const char *rbd_segment_name(struct rbd_device *rbd_dev, u64 offset)
1243 {
1244         char *name;
1245         u64 segment;
1246         int ret;
1247         char *name_format;
1248
1249         name = kmem_cache_alloc(rbd_segment_name_cache, GFP_NOIO);
1250         if (!name)
1251                 return NULL;
1252         segment = offset >> rbd_dev->header.obj_order;
1253         name_format = "%s.%012llx";
1254         if (rbd_dev->image_format == 2)
1255                 name_format = "%s.%016llx";
1256         ret = snprintf(name, CEPH_MAX_OID_NAME_LEN + 1, name_format,
1257                         rbd_dev->header.object_prefix, segment);
1258         if (ret < 0 || ret > CEPH_MAX_OID_NAME_LEN) {
1259                 pr_err("error formatting segment name for #%llu (%d)\n",
1260                         segment, ret);
1261                 rbd_segment_name_free(name);
1262                 name = NULL;
1263         }
1264
1265         return name;
1266 }
1267
1268 static u64 rbd_segment_offset(struct rbd_device *rbd_dev, u64 offset)
1269 {
1270         u64 segment_size = (u64) 1 << rbd_dev->header.obj_order;
1271
1272         return offset & (segment_size - 1);
1273 }
1274
1275 static u64 rbd_segment_length(struct rbd_device *rbd_dev,
1276                                 u64 offset, u64 length)
1277 {
1278         u64 segment_size = (u64) 1 << rbd_dev->header.obj_order;
1279
1280         offset &= segment_size - 1;
1281
1282         rbd_assert(length <= U64_MAX - offset);
1283         if (offset + length > segment_size)
1284                 length = segment_size - offset;
1285
1286         return length;
1287 }
1288
1289 /*
1290  * returns the size of an object in the image
1291  */
1292 static u64 rbd_obj_bytes(struct rbd_image_header *header)
1293 {
1294         return 1 << header->obj_order;
1295 }
1296
1297 /*
1298  * bio helpers
1299  */
1300
1301 static void bio_chain_put(struct bio *chain)
1302 {
1303         struct bio *tmp;
1304
1305         while (chain) {
1306                 tmp = chain;
1307                 chain = chain->bi_next;
1308                 bio_put(tmp);
1309         }
1310 }
1311
1312 /*
1313  * zeros a bio chain, starting at specific offset
1314  */
1315 static void zero_bio_chain(struct bio *chain, int start_ofs)
1316 {
1317         struct bio_vec bv;
1318         struct bvec_iter iter;
1319         unsigned long flags;
1320         void *buf;
1321         int pos = 0;
1322
1323         while (chain) {
1324                 bio_for_each_segment(bv, chain, iter) {
1325                         if (pos + bv.bv_len > start_ofs) {
1326                                 int remainder = max(start_ofs - pos, 0);
1327                                 buf = bvec_kmap_irq(&bv, &flags);
1328                                 memset(buf + remainder, 0,
1329                                        bv.bv_len - remainder);
1330                                 flush_dcache_page(bv.bv_page);
1331                                 bvec_kunmap_irq(buf, &flags);
1332                         }
1333                         pos += bv.bv_len;
1334                 }
1335
1336                 chain = chain->bi_next;
1337         }
1338 }
1339
1340 /*
1341  * similar to zero_bio_chain(), zeros data defined by a page array,
1342  * starting at the given byte offset from the start of the array and
1343  * continuing up to the given end offset.  The pages array is
1344  * assumed to be big enough to hold all bytes up to the end.
1345  */
1346 static void zero_pages(struct page **pages, u64 offset, u64 end)
1347 {
1348         struct page **page = &pages[offset >> PAGE_SHIFT];
1349
1350         rbd_assert(end > offset);
1351         rbd_assert(end - offset <= (u64)SIZE_MAX);
1352         while (offset < end) {
1353                 size_t page_offset;
1354                 size_t length;
1355                 unsigned long flags;
1356                 void *kaddr;
1357
1358                 page_offset = offset & ~PAGE_MASK;
1359                 length = min_t(size_t, PAGE_SIZE - page_offset, end - offset);
1360                 local_irq_save(flags);
1361                 kaddr = kmap_atomic(*page);
1362                 memset(kaddr + page_offset, 0, length);
1363                 flush_dcache_page(*page);
1364                 kunmap_atomic(kaddr);
1365                 local_irq_restore(flags);
1366
1367                 offset += length;
1368                 page++;
1369         }
1370 }
1371
1372 /*
1373  * Clone a portion of a bio, starting at the given byte offset
1374  * and continuing for the number of bytes indicated.
1375  */
1376 static struct bio *bio_clone_range(struct bio *bio_src,
1377                                         unsigned int offset,
1378                                         unsigned int len,
1379                                         gfp_t gfpmask)
1380 {
1381         struct bio *bio;
1382
1383         bio = bio_clone(bio_src, gfpmask);
1384         if (!bio)
1385                 return NULL;    /* ENOMEM */
1386
1387         bio_advance(bio, offset);
1388         bio->bi_iter.bi_size = len;
1389
1390         return bio;
1391 }
1392
1393 /*
1394  * Clone a portion of a bio chain, starting at the given byte offset
1395  * into the first bio in the source chain and continuing for the
1396  * number of bytes indicated.  The result is another bio chain of
1397  * exactly the given length, or a null pointer on error.
1398  *
1399  * The bio_src and offset parameters are both in-out.  On entry they
1400  * refer to the first source bio and the offset into that bio where
1401  * the start of data to be cloned is located.
1402  *
1403  * On return, bio_src is updated to refer to the bio in the source
1404  * chain that contains first un-cloned byte, and *offset will
1405  * contain the offset of that byte within that bio.
1406  */
1407 static struct bio *bio_chain_clone_range(struct bio **bio_src,
1408                                         unsigned int *offset,
1409                                         unsigned int len,
1410                                         gfp_t gfpmask)
1411 {
1412         struct bio *bi = *bio_src;
1413         unsigned int off = *offset;
1414         struct bio *chain = NULL;
1415         struct bio **end;
1416
1417         /* Build up a chain of clone bios up to the limit */
1418
1419         if (!bi || off >= bi->bi_iter.bi_size || !len)
1420                 return NULL;            /* Nothing to clone */
1421
1422         end = &chain;
1423         while (len) {
1424                 unsigned int bi_size;
1425                 struct bio *bio;
1426
1427                 if (!bi) {
1428                         rbd_warn(NULL, "bio_chain exhausted with %u left", len);
1429                         goto out_err;   /* EINVAL; ran out of bio's */
1430                 }
1431                 bi_size = min_t(unsigned int, bi->bi_iter.bi_size - off, len);
1432                 bio = bio_clone_range(bi, off, bi_size, gfpmask);
1433                 if (!bio)
1434                         goto out_err;   /* ENOMEM */
1435
1436                 *end = bio;
1437                 end = &bio->bi_next;
1438
1439                 off += bi_size;
1440                 if (off == bi->bi_iter.bi_size) {
1441                         bi = bi->bi_next;
1442                         off = 0;
1443                 }
1444                 len -= bi_size;
1445         }
1446         *bio_src = bi;
1447         *offset = off;
1448
1449         return chain;
1450 out_err:
1451         bio_chain_put(chain);
1452
1453         return NULL;
1454 }
1455
1456 /*
1457  * The default/initial value for all object request flags is 0.  For
1458  * each flag, once its value is set to 1 it is never reset to 0
1459  * again.
1460  */
1461 static void obj_request_img_data_set(struct rbd_obj_request *obj_request)
1462 {
1463         if (test_and_set_bit(OBJ_REQ_IMG_DATA, &obj_request->flags)) {
1464                 struct rbd_device *rbd_dev;
1465
1466                 rbd_dev = obj_request->img_request->rbd_dev;
1467                 rbd_warn(rbd_dev, "obj_request %p already marked img_data",
1468                         obj_request);
1469         }
1470 }
1471
1472 static bool obj_request_img_data_test(struct rbd_obj_request *obj_request)
1473 {
1474         smp_mb();
1475         return test_bit(OBJ_REQ_IMG_DATA, &obj_request->flags) != 0;
1476 }
1477
1478 static void obj_request_done_set(struct rbd_obj_request *obj_request)
1479 {
1480         if (test_and_set_bit(OBJ_REQ_DONE, &obj_request->flags)) {
1481                 struct rbd_device *rbd_dev = NULL;
1482
1483                 if (obj_request_img_data_test(obj_request))
1484                         rbd_dev = obj_request->img_request->rbd_dev;
1485                 rbd_warn(rbd_dev, "obj_request %p already marked done",
1486                         obj_request);
1487         }
1488 }
1489
1490 static bool obj_request_done_test(struct rbd_obj_request *obj_request)
1491 {
1492         smp_mb();
1493         return test_bit(OBJ_REQ_DONE, &obj_request->flags) != 0;
1494 }
1495
1496 /*
1497  * This sets the KNOWN flag after (possibly) setting the EXISTS
1498  * flag.  The latter is set based on the "exists" value provided.
1499  *
1500  * Note that for our purposes once an object exists it never goes
1501  * away again.  It's possible that the response from two existence
1502  * checks are separated by the creation of the target object, and
1503  * the first ("doesn't exist") response arrives *after* the second
1504  * ("does exist").  In that case we ignore the second one.
1505  */
1506 static void obj_request_existence_set(struct rbd_obj_request *obj_request,
1507                                 bool exists)
1508 {
1509         if (exists)
1510                 set_bit(OBJ_REQ_EXISTS, &obj_request->flags);
1511         set_bit(OBJ_REQ_KNOWN, &obj_request->flags);
1512         smp_mb();
1513 }
1514
1515 static bool obj_request_known_test(struct rbd_obj_request *obj_request)
1516 {
1517         smp_mb();
1518         return test_bit(OBJ_REQ_KNOWN, &obj_request->flags) != 0;
1519 }
1520
1521 static bool obj_request_exists_test(struct rbd_obj_request *obj_request)
1522 {
1523         smp_mb();
1524         return test_bit(OBJ_REQ_EXISTS, &obj_request->flags) != 0;
1525 }
1526
1527 static bool obj_request_overlaps_parent(struct rbd_obj_request *obj_request)
1528 {
1529         struct rbd_device *rbd_dev = obj_request->img_request->rbd_dev;
1530
1531         return obj_request->img_offset <
1532             round_up(rbd_dev->parent_overlap, rbd_obj_bytes(&rbd_dev->header));
1533 }
1534
1535 static void rbd_obj_request_get(struct rbd_obj_request *obj_request)
1536 {
1537         dout("%s: obj %p (was %d)\n", __func__, obj_request,
1538                 atomic_read(&obj_request->kref.refcount));
1539         kref_get(&obj_request->kref);
1540 }
1541
1542 static void rbd_obj_request_destroy(struct kref *kref);
1543 static void rbd_obj_request_put(struct rbd_obj_request *obj_request)
1544 {
1545         rbd_assert(obj_request != NULL);
1546         dout("%s: obj %p (was %d)\n", __func__, obj_request,
1547                 atomic_read(&obj_request->kref.refcount));
1548         kref_put(&obj_request->kref, rbd_obj_request_destroy);
1549 }
1550
1551 static void rbd_img_request_get(struct rbd_img_request *img_request)
1552 {
1553         dout("%s: img %p (was %d)\n", __func__, img_request,
1554              atomic_read(&img_request->kref.refcount));
1555         kref_get(&img_request->kref);
1556 }
1557
1558 static bool img_request_child_test(struct rbd_img_request *img_request);
1559 static void rbd_parent_request_destroy(struct kref *kref);
1560 static void rbd_img_request_destroy(struct kref *kref);
1561 static void rbd_img_request_put(struct rbd_img_request *img_request)
1562 {
1563         rbd_assert(img_request != NULL);
1564         dout("%s: img %p (was %d)\n", __func__, img_request,
1565                 atomic_read(&img_request->kref.refcount));
1566         if (img_request_child_test(img_request))
1567                 kref_put(&img_request->kref, rbd_parent_request_destroy);
1568         else
1569                 kref_put(&img_request->kref, rbd_img_request_destroy);
1570 }
1571
1572 static inline void rbd_img_obj_request_add(struct rbd_img_request *img_request,
1573                                         struct rbd_obj_request *obj_request)
1574 {
1575         rbd_assert(obj_request->img_request == NULL);
1576
1577         /* Image request now owns object's original reference */
1578         obj_request->img_request = img_request;
1579         obj_request->which = img_request->obj_request_count;
1580         rbd_assert(!obj_request_img_data_test(obj_request));
1581         obj_request_img_data_set(obj_request);
1582         rbd_assert(obj_request->which != BAD_WHICH);
1583         img_request->obj_request_count++;
1584         list_add_tail(&obj_request->links, &img_request->obj_requests);
1585         dout("%s: img %p obj %p w=%u\n", __func__, img_request, obj_request,
1586                 obj_request->which);
1587 }
1588
1589 static inline void rbd_img_obj_request_del(struct rbd_img_request *img_request,
1590                                         struct rbd_obj_request *obj_request)
1591 {
1592         rbd_assert(obj_request->which != BAD_WHICH);
1593
1594         dout("%s: img %p obj %p w=%u\n", __func__, img_request, obj_request,
1595                 obj_request->which);
1596         list_del(&obj_request->links);
1597         rbd_assert(img_request->obj_request_count > 0);
1598         img_request->obj_request_count--;
1599         rbd_assert(obj_request->which == img_request->obj_request_count);
1600         obj_request->which = BAD_WHICH;
1601         rbd_assert(obj_request_img_data_test(obj_request));
1602         rbd_assert(obj_request->img_request == img_request);
1603         obj_request->img_request = NULL;
1604         obj_request->callback = NULL;
1605         rbd_obj_request_put(obj_request);
1606 }
1607
1608 static bool obj_request_type_valid(enum obj_request_type type)
1609 {
1610         switch (type) {
1611         case OBJ_REQUEST_NODATA:
1612         case OBJ_REQUEST_BIO:
1613         case OBJ_REQUEST_PAGES:
1614                 return true;
1615         default:
1616                 return false;
1617         }
1618 }
1619
1620 static void rbd_img_obj_callback(struct rbd_obj_request *obj_request);
1621
1622 static void rbd_obj_request_submit(struct rbd_obj_request *obj_request)
1623 {
1624         struct ceph_osd_request *osd_req = obj_request->osd_req;
1625
1626         dout("%s %p osd_req %p\n", __func__, obj_request, osd_req);
1627         if (obj_request_img_data_test(obj_request)) {
1628                 WARN_ON(obj_request->callback != rbd_img_obj_callback);
1629                 rbd_img_request_get(obj_request->img_request);
1630         }
1631         ceph_osdc_start_request(osd_req->r_osdc, osd_req, false);
1632 }
1633
1634 static void rbd_obj_request_end(struct rbd_obj_request *obj_request)
1635 {
1636         dout("%s %p\n", __func__, obj_request);
1637         ceph_osdc_cancel_request(obj_request->osd_req);
1638 }
1639
1640 /*
1641  * Wait for an object request to complete.  If interrupted, cancel the
1642  * underlying osd request.
1643  *
1644  * @timeout: in jiffies, 0 means "wait forever"
1645  */
1646 static int __rbd_obj_request_wait(struct rbd_obj_request *obj_request,
1647                                   unsigned long timeout)
1648 {
1649         long ret;
1650
1651         dout("%s %p\n", __func__, obj_request);
1652         ret = wait_for_completion_interruptible_timeout(
1653                                         &obj_request->completion,
1654                                         ceph_timeout_jiffies(timeout));
1655         if (ret <= 0) {
1656                 if (ret == 0)
1657                         ret = -ETIMEDOUT;
1658                 rbd_obj_request_end(obj_request);
1659         } else {
1660                 ret = 0;
1661         }
1662
1663         dout("%s %p ret %d\n", __func__, obj_request, (int)ret);
1664         return ret;
1665 }
1666
1667 static int rbd_obj_request_wait(struct rbd_obj_request *obj_request)
1668 {
1669         return __rbd_obj_request_wait(obj_request, 0);
1670 }
1671
1672 static void rbd_img_request_complete(struct rbd_img_request *img_request)
1673 {
1674
1675         dout("%s: img %p\n", __func__, img_request);
1676
1677         /*
1678          * If no error occurred, compute the aggregate transfer
1679          * count for the image request.  We could instead use
1680          * atomic64_cmpxchg() to update it as each object request
1681          * completes; not clear which way is better off hand.
1682          */
1683         if (!img_request->result) {
1684                 struct rbd_obj_request *obj_request;
1685                 u64 xferred = 0;
1686
1687                 for_each_obj_request(img_request, obj_request)
1688                         xferred += obj_request->xferred;
1689                 img_request->xferred = xferred;
1690         }
1691
1692         if (img_request->callback)
1693                 img_request->callback(img_request);
1694         else
1695                 rbd_img_request_put(img_request);
1696 }
1697
1698 /*
1699  * The default/initial value for all image request flags is 0.  Each
1700  * is conditionally set to 1 at image request initialization time
1701  * and currently never change thereafter.
1702  */
1703 static void img_request_write_set(struct rbd_img_request *img_request)
1704 {
1705         set_bit(IMG_REQ_WRITE, &img_request->flags);
1706         smp_mb();
1707 }
1708
1709 static bool img_request_write_test(struct rbd_img_request *img_request)
1710 {
1711         smp_mb();
1712         return test_bit(IMG_REQ_WRITE, &img_request->flags) != 0;
1713 }
1714
1715 /*
1716  * Set the discard flag when the img_request is an discard request
1717  */
1718 static void img_request_discard_set(struct rbd_img_request *img_request)
1719 {
1720         set_bit(IMG_REQ_DISCARD, &img_request->flags);
1721         smp_mb();
1722 }
1723
1724 static bool img_request_discard_test(struct rbd_img_request *img_request)
1725 {
1726         smp_mb();
1727         return test_bit(IMG_REQ_DISCARD, &img_request->flags) != 0;
1728 }
1729
1730 static void img_request_child_set(struct rbd_img_request *img_request)
1731 {
1732         set_bit(IMG_REQ_CHILD, &img_request->flags);
1733         smp_mb();
1734 }
1735
1736 static void img_request_child_clear(struct rbd_img_request *img_request)
1737 {
1738         clear_bit(IMG_REQ_CHILD, &img_request->flags);
1739         smp_mb();
1740 }
1741
1742 static bool img_request_child_test(struct rbd_img_request *img_request)
1743 {
1744         smp_mb();
1745         return test_bit(IMG_REQ_CHILD, &img_request->flags) != 0;
1746 }
1747
1748 static void img_request_layered_set(struct rbd_img_request *img_request)
1749 {
1750         set_bit(IMG_REQ_LAYERED, &img_request->flags);
1751         smp_mb();
1752 }
1753
1754 static void img_request_layered_clear(struct rbd_img_request *img_request)
1755 {
1756         clear_bit(IMG_REQ_LAYERED, &img_request->flags);
1757         smp_mb();
1758 }
1759
1760 static bool img_request_layered_test(struct rbd_img_request *img_request)
1761 {
1762         smp_mb();
1763         return test_bit(IMG_REQ_LAYERED, &img_request->flags) != 0;
1764 }
1765
1766 static enum obj_operation_type
1767 rbd_img_request_op_type(struct rbd_img_request *img_request)
1768 {
1769         if (img_request_write_test(img_request))
1770                 return OBJ_OP_WRITE;
1771         else if (img_request_discard_test(img_request))
1772                 return OBJ_OP_DISCARD;
1773         else
1774                 return OBJ_OP_READ;
1775 }
1776
1777 static void
1778 rbd_img_obj_request_read_callback(struct rbd_obj_request *obj_request)
1779 {
1780         u64 xferred = obj_request->xferred;
1781         u64 length = obj_request->length;
1782
1783         dout("%s: obj %p img %p result %d %llu/%llu\n", __func__,
1784                 obj_request, obj_request->img_request, obj_request->result,
1785                 xferred, length);
1786         /*
1787          * ENOENT means a hole in the image.  We zero-fill the entire
1788          * length of the request.  A short read also implies zero-fill
1789          * to the end of the request.  An error requires the whole
1790          * length of the request to be reported finished with an error
1791          * to the block layer.  In each case we update the xferred
1792          * count to indicate the whole request was satisfied.
1793          */
1794         rbd_assert(obj_request->type != OBJ_REQUEST_NODATA);
1795         if (obj_request->result == -ENOENT) {
1796                 if (obj_request->type == OBJ_REQUEST_BIO)
1797                         zero_bio_chain(obj_request->bio_list, 0);
1798                 else
1799                         zero_pages(obj_request->pages, 0, length);
1800                 obj_request->result = 0;
1801         } else if (xferred < length && !obj_request->result) {
1802                 if (obj_request->type == OBJ_REQUEST_BIO)
1803                         zero_bio_chain(obj_request->bio_list, xferred);
1804                 else
1805                         zero_pages(obj_request->pages, xferred, length);
1806         }
1807         obj_request->xferred = length;
1808         obj_request_done_set(obj_request);
1809 }
1810
1811 static void rbd_obj_request_complete(struct rbd_obj_request *obj_request)
1812 {
1813         dout("%s: obj %p cb %p\n", __func__, obj_request,
1814                 obj_request->callback);
1815         if (obj_request->callback)
1816                 obj_request->callback(obj_request);
1817         else
1818                 complete_all(&obj_request->completion);
1819 }
1820
1821 static void rbd_obj_request_error(struct rbd_obj_request *obj_request, int err)
1822 {
1823         obj_request->result = err;
1824         obj_request->xferred = 0;
1825         /*
1826          * kludge - mirror rbd_obj_request_submit() to match a put in
1827          * rbd_img_obj_callback()
1828          */
1829         if (obj_request_img_data_test(obj_request)) {
1830                 WARN_ON(obj_request->callback != rbd_img_obj_callback);
1831                 rbd_img_request_get(obj_request->img_request);
1832         }
1833         obj_request_done_set(obj_request);
1834         rbd_obj_request_complete(obj_request);
1835 }
1836
1837 static void rbd_osd_read_callback(struct rbd_obj_request *obj_request)
1838 {
1839         struct rbd_img_request *img_request = NULL;
1840         struct rbd_device *rbd_dev = NULL;
1841         bool layered = false;
1842
1843         if (obj_request_img_data_test(obj_request)) {
1844                 img_request = obj_request->img_request;
1845                 layered = img_request && img_request_layered_test(img_request);
1846                 rbd_dev = img_request->rbd_dev;
1847         }
1848
1849         dout("%s: obj %p img %p result %d %llu/%llu\n", __func__,
1850                 obj_request, img_request, obj_request->result,
1851                 obj_request->xferred, obj_request->length);
1852         if (layered && obj_request->result == -ENOENT &&
1853                         obj_request->img_offset < rbd_dev->parent_overlap)
1854                 rbd_img_parent_read(obj_request);
1855         else if (img_request)
1856                 rbd_img_obj_request_read_callback(obj_request);
1857         else
1858                 obj_request_done_set(obj_request);
1859 }
1860
1861 static void rbd_osd_write_callback(struct rbd_obj_request *obj_request)
1862 {
1863         dout("%s: obj %p result %d %llu\n", __func__, obj_request,
1864                 obj_request->result, obj_request->length);
1865         /*
1866          * There is no such thing as a successful short write.  Set
1867          * it to our originally-requested length.
1868          */
1869         obj_request->xferred = obj_request->length;
1870         obj_request_done_set(obj_request);
1871 }
1872
1873 static void rbd_osd_discard_callback(struct rbd_obj_request *obj_request)
1874 {
1875         dout("%s: obj %p result %d %llu\n", __func__, obj_request,
1876                 obj_request->result, obj_request->length);
1877         /*
1878          * There is no such thing as a successful short discard.  Set
1879          * it to our originally-requested length.
1880          */
1881         obj_request->xferred = obj_request->length;
1882         /* discarding a non-existent object is not a problem */
1883         if (obj_request->result == -ENOENT)
1884                 obj_request->result = 0;
1885         obj_request_done_set(obj_request);
1886 }
1887
1888 /*
1889  * For a simple stat call there's nothing to do.  We'll do more if
1890  * this is part of a write sequence for a layered image.
1891  */
1892 static void rbd_osd_stat_callback(struct rbd_obj_request *obj_request)
1893 {
1894         dout("%s: obj %p\n", __func__, obj_request);
1895         obj_request_done_set(obj_request);
1896 }
1897
1898 static void rbd_osd_call_callback(struct rbd_obj_request *obj_request)
1899 {
1900         dout("%s: obj %p\n", __func__, obj_request);
1901
1902         if (obj_request_img_data_test(obj_request))
1903                 rbd_osd_copyup_callback(obj_request);
1904         else
1905                 obj_request_done_set(obj_request);
1906 }
1907
1908 static void rbd_osd_req_callback(struct ceph_osd_request *osd_req)
1909 {
1910         struct rbd_obj_request *obj_request = osd_req->r_priv;
1911         u16 opcode;
1912
1913         dout("%s: osd_req %p\n", __func__, osd_req);
1914         rbd_assert(osd_req == obj_request->osd_req);
1915         if (obj_request_img_data_test(obj_request)) {
1916                 rbd_assert(obj_request->img_request);
1917                 rbd_assert(obj_request->which != BAD_WHICH);
1918         } else {
1919                 rbd_assert(obj_request->which == BAD_WHICH);
1920         }
1921
1922         if (osd_req->r_result < 0)
1923                 obj_request->result = osd_req->r_result;
1924
1925         /*
1926          * We support a 64-bit length, but ultimately it has to be
1927          * passed to the block layer, which just supports a 32-bit
1928          * length field.
1929          */
1930         obj_request->xferred = osd_req->r_ops[0].outdata_len;
1931         rbd_assert(obj_request->xferred < (u64)UINT_MAX);
1932
1933         opcode = osd_req->r_ops[0].op;
1934         switch (opcode) {
1935         case CEPH_OSD_OP_READ:
1936                 rbd_osd_read_callback(obj_request);
1937                 break;
1938         case CEPH_OSD_OP_SETALLOCHINT:
1939                 rbd_assert(osd_req->r_ops[1].op == CEPH_OSD_OP_WRITE ||
1940                            osd_req->r_ops[1].op == CEPH_OSD_OP_WRITEFULL);
1941                 /* fall through */
1942         case CEPH_OSD_OP_WRITE:
1943         case CEPH_OSD_OP_WRITEFULL:
1944                 rbd_osd_write_callback(obj_request);
1945                 break;
1946         case CEPH_OSD_OP_STAT:
1947                 rbd_osd_stat_callback(obj_request);
1948                 break;
1949         case CEPH_OSD_OP_DELETE:
1950         case CEPH_OSD_OP_TRUNCATE:
1951         case CEPH_OSD_OP_ZERO:
1952                 rbd_osd_discard_callback(obj_request);
1953                 break;
1954         case CEPH_OSD_OP_CALL:
1955                 rbd_osd_call_callback(obj_request);
1956                 break;
1957         default:
1958                 rbd_warn(NULL, "%s: unsupported op %hu",
1959                         obj_request->object_name, (unsigned short) opcode);
1960                 break;
1961         }
1962
1963         if (obj_request_done_test(obj_request))
1964                 rbd_obj_request_complete(obj_request);
1965 }
1966
1967 static void rbd_osd_req_format_read(struct rbd_obj_request *obj_request)
1968 {
1969         struct ceph_osd_request *osd_req = obj_request->osd_req;
1970
1971         rbd_assert(obj_request_img_data_test(obj_request));
1972         osd_req->r_snapid = obj_request->img_request->snap_id;
1973 }
1974
1975 static void rbd_osd_req_format_write(struct rbd_obj_request *obj_request)
1976 {
1977         struct ceph_osd_request *osd_req = obj_request->osd_req;
1978
1979         osd_req->r_mtime = CURRENT_TIME;
1980         osd_req->r_data_offset = obj_request->offset;
1981 }
1982
1983 /*
1984  * Create an osd request.  A read request has one osd op (read).
1985  * A write request has either one (watch) or two (hint+write) osd ops.
1986  * (All rbd data writes are prefixed with an allocation hint op, but
1987  * technically osd watch is a write request, hence this distinction.)
1988  */
1989 static struct ceph_osd_request *rbd_osd_req_create(
1990                                         struct rbd_device *rbd_dev,
1991                                         enum obj_operation_type op_type,
1992                                         unsigned int num_ops,
1993                                         struct rbd_obj_request *obj_request)
1994 {
1995         struct ceph_snap_context *snapc = NULL;
1996         struct ceph_osd_client *osdc;
1997         struct ceph_osd_request *osd_req;
1998
1999         if (obj_request_img_data_test(obj_request) &&
2000                 (op_type == OBJ_OP_DISCARD || op_type == OBJ_OP_WRITE)) {
2001                 struct rbd_img_request *img_request = obj_request->img_request;
2002                 if (op_type == OBJ_OP_WRITE) {
2003                         rbd_assert(img_request_write_test(img_request));
2004                 } else {
2005                         rbd_assert(img_request_discard_test(img_request));
2006                 }
2007                 snapc = img_request->snapc;
2008         }
2009
2010         rbd_assert(num_ops == 1 || ((op_type == OBJ_OP_WRITE) && num_ops == 2));
2011
2012         /* Allocate and initialize the request, for the num_ops ops */
2013
2014         osdc = &rbd_dev->rbd_client->client->osdc;
2015         osd_req = ceph_osdc_alloc_request(osdc, snapc, num_ops, false,
2016                                           GFP_NOIO);
2017         if (!osd_req)
2018                 goto fail;
2019
2020         if (op_type == OBJ_OP_WRITE || op_type == OBJ_OP_DISCARD)
2021                 osd_req->r_flags = CEPH_OSD_FLAG_WRITE | CEPH_OSD_FLAG_ONDISK;
2022         else
2023                 osd_req->r_flags = CEPH_OSD_FLAG_READ;
2024
2025         osd_req->r_callback = rbd_osd_req_callback;
2026         osd_req->r_priv = obj_request;
2027
2028         osd_req->r_base_oloc.pool = rbd_dev->layout.pool_id;
2029         if (ceph_oid_aprintf(&osd_req->r_base_oid, GFP_NOIO, "%s",
2030                              obj_request->object_name))
2031                 goto fail;
2032
2033         if (ceph_osdc_alloc_messages(osd_req, GFP_NOIO))
2034                 goto fail;
2035
2036         return osd_req;
2037
2038 fail:
2039         ceph_osdc_put_request(osd_req);
2040         return NULL;
2041 }
2042
2043 /*
2044  * Create a copyup osd request based on the information in the object
2045  * request supplied.  A copyup request has two or three osd ops, a
2046  * copyup method call, potentially a hint op, and a write or truncate
2047  * or zero op.
2048  */
2049 static struct ceph_osd_request *
2050 rbd_osd_req_create_copyup(struct rbd_obj_request *obj_request)
2051 {
2052         struct rbd_img_request *img_request;
2053         struct ceph_snap_context *snapc;
2054         struct rbd_device *rbd_dev;
2055         struct ceph_osd_client *osdc;
2056         struct ceph_osd_request *osd_req;
2057         int num_osd_ops = 3;
2058
2059         rbd_assert(obj_request_img_data_test(obj_request));
2060         img_request = obj_request->img_request;
2061         rbd_assert(img_request);
2062         rbd_assert(img_request_write_test(img_request) ||
2063                         img_request_discard_test(img_request));
2064
2065         if (img_request_discard_test(img_request))
2066                 num_osd_ops = 2;
2067
2068         /* Allocate and initialize the request, for all the ops */
2069
2070         snapc = img_request->snapc;
2071         rbd_dev = img_request->rbd_dev;
2072         osdc = &rbd_dev->rbd_client->client->osdc;
2073         osd_req = ceph_osdc_alloc_request(osdc, snapc, num_osd_ops,
2074                                                 false, GFP_NOIO);
2075         if (!osd_req)
2076                 goto fail;
2077
2078         osd_req->r_flags = CEPH_OSD_FLAG_WRITE | CEPH_OSD_FLAG_ONDISK;
2079         osd_req->r_callback = rbd_osd_req_callback;
2080         osd_req->r_priv = obj_request;
2081
2082         osd_req->r_base_oloc.pool = rbd_dev->layout.pool_id;
2083         if (ceph_oid_aprintf(&osd_req->r_base_oid, GFP_NOIO, "%s",
2084                              obj_request->object_name))
2085                 goto fail;
2086
2087         if (ceph_osdc_alloc_messages(osd_req, GFP_NOIO))
2088                 goto fail;
2089
2090         return osd_req;
2091
2092 fail:
2093         ceph_osdc_put_request(osd_req);
2094         return NULL;
2095 }
2096
2097
2098 static void rbd_osd_req_destroy(struct ceph_osd_request *osd_req)
2099 {
2100         ceph_osdc_put_request(osd_req);
2101 }
2102
2103 /* object_name is assumed to be a non-null pointer and NUL-terminated */
2104
2105 static struct rbd_obj_request *rbd_obj_request_create(const char *object_name,
2106                                                 u64 offset, u64 length,
2107                                                 enum obj_request_type type)
2108 {
2109         struct rbd_obj_request *obj_request;
2110         size_t size;
2111         char *name;
2112
2113         rbd_assert(obj_request_type_valid(type));
2114
2115         size = strlen(object_name) + 1;
2116         name = kmalloc(size, GFP_NOIO);
2117         if (!name)
2118                 return NULL;
2119
2120         obj_request = kmem_cache_zalloc(rbd_obj_request_cache, GFP_NOIO);
2121         if (!obj_request) {
2122                 kfree(name);
2123                 return NULL;
2124         }
2125
2126         obj_request->object_name = memcpy(name, object_name, size);
2127         obj_request->offset = offset;
2128         obj_request->length = length;
2129         obj_request->flags = 0;
2130         obj_request->which = BAD_WHICH;
2131         obj_request->type = type;
2132         INIT_LIST_HEAD(&obj_request->links);
2133         init_completion(&obj_request->completion);
2134         kref_init(&obj_request->kref);
2135
2136         dout("%s: \"%s\" %llu/%llu %d -> obj %p\n", __func__, object_name,
2137                 offset, length, (int)type, obj_request);
2138
2139         return obj_request;
2140 }
2141
2142 static void rbd_obj_request_destroy(struct kref *kref)
2143 {
2144         struct rbd_obj_request *obj_request;
2145
2146         obj_request = container_of(kref, struct rbd_obj_request, kref);
2147
2148         dout("%s: obj %p\n", __func__, obj_request);
2149
2150         rbd_assert(obj_request->img_request == NULL);
2151         rbd_assert(obj_request->which == BAD_WHICH);
2152
2153         if (obj_request->osd_req)
2154                 rbd_osd_req_destroy(obj_request->osd_req);
2155
2156         rbd_assert(obj_request_type_valid(obj_request->type));
2157         switch (obj_request->type) {
2158         case OBJ_REQUEST_NODATA:
2159                 break;          /* Nothing to do */
2160         case OBJ_REQUEST_BIO:
2161                 if (obj_request->bio_list)
2162                         bio_chain_put(obj_request->bio_list);
2163                 break;
2164         case OBJ_REQUEST_PAGES:
2165                 /* img_data requests don't own their page array */
2166                 if (obj_request->pages &&
2167                     !obj_request_img_data_test(obj_request))
2168                         ceph_release_page_vector(obj_request->pages,
2169                                                 obj_request->page_count);
2170                 break;
2171         }
2172
2173         kfree(obj_request->object_name);
2174         obj_request->object_name = NULL;
2175         kmem_cache_free(rbd_obj_request_cache, obj_request);
2176 }
2177
2178 /* It's OK to call this for a device with no parent */
2179
2180 static void rbd_spec_put(struct rbd_spec *spec);
2181 static void rbd_dev_unparent(struct rbd_device *rbd_dev)
2182 {
2183         rbd_dev_remove_parent(rbd_dev);
2184         rbd_spec_put(rbd_dev->parent_spec);
2185         rbd_dev->parent_spec = NULL;
2186         rbd_dev->parent_overlap = 0;
2187 }
2188
2189 /*
2190  * Parent image reference counting is used to determine when an
2191  * image's parent fields can be safely torn down--after there are no
2192  * more in-flight requests to the parent image.  When the last
2193  * reference is dropped, cleaning them up is safe.
2194  */
2195 static void rbd_dev_parent_put(struct rbd_device *rbd_dev)
2196 {
2197         int counter;
2198
2199         if (!rbd_dev->parent_spec)
2200                 return;
2201
2202         counter = atomic_dec_return_safe(&rbd_dev->parent_ref);
2203         if (counter > 0)
2204                 return;
2205
2206         /* Last reference; clean up parent data structures */
2207
2208         if (!counter)
2209                 rbd_dev_unparent(rbd_dev);
2210         else
2211                 rbd_warn(rbd_dev, "parent reference underflow");
2212 }
2213
2214 /*
2215  * If an image has a non-zero parent overlap, get a reference to its
2216  * parent.
2217  *
2218  * Returns true if the rbd device has a parent with a non-zero
2219  * overlap and a reference for it was successfully taken, or
2220  * false otherwise.
2221  */
2222 static bool rbd_dev_parent_get(struct rbd_device *rbd_dev)
2223 {
2224         int counter = 0;
2225
2226         if (!rbd_dev->parent_spec)
2227                 return false;
2228
2229         down_read(&rbd_dev->header_rwsem);
2230         if (rbd_dev->parent_overlap)
2231                 counter = atomic_inc_return_safe(&rbd_dev->parent_ref);
2232         up_read(&rbd_dev->header_rwsem);
2233
2234         if (counter < 0)
2235                 rbd_warn(rbd_dev, "parent reference overflow");
2236
2237         return counter > 0;
2238 }
2239
2240 /*
2241  * Caller is responsible for filling in the list of object requests
2242  * that comprises the image request, and the Linux request pointer
2243  * (if there is one).
2244  */
2245 static struct rbd_img_request *rbd_img_request_create(
2246                                         struct rbd_device *rbd_dev,
2247                                         u64 offset, u64 length,
2248                                         enum obj_operation_type op_type,
2249                                         struct ceph_snap_context *snapc)
2250 {
2251         struct rbd_img_request *img_request;
2252
2253         img_request = kmem_cache_alloc(rbd_img_request_cache, GFP_NOIO);
2254         if (!img_request)
2255                 return NULL;
2256
2257         img_request->rq = NULL;
2258         img_request->rbd_dev = rbd_dev;
2259         img_request->offset = offset;
2260         img_request->length = length;
2261         img_request->flags = 0;
2262         if (op_type == OBJ_OP_DISCARD) {
2263                 img_request_discard_set(img_request);
2264                 img_request->snapc = snapc;
2265         } else if (op_type == OBJ_OP_WRITE) {
2266                 img_request_write_set(img_request);
2267                 img_request->snapc = snapc;
2268         } else {
2269                 img_request->snap_id = rbd_dev->spec->snap_id;
2270         }
2271         if (rbd_dev_parent_get(rbd_dev))
2272                 img_request_layered_set(img_request);
2273         spin_lock_init(&img_request->completion_lock);
2274         img_request->next_completion = 0;
2275         img_request->callback = NULL;
2276         img_request->result = 0;
2277         img_request->obj_request_count = 0;
2278         INIT_LIST_HEAD(&img_request->obj_requests);
2279         kref_init(&img_request->kref);
2280
2281         dout("%s: rbd_dev %p %s %llu/%llu -> img %p\n", __func__, rbd_dev,
2282                 obj_op_name(op_type), offset, length, img_request);
2283
2284         return img_request;
2285 }
2286
2287 static void rbd_img_request_destroy(struct kref *kref)
2288 {
2289         struct rbd_img_request *img_request;
2290         struct rbd_obj_request *obj_request;
2291         struct rbd_obj_request *next_obj_request;
2292
2293         img_request = container_of(kref, struct rbd_img_request, kref);
2294
2295         dout("%s: img %p\n", __func__, img_request);
2296
2297         for_each_obj_request_safe(img_request, obj_request, next_obj_request)
2298                 rbd_img_obj_request_del(img_request, obj_request);
2299         rbd_assert(img_request->obj_request_count == 0);
2300
2301         if (img_request_layered_test(img_request)) {
2302                 img_request_layered_clear(img_request);
2303                 rbd_dev_parent_put(img_request->rbd_dev);
2304         }
2305
2306         if (img_request_write_test(img_request) ||
2307                 img_request_discard_test(img_request))
2308                 ceph_put_snap_context(img_request->snapc);
2309
2310         kmem_cache_free(rbd_img_request_cache, img_request);
2311 }
2312
2313 static struct rbd_img_request *rbd_parent_request_create(
2314                                         struct rbd_obj_request *obj_request,
2315                                         u64 img_offset, u64 length)
2316 {
2317         struct rbd_img_request *parent_request;
2318         struct rbd_device *rbd_dev;
2319
2320         rbd_assert(obj_request->img_request);
2321         rbd_dev = obj_request->img_request->rbd_dev;
2322
2323         parent_request = rbd_img_request_create(rbd_dev->parent, img_offset,
2324                                                 length, OBJ_OP_READ, NULL);
2325         if (!parent_request)
2326                 return NULL;
2327
2328         img_request_child_set(parent_request);
2329         rbd_obj_request_get(obj_request);
2330         parent_request->obj_request = obj_request;
2331
2332         return parent_request;
2333 }
2334
2335 static void rbd_parent_request_destroy(struct kref *kref)
2336 {
2337         struct rbd_img_request *parent_request;
2338         struct rbd_obj_request *orig_request;
2339
2340         parent_request = container_of(kref, struct rbd_img_request, kref);
2341         orig_request = parent_request->obj_request;
2342
2343         parent_request->obj_request = NULL;
2344         rbd_obj_request_put(orig_request);
2345         img_request_child_clear(parent_request);
2346
2347         rbd_img_request_destroy(kref);
2348 }
2349
2350 static bool rbd_img_obj_end_request(struct rbd_obj_request *obj_request)
2351 {
2352         struct rbd_img_request *img_request;
2353         unsigned int xferred;
2354         int result;
2355         bool more;
2356
2357         rbd_assert(obj_request_img_data_test(obj_request));
2358         img_request = obj_request->img_request;
2359
2360         rbd_assert(obj_request->xferred <= (u64)UINT_MAX);
2361         xferred = (unsigned int)obj_request->xferred;
2362         result = obj_request->result;
2363         if (result) {
2364                 struct rbd_device *rbd_dev = img_request->rbd_dev;
2365                 enum obj_operation_type op_type;
2366
2367                 if (img_request_discard_test(img_request))
2368                         op_type = OBJ_OP_DISCARD;
2369                 else if (img_request_write_test(img_request))
2370                         op_type = OBJ_OP_WRITE;
2371                 else
2372                         op_type = OBJ_OP_READ;
2373
2374                 rbd_warn(rbd_dev, "%s %llx at %llx (%llx)",
2375                         obj_op_name(op_type), obj_request->length,
2376                         obj_request->img_offset, obj_request->offset);
2377                 rbd_warn(rbd_dev, "  result %d xferred %x",
2378                         result, xferred);
2379                 if (!img_request->result)
2380                         img_request->result = result;
2381                 /*
2382                  * Need to end I/O on the entire obj_request worth of
2383                  * bytes in case of error.
2384                  */
2385                 xferred = obj_request->length;
2386         }
2387
2388         if (img_request_child_test(img_request)) {
2389                 rbd_assert(img_request->obj_request != NULL);
2390                 more = obj_request->which < img_request->obj_request_count - 1;
2391         } else {
2392                 rbd_assert(img_request->rq != NULL);
2393
2394                 more = blk_update_request(img_request->rq, result, xferred);
2395                 if (!more)
2396                         __blk_mq_end_request(img_request->rq, result);
2397         }
2398
2399         return more;
2400 }
2401
2402 static void rbd_img_obj_callback(struct rbd_obj_request *obj_request)
2403 {
2404         struct rbd_img_request *img_request;
2405         u32 which = obj_request->which;
2406         bool more = true;
2407
2408         rbd_assert(obj_request_img_data_test(obj_request));
2409         img_request = obj_request->img_request;
2410
2411         dout("%s: img %p obj %p\n", __func__, img_request, obj_request);
2412         rbd_assert(img_request != NULL);
2413         rbd_assert(img_request->obj_request_count > 0);
2414         rbd_assert(which != BAD_WHICH);
2415         rbd_assert(which < img_request->obj_request_count);
2416
2417         spin_lock_irq(&img_request->completion_lock);
2418         if (which != img_request->next_completion)
2419                 goto out;
2420
2421         for_each_obj_request_from(img_request, obj_request) {
2422                 rbd_assert(more);
2423                 rbd_assert(which < img_request->obj_request_count);
2424
2425                 if (!obj_request_done_test(obj_request))
2426                         break;
2427                 more = rbd_img_obj_end_request(obj_request);
2428                 which++;
2429         }
2430
2431         rbd_assert(more ^ (which == img_request->obj_request_count));
2432         img_request->next_completion = which;
2433 out:
2434         spin_unlock_irq(&img_request->completion_lock);
2435         rbd_img_request_put(img_request);
2436
2437         if (!more)
2438                 rbd_img_request_complete(img_request);
2439 }
2440
2441 /*
2442  * Add individual osd ops to the given ceph_osd_request and prepare
2443  * them for submission. num_ops is the current number of
2444  * osd operations already to the object request.
2445  */
2446 static void rbd_img_obj_request_fill(struct rbd_obj_request *obj_request,
2447                                 struct ceph_osd_request *osd_request,
2448                                 enum obj_operation_type op_type,
2449                                 unsigned int num_ops)
2450 {
2451         struct rbd_img_request *img_request = obj_request->img_request;
2452         struct rbd_device *rbd_dev = img_request->rbd_dev;
2453         u64 object_size = rbd_obj_bytes(&rbd_dev->header);
2454         u64 offset = obj_request->offset;
2455         u64 length = obj_request->length;
2456         u64 img_end;
2457         u16 opcode;
2458
2459         if (op_type == OBJ_OP_DISCARD) {
2460                 if (!offset && length == object_size &&
2461                     (!img_request_layered_test(img_request) ||
2462                      !obj_request_overlaps_parent(obj_request))) {
2463                         opcode = CEPH_OSD_OP_DELETE;
2464                 } else if ((offset + length == object_size)) {
2465                         opcode = CEPH_OSD_OP_TRUNCATE;
2466                 } else {
2467                         down_read(&rbd_dev->header_rwsem);
2468                         img_end = rbd_dev->header.image_size;
2469                         up_read(&rbd_dev->header_rwsem);
2470
2471                         if (obj_request->img_offset + length == img_end)
2472                                 opcode = CEPH_OSD_OP_TRUNCATE;
2473                         else
2474                                 opcode = CEPH_OSD_OP_ZERO;
2475                 }
2476         } else if (op_type == OBJ_OP_WRITE) {
2477                 if (!offset && length == object_size)
2478                         opcode = CEPH_OSD_OP_WRITEFULL;
2479                 else
2480                         opcode = CEPH_OSD_OP_WRITE;
2481                 osd_req_op_alloc_hint_init(osd_request, num_ops,
2482                                         object_size, object_size);
2483                 num_ops++;
2484         } else {
2485                 opcode = CEPH_OSD_OP_READ;
2486         }
2487
2488         if (opcode == CEPH_OSD_OP_DELETE)
2489                 osd_req_op_init(osd_request, num_ops, opcode, 0);
2490         else
2491                 osd_req_op_extent_init(osd_request, num_ops, opcode,
2492                                        offset, length, 0, 0);
2493
2494         if (obj_request->type == OBJ_REQUEST_BIO)
2495                 osd_req_op_extent_osd_data_bio(osd_request, num_ops,
2496                                         obj_request->bio_list, length);
2497         else if (obj_request->type == OBJ_REQUEST_PAGES)
2498                 osd_req_op_extent_osd_data_pages(osd_request, num_ops,
2499                                         obj_request->pages, length,
2500                                         offset & ~PAGE_MASK, false, false);
2501
2502         /* Discards are also writes */
2503         if (op_type == OBJ_OP_WRITE || op_type == OBJ_OP_DISCARD)
2504                 rbd_osd_req_format_write(obj_request);
2505         else
2506                 rbd_osd_req_format_read(obj_request);
2507 }
2508
2509 /*
2510  * Split up an image request into one or more object requests, each
2511  * to a different object.  The "type" parameter indicates whether
2512  * "data_desc" is the pointer to the head of a list of bio
2513  * structures, or the base of a page array.  In either case this
2514  * function assumes data_desc describes memory sufficient to hold
2515  * all data described by the image request.
2516  */
2517 static int rbd_img_request_fill(struct rbd_img_request *img_request,
2518                                         enum obj_request_type type,
2519                                         void *data_desc)
2520 {
2521         struct rbd_device *rbd_dev = img_request->rbd_dev;
2522         struct rbd_obj_request *obj_request = NULL;
2523         struct rbd_obj_request *next_obj_request;
2524         struct bio *bio_list = NULL;
2525         unsigned int bio_offset = 0;
2526         struct page **pages = NULL;
2527         enum obj_operation_type op_type;
2528         u64 img_offset;
2529         u64 resid;
2530
2531         dout("%s: img %p type %d data_desc %p\n", __func__, img_request,
2532                 (int)type, data_desc);
2533
2534         img_offset = img_request->offset;
2535         resid = img_request->length;
2536         rbd_assert(resid > 0);
2537         op_type = rbd_img_request_op_type(img_request);
2538
2539         if (type == OBJ_REQUEST_BIO) {
2540                 bio_list = data_desc;
2541                 rbd_assert(img_offset ==
2542                            bio_list->bi_iter.bi_sector << SECTOR_SHIFT);
2543         } else if (type == OBJ_REQUEST_PAGES) {
2544                 pages = data_desc;
2545         }
2546
2547         while (resid) {
2548                 struct ceph_osd_request *osd_req;
2549                 const char *object_name;
2550                 u64 offset;
2551                 u64 length;
2552
2553                 object_name = rbd_segment_name(rbd_dev, img_offset);
2554                 if (!object_name)
2555                         goto out_unwind;
2556                 offset = rbd_segment_offset(rbd_dev, img_offset);
2557                 length = rbd_segment_length(rbd_dev, img_offset, resid);
2558                 obj_request = rbd_obj_request_create(object_name,
2559                                                 offset, length, type);
2560                 /* object request has its own copy of the object name */
2561                 rbd_segment_name_free(object_name);
2562                 if (!obj_request)
2563                         goto out_unwind;
2564
2565                 /*
2566                  * set obj_request->img_request before creating the
2567                  * osd_request so that it gets the right snapc
2568                  */
2569                 rbd_img_obj_request_add(img_request, obj_request);
2570
2571                 if (type == OBJ_REQUEST_BIO) {
2572                         unsigned int clone_size;
2573
2574                         rbd_assert(length <= (u64)UINT_MAX);
2575                         clone_size = (unsigned int)length;
2576                         obj_request->bio_list =
2577                                         bio_chain_clone_range(&bio_list,
2578                                                                 &bio_offset,
2579                                                                 clone_size,
2580                                                                 GFP_NOIO);
2581                         if (!obj_request->bio_list)
2582                                 goto out_unwind;
2583                 } else if (type == OBJ_REQUEST_PAGES) {
2584                         unsigned int page_count;
2585
2586                         obj_request->pages = pages;
2587                         page_count = (u32)calc_pages_for(offset, length);
2588                         obj_request->page_count = page_count;
2589                         if ((offset + length) & ~PAGE_MASK)
2590                                 page_count--;   /* more on last page */
2591                         pages += page_count;
2592                 }
2593
2594                 osd_req = rbd_osd_req_create(rbd_dev, op_type,
2595                                         (op_type == OBJ_OP_WRITE) ? 2 : 1,
2596                                         obj_request);
2597                 if (!osd_req)
2598                         goto out_unwind;
2599
2600                 obj_request->osd_req = osd_req;
2601                 obj_request->callback = rbd_img_obj_callback;
2602                 obj_request->img_offset = img_offset;
2603
2604                 rbd_img_obj_request_fill(obj_request, osd_req, op_type, 0);
2605
2606                 img_offset += length;
2607                 resid -= length;
2608         }
2609
2610         return 0;
2611
2612 out_unwind:
2613         for_each_obj_request_safe(img_request, obj_request, next_obj_request)
2614                 rbd_img_obj_request_del(img_request, obj_request);
2615
2616         return -ENOMEM;
2617 }
2618
2619 static void
2620 rbd_osd_copyup_callback(struct rbd_obj_request *obj_request)
2621 {
2622         struct rbd_img_request *img_request;
2623         struct rbd_device *rbd_dev;
2624         struct page **pages;
2625         u32 page_count;
2626
2627         dout("%s: obj %p\n", __func__, obj_request);
2628
2629         rbd_assert(obj_request->type == OBJ_REQUEST_BIO ||
2630                 obj_request->type == OBJ_REQUEST_NODATA);
2631         rbd_assert(obj_request_img_data_test(obj_request));
2632         img_request = obj_request->img_request;
2633         rbd_assert(img_request);
2634
2635         rbd_dev = img_request->rbd_dev;
2636         rbd_assert(rbd_dev);
2637
2638         pages = obj_request->copyup_pages;
2639         rbd_assert(pages != NULL);
2640         obj_request->copyup_pages = NULL;
2641         page_count = obj_request->copyup_page_count;
2642         rbd_assert(page_count);
2643         obj_request->copyup_page_count = 0;
2644         ceph_release_page_vector(pages, page_count);
2645
2646         /*
2647          * We want the transfer count to reflect the size of the
2648          * original write request.  There is no such thing as a
2649          * successful short write, so if the request was successful
2650          * we can just set it to the originally-requested length.
2651          */
2652         if (!obj_request->result)
2653                 obj_request->xferred = obj_request->length;
2654
2655         obj_request_done_set(obj_request);
2656 }
2657
2658 static void
2659 rbd_img_obj_parent_read_full_callback(struct rbd_img_request *img_request)
2660 {
2661         struct rbd_obj_request *orig_request;
2662         struct ceph_osd_request *osd_req;
2663         struct rbd_device *rbd_dev;
2664         struct page **pages;
2665         enum obj_operation_type op_type;
2666         u32 page_count;
2667         int img_result;
2668         u64 parent_length;
2669
2670         rbd_assert(img_request_child_test(img_request));
2671
2672         /* First get what we need from the image request */
2673
2674         pages = img_request->copyup_pages;
2675         rbd_assert(pages != NULL);
2676         img_request->copyup_pages = NULL;
2677         page_count = img_request->copyup_page_count;
2678         rbd_assert(page_count);
2679         img_request->copyup_page_count = 0;
2680
2681         orig_request = img_request->obj_request;
2682         rbd_assert(orig_request != NULL);
2683         rbd_assert(obj_request_type_valid(orig_request->type));
2684         img_result = img_request->result;
2685         parent_length = img_request->length;
2686         rbd_assert(img_result || parent_length == img_request->xferred);
2687         rbd_img_request_put(img_request);
2688
2689         rbd_assert(orig_request->img_request);
2690         rbd_dev = orig_request->img_request->rbd_dev;
2691         rbd_assert(rbd_dev);
2692
2693         /*
2694          * If the overlap has become 0 (most likely because the
2695          * image has been flattened) we need to free the pages
2696          * and re-submit the original write request.
2697          */
2698         if (!rbd_dev->parent_overlap) {
2699                 ceph_release_page_vector(pages, page_count);
2700                 rbd_obj_request_submit(orig_request);
2701                 return;
2702         }
2703
2704         if (img_result)
2705                 goto out_err;
2706
2707         /*
2708          * The original osd request is of no use to use any more.
2709          * We need a new one that can hold the three ops in a copyup
2710          * request.  Allocate the new copyup osd request for the
2711          * original request, and release the old one.
2712          */
2713         img_result = -ENOMEM;
2714         osd_req = rbd_osd_req_create_copyup(orig_request);
2715         if (!osd_req)
2716                 goto out_err;
2717         rbd_osd_req_destroy(orig_request->osd_req);
2718         orig_request->osd_req = osd_req;
2719         orig_request->copyup_pages = pages;
2720         orig_request->copyup_page_count = page_count;
2721
2722         /* Initialize the copyup op */
2723
2724         osd_req_op_cls_init(osd_req, 0, CEPH_OSD_OP_CALL, "rbd", "copyup");
2725         osd_req_op_cls_request_data_pages(osd_req, 0, pages, parent_length, 0,
2726                                                 false, false);
2727
2728         /* Add the other op(s) */
2729
2730         op_type = rbd_img_request_op_type(orig_request->img_request);
2731         rbd_img_obj_request_fill(orig_request, osd_req, op_type, 1);
2732
2733         /* All set, send it off. */
2734
2735         rbd_obj_request_submit(orig_request);
2736         return;
2737
2738 out_err:
2739         ceph_release_page_vector(pages, page_count);
2740         rbd_obj_request_error(orig_request, img_result);
2741 }
2742
2743 /*
2744  * Read from the parent image the range of data that covers the
2745  * entire target of the given object request.  This is used for
2746  * satisfying a layered image write request when the target of an
2747  * object request from the image request does not exist.
2748  *
2749  * A page array big enough to hold the returned data is allocated
2750  * and supplied to rbd_img_request_fill() as the "data descriptor."
2751  * When the read completes, this page array will be transferred to
2752  * the original object request for the copyup operation.
2753  *
2754  * If an error occurs, it is recorded as the result of the original
2755  * object request in rbd_img_obj_exists_callback().
2756  */
2757 static int rbd_img_obj_parent_read_full(struct rbd_obj_request *obj_request)
2758 {
2759         struct rbd_device *rbd_dev = obj_request->img_request->rbd_dev;
2760         struct rbd_img_request *parent_request = NULL;
2761         u64 img_offset;
2762         u64 length;
2763         struct page **pages = NULL;
2764         u32 page_count;
2765         int result;
2766
2767         rbd_assert(rbd_dev->parent != NULL);
2768
2769         /*
2770          * Determine the byte range covered by the object in the
2771          * child image to which the original request was to be sent.
2772          */
2773         img_offset = obj_request->img_offset - obj_request->offset;
2774         length = (u64)1 << rbd_dev->header.obj_order;
2775
2776         /*
2777          * There is no defined parent data beyond the parent
2778          * overlap, so limit what we read at that boundary if
2779          * necessary.
2780          */
2781         if (img_offset + length > rbd_dev->parent_overlap) {
2782                 rbd_assert(img_offset < rbd_dev->parent_overlap);
2783                 length = rbd_dev->parent_overlap - img_offset;
2784         }
2785
2786         /*
2787          * Allocate a page array big enough to receive the data read
2788          * from the parent.
2789          */
2790         page_count = (u32)calc_pages_for(0, length);
2791         pages = ceph_alloc_page_vector(page_count, GFP_KERNEL);
2792         if (IS_ERR(pages)) {
2793                 result = PTR_ERR(pages);
2794                 pages = NULL;
2795                 goto out_err;
2796         }
2797
2798         result = -ENOMEM;
2799         parent_request = rbd_parent_request_create(obj_request,
2800                                                 img_offset, length);
2801         if (!parent_request)
2802                 goto out_err;
2803
2804         result = rbd_img_request_fill(parent_request, OBJ_REQUEST_PAGES, pages);
2805         if (result)
2806                 goto out_err;
2807
2808         parent_request->copyup_pages = pages;
2809         parent_request->copyup_page_count = page_count;
2810         parent_request->callback = rbd_img_obj_parent_read_full_callback;
2811
2812         result = rbd_img_request_submit(parent_request);
2813         if (!result)
2814                 return 0;
2815
2816         parent_request->copyup_pages = NULL;
2817         parent_request->copyup_page_count = 0;
2818         parent_request->obj_request = NULL;
2819         rbd_obj_request_put(obj_request);
2820 out_err:
2821         if (pages)
2822                 ceph_release_page_vector(pages, page_count);
2823         if (parent_request)
2824                 rbd_img_request_put(parent_request);
2825         return result;
2826 }
2827
2828 static void rbd_img_obj_exists_callback(struct rbd_obj_request *obj_request)
2829 {
2830         struct rbd_obj_request *orig_request;
2831         struct rbd_device *rbd_dev;
2832         int result;
2833
2834         rbd_assert(!obj_request_img_data_test(obj_request));
2835
2836         /*
2837          * All we need from the object request is the original
2838          * request and the result of the STAT op.  Grab those, then
2839          * we're done with the request.
2840          */
2841         orig_request = obj_request->obj_request;
2842         obj_request->obj_request = NULL;
2843         rbd_obj_request_put(orig_request);
2844         rbd_assert(orig_request);
2845         rbd_assert(orig_request->img_request);
2846
2847         result = obj_request->result;
2848         obj_request->result = 0;
2849
2850         dout("%s: obj %p for obj %p result %d %llu/%llu\n", __func__,
2851                 obj_request, orig_request, result,
2852                 obj_request->xferred, obj_request->length);
2853         rbd_obj_request_put(obj_request);
2854
2855         /*
2856          * If the overlap has become 0 (most likely because the
2857          * image has been flattened) we need to re-submit the
2858          * original request.
2859          */
2860         rbd_dev = orig_request->img_request->rbd_dev;
2861         if (!rbd_dev->parent_overlap) {
2862                 rbd_obj_request_submit(orig_request);
2863                 return;
2864         }
2865
2866         /*
2867          * Our only purpose here is to determine whether the object
2868          * exists, and we don't want to treat the non-existence as
2869          * an error.  If something else comes back, transfer the
2870          * error to the original request and complete it now.
2871          */
2872         if (!result) {
2873                 obj_request_existence_set(orig_request, true);
2874         } else if (result == -ENOENT) {
2875                 obj_request_existence_set(orig_request, false);
2876         } else {
2877                 goto fail_orig_request;
2878         }
2879
2880         /*
2881          * Resubmit the original request now that we have recorded
2882          * whether the target object exists.
2883          */
2884         result = rbd_img_obj_request_submit(orig_request);
2885         if (result)
2886                 goto fail_orig_request;
2887
2888         return;
2889
2890 fail_orig_request:
2891         rbd_obj_request_error(orig_request, result);
2892 }
2893
2894 static int rbd_img_obj_exists_submit(struct rbd_obj_request *obj_request)
2895 {
2896         struct rbd_device *rbd_dev = obj_request->img_request->rbd_dev;
2897         struct rbd_obj_request *stat_request;
2898         struct page **pages;
2899         u32 page_count;
2900         size_t size;
2901         int ret;
2902
2903         stat_request = rbd_obj_request_create(obj_request->object_name, 0, 0,
2904                                               OBJ_REQUEST_PAGES);
2905         if (!stat_request)
2906                 return -ENOMEM;
2907
2908         stat_request->osd_req = rbd_osd_req_create(rbd_dev, OBJ_OP_READ, 1,
2909                                                    stat_request);
2910         if (!stat_request->osd_req) {
2911                 ret = -ENOMEM;
2912                 goto fail_stat_request;
2913         }
2914
2915         /*
2916          * The response data for a STAT call consists of:
2917          *     le64 length;
2918          *     struct {
2919          *         le32 tv_sec;
2920          *         le32 tv_nsec;
2921          *     } mtime;
2922          */
2923         size = sizeof (__le64) + sizeof (__le32) + sizeof (__le32);
2924         page_count = (u32)calc_pages_for(0, size);
2925         pages = ceph_alloc_page_vector(page_count, GFP_KERNEL);
2926         if (IS_ERR(pages)) {
2927                 ret = PTR_ERR(pages);
2928                 goto fail_stat_request;
2929         }
2930
2931         osd_req_op_init(stat_request->osd_req, 0, CEPH_OSD_OP_STAT, 0);
2932         osd_req_op_raw_data_in_pages(stat_request->osd_req, 0, pages, size, 0,
2933                                      false, false);
2934
2935         rbd_obj_request_get(obj_request);
2936         stat_request->obj_request = obj_request;
2937         stat_request->pages = pages;
2938         stat_request->page_count = page_count;
2939         stat_request->callback = rbd_img_obj_exists_callback;
2940
2941         rbd_obj_request_submit(stat_request);
2942         return 0;
2943
2944 fail_stat_request:
2945         rbd_obj_request_put(stat_request);
2946         return ret;
2947 }
2948
2949 static bool img_obj_request_simple(struct rbd_obj_request *obj_request)
2950 {
2951         struct rbd_img_request *img_request = obj_request->img_request;
2952         struct rbd_device *rbd_dev = img_request->rbd_dev;
2953
2954         /* Reads */
2955         if (!img_request_write_test(img_request) &&
2956             !img_request_discard_test(img_request))
2957                 return true;
2958
2959         /* Non-layered writes */
2960         if (!img_request_layered_test(img_request))
2961                 return true;
2962
2963         /*
2964          * Layered writes outside of the parent overlap range don't
2965          * share any data with the parent.
2966          */
2967         if (!obj_request_overlaps_parent(obj_request))
2968                 return true;
2969
2970         /*
2971          * Entire-object layered writes - we will overwrite whatever
2972          * parent data there is anyway.
2973          */
2974         if (!obj_request->offset &&
2975             obj_request->length == rbd_obj_bytes(&rbd_dev->header))
2976                 return true;
2977
2978         /*
2979          * If the object is known to already exist, its parent data has
2980          * already been copied.
2981          */
2982         if (obj_request_known_test(obj_request) &&
2983             obj_request_exists_test(obj_request))
2984                 return true;
2985
2986         return false;
2987 }
2988
2989 static int rbd_img_obj_request_submit(struct rbd_obj_request *obj_request)
2990 {
2991         rbd_assert(obj_request_img_data_test(obj_request));
2992         rbd_assert(obj_request_type_valid(obj_request->type));
2993         rbd_assert(obj_request->img_request);
2994
2995         if (img_obj_request_simple(obj_request)) {
2996                 rbd_obj_request_submit(obj_request);
2997                 return 0;
2998         }
2999
3000         /*
3001          * It's a layered write.  The target object might exist but
3002          * we may not know that yet.  If we know it doesn't exist,
3003          * start by reading the data for the full target object from
3004          * the parent so we can use it for a copyup to the target.
3005          */
3006         if (obj_request_known_test(obj_request))
3007                 return rbd_img_obj_parent_read_full(obj_request);
3008
3009         /* We don't know whether the target exists.  Go find out. */
3010
3011         return rbd_img_obj_exists_submit(obj_request);
3012 }
3013
3014 static int rbd_img_request_submit(struct rbd_img_request *img_request)
3015 {
3016         struct rbd_obj_request *obj_request;
3017         struct rbd_obj_request *next_obj_request;
3018         int ret = 0;
3019
3020         dout("%s: img %p\n", __func__, img_request);
3021
3022         rbd_img_request_get(img_request);
3023         for_each_obj_request_safe(img_request, obj_request, next_obj_request) {
3024                 ret = rbd_img_obj_request_submit(obj_request);
3025                 if (ret)
3026                         goto out_put_ireq;
3027         }
3028
3029 out_put_ireq:
3030         rbd_img_request_put(img_request);
3031         return ret;
3032 }
3033
3034 static void rbd_img_parent_read_callback(struct rbd_img_request *img_request)
3035 {
3036         struct rbd_obj_request *obj_request;
3037         struct rbd_device *rbd_dev;
3038         u64 obj_end;
3039         u64 img_xferred;
3040         int img_result;
3041
3042         rbd_assert(img_request_child_test(img_request));
3043
3044         /* First get what we need from the image request and release it */
3045
3046         obj_request = img_request->obj_request;
3047         img_xferred = img_request->xferred;
3048         img_result = img_request->result;
3049         rbd_img_request_put(img_request);
3050
3051         /*
3052          * If the overlap has become 0 (most likely because the
3053          * image has been flattened) we need to re-submit the
3054          * original request.
3055          */
3056         rbd_assert(obj_request);
3057         rbd_assert(obj_request->img_request);
3058         rbd_dev = obj_request->img_request->rbd_dev;
3059         if (!rbd_dev->parent_overlap) {
3060                 rbd_obj_request_submit(obj_request);
3061                 return;
3062         }
3063
3064         obj_request->result = img_result;
3065         if (obj_request->result)
3066                 goto out;
3067
3068         /*
3069          * We need to zero anything beyond the parent overlap
3070          * boundary.  Since rbd_img_obj_request_read_callback()
3071          * will zero anything beyond the end of a short read, an
3072          * easy way to do this is to pretend the data from the
3073          * parent came up short--ending at the overlap boundary.
3074          */
3075         rbd_assert(obj_request->img_offset < U64_MAX - obj_request->length);
3076         obj_end = obj_request->img_offset + obj_request->length;
3077         if (obj_end > rbd_dev->parent_overlap) {
3078                 u64 xferred = 0;
3079
3080                 if (obj_request->img_offset < rbd_dev->parent_overlap)
3081                         xferred = rbd_dev->parent_overlap -
3082                                         obj_request->img_offset;
3083
3084                 obj_request->xferred = min(img_xferred, xferred);
3085         } else {
3086                 obj_request->xferred = img_xferred;
3087         }
3088 out:
3089         rbd_img_obj_request_read_callback(obj_request);
3090         rbd_obj_request_complete(obj_request);
3091 }
3092
3093 static void rbd_img_parent_read(struct rbd_obj_request *obj_request)
3094 {
3095         struct rbd_img_request *img_request;
3096         int result;
3097
3098         rbd_assert(obj_request_img_data_test(obj_request));
3099         rbd_assert(obj_request->img_request != NULL);
3100         rbd_assert(obj_request->result == (s32) -ENOENT);
3101         rbd_assert(obj_request_type_valid(obj_request->type));
3102
3103         /* rbd_read_finish(obj_request, obj_request->length); */
3104         img_request = rbd_parent_request_create(obj_request,
3105                                                 obj_request->img_offset,
3106                                                 obj_request->length);
3107         result = -ENOMEM;
3108         if (!img_request)
3109                 goto out_err;
3110
3111         if (obj_request->type == OBJ_REQUEST_BIO)
3112                 result = rbd_img_request_fill(img_request, OBJ_REQUEST_BIO,
3113                                                 obj_request->bio_list);
3114         else
3115                 result = rbd_img_request_fill(img_request, OBJ_REQUEST_PAGES,
3116                                                 obj_request->pages);
3117         if (result)
3118                 goto out_err;
3119
3120         img_request->callback = rbd_img_parent_read_callback;
3121         result = rbd_img_request_submit(img_request);
3122         if (result)
3123                 goto out_err;
3124
3125         return;
3126 out_err:
3127         if (img_request)
3128                 rbd_img_request_put(img_request);
3129         obj_request->result = result;
3130         obj_request->xferred = 0;
3131         obj_request_done_set(obj_request);
3132 }
3133
3134 static const struct rbd_client_id rbd_empty_cid;
3135
3136 static bool rbd_cid_equal(const struct rbd_client_id *lhs,
3137                           const struct rbd_client_id *rhs)
3138 {
3139         return lhs->gid == rhs->gid && lhs->handle == rhs->handle;
3140 }
3141
3142 static struct rbd_client_id rbd_get_cid(struct rbd_device *rbd_dev)
3143 {
3144         struct rbd_client_id cid;
3145
3146         mutex_lock(&rbd_dev->watch_mutex);
3147         cid.gid = ceph_client_gid(rbd_dev->rbd_client->client);
3148         cid.handle = rbd_dev->watch_cookie;
3149         mutex_unlock(&rbd_dev->watch_mutex);
3150         return cid;
3151 }
3152
3153 /*
3154  * lock_rwsem must be held for write
3155  */
3156 static void rbd_set_owner_cid(struct rbd_device *rbd_dev,
3157                               const struct rbd_client_id *cid)
3158 {
3159         dout("%s rbd_dev %p %llu-%llu -> %llu-%llu\n", __func__, rbd_dev,
3160              rbd_dev->owner_cid.gid, rbd_dev->owner_cid.handle,
3161              cid->gid, cid->handle);
3162         rbd_dev->owner_cid = *cid; /* struct */
3163 }
3164
3165 static void format_lock_cookie(struct rbd_device *rbd_dev, char *buf)
3166 {
3167         mutex_lock(&rbd_dev->watch_mutex);
3168         sprintf(buf, "%s %llu", RBD_LOCK_COOKIE_PREFIX, rbd_dev->watch_cookie);
3169         mutex_unlock(&rbd_dev->watch_mutex);
3170 }
3171
3172 /*
3173  * lock_rwsem must be held for write
3174  */
3175 static int rbd_lock(struct rbd_device *rbd_dev)
3176 {
3177         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
3178         struct rbd_client_id cid = rbd_get_cid(rbd_dev);
3179         char cookie[32];
3180         int ret;
3181
3182         WARN_ON(__rbd_is_lock_owner(rbd_dev));
3183
3184         format_lock_cookie(rbd_dev, cookie);
3185         ret = ceph_cls_lock(osdc, &rbd_dev->header_oid, &rbd_dev->header_oloc,
3186                             RBD_LOCK_NAME, CEPH_CLS_LOCK_EXCLUSIVE, cookie,
3187                             RBD_LOCK_TAG, "", 0);
3188         if (ret)
3189                 return ret;
3190
3191         rbd_dev->lock_state = RBD_LOCK_STATE_LOCKED;
3192         rbd_set_owner_cid(rbd_dev, &cid);
3193         queue_work(rbd_dev->task_wq, &rbd_dev->acquired_lock_work);
3194         return 0;
3195 }
3196
3197 /*
3198  * lock_rwsem must be held for write
3199  */
3200 static int rbd_unlock(struct rbd_device *rbd_dev)
3201 {
3202         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
3203         char cookie[32];
3204         int ret;
3205
3206         WARN_ON(!__rbd_is_lock_owner(rbd_dev));
3207
3208         rbd_dev->lock_state = RBD_LOCK_STATE_UNLOCKED;
3209
3210         format_lock_cookie(rbd_dev, cookie);
3211         ret = ceph_cls_unlock(osdc, &rbd_dev->header_oid, &rbd_dev->header_oloc,
3212                               RBD_LOCK_NAME, cookie);
3213         if (ret && ret != -ENOENT) {
3214                 rbd_warn(rbd_dev, "cls_unlock failed: %d", ret);
3215                 return ret;
3216         }
3217
3218         rbd_set_owner_cid(rbd_dev, &rbd_empty_cid);
3219         queue_work(rbd_dev->task_wq, &rbd_dev->released_lock_work);
3220         return 0;
3221 }
3222
3223 static int __rbd_notify_op_lock(struct rbd_device *rbd_dev,
3224                                 enum rbd_notify_op notify_op,
3225                                 struct page ***preply_pages,
3226                                 size_t *preply_len)
3227 {
3228         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
3229         struct rbd_client_id cid = rbd_get_cid(rbd_dev);
3230         int buf_size = 4 + 8 + 8 + CEPH_ENCODING_START_BLK_LEN;
3231         char buf[buf_size];
3232         void *p = buf;
3233
3234         dout("%s rbd_dev %p notify_op %d\n", __func__, rbd_dev, notify_op);
3235
3236         /* encode *LockPayload NotifyMessage (op + ClientId) */
3237         ceph_start_encoding(&p, 2, 1, buf_size - CEPH_ENCODING_START_BLK_LEN);
3238         ceph_encode_32(&p, notify_op);
3239         ceph_encode_64(&p, cid.gid);
3240         ceph_encode_64(&p, cid.handle);
3241
3242         return ceph_osdc_notify(osdc, &rbd_dev->header_oid,
3243                                 &rbd_dev->header_oloc, buf, buf_size,
3244                                 RBD_NOTIFY_TIMEOUT, preply_pages, preply_len);
3245 }
3246
3247 static void rbd_notify_op_lock(struct rbd_device *rbd_dev,
3248                                enum rbd_notify_op notify_op)
3249 {
3250         struct page **reply_pages;
3251         size_t reply_len;
3252
3253         __rbd_notify_op_lock(rbd_dev, notify_op, &reply_pages, &reply_len);
3254         ceph_release_page_vector(reply_pages, calc_pages_for(0, reply_len));
3255 }
3256
3257 static void rbd_notify_acquired_lock(struct work_struct *work)
3258 {
3259         struct rbd_device *rbd_dev = container_of(work, struct rbd_device,
3260                                                   acquired_lock_work);
3261
3262         rbd_notify_op_lock(rbd_dev, RBD_NOTIFY_OP_ACQUIRED_LOCK);
3263 }
3264
3265 static void rbd_notify_released_lock(struct work_struct *work)
3266 {
3267         struct rbd_device *rbd_dev = container_of(work, struct rbd_device,
3268                                                   released_lock_work);
3269
3270         rbd_notify_op_lock(rbd_dev, RBD_NOTIFY_OP_RELEASED_LOCK);
3271 }
3272
3273 static int rbd_request_lock(struct rbd_device *rbd_dev)
3274 {
3275         struct page **reply_pages;
3276         size_t reply_len;
3277         bool lock_owner_responded = false;
3278         int ret;
3279
3280         dout("%s rbd_dev %p\n", __func__, rbd_dev);
3281
3282         ret = __rbd_notify_op_lock(rbd_dev, RBD_NOTIFY_OP_REQUEST_LOCK,
3283                                    &reply_pages, &reply_len);
3284         if (ret && ret != -ETIMEDOUT) {
3285                 rbd_warn(rbd_dev, "failed to request lock: %d", ret);
3286                 goto out;
3287         }
3288
3289         if (reply_len > 0 && reply_len <= PAGE_SIZE) {
3290                 void *p = page_address(reply_pages[0]);
3291                 void *const end = p + reply_len;
3292                 u32 n;
3293
3294                 ceph_decode_32_safe(&p, end, n, e_inval); /* num_acks */
3295                 while (n--) {
3296                         u8 struct_v;
3297                         u32 len;
3298
3299                         ceph_decode_need(&p, end, 8 + 8, e_inval);
3300                         p += 8 + 8; /* skip gid and cookie */
3301
3302                         ceph_decode_32_safe(&p, end, len, e_inval);
3303                         if (!len)
3304                                 continue;
3305
3306                         if (lock_owner_responded) {
3307                                 rbd_warn(rbd_dev,
3308                                          "duplicate lock owners detected");
3309                                 ret = -EIO;
3310                                 goto out;
3311                         }
3312
3313                         lock_owner_responded = true;
3314                         ret = ceph_start_decoding(&p, end, 1, "ResponseMessage",
3315                                                   &struct_v, &len);
3316                         if (ret) {
3317                                 rbd_warn(rbd_dev,
3318                                          "failed to decode ResponseMessage: %d",
3319                                          ret);
3320                                 goto e_inval;
3321                         }
3322
3323                         ret = ceph_decode_32(&p);
3324                 }
3325         }
3326
3327         if (!lock_owner_responded) {
3328                 rbd_warn(rbd_dev, "no lock owners detected");
3329                 ret = -ETIMEDOUT;
3330         }
3331
3332 out:
3333         ceph_release_page_vector(reply_pages, calc_pages_for(0, reply_len));
3334         return ret;
3335
3336 e_inval:
3337         ret = -EINVAL;
3338         goto out;
3339 }
3340
3341 static void wake_requests(struct rbd_device *rbd_dev, bool wake_all)
3342 {
3343         dout("%s rbd_dev %p wake_all %d\n", __func__, rbd_dev, wake_all);
3344
3345         cancel_delayed_work(&rbd_dev->lock_dwork);
3346         if (wake_all)
3347                 wake_up_all(&rbd_dev->lock_waitq);
3348         else
3349                 wake_up(&rbd_dev->lock_waitq);
3350 }
3351
3352 static int get_lock_owner_info(struct rbd_device *rbd_dev,
3353                                struct ceph_locker **lockers, u32 *num_lockers)
3354 {
3355         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
3356         u8 lock_type;
3357         char *lock_tag;
3358         int ret;
3359
3360         dout("%s rbd_dev %p\n", __func__, rbd_dev);
3361
3362         ret = ceph_cls_lock_info(osdc, &rbd_dev->header_oid,
3363                                  &rbd_dev->header_oloc, RBD_LOCK_NAME,
3364                                  &lock_type, &lock_tag, lockers, num_lockers);
3365         if (ret)
3366                 return ret;
3367
3368         if (*num_lockers == 0) {
3369                 dout("%s rbd_dev %p no lockers detected\n", __func__, rbd_dev);
3370                 goto out;
3371         }
3372
3373         if (strcmp(lock_tag, RBD_LOCK_TAG)) {
3374                 rbd_warn(rbd_dev, "locked by external mechanism, tag %s",
3375                          lock_tag);
3376                 ret = -EBUSY;
3377                 goto out;
3378         }
3379
3380         if (lock_type == CEPH_CLS_LOCK_SHARED) {
3381                 rbd_warn(rbd_dev, "shared lock type detected");
3382                 ret = -EBUSY;
3383                 goto out;
3384         }
3385
3386         if (strncmp((*lockers)[0].id.cookie, RBD_LOCK_COOKIE_PREFIX,
3387                     strlen(RBD_LOCK_COOKIE_PREFIX))) {
3388                 rbd_warn(rbd_dev, "locked by external mechanism, cookie %s",
3389                          (*lockers)[0].id.cookie);
3390                 ret = -EBUSY;
3391                 goto out;
3392         }
3393
3394 out:
3395         kfree(lock_tag);
3396         return ret;
3397 }
3398
3399 static int find_watcher(struct rbd_device *rbd_dev,
3400                         const struct ceph_locker *locker)
3401 {
3402         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
3403         struct ceph_watch_item *watchers;
3404         u32 num_watchers;
3405         u64 cookie;
3406         int i;
3407         int ret;
3408
3409         ret = ceph_osdc_list_watchers(osdc, &rbd_dev->header_oid,
3410                                       &rbd_dev->header_oloc, &watchers,
3411                                       &num_watchers);
3412         if (ret)
3413                 return ret;
3414
3415         sscanf(locker->id.cookie, RBD_LOCK_COOKIE_PREFIX " %llu", &cookie);
3416         for (i = 0; i < num_watchers; i++) {
3417                 if (!memcmp(&watchers[i].addr, &locker->info.addr,
3418                             sizeof(locker->info.addr)) &&
3419                     watchers[i].cookie == cookie) {
3420                         struct rbd_client_id cid = {
3421                                 .gid = le64_to_cpu(watchers[i].name.num),
3422                                 .handle = cookie,
3423                         };
3424
3425                         dout("%s rbd_dev %p found cid %llu-%llu\n", __func__,
3426                              rbd_dev, cid.gid, cid.handle);
3427                         rbd_set_owner_cid(rbd_dev, &cid);
3428                         ret = 1;
3429                         goto out;
3430                 }
3431         }
3432
3433         dout("%s rbd_dev %p no watchers\n", __func__, rbd_dev);
3434         ret = 0;
3435 out:
3436         kfree(watchers);
3437         return ret;
3438 }
3439
3440 /*
3441  * lock_rwsem must be held for write
3442  */
3443 static int rbd_try_lock(struct rbd_device *rbd_dev)
3444 {
3445         struct ceph_client *client = rbd_dev->rbd_client->client;
3446         struct ceph_locker *lockers;
3447         u32 num_lockers;
3448         int ret;
3449
3450         for (;;) {
3451                 ret = rbd_lock(rbd_dev);
3452                 if (ret != -EBUSY)
3453                         return ret;
3454
3455                 /* determine if the current lock holder is still alive */
3456                 ret = get_lock_owner_info(rbd_dev, &lockers, &num_lockers);
3457                 if (ret)
3458                         return ret;
3459
3460                 if (num_lockers == 0)
3461                         goto again;
3462
3463                 ret = find_watcher(rbd_dev, lockers);
3464                 if (ret) {
3465                         if (ret > 0)
3466                                 ret = 0; /* have to request lock */
3467                         goto out;
3468                 }
3469
3470                 rbd_warn(rbd_dev, "%s%llu seems dead, breaking lock",
3471                          ENTITY_NAME(lockers[0].id.name));
3472
3473                 ret = ceph_monc_blacklist_add(&client->monc,
3474                                               &lockers[0].info.addr);
3475                 if (ret) {
3476                         rbd_warn(rbd_dev, "blacklist of %s%llu failed: %d",
3477                                  ENTITY_NAME(lockers[0].id.name), ret);
3478                         goto out;
3479                 }
3480
3481                 ret = ceph_cls_break_lock(&client->osdc, &rbd_dev->header_oid,
3482                                           &rbd_dev->header_oloc, RBD_LOCK_NAME,
3483                                           lockers[0].id.cookie,
3484                                           &lockers[0].id.name);
3485                 if (ret && ret != -ENOENT)
3486                         goto out;
3487
3488 again:
3489                 ceph_free_lockers(lockers, num_lockers);
3490         }
3491
3492 out:
3493         ceph_free_lockers(lockers, num_lockers);
3494         return ret;
3495 }
3496
3497 /*
3498  * ret is set only if lock_state is RBD_LOCK_STATE_UNLOCKED
3499  */
3500 static enum rbd_lock_state rbd_try_acquire_lock(struct&