Merge tag 'ceph-for-5.1-rc1' of git://github.com/ceph/ceph-client
[sfrench/cifs-2.6.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_DEEP_FLATTEN        (1ULL<<5)
119 #define RBD_FEATURE_DATA_POOL           (1ULL<<7)
120 #define RBD_FEATURE_OPERATIONS          (1ULL<<8)
121
122 #define RBD_FEATURES_ALL        (RBD_FEATURE_LAYERING |         \
123                                  RBD_FEATURE_STRIPINGV2 |       \
124                                  RBD_FEATURE_EXCLUSIVE_LOCK |   \
125                                  RBD_FEATURE_DEEP_FLATTEN |     \
126                                  RBD_FEATURE_DATA_POOL |        \
127                                  RBD_FEATURE_OPERATIONS)
128
129 /* Features supported by this (client software) implementation. */
130
131 #define RBD_FEATURES_SUPPORTED  (RBD_FEATURES_ALL)
132
133 /*
134  * An RBD device name will be "rbd#", where the "rbd" comes from
135  * RBD_DRV_NAME above, and # is a unique integer identifier.
136  */
137 #define DEV_NAME_LEN            32
138
139 /*
140  * block device image metadata (in-memory version)
141  */
142 struct rbd_image_header {
143         /* These six fields never change for a given rbd image */
144         char *object_prefix;
145         __u8 obj_order;
146         u64 stripe_unit;
147         u64 stripe_count;
148         s64 data_pool_id;
149         u64 features;           /* Might be changeable someday? */
150
151         /* The remaining fields need to be updated occasionally */
152         u64 image_size;
153         struct ceph_snap_context *snapc;
154         char *snap_names;       /* format 1 only */
155         u64 *snap_sizes;        /* format 1 only */
156 };
157
158 /*
159  * An rbd image specification.
160  *
161  * The tuple (pool_id, image_id, snap_id) is sufficient to uniquely
162  * identify an image.  Each rbd_dev structure includes a pointer to
163  * an rbd_spec structure that encapsulates this identity.
164  *
165  * Each of the id's in an rbd_spec has an associated name.  For a
166  * user-mapped image, the names are supplied and the id's associated
167  * with them are looked up.  For a layered image, a parent image is
168  * defined by the tuple, and the names are looked up.
169  *
170  * An rbd_dev structure contains a parent_spec pointer which is
171  * non-null if the image it represents is a child in a layered
172  * image.  This pointer will refer to the rbd_spec structure used
173  * by the parent rbd_dev for its own identity (i.e., the structure
174  * is shared between the parent and child).
175  *
176  * Since these structures are populated once, during the discovery
177  * phase of image construction, they are effectively immutable so
178  * we make no effort to synchronize access to them.
179  *
180  * Note that code herein does not assume the image name is known (it
181  * could be a null pointer).
182  */
183 struct rbd_spec {
184         u64             pool_id;
185         const char      *pool_name;
186         const char      *pool_ns;       /* NULL if default, never "" */
187
188         const char      *image_id;
189         const char      *image_name;
190
191         u64             snap_id;
192         const char      *snap_name;
193
194         struct kref     kref;
195 };
196
197 /*
198  * an instance of the client.  multiple devices may share an rbd client.
199  */
200 struct rbd_client {
201         struct ceph_client      *client;
202         struct kref             kref;
203         struct list_head        node;
204 };
205
206 struct rbd_img_request;
207
208 enum obj_request_type {
209         OBJ_REQUEST_NODATA = 1,
210         OBJ_REQUEST_BIO,        /* pointer into provided bio (list) */
211         OBJ_REQUEST_BVECS,      /* pointer into provided bio_vec array */
212         OBJ_REQUEST_OWN_BVECS,  /* private bio_vec array, doesn't own pages */
213 };
214
215 enum obj_operation_type {
216         OBJ_OP_READ = 1,
217         OBJ_OP_WRITE,
218         OBJ_OP_DISCARD,
219         OBJ_OP_ZEROOUT,
220 };
221
222 /*
223  * Writes go through the following state machine to deal with
224  * layering:
225  *
226  *            . . . . . RBD_OBJ_WRITE_GUARD. . . . . . . . . . . . . .
227  *            .                 |                                    .
228  *            .                 v                                    .
229  *            .    RBD_OBJ_WRITE_READ_FROM_PARENT. . .               .
230  *            .                 |                    .               .
231  *            .                 v                    v (deep-copyup  .
232  *    (image  .   RBD_OBJ_WRITE_COPYUP_EMPTY_SNAPC   .  not needed)  .
233  * flattened) v                 |                    .               .
234  *            .                 v                    .               .
235  *            . . . .RBD_OBJ_WRITE_COPYUP_OPS. . . . .      (copyup  .
236  *                              |                        not needed) v
237  *                              v                                    .
238  *                            done . . . . . . . . . . . . . . . . . .
239  *                              ^
240  *                              |
241  *                     RBD_OBJ_WRITE_FLAT
242  *
243  * Writes start in RBD_OBJ_WRITE_GUARD or _FLAT, depending on whether
244  * assert_exists guard is needed or not (in some cases it's not needed
245  * even if there is a parent).
246  */
247 enum rbd_obj_write_state {
248         RBD_OBJ_WRITE_FLAT = 1,
249         RBD_OBJ_WRITE_GUARD,
250         RBD_OBJ_WRITE_READ_FROM_PARENT,
251         RBD_OBJ_WRITE_COPYUP_EMPTY_SNAPC,
252         RBD_OBJ_WRITE_COPYUP_OPS,
253 };
254
255 struct rbd_obj_request {
256         struct ceph_object_extent ex;
257         union {
258                 bool                    tried_parent;   /* for reads */
259                 enum rbd_obj_write_state write_state;   /* for writes */
260         };
261
262         struct rbd_img_request  *img_request;
263         struct ceph_file_extent *img_extents;
264         u32                     num_img_extents;
265
266         union {
267                 struct ceph_bio_iter    bio_pos;
268                 struct {
269                         struct ceph_bvec_iter   bvec_pos;
270                         u32                     bvec_count;
271                         u32                     bvec_idx;
272                 };
273         };
274         struct bio_vec          *copyup_bvecs;
275         u32                     copyup_bvec_count;
276
277         struct ceph_osd_request *osd_req;
278
279         u64                     xferred;        /* bytes transferred */
280         int                     result;
281
282         struct kref             kref;
283 };
284
285 enum img_req_flags {
286         IMG_REQ_CHILD,          /* initiator: block = 0, child image = 1 */
287         IMG_REQ_LAYERED,        /* ENOENT handling: normal = 0, layered = 1 */
288 };
289
290 struct rbd_img_request {
291         struct rbd_device       *rbd_dev;
292         enum obj_operation_type op_type;
293         enum obj_request_type   data_type;
294         unsigned long           flags;
295         union {
296                 u64                     snap_id;        /* for reads */
297                 struct ceph_snap_context *snapc;        /* for writes */
298         };
299         union {
300                 struct request          *rq;            /* block request */
301                 struct rbd_obj_request  *obj_request;   /* obj req initiator */
302         };
303         spinlock_t              completion_lock;
304         u64                     xferred;/* aggregate bytes transferred */
305         int                     result; /* first nonzero obj_request result */
306
307         struct list_head        object_extents; /* obj_req.ex structs */
308         u32                     pending_count;
309
310         struct kref             kref;
311 };
312
313 #define for_each_obj_request(ireq, oreq) \
314         list_for_each_entry(oreq, &(ireq)->object_extents, ex.oe_item)
315 #define for_each_obj_request_safe(ireq, oreq, n) \
316         list_for_each_entry_safe(oreq, n, &(ireq)->object_extents, ex.oe_item)
317
318 enum rbd_watch_state {
319         RBD_WATCH_STATE_UNREGISTERED,
320         RBD_WATCH_STATE_REGISTERED,
321         RBD_WATCH_STATE_ERROR,
322 };
323
324 enum rbd_lock_state {
325         RBD_LOCK_STATE_UNLOCKED,
326         RBD_LOCK_STATE_LOCKED,
327         RBD_LOCK_STATE_RELEASING,
328 };
329
330 /* WatchNotify::ClientId */
331 struct rbd_client_id {
332         u64 gid;
333         u64 handle;
334 };
335
336 struct rbd_mapping {
337         u64                     size;
338         u64                     features;
339 };
340
341 /*
342  * a single device
343  */
344 struct rbd_device {
345         int                     dev_id;         /* blkdev unique id */
346
347         int                     major;          /* blkdev assigned major */
348         int                     minor;
349         struct gendisk          *disk;          /* blkdev's gendisk and rq */
350
351         u32                     image_format;   /* Either 1 or 2 */
352         struct rbd_client       *rbd_client;
353
354         char                    name[DEV_NAME_LEN]; /* blkdev name, e.g. rbd3 */
355
356         spinlock_t              lock;           /* queue, flags, open_count */
357
358         struct rbd_image_header header;
359         unsigned long           flags;          /* possibly lock protected */
360         struct rbd_spec         *spec;
361         struct rbd_options      *opts;
362         char                    *config_info;   /* add{,_single_major} string */
363
364         struct ceph_object_id   header_oid;
365         struct ceph_object_locator header_oloc;
366
367         struct ceph_file_layout layout;         /* used for all rbd requests */
368
369         struct mutex            watch_mutex;
370         enum rbd_watch_state    watch_state;
371         struct ceph_osd_linger_request *watch_handle;
372         u64                     watch_cookie;
373         struct delayed_work     watch_dwork;
374
375         struct rw_semaphore     lock_rwsem;
376         enum rbd_lock_state     lock_state;
377         char                    lock_cookie[32];
378         struct rbd_client_id    owner_cid;
379         struct work_struct      acquired_lock_work;
380         struct work_struct      released_lock_work;
381         struct delayed_work     lock_dwork;
382         struct work_struct      unlock_work;
383         wait_queue_head_t       lock_waitq;
384
385         struct workqueue_struct *task_wq;
386
387         struct rbd_spec         *parent_spec;
388         u64                     parent_overlap;
389         atomic_t                parent_ref;
390         struct rbd_device       *parent;
391
392         /* Block layer tags. */
393         struct blk_mq_tag_set   tag_set;
394
395         /* protects updating the header */
396         struct rw_semaphore     header_rwsem;
397
398         struct rbd_mapping      mapping;
399
400         struct list_head        node;
401
402         /* sysfs related */
403         struct device           dev;
404         unsigned long           open_count;     /* protected by lock */
405 };
406
407 /*
408  * Flag bits for rbd_dev->flags:
409  * - REMOVING (which is coupled with rbd_dev->open_count) is protected
410  *   by rbd_dev->lock
411  * - BLACKLISTED is protected by rbd_dev->lock_rwsem
412  */
413 enum rbd_dev_flags {
414         RBD_DEV_FLAG_EXISTS,    /* mapped snapshot has not been deleted */
415         RBD_DEV_FLAG_REMOVING,  /* this mapping is being removed */
416         RBD_DEV_FLAG_BLACKLISTED, /* our ceph_client is blacklisted */
417 };
418
419 static DEFINE_MUTEX(client_mutex);      /* Serialize client creation */
420
421 static LIST_HEAD(rbd_dev_list);    /* devices */
422 static DEFINE_SPINLOCK(rbd_dev_list_lock);
423
424 static LIST_HEAD(rbd_client_list);              /* clients */
425 static DEFINE_SPINLOCK(rbd_client_list_lock);
426
427 /* Slab caches for frequently-allocated structures */
428
429 static struct kmem_cache        *rbd_img_request_cache;
430 static struct kmem_cache        *rbd_obj_request_cache;
431
432 static int rbd_major;
433 static DEFINE_IDA(rbd_dev_id_ida);
434
435 static struct workqueue_struct *rbd_wq;
436
437 static struct ceph_snap_context rbd_empty_snapc = {
438         .nref = REFCOUNT_INIT(1),
439 };
440
441 /*
442  * single-major requires >= 0.75 version of userspace rbd utility.
443  */
444 static bool single_major = true;
445 module_param(single_major, bool, 0444);
446 MODULE_PARM_DESC(single_major, "Use a single major number for all rbd devices (default: true)");
447
448 static ssize_t add_store(struct bus_type *bus, const char *buf, size_t count);
449 static ssize_t remove_store(struct bus_type *bus, const char *buf,
450                             size_t count);
451 static ssize_t add_single_major_store(struct bus_type *bus, const char *buf,
452                                       size_t count);
453 static ssize_t remove_single_major_store(struct bus_type *bus, const char *buf,
454                                          size_t count);
455 static int rbd_dev_image_probe(struct rbd_device *rbd_dev, int depth);
456
457 static int rbd_dev_id_to_minor(int dev_id)
458 {
459         return dev_id << RBD_SINGLE_MAJOR_PART_SHIFT;
460 }
461
462 static int minor_to_rbd_dev_id(int minor)
463 {
464         return minor >> RBD_SINGLE_MAJOR_PART_SHIFT;
465 }
466
467 static bool __rbd_is_lock_owner(struct rbd_device *rbd_dev)
468 {
469         return rbd_dev->lock_state == RBD_LOCK_STATE_LOCKED ||
470                rbd_dev->lock_state == RBD_LOCK_STATE_RELEASING;
471 }
472
473 static bool rbd_is_lock_owner(struct rbd_device *rbd_dev)
474 {
475         bool is_lock_owner;
476
477         down_read(&rbd_dev->lock_rwsem);
478         is_lock_owner = __rbd_is_lock_owner(rbd_dev);
479         up_read(&rbd_dev->lock_rwsem);
480         return is_lock_owner;
481 }
482
483 static ssize_t supported_features_show(struct bus_type *bus, char *buf)
484 {
485         return sprintf(buf, "0x%llx\n", RBD_FEATURES_SUPPORTED);
486 }
487
488 static BUS_ATTR_WO(add);
489 static BUS_ATTR_WO(remove);
490 static BUS_ATTR_WO(add_single_major);
491 static BUS_ATTR_WO(remove_single_major);
492 static BUS_ATTR_RO(supported_features);
493
494 static struct attribute *rbd_bus_attrs[] = {
495         &bus_attr_add.attr,
496         &bus_attr_remove.attr,
497         &bus_attr_add_single_major.attr,
498         &bus_attr_remove_single_major.attr,
499         &bus_attr_supported_features.attr,
500         NULL,
501 };
502
503 static umode_t rbd_bus_is_visible(struct kobject *kobj,
504                                   struct attribute *attr, int index)
505 {
506         if (!single_major &&
507             (attr == &bus_attr_add_single_major.attr ||
508              attr == &bus_attr_remove_single_major.attr))
509                 return 0;
510
511         return attr->mode;
512 }
513
514 static const struct attribute_group rbd_bus_group = {
515         .attrs = rbd_bus_attrs,
516         .is_visible = rbd_bus_is_visible,
517 };
518 __ATTRIBUTE_GROUPS(rbd_bus);
519
520 static struct bus_type rbd_bus_type = {
521         .name           = "rbd",
522         .bus_groups     = rbd_bus_groups,
523 };
524
525 static void rbd_root_dev_release(struct device *dev)
526 {
527 }
528
529 static struct device rbd_root_dev = {
530         .init_name =    "rbd",
531         .release =      rbd_root_dev_release,
532 };
533
534 static __printf(2, 3)
535 void rbd_warn(struct rbd_device *rbd_dev, const char *fmt, ...)
536 {
537         struct va_format vaf;
538         va_list args;
539
540         va_start(args, fmt);
541         vaf.fmt = fmt;
542         vaf.va = &args;
543
544         if (!rbd_dev)
545                 printk(KERN_WARNING "%s: %pV\n", RBD_DRV_NAME, &vaf);
546         else if (rbd_dev->disk)
547                 printk(KERN_WARNING "%s: %s: %pV\n",
548                         RBD_DRV_NAME, rbd_dev->disk->disk_name, &vaf);
549         else if (rbd_dev->spec && rbd_dev->spec->image_name)
550                 printk(KERN_WARNING "%s: image %s: %pV\n",
551                         RBD_DRV_NAME, rbd_dev->spec->image_name, &vaf);
552         else if (rbd_dev->spec && rbd_dev->spec->image_id)
553                 printk(KERN_WARNING "%s: id %s: %pV\n",
554                         RBD_DRV_NAME, rbd_dev->spec->image_id, &vaf);
555         else    /* punt */
556                 printk(KERN_WARNING "%s: rbd_dev %p: %pV\n",
557                         RBD_DRV_NAME, rbd_dev, &vaf);
558         va_end(args);
559 }
560
561 #ifdef RBD_DEBUG
562 #define rbd_assert(expr)                                                \
563                 if (unlikely(!(expr))) {                                \
564                         printk(KERN_ERR "\nAssertion failure in %s() "  \
565                                                 "at line %d:\n\n"       \
566                                         "\trbd_assert(%s);\n\n",        \
567                                         __func__, __LINE__, #expr);     \
568                         BUG();                                          \
569                 }
570 #else /* !RBD_DEBUG */
571 #  define rbd_assert(expr)      ((void) 0)
572 #endif /* !RBD_DEBUG */
573
574 static void rbd_dev_remove_parent(struct rbd_device *rbd_dev);
575
576 static int rbd_dev_refresh(struct rbd_device *rbd_dev);
577 static int rbd_dev_v2_header_onetime(struct rbd_device *rbd_dev);
578 static int rbd_dev_header_info(struct rbd_device *rbd_dev);
579 static int rbd_dev_v2_parent_info(struct rbd_device *rbd_dev);
580 static const char *rbd_dev_v2_snap_name(struct rbd_device *rbd_dev,
581                                         u64 snap_id);
582 static int _rbd_dev_v2_snap_size(struct rbd_device *rbd_dev, u64 snap_id,
583                                 u8 *order, u64 *snap_size);
584 static int _rbd_dev_v2_snap_features(struct rbd_device *rbd_dev, u64 snap_id,
585                 u64 *snap_features);
586
587 static int rbd_open(struct block_device *bdev, fmode_t mode)
588 {
589         struct rbd_device *rbd_dev = bdev->bd_disk->private_data;
590         bool removing = false;
591
592         spin_lock_irq(&rbd_dev->lock);
593         if (test_bit(RBD_DEV_FLAG_REMOVING, &rbd_dev->flags))
594                 removing = true;
595         else
596                 rbd_dev->open_count++;
597         spin_unlock_irq(&rbd_dev->lock);
598         if (removing)
599                 return -ENOENT;
600
601         (void) get_device(&rbd_dev->dev);
602
603         return 0;
604 }
605
606 static void rbd_release(struct gendisk *disk, fmode_t mode)
607 {
608         struct rbd_device *rbd_dev = disk->private_data;
609         unsigned long open_count_before;
610
611         spin_lock_irq(&rbd_dev->lock);
612         open_count_before = rbd_dev->open_count--;
613         spin_unlock_irq(&rbd_dev->lock);
614         rbd_assert(open_count_before > 0);
615
616         put_device(&rbd_dev->dev);
617 }
618
619 static int rbd_ioctl_set_ro(struct rbd_device *rbd_dev, unsigned long arg)
620 {
621         int ro;
622
623         if (get_user(ro, (int __user *)arg))
624                 return -EFAULT;
625
626         /* Snapshots can't be marked read-write */
627         if (rbd_dev->spec->snap_id != CEPH_NOSNAP && !ro)
628                 return -EROFS;
629
630         /* Let blkdev_roset() handle it */
631         return -ENOTTY;
632 }
633
634 static int rbd_ioctl(struct block_device *bdev, fmode_t mode,
635                         unsigned int cmd, unsigned long arg)
636 {
637         struct rbd_device *rbd_dev = bdev->bd_disk->private_data;
638         int ret;
639
640         switch (cmd) {
641         case BLKROSET:
642                 ret = rbd_ioctl_set_ro(rbd_dev, arg);
643                 break;
644         default:
645                 ret = -ENOTTY;
646         }
647
648         return ret;
649 }
650
651 #ifdef CONFIG_COMPAT
652 static int rbd_compat_ioctl(struct block_device *bdev, fmode_t mode,
653                                 unsigned int cmd, unsigned long arg)
654 {
655         return rbd_ioctl(bdev, mode, cmd, arg);
656 }
657 #endif /* CONFIG_COMPAT */
658
659 static const struct block_device_operations rbd_bd_ops = {
660         .owner                  = THIS_MODULE,
661         .open                   = rbd_open,
662         .release                = rbd_release,
663         .ioctl                  = rbd_ioctl,
664 #ifdef CONFIG_COMPAT
665         .compat_ioctl           = rbd_compat_ioctl,
666 #endif
667 };
668
669 /*
670  * Initialize an rbd client instance.  Success or not, this function
671  * consumes ceph_opts.  Caller holds client_mutex.
672  */
673 static struct rbd_client *rbd_client_create(struct ceph_options *ceph_opts)
674 {
675         struct rbd_client *rbdc;
676         int ret = -ENOMEM;
677
678         dout("%s:\n", __func__);
679         rbdc = kmalloc(sizeof(struct rbd_client), GFP_KERNEL);
680         if (!rbdc)
681                 goto out_opt;
682
683         kref_init(&rbdc->kref);
684         INIT_LIST_HEAD(&rbdc->node);
685
686         rbdc->client = ceph_create_client(ceph_opts, rbdc);
687         if (IS_ERR(rbdc->client))
688                 goto out_rbdc;
689         ceph_opts = NULL; /* Now rbdc->client is responsible for ceph_opts */
690
691         ret = ceph_open_session(rbdc->client);
692         if (ret < 0)
693                 goto out_client;
694
695         spin_lock(&rbd_client_list_lock);
696         list_add_tail(&rbdc->node, &rbd_client_list);
697         spin_unlock(&rbd_client_list_lock);
698
699         dout("%s: rbdc %p\n", __func__, rbdc);
700
701         return rbdc;
702 out_client:
703         ceph_destroy_client(rbdc->client);
704 out_rbdc:
705         kfree(rbdc);
706 out_opt:
707         if (ceph_opts)
708                 ceph_destroy_options(ceph_opts);
709         dout("%s: error %d\n", __func__, ret);
710
711         return ERR_PTR(ret);
712 }
713
714 static struct rbd_client *__rbd_get_client(struct rbd_client *rbdc)
715 {
716         kref_get(&rbdc->kref);
717
718         return rbdc;
719 }
720
721 /*
722  * Find a ceph client with specific addr and configuration.  If
723  * found, bump its reference count.
724  */
725 static struct rbd_client *rbd_client_find(struct ceph_options *ceph_opts)
726 {
727         struct rbd_client *client_node;
728         bool found = false;
729
730         if (ceph_opts->flags & CEPH_OPT_NOSHARE)
731                 return NULL;
732
733         spin_lock(&rbd_client_list_lock);
734         list_for_each_entry(client_node, &rbd_client_list, node) {
735                 if (!ceph_compare_options(ceph_opts, client_node->client)) {
736                         __rbd_get_client(client_node);
737
738                         found = true;
739                         break;
740                 }
741         }
742         spin_unlock(&rbd_client_list_lock);
743
744         return found ? client_node : NULL;
745 }
746
747 /*
748  * (Per device) rbd map options
749  */
750 enum {
751         Opt_queue_depth,
752         Opt_alloc_size,
753         Opt_lock_timeout,
754         Opt_last_int,
755         /* int args above */
756         Opt_pool_ns,
757         Opt_last_string,
758         /* string args above */
759         Opt_read_only,
760         Opt_read_write,
761         Opt_lock_on_read,
762         Opt_exclusive,
763         Opt_notrim,
764         Opt_err
765 };
766
767 static match_table_t rbd_opts_tokens = {
768         {Opt_queue_depth, "queue_depth=%d"},
769         {Opt_alloc_size, "alloc_size=%d"},
770         {Opt_lock_timeout, "lock_timeout=%d"},
771         /* int args above */
772         {Opt_pool_ns, "_pool_ns=%s"},
773         /* string args above */
774         {Opt_read_only, "read_only"},
775         {Opt_read_only, "ro"},          /* Alternate spelling */
776         {Opt_read_write, "read_write"},
777         {Opt_read_write, "rw"},         /* Alternate spelling */
778         {Opt_lock_on_read, "lock_on_read"},
779         {Opt_exclusive, "exclusive"},
780         {Opt_notrim, "notrim"},
781         {Opt_err, NULL}
782 };
783
784 struct rbd_options {
785         int     queue_depth;
786         int     alloc_size;
787         unsigned long   lock_timeout;
788         bool    read_only;
789         bool    lock_on_read;
790         bool    exclusive;
791         bool    trim;
792 };
793
794 #define RBD_QUEUE_DEPTH_DEFAULT BLKDEV_MAX_RQ
795 #define RBD_ALLOC_SIZE_DEFAULT  (64 * 1024)
796 #define RBD_LOCK_TIMEOUT_DEFAULT 0  /* no timeout */
797 #define RBD_READ_ONLY_DEFAULT   false
798 #define RBD_LOCK_ON_READ_DEFAULT false
799 #define RBD_EXCLUSIVE_DEFAULT   false
800 #define RBD_TRIM_DEFAULT        true
801
802 struct parse_rbd_opts_ctx {
803         struct rbd_spec         *spec;
804         struct rbd_options      *opts;
805 };
806
807 static int parse_rbd_opts_token(char *c, void *private)
808 {
809         struct parse_rbd_opts_ctx *pctx = private;
810         substring_t argstr[MAX_OPT_ARGS];
811         int token, intval, ret;
812
813         token = match_token(c, rbd_opts_tokens, argstr);
814         if (token < Opt_last_int) {
815                 ret = match_int(&argstr[0], &intval);
816                 if (ret < 0) {
817                         pr_err("bad option arg (not int) at '%s'\n", c);
818                         return ret;
819                 }
820                 dout("got int token %d val %d\n", token, intval);
821         } else if (token > Opt_last_int && token < Opt_last_string) {
822                 dout("got string token %d val %s\n", token, argstr[0].from);
823         } else {
824                 dout("got token %d\n", token);
825         }
826
827         switch (token) {
828         case Opt_queue_depth:
829                 if (intval < 1) {
830                         pr_err("queue_depth out of range\n");
831                         return -EINVAL;
832                 }
833                 pctx->opts->queue_depth = intval;
834                 break;
835         case Opt_alloc_size:
836                 if (intval < 1) {
837                         pr_err("alloc_size out of range\n");
838                         return -EINVAL;
839                 }
840                 if (!is_power_of_2(intval)) {
841                         pr_err("alloc_size must be a power of 2\n");
842                         return -EINVAL;
843                 }
844                 pctx->opts->alloc_size = intval;
845                 break;
846         case Opt_lock_timeout:
847                 /* 0 is "wait forever" (i.e. infinite timeout) */
848                 if (intval < 0 || intval > INT_MAX / 1000) {
849                         pr_err("lock_timeout out of range\n");
850                         return -EINVAL;
851                 }
852                 pctx->opts->lock_timeout = msecs_to_jiffies(intval * 1000);
853                 break;
854         case Opt_pool_ns:
855                 kfree(pctx->spec->pool_ns);
856                 pctx->spec->pool_ns = match_strdup(argstr);
857                 if (!pctx->spec->pool_ns)
858                         return -ENOMEM;
859                 break;
860         case Opt_read_only:
861                 pctx->opts->read_only = true;
862                 break;
863         case Opt_read_write:
864                 pctx->opts->read_only = false;
865                 break;
866         case Opt_lock_on_read:
867                 pctx->opts->lock_on_read = true;
868                 break;
869         case Opt_exclusive:
870                 pctx->opts->exclusive = true;
871                 break;
872         case Opt_notrim:
873                 pctx->opts->trim = false;
874                 break;
875         default:
876                 /* libceph prints "bad option" msg */
877                 return -EINVAL;
878         }
879
880         return 0;
881 }
882
883 static char* obj_op_name(enum obj_operation_type op_type)
884 {
885         switch (op_type) {
886         case OBJ_OP_READ:
887                 return "read";
888         case OBJ_OP_WRITE:
889                 return "write";
890         case OBJ_OP_DISCARD:
891                 return "discard";
892         case OBJ_OP_ZEROOUT:
893                 return "zeroout";
894         default:
895                 return "???";
896         }
897 }
898
899 /*
900  * Destroy ceph client
901  *
902  * Caller must hold rbd_client_list_lock.
903  */
904 static void rbd_client_release(struct kref *kref)
905 {
906         struct rbd_client *rbdc = container_of(kref, struct rbd_client, kref);
907
908         dout("%s: rbdc %p\n", __func__, rbdc);
909         spin_lock(&rbd_client_list_lock);
910         list_del(&rbdc->node);
911         spin_unlock(&rbd_client_list_lock);
912
913         ceph_destroy_client(rbdc->client);
914         kfree(rbdc);
915 }
916
917 /*
918  * Drop reference to ceph client node. If it's not referenced anymore, release
919  * it.
920  */
921 static void rbd_put_client(struct rbd_client *rbdc)
922 {
923         if (rbdc)
924                 kref_put(&rbdc->kref, rbd_client_release);
925 }
926
927 static int wait_for_latest_osdmap(struct ceph_client *client)
928 {
929         u64 newest_epoch;
930         int ret;
931
932         ret = ceph_monc_get_version(&client->monc, "osdmap", &newest_epoch);
933         if (ret)
934                 return ret;
935
936         if (client->osdc.osdmap->epoch >= newest_epoch)
937                 return 0;
938
939         ceph_osdc_maybe_request_map(&client->osdc);
940         return ceph_monc_wait_osdmap(&client->monc, newest_epoch,
941                                      client->options->mount_timeout);
942 }
943
944 /*
945  * Get a ceph client with specific addr and configuration, if one does
946  * not exist create it.  Either way, ceph_opts is consumed by this
947  * function.
948  */
949 static struct rbd_client *rbd_get_client(struct ceph_options *ceph_opts)
950 {
951         struct rbd_client *rbdc;
952         int ret;
953
954         mutex_lock_nested(&client_mutex, SINGLE_DEPTH_NESTING);
955         rbdc = rbd_client_find(ceph_opts);
956         if (rbdc) {
957                 ceph_destroy_options(ceph_opts);
958
959                 /*
960                  * Using an existing client.  Make sure ->pg_pools is up to
961                  * date before we look up the pool id in do_rbd_add().
962                  */
963                 ret = wait_for_latest_osdmap(rbdc->client);
964                 if (ret) {
965                         rbd_warn(NULL, "failed to get latest osdmap: %d", ret);
966                         rbd_put_client(rbdc);
967                         rbdc = ERR_PTR(ret);
968                 }
969         } else {
970                 rbdc = rbd_client_create(ceph_opts);
971         }
972         mutex_unlock(&client_mutex);
973
974         return rbdc;
975 }
976
977 static bool rbd_image_format_valid(u32 image_format)
978 {
979         return image_format == 1 || image_format == 2;
980 }
981
982 static bool rbd_dev_ondisk_valid(struct rbd_image_header_ondisk *ondisk)
983 {
984         size_t size;
985         u32 snap_count;
986
987         /* The header has to start with the magic rbd header text */
988         if (memcmp(&ondisk->text, RBD_HEADER_TEXT, sizeof (RBD_HEADER_TEXT)))
989                 return false;
990
991         /* The bio layer requires at least sector-sized I/O */
992
993         if (ondisk->options.order < SECTOR_SHIFT)
994                 return false;
995
996         /* If we use u64 in a few spots we may be able to loosen this */
997
998         if (ondisk->options.order > 8 * sizeof (int) - 1)
999                 return false;
1000
1001         /*
1002          * The size of a snapshot header has to fit in a size_t, and
1003          * that limits the number of snapshots.
1004          */
1005         snap_count = le32_to_cpu(ondisk->snap_count);
1006         size = SIZE_MAX - sizeof (struct ceph_snap_context);
1007         if (snap_count > size / sizeof (__le64))
1008                 return false;
1009
1010         /*
1011          * Not only that, but the size of the entire the snapshot
1012          * header must also be representable in a size_t.
1013          */
1014         size -= snap_count * sizeof (__le64);
1015         if ((u64) size < le64_to_cpu(ondisk->snap_names_len))
1016                 return false;
1017
1018         return true;
1019 }
1020
1021 /*
1022  * returns the size of an object in the image
1023  */
1024 static u32 rbd_obj_bytes(struct rbd_image_header *header)
1025 {
1026         return 1U << header->obj_order;
1027 }
1028
1029 static void rbd_init_layout(struct rbd_device *rbd_dev)
1030 {
1031         if (rbd_dev->header.stripe_unit == 0 ||
1032             rbd_dev->header.stripe_count == 0) {
1033                 rbd_dev->header.stripe_unit = rbd_obj_bytes(&rbd_dev->header);
1034                 rbd_dev->header.stripe_count = 1;
1035         }
1036
1037         rbd_dev->layout.stripe_unit = rbd_dev->header.stripe_unit;
1038         rbd_dev->layout.stripe_count = rbd_dev->header.stripe_count;
1039         rbd_dev->layout.object_size = rbd_obj_bytes(&rbd_dev->header);
1040         rbd_dev->layout.pool_id = rbd_dev->header.data_pool_id == CEPH_NOPOOL ?
1041                           rbd_dev->spec->pool_id : rbd_dev->header.data_pool_id;
1042         RCU_INIT_POINTER(rbd_dev->layout.pool_ns, NULL);
1043 }
1044
1045 /*
1046  * Fill an rbd image header with information from the given format 1
1047  * on-disk header.
1048  */
1049 static int rbd_header_from_disk(struct rbd_device *rbd_dev,
1050                                  struct rbd_image_header_ondisk *ondisk)
1051 {
1052         struct rbd_image_header *header = &rbd_dev->header;
1053         bool first_time = header->object_prefix == NULL;
1054         struct ceph_snap_context *snapc;
1055         char *object_prefix = NULL;
1056         char *snap_names = NULL;
1057         u64 *snap_sizes = NULL;
1058         u32 snap_count;
1059         int ret = -ENOMEM;
1060         u32 i;
1061
1062         /* Allocate this now to avoid having to handle failure below */
1063
1064         if (first_time) {
1065                 object_prefix = kstrndup(ondisk->object_prefix,
1066                                          sizeof(ondisk->object_prefix),
1067                                          GFP_KERNEL);
1068                 if (!object_prefix)
1069                         return -ENOMEM;
1070         }
1071
1072         /* Allocate the snapshot context and fill it in */
1073
1074         snap_count = le32_to_cpu(ondisk->snap_count);
1075         snapc = ceph_create_snap_context(snap_count, GFP_KERNEL);
1076         if (!snapc)
1077                 goto out_err;
1078         snapc->seq = le64_to_cpu(ondisk->snap_seq);
1079         if (snap_count) {
1080                 struct rbd_image_snap_ondisk *snaps;
1081                 u64 snap_names_len = le64_to_cpu(ondisk->snap_names_len);
1082
1083                 /* We'll keep a copy of the snapshot names... */
1084
1085                 if (snap_names_len > (u64)SIZE_MAX)
1086                         goto out_2big;
1087                 snap_names = kmalloc(snap_names_len, GFP_KERNEL);
1088                 if (!snap_names)
1089                         goto out_err;
1090
1091                 /* ...as well as the array of their sizes. */
1092                 snap_sizes = kmalloc_array(snap_count,
1093                                            sizeof(*header->snap_sizes),
1094                                            GFP_KERNEL);
1095                 if (!snap_sizes)
1096                         goto out_err;
1097
1098                 /*
1099                  * Copy the names, and fill in each snapshot's id
1100                  * and size.
1101                  *
1102                  * Note that rbd_dev_v1_header_info() guarantees the
1103                  * ondisk buffer we're working with has
1104                  * snap_names_len bytes beyond the end of the
1105                  * snapshot id array, this memcpy() is safe.
1106                  */
1107                 memcpy(snap_names, &ondisk->snaps[snap_count], snap_names_len);
1108                 snaps = ondisk->snaps;
1109                 for (i = 0; i < snap_count; i++) {
1110                         snapc->snaps[i] = le64_to_cpu(snaps[i].id);
1111                         snap_sizes[i] = le64_to_cpu(snaps[i].image_size);
1112                 }
1113         }
1114
1115         /* We won't fail any more, fill in the header */
1116
1117         if (first_time) {
1118                 header->object_prefix = object_prefix;
1119                 header->obj_order = ondisk->options.order;
1120                 rbd_init_layout(rbd_dev);
1121         } else {
1122                 ceph_put_snap_context(header->snapc);
1123                 kfree(header->snap_names);
1124                 kfree(header->snap_sizes);
1125         }
1126
1127         /* The remaining fields always get updated (when we refresh) */
1128
1129         header->image_size = le64_to_cpu(ondisk->image_size);
1130         header->snapc = snapc;
1131         header->snap_names = snap_names;
1132         header->snap_sizes = snap_sizes;
1133
1134         return 0;
1135 out_2big:
1136         ret = -EIO;
1137 out_err:
1138         kfree(snap_sizes);
1139         kfree(snap_names);
1140         ceph_put_snap_context(snapc);
1141         kfree(object_prefix);
1142
1143         return ret;
1144 }
1145
1146 static const char *_rbd_dev_v1_snap_name(struct rbd_device *rbd_dev, u32 which)
1147 {
1148         const char *snap_name;
1149
1150         rbd_assert(which < rbd_dev->header.snapc->num_snaps);
1151
1152         /* Skip over names until we find the one we are looking for */
1153
1154         snap_name = rbd_dev->header.snap_names;
1155         while (which--)
1156                 snap_name += strlen(snap_name) + 1;
1157
1158         return kstrdup(snap_name, GFP_KERNEL);
1159 }
1160
1161 /*
1162  * Snapshot id comparison function for use with qsort()/bsearch().
1163  * Note that result is for snapshots in *descending* order.
1164  */
1165 static int snapid_compare_reverse(const void *s1, const void *s2)
1166 {
1167         u64 snap_id1 = *(u64 *)s1;
1168         u64 snap_id2 = *(u64 *)s2;
1169
1170         if (snap_id1 < snap_id2)
1171                 return 1;
1172         return snap_id1 == snap_id2 ? 0 : -1;
1173 }
1174
1175 /*
1176  * Search a snapshot context to see if the given snapshot id is
1177  * present.
1178  *
1179  * Returns the position of the snapshot id in the array if it's found,
1180  * or BAD_SNAP_INDEX otherwise.
1181  *
1182  * Note: The snapshot array is in kept sorted (by the osd) in
1183  * reverse order, highest snapshot id first.
1184  */
1185 static u32 rbd_dev_snap_index(struct rbd_device *rbd_dev, u64 snap_id)
1186 {
1187         struct ceph_snap_context *snapc = rbd_dev->header.snapc;
1188         u64 *found;
1189
1190         found = bsearch(&snap_id, &snapc->snaps, snapc->num_snaps,
1191                                 sizeof (snap_id), snapid_compare_reverse);
1192
1193         return found ? (u32)(found - &snapc->snaps[0]) : BAD_SNAP_INDEX;
1194 }
1195
1196 static const char *rbd_dev_v1_snap_name(struct rbd_device *rbd_dev,
1197                                         u64 snap_id)
1198 {
1199         u32 which;
1200         const char *snap_name;
1201
1202         which = rbd_dev_snap_index(rbd_dev, snap_id);
1203         if (which == BAD_SNAP_INDEX)
1204                 return ERR_PTR(-ENOENT);
1205
1206         snap_name = _rbd_dev_v1_snap_name(rbd_dev, which);
1207         return snap_name ? snap_name : ERR_PTR(-ENOMEM);
1208 }
1209
1210 static const char *rbd_snap_name(struct rbd_device *rbd_dev, u64 snap_id)
1211 {
1212         if (snap_id == CEPH_NOSNAP)
1213                 return RBD_SNAP_HEAD_NAME;
1214
1215         rbd_assert(rbd_image_format_valid(rbd_dev->image_format));
1216         if (rbd_dev->image_format == 1)
1217                 return rbd_dev_v1_snap_name(rbd_dev, snap_id);
1218
1219         return rbd_dev_v2_snap_name(rbd_dev, snap_id);
1220 }
1221
1222 static int rbd_snap_size(struct rbd_device *rbd_dev, u64 snap_id,
1223                                 u64 *snap_size)
1224 {
1225         rbd_assert(rbd_image_format_valid(rbd_dev->image_format));
1226         if (snap_id == CEPH_NOSNAP) {
1227                 *snap_size = rbd_dev->header.image_size;
1228         } else if (rbd_dev->image_format == 1) {
1229                 u32 which;
1230
1231                 which = rbd_dev_snap_index(rbd_dev, snap_id);
1232                 if (which == BAD_SNAP_INDEX)
1233                         return -ENOENT;
1234
1235                 *snap_size = rbd_dev->header.snap_sizes[which];
1236         } else {
1237                 u64 size = 0;
1238                 int ret;
1239
1240                 ret = _rbd_dev_v2_snap_size(rbd_dev, snap_id, NULL, &size);
1241                 if (ret)
1242                         return ret;
1243
1244                 *snap_size = size;
1245         }
1246         return 0;
1247 }
1248
1249 static int rbd_snap_features(struct rbd_device *rbd_dev, u64 snap_id,
1250                         u64 *snap_features)
1251 {
1252         rbd_assert(rbd_image_format_valid(rbd_dev->image_format));
1253         if (snap_id == CEPH_NOSNAP) {
1254                 *snap_features = rbd_dev->header.features;
1255         } else if (rbd_dev->image_format == 1) {
1256                 *snap_features = 0;     /* No features for format 1 */
1257         } else {
1258                 u64 features = 0;
1259                 int ret;
1260
1261                 ret = _rbd_dev_v2_snap_features(rbd_dev, snap_id, &features);
1262                 if (ret)
1263                         return ret;
1264
1265                 *snap_features = features;
1266         }
1267         return 0;
1268 }
1269
1270 static int rbd_dev_mapping_set(struct rbd_device *rbd_dev)
1271 {
1272         u64 snap_id = rbd_dev->spec->snap_id;
1273         u64 size = 0;
1274         u64 features = 0;
1275         int ret;
1276
1277         ret = rbd_snap_size(rbd_dev, snap_id, &size);
1278         if (ret)
1279                 return ret;
1280         ret = rbd_snap_features(rbd_dev, snap_id, &features);
1281         if (ret)
1282                 return ret;
1283
1284         rbd_dev->mapping.size = size;
1285         rbd_dev->mapping.features = features;
1286
1287         return 0;
1288 }
1289
1290 static void rbd_dev_mapping_clear(struct rbd_device *rbd_dev)
1291 {
1292         rbd_dev->mapping.size = 0;
1293         rbd_dev->mapping.features = 0;
1294 }
1295
1296 static void zero_bvec(struct bio_vec *bv)
1297 {
1298         void *buf;
1299         unsigned long flags;
1300
1301         buf = bvec_kmap_irq(bv, &flags);
1302         memset(buf, 0, bv->bv_len);
1303         flush_dcache_page(bv->bv_page);
1304         bvec_kunmap_irq(buf, &flags);
1305 }
1306
1307 static void zero_bios(struct ceph_bio_iter *bio_pos, u32 off, u32 bytes)
1308 {
1309         struct ceph_bio_iter it = *bio_pos;
1310
1311         ceph_bio_iter_advance(&it, off);
1312         ceph_bio_iter_advance_step(&it, bytes, ({
1313                 zero_bvec(&bv);
1314         }));
1315 }
1316
1317 static void zero_bvecs(struct ceph_bvec_iter *bvec_pos, u32 off, u32 bytes)
1318 {
1319         struct ceph_bvec_iter it = *bvec_pos;
1320
1321         ceph_bvec_iter_advance(&it, off);
1322         ceph_bvec_iter_advance_step(&it, bytes, ({
1323                 zero_bvec(&bv);
1324         }));
1325 }
1326
1327 /*
1328  * Zero a range in @obj_req data buffer defined by a bio (list) or
1329  * (private) bio_vec array.
1330  *
1331  * @off is relative to the start of the data buffer.
1332  */
1333 static void rbd_obj_zero_range(struct rbd_obj_request *obj_req, u32 off,
1334                                u32 bytes)
1335 {
1336         switch (obj_req->img_request->data_type) {
1337         case OBJ_REQUEST_BIO:
1338                 zero_bios(&obj_req->bio_pos, off, bytes);
1339                 break;
1340         case OBJ_REQUEST_BVECS:
1341         case OBJ_REQUEST_OWN_BVECS:
1342                 zero_bvecs(&obj_req->bvec_pos, off, bytes);
1343                 break;
1344         default:
1345                 rbd_assert(0);
1346         }
1347 }
1348
1349 static void rbd_obj_request_destroy(struct kref *kref);
1350 static void rbd_obj_request_put(struct rbd_obj_request *obj_request)
1351 {
1352         rbd_assert(obj_request != NULL);
1353         dout("%s: obj %p (was %d)\n", __func__, obj_request,
1354                 kref_read(&obj_request->kref));
1355         kref_put(&obj_request->kref, rbd_obj_request_destroy);
1356 }
1357
1358 static void rbd_img_request_get(struct rbd_img_request *img_request)
1359 {
1360         dout("%s: img %p (was %d)\n", __func__, img_request,
1361              kref_read(&img_request->kref));
1362         kref_get(&img_request->kref);
1363 }
1364
1365 static void rbd_img_request_destroy(struct kref *kref);
1366 static void rbd_img_request_put(struct rbd_img_request *img_request)
1367 {
1368         rbd_assert(img_request != NULL);
1369         dout("%s: img %p (was %d)\n", __func__, img_request,
1370                 kref_read(&img_request->kref));
1371         kref_put(&img_request->kref, rbd_img_request_destroy);
1372 }
1373
1374 static inline void rbd_img_obj_request_add(struct rbd_img_request *img_request,
1375                                         struct rbd_obj_request *obj_request)
1376 {
1377         rbd_assert(obj_request->img_request == NULL);
1378
1379         /* Image request now owns object's original reference */
1380         obj_request->img_request = img_request;
1381         img_request->pending_count++;
1382         dout("%s: img %p obj %p\n", __func__, img_request, obj_request);
1383 }
1384
1385 static inline void rbd_img_obj_request_del(struct rbd_img_request *img_request,
1386                                         struct rbd_obj_request *obj_request)
1387 {
1388         dout("%s: img %p obj %p\n", __func__, img_request, obj_request);
1389         list_del(&obj_request->ex.oe_item);
1390         rbd_assert(obj_request->img_request == img_request);
1391         rbd_obj_request_put(obj_request);
1392 }
1393
1394 static void rbd_obj_request_submit(struct rbd_obj_request *obj_request)
1395 {
1396         struct ceph_osd_request *osd_req = obj_request->osd_req;
1397
1398         dout("%s %p object_no %016llx %llu~%llu osd_req %p\n", __func__,
1399              obj_request, obj_request->ex.oe_objno, obj_request->ex.oe_off,
1400              obj_request->ex.oe_len, osd_req);
1401         ceph_osdc_start_request(osd_req->r_osdc, osd_req, false);
1402 }
1403
1404 /*
1405  * The default/initial value for all image request flags is 0.  Each
1406  * is conditionally set to 1 at image request initialization time
1407  * and currently never change thereafter.
1408  */
1409 static void img_request_layered_set(struct rbd_img_request *img_request)
1410 {
1411         set_bit(IMG_REQ_LAYERED, &img_request->flags);
1412         smp_mb();
1413 }
1414
1415 static void img_request_layered_clear(struct rbd_img_request *img_request)
1416 {
1417         clear_bit(IMG_REQ_LAYERED, &img_request->flags);
1418         smp_mb();
1419 }
1420
1421 static bool img_request_layered_test(struct rbd_img_request *img_request)
1422 {
1423         smp_mb();
1424         return test_bit(IMG_REQ_LAYERED, &img_request->flags) != 0;
1425 }
1426
1427 static bool rbd_obj_is_entire(struct rbd_obj_request *obj_req)
1428 {
1429         struct rbd_device *rbd_dev = obj_req->img_request->rbd_dev;
1430
1431         return !obj_req->ex.oe_off &&
1432                obj_req->ex.oe_len == rbd_dev->layout.object_size;
1433 }
1434
1435 static bool rbd_obj_is_tail(struct rbd_obj_request *obj_req)
1436 {
1437         struct rbd_device *rbd_dev = obj_req->img_request->rbd_dev;
1438
1439         return obj_req->ex.oe_off + obj_req->ex.oe_len ==
1440                                         rbd_dev->layout.object_size;
1441 }
1442
1443 /*
1444  * Must be called after rbd_obj_calc_img_extents().
1445  */
1446 static bool rbd_obj_copyup_enabled(struct rbd_obj_request *obj_req)
1447 {
1448         if (!obj_req->num_img_extents ||
1449             (rbd_obj_is_entire(obj_req) &&
1450              !obj_req->img_request->snapc->num_snaps))
1451                 return false;
1452
1453         return true;
1454 }
1455
1456 static u64 rbd_obj_img_extents_bytes(struct rbd_obj_request *obj_req)
1457 {
1458         return ceph_file_extents_bytes(obj_req->img_extents,
1459                                        obj_req->num_img_extents);
1460 }
1461
1462 static bool rbd_img_is_write(struct rbd_img_request *img_req)
1463 {
1464         switch (img_req->op_type) {
1465         case OBJ_OP_READ:
1466                 return false;
1467         case OBJ_OP_WRITE:
1468         case OBJ_OP_DISCARD:
1469         case OBJ_OP_ZEROOUT:
1470                 return true;
1471         default:
1472                 BUG();
1473         }
1474 }
1475
1476 static void rbd_obj_handle_request(struct rbd_obj_request *obj_req);
1477
1478 static void rbd_osd_req_callback(struct ceph_osd_request *osd_req)
1479 {
1480         struct rbd_obj_request *obj_req = osd_req->r_priv;
1481
1482         dout("%s osd_req %p result %d for obj_req %p\n", __func__, osd_req,
1483              osd_req->r_result, obj_req);
1484         rbd_assert(osd_req == obj_req->osd_req);
1485
1486         obj_req->result = osd_req->r_result < 0 ? osd_req->r_result : 0;
1487         if (!obj_req->result && !rbd_img_is_write(obj_req->img_request))
1488                 obj_req->xferred = osd_req->r_result;
1489         else
1490                 /*
1491                  * Writes aren't allowed to return a data payload.  In some
1492                  * guarded write cases (e.g. stat + zero on an empty object)
1493                  * a stat response makes it through, but we don't care.
1494                  */
1495                 obj_req->xferred = 0;
1496
1497         rbd_obj_handle_request(obj_req);
1498 }
1499
1500 static void rbd_osd_req_format_read(struct rbd_obj_request *obj_request)
1501 {
1502         struct ceph_osd_request *osd_req = obj_request->osd_req;
1503
1504         osd_req->r_flags = CEPH_OSD_FLAG_READ;
1505         osd_req->r_snapid = obj_request->img_request->snap_id;
1506 }
1507
1508 static void rbd_osd_req_format_write(struct rbd_obj_request *obj_request)
1509 {
1510         struct ceph_osd_request *osd_req = obj_request->osd_req;
1511
1512         osd_req->r_flags = CEPH_OSD_FLAG_WRITE;
1513         ktime_get_real_ts64(&osd_req->r_mtime);
1514         osd_req->r_data_offset = obj_request->ex.oe_off;
1515 }
1516
1517 static struct ceph_osd_request *
1518 __rbd_osd_req_create(struct rbd_obj_request *obj_req,
1519                      struct ceph_snap_context *snapc, unsigned int num_ops)
1520 {
1521         struct rbd_device *rbd_dev = obj_req->img_request->rbd_dev;
1522         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
1523         struct ceph_osd_request *req;
1524         const char *name_format = rbd_dev->image_format == 1 ?
1525                                       RBD_V1_DATA_FORMAT : RBD_V2_DATA_FORMAT;
1526
1527         req = ceph_osdc_alloc_request(osdc, snapc, num_ops, false, GFP_NOIO);
1528         if (!req)
1529                 return NULL;
1530
1531         req->r_callback = rbd_osd_req_callback;
1532         req->r_priv = obj_req;
1533
1534         /*
1535          * Data objects may be stored in a separate pool, but always in
1536          * the same namespace in that pool as the header in its pool.
1537          */
1538         ceph_oloc_copy(&req->r_base_oloc, &rbd_dev->header_oloc);
1539         req->r_base_oloc.pool = rbd_dev->layout.pool_id;
1540
1541         if (ceph_oid_aprintf(&req->r_base_oid, GFP_NOIO, name_format,
1542                         rbd_dev->header.object_prefix, obj_req->ex.oe_objno))
1543                 goto err_req;
1544
1545         return req;
1546
1547 err_req:
1548         ceph_osdc_put_request(req);
1549         return NULL;
1550 }
1551
1552 static struct ceph_osd_request *
1553 rbd_osd_req_create(struct rbd_obj_request *obj_req, unsigned int num_ops)
1554 {
1555         return __rbd_osd_req_create(obj_req, obj_req->img_request->snapc,
1556                                     num_ops);
1557 }
1558
1559 static void rbd_osd_req_destroy(struct ceph_osd_request *osd_req)
1560 {
1561         ceph_osdc_put_request(osd_req);
1562 }
1563
1564 static struct rbd_obj_request *rbd_obj_request_create(void)
1565 {
1566         struct rbd_obj_request *obj_request;
1567
1568         obj_request = kmem_cache_zalloc(rbd_obj_request_cache, GFP_NOIO);
1569         if (!obj_request)
1570                 return NULL;
1571
1572         ceph_object_extent_init(&obj_request->ex);
1573         kref_init(&obj_request->kref);
1574
1575         dout("%s %p\n", __func__, obj_request);
1576         return obj_request;
1577 }
1578
1579 static void rbd_obj_request_destroy(struct kref *kref)
1580 {
1581         struct rbd_obj_request *obj_request;
1582         u32 i;
1583
1584         obj_request = container_of(kref, struct rbd_obj_request, kref);
1585
1586         dout("%s: obj %p\n", __func__, obj_request);
1587
1588         if (obj_request->osd_req)
1589                 rbd_osd_req_destroy(obj_request->osd_req);
1590
1591         switch (obj_request->img_request->data_type) {
1592         case OBJ_REQUEST_NODATA:
1593         case OBJ_REQUEST_BIO:
1594         case OBJ_REQUEST_BVECS:
1595                 break;          /* Nothing to do */
1596         case OBJ_REQUEST_OWN_BVECS:
1597                 kfree(obj_request->bvec_pos.bvecs);
1598                 break;
1599         default:
1600                 rbd_assert(0);
1601         }
1602
1603         kfree(obj_request->img_extents);
1604         if (obj_request->copyup_bvecs) {
1605                 for (i = 0; i < obj_request->copyup_bvec_count; i++) {
1606                         if (obj_request->copyup_bvecs[i].bv_page)
1607                                 __free_page(obj_request->copyup_bvecs[i].bv_page);
1608                 }
1609                 kfree(obj_request->copyup_bvecs);
1610         }
1611
1612         kmem_cache_free(rbd_obj_request_cache, obj_request);
1613 }
1614
1615 /* It's OK to call this for a device with no parent */
1616
1617 static void rbd_spec_put(struct rbd_spec *spec);
1618 static void rbd_dev_unparent(struct rbd_device *rbd_dev)
1619 {
1620         rbd_dev_remove_parent(rbd_dev);
1621         rbd_spec_put(rbd_dev->parent_spec);
1622         rbd_dev->parent_spec = NULL;
1623         rbd_dev->parent_overlap = 0;
1624 }
1625
1626 /*
1627  * Parent image reference counting is used to determine when an
1628  * image's parent fields can be safely torn down--after there are no
1629  * more in-flight requests to the parent image.  When the last
1630  * reference is dropped, cleaning them up is safe.
1631  */
1632 static void rbd_dev_parent_put(struct rbd_device *rbd_dev)
1633 {
1634         int counter;
1635
1636         if (!rbd_dev->parent_spec)
1637                 return;
1638
1639         counter = atomic_dec_return_safe(&rbd_dev->parent_ref);
1640         if (counter > 0)
1641                 return;
1642
1643         /* Last reference; clean up parent data structures */
1644
1645         if (!counter)
1646                 rbd_dev_unparent(rbd_dev);
1647         else
1648                 rbd_warn(rbd_dev, "parent reference underflow");
1649 }
1650
1651 /*
1652  * If an image has a non-zero parent overlap, get a reference to its
1653  * parent.
1654  *
1655  * Returns true if the rbd device has a parent with a non-zero
1656  * overlap and a reference for it was successfully taken, or
1657  * false otherwise.
1658  */
1659 static bool rbd_dev_parent_get(struct rbd_device *rbd_dev)
1660 {
1661         int counter = 0;
1662
1663         if (!rbd_dev->parent_spec)
1664                 return false;
1665
1666         down_read(&rbd_dev->header_rwsem);
1667         if (rbd_dev->parent_overlap)
1668                 counter = atomic_inc_return_safe(&rbd_dev->parent_ref);
1669         up_read(&rbd_dev->header_rwsem);
1670
1671         if (counter < 0)
1672                 rbd_warn(rbd_dev, "parent reference overflow");
1673
1674         return counter > 0;
1675 }
1676
1677 /*
1678  * Caller is responsible for filling in the list of object requests
1679  * that comprises the image request, and the Linux request pointer
1680  * (if there is one).
1681  */
1682 static struct rbd_img_request *rbd_img_request_create(
1683                                         struct rbd_device *rbd_dev,
1684                                         enum obj_operation_type op_type,
1685                                         struct ceph_snap_context *snapc)
1686 {
1687         struct rbd_img_request *img_request;
1688
1689         img_request = kmem_cache_zalloc(rbd_img_request_cache, GFP_NOIO);
1690         if (!img_request)
1691                 return NULL;
1692
1693         img_request->rbd_dev = rbd_dev;
1694         img_request->op_type = op_type;
1695         if (!rbd_img_is_write(img_request))
1696                 img_request->snap_id = rbd_dev->spec->snap_id;
1697         else
1698                 img_request->snapc = snapc;
1699
1700         if (rbd_dev_parent_get(rbd_dev))
1701                 img_request_layered_set(img_request);
1702
1703         spin_lock_init(&img_request->completion_lock);
1704         INIT_LIST_HEAD(&img_request->object_extents);
1705         kref_init(&img_request->kref);
1706
1707         dout("%s: rbd_dev %p %s -> img %p\n", __func__, rbd_dev,
1708              obj_op_name(op_type), img_request);
1709         return img_request;
1710 }
1711
1712 static void rbd_img_request_destroy(struct kref *kref)
1713 {
1714         struct rbd_img_request *img_request;
1715         struct rbd_obj_request *obj_request;
1716         struct rbd_obj_request *next_obj_request;
1717
1718         img_request = container_of(kref, struct rbd_img_request, kref);
1719
1720         dout("%s: img %p\n", __func__, img_request);
1721
1722         for_each_obj_request_safe(img_request, obj_request, next_obj_request)
1723                 rbd_img_obj_request_del(img_request, obj_request);
1724
1725         if (img_request_layered_test(img_request)) {
1726                 img_request_layered_clear(img_request);
1727                 rbd_dev_parent_put(img_request->rbd_dev);
1728         }
1729
1730         if (rbd_img_is_write(img_request))
1731                 ceph_put_snap_context(img_request->snapc);
1732
1733         kmem_cache_free(rbd_img_request_cache, img_request);
1734 }
1735
1736 static void prune_extents(struct ceph_file_extent *img_extents,
1737                           u32 *num_img_extents, u64 overlap)
1738 {
1739         u32 cnt = *num_img_extents;
1740
1741         /* drop extents completely beyond the overlap */
1742         while (cnt && img_extents[cnt - 1].fe_off >= overlap)
1743                 cnt--;
1744
1745         if (cnt) {
1746                 struct ceph_file_extent *ex = &img_extents[cnt - 1];
1747
1748                 /* trim final overlapping extent */
1749                 if (ex->fe_off + ex->fe_len > overlap)
1750                         ex->fe_len = overlap - ex->fe_off;
1751         }
1752
1753         *num_img_extents = cnt;
1754 }
1755
1756 /*
1757  * Determine the byte range(s) covered by either just the object extent
1758  * or the entire object in the parent image.
1759  */
1760 static int rbd_obj_calc_img_extents(struct rbd_obj_request *obj_req,
1761                                     bool entire)
1762 {
1763         struct rbd_device *rbd_dev = obj_req->img_request->rbd_dev;
1764         int ret;
1765
1766         if (!rbd_dev->parent_overlap)
1767                 return 0;
1768
1769         ret = ceph_extent_to_file(&rbd_dev->layout, obj_req->ex.oe_objno,
1770                                   entire ? 0 : obj_req->ex.oe_off,
1771                                   entire ? rbd_dev->layout.object_size :
1772                                                         obj_req->ex.oe_len,
1773                                   &obj_req->img_extents,
1774                                   &obj_req->num_img_extents);
1775         if (ret)
1776                 return ret;
1777
1778         prune_extents(obj_req->img_extents, &obj_req->num_img_extents,
1779                       rbd_dev->parent_overlap);
1780         return 0;
1781 }
1782
1783 static void rbd_osd_req_setup_data(struct rbd_obj_request *obj_req, u32 which)
1784 {
1785         switch (obj_req->img_request->data_type) {
1786         case OBJ_REQUEST_BIO:
1787                 osd_req_op_extent_osd_data_bio(obj_req->osd_req, which,
1788                                                &obj_req->bio_pos,
1789                                                obj_req->ex.oe_len);
1790                 break;
1791         case OBJ_REQUEST_BVECS:
1792         case OBJ_REQUEST_OWN_BVECS:
1793                 rbd_assert(obj_req->bvec_pos.iter.bi_size ==
1794                                                         obj_req->ex.oe_len);
1795                 rbd_assert(obj_req->bvec_idx == obj_req->bvec_count);
1796                 osd_req_op_extent_osd_data_bvec_pos(obj_req->osd_req, which,
1797                                                     &obj_req->bvec_pos);
1798                 break;
1799         default:
1800                 rbd_assert(0);
1801         }
1802 }
1803
1804 static int rbd_obj_setup_read(struct rbd_obj_request *obj_req)
1805 {
1806         obj_req->osd_req = __rbd_osd_req_create(obj_req, NULL, 1);
1807         if (!obj_req->osd_req)
1808                 return -ENOMEM;
1809
1810         osd_req_op_extent_init(obj_req->osd_req, 0, CEPH_OSD_OP_READ,
1811                                obj_req->ex.oe_off, obj_req->ex.oe_len, 0, 0);
1812         rbd_osd_req_setup_data(obj_req, 0);
1813
1814         rbd_osd_req_format_read(obj_req);
1815         return 0;
1816 }
1817
1818 static int __rbd_obj_setup_stat(struct rbd_obj_request *obj_req,
1819                                 unsigned int which)
1820 {
1821         struct page **pages;
1822
1823         /*
1824          * The response data for a STAT call consists of:
1825          *     le64 length;
1826          *     struct {
1827          *         le32 tv_sec;
1828          *         le32 tv_nsec;
1829          *     } mtime;
1830          */
1831         pages = ceph_alloc_page_vector(1, GFP_NOIO);
1832         if (IS_ERR(pages))
1833                 return PTR_ERR(pages);
1834
1835         osd_req_op_init(obj_req->osd_req, which, CEPH_OSD_OP_STAT, 0);
1836         osd_req_op_raw_data_in_pages(obj_req->osd_req, which, pages,
1837                                      8 + sizeof(struct ceph_timespec),
1838                                      0, false, true);
1839         return 0;
1840 }
1841
1842 static int count_write_ops(struct rbd_obj_request *obj_req)
1843 {
1844         return 2; /* setallochint + write/writefull */
1845 }
1846
1847 static void __rbd_obj_setup_write(struct rbd_obj_request *obj_req,
1848                                   unsigned int which)
1849 {
1850         struct rbd_device *rbd_dev = obj_req->img_request->rbd_dev;
1851         u16 opcode;
1852
1853         osd_req_op_alloc_hint_init(obj_req->osd_req, which++,
1854                                    rbd_dev->layout.object_size,
1855                                    rbd_dev->layout.object_size);
1856
1857         if (rbd_obj_is_entire(obj_req))
1858                 opcode = CEPH_OSD_OP_WRITEFULL;
1859         else
1860                 opcode = CEPH_OSD_OP_WRITE;
1861
1862         osd_req_op_extent_init(obj_req->osd_req, which, opcode,
1863                                obj_req->ex.oe_off, obj_req->ex.oe_len, 0, 0);
1864         rbd_osd_req_setup_data(obj_req, which++);
1865
1866         rbd_assert(which == obj_req->osd_req->r_num_ops);
1867         rbd_osd_req_format_write(obj_req);
1868 }
1869
1870 static int rbd_obj_setup_write(struct rbd_obj_request *obj_req)
1871 {
1872         unsigned int num_osd_ops, which = 0;
1873         bool need_guard;
1874         int ret;
1875
1876         /* reverse map the entire object onto the parent */
1877         ret = rbd_obj_calc_img_extents(obj_req, true);
1878         if (ret)
1879                 return ret;
1880
1881         need_guard = rbd_obj_copyup_enabled(obj_req);
1882         num_osd_ops = need_guard + count_write_ops(obj_req);
1883
1884         obj_req->osd_req = rbd_osd_req_create(obj_req, num_osd_ops);
1885         if (!obj_req->osd_req)
1886                 return -ENOMEM;
1887
1888         if (need_guard) {
1889                 ret = __rbd_obj_setup_stat(obj_req, which++);
1890                 if (ret)
1891                         return ret;
1892
1893                 obj_req->write_state = RBD_OBJ_WRITE_GUARD;
1894         } else {
1895                 obj_req->write_state = RBD_OBJ_WRITE_FLAT;
1896         }
1897
1898         __rbd_obj_setup_write(obj_req, which);
1899         return 0;
1900 }
1901
1902 static u16 truncate_or_zero_opcode(struct rbd_obj_request *obj_req)
1903 {
1904         return rbd_obj_is_tail(obj_req) ? CEPH_OSD_OP_TRUNCATE :
1905                                           CEPH_OSD_OP_ZERO;
1906 }
1907
1908 static int rbd_obj_setup_discard(struct rbd_obj_request *obj_req)
1909 {
1910         struct rbd_device *rbd_dev = obj_req->img_request->rbd_dev;
1911         u64 off = obj_req->ex.oe_off;
1912         u64 next_off = obj_req->ex.oe_off + obj_req->ex.oe_len;
1913         int ret;
1914
1915         /*
1916          * Align the range to alloc_size boundary and punt on discards
1917          * that are too small to free up any space.
1918          *
1919          * alloc_size == object_size && is_tail() is a special case for
1920          * filestore with filestore_punch_hole = false, needed to allow
1921          * truncate (in addition to delete).
1922          */
1923         if (rbd_dev->opts->alloc_size != rbd_dev->layout.object_size ||
1924             !rbd_obj_is_tail(obj_req)) {
1925                 off = round_up(off, rbd_dev->opts->alloc_size);
1926                 next_off = round_down(next_off, rbd_dev->opts->alloc_size);
1927                 if (off >= next_off)
1928                         return 1;
1929         }
1930
1931         /* reverse map the entire object onto the parent */
1932         ret = rbd_obj_calc_img_extents(obj_req, true);
1933         if (ret)
1934                 return ret;
1935
1936         obj_req->osd_req = rbd_osd_req_create(obj_req, 1);
1937         if (!obj_req->osd_req)
1938                 return -ENOMEM;
1939
1940         if (rbd_obj_is_entire(obj_req) && !obj_req->num_img_extents) {
1941                 osd_req_op_init(obj_req->osd_req, 0, CEPH_OSD_OP_DELETE, 0);
1942         } else {
1943                 dout("%s %p %llu~%llu -> %llu~%llu\n", __func__,
1944                      obj_req, obj_req->ex.oe_off, obj_req->ex.oe_len,
1945                      off, next_off - off);
1946                 osd_req_op_extent_init(obj_req->osd_req, 0,
1947                                        truncate_or_zero_opcode(obj_req),
1948                                        off, next_off - off, 0, 0);
1949         }
1950
1951         obj_req->write_state = RBD_OBJ_WRITE_FLAT;
1952         rbd_osd_req_format_write(obj_req);
1953         return 0;
1954 }
1955
1956 static int count_zeroout_ops(struct rbd_obj_request *obj_req)
1957 {
1958         int num_osd_ops;
1959
1960         if (rbd_obj_is_entire(obj_req) && obj_req->num_img_extents &&
1961             !rbd_obj_copyup_enabled(obj_req))
1962                 num_osd_ops = 2; /* create + truncate */
1963         else
1964                 num_osd_ops = 1; /* delete/truncate/zero */
1965
1966         return num_osd_ops;
1967 }
1968
1969 static void __rbd_obj_setup_zeroout(struct rbd_obj_request *obj_req,
1970                                     unsigned int which)
1971 {
1972         u16 opcode;
1973
1974         if (rbd_obj_is_entire(obj_req)) {
1975                 if (obj_req->num_img_extents) {
1976                         if (!rbd_obj_copyup_enabled(obj_req))
1977                                 osd_req_op_init(obj_req->osd_req, which++,
1978                                                 CEPH_OSD_OP_CREATE, 0);
1979                         opcode = CEPH_OSD_OP_TRUNCATE;
1980                 } else {
1981                         osd_req_op_init(obj_req->osd_req, which++,
1982                                         CEPH_OSD_OP_DELETE, 0);
1983                         opcode = 0;
1984                 }
1985         } else {
1986                 opcode = truncate_or_zero_opcode(obj_req);
1987         }
1988
1989         if (opcode)
1990                 osd_req_op_extent_init(obj_req->osd_req, which++, opcode,
1991                                        obj_req->ex.oe_off, obj_req->ex.oe_len,
1992                                        0, 0);
1993
1994         rbd_assert(which == obj_req->osd_req->r_num_ops);
1995         rbd_osd_req_format_write(obj_req);
1996 }
1997
1998 static int rbd_obj_setup_zeroout(struct rbd_obj_request *obj_req)
1999 {
2000         unsigned int num_osd_ops, which = 0;
2001         bool need_guard;
2002         int ret;
2003
2004         /* reverse map the entire object onto the parent */
2005         ret = rbd_obj_calc_img_extents(obj_req, true);
2006         if (ret)
2007                 return ret;
2008
2009         need_guard = rbd_obj_copyup_enabled(obj_req);
2010         num_osd_ops = need_guard + count_zeroout_ops(obj_req);
2011
2012         obj_req->osd_req = rbd_osd_req_create(obj_req, num_osd_ops);
2013         if (!obj_req->osd_req)
2014                 return -ENOMEM;
2015
2016         if (need_guard) {
2017                 ret = __rbd_obj_setup_stat(obj_req, which++);
2018                 if (ret)
2019                         return ret;
2020
2021                 obj_req->write_state = RBD_OBJ_WRITE_GUARD;
2022         } else {
2023                 obj_req->write_state = RBD_OBJ_WRITE_FLAT;
2024         }
2025
2026         __rbd_obj_setup_zeroout(obj_req, which);
2027         return 0;
2028 }
2029
2030 /*
2031  * For each object request in @img_req, allocate an OSD request, add
2032  * individual OSD ops and prepare them for submission.  The number of
2033  * OSD ops depends on op_type and the overlap point (if any).
2034  */
2035 static int __rbd_img_fill_request(struct rbd_img_request *img_req)
2036 {
2037         struct rbd_obj_request *obj_req, *next_obj_req;
2038         int ret;
2039
2040         for_each_obj_request_safe(img_req, obj_req, next_obj_req) {
2041                 switch (img_req->op_type) {
2042                 case OBJ_OP_READ:
2043                         ret = rbd_obj_setup_read(obj_req);
2044                         break;
2045                 case OBJ_OP_WRITE:
2046                         ret = rbd_obj_setup_write(obj_req);
2047                         break;
2048                 case OBJ_OP_DISCARD:
2049                         ret = rbd_obj_setup_discard(obj_req);
2050                         break;
2051                 case OBJ_OP_ZEROOUT:
2052                         ret = rbd_obj_setup_zeroout(obj_req);
2053                         break;
2054                 default:
2055                         rbd_assert(0);
2056                 }
2057                 if (ret < 0)
2058                         return ret;
2059                 if (ret > 0) {
2060                         img_req->xferred += obj_req->ex.oe_len;
2061                         img_req->pending_count--;
2062                         rbd_img_obj_request_del(img_req, obj_req);
2063                         continue;
2064                 }
2065
2066                 ret = ceph_osdc_alloc_messages(obj_req->osd_req, GFP_NOIO);
2067                 if (ret)
2068                         return ret;
2069         }
2070
2071         return 0;
2072 }
2073
2074 union rbd_img_fill_iter {
2075         struct ceph_bio_iter    bio_iter;
2076         struct ceph_bvec_iter   bvec_iter;
2077 };
2078
2079 struct rbd_img_fill_ctx {
2080         enum obj_request_type   pos_type;
2081         union rbd_img_fill_iter *pos;
2082         union rbd_img_fill_iter iter;
2083         ceph_object_extent_fn_t set_pos_fn;
2084         ceph_object_extent_fn_t count_fn;
2085         ceph_object_extent_fn_t copy_fn;
2086 };
2087
2088 static struct ceph_object_extent *alloc_object_extent(void *arg)
2089 {
2090         struct rbd_img_request *img_req = arg;
2091         struct rbd_obj_request *obj_req;
2092
2093         obj_req = rbd_obj_request_create();
2094         if (!obj_req)
2095                 return NULL;
2096
2097         rbd_img_obj_request_add(img_req, obj_req);
2098         return &obj_req->ex;
2099 }
2100
2101 /*
2102  * While su != os && sc == 1 is technically not fancy (it's the same
2103  * layout as su == os && sc == 1), we can't use the nocopy path for it
2104  * because ->set_pos_fn() should be called only once per object.
2105  * ceph_file_to_extents() invokes action_fn once per stripe unit, so
2106  * treat su != os && sc == 1 as fancy.
2107  */
2108 static bool rbd_layout_is_fancy(struct ceph_file_layout *l)
2109 {
2110         return l->stripe_unit != l->object_size;
2111 }
2112
2113 static int rbd_img_fill_request_nocopy(struct rbd_img_request *img_req,
2114                                        struct ceph_file_extent *img_extents,
2115                                        u32 num_img_extents,
2116                                        struct rbd_img_fill_ctx *fctx)
2117 {
2118         u32 i;
2119         int ret;
2120
2121         img_req->data_type = fctx->pos_type;
2122
2123         /*
2124          * Create object requests and set each object request's starting
2125          * position in the provided bio (list) or bio_vec array.
2126          */
2127         fctx->iter = *fctx->pos;
2128         for (i = 0; i < num_img_extents; i++) {
2129                 ret = ceph_file_to_extents(&img_req->rbd_dev->layout,
2130                                            img_extents[i].fe_off,
2131                                            img_extents[i].fe_len,
2132                                            &img_req->object_extents,
2133                                            alloc_object_extent, img_req,
2134                                            fctx->set_pos_fn, &fctx->iter);
2135                 if (ret)
2136                         return ret;
2137         }
2138
2139         return __rbd_img_fill_request(img_req);
2140 }
2141
2142 /*
2143  * Map a list of image extents to a list of object extents, create the
2144  * corresponding object requests (normally each to a different object,
2145  * but not always) and add them to @img_req.  For each object request,
2146  * set up its data descriptor to point to the corresponding chunk(s) of
2147  * @fctx->pos data buffer.
2148  *
2149  * Because ceph_file_to_extents() will merge adjacent object extents
2150  * together, each object request's data descriptor may point to multiple
2151  * different chunks of @fctx->pos data buffer.
2152  *
2153  * @fctx->pos data buffer is assumed to be large enough.
2154  */
2155 static int rbd_img_fill_request(struct rbd_img_request *img_req,
2156                                 struct ceph_file_extent *img_extents,
2157                                 u32 num_img_extents,
2158                                 struct rbd_img_fill_ctx *fctx)
2159 {
2160         struct rbd_device *rbd_dev = img_req->rbd_dev;
2161         struct rbd_obj_request *obj_req;
2162         u32 i;
2163         int ret;
2164
2165         if (fctx->pos_type == OBJ_REQUEST_NODATA ||
2166             !rbd_layout_is_fancy(&rbd_dev->layout))
2167                 return rbd_img_fill_request_nocopy(img_req, img_extents,
2168                                                    num_img_extents, fctx);
2169
2170         img_req->data_type = OBJ_REQUEST_OWN_BVECS;
2171
2172         /*
2173          * Create object requests and determine ->bvec_count for each object
2174          * request.  Note that ->bvec_count sum over all object requests may
2175          * be greater than the number of bio_vecs in the provided bio (list)
2176          * or bio_vec array because when mapped, those bio_vecs can straddle
2177          * stripe unit boundaries.
2178          */
2179         fctx->iter = *fctx->pos;
2180         for (i = 0; i < num_img_extents; i++) {
2181                 ret = ceph_file_to_extents(&rbd_dev->layout,
2182                                            img_extents[i].fe_off,
2183                                            img_extents[i].fe_len,
2184                                            &img_req->object_extents,
2185                                            alloc_object_extent, img_req,
2186                                            fctx->count_fn, &fctx->iter);
2187                 if (ret)
2188                         return ret;
2189         }
2190
2191         for_each_obj_request(img_req, obj_req) {
2192                 obj_req->bvec_pos.bvecs = kmalloc_array(obj_req->bvec_count,
2193                                               sizeof(*obj_req->bvec_pos.bvecs),
2194                                               GFP_NOIO);
2195                 if (!obj_req->bvec_pos.bvecs)
2196                         return -ENOMEM;
2197         }
2198
2199         /*
2200          * Fill in each object request's private bio_vec array, splitting and
2201          * rearranging the provided bio_vecs in stripe unit chunks as needed.
2202          */
2203         fctx->iter = *fctx->pos;
2204         for (i = 0; i < num_img_extents; i++) {
2205                 ret = ceph_iterate_extents(&rbd_dev->layout,
2206                                            img_extents[i].fe_off,
2207                                            img_extents[i].fe_len,
2208                                            &img_req->object_extents,
2209                                            fctx->copy_fn, &fctx->iter);
2210                 if (ret)
2211                         return ret;
2212         }
2213
2214         return __rbd_img_fill_request(img_req);
2215 }
2216
2217 static int rbd_img_fill_nodata(struct rbd_img_request *img_req,
2218                                u64 off, u64 len)
2219 {
2220         struct ceph_file_extent ex = { off, len };
2221         union rbd_img_fill_iter dummy;
2222         struct rbd_img_fill_ctx fctx = {
2223                 .pos_type = OBJ_REQUEST_NODATA,
2224                 .pos = &dummy,
2225         };
2226
2227         return rbd_img_fill_request(img_req, &ex, 1, &fctx);
2228 }
2229
2230 static void set_bio_pos(struct ceph_object_extent *ex, u32 bytes, void *arg)
2231 {
2232         struct rbd_obj_request *obj_req =
2233             container_of(ex, struct rbd_obj_request, ex);
2234         struct ceph_bio_iter *it = arg;
2235
2236         dout("%s objno %llu bytes %u\n", __func__, ex->oe_objno, bytes);
2237         obj_req->bio_pos = *it;
2238         ceph_bio_iter_advance(it, bytes);
2239 }
2240
2241 static void count_bio_bvecs(struct ceph_object_extent *ex, u32 bytes, void *arg)
2242 {
2243         struct rbd_obj_request *obj_req =
2244             container_of(ex, struct rbd_obj_request, ex);
2245         struct ceph_bio_iter *it = arg;
2246
2247         dout("%s objno %llu bytes %u\n", __func__, ex->oe_objno, bytes);
2248         ceph_bio_iter_advance_step(it, bytes, ({
2249                 obj_req->bvec_count++;
2250         }));
2251
2252 }
2253
2254 static void copy_bio_bvecs(struct ceph_object_extent *ex, u32 bytes, void *arg)
2255 {
2256         struct rbd_obj_request *obj_req =
2257             container_of(ex, struct rbd_obj_request, ex);
2258         struct ceph_bio_iter *it = arg;
2259
2260         dout("%s objno %llu bytes %u\n", __func__, ex->oe_objno, bytes);
2261         ceph_bio_iter_advance_step(it, bytes, ({
2262                 obj_req->bvec_pos.bvecs[obj_req->bvec_idx++] = bv;
2263                 obj_req->bvec_pos.iter.bi_size += bv.bv_len;
2264         }));
2265 }
2266
2267 static int __rbd_img_fill_from_bio(struct rbd_img_request *img_req,
2268                                    struct ceph_file_extent *img_extents,
2269                                    u32 num_img_extents,
2270                                    struct ceph_bio_iter *bio_pos)
2271 {
2272         struct rbd_img_fill_ctx fctx = {
2273                 .pos_type = OBJ_REQUEST_BIO,
2274                 .pos = (union rbd_img_fill_iter *)bio_pos,
2275                 .set_pos_fn = set_bio_pos,
2276                 .count_fn = count_bio_bvecs,
2277                 .copy_fn = copy_bio_bvecs,
2278         };
2279
2280         return rbd_img_fill_request(img_req, img_extents, num_img_extents,
2281                                     &fctx);
2282 }
2283
2284 static int rbd_img_fill_from_bio(struct rbd_img_request *img_req,
2285                                  u64 off, u64 len, struct bio *bio)
2286 {
2287         struct ceph_file_extent ex = { off, len };
2288         struct ceph_bio_iter it = { .bio = bio, .iter = bio->bi_iter };
2289
2290         return __rbd_img_fill_from_bio(img_req, &ex, 1, &it);
2291 }
2292
2293 static void set_bvec_pos(struct ceph_object_extent *ex, u32 bytes, void *arg)
2294 {
2295         struct rbd_obj_request *obj_req =
2296             container_of(ex, struct rbd_obj_request, ex);
2297         struct ceph_bvec_iter *it = arg;
2298
2299         obj_req->bvec_pos = *it;
2300         ceph_bvec_iter_shorten(&obj_req->bvec_pos, bytes);
2301         ceph_bvec_iter_advance(it, bytes);
2302 }
2303
2304 static void count_bvecs(struct ceph_object_extent *ex, u32 bytes, void *arg)
2305 {
2306         struct rbd_obj_request *obj_req =
2307             container_of(ex, struct rbd_obj_request, ex);
2308         struct ceph_bvec_iter *it = arg;
2309
2310         ceph_bvec_iter_advance_step(it, bytes, ({
2311                 obj_req->bvec_count++;
2312         }));
2313 }
2314
2315 static void copy_bvecs(struct ceph_object_extent *ex, u32 bytes, void *arg)
2316 {
2317         struct rbd_obj_request *obj_req =
2318             container_of(ex, struct rbd_obj_request, ex);
2319         struct ceph_bvec_iter *it = arg;
2320
2321         ceph_bvec_iter_advance_step(it, bytes, ({
2322                 obj_req->bvec_pos.bvecs[obj_req->bvec_idx++] = bv;
2323                 obj_req->bvec_pos.iter.bi_size += bv.bv_len;
2324         }));
2325 }
2326
2327 static int __rbd_img_fill_from_bvecs(struct rbd_img_request *img_req,
2328                                      struct ceph_file_extent *img_extents,
2329                                      u32 num_img_extents,
2330                                      struct ceph_bvec_iter *bvec_pos)
2331 {
2332         struct rbd_img_fill_ctx fctx = {
2333                 .pos_type = OBJ_REQUEST_BVECS,
2334                 .pos = (union rbd_img_fill_iter *)bvec_pos,
2335                 .set_pos_fn = set_bvec_pos,
2336                 .count_fn = count_bvecs,
2337                 .copy_fn = copy_bvecs,
2338         };
2339
2340         return rbd_img_fill_request(img_req, img_extents, num_img_extents,
2341                                     &fctx);
2342 }
2343
2344 static int rbd_img_fill_from_bvecs(struct rbd_img_request *img_req,
2345                                    struct ceph_file_extent *img_extents,
2346                                    u32 num_img_extents,
2347                                    struct bio_vec *bvecs)
2348 {
2349         struct ceph_bvec_iter it = {
2350                 .bvecs = bvecs,
2351                 .iter = { .bi_size = ceph_file_extents_bytes(img_extents,
2352                                                              num_img_extents) },
2353         };
2354
2355         return __rbd_img_fill_from_bvecs(img_req, img_extents, num_img_extents,
2356                                          &it);
2357 }
2358
2359 static void rbd_img_request_submit(struct rbd_img_request *img_request)
2360 {
2361         struct rbd_obj_request *obj_request;
2362
2363         dout("%s: img %p\n", __func__, img_request);
2364
2365         rbd_img_request_get(img_request);
2366         for_each_obj_request(img_request, obj_request)
2367                 rbd_obj_request_submit(obj_request);
2368
2369         rbd_img_request_put(img_request);
2370 }
2371
2372 static int rbd_obj_read_from_parent(struct rbd_obj_request *obj_req)
2373 {
2374         struct rbd_img_request *img_req = obj_req->img_request;
2375         struct rbd_img_request *child_img_req;
2376         int ret;
2377
2378         child_img_req = rbd_img_request_create(img_req->rbd_dev->parent,
2379                                                OBJ_OP_READ, NULL);
2380         if (!child_img_req)
2381                 return -ENOMEM;
2382
2383         __set_bit(IMG_REQ_CHILD, &child_img_req->flags);
2384         child_img_req->obj_request = obj_req;
2385
2386         if (!rbd_img_is_write(img_req)) {
2387                 switch (img_req->data_type) {
2388                 case OBJ_REQUEST_BIO:
2389                         ret = __rbd_img_fill_from_bio(child_img_req,
2390                                                       obj_req->img_extents,
2391                                                       obj_req->num_img_extents,
2392                                                       &obj_req->bio_pos);
2393                         break;
2394                 case OBJ_REQUEST_BVECS:
2395                 case OBJ_REQUEST_OWN_BVECS:
2396                         ret = __rbd_img_fill_from_bvecs(child_img_req,
2397                                                       obj_req->img_extents,
2398                                                       obj_req->num_img_extents,
2399                                                       &obj_req->bvec_pos);
2400                         break;
2401                 default:
2402                         rbd_assert(0);
2403                 }
2404         } else {
2405                 ret = rbd_img_fill_from_bvecs(child_img_req,
2406                                               obj_req->img_extents,
2407                                               obj_req->num_img_extents,
2408                                               obj_req->copyup_bvecs);
2409         }
2410         if (ret) {
2411                 rbd_img_request_put(child_img_req);
2412                 return ret;
2413         }
2414
2415         rbd_img_request_submit(child_img_req);
2416         return 0;
2417 }
2418
2419 static bool rbd_obj_handle_read(struct rbd_obj_request *obj_req)
2420 {
2421         struct rbd_device *rbd_dev = obj_req->img_request->rbd_dev;
2422         int ret;
2423
2424         if (obj_req->result == -ENOENT &&
2425             rbd_dev->parent_overlap && !obj_req->tried_parent) {
2426                 /* reverse map this object extent onto the parent */
2427                 ret = rbd_obj_calc_img_extents(obj_req, false);
2428                 if (ret) {
2429                         obj_req->result = ret;
2430                         return true;
2431                 }
2432
2433                 if (obj_req->num_img_extents) {
2434                         obj_req->tried_parent = true;
2435                         ret = rbd_obj_read_from_parent(obj_req);
2436                         if (ret) {
2437                                 obj_req->result = ret;
2438                                 return true;
2439                         }
2440                         return false;
2441                 }
2442         }
2443
2444         /*
2445          * -ENOENT means a hole in the image -- zero-fill the entire
2446          * length of the request.  A short read also implies zero-fill
2447          * to the end of the request.  In both cases we update xferred
2448          * count to indicate the whole request was satisfied.
2449          */
2450         if (obj_req->result == -ENOENT ||
2451             (!obj_req->result && obj_req->xferred < obj_req->ex.oe_len)) {
2452                 rbd_assert(!obj_req->xferred || !obj_req->result);
2453                 rbd_obj_zero_range(obj_req, obj_req->xferred,
2454                                    obj_req->ex.oe_len - obj_req->xferred);
2455                 obj_req->result = 0;
2456                 obj_req->xferred = obj_req->ex.oe_len;
2457         }
2458
2459         return true;
2460 }
2461
2462 /*
2463  * copyup_bvecs pages are never highmem pages
2464  */
2465 static bool is_zero_bvecs(struct bio_vec *bvecs, u32 bytes)
2466 {
2467         struct ceph_bvec_iter it = {
2468                 .bvecs = bvecs,
2469                 .iter = { .bi_size = bytes },
2470         };
2471
2472         ceph_bvec_iter_advance_step(&it, bytes, ({
2473                 if (memchr_inv(page_address(bv.bv_page) + bv.bv_offset, 0,
2474                                bv.bv_len))
2475                         return false;
2476         }));
2477         return true;
2478 }
2479
2480 #define MODS_ONLY       U32_MAX
2481
2482 static int rbd_obj_issue_copyup_empty_snapc(struct rbd_obj_request *obj_req,
2483                                             u32 bytes)
2484 {
2485         int ret;
2486
2487         dout("%s obj_req %p bytes %u\n", __func__, obj_req, bytes);
2488         rbd_assert(obj_req->osd_req->r_ops[0].op == CEPH_OSD_OP_STAT);
2489         rbd_assert(bytes > 0 && bytes != MODS_ONLY);
2490         rbd_osd_req_destroy(obj_req->osd_req);
2491
2492         obj_req->osd_req = __rbd_osd_req_create(obj_req, &rbd_empty_snapc, 1);
2493         if (!obj_req->osd_req)
2494                 return -ENOMEM;
2495
2496         ret = osd_req_op_cls_init(obj_req->osd_req, 0, "rbd", "copyup");
2497         if (ret)
2498                 return ret;
2499
2500         osd_req_op_cls_request_data_bvecs(obj_req->osd_req, 0,
2501                                           obj_req->copyup_bvecs,
2502                                           obj_req->copyup_bvec_count,
2503                                           bytes);
2504         rbd_osd_req_format_write(obj_req);
2505
2506         ret = ceph_osdc_alloc_messages(obj_req->osd_req, GFP_NOIO);
2507         if (ret)
2508                 return ret;
2509
2510         rbd_obj_request_submit(obj_req);
2511         return 0;
2512 }
2513
2514 static int rbd_obj_issue_copyup_ops(struct rbd_obj_request *obj_req, u32 bytes)
2515 {
2516         struct rbd_img_request *img_req = obj_req->img_request;
2517         unsigned int num_osd_ops = (bytes != MODS_ONLY);
2518         unsigned int which = 0;
2519         int ret;
2520
2521         dout("%s obj_req %p bytes %u\n", __func__, obj_req, bytes);
2522         rbd_assert(obj_req->osd_req->r_ops[0].op == CEPH_OSD_OP_STAT ||
2523                    obj_req->osd_req->r_ops[0].op == CEPH_OSD_OP_CALL);
2524         rbd_osd_req_destroy(obj_req->osd_req);
2525
2526         switch (img_req->op_type) {
2527         case OBJ_OP_WRITE:
2528                 num_osd_ops += count_write_ops(obj_req);
2529                 break;
2530         case OBJ_OP_ZEROOUT:
2531                 num_osd_ops += count_zeroout_ops(obj_req);
2532                 break;
2533         default:
2534                 rbd_assert(0);
2535         }
2536
2537         obj_req->osd_req = rbd_osd_req_create(obj_req, num_osd_ops);
2538         if (!obj_req->osd_req)
2539                 return -ENOMEM;
2540
2541         if (bytes != MODS_ONLY) {
2542                 ret = osd_req_op_cls_init(obj_req->osd_req, which, "rbd",
2543                                           "copyup");
2544                 if (ret)
2545                         return ret;
2546
2547                 osd_req_op_cls_request_data_bvecs(obj_req->osd_req, which++,
2548                                                   obj_req->copyup_bvecs,
2549                                                   obj_req->copyup_bvec_count,
2550                                                   bytes);
2551         }
2552
2553         switch (img_req->op_type) {
2554         case OBJ_OP_WRITE:
2555                 __rbd_obj_setup_write(obj_req, which);
2556                 break;
2557         case OBJ_OP_ZEROOUT:
2558                 __rbd_obj_setup_zeroout(obj_req, which);
2559                 break;
2560         default:
2561                 rbd_assert(0);
2562         }
2563
2564         ret = ceph_osdc_alloc_messages(obj_req->osd_req, GFP_NOIO);
2565         if (ret)
2566                 return ret;
2567
2568         rbd_obj_request_submit(obj_req);
2569         return 0;
2570 }
2571
2572 static int rbd_obj_issue_copyup(struct rbd_obj_request *obj_req, u32 bytes)
2573 {
2574         /*
2575          * Only send non-zero copyup data to save some I/O and network
2576          * bandwidth -- zero copyup data is equivalent to the object not
2577          * existing.
2578          */
2579         if (is_zero_bvecs(obj_req->copyup_bvecs, bytes)) {
2580                 dout("%s obj_req %p detected zeroes\n", __func__, obj_req);
2581                 bytes = 0;
2582         }
2583
2584         if (obj_req->img_request->snapc->num_snaps && bytes > 0) {
2585                 /*
2586                  * Send a copyup request with an empty snapshot context to
2587                  * deep-copyup the object through all existing snapshots.
2588                  * A second request with the current snapshot context will be
2589                  * sent for the actual modification.
2590                  */
2591                 obj_req->write_state = RBD_OBJ_WRITE_COPYUP_EMPTY_SNAPC;
2592                 return rbd_obj_issue_copyup_empty_snapc(obj_req, bytes);
2593         }
2594
2595         obj_req->write_state = RBD_OBJ_WRITE_COPYUP_OPS;
2596         return rbd_obj_issue_copyup_ops(obj_req, bytes);
2597 }
2598
2599 static int setup_copyup_bvecs(struct rbd_obj_request *obj_req, u64 obj_overlap)
2600 {
2601         u32 i;
2602
2603         rbd_assert(!obj_req->copyup_bvecs);
2604         obj_req->copyup_bvec_count = calc_pages_for(0, obj_overlap);
2605         obj_req->copyup_bvecs = kcalloc(obj_req->copyup_bvec_count,
2606                                         sizeof(*obj_req->copyup_bvecs),
2607                                         GFP_NOIO);
2608         if (!obj_req->copyup_bvecs)
2609                 return -ENOMEM;
2610
2611         for (i = 0; i < obj_req->copyup_bvec_count; i++) {
2612                 unsigned int len = min(obj_overlap, (u64)PAGE_SIZE);
2613
2614                 obj_req->copyup_bvecs[i].bv_page = alloc_page(GFP_NOIO);
2615                 if (!obj_req->copyup_bvecs[i].bv_page)
2616                         return -ENOMEM;
2617
2618                 obj_req->copyup_bvecs[i].bv_offset = 0;
2619                 obj_req->copyup_bvecs[i].bv_len = len;
2620                 obj_overlap -= len;
2621         }
2622
2623         rbd_assert(!obj_overlap);
2624         return 0;
2625 }
2626
2627 static int rbd_obj_handle_write_guard(struct rbd_obj_request *obj_req)
2628 {
2629         struct rbd_device *rbd_dev = obj_req->img_request->rbd_dev;
2630         int ret;
2631
2632         rbd_assert(obj_req->num_img_extents);
2633         prune_extents(obj_req->img_extents, &obj_req->num_img_extents,
2634                       rbd_dev->parent_overlap);
2635         if (!obj_req->num_img_extents) {
2636                 /*
2637                  * The overlap has become 0 (most likely because the
2638                  * image has been flattened).  Re-submit the original write
2639                  * request -- pass MODS_ONLY since the copyup isn't needed
2640                  * anymore.
2641                  */
2642                 obj_req->write_state = RBD_OBJ_WRITE_COPYUP_OPS;
2643                 return rbd_obj_issue_copyup_ops(obj_req, MODS_ONLY);
2644         }
2645
2646         ret = setup_copyup_bvecs(obj_req, rbd_obj_img_extents_bytes(obj_req));
2647         if (ret)
2648                 return ret;
2649
2650         obj_req->write_state = RBD_OBJ_WRITE_READ_FROM_PARENT;
2651         return rbd_obj_read_from_parent(obj_req);
2652 }
2653
2654 static bool rbd_obj_handle_write(struct rbd_obj_request *obj_req)
2655 {
2656         int ret;
2657
2658         switch (obj_req->write_state) {
2659         case RBD_OBJ_WRITE_GUARD:
2660                 rbd_assert(!obj_req->xferred);
2661                 if (obj_req->result == -ENOENT) {
2662                         /*
2663                          * The target object doesn't exist.  Read the data for
2664                          * the entire target object up to the overlap point (if
2665                          * any) from the parent, so we can use it for a copyup.
2666                          */
2667                         ret = rbd_obj_handle_write_guard(obj_req);
2668                         if (ret) {
2669                                 obj_req->result = ret;
2670                                 return true;
2671                         }
2672                         return false;
2673                 }
2674                 /* fall through */
2675         case RBD_OBJ_WRITE_FLAT:
2676         case RBD_OBJ_WRITE_COPYUP_OPS:
2677                 if (!obj_req->result)
2678                         /*
2679                          * There is no such thing as a successful short
2680                          * write -- indicate the whole request was satisfied.
2681                          */
2682                         obj_req->xferred = obj_req->ex.oe_len;
2683                 return true;
2684         case RBD_OBJ_WRITE_READ_FROM_PARENT:
2685                 if (obj_req->result)
2686                         return true;
2687
2688                 rbd_assert(obj_req->xferred);
2689                 ret = rbd_obj_issue_copyup(obj_req, obj_req->xferred);
2690                 if (ret) {
2691                         obj_req->result = ret;
2692                         obj_req->xferred = 0;
2693                         return true;
2694                 }
2695                 return false;
2696         case RBD_OBJ_WRITE_COPYUP_EMPTY_SNAPC:
2697                 if (obj_req->result)
2698                         return true;
2699
2700                 obj_req->write_state = RBD_OBJ_WRITE_COPYUP_OPS;
2701                 ret = rbd_obj_issue_copyup_ops(obj_req, MODS_ONLY);
2702                 if (ret) {
2703                         obj_req->result = ret;
2704                         return true;
2705                 }
2706                 return false;
2707         default:
2708                 BUG();
2709         }
2710 }
2711
2712 /*
2713  * Returns true if @obj_req is completed, or false otherwise.
2714  */
2715 static bool __rbd_obj_handle_request(struct rbd_obj_request *obj_req)
2716 {
2717         switch (obj_req->img_request->op_type) {
2718         case OBJ_OP_READ:
2719                 return rbd_obj_handle_read(obj_req);
2720         case OBJ_OP_WRITE:
2721                 return rbd_obj_handle_write(obj_req);
2722         case OBJ_OP_DISCARD:
2723         case OBJ_OP_ZEROOUT:
2724                 if (rbd_obj_handle_write(obj_req)) {
2725                         /*
2726                          * Hide -ENOENT from delete/truncate/zero -- discarding
2727                          * a non-existent object is not a problem.
2728                          */
2729                         if (obj_req->result == -ENOENT) {
2730                                 obj_req->result = 0;
2731                                 obj_req->xferred = obj_req->ex.oe_len;
2732                         }
2733                         return true;
2734                 }
2735                 return false;
2736         default:
2737                 BUG();
2738         }
2739 }
2740
2741 static void rbd_obj_end_request(struct rbd_obj_request *obj_req)
2742 {
2743         struct rbd_img_request *img_req = obj_req->img_request;
2744
2745         rbd_assert((!obj_req->result &&
2746                     obj_req->xferred == obj_req->ex.oe_len) ||
2747                    (obj_req->result < 0 && !obj_req->xferred));
2748         if (!obj_req->result) {
2749                 img_req->xferred += obj_req->xferred;
2750                 return;
2751         }
2752
2753         rbd_warn(img_req->rbd_dev,
2754                  "%s at objno %llu %llu~%llu result %d xferred %llu",
2755                  obj_op_name(img_req->op_type), obj_req->ex.oe_objno,
2756                  obj_req->ex.oe_off, obj_req->ex.oe_len, obj_req->result,
2757                  obj_req->xferred);
2758         if (!img_req->result) {
2759                 img_req->result = obj_req->result;
2760                 img_req->xferred = 0;
2761         }
2762 }
2763
2764 static void rbd_img_end_child_request(struct rbd_img_request *img_req)
2765 {
2766         struct rbd_obj_request *obj_req = img_req->obj_request;
2767
2768         rbd_assert(test_bit(IMG_REQ_CHILD, &img_req->flags));
2769         rbd_assert((!img_req->result &&
2770                     img_req->xferred == rbd_obj_img_extents_bytes(obj_req)) ||
2771                    (img_req->result < 0 && !img_req->xferred));
2772
2773         obj_req->result = img_req->result;
2774         obj_req->xferred = img_req->xferred;
2775         rbd_img_request_put(img_req);
2776 }
2777
2778 static void rbd_img_end_request(struct rbd_img_request *img_req)
2779 {
2780         rbd_assert(!test_bit(IMG_REQ_CHILD, &img_req->flags));
2781         rbd_assert((!img_req->result &&
2782                     img_req->xferred == blk_rq_bytes(img_req->rq)) ||
2783                    (img_req->result < 0 && !img_req->xferred));
2784
2785         blk_mq_end_request(img_req->rq,
2786                            errno_to_blk_status(img_req->result));
2787         rbd_img_request_put(img_req);
2788 }
2789
2790 static void rbd_obj_handle_request(struct rbd_obj_request *obj_req)
2791 {
2792         struct rbd_img_request *img_req;
2793
2794 again:
2795         if (!__rbd_obj_handle_request(obj_req))
2796                 return;
2797
2798         img_req = obj_req->img_request;
2799         spin_lock(&img_req->completion_lock);
2800         rbd_obj_end_request(obj_req);
2801         rbd_assert(img_req->pending_count);
2802         if (--img_req->pending_count) {
2803                 spin_unlock(&img_req->completion_lock);
2804                 return;
2805         }
2806
2807         spin_unlock(&img_req->completion_lock);
2808         if (test_bit(IMG_REQ_CHILD, &img_req->flags)) {
2809                 obj_req = img_req->obj_request;
2810                 rbd_img_end_child_request(img_req);
2811                 goto again;
2812         }
2813         rbd_img_end_request(img_req);
2814 }
2815
2816 static const struct rbd_client_id rbd_empty_cid;
2817
2818 static bool rbd_cid_equal(const struct rbd_client_id *lhs,
2819                           const struct rbd_client_id *rhs)
2820 {
2821         return lhs->gid == rhs->gid && lhs->handle == rhs->handle;
2822 }
2823
2824 static struct rbd_client_id rbd_get_cid(struct rbd_device *rbd_dev)
2825 {
2826         struct rbd_client_id cid;
2827
2828         mutex_lock(&rbd_dev->watch_mutex);
2829         cid.gid = ceph_client_gid(rbd_dev->rbd_client->client);
2830         cid.handle = rbd_dev->watch_cookie;
2831         mutex_unlock(&rbd_dev->watch_mutex);
2832         return cid;
2833 }
2834
2835 /*
2836  * lock_rwsem must be held for write
2837  */
2838 static void rbd_set_owner_cid(struct rbd_device *rbd_dev,
2839                               const struct rbd_client_id *cid)
2840 {
2841         dout("%s rbd_dev %p %llu-%llu -> %llu-%llu\n", __func__, rbd_dev,
2842              rbd_dev->owner_cid.gid, rbd_dev->owner_cid.handle,
2843              cid->gid, cid->handle);
2844         rbd_dev->owner_cid = *cid; /* struct */
2845 }
2846
2847 static void format_lock_cookie(struct rbd_device *rbd_dev, char *buf)
2848 {
2849         mutex_lock(&rbd_dev->watch_mutex);
2850         sprintf(buf, "%s %llu", RBD_LOCK_COOKIE_PREFIX, rbd_dev->watch_cookie);
2851         mutex_unlock(&rbd_dev->watch_mutex);
2852 }
2853
2854 static void __rbd_lock(struct rbd_device *rbd_dev, const char *cookie)
2855 {
2856         struct rbd_client_id cid = rbd_get_cid(rbd_dev);
2857
2858         strcpy(rbd_dev->lock_cookie, cookie);
2859         rbd_set_owner_cid(rbd_dev, &cid);
2860         queue_work(rbd_dev->task_wq, &rbd_dev->acquired_lock_work);
2861 }
2862
2863 /*
2864  * lock_rwsem must be held for write
2865  */
2866 static int rbd_lock(struct rbd_device *rbd_dev)
2867 {
2868         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
2869         char cookie[32];
2870         int ret;
2871
2872         WARN_ON(__rbd_is_lock_owner(rbd_dev) ||
2873                 rbd_dev->lock_cookie[0] != '\0');
2874
2875         format_lock_cookie(rbd_dev, cookie);
2876         ret = ceph_cls_lock(osdc, &rbd_dev->header_oid, &rbd_dev->header_oloc,
2877                             RBD_LOCK_NAME, CEPH_CLS_LOCK_EXCLUSIVE, cookie,
2878                             RBD_LOCK_TAG, "", 0);
2879         if (ret)
2880                 return ret;
2881
2882         rbd_dev->lock_state = RBD_LOCK_STATE_LOCKED;
2883         __rbd_lock(rbd_dev, cookie);
2884         return 0;
2885 }
2886
2887 /*
2888  * lock_rwsem must be held for write
2889  */
2890 static void rbd_unlock(struct rbd_device *rbd_dev)
2891 {
2892         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
2893         int ret;
2894
2895         WARN_ON(!__rbd_is_lock_owner(rbd_dev) ||
2896                 rbd_dev->lock_cookie[0] == '\0');
2897
2898         ret = ceph_cls_unlock(osdc, &rbd_dev->header_oid, &rbd_dev->header_oloc,
2899                               RBD_LOCK_NAME, rbd_dev->lock_cookie);
2900         if (ret && ret != -ENOENT)
2901                 rbd_warn(rbd_dev, "failed to unlock: %d", ret);
2902
2903         /* treat errors as the image is unlocked */
2904         rbd_dev->lock_state = RBD_LOCK_STATE_UNLOCKED;
2905         rbd_dev->lock_cookie[0] = '\0';
2906         rbd_set_owner_cid(rbd_dev, &rbd_empty_cid);
2907         queue_work(rbd_dev->task_wq, &rbd_dev->released_lock_work);
2908 }
2909
2910 static int __rbd_notify_op_lock(struct rbd_device *rbd_dev,
2911                                 enum rbd_notify_op notify_op,
2912                                 struct page ***preply_pages,
2913                                 size_t *preply_len)
2914 {
2915         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
2916         struct rbd_client_id cid = rbd_get_cid(rbd_dev);
2917         char buf[4 + 8 + 8 + CEPH_ENCODING_START_BLK_LEN];
2918         int buf_size = sizeof(buf);
2919         void *p = buf;
2920
2921         dout("%s rbd_dev %p notify_op %d\n", __func__, rbd_dev, notify_op);
2922
2923         /* encode *LockPayload NotifyMessage (op + ClientId) */
2924         ceph_start_encoding(&p, 2, 1, buf_size - CEPH_ENCODING_START_BLK_LEN);
2925         ceph_encode_32(&p, notify_op);
2926         ceph_encode_64(&p, cid.gid);
2927         ceph_encode_64(&p, cid.handle);
2928
2929         return ceph_osdc_notify(osdc, &rbd_dev->header_oid,
2930                                 &rbd_dev->header_oloc, buf, buf_size,
2931                                 RBD_NOTIFY_TIMEOUT, preply_pages, preply_len);
2932 }
2933
2934 static void rbd_notify_op_lock(struct rbd_device *rbd_dev,
2935                                enum rbd_notify_op notify_op)
2936 {
2937         struct page **reply_pages;
2938         size_t reply_len;
2939
2940         __rbd_notify_op_lock(rbd_dev, notify_op, &reply_pages, &reply_len);
2941         ceph_release_page_vector(reply_pages, calc_pages_for(0, reply_len));
2942 }
2943
2944 static void rbd_notify_acquired_lock(struct work_struct *work)
2945 {
2946         struct rbd_device *rbd_dev = container_of(work, struct rbd_device,
2947                                                   acquired_lock_work);
2948
2949         rbd_notify_op_lock(rbd_dev, RBD_NOTIFY_OP_ACQUIRED_LOCK);
2950 }
2951
2952 static void rbd_notify_released_lock(struct work_struct *work)
2953 {
2954         struct rbd_device *rbd_dev = container_of(work, struct rbd_device,
2955                                                   released_lock_work);
2956
2957         rbd_notify_op_lock(rbd_dev, RBD_NOTIFY_OP_RELEASED_LOCK);
2958 }
2959
2960 static int rbd_request_lock(struct rbd_device *rbd_dev)
2961 {
2962         struct page **reply_pages;
2963         size_t reply_len;
2964         bool lock_owner_responded = false;
2965         int ret;
2966
2967         dout("%s rbd_dev %p\n", __func__, rbd_dev);
2968
2969         ret = __rbd_notify_op_lock(rbd_dev, RBD_NOTIFY_OP_REQUEST_LOCK,
2970                                    &reply_pages, &reply_len);
2971         if (ret && ret != -ETIMEDOUT) {
2972                 rbd_warn(rbd_dev, "failed to request lock: %d", ret);
2973                 goto out;
2974         }
2975
2976         if (reply_len > 0 && reply_len <= PAGE_SIZE) {
2977                 void *p = page_address(reply_pages[0]);
2978                 void *const end = p + reply_len;
2979                 u32 n;
2980
2981                 ceph_decode_32_safe(&p, end, n, e_inval); /* num_acks */
2982                 while (n--) {
2983                         u8 struct_v;
2984                         u32 len;
2985
2986                         ceph_decode_need(&p, end, 8 + 8, e_inval);
2987                         p += 8 + 8; /* skip gid and cookie */
2988
2989                         ceph_decode_32_safe(&p, end, len, e_inval);
2990                         if (!len)
2991                                 continue;
2992
2993                         if (lock_owner_responded) {
2994                                 rbd_warn(rbd_dev,
2995                                          "duplicate lock owners detected");
2996                                 ret = -EIO;
2997                                 goto out;
2998                         }
2999
3000                         lock_owner_responded = true;
3001                         ret = ceph_start_decoding(&p, end, 1, "ResponseMessage",
3002                                                   &struct_v, &len);
3003                         if (ret) {
3004                                 rbd_warn(rbd_dev,
3005                                          "failed to decode ResponseMessage: %d",
3006                                          ret);
3007                                 goto e_inval;
3008                         }
3009
3010                         ret = ceph_decode_32(&p);
3011                 }
3012         }
3013
3014         if (!lock_owner_responded) {
3015                 rbd_warn(rbd_dev, "no lock owners detected");
3016                 ret = -ETIMEDOUT;
3017         }
3018
3019 out:
3020         ceph_release_page_vector(reply_pages, calc_pages_for(0, reply_len));
3021         return ret;
3022
3023 e_inval:
3024         ret = -EINVAL;
3025         goto out;
3026 }
3027
3028 static void wake_requests(struct rbd_device *rbd_dev, bool wake_all)
3029 {
3030         dout("%s rbd_dev %p wake_all %d\n", __func__, rbd_dev, wake_all);
3031
3032         cancel_delayed_work(&rbd_dev->lock_dwork);
3033         if (wake_all)
3034                 wake_up_all(&rbd_dev->lock_waitq);
3035         else
3036                 wake_up(&rbd_dev->lock_waitq);
3037 }
3038
3039 static int get_lock_owner_info(struct rbd_device *rbd_dev,
3040                                struct ceph_locker **lockers, u32 *num_lockers)
3041 {
3042         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
3043         u8 lock_type;
3044         char *lock_tag;
3045         int ret;
3046
3047         dout("%s rbd_dev %p\n", __func__, rbd_dev);
3048
3049         ret = ceph_cls_lock_info(osdc, &rbd_dev->header_oid,
3050                                  &rbd_dev->header_oloc, RBD_LOCK_NAME,
3051                                  &lock_type, &lock_tag, lockers, num_lockers);
3052         if (ret)
3053                 return ret;
3054
3055         if (*num_lockers == 0) {
3056                 dout("%s rbd_dev %p no lockers detected\n", __func__, rbd_dev);
3057                 goto out;
3058         }
3059
3060         if (strcmp(lock_tag, RBD_LOCK_TAG)) {
3061                 rbd_warn(rbd_dev, "locked by external mechanism, tag %s",
3062                          lock_tag);
3063                 ret = -EBUSY;
3064                 goto out;
3065         }
3066
3067         if (lock_type == CEPH_CLS_LOCK_SHARED) {
3068                 rbd_warn(rbd_dev, "shared lock type detected");
3069                 ret = -EBUSY;
3070                 goto out;
3071         }
3072
3073         if (strncmp((*lockers)[0].id.cookie, RBD_LOCK_COOKIE_PREFIX,
3074                     strlen(RBD_LOCK_COOKIE_PREFIX))) {
3075                 rbd_warn(rbd_dev, "locked by external mechanism, cookie %s",
3076                          (*lockers)[0].id.cookie);
3077                 ret = -EBUSY;
3078                 goto out;
3079         }
3080
3081 out:
3082         kfree(lock_tag);
3083         return ret;
3084 }
3085
3086 static int find_watcher(struct rbd_device *rbd_dev,
3087                         const struct ceph_locker *locker)
3088 {
3089         struct ceph_osd_client *osdc = &rbd_dev->rbd_client->client->osdc;
3090         struct ceph_watch_item *watchers;
3091         u32 num_watchers;
3092         u64 cookie;
3093         int i;
3094         int ret;
3095
3096         ret = ceph_osdc_list_watchers(osdc, &rbd_dev->header_oid,
3097                                       &rbd_dev->header_oloc, &watchers,
3098                                       &num_watchers);
3099         if (ret)
3100                 return ret;
3101
3102         sscanf(locker->id.cookie, RBD_LOCK_COOKIE_PREFIX " %llu", &cookie);
3103         for (i = 0; i < num_watchers; i++) {
3104                 if (!memcmp(&watchers[i].addr, &locker->info.addr,
3105                             sizeof(locker->info.addr)) &&
3106                     watchers[i].cookie == cookie) {
3107                         struct rbd_client_id cid = {
3108                                 .gid = le64_to_cpu(watchers[i].name.num),
3109                                 .handle = cookie,
3110                         };
3111
3112                         dout("%s rbd_dev %p found cid %llu-%llu\n", __func__,
3113                              rbd_dev, cid.gid, cid.handle);
3114                         rbd_set_owner_cid(rbd_dev, &cid);
3115                         ret = 1;
3116                         goto out;
3117                 }
3118         }
3119
3120         dout("%s rbd_dev %p no watchers\n", __func__, rbd_dev);
3121         ret = 0;
3122 out:
3123         kfree(watchers);
3124         return ret;
3125 }
3126
3127 /*
3128  * lock_rwsem must be held for write
3129  */
3130 static int rbd_try_lock(struct rbd_device *rbd_dev)
3131 {
3132         struct ceph_client *client = rbd_dev->rbd_client->client;
3133         struct ceph_locker *lockers;
3134         u32 num_lockers;
3135         int ret;
3136
3137         for (;;) {
3138                 ret = rbd_lock(rbd_dev);
3139                 if (ret != -EBUSY)
3140                         return ret;
3141
3142                 /* determine if the current lock holder is still alive */
3143                 ret = get_lock_owner_info(rbd_dev, &lockers, &num_lockers);
3144                 if (ret)
3145                         return ret;
3146
3147                 if (num_lockers == 0)
3148                         goto again;
3149
3150                 ret = find_watcher(rbd_dev, lockers);
3151                 if (ret) {
3152                         if (ret > 0)
3153                                 ret = 0; /* have to request lock */
3154                         goto out;
3155                 }
3156
3157                 rbd_warn(rbd_dev, "%s%llu seems dead, breaking lock",
3158                          ENTITY_NAME(lockers[0].id.name));
3159
3160                 ret = ceph_monc_blacklist_add(&client->monc,
3161                                               &lockers[0].info.addr);
3162                 if (ret) {
3163                         rbd_warn(rbd_dev, "blacklist of %s%llu failed: %d",
3164                                  ENTITY_NAME(lockers[0].id.name), ret);
3165                         goto out;
3166                 }
3167
3168                 ret = ceph_cls_break_lock(&client->osdc, &rbd_dev->header_oid,
3169                                           &rbd_dev->header_oloc, RBD_LOCK_NAME,
3170                                           lockers[0].id.cookie,
3171                                           &lockers[0].id.name);
3172                 if (ret && ret != -ENOENT)
3173                         goto out;
3174
3175 again:
3176                 ceph_free_lockers(lockers, num_lockers);
3177         }
3178
3179 out:
3180         ceph_free_lockers(lockers, num_lockers);
3181         return ret;
3182 }
3183
3184 /*
3185  * ret is set only if lock_state is RBD_LOCK_STATE_UNLOCKED
3186  */
3187 static enum rbd_lock_state rbd_try_acquire_lock(struct rbd_device *rbd_dev,
3188                                                 int *pret)
3189 {
3190         enum rbd_lock_state lock_state;
3191
3192         down_read(&rbd_dev->lock_rwsem);
3193         dout("%s rbd_dev %p read lock_state %d\n", __func__, rbd_dev,
3194              rbd_dev->lock_state);
3195         if (__rbd_is_lock_owner(rbd_dev)) {
3196                 lock_state = rbd_dev->lock_state;
3197                 up_read(&rbd_dev->lock_rwsem);
3198                 return lock_state;
3199         }
3200
3201         up_read(&rbd_dev->lock_rwsem);
3202         down_write(&rbd_dev->lock_rwsem);
3203         dout("%s rbd_dev %p write lock_state %d\n", __func__, rbd_dev,
3204              rbd_dev->lock_state);
3205         if (!__rbd_is_lock_owner(rbd_dev)) {
3206                 *pret = rbd_try_lock(rbd_dev);
3207                 if (*pret)
3208                         rbd_warn(rbd_dev, "failed to acquire lock: %d", *pret);
3209         }
3210
3211         lock_state = rbd_dev->lock_state;
3212         up_write(&rbd_dev->lock_rwsem);
3213         return lock_state;
3214 }
3215
3216 static void rbd_acquire_lock(struct work_struct *work)
3217 {
3218         struct rbd_device *rbd_dev = container_of(to_delayed_work(work),
3219                                             struct rbd_device, lock_dwork);
3220         enum rbd_lock_state lock_state;
3221         int ret = 0;
3222
3223         dout("%s rbd_dev %p\n", __func__, rbd_dev);
3224 again:
3225         lock_state = rbd_try_acquire_lock(rbd_dev, &ret);
3226         if (lock_state != RBD_LOCK_STATE_UNLOCKED || ret == -EBLACKLISTED) {
3227                 if (lock_state == RBD_LOCK_STATE_LOCKED)
3228                         wake_requests(rbd_dev, true);
3229                 dout("%s rbd_dev %p lock_state %d ret %d - done\n", __func__,
3230                      rbd_dev, lock_state, ret);
3231                 return;
3232         }
3233
3234         ret = rbd_request_lock(rbd_dev);
3235         if (ret == -ETIMEDOUT) {
3236                 goto again; /* treat this as a dead client */
3237         } else if (ret == -EROFS) {
3238                 rbd_warn(rbd_dev, "peer will not release lock");
3239                 /*
3240                  * If this is rbd_add_acquire_lock(), we want to fail
3241                  * immediately -- reuse BLACKLISTED flag.  Otherwise we
3242                  * want to block.
3243                  */
3244                 if (!(rbd_dev->disk->flags & GENHD_FL_UP)) {
3245                         set_bit(RBD_DEV_FLAG_BLACKLISTED, &rbd_dev->flags);
3246                         /* wake "rbd map --exclusive" process */
3247                         wake_requests(rbd_dev, false);
3248                 }
3249         } else if (ret < 0) {
3250                 rbd_warn(rbd_dev, "error requesting lock: %d", ret);
3251                 mod_delayed_work(rbd_dev->task_wq, &rbd_dev->lock_dwork,
3252                                  RBD_RETRY_DELAY);
3253         } else {
3254                 /*
3255                  * lock owner acked, but resend if we don't see them
3256                  * release the lock
3257                  */
3258                 dout("%s rbd_dev %p requeueing lock_dwork\n", __func__,
3259                      rbd_dev);
3260                 mod_delayed_work(rbd_dev->task_wq, &rbd_dev->lock_dwork,
3261                     msecs_to_jiffies(2 * RBD_NOTIFY_TIMEOUT * MSEC_PER_SEC));
3262         }
3263 }
3264
3265 /*
3266  * lock_rwsem must be held for write
3267  */
3268 static bool rbd_release_lock(struct rbd_device *rbd_dev)
3269 {
3270         dout("%s rbd_dev %p read lock_state %d\n", __func__, rbd_dev,
3271              rbd_dev->lock_state);
3272         if (rbd_dev->lock_state != RBD_LOCK_STATE_LOCKED)
3273                 return false;
3274
3275         rbd_dev->lock_state = RBD_LOCK_STATE_RELEASING;
3276         downgrade_write(&rbd_dev->lock_rwsem);
3277         /*
3278          * Ensure that all in-flight IO is flushed.
3279          *
3280          * FIXME: ceph_osdc_sync() flushes the entire OSD client, which
3281          * may be shared with other devices.
3282          */
3283         ceph_osdc_sync(&rbd_dev->rbd_client->client->osdc);
3284         up_read(&rbd_dev->lock_rwsem);
3285
3286         down_write(&rbd_dev->lock_rwsem);
3287         dout("%s rbd_dev %p write lock_state %d\n", __func__, rbd_dev,
3288              rbd_dev->lock_state);
3289         if (rbd_dev->lock_state != RBD_LOCK_STATE_RELEASING)
3290                 return false;
3291
3292         rbd_unlock(rbd_dev);
3293         /*
3294          * Give others a chance to grab the lock - we would re-acquire
3295          * almost immediately if we got new IO during ceph_osdc_sync()
3296          * otherwise.  We need to ack our own notifications, so this
3297          * lock_dwork will be requeued from rbd_wait_state_locked()
3298          * after wake_requests() in rbd_handle_released_lock().
3299          */
3300         cancel_delayed_work(&rbd_dev->lock_dwork);
3301         return true;
3302 }
3303
3304 static void rbd_release_lock_work(struct work_struct *work)
3305 {
3306         struct rbd_device *rbd_dev = container_of(work, struct rbd_device,
3307                                                   unlock_work);
3308
3309         down_write(&rbd_dev->lock_rwsem);
3310         rbd_release_lock(rbd_dev);
3311         up_write(&rbd_dev->lock_rwsem);
3312 }
3313
3314 static void rbd_handle_acquired_lock(struct rbd_device *rbd_dev, u8 struct_v,
3315                                      void **p)
3316 {
3317         struct rbd_client_id cid = { 0 };
3318
3319         if (struct_v >= 2) {
3320                 cid.gid = ceph_decode_64(p);
3321                 cid.handle = ceph_decode_64(p);
3322         }