rbd: stop copying num_osd_ops in rbd_obj_issue_copyup()
[linux-2.6-microblaze.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/striper.h>
36 #include <linux/ceph/decode.h>
37 #include <linux/parser.h>
38 #include <linux/bsearch.h>
39
40 #include <linux/kernel.h>
41 #include <linux/device.h>
42 #include <linux/module.h>
43 #include <linux/blk-mq.h>
44 #include <linux/fs.h>
45 #include <linux/blkdev.h>
46 #include <linux/slab.h>
47 #include <linux/idr.h>
48 #include <linux/workqueue.h>
49
50 #include "rbd_types.h"
51
52 #define RBD_DEBUG       /* Activate rbd_assert() calls */
53
54 /*
55  * Increment the given counter and return its updated value.
56  * If the counter is already 0 it will not be incremented.
57  * If the counter is already at its maximum value returns
58  * -EINVAL without updating it.
59  */
60 static int atomic_inc_return_safe(atomic_t *v)
61 {
62         unsigned int counter;
63
64         counter = (unsigned int)atomic_fetch_add_unless(v, 1, 0);
65         if (counter <= (unsigned int)INT_MAX)
66                 return (int)counter;
67
68         atomic_dec(v);
69
70         return -EINVAL;
71 }
72
73 /* Decrement the counter.  Return the resulting value, or -EINVAL */
74 static int atomic_dec_return_safe(atomic_t *v)
75 {
76         int counter;
77
78         counter = atomic_dec_return(v);
79         if (counter >= 0)
80                 return counter;
81
82         atomic_inc(v);
83
84         return -EINVAL;
85 }
86
87 #define RBD_DRV_NAME "rbd"
88
89 #define RBD_MINORS_PER_MAJOR            256
90 #define RBD_SINGLE_MAJOR_PART_SHIFT     4
91
92 #define RBD_MAX_PARENT_CHAIN_LEN        16
93
94 #define RBD_SNAP_DEV_NAME_PREFIX        "snap_"
95 #define RBD_MAX_SNAP_NAME_LEN   \
96                         (NAME_MAX - (sizeof (RBD_SNAP_DEV_NAME_PREFIX) - 1))
97
98 #define RBD_MAX_SNAP_COUNT      510     /* allows max snapc to fit in 4KB */
99
100 #define RBD_SNAP_HEAD_NAME      "-"
101
102 #define BAD_SNAP_INDEX  U32_MAX         /* invalid index into snap array */
103
104 /* This allows a single page to hold an image name sent by OSD */
105 #define RBD_IMAGE_NAME_LEN_MAX  (PAGE_SIZE - sizeof (__le32) - 1)
106 #define RBD_IMAGE_ID_LEN_MAX    64
107
108 #define RBD_OBJ_PREFIX_LEN_MAX  64
109
110 #define RBD_NOTIFY_TIMEOUT      5       /* seconds */
111 #define RBD_RETRY_DELAY         msecs_to_jiffies(1000)
112
113 /* Feature bits */
114
115 #define RBD_FEATURE_LAYERING            (1ULL<<0)
116 #define RBD_FEATURE_STRIPINGV2          (1ULL<<1)
117 #define RBD_FEATURE_EXCLUSIVE_LOCK      (1ULL<<2)
118 #define RBD_FEATURE_DATA_POOL           (1ULL<<7)
119 #define RBD_FEATURE_OPERATIONS          (1ULL<<8)
120
121 #define RBD_FEATURES_ALL        (RBD_FEATURE_LAYERING |         \
122                                  RBD_FEATURE_STRIPINGV2 |       \
123                                  RBD_FEATURE_EXCLUSIVE_LOCK |   \
124                                  RBD_FEATURE_DATA_POOL |        \
125                                  RBD_FEATURE_OPERATIONS)
126
127 /* Features supported by this (client software) implementation. */
128
129 #define RBD_FEATURES_SUPPORTED  (RBD_FEATURES_ALL)
130
131 /*
132  * An RBD device name will be "rbd#", where the "rbd" comes from
133  * RBD_DRV_NAME above, and # is a unique integer identifier.
134  */
135 #define DEV_NAME_LEN            32
136
137 /*
138  * block device image metadata (in-memory version)
139  */
140 struct rbd_image_header {
141         /* These six fields never change for a given rbd image */
142         char *object_prefix;
143         __u8 obj_order;
144         u64 stripe_unit;
145         u64 stripe_count;
146         s64 data_pool_id;
147         u64 features;           /* Might be changeable someday? */
148
149         /* The remaining fields need to be updated occasionally */
150         u64 image_size;
151         struct ceph_snap_context *snapc;
152         char *snap_names;       /* format 1 only */
153         u64 *snap_sizes;        /* format 1 only */
154 };
155
156 /*
157  * An rbd image specification.
158  *
159  * The tuple (pool_id, image_id, snap_id) is sufficient to uniquely
160  * identify an image.  Each rbd_dev structure includes a pointer to
161  * an rbd_spec structure that encapsulates this identity.
162  *
163  * Each of the id's in an rbd_spec has an associated name.  For a
164  * user-mapped image, the names are supplied and the id's associated
165  * with them are looked up.  For a layered image, a parent image is
166  * defined by the tuple, and the names are looked up.
167  *
168  * An rbd_dev structure contains a parent_spec pointer which is
169  * non-null if the image it represents is a child in a layered
170  * image.  This pointer will refer to the rbd_spec structure used
171  * by the parent rbd_dev for its own identity (i.e., the structure
172  * is shared between the parent and child).
173  *
174  * Since these structures are populated once, during the discovery
175  * phase of image construction, they are effectively immutable so
176  * we make no effort to synchronize access to them.
177  *
178  * Note that code herein does not assume the image name is known (it
179  * could be a null pointer).
180  */
181 struct rbd_spec {
182         u64             pool_id;
183         const char      *pool_name;
184         const char      *pool_ns;       /* NULL if default, never "" */
185
186         const char      *image_id;
187         const char      *image_name;
188
189         u64             snap_id;
190         const char      *snap_name;
191
192         struct kref     kref;
193 };
194
195 /*
196  * an instance of the client.  multiple devices may share an rbd client.
197  */
198 struct rbd_client {
199         struct ceph_client      *client;
200         struct kref             kref;
201         struct list_head        node;
202 };
203
204 struct rbd_img_request;
205
206 enum obj_request_type {
207         OBJ_REQUEST_NODATA = 1,
208         OBJ_REQUEST_BIO,        /* pointer into provided bio (list) */
209         OBJ_REQUEST_BVECS,      /* pointer into provided bio_vec array */
210         OBJ_REQUEST_OWN_BVECS,  /* private bio_vec array, doesn't own pages */
211 };
212
213 enum obj_operation_type {
214         OBJ_OP_READ = 1,
215         OBJ_OP_WRITE,
216         OBJ_OP_DISCARD,
217         OBJ_OP_ZEROOUT,
218 };
219
220 /*
221  * Writes go through the following state machine to deal with
222  * layering:
223  *
224  *                       need copyup
225  * RBD_OBJ_WRITE_GUARD ---------------> RBD_OBJ_WRITE_COPYUP
226  *        |     ^                              |
227  *        v     \------------------------------/
228  *      done
229  *        ^
230  *        |
231  * RBD_OBJ_WRITE_FLAT
232  *
233  * Writes start in RBD_OBJ_WRITE_GUARD or _FLAT, depending on whether
234  * there is a parent or not.
235  */
236 enum rbd_obj_write_state {
237         RBD_OBJ_WRITE_FLAT = 1,
238         RBD_OBJ_WRITE_GUARD,
239         RBD_OBJ_WRITE_COPYUP,
240 };
241
242 struct rbd_obj_request {
243         struct ceph_object_extent ex;
244         union {
245                 bool                    tried_parent;   /* for reads */
246                 enum rbd_obj_write_state write_state;   /* for writes */
247         };
248
249         struct rbd_img_request  *img_request;
250         struct ceph_file_extent *img_extents;
251         u32                     num_img_extents;
252
253         union {
254                 struct ceph_bio_iter    bio_pos;
255                 struct {
256                         struct ceph_bvec_iter   bvec_pos;
257                         u32                     bvec_count;
258                         u32                     bvec_idx;
259                 };
260         };
261         struct bio_vec          *copyup_bvecs;
262         u32                     copyup_bvec_count;
263
264         struct ceph_osd_request *osd_req;
265
266         u64                     xferred;        /* bytes transferred */
267         int                     result;
268
269         struct kref             kref;
270 };
271
272 enum img_req_flags {
273         IMG_REQ_CHILD,          /* initiator: block = 0, child image = 1 */
274         IMG_REQ_LAYERED,        /* ENOENT handling: normal = 0, layered = 1 */
275 };
276
277 struct rbd_img_request {
278         struct rbd_device       *rbd_dev;
279         enum obj_operation_type op_type;
280         enum obj_request_type   data_type;
281         unsigned long           flags;
282         union {
283                 u64                     snap_id;        /* for reads */
284                 struct ceph_snap_context *snapc;        /* for writes */
285         };
286         union {
287                 struct request          *rq;            /* block request */
288                 struct rbd_obj_request  *obj_request;   /* obj req initiator */
289         };
290         spinlock_t              completion_lock;
291         u64                     xferred;/* aggregate bytes transferred */
292         int                     result; /* first nonzero obj_request result */
293
294         struct list_head        object_extents; /* obj_req.ex structs */
295         u32                     pending_count;
296
297         struct kref             kref;
298 };
299
300 #define for_each_obj_request(ireq, oreq) \
301         list_for_each_entry(oreq, &(ireq)->object_extents, ex.oe_item)
302 #define for_each_obj_request_safe(ireq, oreq, n) \
303         list_for_each_entry_safe(oreq, n, &(ireq)->object_extents, ex.oe_item)
304
305 enum rbd_watch_state {
306         RBD_WATCH_STATE_UNREGISTERED,
307         RBD_WATCH_STATE_REGISTERED,
308         RBD_WATCH_STATE_ERROR,
309 };
310
311 enum rbd_lock_state {
312         RBD_LOCK_STATE_UNLOCKED,
313         RBD_LOCK_STATE_LOCKED,
314         RBD_LOCK_STATE_RELEASING,
315 };
316
317 /* WatchNotify::ClientId */
318 struct rbd_client_id {
319         u64 gid;
320         u64 handle;
321 };
322
323 struct rbd_mapping {
324         u64                     size;
325         u64                     features;
326 };
327
328 /*
329  * a single device
330  */
331 struct rbd_device {
332         int                     dev_id;         /* blkdev unique id */
333
334         int                     major;          /* blkdev assigned major */
335         int                     minor;
336         struct gendisk          *disk;          /* blkdev's gendisk and rq */
337
338         u32                     image_format;   /* Either 1 or 2 */
339         struct rbd_client       *rbd_client;
340
341         char                    name[DEV_NAME_LEN]; /* blkdev name, e.g. rbd3 */
342
343         spinlock_t              lock;           /* queue, flags, open_count */
344
345         struct rbd_image_header header;
346         unsigned long           flags;          /* possibly lock protected */
347         struct rbd_spec         *spec;
348         struct rbd_options      *opts;
349         char                    *config_info;   /* add{,_single_major} string */
350
351         struct ceph_object_id   header_oid;
352         struct ceph_object_locator header_oloc;
353
354         struct ceph_file_layout layout;         /* used for all rbd requests */
355
356         struct mutex            watch_mutex;
357         enum rbd_watch_state    watch_state;
358         struct ceph_osd_linger_request *watch_handle;
359         u64                     watch_cookie;
360         struct delayed_work     watch_dwork;
361
362         struct rw_semaphore     lock_rwsem;
363         enum rbd_lock_state     lock_state;
364         char                    lock_cookie[32];
365         struct rbd_client_id    owner_cid;
366         struct work_struct      acquired_lock_work;
367         struct work_struct      released_lock_work;
368         struct delayed_work     lock_dwork;
369         struct work_struct      unlock_work;
370         wait_queue_head_t       lock_waitq;
371
372         struct workqueue_struct *task_wq;
373
374         struct rbd_spec         *parent_spec;
375         u64                     parent_overlap;
376         atomic_t                parent_ref;
377         struct rbd_device       *parent;
378
379         /* Block layer tags. */
380         struct blk_mq_tag_set   tag_set;
381
382         /* protects updating the header */
383         struct rw_semaphore     header_rwsem;
384
385         struct rbd_mapping      mapping;
386
387         struct list_head        node;
388
389         /* sysfs related */
390         struct device           dev;
391         unsigned long           open_count;     /* protected by lock */
392 };
393
394 /*
395  * Flag bits for rbd_dev->flags:
396  * - REMOVING (which is coupled with rbd_dev->open_count) is protected
397  *   by rbd_dev->lock
398  * - BLACKLISTED is protected by rbd_dev->lock_rwsem
399  */
400 enum rbd_dev_flags {
401         RBD_DEV_FLAG_EXISTS,    /* mapped snapshot has not been deleted */
402         RBD_DEV_FLAG_REMOVING,  /* this mapping is being removed */
403         RBD_DEV_FLAG_BLACKLISTED, /* our ceph_client is blacklisted */
404 };
405
406 static DEFINE_MUTEX(client_mutex);      /* Serialize client creation */
407
408 static LIST_HEAD(rbd_dev_list);    /* devices */
409 static DEFINE_SPINLOCK(rbd_dev_list_lock);
410
411 static LIST_HEAD(rbd_client_list);              /* clients */
412 static DEFINE_SPINLOCK(rbd_client_list_lock);
413
414 /* Slab caches for frequently-allocated structures */
415
416 static struct kmem_cache        *rbd_img_request_cache;
417 static struct kmem_cache        *rbd_obj_request_cache;
418
419 static int rbd_major;
420 static DEFINE_IDA(rbd_dev_id_ida);
421
422 static struct workqueue_struct *rbd_wq;
423
424 /*
425  * single-major requires >= 0.75 version of userspace rbd utility.
426  */
427 static bool single_major = true;
428 module_param(single_major, bool, 0444);
429 MODULE_PARM_DESC(single_major, "Use a single major number for all rbd devices (default: true)");
430
431 static ssize_t rbd_add(struct bus_type *bus, const char *buf,
432                        size_t count);
433 static ssize_t rbd_remove(struct bus_type *bus, const char *buf,
434                           size_t count);
435 static ssize_t rbd_add_single_major(struct bus_type *bus, const char *buf,
436                                     size_t count);
437 static ssize_t rbd_remove_single_major(struct bus_type *bus, const char *buf,
438                                        size_t count);
439 static int rbd_dev_image_probe(struct rbd_device *rbd_dev, int depth);
440
441 static int rbd_dev_id_to_minor(int dev_id)
442 {
443         return dev_id << RBD_SINGLE_MAJOR_PART_SHIFT;
444 }
445
446 static int minor_to_rbd_dev_id(int minor)
447 {
448         return minor >> RBD_SINGLE_MAJOR_PART_SHIFT;
449 }
450
451 static bool __rbd_is_lock_owner(struct rbd_device *rbd_dev)
452 {
453         return rbd_dev->lock_state == RBD_LOCK_STATE_LOCKED ||
454                rbd_dev->lock_state == RBD_LOCK_STATE_RELEASING;
455 }
456
457 static bool rbd_is_lock_owner(struct rbd_device *rbd_dev)
458 {
459         bool is_lock_owner;
460
461         down_read(&rbd_dev->lock_rwsem);
462         is_lock_owner = __rbd_is_lock_owner(rbd_dev);
463         up_read(&rbd_dev->lock_rwsem);
464         return is_lock_owner;
465 }
466
467 static ssize_t rbd_supported_features_show(struct bus_type *bus, char *buf)
468 {
469         return sprintf(buf, "0x%llx\n", RBD_FEATURES_SUPPORTED);
470 }
471
472 static BUS_ATTR(add, 0200, NULL, rbd_add);
473 static BUS_ATTR(remove, 0200, NULL, rbd_remove);
474 static BUS_ATTR(add_single_major, 0200, NULL, rbd_add_single_major);
475 static BUS_ATTR(remove_single_major, 0200, NULL, rbd_remove_single_major);
476 static BUS_ATTR(supported_features, 0444, rbd_supported_features_show, NULL);
477
478 static struct attribute *rbd_bus_attrs[] = {
479         &bus_attr_add.attr,
480         &bus_attr_remove.attr,
481         &bus_attr_add_single_major.attr,
482         &bus_attr_remove_single_major.attr,
483         &bus_attr_supported_features.attr,
484         NULL,
485 };
486
487 static umode_t rbd_bus_is_visible(struct kobject *kobj,
488                                   struct attribute *attr, int index)
489 {
490         if (!single_major &&
491             (attr == &bus_attr_add_single_major.attr ||
492              attr == &bus_attr_remove_single_major.attr))
493                 return 0;
494
495         return attr->mode;
496 }
497
498 static const struct attribute_group rbd_bus_group = {
499         .attrs = rbd_bus_attrs,
500         .is_visible = rbd_bus_is_visible,
501 };
502 __ATTRIBUTE_GROUPS(rbd_bus);
503
504 static struct bus_type rbd_bus_type = {
505         .name           = "rbd",
506         .bus_groups     = rbd_bus_groups,
507 };
508
509 static void rbd_root_dev_release(struct device *dev)
510 {
511 }
512
513 static struct device rbd_root_dev = {
514         .init_name =    "rbd",
515         .release =      rbd_root_dev_release,
516 };
517
518 static __printf(2, 3)
519 void rbd_warn(struct rbd_device *rbd_dev, const char *fmt, ...)
520 {
521         struct va_format vaf;
522         va_list args;
523
524         va_start(args, fmt);
525         vaf.fmt = fmt;
526         vaf.va = &args;
527
528         if (!rbd_dev)
529                 printk(KERN_WARNING "%s: %pV\n", RBD_DRV_NAME, &vaf);
530         else if (rbd_dev->disk)
531                 printk(KERN_WARNING "%s: %s: %pV\n",
532                         RBD_DRV_NAME, rbd_dev->disk->disk_name, &vaf);
533         else if (rbd_dev->spec && rbd_dev->spec->image_name)
534                 printk(KERN_WARNING "%s: image %s: %pV\n",
535                         RBD_DRV_NAME, rbd_dev->spec->image_name, &vaf);
536         else if (rbd_dev->spec && rbd_dev->spec->image_id)
537                 printk(KERN_WARNING "%s: id %s: %pV\n",
538                         RBD_DRV_NAME, rbd_dev->spec->image_id, &vaf);
539         else    /* punt */
540                 printk(KERN_WARNING "%s: rbd_dev %p: %pV\n",
541                         RBD_DRV_NAME, rbd_dev, &vaf);
542         va_end(args);
543 }
544
545 #ifdef RBD_DEBUG
546 #define rbd_assert(expr)                                                \
547                 if (unlikely(!(expr))) {                                \
548                         printk(KERN_ERR "\nAssertion failure in %s() "  \
549                                                 "at line %d:\n\n"       \
550                                         "\trbd_assert(%s);\n\n",        \
551                                         __func__, __LINE__, #expr);     \
552                         BUG();                                          \
553                 }
554 #else /* !RBD_DEBUG */
555 #  define rbd_assert(expr)      ((void) 0)
556 #endif /* !RBD_DEBUG */
557
558 static void rbd_dev_remove_parent(struct rbd_device *rbd_dev);
559
560 static int rbd_dev_refresh(struct rbd_device *rbd_dev);
561 static int rbd_dev_v2_header_onetime(struct rbd_device *rbd_dev);
562 static int rbd_dev_header_info(struct rbd_device *rbd_dev);
563 static int rbd_dev_v2_parent_info(struct rbd_device *rbd_dev);
564 static const char *rbd_dev_v2_snap_name(struct rbd_device *rbd_dev,
565                                         u64 snap_id);
566 static int _rbd_dev_v2_snap_size(struct rbd_device *rbd_dev, u64 snap_id,
567                                 u8 *order, u64 *snap_size);
568 static int _rbd_dev_v2_snap_features(struct rbd_device *rbd_dev, u64 snap_id,
569                 u64 *snap_features);
570
571 static int rbd_open(struct block_device *bdev, fmode_t mode)
572 {
573         struct rbd_device *rbd_dev = bdev->bd_disk->private_data;
574         bool removing = false;
575
576         spin_lock_irq(&rbd_dev->lock);
577         if (test_bit(RBD_DEV_FLAG_REMOVING, &rbd_dev->flags))
578                 removing = true;
579         else
580                 rbd_dev->open_count++;
581         spin_unlock_irq(&rbd_dev->lock);
582         if (removing)
583                 return -ENOENT;
584
585         (void) get_device(&rbd_dev->dev);
586
587         return 0;
588 }
589
590 static void rbd_release(struct gendisk *disk, fmode_t mode)
591 {
592         struct rbd_device *rbd_dev = disk->private_data;
593         unsigned long open_count_before;
594
595         spin_lock_irq(&rbd_dev->lock);
596         open_count_before = rbd_dev->open_count--;
597         spin_unlock_irq(&rbd_dev->lock);
598         rbd_assert(open_count_before > 0);
599
600         put_device(&rbd_dev->dev);
601 }
602
603 static int rbd_ioctl_set_ro(struct rbd_device *rbd_dev, unsigned long arg)
604 {
605         int ro;
606
607         if (get_user(ro, (int __user *)arg))
608                 return -EFAULT;
609
610         /* Snapshots can't be marked read-write */
611         if (rbd_dev->spec->snap_id != CEPH_NOSNAP && !ro)
612                 return -EROFS;
613
614         /* Let blkdev_roset() handle it */
615         return -ENOTTY;
616 }
617
618 static int rbd_ioctl(struct block_device *bdev, fmode_t mode,
619                         unsigned int cmd, unsigned long arg)
620 {
621         struct rbd_device *rbd_dev = bdev->bd_disk->private_data;
622         int ret;
623
624         switch (cmd) {
625         case BLKROSET:
626                 ret = rbd_ioctl_set_ro(rbd_dev, arg);
627                 break;
628         default:
629                 ret = -ENOTTY;
630         }
631
632         return ret;
633 }
634
635 #ifdef CONFIG_COMPAT
636 static int rbd_compat_ioctl(struct block_device *bdev, fmode_t mode,
637                                 unsigned int cmd, unsigned long arg)
638 {
639         return rbd_ioctl(bdev, mode, cmd, arg);
640 }
641 #endif /* CONFIG_COMPAT */
642
643 static const struct block_device_operations rbd_bd_ops = {
644         .owner                  = THIS_MODULE,
645         .open                   = rbd_open,
646         .release                = rbd_release,
647         .ioctl                  = rbd_ioctl,
648 #ifdef CONFIG_COMPAT
649         .compat_ioctl           = rbd_compat_ioctl,
650 #endif
651 };
652
653 /*
654  * Initialize an rbd client instance.  Success or not, this function
655  * consumes ceph_opts.  Caller holds client_mutex.
656  */
657 static struct rbd_client *rbd_client_create(struct ceph_options *ceph_opts)
658 {
659         struct rbd_client *rbdc;
660         int ret = -ENOMEM;
661
662         dout("%s:\n", __func__);
663         rbdc = kmalloc(sizeof(struct rbd_client), GFP_KERNEL);
664         if (!rbdc)
665                 goto out_opt;
666
667         kref_init(&rbdc->kref);
668         INIT_LIST_HEAD(&rbdc->node);
669
670         rbdc->client = ceph_create_client(ceph_opts, rbdc);
671         if (IS_ERR(rbdc->client))
672                 goto out_rbdc;
673         ceph_opts = NULL; /* Now rbdc->client is responsible for ceph_opts */
674
675         ret = ceph_open_session(rbdc->client);
676         if (ret < 0)
677                 goto out_client;
678
679         spin_lock(&rbd_client_list_lock);
680         list_add_tail(&rbdc->node, &rbd_client_list);
681         spin_unlock(&rbd_client_list_lock);
682
683         dout("%s: rbdc %p\n", __func__, rbdc);
684
685         return rbdc;
686 out_client:
687         ceph_destroy_client(rbdc->client);
688 out_rbdc:
689         kfree(rbdc);
690 out_opt:
691         if (ceph_opts)
692                 ceph_destroy_options(ceph_opts);
693         dout("%s: error %d\n", __func__, ret);
694
695         return ERR_PTR(ret);
696 }
697
698 static struct rbd_client *__rbd_get_client(struct rbd_client *rbdc)
699 {
700         kref_get(&rbdc->kref);
701
702         return rbdc;
703 }
704
705 /*
706  * Find a ceph client with specific addr and configuration.  If
707  * found, bump its reference count.
708  */
709 static struct rbd_client *rbd_client_find(struct ceph_options *ceph_opts)
710 {
711         struct rbd_client *client_node;
712         bool found = false;
713
714         if (ceph_opts->flags & CEPH_OPT_NOSHARE)
715                 return NULL;
716
717         spin_lock(&rbd_client_list_lock);
718         list_for_each_entry(client_node, &rbd_client_list, node) {
719                 if (!ceph_compare_options(ceph_opts, client_node->client)) {
720                         __rbd_get_client(client_node);
721
722                         found = true;
723                         break;
724                 }
725         }
726         spin_unlock(&rbd_client_list_lock);
727
728         return found ? client_node : NULL;
729 }
730
731 /*
732  * (Per device) rbd map options
733  */
734 enum {
735         Opt_queue_depth,
736         Opt_alloc_size,
737         Opt_lock_timeout,
738         Opt_last_int,
739         /* int args above */
740         Opt_pool_ns,
741         Opt_last_string,
742         /* string args above */
743         Opt_read_only,
744         Opt_read_write,
745         Opt_lock_on_read,
746         Opt_exclusive,
747         Opt_notrim,
748         Opt_err
749 };
750
751 static match_table_t rbd_opts_tokens = {
752         {Opt_queue_depth, "queue_depth=%d"},
753         {Opt_alloc_size, "alloc_size=%d"},
754         {Opt_lock_timeout, "lock_timeout=%d"},
755         /* int args above */
756         {Opt_pool_ns, "_pool_ns=%s"},
757         /* string args above */
758         {Opt_read_only, "read_only"},
759         {Opt_read_only, "ro"},          /* Alternate spelling */
760         {Opt_read_write, "read_write"},
761         {Opt_read_write, "rw"},         /* Alternate spelling */
762         {Opt_lock_on_read, "lock_on_read"},
763         {Opt_exclusive, "exclusive"},
764         {Opt_notrim, "notrim"},
765         {Opt_err, NULL}
766 };
767
768 struct rbd_options {
769         int     queue_depth;
770         int     alloc_size;
771         unsigned long   lock_timeout;
772         bool    read_only;
773         bool    lock_on_read;
774         bool    exclusive;
775         bool    trim;
776 };
777
778 #define RBD_QUEUE_DEPTH_DEFAULT BLKDEV_MAX_RQ
779 #define RBD_ALLOC_SIZE_DEFAULT  (64 * 1024)
780 #define RBD_LOCK_TIMEOUT_DEFAULT 0  /* no timeout */
781 #define RBD_READ_ONLY_DEFAULT   false
782 #define RBD_LOCK_ON_READ_DEFAULT false
783 #define RBD_EXCLUSIVE_DEFAULT   false
784 #define RBD_TRIM_DEFAULT        true
785
786 struct parse_rbd_opts_ctx {
787         struct rbd_spec         *spec;
788         struct rbd_options      *opts;
789 };
790
791 static int parse_rbd_opts_token(char *c, void *private)
792 {
793         struct parse_rbd_opts_ctx *pctx = private;
794         substring_t argstr[MAX_OPT_ARGS];
795         int token, intval, ret;
796
797         token = match_token(c, rbd_opts_tokens, argstr);
798         if (token < Opt_last_int) {
799                 ret = match_int(&argstr[0], &intval);
800                 if (ret < 0) {
801                         pr_err("bad option arg (not int) at '%s'\n", c);
802                         return ret;
803                 }
804                 dout("got int token %d val %d\n", token, intval);
805         } else if (token > Opt_last_int && token < Opt_last_string) {
806                 dout("got string token %d val %s\n", token, argstr[0].from);
807         } else {
808                 dout("got token %d\n", token);
809         }
810
811         switch (token) {
812         case Opt_queue_depth:
813                 if (intval < 1) {
814                         pr_err("queue_depth out of range\n");
815                         return -EINVAL;
816                 }
817                 pctx->opts->queue_depth = intval;
818                 break;
819         case Opt_alloc_size:
820                 if (intval < 1) {
821                         pr_err("alloc_size out of range\n");
822                         return -EINVAL;
823                 }
824                 if (!is_power_of_2(intval)) {
825                         pr_err("alloc_size must be a power of 2\n");
826                         return -EINVAL;
827                 }
828                 pctx->opts->alloc_size = intval;
829                 break;
830         case Opt_lock_timeout:
831                 /* 0 is "wait forever" (i.e. infinite timeout) */
832                 if (intval < 0 || intval > INT_MAX / 1000) {
833                         pr_err("lock_timeout out of range\n");
834                         return -EINVAL;
835                 }
836                 pctx->opts->lock_timeout = msecs_to_jiffies(intval * 1000);
837                 break;
838         case Opt_pool_ns:
839                 kfree(pctx->spec->pool_ns);
840                 pctx->spec->pool_ns = match_strdup(argstr);
841                 if (!pctx->spec->pool_ns)
842                         return -ENOMEM;
843                 break;
844         case Opt_read_only:
845                 pctx->opts->read_only = true;
846                 break;
847         case Opt_read_write:
848                 pctx->opts->read_only = false;
849                 break;
850         case Opt_lock_on_read:
851                 pctx->opts->lock_on_read = true;
852                 break;
853         case Opt_exclusive:
854                 pctx->opts->exclusive = true;
855                 break;
856         case Opt_notrim:
857                 pctx->opts->trim = false;
858                 break;
859         default:
860                 /* libceph prints "bad option" msg */
861                 return -EINVAL;
862         }
863
864         return 0;
865 }
866
867 static char* obj_op_name(enum obj_operation_type op_type)
868 {
869         switch (op_type) {
870         case OBJ_OP_READ:
871                 return "read";
872         case OBJ_OP_WRITE:
873                 return "write";
874         case OBJ_OP_DISCARD:
875                 return "discard";
876         case OBJ_OP_ZEROOUT:
877                 return "zeroout";
878         default:
879                 return "???";
880         }
881 }
882
883 /*
884  * Destroy ceph client
885  *
886  * Caller must hold rbd_client_list_lock.
887  */
888 static void rbd_client_release(struct kref *kref)
889 {
890         struct rbd_client *rbdc = container_of(kref, struct rbd_client, kref);
891
892         dout("%s: rbdc %p\n", __func__, rbdc);
893         spin_lock(&rbd_client_list_lock);
894         list_del(&rbdc->node);
895         spin_unlock(&rbd_client_list_lock);
896
897         ceph_destroy_client(rbdc->client);
898         kfree(rbdc);
899 }
900
901 /*
902  * Drop reference to ceph client node. If it's not referenced anymore, release
903  * it.
904  */
905 static void rbd_put_client(struct rbd_client *rbdc)
906 {
907         if (rbdc)
908                 kref_put(&rbdc->kref, rbd_client_release);
909 }
910
911 static int wait_for_latest_osdmap(struct ceph_client *client)
912 {
913         u64 newest_epoch;
914         int ret;
915
916         ret = ceph_monc_get_version(&client->monc, "osdmap", &newest_epoch);
917         if (ret)
918                 return ret;
919
920         if (client->osdc.osdmap->epoch >= newest_epoch)
921                 return 0;
922
923         ceph_osdc_maybe_request_map(&client->osdc);
924         return ceph_monc_wait_osdmap(&client->monc, newest_epoch,
925                                      client->options->mount_timeout);
926 }
927
928 /*
929  * Get a ceph client with specific addr and configuration, if one does
930  * not exist create it.  Either way, ceph_opts is consumed by this
931  * function.
932  */
933 static struct rbd_client *rbd_get_client(struct ceph_options *ceph_opts)
934 {
935         struct rbd_client *rbdc;
936         int ret;
937
938         mutex_lock_nested(&client_mutex, SINGLE_DEPTH_NESTING);
939         rbdc = rbd_client_find(ceph_opts);
940         if (rbdc) {
941                 ceph_destroy_options(ceph_opts);
942
943                 /*
944                  * Using an existing client.  Make sure ->pg_pools is up to
945                  * date before we look up the pool id in do_rbd_add().
946                  */
947                 ret = wait_for_latest_osdmap(rbdc->client);
948                 if (ret) {
949                         rbd_warn(NULL, "failed to get latest osdmap: %d", ret);
950                         rbd_put_client(rbdc);
951                         rbdc = ERR_PTR(ret);
952                 }
953         } else {
954                 rbdc = rbd_client_create(ceph_opts);
955         }
956         mutex_unlock(&client_mutex);
957
958         return rbdc;
959 }
960
961 static bool rbd_image_format_valid(u32 image_format)
962 {
963         return image_format == 1 || image_format == 2;
964 }
965
966 static bool rbd_dev_ondisk_valid(struct rbd_image_header_ondisk *ondisk)
967 {
968         size_t size;
969         u32 snap_count;
970
971         /* The header has to start with the magic rbd header text */
972         if (memcmp(&ondisk->text, RBD_HEADER_TEXT, sizeof (RBD_HEADER_TEXT)))
973                 return false;
974
975         /* The bio layer requires at least sector-sized I/O */
976
977         if (ondisk->options.order < SECTOR_SHIFT)
978                 return false;
979
980         /* If we use u64 in a few spots we may be able to loosen this */
981
982         if (ondisk->options.order > 8 * sizeof (int) - 1)
983                 return false;
984
985         /*
986          * The size of a snapshot header has to fit in a size_t, and
987          * that limits the number of snapshots.
988          */
989         snap_count = le32_to_cpu(ondisk->snap_count);
990         size = SIZE_MAX - sizeof (struct ceph_snap_context);
991         if (snap_count > size / sizeof (__le64))
992                 return false;
993
994         /*
995          * Not only that, but the size of the entire the snapshot
996          * header must also be representable in a size_t.
997          */
998         size -= snap_count * sizeof (__le64);
999         if ((u64) size < le64_to_cpu(ondisk->snap_names_len))
1000                 return false;
1001
1002         return true;
1003 }
1004
1005 /*
1006  * returns the size of an object in the image
1007  */
1008 static u32 rbd_obj_bytes(struct rbd_image_header *header)
1009 {
1010         return 1U << header->obj_order;
1011 }
1012
1013 static void rbd_init_layout(struct rbd_device *rbd_dev)
1014 {
1015         if (rbd_dev->header.stripe_unit == 0 ||
1016             rbd_dev->header.stripe_count == 0) {
1017                 rbd_dev->header.stripe_unit = rbd_obj_bytes(&rbd_dev->header);
1018                 rbd_dev->header.stripe_count = 1;
1019         }
1020
1021         rbd_dev->layout.stripe_unit = rbd_dev->header.stripe_unit;
1022         rbd_dev->layout.stripe_count = rbd_dev->header.stripe_count;
1023         rbd_dev->layout.object_size = rbd_obj_bytes(&rbd_dev->header);
1024         rbd_dev->layout.pool_id = rbd_dev->header.data_pool_id == CEPH_NOPOOL ?
1025                           rbd_dev->spec->pool_id : rbd_dev->header.data_pool_id;
1026         RCU_INIT_POINTER(rbd_dev->layout.pool_ns, NULL);
1027 }
1028
1029 /*
1030  * Fill an rbd image header with information from the given format 1
1031  * on-disk header.
1032  */
1033 static int rbd_header_from_disk(struct rbd_device *rbd_dev,
1034                                  struct rbd_image_header_ondisk *ondisk)
1035 {
1036         struct rbd_image_header *header = &rbd_dev->header;
1037         bool first_time = header->object_prefix == NULL;
1038         struct ceph_snap_context *snapc;
1039         char *object_prefix = NULL;
1040         char *snap_names = NULL;
1041         u64 *snap_sizes = NULL;
1042         u32 snap_count;
1043         int ret = -ENOMEM;
1044         u32 i;
1045
1046         /* Allocate this now to avoid having to handle failure below */
1047
1048         if (first_time) {
1049                 object_prefix = kstrndup(ondisk->object_prefix,
1050                                          sizeof(ondisk->object_prefix),
1051                                          GFP_KERNEL);
1052                 if (!object_prefix)
1053                         return -ENOMEM;
1054         }
1055
1056         /* Allocate the snapshot context and fill it in */
1057
1058         snap_count = le32_to_cpu(ondisk->snap_count);
1059         snapc = ceph_create_snap_context(snap_count, GFP_KERNEL);
1060         if (!snapc)
1061                 goto out_err;
1062         snapc->seq = le64_to_cpu(ondisk->snap_seq);
1063         if (snap_count) {
1064                 struct rbd_image_snap_ondisk *snaps;
1065                 u64 snap_names_len = le64_to_cpu(ondisk->snap_names_len);
1066
1067                 /* We'll keep a copy of the snapshot names... */
1068
1069                 if (snap_names_len > (u64)SIZE_MAX)
1070                         goto out_2big;
1071                 snap_names = kmalloc(snap_names_len, GFP_KERNEL);
1072                 if (!snap_names)
1073                         goto out_err;
1074
1075                 /* ...as well as the array of their sizes. */
1076                 snap_sizes = kmalloc_array(snap_count,
1077                                            sizeof(*header->snap_sizes),
1078                                            GFP_KERNEL);
1079                 if (!snap_sizes)
1080                         goto out_err;
1081
1082                 /*
1083                  * Copy the names, and fill in each snapshot's id
1084                  * and size.
1085                  *
1086                  * Note that rbd_dev_v1_header_info() guarantees the
1087                  * ondisk buffer we're working with has
1088                  * snap_names_len bytes beyond the end of the
1089                  * snapshot id array, this memcpy() is safe.
1090                  */
1091                 memcpy(snap_names, &ondisk->snaps[snap_count], snap_names_len);
1092                 snaps = ondisk->snaps;
1093                 for (i = 0; i < snap_count; i++) {
1094                         snapc->snaps[i] = le64_to_cpu(snaps[i].id);
1095                         snap_sizes[i] = le64_to_cpu(snaps[i].image_size);
1096                 }
1097         }
1098
1099         /* We won't fail any more, fill in the header */
1100
1101         if (first_time) {
1102                 header->object_prefix = object_prefix;
1103                 header->obj_order = ondisk->options.order;
1104                 rbd_init_layout(rbd_dev);
1105         } else {
1106                 ceph_put_snap_context(header->snapc);
1107                 kfree(header->snap_names);
1108                 kfree(header->snap_sizes);
1109         }
1110
1111         /* The remaining fields always get updated (when we refresh) */
1112
1113         header->image_size = le64_to_cpu(ondisk->image_size);
1114         header->snapc = snapc;
1115         header->snap_names = snap_names;
1116         header->snap_sizes = snap_sizes;
1117
1118         return 0;
1119 out_2big:
1120         ret = -EIO;
1121 out_err:
1122         kfree(snap_sizes);
1123         kfree(snap_names);
1124         ceph_put_snap_context(snapc);
1125         kfree(object_prefix);
1126
1127         return ret;
1128 }
1129
1130 static const char *_rbd_dev_v1_snap_name(struct rbd_device *rbd_dev, u32 which)
1131 {
1132         const char *snap_name;
1133
1134         rbd_assert(which < rbd_dev->header.snapc->num_snaps);
1135
1136         /* Skip over names until we find the one we are looking for */
1137
1138         snap_name = rbd_dev->header.snap_names;
1139         while (which--)
1140                 snap_name += strlen(snap_name) + 1;
1141
1142         return kstrdup(snap_name, GFP_KERNEL);
1143 }
1144
1145 /*
1146  * Snapshot id comparison function for use with qsort()/bsearch().
1147  * Note that result is for snapshots in *descending* order.
1148  */
1149 static int snapid_compare_reverse(const void *s1, const void *s2)
1150 {
1151         u64 snap_id1 = *(u64 *)s1;
1152         u64 snap_id2 = *(u64 *)s2;
1153
1154         if (snap_id1 < snap_id2)
1155                 return 1;
1156         return snap_id1 == snap_id2 ? 0 : -1;
1157 }
1158
1159 /*
1160  * Search a snapshot context to see if the given snapshot id is
1161  * present.
1162  *
1163  * Returns the position of the snapshot id in the array if it's found,
1164  * or BAD_SNAP_INDEX otherwise.
1165  *
1166  * Note: The snapshot array is in kept sorted (by the osd) in
1167  * reverse order, highest snapshot id first.
1168  */
1169 static u32 rbd_dev_snap_index(struct rbd_device *rbd_dev, u64 snap_id)
1170 {
1171         struct ceph_snap_context *snapc = rbd_dev->header.snapc;
1172         u64 *found;
1173
1174         found = bsearch(&snap_id, &snapc->snaps, snapc->num_snaps,
1175                                 sizeof (snap_id), snapid_compare_reverse);
1176
1177         return found ? (u32)(found - &snapc->snaps[0]) : BAD_SNAP_INDEX;
1178 }
1179
1180 static const char *rbd_dev_v1_snap_name(struct rbd_device *rbd_dev,
1181                                         u64 snap_id)
1182 {
1183         u32 which;
1184         const char *snap_name;
1185
1186         which = rbd_dev_snap_index(rbd_dev, snap_id);
1187         if (which == BAD_SNAP_INDEX)
1188                 return ERR_PTR(-ENOENT);
1189
1190         snap_name = _rbd_dev_v1_snap_name(rbd_dev, which);
1191         return snap_name ? snap_name : ERR_PTR(-ENOMEM);
1192 }
1193
1194 static const char *rbd_snap_name(struct rbd_device *rbd_dev, u64 snap_id)
1195 {
1196         if (snap_id == CEPH_NOSNAP)
1197                 return RBD_SNAP_HEAD_NAME;
1198
1199         rbd_assert(rbd_image_format_valid(rbd_dev->image_format));
1200         if (rbd_dev->image_format == 1)
1201                 return rbd_dev_v1_snap_name(rbd_dev, snap_id);
1202
1203         return rbd_dev_v2_snap_name(rbd_dev, snap_id);
1204 }
1205
1206 static int rbd_snap_size(struct rbd_device *rbd_dev, u64 snap_id,
1207                                 u64 *snap_size)
1208 {
1209         rbd_assert(rbd_image_format_valid(rbd_dev->image_format));
1210         if (snap_id == CEPH_NOSNAP) {
1211                 *snap_size = rbd_dev->header.image_size;
1212         } else if (rbd_dev->image_format == 1) {
1213                 u32 which;
1214
1215                 which = rbd_dev_snap_index(rbd_dev, snap_id);
1216                 if (which == BAD_SNAP_INDEX)
1217                         return -ENOENT;
1218
1219                 *snap_size = rbd_dev->header.snap_sizes[which];
1220         } else {
1221                 u64 size = 0;
1222                 int ret;
1223
1224                 ret = _rbd_dev_v2_snap_size(rbd_dev, snap_id, NULL, &size);
1225                 if (ret)
1226                         return ret;
1227
1228                 *snap_size = size;
1229         }
1230         return 0;
1231 }
1232
1233 static int rbd_snap_features(struct rbd_device *rbd_dev, u64 snap_id,
1234                         u64 *snap_features)
1235 {
1236         rbd_assert(rbd_image_format_valid(rbd_dev->image_format));
1237         if (snap_id == CEPH_NOSNAP) {
1238                 *snap_features = rbd_dev->header.features;
1239         } else if (rbd_dev->image_format == 1) {
1240                 *snap_features = 0;     /* No features for format 1 */
1241         } else {
1242                 u64 features = 0;
1243                 int ret;
1244
1245                 ret = _rbd_dev_v2_snap_features(rbd_dev, snap_id, &features);
1246                 if (ret)
1247                         return ret;
1248
1249                 *snap_features = features;
1250         }
1251         return 0;
1252 }
1253
1254 static int rbd_dev_mapping_set(struct rbd_device *rbd_dev)
1255 {
1256         u64 snap_id = rbd_dev->spec->snap_id;
1257         u64 size = 0;
1258         u64 features = 0;
1259         int ret;
1260
1261         ret = rbd_snap_size(rbd_dev, snap_id, &size);
1262         if (ret)
1263                 return ret;
1264         ret = rbd_snap_features(rbd_dev, snap_id, &features);
1265         if (ret)
1266                 return ret;
1267
1268         rbd_dev->mapping.size = size;
1269         rbd_dev->mapping.features = features;
1270
1271         return 0;
1272 }
1273
1274 static void rbd_dev_mapping_clear(struct rbd_device *rbd_dev)
1275 {
1276         rbd_dev->mapping.size = 0;
1277         rbd_dev->mapping.features = 0;
1278 }
1279
1280 static void zero_bvec(struct bio_vec *bv)
1281 {
1282         void *buf;
1283         unsigned long flags;
1284
1285         buf = bvec_kmap_irq(bv, &flags);
1286         memset(buf, 0, bv->bv_len);
1287         flush_dcache_page(bv->bv_page);
1288         bvec_kunmap_irq(buf, &flags);
1289 }
1290
1291 static void zero_bios(struct ceph_bio_iter *bio_pos, u32 off, u32 bytes)
1292 {
1293         struct ceph_bio_iter it = *bio_pos;
1294
1295         ceph_bio_iter_advance(&it, off);
1296         ceph_bio_iter_advance_step(&it, bytes, ({
1297                 zero_bvec(&bv);
1298         }));
1299 }
1300
1301 static void zero_bvecs(struct ceph_bvec_iter *bvec_pos, u32 off, u32 bytes)
1302 {
1303         struct ceph_bvec_iter it = *bvec_pos;
1304
1305         ceph_bvec_iter_advance(&it, off);
1306         ceph_bvec_iter_advance_step(&it, bytes, ({
1307                 zero_bvec(&bv);
1308         }));
1309 }
1310
1311 /*
1312  * Zero a range in @obj_req data buffer defined by a bio (list) or
1313  * (private) bio_vec array.
1314  *
1315  * @off is relative to the start of the data buffer.
1316  */
1317 static void rbd_obj_zero_range(struct rbd_obj_request *obj_req, u32 off,
1318                                u32 bytes)
1319 {
1320         switch (obj_req->img_request->data_type) {
1321         case OBJ_REQUEST_BIO:
1322                 zero_bios(&obj_req->bio_pos, off, bytes);
1323                 break;
1324         case OBJ_REQUEST_BVECS:
1325         case OBJ_REQUEST_OWN_BVECS:
1326                 zero_bvecs(&obj_req->bvec_pos, off, bytes);
1327                 break;
1328         default:
1329                 rbd_assert(0);
1330         }
1331 }
1332
1333 static void rbd_obj_request_destroy(struct kref *kref);
1334 static void rbd_obj_request_put(struct rbd_obj_request *obj_request)
1335 {
1336         rbd_assert(obj_request != NULL);
1337         dout("%s: obj %p (was %d)\n", __func__, obj_request,
1338                 kref_read(&obj_request->kref));
1339         kref_put(&obj_request->kref, rbd_obj_request_destroy);
1340 }
1341
1342 static void rbd_img_request_get(struct rbd_img_request *img_request)
1343 {
1344         dout("%s: img %p (was %d)\n", __func__, img_request,
1345              kref_read(&img_request->kref));
1346         kref_get(&img_request->kref);
1347 }
1348
1349 static void rbd_img_request_destroy(struct kref *kref);
1350 static void rbd_img_request_put(struct rbd_img_request *img_request)
1351 {
1352         rbd_assert(img_request != NULL);
1353         dout("%s: img %p (was %d)\n", __func__, img_request,
1354                 kref_read(&img_request->kref));
1355         kref_put(&img_request->kref, rbd_img_request_destroy);
1356 }
1357
1358 static inline void rbd_img_obj_request_add(struct rbd_img_request *img_request,
1359                                         struct rbd_obj_request *obj_request)
1360 {
1361         rbd_assert(obj_request->img_request == NULL);
1362
1363         /* Image request now owns object's original reference */
1364         obj_request->img_request = img_request;
1365         img_request->pending_count++;
1366         dout("%s: img %p obj %p\n", __func__, img_request, obj_request);
1367 }
1368
1369 static inline void rbd_img_obj_request_del(struct rbd_img_request *img_request,
1370                                         struct rbd_obj_request *obj_request)
1371 {
1372         dout("%s: img %p obj %p\n", __func__, img_request, obj_request);
1373         list_del(&obj_request->ex.oe_item);
1374         rbd_assert(obj_request->img_request == img_request);
1375         rbd_obj_request_put(obj_request);
1376 }
1377
1378 static void rbd_obj_request_submit(struct rbd_obj_request *obj_request)
1379 {
1380         struct ceph_osd_request *osd_req = obj_request->osd_req;
1381
1382         dout("%s %p object_no %016llx %llu~%llu osd_req %p\n", __func__,
1383              obj_request, obj_request->ex.oe_objno, obj_request->ex.oe_off,
1384              obj_request->ex.oe_len, osd_req);
1385         ceph_osdc_start_request(osd_req->r_osdc, osd_req, false);
1386 }
1387
1388 /*
1389  * The default/initial value for all image request flags is 0.  Each
1390  * is conditionally set to 1 at image request initialization time
1391  * and currently never change thereafter.
1392  */
1393 static void img_request_layered_set(struct rbd_img_request *img_request)
1394 {
1395         set_bit(IMG_REQ_LAYERED, &img_request->flags);
1396         smp_mb();
1397 }
1398
1399 static void img_request_layered_clear(struct rbd_img_request *img_request)
1400 {
1401         clear_bit(IMG_REQ_LAYERED, &img_request->flags);
1402         smp_mb();
1403 }
1404
1405 static bool img_request_layered_test(struct rbd_img_request *img_request)
1406 {
1407         smp_mb();
1408         return test_bit(IMG_REQ_LAYERED, &img_request->flags) != 0;
1409 }
1410
1411 static bool rbd_obj_is_entire(struct rbd_obj_request *obj_req)
1412 {
1413         struct rbd_device *rbd_dev = obj_req->img_request->rbd_dev;
1414
1415         return !obj_req->ex.oe_off &&
1416                obj_req->ex.oe_len == rbd_dev->layout.object_size;
1417 }
1418
1419 static bool rbd_obj_is_tail(struct rbd_obj_request *obj_req)
1420 {
1421         struct rbd_device *rbd_dev = obj_req->img_request->rbd_dev;
1422
1423         return obj_req->ex.oe_off + obj_req->ex.oe_len ==
1424                                         rbd_dev->layout.object_size;
1425 }
1426
1427 /*
1428  * Must be called after rbd_obj_calc_img_extents().
1429  */
1430 static bool rbd_obj_copyup_enabled(struct rbd_obj_request *obj_req)
1431 {
1432         if (!obj_req->num_img_extents ||
1433             rbd_obj_is_entire(obj_req))
1434                 return false;
1435
1436         return true;
1437 }
1438
1439 static u64 rbd_obj_img_extents_bytes(struct rbd_obj_request *obj_req)
1440 {
1441         return ceph_file_extents_bytes(obj_req->img_extents,
1442                                        obj_req->num_img_extents);
1443 }
1444
1445 static bool rbd_img_is_write(struct rbd_img_request *img_req)
1446 {
1447         switch (img_req->op_type) {
1448         case OBJ_OP_READ:
1449                 return false;
1450         case OBJ_OP_WRITE:
1451         case OBJ_OP_DISCARD:
1452         case OBJ_OP_ZEROOUT:
1453                 return true;
1454         default:
1455                 BUG();
1456         }
1457 }
1458
1459 static void rbd_obj_handle_request(struct rbd_obj_request *obj_req);
1460
1461 static void rbd_osd_req_callback(struct ceph_osd_request *osd_req)
1462 {
1463         struct rbd_obj_request *obj_req = osd_req->r_priv;
1464
1465         dout("%s osd_req %p result %d for obj_req %p\n", __func__, osd_req,
1466              osd_req->r_result, obj_req);
1467         rbd_assert(osd_req == obj_req->osd_req);
1468
1469         obj_req->result = osd_req->r_result < 0 ? osd_req->r_result : 0;
1470         if (!obj_req->result && !rbd_img_is_write(obj_req->img_request))
1471                 obj_req->xferred = osd_req->r_result;
1472         else
1473                 /*
1474                  * Writes aren't allowed to return a data payload.  In some
1475                  * guarded write cases (e.g. stat + zero on an empty object)
1476                  * a stat response makes it through, but we don't care.
1477                  */
1478                 obj_req->xferred = 0;
1479
1480         rbd_obj_handle_request(obj_req);
1481 }
1482
1483 static void rbd_osd_req_format_read(struct rbd_obj_request *obj_request)
1484 {
1485         struct ceph_osd_request *osd_req = obj_request->osd_req;
1486
1487         osd_req->r_flags = CEPH_OSD_FLAG_READ;
1488         osd_req->r_snapid = obj_request->img_request->snap_id;
1489 }
1490
1491 static void rbd_osd_req_format_write(struct rbd_obj_request *obj_request)
1492 {
1493         struct ceph_osd_request *osd_req = obj_request->osd_req;
1494
1495         osd_req->r_flags = CEPH_OSD_FLAG_WRITE;
1496         ktime_get_real_ts64(&osd_req->r_mtime);
1497         osd_req->r_data_offset = obj_request->ex.oe_off;
1498 }
1499
1500 static struct ceph_osd_request *
1501 __rbd_osd_req_create(struct rbd_obj_request *obj_req,
1502                      struct ceph_snap_context *snapc, unsigned int num_ops)
1503 {
1504         struct rbd_device *rbd_dev = obj_req->img_request->rbd_dev;
1505         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
1506         struct ceph_osd_request *req;
1507         const char *name_format = rbd_dev->image_format == 1 ?
1508                                       RBD_V1_DATA_FORMAT : RBD_V2_DATA_FORMAT;
1509
1510         req = ceph_osdc_alloc_request(osdc, snapc, num_ops, false, GFP_NOIO);
1511         if (!req)
1512                 return NULL;
1513
1514         req->r_callback = rbd_osd_req_callback;
1515         req->r_priv = obj_req;
1516
1517         /*
1518          * Data objects may be stored in a separate pool, but always in
1519          * the same namespace in that pool as the header in its pool.
1520          */
1521         ceph_oloc_copy(&req->r_base_oloc, &rbd_dev->header_oloc);
1522         req->r_base_oloc.pool = rbd_dev->layout.pool_id;
1523
1524         if (ceph_oid_aprintf(&req->r_base_oid, GFP_NOIO, name_format,
1525                         rbd_dev->header.object_prefix, obj_req->ex.oe_objno))
1526                 goto err_req;
1527
1528         return req;
1529
1530 err_req:
1531         ceph_osdc_put_request(req);
1532         return NULL;
1533 }
1534
1535 static struct ceph_osd_request *
1536 rbd_osd_req_create(struct rbd_obj_request *obj_req, unsigned int num_ops)
1537 {
1538         return __rbd_osd_req_create(obj_req, obj_req->img_request->snapc,
1539                                     num_ops);
1540 }
1541
1542 static void rbd_osd_req_destroy(struct ceph_osd_request *osd_req)
1543 {
1544         ceph_osdc_put_request(osd_req);
1545 }
1546
1547 static struct rbd_obj_request *rbd_obj_request_create(void)
1548 {
1549         struct rbd_obj_request *obj_request;
1550
1551         obj_request = kmem_cache_zalloc(rbd_obj_request_cache, GFP_NOIO);
1552         if (!obj_request)
1553                 return NULL;
1554
1555         ceph_object_extent_init(&obj_request->ex);
1556         kref_init(&obj_request->kref);
1557
1558         dout("%s %p\n", __func__, obj_request);
1559         return obj_request;
1560 }
1561
1562 static void rbd_obj_request_destroy(struct kref *kref)
1563 {
1564         struct rbd_obj_request *obj_request;
1565         u32 i;
1566
1567         obj_request = container_of(kref, struct rbd_obj_request, kref);
1568
1569         dout("%s: obj %p\n", __func__, obj_request);
1570
1571         if (obj_request->osd_req)
1572                 rbd_osd_req_destroy(obj_request->osd_req);
1573
1574         switch (obj_request->img_request->data_type) {
1575         case OBJ_REQUEST_NODATA:
1576         case OBJ_REQUEST_BIO:
1577         case OBJ_REQUEST_BVECS:
1578                 break;          /* Nothing to do */
1579         case OBJ_REQUEST_OWN_BVECS:
1580                 kfree(obj_request->bvec_pos.bvecs);
1581                 break;
1582         default:
1583                 rbd_assert(0);
1584         }
1585
1586         kfree(obj_request->img_extents);
1587         if (obj_request->copyup_bvecs) {
1588                 for (i = 0; i < obj_request->copyup_bvec_count; i++) {
1589                         if (obj_request->copyup_bvecs[i].bv_page)
1590                                 __free_page(obj_request->copyup_bvecs[i].bv_page);
1591                 }
1592                 kfree(obj_request->copyup_bvecs);
1593         }
1594
1595         kmem_cache_free(rbd_obj_request_cache, obj_request);
1596 }
1597
1598 /* It's OK to call this for a device with no parent */
1599
1600 static void rbd_spec_put(struct rbd_spec *spec);
1601 static void rbd_dev_unparent(struct rbd_device *rbd_dev)
1602 {
1603         rbd_dev_remove_parent(rbd_dev);
1604         rbd_spec_put(rbd_dev->parent_spec);
1605         rbd_dev->parent_spec = NULL;
1606         rbd_dev->parent_overlap = 0;
1607 }
1608
1609 /*
1610  * Parent image reference counting is used to determine when an
1611  * image's parent fields can be safely torn down--after there are no
1612  * more in-flight requests to the parent image.  When the last
1613  * reference is dropped, cleaning them up is safe.
1614  */
1615 static void rbd_dev_parent_put(struct rbd_device *rbd_dev)
1616 {
1617         int counter;
1618
1619         if (!rbd_dev->parent_spec)
1620                 return;
1621
1622         counter = atomic_dec_return_safe(&rbd_dev->parent_ref);
1623         if (counter > 0)
1624                 return;
1625
1626         /* Last reference; clean up parent data structures */
1627
1628         if (!counter)
1629                 rbd_dev_unparent(rbd_dev);
1630         else
1631                 rbd_warn(rbd_dev, "parent reference underflow");
1632 }
1633
1634 /*
1635  * If an image has a non-zero parent overlap, get a reference to its
1636  * parent.
1637  *
1638  * Returns true if the rbd device has a parent with a non-zero
1639  * overlap and a reference for it was successfully taken, or
1640  * false otherwise.
1641  */
1642 static bool rbd_dev_parent_get(struct rbd_device *rbd_dev)
1643 {
1644         int counter = 0;
1645
1646         if (!rbd_dev->parent_spec)
1647                 return false;
1648
1649         down_read(&rbd_dev->header_rwsem);
1650         if (rbd_dev->parent_overlap)
1651                 counter = atomic_inc_return_safe(&rbd_dev->parent_ref);
1652         up_read(&rbd_dev->header_rwsem);
1653
1654         if (counter < 0)
1655                 rbd_warn(rbd_dev, "parent reference overflow");
1656
1657         return counter > 0;
1658 }
1659
1660 /*
1661  * Caller is responsible for filling in the list of object requests
1662  * that comprises the image request, and the Linux request pointer
1663  * (if there is one).
1664  */
1665 static struct rbd_img_request *rbd_img_request_create(
1666                                         struct rbd_device *rbd_dev,
1667                                         enum obj_operation_type op_type,
1668                                         struct ceph_snap_context *snapc)
1669 {
1670         struct rbd_img_request *img_request;
1671
1672         img_request = kmem_cache_zalloc(rbd_img_request_cache, GFP_NOIO);
1673         if (!img_request)
1674                 return NULL;
1675
1676         img_request->rbd_dev = rbd_dev;
1677         img_request->op_type = op_type;
1678         if (!rbd_img_is_write(img_request))
1679                 img_request->snap_id = rbd_dev->spec->snap_id;
1680         else
1681                 img_request->snapc = snapc;
1682
1683         if (rbd_dev_parent_get(rbd_dev))
1684                 img_request_layered_set(img_request);
1685
1686         spin_lock_init(&img_request->completion_lock);
1687         INIT_LIST_HEAD(&img_request->object_extents);
1688         kref_init(&img_request->kref);
1689
1690         dout("%s: rbd_dev %p %s -> img %p\n", __func__, rbd_dev,
1691              obj_op_name(op_type), img_request);
1692         return img_request;
1693 }
1694
1695 static void rbd_img_request_destroy(struct kref *kref)
1696 {
1697         struct rbd_img_request *img_request;
1698         struct rbd_obj_request *obj_request;
1699         struct rbd_obj_request *next_obj_request;
1700
1701         img_request = container_of(kref, struct rbd_img_request, kref);
1702
1703         dout("%s: img %p\n", __func__, img_request);
1704
1705         for_each_obj_request_safe(img_request, obj_request, next_obj_request)
1706                 rbd_img_obj_request_del(img_request, obj_request);
1707
1708         if (img_request_layered_test(img_request)) {
1709                 img_request_layered_clear(img_request);
1710                 rbd_dev_parent_put(img_request->rbd_dev);
1711         }
1712
1713         if (rbd_img_is_write(img_request))
1714                 ceph_put_snap_context(img_request->snapc);
1715
1716         kmem_cache_free(rbd_img_request_cache, img_request);
1717 }
1718
1719 static void prune_extents(struct ceph_file_extent *img_extents,
1720                           u32 *num_img_extents, u64 overlap)
1721 {
1722         u32 cnt = *num_img_extents;
1723
1724         /* drop extents completely beyond the overlap */
1725         while (cnt && img_extents[cnt - 1].fe_off >= overlap)
1726                 cnt--;
1727
1728         if (cnt) {
1729                 struct ceph_file_extent *ex = &img_extents[cnt - 1];
1730
1731                 /* trim final overlapping extent */
1732                 if (ex->fe_off + ex->fe_len > overlap)
1733                         ex->fe_len = overlap - ex->fe_off;
1734         }
1735
1736         *num_img_extents = cnt;
1737 }
1738
1739 /*
1740  * Determine the byte range(s) covered by either just the object extent
1741  * or the entire object in the parent image.
1742  */
1743 static int rbd_obj_calc_img_extents(struct rbd_obj_request *obj_req,
1744                                     bool entire)
1745 {
1746         struct rbd_device *rbd_dev = obj_req->img_request->rbd_dev;
1747         int ret;
1748
1749         if (!rbd_dev->parent_overlap)
1750                 return 0;
1751
1752         ret = ceph_extent_to_file(&rbd_dev->layout, obj_req->ex.oe_objno,
1753                                   entire ? 0 : obj_req->ex.oe_off,
1754                                   entire ? rbd_dev->layout.object_size :
1755                                                         obj_req->ex.oe_len,
1756                                   &obj_req->img_extents,
1757                                   &obj_req->num_img_extents);
1758         if (ret)
1759                 return ret;
1760
1761         prune_extents(obj_req->img_extents, &obj_req->num_img_extents,
1762                       rbd_dev->parent_overlap);
1763         return 0;
1764 }
1765
1766 static void rbd_osd_req_setup_data(struct rbd_obj_request *obj_req, u32 which)
1767 {
1768         switch (obj_req->img_request->data_type) {
1769         case OBJ_REQUEST_BIO:
1770                 osd_req_op_extent_osd_data_bio(obj_req->osd_req, which,
1771                                                &obj_req->bio_pos,
1772                                                obj_req->ex.oe_len);
1773                 break;
1774         case OBJ_REQUEST_BVECS:
1775         case OBJ_REQUEST_OWN_BVECS:
1776                 rbd_assert(obj_req->bvec_pos.iter.bi_size ==
1777                                                         obj_req->ex.oe_len);
1778                 rbd_assert(obj_req->bvec_idx == obj_req->bvec_count);
1779                 osd_req_op_extent_osd_data_bvec_pos(obj_req->osd_req, which,
1780                                                     &obj_req->bvec_pos);
1781                 break;
1782         default:
1783                 rbd_assert(0);
1784         }
1785 }
1786
1787 static int rbd_obj_setup_read(struct rbd_obj_request *obj_req)
1788 {
1789         obj_req->osd_req = __rbd_osd_req_create(obj_req, NULL, 1);
1790         if (!obj_req->osd_req)
1791                 return -ENOMEM;
1792
1793         osd_req_op_extent_init(obj_req->osd_req, 0, CEPH_OSD_OP_READ,
1794                                obj_req->ex.oe_off, obj_req->ex.oe_len, 0, 0);
1795         rbd_osd_req_setup_data(obj_req, 0);
1796
1797         rbd_osd_req_format_read(obj_req);
1798         return 0;
1799 }
1800
1801 static int __rbd_obj_setup_stat(struct rbd_obj_request *obj_req,
1802                                 unsigned int which)
1803 {
1804         struct page **pages;
1805
1806         /*
1807          * The response data for a STAT call consists of:
1808          *     le64 length;
1809          *     struct {
1810          *         le32 tv_sec;
1811          *         le32 tv_nsec;
1812          *     } mtime;
1813          */
1814         pages = ceph_alloc_page_vector(1, GFP_NOIO);
1815         if (IS_ERR(pages))
1816                 return PTR_ERR(pages);
1817
1818         osd_req_op_init(obj_req->osd_req, which, CEPH_OSD_OP_STAT, 0);
1819         osd_req_op_raw_data_in_pages(obj_req->osd_req, which, pages,
1820                                      8 + sizeof(struct ceph_timespec),
1821                                      0, false, true);
1822         return 0;
1823 }
1824
1825 static int count_write_ops(struct rbd_obj_request *obj_req)
1826 {
1827         return 2; /* setallochint + write/writefull */
1828 }
1829
1830 static void __rbd_obj_setup_write(struct rbd_obj_request *obj_req,
1831                                   unsigned int which)
1832 {
1833         struct rbd_device *rbd_dev = obj_req->img_request->rbd_dev;
1834         u16 opcode;
1835
1836         osd_req_op_alloc_hint_init(obj_req->osd_req, which++,
1837                                    rbd_dev->layout.object_size,
1838                                    rbd_dev->layout.object_size);
1839
1840         if (rbd_obj_is_entire(obj_req))
1841                 opcode = CEPH_OSD_OP_WRITEFULL;
1842         else
1843                 opcode = CEPH_OSD_OP_WRITE;
1844
1845         osd_req_op_extent_init(obj_req->osd_req, which, opcode,
1846                                obj_req->ex.oe_off, obj_req->ex.oe_len, 0, 0);
1847         rbd_osd_req_setup_data(obj_req, which++);
1848
1849         rbd_assert(which == obj_req->osd_req->r_num_ops);
1850         rbd_osd_req_format_write(obj_req);
1851 }
1852
1853 static int rbd_obj_setup_write(struct rbd_obj_request *obj_req)
1854 {
1855         unsigned int num_osd_ops, which = 0;
1856         bool need_guard;
1857         int ret;
1858
1859         /* reverse map the entire object onto the parent */
1860         ret = rbd_obj_calc_img_extents(obj_req, true);
1861         if (ret)
1862                 return ret;
1863
1864         need_guard = rbd_obj_copyup_enabled(obj_req);
1865         num_osd_ops = need_guard + count_write_ops(obj_req);
1866
1867         obj_req->osd_req = rbd_osd_req_create(obj_req, num_osd_ops);
1868         if (!obj_req->osd_req)
1869                 return -ENOMEM;
1870
1871         if (need_guard) {
1872                 ret = __rbd_obj_setup_stat(obj_req, which++);
1873                 if (ret)
1874                         return ret;
1875
1876                 obj_req->write_state = RBD_OBJ_WRITE_GUARD;
1877         } else {
1878                 obj_req->write_state = RBD_OBJ_WRITE_FLAT;
1879         }
1880
1881         __rbd_obj_setup_write(obj_req, which);
1882         return 0;
1883 }
1884
1885 static u16 truncate_or_zero_opcode(struct rbd_obj_request *obj_req)
1886 {
1887         return rbd_obj_is_tail(obj_req) ? CEPH_OSD_OP_TRUNCATE :
1888                                           CEPH_OSD_OP_ZERO;
1889 }
1890
1891 static int rbd_obj_setup_discard(struct rbd_obj_request *obj_req)
1892 {
1893         struct rbd_device *rbd_dev = obj_req->img_request->rbd_dev;
1894         u64 off = obj_req->ex.oe_off;
1895         u64 next_off = obj_req->ex.oe_off + obj_req->ex.oe_len;
1896         int ret;
1897
1898         /*
1899          * Align the range to alloc_size boundary and punt on discards
1900          * that are too small to free up any space.
1901          *
1902          * alloc_size == object_size && is_tail() is a special case for
1903          * filestore with filestore_punch_hole = false, needed to allow
1904          * truncate (in addition to delete).
1905          */
1906         if (rbd_dev->opts->alloc_size != rbd_dev->layout.object_size ||
1907             !rbd_obj_is_tail(obj_req)) {
1908                 off = round_up(off, rbd_dev->opts->alloc_size);
1909                 next_off = round_down(next_off, rbd_dev->opts->alloc_size);
1910                 if (off >= next_off)
1911                         return 1;
1912         }
1913
1914         /* reverse map the entire object onto the parent */
1915         ret = rbd_obj_calc_img_extents(obj_req, true);
1916         if (ret)
1917                 return ret;
1918
1919         obj_req->osd_req = rbd_osd_req_create(obj_req, 1);
1920         if (!obj_req->osd_req)
1921                 return -ENOMEM;
1922
1923         if (rbd_obj_is_entire(obj_req) && !obj_req->num_img_extents) {
1924                 osd_req_op_init(obj_req->osd_req, 0, CEPH_OSD_OP_DELETE, 0);
1925         } else {
1926                 dout("%s %p %llu~%llu -> %llu~%llu\n", __func__,
1927                      obj_req, obj_req->ex.oe_off, obj_req->ex.oe_len,
1928                      off, next_off - off);
1929                 osd_req_op_extent_init(obj_req->osd_req, 0,
1930                                        truncate_or_zero_opcode(obj_req),
1931                                        off, next_off - off, 0, 0);
1932         }
1933
1934         obj_req->write_state = RBD_OBJ_WRITE_FLAT;
1935         rbd_osd_req_format_write(obj_req);
1936         return 0;
1937 }
1938
1939 static int count_zeroout_ops(struct rbd_obj_request *obj_req)
1940 {
1941         int num_osd_ops;
1942
1943         if (rbd_obj_is_entire(obj_req) && obj_req->num_img_extents)
1944                 num_osd_ops = 2; /* create + truncate */
1945         else
1946                 num_osd_ops = 1; /* delete/truncate/zero */
1947
1948         return num_osd_ops;
1949 }
1950
1951 static void __rbd_obj_setup_zeroout(struct rbd_obj_request *obj_req,
1952                                     unsigned int which)
1953 {
1954         u16 opcode;
1955
1956         if (rbd_obj_is_entire(obj_req)) {
1957                 if (obj_req->num_img_extents) {
1958                         osd_req_op_init(obj_req->osd_req, which++,
1959                                         CEPH_OSD_OP_CREATE, 0);
1960                         opcode = CEPH_OSD_OP_TRUNCATE;
1961                 } else {
1962                         osd_req_op_init(obj_req->osd_req, which++,
1963                                         CEPH_OSD_OP_DELETE, 0);
1964                         opcode = 0;
1965                 }
1966         } else {
1967                 opcode = truncate_or_zero_opcode(obj_req);
1968         }
1969
1970         if (opcode)
1971                 osd_req_op_extent_init(obj_req->osd_req, which++, opcode,
1972                                        obj_req->ex.oe_off, obj_req->ex.oe_len,
1973                                        0, 0);
1974
1975         rbd_assert(which == obj_req->osd_req->r_num_ops);
1976         rbd_osd_req_format_write(obj_req);
1977 }
1978
1979 static int rbd_obj_setup_zeroout(struct rbd_obj_request *obj_req)
1980 {
1981         unsigned int num_osd_ops, which = 0;
1982         bool need_guard;
1983         int ret;
1984
1985         /* reverse map the entire object onto the parent */
1986         ret = rbd_obj_calc_img_extents(obj_req, true);
1987         if (ret)
1988                 return ret;
1989
1990         need_guard = rbd_obj_copyup_enabled(obj_req);
1991         num_osd_ops = need_guard + count_zeroout_ops(obj_req);
1992
1993         obj_req->osd_req = rbd_osd_req_create(obj_req, num_osd_ops);
1994         if (!obj_req->osd_req)
1995                 return -ENOMEM;
1996
1997         if (need_guard) {
1998                 ret = __rbd_obj_setup_stat(obj_req, which++);
1999                 if (ret)
2000                         return ret;
2001
2002                 obj_req->write_state = RBD_OBJ_WRITE_GUARD;
2003         } else {
2004                 obj_req->write_state = RBD_OBJ_WRITE_FLAT;
2005         }
2006
2007         __rbd_obj_setup_zeroout(obj_req, which);
2008         return 0;
2009 }
2010
2011 /*
2012  * For each object request in @img_req, allocate an OSD request, add
2013  * individual OSD ops and prepare them for submission.  The number of
2014  * OSD ops depends on op_type and the overlap point (if any).
2015  */
2016 static int __rbd_img_fill_request(struct rbd_img_request *img_req)
2017 {
2018         struct rbd_obj_request *obj_req, *next_obj_req;
2019         int ret;
2020
2021         for_each_obj_request_safe(img_req, obj_req, next_obj_req) {
2022                 switch (img_req->op_type) {
2023                 case OBJ_OP_READ:
2024                         ret = rbd_obj_setup_read(obj_req);
2025                         break;
2026                 case OBJ_OP_WRITE:
2027                         ret = rbd_obj_setup_write(obj_req);
2028                         break;
2029                 case OBJ_OP_DISCARD:
2030                         ret = rbd_obj_setup_discard(obj_req);
2031                         break;
2032                 case OBJ_OP_ZEROOUT:
2033                         ret = rbd_obj_setup_zeroout(obj_req);
2034                         break;
2035                 default:
2036                         rbd_assert(0);
2037                 }
2038                 if (ret < 0)
2039                         return ret;
2040                 if (ret > 0) {
2041                         img_req->xferred += obj_req->ex.oe_len;
2042                         img_req->pending_count--;
2043                         rbd_img_obj_request_del(img_req, obj_req);
2044                         continue;
2045                 }
2046
2047                 ret = ceph_osdc_alloc_messages(obj_req->osd_req, GFP_NOIO);
2048                 if (ret)
2049                         return ret;
2050         }
2051
2052         return 0;
2053 }
2054
2055 union rbd_img_fill_iter {
2056         struct ceph_bio_iter    bio_iter;
2057         struct ceph_bvec_iter   bvec_iter;
2058 };
2059
2060 struct rbd_img_fill_ctx {
2061         enum obj_request_type   pos_type;
2062         union rbd_img_fill_iter *pos;
2063         union rbd_img_fill_iter iter;
2064         ceph_object_extent_fn_t set_pos_fn;
2065         ceph_object_extent_fn_t count_fn;
2066         ceph_object_extent_fn_t copy_fn;
2067 };
2068
2069 static struct ceph_object_extent *alloc_object_extent(void *arg)
2070 {
2071         struct rbd_img_request *img_req = arg;
2072         struct rbd_obj_request *obj_req;
2073
2074         obj_req = rbd_obj_request_create();
2075         if (!obj_req)
2076                 return NULL;
2077
2078         rbd_img_obj_request_add(img_req, obj_req);
2079         return &obj_req->ex;
2080 }
2081
2082 /*
2083  * While su != os && sc == 1 is technically not fancy (it's the same
2084  * layout as su == os && sc == 1), we can't use the nocopy path for it
2085  * because ->set_pos_fn() should be called only once per object.
2086  * ceph_file_to_extents() invokes action_fn once per stripe unit, so
2087  * treat su != os && sc == 1 as fancy.
2088  */
2089 static bool rbd_layout_is_fancy(struct ceph_file_layout *l)
2090 {
2091         return l->stripe_unit != l->object_size;
2092 }
2093
2094 static int rbd_img_fill_request_nocopy(struct rbd_img_request *img_req,
2095                                        struct ceph_file_extent *img_extents,
2096                                        u32 num_img_extents,
2097                                        struct rbd_img_fill_ctx *fctx)
2098 {
2099         u32 i;
2100         int ret;
2101
2102         img_req->data_type = fctx->pos_type;
2103
2104         /*
2105          * Create object requests and set each object request's starting
2106          * position in the provided bio (list) or bio_vec array.
2107          */
2108         fctx->iter = *fctx->pos;
2109         for (i = 0; i < num_img_extents; i++) {
2110                 ret = ceph_file_to_extents(&img_req->rbd_dev->layout,
2111                                            img_extents[i].fe_off,
2112                                            img_extents[i].fe_len,
2113                                            &img_req->object_extents,
2114                                            alloc_object_extent, img_req,
2115                                            fctx->set_pos_fn, &fctx->iter);
2116                 if (ret)
2117                         return ret;
2118         }
2119
2120         return __rbd_img_fill_request(img_req);
2121 }
2122
2123 /*
2124  * Map a list of image extents to a list of object extents, create the
2125  * corresponding object requests (normally each to a different object,
2126  * but not always) and add them to @img_req.  For each object request,
2127  * set up its data descriptor to point to the corresponding chunk(s) of
2128  * @fctx->pos data buffer.
2129  *
2130  * Because ceph_file_to_extents() will merge adjacent object extents
2131  * together, each object request's data descriptor may point to multiple
2132  * different chunks of @fctx->pos data buffer.
2133  *
2134  * @fctx->pos data buffer is assumed to be large enough.
2135  */
2136 static int rbd_img_fill_request(struct rbd_img_request *img_req,
2137                                 struct ceph_file_extent *img_extents,
2138                                 u32 num_img_extents,
2139                                 struct rbd_img_fill_ctx *fctx)
2140 {
2141         struct rbd_device *rbd_dev = img_req->rbd_dev;
2142         struct rbd_obj_request *obj_req;
2143         u32 i;
2144         int ret;
2145
2146         if (fctx->pos_type == OBJ_REQUEST_NODATA ||
2147             !rbd_layout_is_fancy(&rbd_dev->layout))
2148                 return rbd_img_fill_request_nocopy(img_req, img_extents,
2149                                                    num_img_extents, fctx);
2150
2151         img_req->data_type = OBJ_REQUEST_OWN_BVECS;
2152
2153         /*
2154          * Create object requests and determine ->bvec_count for each object
2155          * request.  Note that ->bvec_count sum over all object requests may
2156          * be greater than the number of bio_vecs in the provided bio (list)
2157          * or bio_vec array because when mapped, those bio_vecs can straddle
2158          * stripe unit boundaries.
2159          */
2160         fctx->iter = *fctx->pos;
2161         for (i = 0; i < num_img_extents; i++) {
2162                 ret = ceph_file_to_extents(&rbd_dev->layout,
2163                                            img_extents[i].fe_off,
2164                                            img_extents[i].fe_len,
2165                                            &img_req->object_extents,
2166                                            alloc_object_extent, img_req,
2167                                            fctx->count_fn, &fctx->iter);
2168                 if (ret)
2169                         return ret;
2170         }
2171
2172         for_each_obj_request(img_req, obj_req) {
2173                 obj_req->bvec_pos.bvecs = kmalloc_array(obj_req->bvec_count,
2174                                               sizeof(*obj_req->bvec_pos.bvecs),
2175                                               GFP_NOIO);
2176                 if (!obj_req->bvec_pos.bvecs)
2177                         return -ENOMEM;
2178         }
2179
2180         /*
2181          * Fill in each object request's private bio_vec array, splitting and
2182          * rearranging the provided bio_vecs in stripe unit chunks as needed.
2183          */
2184         fctx->iter = *fctx->pos;
2185         for (i = 0; i < num_img_extents; i++) {
2186                 ret = ceph_iterate_extents(&rbd_dev->layout,
2187                                            img_extents[i].fe_off,
2188                                            img_extents[i].fe_len,
2189                                            &img_req->object_extents,
2190                                            fctx->copy_fn, &fctx->iter);
2191                 if (ret)
2192                         return ret;
2193         }
2194
2195         return __rbd_img_fill_request(img_req);
2196 }
2197
2198 static int rbd_img_fill_nodata(struct rbd_img_request *img_req,
2199                                u64 off, u64 len)
2200 {
2201         struct ceph_file_extent ex = { off, len };
2202         union rbd_img_fill_iter dummy;
2203         struct rbd_img_fill_ctx fctx = {
2204                 .pos_type = OBJ_REQUEST_NODATA,
2205                 .pos = &dummy,
2206         };
2207
2208         return rbd_img_fill_request(img_req, &ex, 1, &fctx);
2209 }
2210
2211 static void set_bio_pos(struct ceph_object_extent *ex, u32 bytes, void *arg)
2212 {
2213         struct rbd_obj_request *obj_req =
2214             container_of(ex, struct rbd_obj_request, ex);
2215         struct ceph_bio_iter *it = arg;
2216
2217         dout("%s objno %llu bytes %u\n", __func__, ex->oe_objno, bytes);
2218         obj_req->bio_pos = *it;
2219         ceph_bio_iter_advance(it, bytes);
2220 }
2221
2222 static void count_bio_bvecs(struct ceph_object_extent *ex, u32 bytes, void *arg)
2223 {
2224         struct rbd_obj_request *obj_req =
2225             container_of(ex, struct rbd_obj_request, ex);
2226         struct ceph_bio_iter *it = arg;
2227
2228         dout("%s objno %llu bytes %u\n", __func__, ex->oe_objno, bytes);
2229         ceph_bio_iter_advance_step(it, bytes, ({
2230                 obj_req->bvec_count++;
2231         }));
2232
2233 }
2234
2235 static void copy_bio_bvecs(struct ceph_object_extent *ex, u32 bytes, void *arg)
2236 {
2237         struct rbd_obj_request *obj_req =
2238             container_of(ex, struct rbd_obj_request, ex);
2239         struct ceph_bio_iter *it = arg;
2240
2241         dout("%s objno %llu bytes %u\n", __func__, ex->oe_objno, bytes);
2242         ceph_bio_iter_advance_step(it, bytes, ({
2243                 obj_req->bvec_pos.bvecs[obj_req->bvec_idx++] = bv;
2244                 obj_req->bvec_pos.iter.bi_size += bv.bv_len;
2245         }));
2246 }
2247
2248 static int __rbd_img_fill_from_bio(struct rbd_img_request *img_req,
2249                                    struct ceph_file_extent *img_extents,
2250                                    u32 num_img_extents,
2251                                    struct ceph_bio_iter *bio_pos)
2252 {
2253         struct rbd_img_fill_ctx fctx = {
2254                 .pos_type = OBJ_REQUEST_BIO,
2255                 .pos = (union rbd_img_fill_iter *)bio_pos,
2256                 .set_pos_fn = set_bio_pos,
2257                 .count_fn = count_bio_bvecs,
2258                 .copy_fn = copy_bio_bvecs,
2259         };
2260
2261         return rbd_img_fill_request(img_req, img_extents, num_img_extents,
2262                                     &fctx);
2263 }
2264
2265 static int rbd_img_fill_from_bio(struct rbd_img_request *img_req,
2266                                  u64 off, u64 len, struct bio *bio)
2267 {
2268         struct ceph_file_extent ex = { off, len };
2269         struct ceph_bio_iter it = { .bio = bio, .iter = bio->bi_iter };
2270
2271         return __rbd_img_fill_from_bio(img_req, &ex, 1, &it);
2272 }
2273
2274 static void set_bvec_pos(struct ceph_object_extent *ex, u32 bytes, void *arg)
2275 {
2276         struct rbd_obj_request *obj_req =
2277             container_of(ex, struct rbd_obj_request, ex);
2278         struct ceph_bvec_iter *it = arg;
2279
2280         obj_req->bvec_pos = *it;
2281         ceph_bvec_iter_shorten(&obj_req->bvec_pos, bytes);
2282         ceph_bvec_iter_advance(it, bytes);
2283 }
2284
2285 static void count_bvecs(struct ceph_object_extent *ex, u32 bytes, void *arg)
2286 {
2287         struct rbd_obj_request *obj_req =
2288             container_of(ex, struct rbd_obj_request, ex);
2289         struct ceph_bvec_iter *it = arg;
2290
2291         ceph_bvec_iter_advance_step(it, bytes, ({
2292                 obj_req->bvec_count++;
2293         }));
2294 }
2295
2296 static void copy_bvecs(struct ceph_object_extent *ex, u32 bytes, void *arg)
2297 {
2298         struct rbd_obj_request *obj_req =
2299             container_of(ex, struct rbd_obj_request, ex);
2300         struct ceph_bvec_iter *it = arg;
2301
2302         ceph_bvec_iter_advance_step(it, bytes, ({
2303                 obj_req->bvec_pos.bvecs[obj_req->bvec_idx++] = bv;
2304                 obj_req->bvec_pos.iter.bi_size += bv.bv_len;
2305         }));
2306 }
2307
2308 static int __rbd_img_fill_from_bvecs(struct rbd_img_request *img_req,
2309                                      struct ceph_file_extent *img_extents,
2310                                      u32 num_img_extents,
2311                                      struct ceph_bvec_iter *bvec_pos)
2312 {
2313         struct rbd_img_fill_ctx fctx = {
2314                 .pos_type = OBJ_REQUEST_BVECS,
2315                 .pos = (union rbd_img_fill_iter *)bvec_pos,
2316                 .set_pos_fn = set_bvec_pos,
2317                 .count_fn = count_bvecs,
2318                 .copy_fn = copy_bvecs,
2319         };
2320
2321         return rbd_img_fill_request(img_req, img_extents, num_img_extents,
2322                                     &fctx);
2323 }
2324
2325 static int rbd_img_fill_from_bvecs(struct rbd_img_request *img_req,
2326                                    struct ceph_file_extent *img_extents,
2327                                    u32 num_img_extents,
2328                                    struct bio_vec *bvecs)
2329 {
2330         struct ceph_bvec_iter it = {
2331                 .bvecs = bvecs,
2332                 .iter = { .bi_size = ceph_file_extents_bytes(img_extents,
2333                                                              num_img_extents) },
2334         };
2335
2336         return __rbd_img_fill_from_bvecs(img_req, img_extents, num_img_extents,
2337                                          &it);
2338 }
2339
2340 static void rbd_img_request_submit(struct rbd_img_request *img_request)
2341 {
2342         struct rbd_obj_request *obj_request;
2343
2344         dout("%s: img %p\n", __func__, img_request);
2345
2346         rbd_img_request_get(img_request);
2347         for_each_obj_request(img_request, obj_request)
2348                 rbd_obj_request_submit(obj_request);
2349
2350         rbd_img_request_put(img_request);
2351 }
2352
2353 static int rbd_obj_read_from_parent(struct rbd_obj_request *obj_req)
2354 {
2355         struct rbd_img_request *img_req = obj_req->img_request;
2356         struct rbd_img_request *child_img_req;
2357         int ret;
2358
2359         child_img_req = rbd_img_request_create(img_req->rbd_dev->parent,
2360                                                OBJ_OP_READ, NULL);
2361         if (!child_img_req)
2362                 return -ENOMEM;
2363
2364         __set_bit(IMG_REQ_CHILD, &child_img_req->flags);
2365         child_img_req->obj_request = obj_req;
2366
2367         if (!rbd_img_is_write(img_req)) {
2368                 switch (img_req->data_type) {
2369                 case OBJ_REQUEST_BIO:
2370                         ret = __rbd_img_fill_from_bio(child_img_req,
2371                                                       obj_req->img_extents,
2372                                                       obj_req->num_img_extents,
2373                                                       &obj_req->bio_pos);
2374                         break;
2375                 case OBJ_REQUEST_BVECS:
2376                 case OBJ_REQUEST_OWN_BVECS:
2377                         ret = __rbd_img_fill_from_bvecs(child_img_req,
2378                                                       obj_req->img_extents,
2379                                                       obj_req->num_img_extents,
2380                                                       &obj_req->bvec_pos);
2381                         break;
2382                 default:
2383                         rbd_assert(0);
2384                 }
2385         } else {
2386                 ret = rbd_img_fill_from_bvecs(child_img_req,
2387                                               obj_req->img_extents,
2388                                               obj_req->num_img_extents,
2389                                               obj_req->copyup_bvecs);
2390         }
2391         if (ret) {
2392                 rbd_img_request_put(child_img_req);
2393                 return ret;
2394         }
2395
2396         rbd_img_request_submit(child_img_req);
2397         return 0;
2398 }
2399
2400 static bool rbd_obj_handle_read(struct rbd_obj_request *obj_req)
2401 {
2402         struct rbd_device *rbd_dev = obj_req->img_request->rbd_dev;
2403         int ret;
2404
2405         if (obj_req->result == -ENOENT &&
2406             rbd_dev->parent_overlap && !obj_req->tried_parent) {
2407                 /* reverse map this object extent onto the parent */
2408                 ret = rbd_obj_calc_img_extents(obj_req, false);
2409                 if (ret) {
2410                         obj_req->result = ret;
2411                         return true;
2412                 }
2413
2414                 if (obj_req->num_img_extents) {
2415                         obj_req->tried_parent = true;
2416                         ret = rbd_obj_read_from_parent(obj_req);
2417                         if (ret) {
2418                                 obj_req->result = ret;
2419                                 return true;
2420                         }
2421                         return false;
2422                 }
2423         }
2424
2425         /*
2426          * -ENOENT means a hole in the image -- zero-fill the entire
2427          * length of the request.  A short read also implies zero-fill
2428          * to the end of the request.  In both cases we update xferred
2429          * count to indicate the whole request was satisfied.
2430          */
2431         if (obj_req->result == -ENOENT ||
2432             (!obj_req->result && obj_req->xferred < obj_req->ex.oe_len)) {
2433                 rbd_assert(!obj_req->xferred || !obj_req->result);
2434                 rbd_obj_zero_range(obj_req, obj_req->xferred,
2435                                    obj_req->ex.oe_len - obj_req->xferred);
2436                 obj_req->result = 0;
2437                 obj_req->xferred = obj_req->ex.oe_len;
2438         }
2439
2440         return true;
2441 }
2442
2443 /*
2444  * copyup_bvecs pages are never highmem pages
2445  */
2446 static bool is_zero_bvecs(struct bio_vec *bvecs, u32 bytes)
2447 {
2448         struct ceph_bvec_iter it = {
2449                 .bvecs = bvecs,
2450                 .iter = { .bi_size = bytes },
2451         };
2452
2453         ceph_bvec_iter_advance_step(&it, bytes, ({
2454                 if (memchr_inv(page_address(bv.bv_page) + bv.bv_offset, 0,
2455                                bv.bv_len))
2456                         return false;
2457         }));
2458         return true;
2459 }
2460
2461 static int rbd_obj_issue_copyup(struct rbd_obj_request *obj_req, u32 bytes)
2462 {
2463         struct rbd_img_request *img_req = obj_req->img_request;
2464         unsigned int num_osd_ops = 1;
2465         int ret;
2466
2467         dout("%s obj_req %p bytes %u\n", __func__, obj_req, bytes);
2468         rbd_assert(obj_req->osd_req->r_ops[0].op == CEPH_OSD_OP_STAT);
2469         rbd_osd_req_destroy(obj_req->osd_req);
2470
2471         switch (img_req->op_type) {
2472         case OBJ_OP_WRITE:
2473                 num_osd_ops += count_write_ops(obj_req);
2474                 break;
2475         case OBJ_OP_ZEROOUT:
2476                 num_osd_ops += count_zeroout_ops(obj_req);
2477                 break;
2478         default:
2479                 rbd_assert(0);
2480         }
2481
2482         obj_req->osd_req = rbd_osd_req_create(obj_req, num_osd_ops);
2483         if (!obj_req->osd_req)
2484                 return -ENOMEM;
2485
2486         ret = osd_req_op_cls_init(obj_req->osd_req, 0, "rbd", "copyup");
2487         if (ret)
2488                 return ret;
2489
2490         /*
2491          * Only send non-zero copyup data to save some I/O and network
2492          * bandwidth -- zero copyup data is equivalent to the object not
2493          * existing.
2494          */
2495         if (is_zero_bvecs(obj_req->copyup_bvecs, bytes)) {
2496                 dout("%s obj_req %p detected zeroes\n", __func__, obj_req);
2497                 bytes = 0;
2498         }
2499         osd_req_op_cls_request_data_bvecs(obj_req->osd_req, 0,
2500                                           obj_req->copyup_bvecs,
2501                                           obj_req->copyup_bvec_count,
2502                                           bytes);
2503
2504         switch (img_req->op_type) {
2505         case OBJ_OP_WRITE:
2506                 __rbd_obj_setup_write(obj_req, 1);
2507                 break;
2508         case OBJ_OP_ZEROOUT:
2509                 rbd_assert(!rbd_obj_is_entire(obj_req));
2510                 __rbd_obj_setup_zeroout(obj_req, 1);
2511                 break;
2512         default:
2513                 rbd_assert(0);
2514         }
2515
2516         ret = ceph_osdc_alloc_messages(obj_req->osd_req, GFP_NOIO);
2517         if (ret)
2518                 return ret;
2519
2520         rbd_obj_request_submit(obj_req);
2521         return 0;
2522 }
2523
2524 static int setup_copyup_bvecs(struct rbd_obj_request *obj_req, u64 obj_overlap)
2525 {
2526         u32 i;
2527
2528         rbd_assert(!obj_req->copyup_bvecs);
2529         obj_req->copyup_bvec_count = calc_pages_for(0, obj_overlap);
2530         obj_req->copyup_bvecs = kcalloc(obj_req->copyup_bvec_count,
2531                                         sizeof(*obj_req->copyup_bvecs),
2532                                         GFP_NOIO);
2533         if (!obj_req->copyup_bvecs)
2534                 return -ENOMEM;
2535
2536         for (i = 0; i < obj_req->copyup_bvec_count; i++) {
2537                 unsigned int len = min(obj_overlap, (u64)PAGE_SIZE);
2538
2539                 obj_req->copyup_bvecs[i].bv_page = alloc_page(GFP_NOIO);
2540                 if (!obj_req->copyup_bvecs[i].bv_page)
2541                         return -ENOMEM;
2542
2543                 obj_req->copyup_bvecs[i].bv_offset = 0;
2544                 obj_req->copyup_bvecs[i].bv_len = len;
2545                 obj_overlap -= len;
2546         }
2547
2548         rbd_assert(!obj_overlap);
2549         return 0;
2550 }
2551
2552 static int rbd_obj_handle_write_guard(struct rbd_obj_request *obj_req)
2553 {
2554         struct rbd_device *rbd_dev = obj_req->img_request->rbd_dev;
2555         int ret;
2556
2557         rbd_assert(obj_req->num_img_extents);
2558         prune_extents(obj_req->img_extents, &obj_req->num_img_extents,
2559                       rbd_dev->parent_overlap);
2560         if (!obj_req->num_img_extents) {
2561                 /*
2562                  * The overlap has become 0 (most likely because the
2563                  * image has been flattened).  Use rbd_obj_issue_copyup()
2564                  * to re-submit the original write request -- the copyup
2565                  * operation itself will be a no-op, since someone must
2566                  * have populated the child object while we weren't
2567                  * looking.  Move to WRITE_FLAT state as we'll be done
2568                  * with the operation once the null copyup completes.
2569                  */
2570                 obj_req->write_state = RBD_OBJ_WRITE_FLAT;
2571                 return rbd_obj_issue_copyup(obj_req, 0);
2572         }
2573
2574         ret = setup_copyup_bvecs(obj_req, rbd_obj_img_extents_bytes(obj_req));
2575         if (ret)
2576                 return ret;
2577
2578         obj_req->write_state = RBD_OBJ_WRITE_COPYUP;
2579         return rbd_obj_read_from_parent(obj_req);
2580 }
2581
2582 static bool rbd_obj_handle_write(struct rbd_obj_request *obj_req)
2583 {
2584         int ret;
2585
2586 again:
2587         switch (obj_req->write_state) {
2588         case RBD_OBJ_WRITE_GUARD:
2589                 rbd_assert(!obj_req->xferred);
2590                 if (obj_req->result == -ENOENT) {
2591                         /*
2592                          * The target object doesn't exist.  Read the data for
2593                          * the entire target object up to the overlap point (if
2594                          * any) from the parent, so we can use it for a copyup.
2595                          */
2596                         ret = rbd_obj_handle_write_guard(obj_req);
2597                         if (ret) {
2598                                 obj_req->result = ret;
2599                                 return true;
2600                         }
2601                         return false;
2602                 }
2603                 /* fall through */
2604         case RBD_OBJ_WRITE_FLAT:
2605                 if (!obj_req->result)
2606                         /*
2607                          * There is no such thing as a successful short
2608                          * write -- indicate the whole request was satisfied.
2609                          */
2610                         obj_req->xferred = obj_req->ex.oe_len;
2611                 return true;
2612         case RBD_OBJ_WRITE_COPYUP:
2613                 obj_req->write_state = RBD_OBJ_WRITE_GUARD;
2614                 if (obj_req->result)
2615                         goto again;
2616
2617                 rbd_assert(obj_req->xferred);
2618                 ret = rbd_obj_issue_copyup(obj_req, obj_req->xferred);
2619                 if (ret) {
2620                         obj_req->result = ret;
2621                         obj_req->xferred = 0;
2622                         return true;
2623                 }
2624                 return false;
2625         default:
2626                 BUG();
2627         }
2628 }
2629
2630 /*
2631  * Returns true if @obj_req is completed, or false otherwise.
2632  */
2633 static bool __rbd_obj_handle_request(struct rbd_obj_request *obj_req)
2634 {
2635         switch (obj_req->img_request->op_type) {
2636         case OBJ_OP_READ:
2637                 return rbd_obj_handle_read(obj_req);
2638         case OBJ_OP_WRITE:
2639                 return rbd_obj_handle_write(obj_req);
2640         case OBJ_OP_DISCARD:
2641         case OBJ_OP_ZEROOUT:
2642                 if (rbd_obj_handle_write(obj_req)) {
2643                         /*
2644                          * Hide -ENOENT from delete/truncate/zero -- discarding
2645                          * a non-existent object is not a problem.
2646                          */
2647                         if (obj_req->result == -ENOENT) {
2648                                 obj_req->result = 0;
2649                                 obj_req->xferred = obj_req->ex.oe_len;
2650                         }
2651                         return true;
2652                 }
2653                 return false;
2654         default:
2655                 BUG();
2656         }
2657 }
2658
2659 static void rbd_obj_end_request(struct rbd_obj_request *obj_req)
2660 {
2661         struct rbd_img_request *img_req = obj_req->img_request;
2662
2663         rbd_assert((!obj_req->result &&
2664                     obj_req->xferred == obj_req->ex.oe_len) ||
2665                    (obj_req->result < 0 && !obj_req->xferred));
2666         if (!obj_req->result) {
2667                 img_req->xferred += obj_req->xferred;
2668                 return;
2669         }
2670
2671         rbd_warn(img_req->rbd_dev,
2672                  "%s at objno %llu %llu~%llu result %d xferred %llu",
2673                  obj_op_name(img_req->op_type), obj_req->ex.oe_objno,
2674                  obj_req->ex.oe_off, obj_req->ex.oe_len, obj_req->result,
2675                  obj_req->xferred);
2676         if (!img_req->result) {
2677                 img_req->result = obj_req->result;
2678                 img_req->xferred = 0;
2679         }
2680 }
2681
2682 static void rbd_img_end_child_request(struct rbd_img_request *img_req)
2683 {
2684         struct rbd_obj_request *obj_req = img_req->obj_request;
2685
2686         rbd_assert(test_bit(IMG_REQ_CHILD, &img_req->flags));
2687         rbd_assert((!img_req->result &&
2688                     img_req->xferred == rbd_obj_img_extents_bytes(obj_req)) ||
2689                    (img_req->result < 0 && !img_req->xferred));
2690
2691         obj_req->result = img_req->result;
2692         obj_req->xferred = img_req->xferred;
2693         rbd_img_request_put(img_req);
2694 }
2695
2696 static void rbd_img_end_request(struct rbd_img_request *img_req)
2697 {
2698         rbd_assert(!test_bit(IMG_REQ_CHILD, &img_req->flags));
2699         rbd_assert((!img_req->result &&
2700                     img_req->xferred == blk_rq_bytes(img_req->rq)) ||
2701                    (img_req->result < 0 && !img_req->xferred));
2702
2703         blk_mq_end_request(img_req->rq,
2704                            errno_to_blk_status(img_req->result));
2705         rbd_img_request_put(img_req);
2706 }
2707
2708 static void rbd_obj_handle_request(struct rbd_obj_request *obj_req)
2709 {
2710         struct rbd_img_request *img_req;
2711
2712 again:
2713         if (!__rbd_obj_handle_request(obj_req))
2714                 return;
2715
2716         img_req = obj_req->img_request;
2717         spin_lock(&img_req->completion_lock);
2718         rbd_obj_end_request(obj_req);
2719         rbd_assert(img_req->pending_count);
2720         if (--img_req->pending_count) {
2721                 spin_unlock(&img_req->completion_lock);
2722                 return;
2723         }
2724
2725         spin_unlock(&img_req->completion_lock);
2726         if (test_bit(IMG_REQ_CHILD, &img_req->flags)) {
2727                 obj_req = img_req->obj_request;
2728                 rbd_img_end_child_request(img_req);
2729                 goto again;
2730         }
2731         rbd_img_end_request(img_req);
2732 }
2733
2734 static const struct rbd_client_id rbd_empty_cid;
2735
2736 static bool rbd_cid_equal(const struct rbd_client_id *lhs,
2737                           const struct rbd_client_id *rhs)
2738 {
2739         return lhs->gid == rhs->gid && lhs->handle == rhs->handle;
2740 }
2741
2742 static struct rbd_client_id rbd_get_cid(struct rbd_device *rbd_dev)
2743 {
2744         struct rbd_client_id cid;
2745
2746         mutex_lock(&rbd_dev->watch_mutex);
2747         cid.gid = ceph_client_gid(rbd_dev->rbd_client->client);
2748         cid.handle = rbd_dev->watch_cookie;
2749         mutex_unlock(&rbd_dev->watch_mutex);
2750         return cid;
2751 }
2752
2753 /*
2754  * lock_rwsem must be held for write
2755  */
2756 static void rbd_set_owner_cid(struct rbd_device *rbd_dev,
2757                               const struct rbd_client_id *cid)
2758 {
2759         dout("%s rbd_dev %p %llu-%llu -> %llu-%llu\n", __func__, rbd_dev,
2760              rbd_dev->owner_cid.gid, rbd_dev->owner_cid.handle,
2761              cid->gid, cid->handle);
2762         rbd_dev->owner_cid = *cid; /* struct */
2763 }
2764
2765 static void format_lock_cookie(struct rbd_device *rbd_dev, char *buf)
2766 {
2767         mutex_lock(&rbd_dev->watch_mutex);
2768         sprintf(buf, "%s %llu", RBD_LOCK_COOKIE_PREFIX, rbd_dev->watch_cookie);
2769         mutex_unlock(&rbd_dev->watch_mutex);
2770 }
2771
2772 static void __rbd_lock(struct rbd_device *rbd_dev, const char *cookie)
2773 {
2774         struct rbd_client_id cid = rbd_get_cid(rbd_dev);
2775
2776         strcpy(rbd_dev->lock_cookie, cookie);
2777         rbd_set_owner_cid(rbd_dev, &cid);
2778         queue_work(rbd_dev->task_wq, &rbd_dev->acquired_lock_work);
2779 }
2780
2781 /*
2782  * lock_rwsem must be held for write
2783  */
2784 static int rbd_lock(struct rbd_device *rbd_dev)
2785 {
2786         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
2787         char cookie[32];
2788         int ret;
2789
2790         WARN_ON(__rbd_is_lock_owner(rbd_dev) ||
2791                 rbd_dev->lock_cookie[0] != '\0');
2792
2793         format_lock_cookie(rbd_dev, cookie);
2794         ret = ceph_cls_lock(osdc, &rbd_dev->header_oid, &rbd_dev->header_oloc,
2795                             RBD_LOCK_NAME, CEPH_CLS_LOCK_EXCLUSIVE, cookie,
2796                             RBD_LOCK_TAG, "", 0);
2797         if (ret)
2798                 return ret;
2799
2800         rbd_dev->lock_state = RBD_LOCK_STATE_LOCKED;
2801         __rbd_lock(rbd_dev, cookie);
2802         return 0;
2803 }
2804
2805 /*
2806  * lock_rwsem must be held for write
2807  */
2808 static void rbd_unlock(struct rbd_device *rbd_dev)
2809 {
2810         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
2811         int ret;
2812
2813         WARN_ON(!__rbd_is_lock_owner(rbd_dev) ||
2814                 rbd_dev->lock_cookie[0] == '\0');
2815
2816         ret = ceph_cls_unlock(osdc, &rbd_dev->header_oid, &rbd_dev->header_oloc,
2817                               RBD_LOCK_NAME, rbd_dev->lock_cookie);
2818         if (ret && ret != -ENOENT)
2819                 rbd_warn(rbd_dev, "failed to unlock: %d", ret);
2820
2821         /* treat errors as the image is unlocked */
2822         rbd_dev->lock_state = RBD_LOCK_STATE_UNLOCKED;
2823         rbd_dev->lock_cookie[0] = '\0';
2824         rbd_set_owner_cid(rbd_dev, &rbd_empty_cid);
2825         queue_work(rbd_dev->task_wq, &rbd_dev->released_lock_work);
2826 }
2827
2828 static int __rbd_notify_op_lock(struct rbd_device *rbd_dev,
2829                                 enum rbd_notify_op notify_op,
2830                                 struct page ***preply_pages,
2831                                 size_t *preply_len)
2832 {
2833         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
2834         struct rbd_client_id cid = rbd_get_cid(rbd_dev);
2835         char buf[4 + 8 + 8 + CEPH_ENCODING_START_BLK_LEN];
2836         int buf_size = sizeof(buf);
2837         void *p = buf;
2838
2839         dout("%s rbd_dev %p notify_op %d\n", __func__, rbd_dev, notify_op);
2840
2841         /* encode *LockPayload NotifyMessage (op + ClientId) */
2842         ceph_start_encoding(&p, 2, 1, buf_size - CEPH_ENCODING_START_BLK_LEN);
2843         ceph_encode_32(&p, notify_op);
2844         ceph_encode_64(&p, cid.gid);
2845         ceph_encode_64(&p, cid.handle);
2846
2847         return ceph_osdc_notify(osdc, &rbd_dev->header_oid,
2848                                 &rbd_dev->header_oloc, buf, buf_size,
2849                                 RBD_NOTIFY_TIMEOUT, preply_pages, preply_len);
2850 }
2851
2852 static void rbd_notify_op_lock(struct rbd_device *rbd_dev,
2853                                enum rbd_notify_op notify_op)
2854 {
2855         struct page **reply_pages;
2856         size_t reply_len;
2857
2858         __rbd_notify_op_lock(rbd_dev, notify_op, &reply_pages, &reply_len);
2859         ceph_release_page_vector(reply_pages, calc_pages_for(0, reply_len));
2860 }
2861
2862 static void rbd_notify_acquired_lock(struct work_struct *work)
2863 {
2864         struct rbd_device *rbd_dev = container_of(work, struct rbd_device,
2865                                                   acquired_lock_work);
2866
2867         rbd_notify_op_lock(rbd_dev, RBD_NOTIFY_OP_ACQUIRED_LOCK);
2868 }
2869
2870 static void rbd_notify_released_lock(struct work_struct *work)
2871 {
2872         struct rbd_device *rbd_dev = container_of(work, struct rbd_device,
2873                                                   released_lock_work);
2874
2875         rbd_notify_op_lock(rbd_dev, RBD_NOTIFY_OP_RELEASED_LOCK);
2876 }
2877
2878 static int rbd_request_lock(struct rbd_device *rbd_dev)
2879 {
2880         struct page **reply_pages;
2881         size_t reply_len;
2882         bool lock_owner_responded = false;
2883         int ret;
2884
2885         dout("%s rbd_dev %p\n", __func__, rbd_dev);
2886
2887         ret = __rbd_notify_op_lock(rbd_dev, RBD_NOTIFY_OP_REQUEST_LOCK,
2888                                    &reply_pages, &reply_len);
2889         if (ret && ret != -ETIMEDOUT) {
2890                 rbd_warn(rbd_dev, "failed to request lock: %d", ret);
2891                 goto out;
2892         }
2893
2894         if (reply_len > 0 && reply_len <= PAGE_SIZE) {
2895                 void *p = page_address(reply_pages[0]);
2896                 void *const end = p + reply_len;
2897                 u32 n;
2898
2899                 ceph_decode_32_safe(&p, end, n, e_inval); /* num_acks */
2900                 while (n--) {
2901                         u8 struct_v;
2902                         u32 len;
2903
2904                         ceph_decode_need(&p, end, 8 + 8, e_inval);
2905                         p += 8 + 8; /* skip gid and cookie */
2906
2907                         ceph_decode_32_safe(&p, end, len, e_inval);
2908                         if (!len)
2909                                 continue;
2910
2911                         if (lock_owner_responded) {
2912                                 rbd_warn(rbd_dev,
2913                                          "duplicate lock owners detected");
2914                                 ret = -EIO;
2915                                 goto out;
2916                         }
2917
2918                         lock_owner_responded = true;
2919                         ret = ceph_start_decoding(&p, end, 1, "ResponseMessage",
2920                                                   &struct_v, &len);
2921                         if (ret) {
2922                                 rbd_warn(rbd_dev,
2923                                          "failed to decode ResponseMessage: %d",
2924                                          ret);
2925                                 goto e_inval;
2926                         }
2927
2928                         ret = ceph_decode_32(&p);
2929                 }
2930         }
2931
2932         if (!lock_owner_responded) {
2933                 rbd_warn(rbd_dev, "no lock owners detected");
2934                 ret = -ETIMEDOUT;
2935         }
2936
2937 out:
2938         ceph_release_page_vector(reply_pages, calc_pages_for(0, reply_len));
2939         return ret;
2940
2941 e_inval:
2942         ret = -EINVAL;
2943         goto out;
2944 }
2945
2946 static void wake_requests(struct rbd_device *rbd_dev, bool wake_all)
2947 {
2948         dout("%s rbd_dev %p wake_all %d\n", __func__, rbd_dev, wake_all);
2949
2950         cancel_delayed_work(&rbd_dev->lock_dwork);
2951         if (wake_all)
2952                 wake_up_all(&rbd_dev->lock_waitq);
2953         else
2954                 wake_up(&rbd_dev->lock_waitq);
2955 }
2956
2957 static int get_lock_owner_info(struct rbd_device *rbd_dev,
2958                                struct ceph_locker **lockers, u32 *num_lockers)
2959 {
2960         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
2961         u8 lock_type;
2962         char *lock_tag;
2963         int ret;
2964
2965         dout("%s rbd_dev %p\n", __func__, rbd_dev);
2966
2967         ret = ceph_cls_lock_info(osdc, &rbd_dev->header_oid,
2968                                  &rbd_dev->header_oloc, RBD_LOCK_NAME,
2969                                  &lock_type, &lock_tag, lockers, num_lockers);
2970         if (ret)
2971                 return ret;
2972
2973         if (*num_lockers == 0) {
2974                 dout("%s rbd_dev %p no lockers detected\n", __func__, rbd_dev);
2975                 goto out;
2976         }
2977
2978         if (strcmp(lock_tag, RBD_LOCK_TAG)) {
2979                 rbd_warn(rbd_dev, "locked by external mechanism, tag %s",
2980                          lock_tag);
2981                 ret = -EBUSY;
2982                 goto out;
2983         }
2984
2985         if (lock_type == CEPH_CLS_LOCK_SHARED) {
2986                 rbd_warn(rbd_dev, "shared lock type detected");
2987                 ret = -EBUSY;
2988                 goto out;
2989         }
2990
2991         if (strncmp((*lockers)[0].id.cookie, RBD_LOCK_COOKIE_PREFIX,
2992                     strlen(RBD_LOCK_COOKIE_PREFIX))) {
2993                 rbd_warn(rbd_dev, "locked by external mechanism, cookie %s",
2994                          (*lockers)[0].id.cookie);
2995                 ret = -EBUSY;
2996                 goto out;
2997         }
2998
2999 out:
3000         kfree(lock_tag);
3001         return ret;
3002 }
3003
3004 static int find_watcher(struct rbd_device *rbd_dev,
3005                         const struct ceph_locker *locker)
3006 {
3007         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
3008         struct ceph_watch_item *watchers;
3009         u32 num_watchers;
3010         u64 cookie;
3011         int i;
3012         int ret;
3013
3014         ret = ceph_osdc_list_watchers(osdc, &rbd_dev->header_oid,
3015                                       &rbd_dev->header_oloc, &watchers,
3016                                       &num_watchers);
3017         if (ret)
3018                 return ret;
3019
3020         sscanf(locker->id.cookie, RBD_LOCK_COOKIE_PREFIX " %llu", &cookie);
3021         for (i = 0; i < num_watchers; i++) {
3022                 if (!memcmp(&watchers[i].addr, &locker->info.addr,
3023                             sizeof(locker->info.addr)) &&
3024                     watchers[i].cookie == cookie) {
3025                         struct rbd_client_id cid = {
3026                                 .gid = le64_to_cpu(watchers[i].name.num),
3027                                 .handle = cookie,
3028                         };
3029
3030                         dout("%s rbd_dev %p found cid %llu-%llu\n", __func__,
3031                              rbd_dev, cid.gid, cid.handle);
3032                         rbd_set_owner_cid(rbd_dev, &cid);
3033                         ret = 1;
3034                         goto out;
3035                 }
3036         }
3037
3038         dout("%s rbd_dev %p no watchers\n", __func__, rbd_dev);
3039         ret = 0;
3040 out:
3041         kfree(watchers);
3042         return ret;
3043 }
3044
3045 /*
3046  * lock_rwsem must be held for write
3047  */
3048 static int rbd_try_lock(struct rbd_device *rbd_dev)
3049 {
3050         struct ceph_client *client = rbd_dev->rbd_client->client;
3051         struct ceph_locker *lockers;
3052         u32 num_lockers;
3053         int ret;
3054
3055         for (;;) {
3056                 ret = rbd_lock(rbd_dev);
3057                 if (ret != -EBUSY)
3058                         return ret;
3059
3060                 /* determine if the current lock holder is still alive */
3061                 ret = get_lock_owner_info(rbd_dev, &lockers, &num_lockers);
3062                 if (ret)
3063                         return ret;
3064
3065                 if (num_lockers == 0)
3066                         goto again;
3067
3068                 ret = find_watcher(rbd_dev, lockers);
3069                 if (ret) {
3070                         if (ret > 0)
3071                                 ret = 0; /* have to request lock */
3072                         goto out;
3073                 }
3074
3075                 rbd_warn(rbd_dev, "%s%llu seems dead, breaking lock",
3076                          ENTITY_NAME(lockers[0].id.name));
3077
3078                 ret = ceph_monc_blacklist_add(&client->monc,
3079                                               &lockers[0].info.addr);
3080                 if (ret) {
3081                         rbd_warn(rbd_dev, "blacklist of %s%llu failed: %d",
3082                                  ENTITY_NAME(lockers[0].id.name), ret);
3083                         goto out;
3084                 }
3085
3086                 ret = ceph_cls_break_lock(&client->osdc, &rbd_dev->header_oid,
3087                                           &rbd_dev->header_oloc, RBD_LOCK_NAME,
3088                                           lockers[0].id.cookie,
3089                                           &lockers[0].id.name);
3090                 if (ret && ret != -ENOENT)
3091                         goto out;
3092
3093 again:
3094                 ceph_free_lockers(lockers, num_lockers);
3095         }
3096
3097 out:
3098         ceph_free_lockers(lockers, num_lockers);
3099         return ret;
3100 }
3101
3102 /*
3103  * ret is set only if lock_state is RBD_LOCK_STATE_UNLOCKED
3104  */
3105 static enum rbd_lock_state rbd_try_acquire_lock(struct rbd_device *rbd_dev,
3106                                                 int *pret)
3107 {
3108         enum rbd_lock_state lock_state;
3109
3110         down_read(&rbd_dev->lock_rwsem);
3111         dout("%s rbd_dev %p read lock_state %d\n", __func__, rbd_dev,
3112              rbd_dev->lock_state);
3113         if (__rbd_is_lock_owner(rbd_dev)) {
3114                 lock_state = rbd_dev->lock_state;
3115                 up_read(&rbd_dev->lock_rwsem);
3116                 return lock_state;
3117         }
3118
3119         up_read(&rbd_dev->lock_rwsem);
3120         down_write(&rbd_dev->lock_rwsem);
3121         dout("%s rbd_dev %p write lock_state %d\n", __func__, rbd_dev,
3122              rbd_dev->lock_state);
3123         if (!__rbd_is_lock_owner(rbd_dev)) {
3124                 *pret = rbd_try_lock(rbd_dev);
3125                 if (*pret)
3126                         rbd_warn(rbd_dev, "failed to acquire lock: %d", *pret);
3127         }
3128
3129         lock_state = rbd_dev->lock_state;
3130         up_write(&rbd_dev->lock_rwsem);
3131         return lock_state;
3132 }
3133
3134 static void rbd_acquire_lock(struct work_struct *work)
3135 {
3136         struct rbd_device *rbd_dev = container_of(to_delayed_work(work),
3137                                             struct rbd_device, lock_dwork);
3138         enum rbd_lock_state lock_state;
3139         int ret = 0;
3140
3141         dout("%s rbd_dev %p\n", __func__, rbd_dev);
3142 again:
3143         lock_state = rbd_try_acquire_lock(rbd_dev, &ret);
3144         if (lock_state != RBD_LOCK_STATE_UNLOCKED || ret == -EBLACKLISTED) {
3145                 if (lock_state == RBD_LOCK_STATE_LOCKED)
3146                         wake_requests(rbd_dev, true);
3147                 dout("%s rbd_dev %p lock_state %d ret %d - done\n", __func__,
3148                      rbd_dev, lock_state, ret);
3149                 return;
3150         }
3151
3152         ret = rbd_request_lock(rbd_dev);
3153         if (ret == -ETIMEDOUT) {
3154                 goto again; /* treat this as a dead client */
3155         } else if (ret == -EROFS) {
3156                 rbd_warn(rbd_dev, "peer will not release lock");
3157                 /*
3158                  * If this is rbd_add_acquire_lock(), we want to fail
3159                  * immediately -- reuse BLACKLISTED flag.  Otherwise we
3160                  * want to block.
3161                  */
3162                 if (!(rbd_dev->disk->flags & GENHD_FL_UP)) {
3163                         set_bit(RBD_DEV_FLAG_BLACKLISTED, &rbd_dev->flags);
3164                         /* wake "rbd map --exclusive" process */
3165                         wake_requests(rbd_dev, false);
3166                 }
3167         } else if (ret < 0) {
3168                 rbd_warn(rbd_dev, "error requesting lock: %d", ret);
3169                 mod_delayed_work(rbd_dev->task_wq, &rbd_dev->lock_dwork,
3170                                  RBD_RETRY_DELAY);
3171         } else {
3172                 /*
3173                  * lock owner acked, but resend if we don't see them
3174                  * release the lock
3175                  */
3176                 dout("%s rbd_dev %p requeueing lock_dwork\n", __func__,
3177                      rbd_dev);
3178                 mod_delayed_work(rbd_dev->task_wq, &rbd_dev->lock_dwork,
3179                     msecs_to_jiffies(2 * RBD_NOTIFY_TIMEOUT * MSEC_PER_SEC));
3180         }
3181 }
3182
3183 /*
3184  * lock_rwsem must be held for write
3185  */
3186 static bool rbd_release_lock(struct rbd_device *rbd_dev)
3187 {
3188         dout("%s rbd_dev %p read lock_state %d\n", __func__, rbd_dev,
3189              rbd_dev->lock_state);
3190         if (rbd_dev->lock_state != RBD_LOCK_STATE_LOCKED)
3191                 return false;
3192
3193         rbd_dev->lock_state = RBD_LOCK_STATE_RELEASING;
3194         downgrade_write(&rbd_dev->lock_rwsem);
3195         /*
3196          * Ensure that all in-flight IO is flushed.
3197          *
3198          * FIXME: ceph_osdc_sync() flushes the entire OSD client, which
3199          * may be shared with other devices.
3200          */
3201         ceph_osdc_sync(&rbd_dev->rbd_client->client->osdc);
3202         up_read(&rbd_dev->lock_rwsem);
3203
3204         down_write(&rbd_dev->lock_rwsem);
3205         dout("%s rbd_dev %p write lock_state %d\n", __func__, rbd_dev,
3206              rbd_dev->lock_state);
3207         if (rbd_dev->lock_state != RBD_LOCK_STATE_RELEASING)
3208                 return false;
3209
3210         rbd_unlock(rbd_dev);
3211         /*
3212          * Give others a chance to grab the lock - we would re-acquire
3213          * almost immediately if we got new IO during ceph_osdc_sync()
3214          * otherwise.  We need to ack our own notifications, so this
3215          * lock_dwork will be requeued from rbd_wait_state_locked()
3216          * after wake_requests() in rbd_handle_released_lock().
3217          */
3218         cancel_delayed_work(&rbd_dev->lock_dwork);
3219         return true;
3220 }
3221
3222 static void rbd_release_lock_work(struct work_struct *work)
3223 {
3224         struct rbd_device *rbd_dev = container_of(work, struct rbd_device,
3225                                                   unlock_work);
3226
3227         down_write(&rbd_dev->lock_rwsem);
3228         rbd_release_lock(rbd_dev);
3229         up_write(&rbd_dev->lock_rwsem);
3230 }
3231
3232 static void rbd_handle_acquired_lock(struct rbd_device *rbd_dev, u8 struct_v,
3233                                      void **p)
3234 {
3235         struct rbd_client_id cid = { 0 };
3236
3237         if (struct_v >= 2) {
3238                 cid.gid = ceph_decode_64(p);
3239                 cid.handle = ceph_decode_64(p);
3240         }
3241
3242         dout("%s rbd_dev %p cid %llu-%llu\n", __func__, rbd_dev, cid.gid,
3243              cid.handle);
3244         if (!rbd_cid_equal(&cid, &rbd_empty_cid)) {
3245                 down_write(&rbd_dev->lock_rwsem);
3246                 if (rbd_cid_equal(&cid, &rbd_dev->owner_cid)) {
3247                         /*
3248                          * we already know that the remote client is
3249                          * the owner
3250                          */
3251                         up_write(&rbd_dev->lock_rwsem);
3252                         return;
3253                 }
3254
3255                 rbd_set_owner_cid(rbd_dev, &cid);
3256                 downgrade_write(&rbd_dev->lock_rwsem);
3257         } else {
3258                 down_read(&rbd_dev->lock_rwsem);
3259         }
3260
3261         if (!__rbd_is_lock_owner(rbd_dev))
3262                 wake_requests(rbd_dev, false);
3263         up_read(&rbd_dev->lock_rwsem);
3264 }
3265
3266 static void rbd_handle_released_lock(struct rbd_device *rbd_dev, u8 struct_v,
3267                                      void **p)
3268 {
3269         struct rbd_client_id cid = { 0 };
3270
3271         if (struct_v >= 2) {
3272                 cid.gid = ceph_decode_64(p);
3273                 cid.handle = ceph_decode_64(p);
3274         }
3275
3276         dout("%s rbd_dev %p cid %llu-%llu\n", __func__, rbd_dev, cid.gid,
3277              cid.handle);
3278         if (!rbd_cid_equal(&cid, &rbd_empty_cid)) {
3279                 down_write(&rbd_dev->lock_rwsem);
3280                 if (!rbd_cid_equal(&cid, &rbd_dev->owner_cid)) {
3281                         dout("%s rbd_dev %p unexpected owner, cid %llu-%llu != owner_cid %llu-%llu\n",
3282                              __func__, rbd_dev, cid.gid, cid.handle,
3283                              rbd_dev->owner_cid.gid, rbd_dev->owner_cid.handle);
3284                         up_write(&rbd_dev->lock_rwsem);
3285                         return;
3286                 }
3287
3288                 rbd_set_owner_cid(rbd_dev, &rbd_empty_cid);
3289                 downgrade_write(&rbd_dev->lock_rwsem);
3290         } else {
3291                 down_read(&rbd_dev->lock_rwsem);
3292         }
3293
3294         if (!__rbd_is_lock_owner(rbd_dev))
3295                 wake_requests(rbd_dev, false);
3296         up_read(&rbd_dev->lock_rwsem);
3297 }
3298
3299 /*
3300  * Returns result for ResponseMessage to be encoded (<= 0), or 1 if no
3301  * ResponseMessage is needed.
3302  */
3303 static int rbd_handle_request_lock(struct rbd_device *rbd_dev, u8 struct_v,
3304                                    void **p)
3305 {
3306         struct rbd_client_id my_cid = rbd_get_cid(rbd_dev);
3307         struct rbd_client_id cid = { 0 };
3308         int result = 1;
3309
3310         if (struct_v >= 2) {
3311                 cid.gid = ceph_decode_64(p);
3312                 cid.handle = ceph_decode_64(p);
3313         }
3314
3315         dout("%s rbd_dev %p cid %llu-%llu\n", __func__, rbd_dev, cid.gid,
3316              cid.handle);
3317         if (rbd_cid_equal(&cid, &my_cid))
3318                 return result;
3319
3320         down_read(&rbd_dev->lock_rwsem);
3321         if (__rbd_is_lock_owner(rbd_dev)) {
3322                 if (rbd_dev->lock_state == RBD_LOCK_STATE_LOCKED &&
3323                     rbd_cid_equal(&rbd_dev->owner_cid, &rbd_empty_cid))
3324                         goto out_unlock;
3325
3326                 /*
3327                  * encode ResponseMessage(0) so the peer can detect
3328                  * a missing owner
3329                  */
3330                 result = 0;
3331
3332                 if (rbd_dev->lock_state == RBD_LOCK_STATE_LOCKED) {
3333                         if (!rbd_dev->opts->exclusive) {
3334                                 dout("%s rbd_dev %p queueing unlock_work\n",
3335                                      __func__, rbd_dev);
3336                                 queue_work(rbd_dev->task_wq,
3337                                            &rbd_dev->unlock_work);
3338                         } else {
3339                                 /* refuse to release the lock */
3340                                 result = -EROFS;
3341                         }
3342                 }
3343         }
3344
3345 out_unlock:
3346         up_read(&rbd_dev->lock_rwsem);
3347         return result;
3348 }
3349
3350 static void __rbd_acknowledge_notify(struct rbd_device *rbd_dev,
3351                                      u64 notify_id, u64 cookie, s32 *result)
3352 {
3353         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
3354         char buf[4 + CEPH_ENCODING_START_BLK_LEN];
3355         int buf_size = sizeof(buf);
3356         int ret;
3357
3358         if (result) {
3359                 void *p = buf;
3360
3361                 /* encode ResponseMessage */
3362                 ceph_start_encoding(&p, 1, 1,
3363                                     buf_size - CEPH_ENCODING_START_BLK_LEN);
3364                 ceph_encode_32(&p, *result);
3365         } else {
3366                 buf_size = 0;
3367         }
3368
3369         ret = ceph_osdc_notify_ack(osdc, &rbd_dev->header_oid,
3370                                    &rbd_dev->header_oloc, notify_id, cookie,
3371                                    buf, buf_size);
3372         if (ret)
3373                 rbd_warn(rbd_dev, "acknowledge_notify failed: %d", ret);
3374 }
3375
3376 static void rbd_acknowledge_notify(struct rbd_device *rbd_dev, u64 notify_id,
3377                                    u64 cookie)
3378 {
3379         dout("%s rbd_dev %p\n", __func__, rbd_dev);
3380         __rbd_acknowledge_notify(rbd_dev, notify_id, cookie, NULL);
3381 }
3382
3383 static void rbd_acknowledge_notify_result(struct rbd_device *rbd_dev,
3384                                           u64 notify_id, u64 cookie, s32 result)
3385 {
3386         dout("%s rbd_dev %p result %d\n", __func__, rbd_dev, result);
3387         __rbd_acknowledge_notify(rbd_dev, notify_id, cookie, &result);
3388 }
3389
3390 static void rbd_watch_cb(void *arg, u64 notify_id, u64 cookie,
3391                          u64 notifier_id, void *data, size_t data_len)
3392 {
3393         struct rbd_device *rbd_dev = arg;
3394         void *p = data;
3395         void *const end = p + data_len;
3396         u8 struct_v = 0;
3397         u32 len;
3398         u32 notify_op;
3399         int ret;
3400
3401         dout("%s rbd_dev %p cookie %llu notify_id %llu data_len %zu\n",
3402              __func__, rbd_dev, cookie, notify_id, data_len);
3403         if (data_len) {
3404                 ret = ceph_start_decoding(&p, end, 1, "NotifyMessage",
3405                                           &struct_v, &len);
3406                 if (ret) {
3407                         rbd_warn(rbd_dev, "failed to decode NotifyMessage: %d",
3408                                  ret);
3409                         return;
3410                 }
3411
3412                 notify_op = ceph_decode_32(&p);
3413         } else {
3414                 /* legacy notification for header updates */
3415                 notify_op = RBD_NOTIFY_OP_HEADER_UPDATE;
3416                 len = 0;
3417         }
3418
3419         dout("%s rbd_dev %p notify_op %u\n", __func__, rbd_dev, notify_op);
3420         switch (notify_op) {
3421         case RBD_NOTIFY_OP_ACQUIRED_LOCK:
3422                 rbd_handle_acquired_lock(rbd_dev, struct_v, &p);
3423                 rbd_acknowledge_notify(rbd_dev, notify_id, cookie);
3424                 break;
3425         case RBD_NOTIFY_OP_RELEASED_LOCK:
3426                 rbd_handle_released_lock(rbd_dev, struct_v, &p);
3427                 rbd_acknowledge_notify(rbd_dev, notify_id, cookie);
3428                 break;
3429         case RBD_NOTIFY_OP_REQUEST_LOCK:
3430                 ret = rbd_handle_request_lock(rbd_dev, struct_v, &p);
3431                 if (ret <= 0)
3432                         rbd_acknowledge_notify_result(rbd_dev, notify_id,
3433                                                       cookie, ret);
3434                 else
3435                         rbd_acknowledge_notify(rbd_dev, notify_id, cookie);
3436                 break;
3437         case RBD_NOTIFY_OP_HEADER_UPDATE:
3438                 ret = rbd_dev_refresh(rbd_dev);
3439                 if (ret)
3440                         rbd_warn(rbd_dev, "refresh failed: %d", ret);
3441
3442                 rbd_acknowledge_notify(rbd_dev, notify_id, cookie);
3443                 break;
3444         default:
3445                 if (rbd_is_lock_owner(rbd_dev))
3446                         rbd_acknowledge_notify_result(rbd_dev, notify_id,
3447                                                       cookie, -EOPNOTSUPP);
3448                 else
3449                         rbd_acknowledge_notify(rbd_dev, notify_id, cookie);
3450                 break;
3451         }
3452 }
3453
3454 static void __rbd_unregister_watch(struct rbd_device *rbd_dev);
3455
3456 static void rbd_watch_errcb(void *arg, u64 cookie, int err)
3457 {
3458         struct rbd_device *rbd_dev = arg;
3459
3460         rbd_warn(rbd_dev, "encountered watch error: %d", err);
3461
3462         down_write(&rbd_dev->lock_rwsem);
3463         rbd_set_owner_cid(rbd_dev, &rbd_empty_cid);
3464         up_write(&rbd_dev->lock_rwsem);
3465
3466         mutex_lock(&rbd_dev->watch_mutex);
3467         if (rbd_dev->watch_state == RBD_WATCH_STATE_REGISTERED) {
3468                 __rbd_unregister_watch(rbd_dev);
3469                 rbd_dev->watch_state = RBD_WATCH_STATE_ERROR;
3470
3471                 queue_delayed_work(rbd_dev->task_wq, &rbd_dev->watch_dwork, 0);
3472         }
3473         mutex_unlock(&rbd_dev->watch_mutex);
3474 }
3475
3476 /*
3477  * watch_mutex must be locked
3478  */
3479 static int __rbd_register_watch(struct rbd_device *rbd_dev)
3480 {
3481         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
3482         struct ceph_osd_linger_request *handle;
3483
3484         rbd_assert(!rbd_dev->watch_handle);
3485         dout("%s rbd_dev %p\n", __func__, rbd_dev);
3486
3487         handle = ceph_osdc_watch(osdc, &rbd_dev->header_oid,
3488                                  &rbd_dev->header_oloc, rbd_watch_cb,
3489                                  rbd_watch_errcb, rbd_dev);
3490         if (IS_ERR(handle))
3491                 return PTR_ERR(handle);
3492
3493         rbd_dev->watch_handle = handle;
3494         return 0;
3495 }
3496
3497 /*
3498  * watch_mutex must be locked
3499  */
3500 static void __rbd_unregister_watch(struct rbd_device *rbd_dev)
3501 {
3502         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
3503         int ret;
3504
3505         rbd_assert(rbd_dev->watch_handle);
3506         dout("%s rbd_dev %p\n", __func__, rbd_dev);
3507
3508         ret = ceph_osdc_unwatch(osdc, rbd_dev->watch_handle);
3509         if (ret)
3510                 rbd_warn(rbd_dev, "failed to unwatch: %d", ret);
3511
3512         rbd_dev->watch_handle = NULL;
3513 }
3514
3515 static int rbd_register_watch(struct rbd_device *rbd_dev)
3516 {
3517         int ret;
3518
3519         mutex_lock(&rbd_dev->watch_mutex);
3520         rbd_assert(rbd_dev->watch_state == RBD_WATCH_STATE_UNREGISTERED);
3521         ret = __rbd_register_watch(rbd_dev);
3522         if (ret)
3523                 goto out;
3524
3525         rbd_dev->watch_state = RBD_WATCH_STATE_REGISTERED;
3526         rbd_dev->watch_cookie = rbd_dev->watch_handle->linger_id;
3527
3528 out:
3529         mutex_unlock(&rbd_dev->watch_mutex);
3530         return ret;
3531 }
3532
3533 static void cancel_tasks_sync(struct rbd_device *rbd_dev)
3534 {
3535         dout("%s rbd_dev %p\n", __func__, rbd_dev);
3536
3537         cancel_work_sync(&rbd_dev->acquired_lock_work);
3538         cancel_work_sync(&rbd_dev->released_lock_work);
3539         cancel_delayed_work_sync(&rbd_dev->lock_dwork);
3540         cancel_work_sync(&rbd_dev->unlock_work);
3541 }
3542
3543 static void rbd_unregister_watch(struct rbd_device *rbd_dev)
3544 {
3545         WARN_ON(waitqueue_active(&rbd_dev->lock_waitq));
3546         cancel_tasks_sync(rbd_dev);
3547
3548         mutex_lock(&rbd_dev->watch_mutex);
3549         if (rbd_dev->watch_state == RBD_WATCH_STATE_REGISTERED)
3550                 __rbd_unregister_watch(rbd_dev);
3551         rbd_dev->watch_state = RBD_WATCH_STATE_UNREGISTERED;
3552         mutex_unlock(&rbd_dev->watch_mutex);
3553
3554         cancel_delayed_work_sync(&rbd_dev->watch_dwork);
3555         ceph_osdc_flush_notifies(&rbd_dev->rbd_client->client->osdc);
3556 }
3557
3558 /*
3559  * lock_rwsem must be held for write
3560  */
3561 static void rbd_reacquire_lock(struct rbd_device *rbd_dev)
3562 {
3563         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
3564         char cookie[32];
3565         int ret;
3566
3567         WARN_ON(rbd_dev->lock_state != RBD_LOCK_STATE_LOCKED);
3568
3569         format_lock_cookie(rbd_dev, cookie);
3570         ret = ceph_cls_set_cookie(osdc, &rbd_dev->header_oid,
3571                                   &rbd_dev->header_oloc, RBD_LOCK_NAME,
3572                                   CEPH_CLS_LOCK_EXCLUSIVE, rbd_dev->lock_cookie,
3573                                   RBD_LOCK_TAG, cookie);
3574         if (ret) {
3575                 if (ret != -EOPNOTSUPP)
3576                         rbd_warn(rbd_dev, "failed to update lock cookie: %d",
3577                                  ret);
3578
3579                 /*
3580                  * Lock cookie cannot be updated on older OSDs, so do
3581                  * a manual release and queue an acquire.
3582                  */
3583                 if (rbd_release_lock(rbd_dev))
3584                         queue_delayed_work(rbd_dev->task_wq,
3585                                            &rbd_dev->lock_dwork, 0);
3586         } else {
3587                 __rbd_lock(rbd_dev, cookie);
3588         }
3589 }
3590
3591 static void rbd_reregister_watch(struct work_struct *work)
3592 {
3593         struct rbd_device *rbd_dev = container_of(to_delayed_work(work),
3594                                             struct rbd_device, watch_dwork);
3595         int ret;
3596
3597         dout("%s rbd_dev %p\n", __func__, rbd_dev);
3598
3599         mutex_lock(&rbd_dev->watch_mutex);
3600         if (rbd_dev->watch_state != RBD_WATCH_STATE_ERROR) {
3601                 mutex_unlock(&rbd_dev->watch_mutex);
3602                 return;
3603         }
3604
3605         ret = __rbd_register_watch(rbd_dev);
3606         if (ret) {
3607                 rbd_warn(rbd_dev, "failed to reregister watch: %d", ret);
3608                 if (ret == -EBLACKLISTED || ret == -ENOENT) {
3609                         set_bit(RBD_DEV_FLAG_BLACKLISTED, &rbd_dev->flags);
3610                         wake_requests(rbd_dev, true);
3611                 } else {
3612                         queue_delayed_work(rbd_dev->task_wq,
3613                                            &rbd_dev->watch_dwork,
3614                                            RBD_RETRY_DELAY);
3615                 }
3616                 mutex_unlock(&rbd_dev->watch_mutex);
3617                 return;
3618         }
3619
3620         rbd_dev->watch_state = RBD_WATCH_STATE_REGISTERED;
3621         rbd_dev->watch_cookie = rbd_dev->watch_handle->linger_id;
3622         mutex_unlock(&rbd_dev->watch_mutex);
3623
3624         down_write(&rbd_dev->lock_rwsem);
3625         if (rbd_dev->lock_state == RBD_LOCK_STATE_LOCKED)
3626                 rbd_reacquire_lock(rbd_dev);
3627         up_write(&rbd_dev->lock_rwsem);
3628
3629         ret = rbd_dev_refresh(rbd_dev);
3630         if (ret)
3631                 rbd_warn(rbd_dev, "reregistration refresh failed: %d", ret);
3632 }
3633
3634 /*
3635  * Synchronous osd object method call.  Returns the number of bytes
3636  * returned in the outbound buffer, or a negative error code.
3637  */
3638 static int rbd_obj_method_sync(struct rbd_device *rbd_dev,
3639                              struct ceph_object_id *oid,
3640                              struct ceph_object_locator *oloc,
3641                              const char *method_name,
3642                              const void *outbound,
3643                              size_t outbound_size,
3644                              void *inbound,
3645                              size_t inbound_size)
3646 {
3647         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
3648         struct page *req_page = NULL;
3649         struct page *reply_page;
3650         int ret;
3651
3652         /*
3653          * Method calls are ultimately read operations.  The result
3654          * should placed into the inbound buffer provided.  They
3655          * also supply outbound data--parameters for the object
3656          * method.  Currently if this is present it will be a
3657          * snapshot id.
3658          */
3659         if (outbound) {
3660                 if (outbound_size > PAGE_SIZE)
3661                         return -E2BIG;
3662
3663                 req_page = alloc_page(GFP_KERNEL);
3664                 if (!req_page)
3665                         return -ENOMEM;
3666
3667                 memcpy(page_address(req_page), outbound, outbound_size);
3668         }
3669
3670         reply_page = alloc_page(GFP_KERNEL);
3671         if (!reply_page) {
3672                 if (req_page)
3673                         __free_page(req_page);
3674                 return -ENOMEM;
3675         }
3676
3677         ret = ceph_osdc_call(osdc, oid, oloc, RBD_DRV_NAME, method_name,
3678                              CEPH_OSD_FLAG_READ, req_page, outbound_size,
3679                              reply_page, &inbound_size);
3680         if (!ret) {
3681                 memcpy(inbound, page_address(reply_page), inbound_size);
3682                 ret = inbound_size;
3683         }
3684
3685         if (req_page)
3686                 __free_page(req_page);
3687         __free_page(reply_page);
3688         return ret;
3689 }
3690
3691 /*
3692  * lock_rwsem must be held for read
3693  */
3694 static int rbd_wait_state_locked(struct rbd_device *rbd_dev, bool may_acquire)
3695 {
3696         DEFINE_WAIT(wait);
3697         unsigned long timeout;
3698         int ret = 0;
3699
3700         if (test_bit(RBD_DEV_FLAG_BLACKLISTED, &rbd_dev->flags))
3701                 return -EBLACKLISTED;
3702
3703         if (rbd_dev->lock_state == RBD_LOCK_STATE_LOCKED)
3704                 return 0;
3705
3706         if (!may_acquire) {
3707                 rbd_warn(rbd_dev, "exclusive lock required");
3708                 return -EROFS;
3709         }
3710
3711         do {
3712                 /*
3713                  * Note the use of mod_delayed_work() in rbd_acquire_lock()
3714                  * and cancel_delayed_work() in wake_requests().
3715                  */
3716                 dout("%s rbd_dev %p queueing lock_dwork\n", __func__, rbd_dev);
3717                 queue_delayed_work(rbd_dev->task_wq, &rbd_dev->lock_dwork, 0);
3718                 prepare_to_wait_exclusive(&rbd_dev->lock_waitq, &wait,
3719                                           TASK_UNINTERRUPTIBLE);
3720                 up_read(&rbd_dev->lock_rwsem);
3721                 timeout = schedule_timeout(ceph_timeout_jiffies(
3722                                                 rbd_dev->opts->lock_timeout));
3723                 down_read(&rbd_dev->lock_rwsem);
3724                 if (test_bit(RBD_DEV_FLAG_BLACKLISTED, &rbd_dev->flags)) {
3725                         ret = -EBLACKLISTED;
3726                         break;
3727                 }
3728                 if (!timeout) {
3729                         rbd_warn(rbd_dev, "timed out waiting for lock");
3730                         ret = -ETIMEDOUT;
3731                         break;
3732                 }
3733         } while (rbd_dev->lock_state != RBD_LOCK_STATE_LOCKED);
3734
3735         finish_wait(&rbd_dev->lock_waitq, &wait);
3736         return ret;
3737 }
3738
3739 static void rbd_queue_workfn(struct work_struct *work)
3740 {
3741         struct request *rq = blk_mq_rq_from_pdu(work);
3742         struct rbd_device *rbd_dev = rq->q->queuedata;
3743         struct rbd_img_request *img_request;
3744         struct ceph_snap_context *snapc = NULL;
3745         u64 offset = (u64)blk_rq_pos(rq) << SECTOR_SHIFT;
3746         u64 length = blk_rq_bytes(rq);
3747         enum obj_operation_type op_type;
3748         u64 mapping_size;
3749         bool must_be_locked;
3750         int result;
3751
3752         switch (req_op(rq)) {
3753         case REQ_OP_DISCARD:
3754                 op_type = OBJ_OP_DISCARD;
3755                 break;
3756         case REQ_OP_WRITE_ZEROES:
3757                 op_type = OBJ_OP_ZEROOUT;
3758                 break;
3759         case REQ_OP_WRITE:
3760                 op_type = OBJ_OP_WRITE;
3761                 break;
3762         case REQ_OP_READ:
3763                 op_type = OBJ_OP_READ;
3764                 break;
3765         default:
3766                 dout("%s: non-fs request type %d\n", __func__, req_op(rq));
3767                 result = -EIO;
3768                 goto err;
3769         }
3770
3771         /* Ignore/skip any zero-length requests */
3772
3773         if (!length) {
3774                 dout("%s: zero-length request\n", __func__);
3775                 result = 0;
3776                 goto err_rq;
3777         }
3778
3779         rbd_assert(op_type == OBJ_OP_READ ||
3780                    rbd_dev->spec->snap_id == CEPH_NOSNAP);
3781
3782         /*
3783          * Quit early if the mapped snapshot no longer exists.  It's
3784          * still possible the snapshot will have disappeared by the
3785          * time our request arrives at the osd, but there's no sense in
3786          * sending it if we already know.
3787          */
3788         if (!test_bit(RBD_DEV_FLAG_EXISTS, &rbd_dev->flags)) {
3789                 dout("request for non-existent snapshot");
3790                 rbd_assert(rbd_dev->spec->snap_id != CEPH_NOSNAP);
3791                 result = -ENXIO;
3792                 goto err_rq;
3793         }
3794
3795         if (offset && length > U64_MAX - offset + 1) {
3796                 rbd_warn(rbd_dev, "bad request range (%llu~%llu)", offset,
3797                          length);
3798                 result = -EINVAL;
3799                 goto err_rq;    /* Shouldn't happen */
3800         }
3801
3802         blk_mq_start_request(rq);
3803
3804         down_read(&rbd_dev->header_rwsem);
3805         mapping_size = rbd_dev->mapping.size;
3806         if (op_type != OBJ_OP_READ) {
3807                 snapc = rbd_dev->header.snapc;
3808                 ceph_get_snap_context(snapc);
3809         }
3810         up_read(&rbd_dev->header_rwsem);
3811
3812         if (offset + length > mapping_size) {
3813                 rbd_warn(rbd_dev, "beyond EOD (%llu~%llu > %llu)", offset,
3814                          length, mapping_size);
3815                 result = -EIO;
3816                 goto err_rq;
3817         }
3818
3819         must_be_locked =
3820             (rbd_dev->header.features & RBD_FEATURE_EXCLUSIVE_LOCK) &&
3821             (op_type != OBJ_OP_READ || rbd_dev->opts->lock_on_read);
3822         if (must_be_locked) {
3823                 down_read(&rbd_dev->lock_rwsem);
3824                 result = rbd_wait_state_locked(rbd_dev,
3825                                                !rbd_dev->opts->exclusive);
3826                 if (result)
3827                         goto err_unlock;
3828         }
3829
3830         img_request = rbd_img_request_create(rbd_dev, op_type, snapc);
3831         if (!img_request) {
3832                 result = -ENOMEM;
3833                 goto err_unlock;
3834         }
3835         img_request->rq = rq;
3836         snapc = NULL; /* img_request consumes a ref */
3837
3838         if (op_type == OBJ_OP_DISCARD || op_type == OBJ_OP_ZEROOUT)
3839                 result = rbd_img_fill_nodata(img_request, offset, length);
3840         else
3841                 result = rbd_img_fill_from_bio(img_request, offset, length,
3842                                                rq->bio);
3843         if (result || !img_request->pending_count)
3844                 goto err_img_request;
3845
3846         rbd_img_request_submit(img_request);
3847         if (must_be_locked)
3848                 up_read(&rbd_dev->lock_rwsem);
3849         return;
3850
3851 err_img_request:
3852         rbd_img_request_put(img_request);
3853 err_unlock:
3854         if (must_be_locked)
3855                 up_read(&rbd_dev->lock_rwsem);
3856 err_rq:
3857         if (result)
3858                 rbd_warn(rbd_dev, "%s %llx at %llx result %d",
3859                          obj_op_name(op_type), length, offset, result);
3860         ceph_put_snap_context(snapc);
3861 err:
3862         blk_mq_end_request(rq, errno_to_blk_status(result));
3863 }
3864
3865 static blk_status_t rbd_queue_rq(struct blk_mq_hw_ctx *hctx,
3866                 const struct blk_mq_queue_data *bd)
3867 {
3868         struct request *rq = bd->rq;
3869         struct work_struct *work = blk_mq_rq_to_pdu(rq);
3870
3871         queue_work(rbd_wq, work);
3872         return BLK_STS_OK;
3873 }
3874
3875 static void rbd_free_disk(struct rbd_device *rbd_dev)
3876 {
3877         blk_cleanup_queue(rbd_dev->disk->queue);
3878         blk_mq_free_tag_set(&rbd_dev->tag_set);
3879         put_disk(rbd_dev->disk);
3880         rbd_dev->disk = NULL;
3881 }
3882
3883 static int rbd_obj_read_sync(struct rbd_device *rbd_dev,
3884                              struct ceph_object_id *oid,
3885                              struct ceph_object_locator *oloc,
3886                              void *buf, int buf_len)
3887
3888 {
3889         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
3890         struct ceph_osd_request *req;
3891         struct page **pages;
3892         int num_pages = calc_pages_for(0, buf_len);
3893         int ret;
3894
3895         req = ceph_osdc_alloc_request(osdc, NULL, 1, false, GFP_KERNEL);
3896         if (!req)
3897                 return -ENOMEM;
3898
3899         ceph_oid_copy(&req->r_base_oid, oid);
3900         ceph_oloc_copy(&req->r_base_oloc, oloc);
3901         req->r_flags = CEPH_OSD_FLAG_READ;
3902
3903         pages = ceph_alloc_page_vector(num_pages, GFP_KERNEL);
3904         if (IS_ERR(pages)) {
3905                 ret = PTR_ERR(pages);
3906                 goto out_req;
3907         }
3908
3909         osd_req_op_extent_init(req, 0, CEPH_OSD_OP_READ, 0, buf_len, 0, 0);
3910         osd_req_op_extent_osd_data_pages(req, 0, pages, buf_len, 0, false,
3911                                          true);
3912
3913         ret = ceph_osdc_alloc_messages(req, GFP_KERNEL);
3914         if (ret)
3915                 goto out_req;
3916
3917         ceph_osdc_start_request(osdc, req, false);
3918         ret = ceph_osdc_wait_request(osdc, req);
3919         if (ret >= 0)
3920                 ceph_copy_from_page_vector(pages, buf, 0, ret);
3921
3922 out_req:
3923         ceph_osdc_put_request(req);
3924         return ret;
3925 }
3926
3927 /*
3928  * Read the complete header for the given rbd device.  On successful
3929  * return, the rbd_dev->header field will contain up-to-date
3930  * information about the image.
3931  */
3932 static int rbd_dev_v1_header_info(struct rbd_device *rbd_dev)
3933 {
3934         struct rbd_image_header_ondisk *ondisk = NULL;
3935         u32 snap_count = 0;
3936         u64 names_size = 0;
3937         u32 want_count;
3938         int ret;
3939
3940         /*
3941          * The complete header will include an array of its 64-bit
3942          * snapshot ids, followed by the names of those snapshots as
3943          * a contiguous block of NUL-terminated strings.  Note that
3944          * the number of snapshots could change by the time we read
3945          * it in, in which case we re-read it.
3946          */
3947         do {
3948                 size_t size;
3949
3950                 kfree(ondisk);
3951
3952                 size = sizeof (*ondisk);
3953                 size += snap_count * sizeof (struct rbd_image_snap_ondisk);
3954                 size += names_size;
3955                 ondisk = kmalloc(size, GFP_KERNEL);
3956                 if (!ondisk)
3957                         return -ENOMEM;
3958
3959                 ret = rbd_obj_read_sync(rbd_dev, &rbd_dev->header_oid,
3960                                         &rbd_dev->header_oloc, ondisk, size);
3961                 if (ret < 0)
3962                         goto out;
3963                 if ((size_t)ret < size) {
3964                         ret = -ENXIO;
3965                         rbd_warn(rbd_dev, "short header read (want %zd got %d)",
3966                                 size, ret);
3967                         goto out;
3968                 }
3969                 if (!rbd_dev_ondisk_valid(ondisk)) {
3970                         ret = -ENXIO;
3971                         rbd_warn(rbd_dev, "invalid header");
3972                         goto out;
3973                 }
3974
3975                 names_size = le64_to_cpu(ondisk->snap_names_len);
3976                 want_count = snap_count;
3977                 snap_count = le32_to_cpu(ondisk->snap_count);
3978         } while (snap_count != want_count);
3979
3980         ret = rbd_header_from_disk(rbd_dev, ondisk);
3981 out:
3982         kfree(ondisk);
3983
3984         return ret;
3985 }
3986
3987 /*
3988  * Clear the rbd device's EXISTS flag if the snapshot it's mapped to
3989  * has disappeared from the (just updated) snapshot context.
3990  */
3991 static void rbd_exists_validate(struct rbd_device *rbd_dev)
3992 {
3993         u64 snap_id;
3994
3995         if (!test_bit(RBD_DEV_FLAG_EXISTS, &rbd_dev->flags))
3996                 return;
3997
3998         snap_id = rbd_dev->spec->snap_id;
3999         if (snap_id == CEPH_NOSNAP)
4000                 return;
4001
4002         if (rbd_dev_snap_index(rbd_dev, snap_id) == BAD_SNAP_INDEX)
4003                 clear_bit(RBD_DEV_FLAG_EXISTS, &rbd_dev->flags);
4004 }
4005
4006 static void rbd_dev_update_size(struct rbd_device *rbd_dev)
4007 {
4008         sector_t size;
4009
4010         /*
4011          * If EXISTS is not set, rbd_dev->disk may be NULL, so don't
4012          * try to update its size.  If REMOVING is set, updating size
4013          * is just useless work since the device can't be opened.
4014          */
4015         if (test_bit(RBD_DEV_FLAG_EXISTS, &rbd_dev->flags) &&
4016             !test_bit(RBD_DEV_FLAG_REMOVING, &rbd_dev->flags)) {
4017                 size = (sector_t)rbd_dev->mapping.size / SECTOR_SIZE;
4018                 dout("setting size to %llu sectors", (unsigned long long)size);
4019                 set_capacity(rbd_dev->disk, size);
4020                 revalidate_disk(rbd_dev->disk);
4021         }
4022 }
4023
4024 static int rbd_dev_refresh(struct rbd_device *rbd_dev)
4025 {
4026         u64 mapping_size;
4027         int ret;
4028
4029         down_write(&rbd_dev->header_rwsem);
4030         mapping_size = rbd_dev->mapping.size;
4031
4032         ret = rbd_dev_header_info(rbd_dev);
4033         if (ret)
4034                 goto out;
4035
4036         /*
4037          * If there is a parent, see if it has disappeared due to the
4038          * mapped image getting flattened.
4039          */
4040         if (rbd_dev->parent) {
4041                 ret = rbd_dev_v2_parent_info(rbd_dev);
4042                 if (ret)
4043                         goto out;
4044         }
4045
4046         if (rbd_dev->spec->snap_id == CEPH_NOSNAP) {
4047                 rbd_dev->mapping.size = rbd_dev->header.image_size;
4048         } else {
4049                 /* validate mapped snapshot's EXISTS flag */
4050                 rbd_exists_validate(rbd_dev);
4051         }
4052
4053 out:
4054         up_write(&rbd_dev->header_rwsem);
4055         if (!ret && mapping_size != rbd_dev->mapping.size)
4056                 rbd_dev_update_size(rbd_dev);
4057
4058         return ret;
4059 }
4060
4061 static int rbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
4062                 unsigned int hctx_idx, unsigned int numa_node)
4063 {
4064         struct work_struct *work = blk_mq_rq_to_pdu(rq);
4065
4066         INIT_WORK(work, rbd_queue_workfn);
4067         return 0;
4068 }
4069
4070 static const struct blk_mq_ops rbd_mq_ops = {
4071         .queue_rq       = rbd_queue_rq,
4072         .init_request   = rbd_init_request,
4073 };
4074
4075 static int rbd_init_disk(struct rbd_device *rbd_dev)
4076 {
4077         struct gendisk *disk;
4078         struct request_queue *q;
4079         unsigned int objset_bytes =
4080             rbd_dev->layout.object_size * rbd_dev->layout.stripe_count;
4081         int err;
4082
4083         /* create gendisk info */
4084         disk = alloc_disk(single_major ?
4085                           (1 << RBD_SINGLE_MAJOR_PART_SHIFT) :
4086                           RBD_MINORS_PER_MAJOR);
4087         if (!disk)
4088                 return -ENOMEM;
4089
4090         snprintf(disk->disk_name, sizeof(disk->disk_name), RBD_DRV_NAME "%d",
4091                  rbd_dev->dev_id);
4092         disk->major = rbd_dev->major;
4093         disk->first_minor = rbd_dev->minor;
4094         if (single_major)
4095                 disk->flags |= GENHD_FL_EXT_DEVT;
4096         disk->fops = &rbd_bd_ops;
4097         disk->private_data = rbd_dev;
4098
4099         memset(&rbd_dev->tag_set, 0, sizeof(rbd_dev->tag_set));
4100         rbd_dev->tag_set.ops = &rbd_mq_ops;
4101         rbd_dev->tag_set.queue_depth = rbd_dev->opts->queue_depth;
4102         rbd_dev->tag_set.numa_node = NUMA_NO_NODE;
4103         rbd_dev->tag_set.flags = BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_SG_MERGE;
4104         rbd_dev->tag_set.nr_hw_queues = 1;
4105         rbd_dev->tag_set.cmd_size = sizeof(struct work_struct);
4106
4107         err = blk_mq_alloc_tag_set(&rbd_dev->tag_set);
4108         if (err)
4109                 goto out_disk;
4110
4111         q = blk_mq_init_queue(&rbd_dev->tag_set);
4112         if (IS_ERR(q)) {
4113                 err = PTR_ERR(q);
4114                 goto out_tag_set;
4115         }
4116
4117         blk_queue_flag_set(QUEUE_FLAG_NONROT, q);
4118         /* QUEUE_FLAG_ADD_RANDOM is off by default for blk-mq */
4119
4120         blk_queue_max_hw_sectors(q, objset_bytes >> SECTOR_SHIFT);
4121         q->limits.max_sectors = queue_max_hw_sectors(q);
4122         blk_queue_max_segments(q, USHRT_MAX);
4123         blk_queue_max_segment_size(q, UINT_MAX);
4124         blk_queue_io_min(q, objset_bytes);
4125         blk_queue_io_opt(q, objset_bytes);
4126
4127         if (rbd_dev->opts->trim) {
4128                 blk_queue_flag_set(QUEUE_FLAG_DISCARD, q);
4129                 q->limits.discard_granularity = objset_bytes;
4130                 blk_queue_max_discard_sectors(q, objset_bytes >> SECTOR_SHIFT);
4131                 blk_queue_max_write_zeroes_sectors(q, objset_bytes >> SECTOR_SHIFT);
4132         }
4133
4134         if (!ceph_test_opt(rbd_dev->rbd_client->client, NOCRC))
4135                 q->backing_dev_info->capabilities |= BDI_CAP_STABLE_WRITES;
4136
4137         /*
4138          * disk_release() expects a queue ref from add_disk() and will
4139          * put it.  Hold an extra ref until add_disk() is called.
4140          */
4141         WARN_ON(!blk_get_queue(q));
4142         disk->queue = q;
4143         q->queuedata = rbd_dev;
4144
4145         rbd_dev->disk = disk;
4146
4147         return 0;
4148 out_tag_set:
4149         blk_mq_free_tag_set(&rbd_dev->tag_set);
4150 out_disk:
4151         put_disk(disk);
4152         return err;
4153 }
4154
4155 /*
4156   sysfs
4157 */
4158
4159 static struct rbd_device *dev_to_rbd_dev(struct device *dev)
4160 {
4161         return container_of(dev, struct rbd_device, dev);
4162 }
4163
4164 static ssize_t rbd_size_show(struct device *dev,
4165                              struct device_attribute *attr, char *buf)
4166 {
4167         struct rbd_device *rbd_dev = dev_to_rbd_dev(dev);
4168
4169         return sprintf(buf, "%llu\n",
4170                 (unsigned long long)rbd_dev->mapping.size);
4171 }
4172
4173 /*
4174  * Note this shows the features for whatever's mapped, which is not
4175  * necessarily the base image.
4176  */
4177 static ssize_t rbd_features_show(struct device *dev,
4178                              struct device_attribute *attr, char *buf)
4179 {
4180         struct rbd_device *rbd_dev = dev_to_rbd_dev(dev);
4181
4182         return sprintf(buf, "0x%016llx\n",
4183                         (unsigned long long)rbd_dev->mapping.features);
4184 }
4185
4186 static ssize_t rbd_major_show(struct device *dev,
4187                               struct device_attribute *attr, char *buf)
4188 {
4189         struct rbd_device *rbd_dev = dev_to_rbd_dev(dev);
4190
4191         if (rbd_dev->major)
4192                 return sprintf(buf, "%d\n", rbd_dev->major);
4193
4194         return sprintf(buf, "(none)\n");
4195 }
4196
4197 static ssize_t rbd_minor_show(struct device *dev,
4198                               struct device_attribute *attr, char *buf)
4199 {
4200         struct rbd_device *rbd_dev = dev_to_rbd_dev(dev);
4201
4202         return sprintf(buf, "%d\n", rbd_dev->minor);
4203 }
4204
4205 static ssize_t rbd_client_addr_show(struct device *dev,
4206                                     struct device_attribute *attr, char *buf)
4207 {
4208         struct rbd_device *rbd_dev = dev_to_rbd_dev(dev);
4209         struct ceph_entity_addr *client_addr =
4210             ceph_client_addr(rbd_dev->rbd_client->client);
4211
4212         return sprintf(buf, "%pISpc/%u\n", &client_addr->in_addr,
4213                        le32_to_cpu(client_addr->nonce));
4214 }
4215
4216 static ssize_t rbd_client_id_show(struct device *dev,
4217                                   struct device_attribute *attr, char *buf)
4218 {
4219         struct rbd_device *rbd_dev = dev_to_rbd_dev(dev);
4220
4221         return sprintf(buf, "client%lld\n",
4222                        ceph_client_gid(rbd_dev->rbd_client->client));
4223 }
4224
4225 static ssize_t rbd_cluster_fsid_show(struct device *dev,
4226                                      struct device_attribute *attr, char *buf)
4227 {
4228         struct rbd_device *rbd_dev = dev_to_rbd_dev(dev);
4229
4230         return sprintf(buf, "%pU\n", &rbd_dev->rbd_client->client->fsid);
4231 }
4232
4233 static ssize_t rbd_config_info_show(struct device *dev,
4234                                     struct device_attribute *attr, char *buf)
4235 {
4236         struct rbd_device *rbd_dev = dev_to_rbd_dev(dev);
4237
4238         return sprintf(buf, "%s\n", rbd_dev->config_info);
4239 }
4240
4241 static ssize_t rbd_pool_show(struct device *dev,
4242                              struct device_attribute *attr, char *buf)
4243 {
4244         struct rbd_device *rbd_dev = dev_to_rbd_dev(dev);
4245
4246         return sprintf(buf, "%s\n", rbd_dev->spec->pool_name);
4247 }
4248
4249 static ssize_t rbd_pool_id_show(struct device *dev,
4250                              struct device_attribute *attr, char *buf)
4251 {
4252         struct rbd_device *rbd_dev = dev_to_rbd_dev(dev);
4253
4254         return sprintf(buf, "%llu\n",
4255                         (unsigned long long) rbd_dev->spec->pool_id);
4256 }
4257
4258 static ssize_t rbd_pool_ns_show(struct device *dev,
4259                                 struct device_attribute *attr, char *buf)
4260 {
4261         struct rbd_device *rbd_dev = dev_to_rbd_dev(dev);
4262
4263         return sprintf(buf, "%s\n", rbd_dev->spec->pool_ns ?: "");
4264 }
4265
4266 static ssize_t rbd_name_show(struct device *dev,
4267                              struct device_attribute *attr, char *buf)
4268 {
4269         struct rbd_device *rbd_dev = dev_to_rbd_dev(dev);
4270
4271         if (rbd_dev->spec->image_name)
4272                 return sprintf(buf, "%s\n", rbd_dev->spec->image_name);
4273
4274         return sprintf(buf, "(unknown)\n");
4275 }
4276
4277 static ssize_t rbd_image_id_show(struct device *dev,
4278                              struct device_attribute *attr, char *buf)
4279 {
4280         struct rbd_device *rbd_dev = dev_to_rbd_dev(dev);
4281
4282         return sprintf(buf, "%s\n", rbd_dev->spec->image_id);
4283 }
4284
4285 /*
4286  * Shows the name of the currently-mapped snapshot (or
4287  * RBD_SNAP_HEAD_NAME for the base image).
4288  */
4289 static ssize_t rbd_snap_show(struct device *dev,
4290                              struct device_attribute *attr,
4291                              char *buf)
4292 {
4293         struct rbd_device *rbd_dev = dev_to_rbd_dev(dev);
4294
4295         return sprintf(buf, "%s\n", rbd_dev->spec->snap_name);
4296 }
4297
4298 static ssize_t rbd_snap_id_show(struct device *dev,
4299                                 struct device_attribute *attr, char *buf)
4300 {
4301         struct rbd_device *rbd_dev = dev_to_rbd_dev(dev);
4302
4303         return sprintf(buf, "%llu\n", rbd_dev->spec->snap_id);
4304 }
4305
4306 /*
4307  * For a v2 image, shows the chain of parent images, separated by empty
4308  * lines.  For v1 images or if there is no parent, shows "(no parent
4309  * image)".
4310  */
4311 static ssize_t rbd_parent_show(struct device *dev,
4312                                struct device_attribute *attr,
4313                                char *buf)
4314 {
4315         struct rbd_device *rbd_dev = dev_to_rbd_dev(dev);
4316         ssize_t count = 0;
4317
4318         if (!rbd_dev->parent)
4319                 return sprintf(buf, "(no parent image)\n");
4320
4321         for ( ; rbd_dev->parent; rbd_dev = rbd_dev->parent) {
4322                 struct rbd_spec *spec = rbd_dev->parent_spec;
4323
4324                 count += sprintf(&buf[count], "%s"
4325                             "pool_id %llu\npool_name %s\n"
4326                             "pool_ns %s\n"
4327                             "image_id %s\nimage_name %s\n"
4328                             "snap_id %llu\nsnap_name %s\n"
4329                             "overlap %llu\n",
4330                             !count ? "" : "\n", /* first? */
4331                             spec->pool_id, spec->pool_name,
4332                             spec->pool_ns ?: "",
4333                             spec->image_id, spec->image_name ?: "(unknown)",
4334                             spec->snap_id, spec->snap_name,
4335                             rbd_dev->parent_overlap);
4336         }
4337
4338         return count;
4339 }
4340
4341 static ssize_t rbd_image_refresh(struct device *dev,
4342                                  struct device_attribute *attr,
4343                                  const char *buf,
4344                                  size_t size)
4345 {
4346         struct rbd_device *rbd_dev = dev_to_rbd_dev(dev);
4347         int ret;
4348
4349         ret = rbd_dev_refresh(rbd_dev);
4350         if (ret)
4351                 return ret;
4352
4353         return size;
4354 }
4355
4356 static DEVICE_ATTR(size, 0444, rbd_size_show, NULL);
4357 static DEVICE_ATTR(features, 0444, rbd_features_show, NULL);
4358 static DEVICE_ATTR(major, 0444, rbd_major_show, NULL);
4359 static DEVICE_ATTR(minor, 0444, rbd_minor_show, NULL);
4360 static DEVICE_ATTR(client_addr, 0444, rbd_client_addr_show, NULL);
4361 static DEVICE_ATTR(client_id, 0444, rbd_client_id_show, NULL);
4362 static DEVICE_ATTR(cluster_fsid, 0444, rbd_cluster_fsid_show, NULL);
4363 static DEVICE_ATTR(config_info, 0400, rbd_config_info_show, NULL);
4364 static DEVICE_ATTR(pool, 0444, rbd_pool_show, NULL);
4365 static DEVICE_ATTR(pool_id, 0444, rbd_pool_id_show, NULL);
4366 static DEVICE_ATTR(pool_ns, 0444, rbd_pool_ns_show, NULL);
4367 static DEVICE_ATTR(name, 0444, rbd_name_show, NULL);
4368 static DEVICE_ATTR(image_id, 0444, rbd_image_id_show, NULL);
4369 static DEVICE_ATTR(refresh, 0200, NULL, rbd_image_refresh);
4370 static DEVICE_ATTR(current_snap, 0444, rbd_snap_show, NULL);
4371 static DEVICE_ATTR(snap_id, 0444, rbd_snap_id_show, NULL);
4372 static DEVICE_ATTR(parent, 0444, rbd_parent_show, NULL);
4373
4374 static struct attribute *rbd_attrs[] = {
4375         &dev_attr_size.attr,
4376         &dev_attr_features.attr,
4377         &dev_attr_major.attr,
4378         &dev_attr_minor.attr,
4379         &dev_attr_client_addr.attr,
4380         &dev_attr_client_id.attr,
4381         &dev_attr_cluster_fsid.attr,
4382         &dev_attr_config_info.attr,
4383         &dev_attr_pool.attr,
4384         &dev_attr_pool_id.attr,
4385         &dev_attr_pool_ns.attr,
4386         &dev_attr_name.attr,
4387         &dev_attr_image_id.attr,
4388         &dev_attr_current_snap.attr,
4389         &dev_attr_snap_id.attr,
4390         &dev_attr_parent.attr,
4391         &dev_attr_refresh.attr,
4392         NULL
4393 };
4394
4395 static struct attribute_group rbd_attr_group = {
4396         .attrs = rbd_attrs,
4397 };
4398
4399 static const struct attribute_group *rbd_attr_groups[] = {
4400         &rbd_attr_group,
4401         NULL
4402 };
4403
4404 static void rbd_dev_release(struct device *dev);
4405
4406 static const struct device_type rbd_device_type = {
4407         .name           = "rbd",
4408         .groups         = rbd_attr_groups,
4409         .release        = rbd_dev_release,
4410 };
4411
4412 static struct rbd_spec *rbd_spec_get(struct rbd_spec *spec)
4413 {
4414         kref_get(&spec->kref);
4415
4416         return spec;
4417 }
4418
4419 static void rbd_spec_free(struct kref *kref);
4420 static void rbd_spec_put(struct rbd_spec *spec)
4421 {
4422         if (spec)
4423                 kref_put(&spec->kref, rbd_spec_free);
4424 }
4425
4426 static struct rbd_spec *rbd_spec_alloc(void)
4427 {
4428         struct rbd_spec *spec;
4429
4430         spec = kzalloc(sizeof (*spec), GFP_KERNEL);
4431         if (!spec)
4432                 return NULL;
4433
4434         spec->pool_id = CEPH_NOPOOL;
4435         spec->snap_id = CEPH_NOSNAP;
4436         kref_init(&spec->kref);
4437
4438         return spec;
4439 }
4440
4441 static void rbd_spec_free(struct kref *kref)
4442 {
4443         struct rbd_spec *spec = container_of(kref, struct rbd_spec, kref);
4444
4445         kfree(spec->pool_name);
4446         kfree(spec->pool_ns);
4447         kfree(spec->image_id);
4448         kfree(spec->image_name);
4449         kfree(spec->snap_name);
4450         kfree(spec);
4451 }
4452
4453 static void rbd_dev_free(struct rbd_device *rbd_dev)
4454 {
4455         WARN_ON(rbd_dev->watch_state != RBD_WATCH_STATE_UNREGISTERED);
4456         WARN_ON(rbd_dev->lock_state != RBD_LOCK_STATE_UNLOCKED);
4457
4458         ceph_oid_destroy(&rbd_dev->header_oid);
4459         ceph_oloc_destroy(&rbd_dev->header_oloc);
4460         kfree(rbd_dev->config_info);
4461
4462         rbd_put_client(rbd_dev->rbd_client);
4463         rbd_spec_put(rbd_dev->spec);
4464         kfree(rbd_dev->opts);
4465         kfree(rbd_dev);
4466 }
4467
4468 static void rbd_dev_release(struct device *dev)
4469 {
4470         struct rbd_device *rbd_dev = dev_to_rbd_dev(dev);
4471         bool need_put = !!rbd_dev->opts;
4472
4473         if (need_put) {
4474                 destroy_workqueue(rbd_dev->task_wq);
4475                 ida_simple_remove(&rbd_dev_id_ida, rbd_dev->dev_id);
4476         }
4477
4478         rbd_dev_free(rbd_dev);
4479
4480         /*
4481          * This is racy, but way better than putting module outside of
4482          * the release callback.  The race window is pretty small, so
4483          * doing something similar to dm (dm-builtin.c) is overkill.
4484          */
4485         if (need_put)
4486                 module_put(THIS_MODULE);
4487 }
4488
4489 static struct rbd_device *__rbd_dev_create(struct rbd_client *rbdc,
4490                                            struct rbd_spec *spec)
4491 {
4492         struct rbd_device *rbd_dev;
4493
4494         rbd_dev = kzalloc(sizeof(*rbd_dev), GFP_KERNEL);
4495         if (!rbd_dev)
4496                 return NULL;
4497
4498         spin_lock_init(&rbd_dev->lock);
4499         INIT_LIST_HEAD(&rbd_dev->node);
4500         init_rwsem(&rbd_dev->header_rwsem);
4501
4502         rbd_dev->header.data_pool_id = CEPH_NOPOOL;
4503         ceph_oid_init(&rbd_dev->header_oid);
4504         rbd_dev->header_oloc.pool = spec->pool_id;
4505         if (spec->pool_ns) {
4506                 WARN_ON(!*spec->pool_ns);
4507                 rbd_dev->header_oloc.pool_ns =
4508                     ceph_find_or_create_string(spec->pool_ns,
4509                                                strlen(spec->pool_ns));
4510         }
4511
4512         mutex_init(&rbd_dev->watch_mutex);
4513         rbd_dev->watch_state = RBD_WATCH_STATE_UNREGISTERED;
4514         INIT_DELAYED_WORK(&rbd_dev->watch_dwork, rbd_reregister_watch);
4515
4516         init_rwsem(&rbd_dev->lock_rwsem);
4517         rbd_dev->lock_state = RBD_LOCK_STATE_UNLOCKED;
4518         INIT_WORK(&rbd_dev->acquired_lock_work, rbd_notify_acquired_lock);
4519         INIT_WORK(&rbd_dev->released_lock_work, rbd_notify_released_lock);
4520         INIT_DELAYED_WORK(&rbd_dev->lock_dwork, rbd_acquire_lock);
4521         INIT_WORK(&rbd_dev->unlock_work, rbd_release_lock_work);
4522         init_waitqueue_head(&rbd_dev->lock_waitq);
4523
4524         rbd_dev->dev.bus = &rbd_bus_type;
4525         rbd_dev->dev.type = &rbd_device_type;
4526         rbd_dev->dev.parent = &rbd_root_dev;
4527         device_initialize(&rbd_dev->dev);
4528
4529         rbd_dev->rbd_client = rbdc;
4530         rbd_dev->spec = spec;
4531
4532         return rbd_dev;
4533 }
4534
4535 /*
4536  * Create a mapping rbd_dev.
4537  */
4538 static struct rbd_device *rbd_dev_create(struct rbd_client *rbdc,
4539                                          struct rbd_spec *spec,
4540                                          struct rbd_options *opts)
4541 {
4542         struct rbd_device *rbd_dev;
4543
4544         rbd_dev = __rbd_dev_create(rbdc, spec);
4545         if (!rbd_dev)
4546                 return NULL;
4547
4548         rbd_dev->opts = opts;
4549
4550         /* get an id and fill in device name */
4551         rbd_dev->dev_id = ida_simple_get(&rbd_dev_id_ida, 0,
4552                                          minor_to_rbd_dev_id(1 << MINORBITS),
4553                                          GFP_KERNEL);
4554         if (rbd_dev->dev_id < 0)
4555                 goto fail_rbd_dev;
4556
4557         sprintf(rbd_dev->name, RBD_DRV_NAME "%d", rbd_dev->dev_id);
4558         rbd_dev->task_wq = alloc_ordered_workqueue("%s-tasks", WQ_MEM_RECLAIM,
4559                                                    rbd_dev->name);
4560         if (!rbd_dev->task_wq)
4561                 goto fail_dev_id;
4562
4563         /* we have a ref from do_rbd_add() */
4564         __module_get(THIS_MODULE);
4565
4566         dout("%s rbd_dev %p dev_id %d\n", __func__, rbd_dev, rbd_dev->dev_id);
4567         return rbd_dev;
4568
4569 fail_dev_id:
4570         ida_simple_remove(&rbd_dev_id_ida, rbd_dev->dev_id);
4571 fail_rbd_dev:
4572         rbd_dev_free(rbd_dev);
4573         return NULL;
4574 }
4575
4576 static void rbd_dev_destroy(struct rbd_device *rbd_dev)
4577 {
4578         if (rbd_dev)
4579                 put_device(&rbd_dev->dev);
4580 }
4581
4582 /*
4583  * Get the size and object order for an image snapshot, or if
4584  * snap_id is CEPH_NOSNAP, gets this information for the base
4585  * image.
4586  */
4587 static int _rbd_dev_v2_snap_size(struct rbd_device *rbd_dev, u64 snap_id,
4588                                 u8 *order, u64 *snap_size)
4589 {
4590         __le64 snapid = cpu_to_le64(snap_id);
4591         int ret;
4592         struct {
4593                 u8 order;
4594                 __le64 size;
4595         } __attribute__ ((packed)) size_buf = { 0 };
4596
4597         ret = rbd_obj_method_sync(rbd_dev, &rbd_dev->header_oid,
4598                                   &rbd_dev->header_oloc, "get_size",
4599                                   &snapid, sizeof(snapid),
4600                                   &size_buf, sizeof(size_buf));
4601         dout("%s: rbd_obj_method_sync returned %d\n", __func__, ret);
4602         if (ret < 0)
4603                 return ret;
4604         if (ret < sizeof (size_buf))
4605                 return -ERANGE;
4606
4607         if (order) {
4608                 *order = size_buf.order;
4609                 dout("  order %u", (unsigned int)*order);
4610         }
4611         *snap_size = le64_to_cpu(size_buf.size);
4612
4613         dout("  snap_id 0x%016llx snap_size = %llu\n",
4614                 (unsigned long long)snap_id,
4615                 (unsigned long long)*snap_size);
4616
4617         return 0;
4618 }
4619
4620 static int rbd_dev_v2_image_size(struct rbd_device *rbd_dev)
4621 {
4622         return _rbd_dev_v2_snap_size(rbd_dev, CEPH_NOSNAP,
4623                                         &rbd_dev->header.obj_order,
4624                                         &rbd_dev->header.image_size);
4625 }
4626
4627 static int rbd_dev_v2_object_prefix(struct rbd_device *rbd_dev)
4628 {
4629         void *reply_buf;
4630         int ret;
4631         void *p;
4632
4633         reply_buf = kzalloc(RBD_OBJ_PREFIX_LEN_MAX, GFP_KERNEL);
4634         if (!reply_buf)
4635                 return -ENOMEM;
4636
4637         ret = rbd_obj_method_sync(rbd_dev, &rbd_dev->header_oid,
4638                                   &rbd_dev->header_oloc, "get_object_prefix",
4639                                   NULL, 0, reply_buf, RBD_OBJ_PREFIX_LEN_MAX);
4640         dout("%s: rbd_obj_method_sync returned %d\n", __func__, ret);
4641         if (ret < 0)
4642                 goto out;
4643
4644         p = reply_buf;
4645         rbd_dev->header.object_prefix = ceph_extract_encoded_string(&p,
4646                                                 p + ret, NULL, GFP_NOIO);
4647         ret = 0;
4648
4649         if (IS_ERR(rbd_dev->header.object_prefix)) {
4650                 ret = PTR_ERR(rbd_dev->header.object_prefix);
4651                 rbd_dev->header.object_prefix = NULL;
4652         } else {
4653                 dout("  object_prefix = %s\n", rbd_dev->header.object_prefix);
4654         }
4655 out:
4656         kfree(reply_buf);
4657
4658         return ret;
4659 }
4660
4661 static int _rbd_dev_v2_snap_features(struct rbd_device *rbd_dev, u64 snap_id,
4662                 u64 *snap_features)
4663 {
4664         __le64 snapid = cpu_to_le64(snap_id);
4665         struct {
4666                 __le64 features;
4667                 __le64 incompat;
4668         } __attribute__ ((packed)) features_buf = { 0 };
4669         u64 unsup;
4670         int ret;
4671
4672         ret = rbd_obj_method_sync(rbd_dev, &rbd_dev->header_oid,
4673                                   &rbd_dev->header_oloc, "get_features",
4674                                   &snapid, sizeof(snapid),
4675                                   &features_buf, sizeof(features_buf));
4676         dout("%s: rbd_obj_method_sync returned %d\n", __func__, ret);
4677         if (ret < 0)
4678                 return ret;
4679         if (ret < sizeof (features_buf))
4680                 return -ERANGE;
4681
4682         unsup = le64_to_cpu(features_buf.incompat) & ~RBD_FEATURES_SUPPORTED;
4683         if (unsup) {
4684                 rbd_warn(rbd_dev, "image uses unsupported features: 0x%llx",
4685                          unsup);
4686                 return -ENXIO;
4687         }
4688
4689         *snap_features = le64_to_cpu(features_buf.features);
4690
4691         dout("  snap_id 0x%016llx features = 0x%016llx incompat = 0x%016llx\n",
4692                 (unsigned long long)snap_id,
4693                 (unsigned long long)*snap_features,
4694                 (unsigned long long)le64_to_cpu(features_buf.incompat));
4695
4696         return 0;
4697 }
4698
4699 static int rbd_dev_v2_features(struct rbd_device *rbd_dev)
4700 {
4701         return _rbd_dev_v2_snap_features(rbd_dev, CEPH_NOSNAP,
4702                                                 &rbd_dev->header.features);
4703 }
4704
4705 struct parent_image_info {
4706         u64             pool_id;
4707         const char      *pool_ns;
4708         const char      *image_id;
4709         u64             snap_id;
4710
4711         bool            has_overlap;
4712         u64             overlap;
4713 };
4714
4715 /*
4716  * The caller is responsible for @pii.
4717  */
4718 static int decode_parent_image_spec(void **p, void *end,
4719                                     struct parent_image_info *pii)
4720 {
4721         u8 struct_v;
4722         u32 struct_len;
4723         int ret;
4724
4725         ret = ceph_start_decoding(p, end, 1, "ParentImageSpec",
4726                                   &struct_v, &struct_len);
4727         if (ret)
4728                 return ret;
4729
4730         ceph_decode_64_safe(p, end, pii->pool_id, e_inval);
4731         pii->pool_ns = ceph_extract_encoded_string(p, end, NULL, GFP_KERNEL);
4732         if (IS_ERR(pii->pool_ns)) {
4733                 ret = PTR_ERR(pii->pool_ns);
4734                 pii->pool_ns = NULL;
4735                 return ret;
4736         }
4737         pii->image_id = ceph_extract_encoded_string(p, end, NULL, GFP_KERNEL);
4738         if (IS_ERR(pii->image_id)) {
4739                 ret = PTR_ERR(pii->image_id);
4740                 pii->image_id = NULL;
4741                 return ret;
4742         }
4743         ceph_decode_64_safe(p, end, pii->snap_id, e_inval);
4744         return 0;
4745
4746 e_inval:
4747         return -EINVAL;
4748 }
4749
4750 static int __get_parent_info(struct rbd_device *rbd_dev,
4751                              struct page *req_page,
4752                              struct page *reply_page,
4753                              struct parent_image_info *pii)
4754 {
4755         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
4756         size_t reply_len = PAGE_SIZE;
4757         void *p, *end;
4758         int ret;
4759
4760         ret = ceph_osdc_call(osdc, &rbd_dev->header_oid, &rbd_dev->header_oloc,
4761                              "rbd", "parent_get", CEPH_OSD_FLAG_READ,
4762                              req_page, sizeof(u64), reply_page, &reply_len);
4763         if (ret)
4764                 return ret == -EOPNOTSUPP ? 1 : ret;
4765
4766         p = page_address(reply_page);
4767         end = p + reply_len;
4768         ret = decode_parent_image_spec(&p, end, pii);
4769         if (ret)
4770                 return ret;
4771
4772         ret = ceph_osdc_call(osdc, &rbd_dev->header_oid, &rbd_dev->header_oloc,
4773                              "rbd", "parent_overlap_get", CEPH_OSD_FLAG_READ,
4774                              req_page, sizeof(u64), reply_page, &reply_len);
4775         if (ret)
4776                 return ret;
4777
4778         p = page_address(reply_page);
4779         end = p + reply_len;
4780         ceph_decode_8_safe(&p, end, pii->has_overlap, e_inval);
4781         if (pii->has_overlap)
4782                 ceph_decode_64_safe(&p, end, pii->overlap, e_inval);
4783
4784         return 0;
4785
4786 e_inval:
4787         return -EINVAL;
4788 }
4789
4790 /*
4791  * The caller is responsible for @pii.
4792  */
4793 static int __get_parent_info_legacy(struct rbd_device *rbd_dev,
4794                                     struct page *req_page,
4795                                     struct page *reply_page,
4796                                     struct parent_image_info *pii)
4797 {
4798         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
4799         size_t reply_len = PAGE_SIZE;
4800         void *p, *end;
4801         int ret;
4802
4803         ret = ceph_osdc_call(osdc, &rbd_dev->header_oid, &rbd_dev->header_oloc,
4804                              "rbd", "get_parent", CEPH_OSD_FLAG_READ,
4805                              req_page, sizeof(u64), reply_page, &reply_len);
4806         if (ret)
4807                 return ret;
4808
4809         p = page_address(reply_page);
4810         end = p + reply_len;
4811         ceph_decode_64_safe(&p, end, pii->pool_id, e_inval);
4812         pii->image_id = ceph_extract_encoded_string(&p, end, NULL, GFP_KERNEL);
4813         if (IS_ERR(pii->image_id)) {
4814                 ret = PTR_ERR(pii->image_id);
4815                 pii->image_id = NULL;
4816                 return ret;
4817         }
4818         ceph_decode_64_safe(&p, end, pii->snap_id, e_inval);
4819         pii->has_overlap = true;
4820         ceph_decode_64_safe(&p, end, pii->overlap, e_inval);
4821
4822         return 0;
4823
4824 e_inval:
4825         return -EINVAL;
4826 }
4827
4828 static int get_parent_info(struct rbd_device *rbd_dev,
4829                            struct parent_image_info *pii)
4830 {
4831         struct page *req_page, *reply_page;
4832         void *p;
4833         int ret;
4834
4835         req_page = alloc_page(GFP_KERNEL);
4836         if (!req_page)
4837                 return -ENOMEM;
4838
4839         reply_page = alloc_page(GFP_KERNEL);
4840         if (!reply_page) {
4841                 __free_page(req_page);
4842                 return -ENOMEM;
4843         }
4844
4845         p = page_address(req_page);
4846         ceph_encode_64(&p, rbd_dev->spec->snap_id);
4847         ret = __get_parent_info(rbd_dev, req_page, reply_page, pii);
4848         if (ret > 0)
4849                 ret = __get_parent_info_legacy(rbd_dev, req_page, reply_page,
4850                                                pii);
4851
4852         __free_page(req_page);
4853         __free_page(reply_page);
4854         return ret;
4855 }
4856
4857 static int rbd_dev_v2_parent_info(struct rbd_device *rbd_dev)
4858 {
4859         struct rbd_spec *parent_spec;
4860         struct parent_image_info pii = { 0 };
4861         int ret;
4862
4863         parent_spec = rbd_spec_alloc();
4864         if (!parent_spec)
4865                 return -ENOMEM;
4866
4867         ret = get_parent_info(rbd_dev, &pii);
4868         if (ret)
4869                 goto out_err;
4870
4871         dout("%s pool_id %llu pool_ns %s image_id %s snap_id %llu has_overlap %d overlap %llu\n",
4872              __func__, pii.pool_id, pii.pool_ns, pii.image_id, pii.snap_id,
4873              pii.has_overlap, pii.overlap);
4874
4875         if (pii.pool_id == CEPH_NOPOOL || !pii.has_overlap) {
4876                 /*
4877                  * Either the parent never existed, or we have
4878                  * record of it but the image got flattened so it no
4879                  * longer has a parent.  When the parent of a
4880                  * layered image disappears we immediately set the
4881                  * overlap to 0.  The effect of this is that all new
4882                  * requests will be treated as if the image had no
4883                  * parent.
4884                  *
4885                  * If !pii.has_overlap, the parent image spec is not
4886                  * applicable.  It's there to avoid duplication in each
4887                  * snapshot record.
4888                  */
4889                 if (rbd_dev->parent_overlap) {
4890                         rbd_dev->parent_overlap = 0;
4891                         rbd_dev_parent_put(rbd_dev);
4892                         pr_info("%s: clone image has been flattened\n",
4893                                 rbd_dev->disk->disk_name);
4894                 }
4895
4896                 goto out;       /* No parent?  No problem. */
4897         }
4898
4899         /* The ceph file layout needs to fit pool id in 32 bits */
4900
4901         ret = -EIO;
4902         if (pii.pool_id > (u64)U32_MAX) {
4903                 rbd_warn(NULL, "parent pool id too large (%llu > %u)",
4904                         (unsigned long long)pii.pool_id, U32_MAX);
4905                 goto out_err;
4906         }
4907
4908         /*
4909          * The parent won't change (except when the clone is
4910          * flattened, already handled that).  So we only need to
4911          * record the parent spec we have not already done so.
4912          */
4913         if (!rbd_dev->parent_spec) {
4914                 parent_spec->pool_id = pii.pool_id;
4915                 if (pii.pool_ns && *pii.pool_ns) {
4916                         parent_spec->pool_ns = pii.pool_ns;
4917                         pii.pool_ns = NULL;
4918                 }
4919                 parent_spec->image_id = pii.image_id;
4920                 pii.image_id = NULL;
4921                 parent_spec->snap_id = pii.snap_id;
4922
4923                 rbd_dev->parent_spec = parent_spec;
4924                 parent_spec = NULL;     /* rbd_dev now owns this */
4925         }
4926
4927         /*
4928          * We always update the parent overlap.  If it's zero we issue
4929          * a warning, as we will proceed as if there was no parent.
4930          */
4931         if (!pii.overlap) {
4932                 if (parent_spec) {
4933                         /* refresh, careful to warn just once */
4934                         if (rbd_dev->parent_overlap)
4935                                 rbd_warn(rbd_dev,
4936                                     "clone now standalone (overlap became 0)");
4937                 } else {
4938                         /* initial probe */
4939                         rbd_warn(rbd_dev, "clone is standalone (overlap 0)");
4940                 }
4941         }
4942         rbd_dev->parent_overlap = pii.overlap;
4943
4944 out:
4945         ret = 0;
4946 out_err:
4947         kfree(pii.pool_ns);
4948         kfree(pii.image_id);
4949         rbd_spec_put(parent_spec);
4950         return ret;
4951 }
4952
4953 static int rbd_dev_v2_striping_info(struct rbd_device *rbd_dev)
4954 {
4955         struct {
4956                 __le64 stripe_unit;
4957                 __le64 stripe_count;
4958         } __attribute__ ((packed)) striping_info_buf = { 0 };
4959         size_t size = sizeof (striping_info_buf);
4960         void *p;
4961         int ret;
4962
4963         ret = rbd_obj_method_sync(rbd_dev, &rbd_dev->header_oid,
4964                                 &rbd_dev->header_oloc, "get_stripe_unit_count",
4965                                 NULL, 0, &striping_info_buf, size);
4966         dout("%s: rbd_obj_method_sync returned %d\n", __func__, ret);
4967         if (ret < 0)
4968                 return ret;
4969         if (ret < size)
4970                 return -ERANGE;
4971
4972         p = &striping_info_buf;
4973         rbd_dev->header.stripe_unit = ceph_decode_64(&p);
4974         rbd_dev->header.stripe_count = ceph_decode_64(&p);
4975         return 0;
4976 }
4977
4978 static int rbd_dev_v2_data_pool(struct rbd_device *rbd_dev)
4979 {
4980         __le64 data_pool_id;
4981         int ret;
4982
4983         ret = rbd_obj_method_sync(rbd_dev, &rbd_dev->header_oid,
4984                                   &rbd_dev->header_oloc, "get_data_pool",
4985                                   NULL, 0, &data_pool_id, sizeof(data_pool_id));
4986         if (ret < 0)
4987                 return ret;
4988         if (ret < sizeof(data_pool_id))
4989                 return -EBADMSG;
4990
4991         rbd_dev->header.data_pool_id = le64_to_cpu(data_pool_id);
4992         WARN_ON(rbd_dev->header.data_pool_id == CEPH_NOPOOL);
4993         return 0;
4994 }
4995
4996 static char *rbd_dev_image_name(struct rbd_device *rbd_dev)
4997 {
4998         CEPH_DEFINE_OID_ONSTACK(oid);
4999         size_t image_id_size;
5000         char *image_id;
5001         void *p;
5002         void *end;
5003         size_t size;
5004         void *reply_buf = NULL;
5005         size_t len = 0;
5006         char *image_name = NULL;
5007         int ret;
5008
5009         rbd_assert(!rbd_dev->spec->image_name);
5010
5011         len = strlen(rbd_dev->spec->image_id);
5012         image_id_size = sizeof (__le32) + len;
5013         image_id = kmalloc(image_id_size, GFP_KERNEL);
5014         if (!image_id)
5015                 return NULL;
5016
5017         p = image_id;
5018         end = image_id + image_id_size;
5019         ceph_encode_string(&p, end, rbd_dev->spec->image_id, (u32)len);
5020
5021         size = sizeof (__le32) + RBD_IMAGE_NAME_LEN_MAX;
5022         reply_buf = kmalloc(size, GFP_KERNEL);
5023         if (!reply_buf)
5024                 goto out;
5025
5026         ceph_oid_printf(&oid, "%s", RBD_DIRECTORY);
5027         ret = rbd_obj_method_sync(rbd_dev, &oid, &rbd_dev->header_oloc,
5028                                   "dir_get_name", image_id, image_id_size,
5029                                   reply_buf, size);
5030         if (ret < 0)
5031                 goto out;
5032         p = reply_buf;
5033         end = reply_buf + ret;
5034
5035         image_name = ceph_extract_encoded_string(&p, end, &len, GFP_KERNEL);
5036         if (IS_ERR(image_name))
5037                 image_name = NULL;
5038         else
5039                 dout("%s: name is %s len is %zd\n", __func__, image_name, len);
5040 out:
5041         kfree(reply_buf);
5042         kfree(image_id);
5043
5044         return image_name;
5045 }
5046
5047 static u64 rbd_v1_snap_id_by_name(struct rbd_device *rbd_dev, const char *name)
5048 {
5049         struct ceph_snap_context *snapc = rbd_dev->header.snapc;
5050         const char *snap_name;
5051         u32 which = 0;
5052
5053         /* Skip over names until we find the one we are looking for */
5054
5055         snap_name = rbd_dev->header.snap_names;
5056         while (which < snapc->num_snaps) {
5057                 if (!strcmp(name, snap_name))
5058                         return snapc->snaps[which];
5059                 snap_name += strlen(snap_name) + 1;
5060                 which++;
5061         }
5062         return CEPH_NOSNAP;
5063 }
5064
5065 static u64 rbd_v2_snap_id_by_name(struct rbd_device *rbd_dev, const char *name)
5066 {
5067         struct ceph_snap_context *snapc = rbd_dev->header.snapc;
5068         u32 which;
5069         bool found = false;
5070         u64 snap_id;
5071
5072         for (which = 0; !found && which < snapc->num_snaps; which++) {
5073                 const char *snap_name;
5074
5075                 snap_id = snapc->snaps[which];
5076                 snap_name = rbd_dev_v2_snap_name(rbd_dev, snap_id);
5077                 if (IS_ERR(snap_name)) {
5078                         /* ignore no-longer existing snapshots */
5079                         if (PTR_ERR(snap_name) == -ENOENT)
5080                                 continue;
5081                         else
5082                                 break;
5083                 }
5084                 found = !strcmp(name, snap_name);
5085                 kfree(snap_name);
5086         }
5087         return found ? snap_id : CEPH_NOSNAP;
5088 }
5089
5090 /*
5091  * Assumes name is never RBD_SNAP_HEAD_NAME; returns CEPH_NOSNAP if
5092  * no snapshot by that name is found, or if an error occurs.
5093  */
5094 static u64 rbd_snap_id_by_name(struct rbd_device *rbd_dev, const char *name)
5095 {
5096         if (rbd_dev->image_format == 1)
5097                 return rbd_v1_snap_id_by_name(rbd_dev, name);
5098
5099         return rbd_v2_snap_id_by_name(rbd_dev, name);
5100 }
5101
5102 /*
5103  * An image being mapped will have everything but the snap id.
5104  */
5105 static int rbd_spec_fill_snap_id(struct rbd_device *rbd_dev)
5106 {
5107         struct rbd_spec *spec = rbd_dev->spec;
5108
5109         rbd_assert(spec->pool_id != CEPH_NOPOOL && spec->pool_name);
5110         rbd_assert(spec->image_id && spec->image_name);
5111         rbd_assert(spec->snap_name);
5112
5113         if (strcmp(spec->snap_name, RBD_SNAP_HEAD_NAME)) {
5114                 u64 snap_id;
5115
5116                 snap_id = rbd_snap_id_by_name(rbd_dev, spec->snap_name);
5117                 if (snap_id == CEPH_NOSNAP)
5118                         return -ENOENT;
5119
5120                 spec->snap_id = snap_id;
5121         } else {
5122                 spec->snap_id = CEPH_NOSNAP;
5123         }
5124
5125         return 0;
5126 }
5127
5128 /*
5129  * A parent image will have all ids but none of the names.
5130  *
5131  * All names in an rbd spec are dynamically allocated.  It's OK if we
5132  * can't figure out the name for an image id.
5133  */
5134 static int rbd_spec_fill_names(struct rbd_device *rbd_dev)
5135 {
5136         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
5137         struct rbd_spec *spec = rbd_dev->spec;
5138         const char *pool_name;
5139         const char *image_name;
5140         const char *snap_name;
5141         int ret;
5142
5143         rbd_assert(spec->pool_id != CEPH_NOPOOL);
5144         rbd_assert(spec->image_id);
5145         rbd_assert(spec->snap_id != CEPH_NOSNAP);
5146
5147         /* Get the pool name; we have to make our own copy of this */
5148
5149         pool_name = ceph_pg_pool_name_by_id(osdc->osdmap, spec->pool_id);
5150         if (!pool_name) {
5151                 rbd_warn(rbd_dev, "no pool with id %llu", spec->pool_id);
5152                 return -EIO;
5153         }
5154         pool_name = kstrdup(pool_name, GFP_KERNEL);
5155         if (!pool_name)
5156                 return -ENOMEM;
5157
5158         /* Fetch the image name; tolerate failure here */
5159
5160         image_name = rbd_dev_image_name(rbd_dev);
5161         if (!image_name)
5162                 rbd_warn(rbd_dev, "unable to get image name");
5163
5164         /* Fetch the snapshot name */
5165
5166         snap_name = rbd_snap_name(rbd_dev, spec->snap_id);
5167         if (IS_ERR(snap_name)) {
5168                 ret = PTR_ERR(snap_name);
5169                 goto out_err;
5170         }
5171
5172         spec->pool_name = pool_name;
5173         spec->image_name = image_name;
5174         spec->snap_name = snap_name;
5175
5176         return 0;
5177
5178 out_err:
5179         kfree(image_name);
5180         kfree(pool_name);
5181         return ret;
5182 }
5183
5184 static int rbd_dev_v2_snap_context(struct rbd_device *rbd_dev)
5185 {
5186         size_t size;
5187         int ret;
5188         void *reply_buf;
5189         void *p;
5190         void *end;
5191         u64 seq;
5192         u32 snap_count;
5193         struct ceph_snap_context *snapc;
5194         u32 i;
5195
5196         /*
5197          * We'll need room for the seq value (maximum snapshot id),
5198          * snapshot count, and array of that many snapshot ids.
5199          * For now we have a fixed upper limit on the number we're
5200          * prepared to receive.
5201          */
5202         size = sizeof (__le64) + sizeof (__le32) +
5203                         RBD_MAX_SNAP_COUNT * sizeof (__le64);
5204         reply_buf = kzalloc(size, GFP_KERNEL);
5205         if (!reply_buf)
5206                 return -ENOMEM;
5207
5208         ret = rbd_obj_method_sync(rbd_dev, &rbd_dev->header_oid,
5209                                   &rbd_dev->header_oloc, "get_snapcontext",
5210                                   NULL, 0, reply_buf, size);
5211         dout("%s: rbd_obj_method_sync returned %d\n", __func__, ret);
5212         if (ret < 0)
5213                 goto out;
5214
5215         p = reply_buf;
5216         end = reply_buf + ret;
5217         ret = -ERANGE;
5218         ceph_decode_64_safe(&p, end, seq, out);
5219         ceph_decode_32_safe(&p, end, snap_count, out);
5220
5221         /*
5222          * Make sure the reported number of snapshot ids wouldn't go
5223          * beyond the end of our buffer.  But before checking that,
5224          * make sure the computed size of the snapshot context we
5225          * allocate is representable in a size_t.
5226          */
5227         if (snap_count > (SIZE_MAX - sizeof (struct ceph_snap_context))
5228                                  / sizeof (u64)) {
5229                 ret = -EINVAL;
5230                 goto out;
5231         }
5232         if (!ceph_has_room(&p, end, snap_count * sizeof (__le64)))
5233                 goto out;
5234         ret = 0;
5235
5236         snapc = ceph_create_snap_context(snap_count, GFP_KERNEL);
5237         if (!snapc) {
5238                 ret = -ENOMEM;
5239                 goto out;
5240         }
5241         snapc->seq = seq;
5242         for (i = 0; i < snap_count; i++)
5243                 snapc->snaps[i] = ceph_decode_64(&p);
5244
5245         ceph_put_snap_context(rbd_dev->header.snapc);
5246         rbd_dev->header.snapc = snapc;
5247
5248         dout("  snap context seq = %llu, snap_count = %u\n",
5249                 (unsigned long long)seq, (unsigned int)snap_count);
5250 out:
5251         kfree(reply_buf);
5252
5253         return ret;
5254 }
5255
5256 static const char *rbd_dev_v2_snap_name(struct rbd_device *rbd_dev,
5257                                         u64 snap_id)
5258 {
5259         size_t size;
5260         void *reply_buf;
5261         __le64 snapid;
5262         int ret;
5263         void *p;
5264         void *end;
5265         char *snap_name;
5266
5267         size = sizeof (__le32) + RBD_MAX_SNAP_NAME_LEN;
5268         reply_buf = kmalloc(size, GFP_KERNEL);
5269         if (!reply_buf)
5270                 return ERR_PTR(-ENOMEM);
5271
5272         snapid = cpu_to_le64(snap_id);
5273         ret = rbd_obj_method_sync(rbd_dev, &rbd_dev->header_oid,
5274                                   &rbd_dev->header_oloc, "get_snapshot_name",
5275                                   &snapid, sizeof(snapid), reply_buf, size);
5276         dout("%s: rbd_obj_method_sync returned %d\n", __func__, ret);
5277         if (ret < 0) {
5278                 snap_name = ERR_PTR(ret);
5279                 goto out;
5280         }
5281
5282         p = reply_buf;
5283         end = reply_buf + ret;
5284         snap_name = ceph_extract_encoded_string(&p, end, NULL, GFP_KERNEL);
5285         if (IS_ERR(snap_name))
5286                 goto out;
5287
5288         dout("  snap_id 0x%016llx snap_name = %s\n",
5289                 (unsigned long long)snap_id, snap_name);
5290 out:
5291         kfree(reply_buf);
5292
5293         return snap_name;
5294 }
5295
5296 static int rbd_dev_v2_header_info(struct rbd_device *rbd_dev)
5297 {
5298         bool first_time = rbd_dev->header.object_prefix == NULL;
5299         int ret;
5300
5301         ret = rbd_dev_v2_image_size(rbd_dev);
5302         if (ret)
5303                 return ret;
5304
5305         if (first_time) {
5306                 ret = rbd_dev_v2_header_onetime(rbd_dev);
5307                 if (ret)
5308                         return ret;
5309         }
5310
5311         ret = rbd_dev_v2_snap_context(rbd_dev);
5312         if (ret && first_time) {
5313                 kfree(rbd_dev->header.object_prefix);
5314                 rbd_dev->header.object_prefix = NULL;
5315         }
5316
5317         return ret;
5318 }
5319
5320 static int rbd_dev_header_info(struct rbd_device *rbd_dev)
5321 {
5322         rbd_assert(rbd_image_format_valid(rbd_dev->image_format));
5323
5324         if (rbd_dev->image_format == 1)
5325                 return rbd_dev_v1_header_info(rbd_dev);
5326
5327         return rbd_dev_v2_header_info(rbd_dev);
5328 }
5329
5330 /*
5331  * Skips over white space at *buf, and updates *buf to point to the
5332  * first found non-space character (if any). Returns the length of
5333  * the token (string of non-white space characters) found.  Note
5334  * that *buf must be terminated with '\0'.
5335  */
5336 static inline size_t next_token(const char **buf)
5337 {
5338         /*
5339         * These are the characters that produce nonzero for
5340         * isspace() in the "C" and "POSIX" locales.
5341         */
5342         const char *spaces = " \f\n\r\t\v";
5343
5344         *buf += strspn(*buf, spaces);   /* Find start of token */
5345
5346         return strcspn(*buf, spaces);   /* Return token length */
5347 }
5348
5349 /*
5350  * Finds the next token in *buf, dynamically allocates a buffer big
5351  * enough to hold a copy of it, and copies the token into the new
5352  * buffer.  The copy is guaranteed to be terminated with '\0'.  Note
5353  * that a duplicate buffer is created even for a zero-length token.
5354  *
5355  * Returns a pointer to the newly-allocated duplicate, or a null
5356  * pointer if memory for the duplicate was not available.  If
5357  * the lenp argument is a non-null pointer, the length of the token
5358  * (not including the '\0') is returned in *lenp.
5359  *
5360  * If successful, the *buf pointer will be updated to point beyond
5361  * the end of the found token.
5362  *
5363  * Note: uses GFP_KERNEL for allocation.
5364  */
5365 static inline char *dup_token(const char **buf, size_t *lenp)
5366 {
5367         char *dup;
5368         size_t len;
5369
5370         len = next_token(buf);
5371         dup = kmemdup(*buf, len + 1, GFP_KERNEL);
5372         if (!dup)
5373                 return NULL;
5374         *(dup + len) = '\0';
5375         *buf += len;
5376
5377         if (lenp)
5378                 *lenp = len;
5379
5380         return dup;
5381 }
5382
5383 /*
5384  * Parse the options provided for an "rbd add" (i.e., rbd image
5385  * mapping) request.  These arrive via a write to /sys/bus/rbd/add,
5386  * and the data written is passed here via a NUL-terminated buffer.
5387  * Returns 0 if successful or an error code otherwise.
5388  *
5389  * The information extracted from these options is recorded in
5390  * the other parameters which return dynamically-allocated
5391  * structures:
5392  *  ceph_opts
5393  *      The address of a pointer that will refer to a ceph options
5394  *      structure.  Caller must release the returned pointer using
5395  *      ceph_destroy_options() when it is no longer needed.
5396  *  rbd_opts
5397  *      Address of an rbd options pointer.  Fully initialized by
5398  *      this function; caller must release with kfree().
5399  *  spec
5400  *      Address of an rbd image specification pointer.  Fully
5401  *      initialized by this function based on parsed options.
5402  *      Caller must release with rbd_spec_put().
5403  *
5404  * The options passed take this form:
5405  *  <mon_addrs> <options> <pool_name> <image_name> [<snap_id>]
5406  * where:
5407  *  <mon_addrs>
5408  *      A comma-separated list of one or more monitor addresses.
5409  *      A monitor address is an ip address, optionally followed
5410  *      by a port number (separated by a colon).
5411  *        I.e.:  ip1[:port1][,ip2[:port2]...]
5412  *  <options>
5413  *      A comma-separated list of ceph and/or rbd options.
5414  *  <pool_name>
5415  *      The name of the rados pool containing the rbd image.
5416  *  <image_name>
5417  *      The name of the image in that pool to map.
5418  *  <snap_id>
5419  *      An optional snapshot id.  If provided, the mapping will
5420  *      present data from the image at the time that snapshot was
5421  *      created.  The image head is used if no snapshot id is
5422  *      provided.  Snapshot mappings are always read-only.
5423  */
5424 static int rbd_add_parse_args(const char *buf,
5425                                 struct ceph_options **ceph_opts,
5426                                 struct rbd_options **opts,
5427                                 struct rbd_spec **rbd_spec)
5428 {
5429         size_t len;
5430         char *options;
5431         const char *mon_addrs;
5432         char *snap_name;
5433         size_t mon_addrs_size;
5434         struct parse_rbd_opts_ctx pctx = { 0 };
5435         struct ceph_options *copts;
5436         int ret;
5437
5438         /* The first four tokens are required */
5439
5440         len = next_token(&buf);
5441         if (!len) {
5442                 rbd_warn(NULL, "no monitor address(es) provided");
5443                 return -EINVAL;
5444         }
5445         mon_addrs = buf;
5446         mon_addrs_size = len + 1;
5447         buf += len;
5448
5449         ret = -EINVAL;
5450         options = dup_token(&buf, NULL);
5451         if (!options)
5452                 return -ENOMEM;
5453         if (!*options) {
5454                 rbd_warn(NULL, "no options provided");
5455                 goto out_err;
5456         }
5457
5458         pctx.spec = rbd_spec_alloc();
5459         if (!pctx.spec)
5460                 goto out_mem;
5461
5462         pctx.spec->pool_name = dup_token(&buf, NULL);
5463         if (!pctx.spec->pool_name)
5464                 goto out_mem;
5465         if (!*pctx.spec->pool_name) {
5466                 rbd_warn(NULL, "no pool name provided");
5467                 goto out_err;
5468         }
5469
5470         pctx.spec->image_name = dup_token(&buf, NULL);
5471         if (!pctx.spec->image_name)
5472                 goto out_mem;
5473         if (!*pctx.spec->image_name) {
5474                 rbd_warn(NULL, "no image name provided");
5475                 goto out_err;
5476         }
5477
5478         /*
5479          * Snapshot name is optional; default is to use "-"
5480          * (indicating the head/no snapshot).
5481          */
5482         len = next_token(&buf);
5483         if (!len) {
5484                 buf = RBD_SNAP_HEAD_NAME; /* No snapshot supplied */
5485                 len = sizeof (RBD_SNAP_HEAD_NAME) - 1;
5486         } else if (len > RBD_MAX_SNAP_NAME_LEN) {
5487                 ret = -ENAMETOOLONG;
5488                 goto out_err;
5489         }
5490         snap_name = kmemdup(buf, len + 1, GFP_KERNEL);
5491         if (!snap_name)
5492                 goto out_mem;
5493         *(snap_name + len) = '\0';
5494         pctx.spec->snap_name = snap_name;
5495
5496         /* Initialize all rbd options to the defaults */
5497
5498         pctx.opts = kzalloc(sizeof(*pctx.opts), GFP_KERNEL);
5499         if (!pctx.opts)
5500                 goto out_mem;
5501
5502         pctx.opts->read_only = RBD_READ_ONLY_DEFAULT;
5503         pctx.opts->queue_depth = RBD_QUEUE_DEPTH_DEFAULT;
5504         pctx.opts->alloc_size = RBD_ALLOC_SIZE_DEFAULT;
5505         pctx.opts->lock_timeout = RBD_LOCK_TIMEOUT_DEFAULT;
5506         pctx.opts->lock_on_read = RBD_LOCK_ON_READ_DEFAULT;
5507         pctx.opts->exclusive = RBD_EXCLUSIVE_DEFAULT;
5508         pctx.opts->trim = RBD_TRIM_DEFAULT;
5509
5510         copts = ceph_parse_options(options, mon_addrs,
5511                                    mon_addrs + mon_addrs_size - 1,
5512                                    parse_rbd_opts_token, &pctx);
5513         if (IS_ERR(copts)) {
5514                 ret = PTR_ERR(copts);
5515                 goto out_err;
5516         }
5517         kfree(options);
5518
5519         *ceph_opts = copts;
5520         *opts = pctx.opts;
5521         *rbd_spec = pctx.spec;
5522
5523         return 0;
5524 out_mem:
5525         ret = -ENOMEM;
5526 out_err:
5527         kfree(pctx.opts);
5528         rbd_spec_put(pctx.spec);
5529         kfree(options);
5530
5531         return ret;
5532 }
5533
5534 static void rbd_dev_image_unlock(struct rbd_device *rbd_dev)
5535 {
5536         down_write(&rbd_dev->lock_rwsem);
5537         if (__rbd_is_lock_owner(rbd_dev))
5538                 rbd_unlock(rbd_dev);
5539         up_write(&rbd_dev->lock_rwsem);
5540 }
5541
5542 static int rbd_add_acquire_lock(struct rbd_device *rbd_dev)
5543 {
5544         int ret;
5545
5546         if (!(rbd_dev->header.features & RBD_FEATURE_EXCLUSIVE_LOCK)) {
5547                 rbd_warn(rbd_dev, "exclusive-lock feature is not enabled");
5548                 return -EINVAL;
5549         }
5550
5551         /* FIXME: "rbd map --exclusive" should be in interruptible */
5552         down_read(&rbd_dev->lock_rwsem);
5553         ret = rbd_wait_state_locked(rbd_dev, true);
5554         up_read(&rbd_dev->lock_rwsem);
5555         if (ret) {
5556                 rbd_warn(rbd_dev, "failed to acquire exclusive lock");
5557                 return -EROFS;
5558         }
5559
5560         return 0;
5561 }
5562
5563 /*
5564  * An rbd format 2 image has a unique identifier, distinct from the
5565  * name given to it by the user.  Internally, that identifier is
5566  * what's used to specify the names of objects related to the image.
5567  *
5568  * A special "rbd id" object is used to map an rbd image name to its
5569  * id.  If that object doesn't exist, then there is no v2 rbd image
5570  * with the supplied name.
5571  *
5572  * This function will record the given rbd_dev's image_id field if
5573  * it can be determined, and in that case will return 0.  If any
5574  * errors occur a negative errno will be returned and the rbd_dev's
5575  * image_id field will be unchanged (and should be NULL).
5576  */
5577 static int rbd_dev_image_id(struct rbd_device *rbd_dev)
5578 {
5579         int ret;
5580         size_t size;
5581         CEPH_DEFINE_OID_ONSTACK(oid);
5582         void *response;
5583         char *image_id;
5584
5585         /*
5586          * When probing a parent image, the image id is already
5587          * known (and the image name likely is not).  There's no
5588          * need to fetch the image id again in this case.  We
5589          * do still need to set the image format though.
5590          */
5591         if (rbd_dev->spec->image_id) {
5592                 rbd_dev->image_format = *rbd_dev->spec->image_id ? 2 : 1;
5593
5594                 return 0;
5595         }
5596
5597         /*
5598          * First, see if the format 2 image id file exists, and if
5599          * so, get the image's persistent id from it.
5600          */
5601         ret = ceph_oid_aprintf(&oid, GFP_KERNEL, "%s%s", RBD_ID_PREFIX,
5602                                rbd_dev->spec->image_name);
5603         if (ret)
5604                 return ret;
5605
5606         dout("rbd id object name is %s\n", oid.name);
5607
5608         /* Response will be an encoded string, which includes a length */
5609
5610         size = sizeof (__le32) + RBD_IMAGE_ID_LEN_MAX;
5611         response = kzalloc(size, GFP_NOIO);
5612         if (!response) {
5613                 ret = -ENOMEM;
5614                 goto out;
5615         }
5616
5617         /* If it doesn't exist we'll assume it's a format 1 image */
5618
5619         ret = rbd_obj_method_sync(rbd_dev, &oid, &rbd_dev->header_oloc,
5620                                   "get_id", NULL, 0,
5621                                   response, RBD_IMAGE_ID_LEN_MAX);
5622         dout("%s: rbd_obj_method_sync returned %d\n", __func__, ret);
5623         if (ret == -ENOENT) {
5624                 image_id = kstrdup("", GFP_KERNEL);
5625                 ret = image_id ? 0 : -ENOMEM;
5626                 if (!ret)
5627                         rbd_dev->image_format = 1;
5628         } else if (ret >= 0) {
5629                 void *p = response;
5630
5631                 image_id = ceph_extract_encoded_string(&p, p + ret,
5632                                                 NULL, GFP_NOIO);
5633                 ret = PTR_ERR_OR_ZERO(image_id);
5634                 if (!ret)
5635                         rbd_dev->image_format = 2;
5636         }
5637
5638         if (!ret) {
5639                 rbd_dev->spec->image_id = image_id;
5640                 dout("image_id is %s\n", image_id);
5641         }
5642 out:
5643         kfree(response);
5644         ceph_oid_destroy(&oid);
5645         return ret;
5646 }
5647
5648 /*
5649  * Undo whatever state changes are made by v1 or v2 header info
5650  * call.
5651  */
5652 static void rbd_dev_unprobe(struct rbd_device *rbd_dev)
5653 {
5654         struct rbd_image_header *header;
5655
5656         rbd_dev_parent_put(rbd_dev);
5657
5658         /* Free dynamic fields from the header, then zero it out */
5659
5660         header = &rbd_dev->header;
5661         ceph_put_snap_context(header->snapc);
5662         kfree(header->snap_sizes);
5663         kfree(header->snap_names);
5664         kfree(header->object_prefix);
5665         memset(header, 0, sizeof (*header));
5666 }
5667
5668 static int rbd_dev_v2_header_onetime(struct rbd_device *rbd_dev)
5669 {
5670         int ret;
5671
5672         ret = rbd_dev_v2_object_prefix(rbd_dev);
5673         if (ret)
5674                 goto out_err;
5675
5676         /*
5677          * Get the and check features for the image.  Currently the
5678          * features are assumed to never change.
5679          */
5680         ret = rbd_dev_v2_features(rbd_dev);
5681         if (ret)
5682                 goto out_err;
5683
5684         /* If the image supports fancy striping, get its parameters */
5685
5686         if (rbd_dev->header.features & RBD_FEATURE_STRIPINGV2) {
5687                 ret = rbd_dev_v2_striping_info(rbd_dev);
5688                 if (ret < 0)
5689                         goto out_err;
5690         }
5691
5692         if (rbd_dev->header.features & RBD_FEATURE_DATA_POOL) {
5693                 ret = rbd_dev_v2_data_pool(rbd_dev);
5694                 if (ret)
5695                         goto out_err;
5696         }
5697
5698         rbd_init_layout(rbd_dev);
5699         return 0;
5700
5701 out_err:
5702         rbd_dev->header.features = 0;
5703         kfree(rbd_dev->header.object_prefix);
5704         rbd_dev->header.object_prefix = NULL;
5705         return ret;
5706 }
5707
5708 /*
5709  * @depth is rbd_dev_image_probe() -> rbd_dev_probe_parent() ->
5710  * rbd_dev_image_probe() recursion depth, which means it's also the
5711  * length of the already discovered part of the parent chain.
5712  */
5713 static int rbd_dev_probe_parent(struct rbd_device *rbd_dev, int depth)
5714 {
5715         struct rbd_device *parent = NULL;
5716         int ret;
5717
5718         if (!rbd_dev->parent_spec)
5719                 return 0;
5720
5721         if (++depth > RBD_MAX_PARENT_CHAIN_LEN) {
5722                 pr_info("parent chain is too long (%d)\n", depth);
5723                 ret = -EINVAL;
5724                 goto out_err;
5725         }
5726
5727         parent = __rbd_dev_create(rbd_dev->rbd_client, rbd_dev->parent_spec);
5728         if (!parent) {
5729                 ret = -ENOMEM;
5730                 goto out_err;
5731         }
5732
5733         /*
5734          * Images related by parent/child relationships always share
5735          * rbd_client and spec/parent_spec, so bump their refcounts.
5736          */
5737         __rbd_get_client(rbd_dev->rbd_client);
5738         rbd_spec_get(rbd_dev->parent_spec);
5739
5740         ret = rbd_dev_image_probe(parent, depth);
5741         if (ret < 0)
5742                 goto out_err;
5743
5744         rbd_dev->parent = parent;
5745         atomic_set(&rbd_dev->parent_ref, 1);
5746         return 0;
5747
5748 out_err:
5749         rbd_dev_unparent(rbd_dev);
5750         rbd_dev_destroy(parent);
5751         return ret;
5752 }
5753
5754 static void rbd_dev_device_release(struct rbd_device *rbd_dev)
5755 {
5756         clear_bit(RBD_DEV_FLAG_EXISTS, &rbd_dev->flags);
5757         rbd_dev_mapping_clear(rbd_dev);
5758         rbd_free_disk(rbd_dev);
5759         if (!single_major)
5760                 unregister_blkdev(rbd_dev->major, rbd_dev->name);
5761 }
5762
5763 /*
5764  * rbd_dev->header_rwsem must be locked for write and will be unlocked
5765  * upon return.
5766  */
5767 static int rbd_dev_device_setup(struct rbd_device *rbd_dev)
5768 {
5769         int ret;
5770
5771         /* Record our major and minor device numbers. */
5772
5773         if (!single_major) {
5774                 ret = register_blkdev(0, rbd_dev->name);
5775                 if (ret < 0)
5776                         goto err_out_unlock;
5777
5778                 rbd_dev->major = ret;
5779                 rbd_dev->minor = 0;
5780         } else {
5781                 rbd_dev->major = rbd_major;
5782                 rbd_dev->minor = rbd_dev_id_to_minor(rbd_dev->dev_id);
5783         }
5784
5785         /* Set up the blkdev mapping. */
5786
5787         ret = rbd_init_disk(rbd_dev);
5788         if (ret)
5789                 goto err_out_blkdev;
5790
5791         ret = rbd_dev_mapping_set(rbd_dev);
5792         if (ret)
5793                 goto err_out_disk;
5794
5795         set_capacity(rbd_dev->disk, rbd_dev->mapping.size / SECTOR_SIZE);
5796         set_disk_ro(rbd_dev->disk, rbd_dev->opts->read_only);
5797
5798         ret = dev_set_name(&rbd_dev->dev, "%d", rbd_dev->dev_id);
5799         if (ret)
5800                 goto err_out_mapping;
5801
5802         set_bit(RBD_DEV_FLAG_EXISTS, &rbd_dev->flags);
5803         up_write(&rbd_dev->header_rwsem);
5804         return 0;
5805
5806 err_out_mapping:
5807         rbd_dev_mapping_clear(rbd_dev);
5808 err_out_disk:
5809         rbd_free_disk(rbd_dev);
5810 err_out_blkdev:
5811         if (!single_major)
5812                 unregister_blkdev(rbd_dev->major, rbd_dev->name);
5813 err_out_unlock:
5814         up_write(&rbd_dev->header_rwsem);
5815         return ret;
5816 }
5817
5818 static int rbd_dev_header_name(struct rbd_device *rbd_dev)
5819 {
5820         struct rbd_spec *spec = rbd_dev->spec;
5821         int ret;
5822
5823         /* Record the header object name for this rbd image. */
5824
5825         rbd_assert(rbd_image_format_valid(rbd_dev->image_format));
5826         if (rbd_dev->image_format == 1)
5827                 ret = ceph_oid_aprintf(&rbd_dev->header_oid, GFP_KERNEL, "%s%s",
5828                                        spec->image_name, RBD_SUFFIX);
5829         else
5830                 ret = ceph_oid_aprintf(&rbd_dev->header_oid, GFP_KERNEL, "%s%s",
5831                                        RBD_HEADER_PREFIX, spec->image_id);
5832
5833         return ret;
5834 }
5835
5836 static void rbd_dev_image_release(struct rbd_device *rbd_dev)
5837 {
5838         rbd_dev_unprobe(rbd_dev);
5839         if (rbd_dev->opts)
5840                 rbd_unregister_watch(rbd_dev);
5841         rbd_dev->image_format = 0;
5842         kfree(rbd_dev->spec->image_id);
5843         rbd_dev->spec->image_id = NULL;
5844 }
5845
5846 /*
5847  * Probe for the existence of the header object for the given rbd
5848  * device.  If this image is the one being mapped (i.e., not a
5849  * parent), initiate a watch on its header object before using that
5850  * object to get detailed information about the rbd image.
5851  */
5852 static int rbd_dev_image_probe(struct rbd_device *rbd_dev, int depth)
5853 {
5854         int ret;
5855
5856         /*
5857          * Get the id from the image id object.  Unless there's an
5858          * error, rbd_dev->spec->image_id will be filled in with
5859          * a dynamically-allocated string, and rbd_dev->image_format
5860          * will be set to either 1 or 2.
5861          */
5862         ret = rbd_dev_image_id(rbd_dev);
5863         if (ret)
5864                 return ret;
5865
5866         ret = rbd_dev_header_name(rbd_dev);
5867         if (ret)
5868                 goto err_out_format;
5869
5870         if (!depth) {
5871                 ret = rbd_register_watch(rbd_dev);
5872                 if (ret) {
5873                         if (ret == -ENOENT)
5874                                 pr_info("image %s/%s%s%s does not exist\n",
5875                                         rbd_dev->spec->pool_name,
5876                                         rbd_dev->spec->pool_ns ?: "",
5877                                         rbd_dev->spec->pool_ns ? "/" : "",
5878                                         rbd_dev->spec->image_name);
5879                         goto err_out_format;
5880                 }
5881         }
5882
5883         ret = rbd_dev_header_info(rbd_dev);
5884         if (ret)
5885                 goto err_out_watch;
5886
5887         /*
5888          * If this image is the one being mapped, we have pool name and
5889          * id, image name and id, and snap name - need to fill snap id.
5890          * Otherwise this is a parent image, identified by pool, image
5891          * and snap ids - need to fill in names for those ids.
5892          */
5893         if (!depth)
5894                 ret = rbd_spec_fill_snap_id(rbd_dev);
5895         else
5896                 ret = rbd_spec_fill_names(rbd_dev);
5897         if (ret) {
5898                 if (ret == -ENOENT)
5899                         pr_info("snap %s/%s%s%s@%s does not exist\n",
5900                                 rbd_dev->spec->pool_name,
5901                                 rbd_dev->spec->pool_ns ?: "",
5902                                 rbd_dev->spec->pool_ns ? "/" : "",
5903                                 rbd_dev->spec->image_name,
5904                                 rbd_dev->spec->snap_name);
5905                 goto err_out_probe;
5906         }
5907
5908         if (rbd_dev->header.features & RBD_FEATURE_LAYERING) {
5909                 ret = rbd_dev_v2_parent_info(rbd_dev);
5910                 if (ret)
5911                         goto err_out_probe;
5912         }
5913
5914         ret = rbd_dev_probe_parent(rbd_dev, depth);
5915         if (ret)
5916                 goto err_out_probe;
5917
5918         dout("discovered format %u image, header name is %s\n",
5919                 rbd_dev->image_format, rbd_dev->header_oid.name);
5920         return 0;
5921
5922 err_out_probe:
5923         rbd_dev_unprobe(rbd_dev);
5924 err_out_watch:
5925         if (!depth)
5926                 rbd_unregister_watch(rbd_dev);
5927 err_out_format:
5928         rbd_dev->image_format = 0;
5929         kfree(rbd_dev->spec->image_id);
5930         rbd_dev->spec->image_id = NULL;
5931         return ret;
5932 }
5933
5934 static ssize_t do_rbd_add(struct bus_type *bus,
5935                           const char *buf,
5936                           size_t count)
5937 {
5938         struct rbd_device *rbd_dev = NULL;
5939         struct ceph_options *ceph_opts = NULL;
5940         struct rbd_options *rbd_opts = NULL;
5941         struct rbd_spec *spec = NULL;
5942         struct rbd_client *rbdc;
5943         int rc;
5944
5945         if (!try_module_get(THIS_MODULE))
5946                 return -ENODEV;
5947
5948         /* parse add command */
5949         rc = rbd_add_parse_args(buf, &ceph_opts, &rbd_opts, &spec);
5950         if (rc < 0)
5951                 goto out;
5952
5953         rbdc = rbd_get_client(ceph_opts);
5954         if (IS_ERR(rbdc)) {
5955                 rc = PTR_ERR(rbdc);
5956                 goto err_out_args;
5957         }
5958
5959         /* pick the pool */
5960         rc = ceph_pg_poolid_by_name(rbdc->client->osdc.osdmap, spec->pool_name);
5961         if (rc < 0) {
5962                 if (rc == -ENOENT)
5963                         pr_info("pool %s does not exist\n", spec->pool_name);
5964                 goto err_out_client;
5965         }
5966         spec->pool_id = (u64)rc;
5967
5968         rbd_dev = rbd_dev_create(rbdc, spec, rbd_opts);
5969         if (!rbd_dev) {
5970                 rc = -ENOMEM;
5971                 goto err_out_client;
5972         }
5973         rbdc = NULL;            /* rbd_dev now owns this */
5974         spec = NULL;            /* rbd_dev now owns this */
5975         rbd_opts = NULL;        /* rbd_dev now owns this */
5976
5977         rbd_dev->config_info = kstrdup(buf, GFP_KERNEL);
5978         if (!rbd_dev->config_info) {
5979                 rc = -ENOMEM;
5980                 goto err_out_rbd_dev;
5981         }
5982
5983         down_write(&rbd_dev->header_rwsem);
5984         rc = rbd_dev_image_probe(rbd_dev, 0);
5985         if (rc < 0) {
5986                 up_write(&rbd_dev->header_rwsem);
5987                 goto err_out_rbd_dev;
5988         }
5989
5990         /* If we are mapping a snapshot it must be marked read-only */
5991         if (rbd_dev->spec->snap_id != CEPH_NOSNAP)
5992                 rbd_dev->opts->read_only = true;
5993
5994         if (rbd_dev->opts->alloc_size > rbd_dev->layout.object_size) {
5995                 rbd_warn(rbd_dev, "alloc_size adjusted to %u",
5996                          rbd_dev->layout.object_size);
5997                 rbd_dev->opts->alloc_size = rbd_dev->layout.object_size;
5998         }
5999
6000         rc = rbd_dev_device_setup(rbd_dev);
6001         if (rc)
6002                 goto err_out_image_probe;
6003
6004         if (rbd_dev->opts->exclusive) {
6005                 rc = rbd_add_acquire_lock(rbd_dev);
6006                 if (rc)
6007                         goto err_out_device_setup;
6008         }
6009
6010         /* Everything's ready.  Announce the disk to the world. */
6011
6012         rc = device_add(&rbd_dev->dev);
6013         if (rc)
6014                 goto err_out_image_lock;
6015
6016         add_disk(rbd_dev->disk);
6017         /* see rbd_init_disk() */
6018         blk_put_queue(rbd_dev->disk->queue);
6019
6020         spin_lock(&rbd_dev_list_lock);
6021         list_add_tail(&rbd_dev->node, &rbd_dev_list);
6022         spin_unlock(&rbd_dev_list_lock);
6023
6024         pr_info("%s: capacity %llu features 0x%llx\n", rbd_dev->disk->disk_name,
6025                 (unsigned long long)get_capacity(rbd_dev->disk) << SECTOR_SHIFT,
6026                 rbd_dev->header.features);
6027         rc = count;
6028 out:
6029         module_put(THIS_MODULE);
6030         return rc;
6031
6032 err_out_image_lock:
6033         rbd_dev_image_unlock(rbd_dev);
6034 err_out_device_setup:
6035         rbd_dev_device_release(rbd_dev);
6036 err_out_image_probe:
6037         rbd_dev_image_release(rbd_dev);
6038 err_out_rbd_dev:
6039         rbd_dev_destroy(rbd_dev);
6040 err_out_client:
6041         rbd_put_client(rbdc);
6042 err_out_args:
6043         rbd_spec_put(spec);
6044         kfree(rbd_opts);
6045         goto out;
6046 }
6047
6048 static ssize_t rbd_add(struct bus_type *bus,
6049                        const char *buf,
6050                        size_t count)
6051 {
6052         if (single_major)
6053                 return -EINVAL;
6054
6055         return do_rbd_add(bus, buf, count);
6056 }
6057
6058 static ssize_t rbd_add_single_major(struct bus_type *bus,
6059                                     const char *buf,
6060                                     size_t count)
6061 {
6062         return do_rbd_add(bus, buf, count);
6063 }
6064
6065 static void rbd_dev_remove_parent(struct rbd_device *rbd_dev)
6066 {
6067         while (rbd_dev->parent) {
6068                 struct rbd_device *first = rbd_dev;
6069                 struct rbd_device *second = first->parent;
6070                 struct rbd_device *third;
6071
6072                 /*
6073                  * Follow to the parent with no grandparent and
6074                  * remove it.
6075                  */
6076                 while (second && (third = second->parent)) {
6077                         first = second;
6078                         second = third;
6079                 }
6080                 rbd_assert(second);
6081                 rbd_dev_image_release(second);
6082                 rbd_dev_destroy(second);
6083                 first->parent = NULL;
6084                 first->parent_overlap = 0;
6085
6086                 rbd_assert(first->parent_spec);
6087                 rbd_spec_put(first->parent_spec);
6088                 first->parent_spec = NULL;
6089         }
6090 }
6091
6092 static ssize_t do_rbd_remove(struct bus_type *bus,
6093                              const char *buf,
6094                              size_t count)
6095 {
6096         struct rbd_device *rbd_dev = NULL;
6097         struct list_head *tmp;
6098         int dev_id;
6099         char opt_buf[6];
6100         bool force = false;
6101         int ret;
6102
6103         dev_id = -1;
6104         opt_buf[0] = '\0';
6105         sscanf(buf, "%d %5s", &dev_id, opt_buf);
6106         if (dev_id < 0) {
6107                 pr_err("dev_id out of range\n");
6108                 return -EINVAL;
6109         }
6110         if (opt_buf[0] != '\0') {
6111                 if (!strcmp(opt_buf, "force")) {
6112                         force = true;
6113                 } else {
6114                         pr_err("bad remove option at '%s'\n", opt_buf);
6115                         return -EINVAL;
6116                 }
6117         }
6118
6119         ret = -ENOENT;
6120         spin_lock(&rbd_dev_list_lock);
6121         list_for_each(tmp, &rbd_dev_list) {
6122                 rbd_dev = list_entry(tmp, struct rbd_device, node);
6123                 if (rbd_dev->dev_id == dev_id) {
6124                         ret = 0;
6125                         break;
6126                 }
6127         }
6128         if (!ret) {
6129                 spin_lock_irq(&rbd_dev->lock);
6130                 if (rbd_dev->open_count && !force)
6131                         ret = -EBUSY;
6132                 else if (test_and_set_bit(RBD_DEV_FLAG_REMOVING,
6133                                           &rbd_dev->flags))
6134                         ret = -EINPROGRESS;
6135                 spin_unlock_irq(&rbd_dev->lock);
6136         }
6137         spin_unlock(&rbd_dev_list_lock);
6138         if (ret)
6139                 return ret;
6140
6141         if (force) {
6142                 /*
6143                  * Prevent new IO from being queued and wait for existing
6144                  * IO to complete/fail.
6145                  */
6146                 blk_mq_freeze_queue(rbd_dev->disk->queue);
6147                 blk_set_queue_dying(rbd_dev->disk->queue);
6148         }
6149
6150         del_gendisk(rbd_dev->disk);
6151         spin_lock(&rbd_dev_list_lock);
6152         list_del_init(&rbd_dev->node);
6153         spin_unlock(&rbd_dev_list_lock);
6154         device_del(&rbd_dev->dev);
6155
6156         rbd_dev_image_unlock(rbd_dev);
6157         rbd_dev_device_release(rbd_dev);
6158         rbd_dev_image_release(rbd_dev);
6159         rbd_dev_destroy(rbd_dev);
6160         return count;
6161 }
6162
6163 static ssize_t rbd_remove(struct bus_type *bus,
6164                           const char *buf,
6165                           size_t count)
6166 {
6167         if (single_major)
6168                 return -EINVAL;
6169
6170         return do_rbd_remove(bus, buf, count);
6171 }
6172
6173 static ssize_t rbd_remove_single_major(struct bus_type *bus,
6174                                        const char *buf,
6175                                        size_t count)
6176 {
6177         return do_rbd_remove(bus, buf, count);
6178 }
6179
6180 /*
6181  * create control files in sysfs
6182  * /sys/bus/rbd/...
6183  */
6184 static int __init rbd_sysfs_init(void)
6185 {
6186         int ret;
6187
6188         ret = device_register(&rbd_root_dev);
6189         if (ret < 0)
6190                 return ret;
6191
6192         ret = bus_register(&rbd_bus_type);
6193         if (ret < 0)
6194                 device_unregister(&rbd_root_dev);
6195
6196         return ret;
6197 }
6198
6199 static void __exit rbd_sysfs_cleanup(void)
6200 {
6201         bus_unregister(&rbd_bus_type);
6202         device_unregister(&rbd_root_dev);
6203 }
6204
6205 static int __init rbd_slab_init(void)
6206 {
6207         rbd_assert(!rbd_img_request_cache);
6208         rbd_img_request_cache = KMEM_CACHE(rbd_img_request, 0);
6209         if (!rbd_img_request_cache)
6210                 return -ENOMEM;
6211
6212         rbd_assert(!rbd_obj_request_cache);
6213         rbd_obj_request_cache = KMEM_CACHE(rbd_obj_request, 0);
6214         if (!rbd_obj_request_cache)
6215                 goto out_err;
6216
6217         return 0;
6218
6219 out_err:
6220         kmem_cache_destroy(rbd_img_request_cache);
6221         rbd_img_request_cache = NULL;
6222         return -ENOMEM;
6223 }
6224
6225 static void rbd_slab_exit(void)
6226 {
6227         rbd_assert(rbd_obj_request_cache);
6228         kmem_cache_destroy(rbd_obj_request_cache);
6229         rbd_obj_request_cache = NULL;
6230
6231         rbd_assert(rbd_img_request_cache);
6232         kmem_cache_destroy(rbd_img_request_cache);
6233         rbd_img_request_cache = NULL;
6234 }
6235
6236 static int __init rbd_init(void)
6237 {
6238         int rc;
6239
6240         if (!libceph_compatible(NULL)) {
6241                 rbd_warn(NULL, "libceph incompatibility (quitting)");
6242                 return -EINVAL;
6243         }
6244
6245         rc = rbd_slab_init();
6246         if (rc)
6247                 return rc;
6248
6249         /*
6250          * The number of active work items is limited by the number of
6251          * rbd devices * queue depth, so leave @max_active at default.
6252          */
6253         rbd_wq = alloc_workqueue(RBD_DRV_NAME, WQ_MEM_RECLAIM, 0);
6254         if (!rbd_wq) {
6255                 rc = -ENOMEM;
6256                 goto err_out_slab;
6257         }
6258
6259         if (single_major) {
6260                 rbd_major = register_blkdev(0, RBD_DRV_NAME);
6261                 if (rbd_major < 0) {
6262                         rc = rbd_major;
6263                         goto err_out_wq;
6264                 }
6265         }
6266
6267         rc = rbd_sysfs_init();
6268         if (rc)
6269                 goto err_out_blkdev;
6270
6271         if (single_major)
6272                 pr_info("loaded (major %d)\n", rbd_major);
6273         else
6274                 pr_info("loaded\n");
6275
6276         return 0;
6277
6278 err_out_blkdev:
6279         if (single_major)
6280                 unregister_blkdev(rbd_major, RBD_DRV_NAME);
6281 err_out_wq:
6282         destroy_workqueue(rbd_wq);
6283 err_out_slab:
6284         rbd_slab_exit();
6285         return rc;
6286 }
6287
6288 static void __exit rbd_exit(void)
6289 {
6290         ida_destroy(&rbd_dev_id_ida);
6291         rbd_sysfs_cleanup();
6292         if (single_major)
6293                 unregister_blkdev(rbd_major, RBD_DRV_NAME);
6294         destroy_workqueue(rbd_wq);
6295         rbd_slab_exit();
6296 }
6297
6298 module_init(rbd_init);
6299 module_exit(rbd_exit);
6300
6301 MODULE_AUTHOR("Alex Elder <elder@inktank.com>");
6302 MODULE_AUTHOR("Sage Weil <sage@newdream.net>");
6303 MODULE_AUTHOR("Yehuda Sadeh <yehuda@hq.newdream.net>");
6304 /* following authorship retained from original osdblk.c */
6305 MODULE_AUTHOR("Jeff Garzik <jeff@garzik.org>");
6306
6307 MODULE_DESCRIPTION("RADOS Block Device (RBD) driver");
6308 MODULE_LICENSE("GPL");