xref: /linux/net/ceph/osd_client.c (revision 10655007b9b679e46a9e383202c7bb791e5d1d13)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 #include <linux/ceph/ceph_debug.h>
4 
5 #include <linux/module.h>
6 #include <linux/err.h>
7 #include <linux/highmem.h>
8 #include <linux/mm.h>
9 #include <linux/overflow.h>
10 #include <linux/pagemap.h>
11 #include <linux/slab.h>
12 #include <linux/uaccess.h>
13 #ifdef CONFIG_BLOCK
14 #include <linux/bio.h>
15 #endif
16 
17 #include <linux/ceph/ceph_features.h>
18 #include <linux/ceph/libceph.h>
19 #include <linux/ceph/osd_client.h>
20 #include <linux/ceph/messenger.h>
21 #include <linux/ceph/decode.h>
22 #include <linux/ceph/auth.h>
23 #include <linux/ceph/pagelist.h>
24 #include <linux/ceph/striper.h>
25 
26 #define OSD_OPREPLY_FRONT_LEN	512
27 
28 static struct kmem_cache	*ceph_osd_request_cache;
29 
30 static const struct ceph_connection_operations osd_con_ops;
31 
32 /*
33  * Implement client access to distributed object storage cluster.
34  *
35  * All data objects are stored within a cluster/cloud of OSDs, or
36  * "object storage devices."  (Note that Ceph OSDs have _nothing_ to
37  * do with the T10 OSD extensions to SCSI.)  Ceph OSDs are simply
38  * remote daemons serving up and coordinating consistent and safe
39  * access to storage.
40  *
41  * Cluster membership and the mapping of data objects onto storage devices
42  * are described by the osd map.
43  *
44  * We keep track of pending OSD requests (read, write), resubmit
45  * requests to different OSDs when the cluster topology/data layout
46  * change, or retry the affected requests when the communications
47  * channel with an OSD is reset.
48  */
49 
50 static void link_request(struct ceph_osd *osd, struct ceph_osd_request *req);
51 static void unlink_request(struct ceph_osd *osd, struct ceph_osd_request *req);
52 static void link_linger(struct ceph_osd *osd,
53 			struct ceph_osd_linger_request *lreq);
54 static void unlink_linger(struct ceph_osd *osd,
55 			  struct ceph_osd_linger_request *lreq);
56 static void clear_backoffs(struct ceph_osd *osd);
57 
58 #if 1
59 static inline bool rwsem_is_wrlocked(struct rw_semaphore *sem)
60 {
61 	bool wrlocked = true;
62 
63 	if (unlikely(down_read_trylock(sem))) {
64 		wrlocked = false;
65 		up_read(sem);
66 	}
67 
68 	return wrlocked;
69 }
70 static inline void verify_osdc_locked(struct ceph_osd_client *osdc)
71 {
72 	WARN_ON(!rwsem_is_locked(&osdc->lock));
73 }
74 static inline void verify_osdc_wrlocked(struct ceph_osd_client *osdc)
75 {
76 	WARN_ON(!rwsem_is_wrlocked(&osdc->lock));
77 }
78 static inline void verify_osd_locked(struct ceph_osd *osd)
79 {
80 	struct ceph_osd_client *osdc = osd->o_osdc;
81 
82 	WARN_ON(!(mutex_is_locked(&osd->lock) &&
83 		  rwsem_is_locked(&osdc->lock)) &&
84 		!rwsem_is_wrlocked(&osdc->lock));
85 }
86 static inline void verify_lreq_locked(struct ceph_osd_linger_request *lreq)
87 {
88 	WARN_ON(!mutex_is_locked(&lreq->lock));
89 }
90 #else
91 static inline void verify_osdc_locked(struct ceph_osd_client *osdc) { }
92 static inline void verify_osdc_wrlocked(struct ceph_osd_client *osdc) { }
93 static inline void verify_osd_locked(struct ceph_osd *osd) { }
94 static inline void verify_lreq_locked(struct ceph_osd_linger_request *lreq) { }
95 #endif
96 
97 /*
98  * calculate the mapping of a file extent onto an object, and fill out the
99  * request accordingly.  shorten extent as necessary if it crosses an
100  * object boundary.
101  *
102  * fill osd op in request message.
103  */
104 static int calc_layout(struct ceph_file_layout *layout, u64 off, u64 *plen,
105 			u64 *objnum, u64 *objoff, u64 *objlen)
106 {
107 	u64 orig_len = *plen;
108 	u32 xlen;
109 
110 	/* object extent? */
111 	ceph_calc_file_object_mapping(layout, off, orig_len, objnum,
112 					  objoff, &xlen);
113 	*objlen = xlen;
114 	if (*objlen < orig_len) {
115 		*plen = *objlen;
116 		dout(" skipping last %llu, final file extent %llu~%llu\n",
117 		     orig_len - *plen, off, *plen);
118 	}
119 
120 	dout("calc_layout objnum=%llx %llu~%llu\n", *objnum, *objoff, *objlen);
121 	return 0;
122 }
123 
124 static void ceph_osd_data_init(struct ceph_osd_data *osd_data)
125 {
126 	memset(osd_data, 0, sizeof (*osd_data));
127 	osd_data->type = CEPH_OSD_DATA_TYPE_NONE;
128 }
129 
130 /*
131  * Consumes @pages if @own_pages is true.
132  */
133 static void ceph_osd_data_pages_init(struct ceph_osd_data *osd_data,
134 			struct page **pages, u64 length, u32 alignment,
135 			bool pages_from_pool, bool own_pages)
136 {
137 	osd_data->type = CEPH_OSD_DATA_TYPE_PAGES;
138 	osd_data->pages = pages;
139 	osd_data->length = length;
140 	osd_data->alignment = alignment;
141 	osd_data->pages_from_pool = pages_from_pool;
142 	osd_data->own_pages = own_pages;
143 }
144 
145 /*
146  * Consumes a ref on @pagelist.
147  */
148 static void ceph_osd_data_pagelist_init(struct ceph_osd_data *osd_data,
149 			struct ceph_pagelist *pagelist)
150 {
151 	osd_data->type = CEPH_OSD_DATA_TYPE_PAGELIST;
152 	osd_data->pagelist = pagelist;
153 }
154 
155 #ifdef CONFIG_BLOCK
156 static void ceph_osd_data_bio_init(struct ceph_osd_data *osd_data,
157 				   struct ceph_bio_iter *bio_pos,
158 				   u32 bio_length)
159 {
160 	osd_data->type = CEPH_OSD_DATA_TYPE_BIO;
161 	osd_data->bio_pos = *bio_pos;
162 	osd_data->bio_length = bio_length;
163 }
164 #endif /* CONFIG_BLOCK */
165 
166 static void ceph_osd_data_bvecs_init(struct ceph_osd_data *osd_data,
167 				     struct ceph_bvec_iter *bvec_pos,
168 				     u32 num_bvecs)
169 {
170 	osd_data->type = CEPH_OSD_DATA_TYPE_BVECS;
171 	osd_data->bvec_pos = *bvec_pos;
172 	osd_data->num_bvecs = num_bvecs;
173 }
174 
175 static void ceph_osd_iter_init(struct ceph_osd_data *osd_data,
176 			       struct iov_iter *iter)
177 {
178 	osd_data->type = CEPH_OSD_DATA_TYPE_ITER;
179 	osd_data->iter = *iter;
180 }
181 
182 static struct ceph_osd_data *
183 osd_req_op_raw_data_in(struct ceph_osd_request *osd_req, unsigned int which)
184 {
185 	BUG_ON(which >= osd_req->r_num_ops);
186 
187 	return &osd_req->r_ops[which].raw_data_in;
188 }
189 
190 struct ceph_osd_data *
191 osd_req_op_extent_osd_data(struct ceph_osd_request *osd_req,
192 			unsigned int which)
193 {
194 	return osd_req_op_data(osd_req, which, extent, osd_data);
195 }
196 EXPORT_SYMBOL(osd_req_op_extent_osd_data);
197 
198 void osd_req_op_raw_data_in_pages(struct ceph_osd_request *osd_req,
199 			unsigned int which, struct page **pages,
200 			u64 length, u32 alignment,
201 			bool pages_from_pool, bool own_pages)
202 {
203 	struct ceph_osd_data *osd_data;
204 
205 	osd_data = osd_req_op_raw_data_in(osd_req, which);
206 	ceph_osd_data_pages_init(osd_data, pages, length, alignment,
207 				pages_from_pool, own_pages);
208 }
209 EXPORT_SYMBOL(osd_req_op_raw_data_in_pages);
210 
211 void osd_req_op_extent_osd_data_pages(struct ceph_osd_request *osd_req,
212 			unsigned int which, struct page **pages,
213 			u64 length, u32 alignment,
214 			bool pages_from_pool, bool own_pages)
215 {
216 	struct ceph_osd_data *osd_data;
217 
218 	osd_data = osd_req_op_data(osd_req, which, extent, osd_data);
219 	ceph_osd_data_pages_init(osd_data, pages, length, alignment,
220 				pages_from_pool, own_pages);
221 }
222 EXPORT_SYMBOL(osd_req_op_extent_osd_data_pages);
223 
224 #ifdef CONFIG_BLOCK
225 void osd_req_op_extent_osd_data_bio(struct ceph_osd_request *osd_req,
226 				    unsigned int which,
227 				    struct ceph_bio_iter *bio_pos,
228 				    u32 bio_length)
229 {
230 	struct ceph_osd_data *osd_data;
231 
232 	osd_data = osd_req_op_data(osd_req, which, extent, osd_data);
233 	ceph_osd_data_bio_init(osd_data, bio_pos, bio_length);
234 }
235 EXPORT_SYMBOL(osd_req_op_extent_osd_data_bio);
236 #endif /* CONFIG_BLOCK */
237 
238 void osd_req_op_extent_osd_data_bvecs(struct ceph_osd_request *osd_req,
239 				      unsigned int which,
240 				      struct bio_vec *bvecs, u32 num_bvecs,
241 				      u32 bytes)
242 {
243 	struct ceph_osd_data *osd_data;
244 	struct ceph_bvec_iter it = {
245 		.bvecs = bvecs,
246 		.iter = { .bi_size = bytes },
247 	};
248 
249 	osd_data = osd_req_op_data(osd_req, which, extent, osd_data);
250 	ceph_osd_data_bvecs_init(osd_data, &it, num_bvecs);
251 }
252 EXPORT_SYMBOL(osd_req_op_extent_osd_data_bvecs);
253 
254 void osd_req_op_extent_osd_data_bvec_pos(struct ceph_osd_request *osd_req,
255 					 unsigned int which,
256 					 struct ceph_bvec_iter *bvec_pos)
257 {
258 	struct ceph_osd_data *osd_data;
259 
260 	osd_data = osd_req_op_data(osd_req, which, extent, osd_data);
261 	ceph_osd_data_bvecs_init(osd_data, bvec_pos, 0);
262 }
263 EXPORT_SYMBOL(osd_req_op_extent_osd_data_bvec_pos);
264 
265 /**
266  * osd_req_op_extent_osd_iter - Set up an operation with an iterator buffer
267  * @osd_req: The request to set up
268  * @which: Index of the operation in which to set the iter
269  * @iter: The buffer iterator
270  */
271 void osd_req_op_extent_osd_iter(struct ceph_osd_request *osd_req,
272 				unsigned int which, struct iov_iter *iter)
273 {
274 	struct ceph_osd_data *osd_data;
275 
276 	osd_data = osd_req_op_data(osd_req, which, extent, osd_data);
277 	ceph_osd_iter_init(osd_data, iter);
278 }
279 EXPORT_SYMBOL(osd_req_op_extent_osd_iter);
280 
281 static void osd_req_op_cls_request_info_pagelist(
282 			struct ceph_osd_request *osd_req,
283 			unsigned int which, struct ceph_pagelist *pagelist)
284 {
285 	struct ceph_osd_data *osd_data;
286 
287 	osd_data = osd_req_op_data(osd_req, which, cls, request_info);
288 	ceph_osd_data_pagelist_init(osd_data, pagelist);
289 }
290 
291 void osd_req_op_cls_request_data_pages(struct ceph_osd_request *osd_req,
292 			unsigned int which, struct page **pages, u64 length,
293 			u32 alignment, bool pages_from_pool, bool own_pages)
294 {
295 	struct ceph_osd_data *osd_data;
296 
297 	osd_data = osd_req_op_data(osd_req, which, cls, request_data);
298 	ceph_osd_data_pages_init(osd_data, pages, length, alignment,
299 				pages_from_pool, own_pages);
300 	osd_req->r_ops[which].cls.indata_len += length;
301 	osd_req->r_ops[which].indata_len += length;
302 }
303 EXPORT_SYMBOL(osd_req_op_cls_request_data_pages);
304 
305 void osd_req_op_cls_request_data_bvecs(struct ceph_osd_request *osd_req,
306 				       unsigned int which,
307 				       struct bio_vec *bvecs, u32 num_bvecs,
308 				       u32 bytes)
309 {
310 	struct ceph_osd_data *osd_data;
311 	struct ceph_bvec_iter it = {
312 		.bvecs = bvecs,
313 		.iter = { .bi_size = bytes },
314 	};
315 
316 	osd_data = osd_req_op_data(osd_req, which, cls, request_data);
317 	ceph_osd_data_bvecs_init(osd_data, &it, num_bvecs);
318 	osd_req->r_ops[which].cls.indata_len += bytes;
319 	osd_req->r_ops[which].indata_len += bytes;
320 }
321 EXPORT_SYMBOL(osd_req_op_cls_request_data_bvecs);
322 
323 void osd_req_op_cls_response_data_pages(struct ceph_osd_request *osd_req,
324 			unsigned int which, struct page **pages, u64 length,
325 			u32 alignment, bool pages_from_pool, bool own_pages)
326 {
327 	struct ceph_osd_data *osd_data;
328 
329 	osd_data = osd_req_op_data(osd_req, which, cls, response_data);
330 	ceph_osd_data_pages_init(osd_data, pages, length, alignment,
331 				pages_from_pool, own_pages);
332 }
333 EXPORT_SYMBOL(osd_req_op_cls_response_data_pages);
334 
335 static u64 ceph_osd_data_length(struct ceph_osd_data *osd_data)
336 {
337 	switch (osd_data->type) {
338 	case CEPH_OSD_DATA_TYPE_NONE:
339 		return 0;
340 	case CEPH_OSD_DATA_TYPE_PAGES:
341 		return osd_data->length;
342 	case CEPH_OSD_DATA_TYPE_PAGELIST:
343 		return (u64)osd_data->pagelist->length;
344 #ifdef CONFIG_BLOCK
345 	case CEPH_OSD_DATA_TYPE_BIO:
346 		return (u64)osd_data->bio_length;
347 #endif /* CONFIG_BLOCK */
348 	case CEPH_OSD_DATA_TYPE_BVECS:
349 		return osd_data->bvec_pos.iter.bi_size;
350 	case CEPH_OSD_DATA_TYPE_ITER:
351 		return iov_iter_count(&osd_data->iter);
352 	default:
353 		WARN(true, "unrecognized data type %d\n", (int)osd_data->type);
354 		return 0;
355 	}
356 }
357 
358 static void ceph_osd_data_release(struct ceph_osd_data *osd_data)
359 {
360 	if (osd_data->type == CEPH_OSD_DATA_TYPE_PAGES && osd_data->own_pages) {
361 		int num_pages;
362 
363 		num_pages = calc_pages_for((u64)osd_data->alignment,
364 						(u64)osd_data->length);
365 		ceph_release_page_vector(osd_data->pages, num_pages);
366 	} else if (osd_data->type == CEPH_OSD_DATA_TYPE_PAGELIST) {
367 		ceph_pagelist_release(osd_data->pagelist);
368 	}
369 	ceph_osd_data_init(osd_data);
370 }
371 
372 static void osd_req_op_data_release(struct ceph_osd_request *osd_req,
373 			unsigned int which)
374 {
375 	struct ceph_osd_req_op *op;
376 
377 	BUG_ON(which >= osd_req->r_num_ops);
378 	op = &osd_req->r_ops[which];
379 
380 	switch (op->op) {
381 	case CEPH_OSD_OP_READ:
382 	case CEPH_OSD_OP_SPARSE_READ:
383 	case CEPH_OSD_OP_WRITE:
384 	case CEPH_OSD_OP_WRITEFULL:
385 		kfree(op->extent.sparse_ext);
386 		ceph_osd_data_release(&op->extent.osd_data);
387 		break;
388 	case CEPH_OSD_OP_CALL:
389 		ceph_osd_data_release(&op->cls.request_info);
390 		ceph_osd_data_release(&op->cls.request_data);
391 		ceph_osd_data_release(&op->cls.response_data);
392 		break;
393 	case CEPH_OSD_OP_SETXATTR:
394 	case CEPH_OSD_OP_CMPXATTR:
395 		ceph_osd_data_release(&op->xattr.osd_data);
396 		break;
397 	case CEPH_OSD_OP_STAT:
398 		ceph_osd_data_release(&op->raw_data_in);
399 		break;
400 	case CEPH_OSD_OP_NOTIFY_ACK:
401 		ceph_osd_data_release(&op->notify_ack.request_data);
402 		break;
403 	case CEPH_OSD_OP_NOTIFY:
404 		ceph_osd_data_release(&op->notify.request_data);
405 		ceph_osd_data_release(&op->notify.response_data);
406 		break;
407 	case CEPH_OSD_OP_LIST_WATCHERS:
408 		ceph_osd_data_release(&op->list_watchers.response_data);
409 		break;
410 	case CEPH_OSD_OP_COPY_FROM2:
411 		ceph_osd_data_release(&op->copy_from.osd_data);
412 		break;
413 	default:
414 		break;
415 	}
416 }
417 
418 /*
419  * Assumes @t is zero-initialized.
420  */
421 static void target_init(struct ceph_osd_request_target *t)
422 {
423 	ceph_oid_init(&t->base_oid);
424 	ceph_oloc_init(&t->base_oloc);
425 	ceph_oid_init(&t->target_oid);
426 	ceph_oloc_init(&t->target_oloc);
427 
428 	ceph_osds_init(&t->acting);
429 	ceph_osds_init(&t->up);
430 	t->size = -1;
431 	t->min_size = -1;
432 
433 	t->osd = CEPH_HOMELESS_OSD;
434 }
435 
436 static void target_copy(struct ceph_osd_request_target *dest,
437 			const struct ceph_osd_request_target *src)
438 {
439 	ceph_oid_copy(&dest->base_oid, &src->base_oid);
440 	ceph_oloc_copy(&dest->base_oloc, &src->base_oloc);
441 	ceph_oid_copy(&dest->target_oid, &src->target_oid);
442 	ceph_oloc_copy(&dest->target_oloc, &src->target_oloc);
443 
444 	dest->pgid = src->pgid; /* struct */
445 	dest->spgid = src->spgid; /* struct */
446 	dest->pg_num = src->pg_num;
447 	dest->pg_num_mask = src->pg_num_mask;
448 	ceph_osds_copy(&dest->acting, &src->acting);
449 	ceph_osds_copy(&dest->up, &src->up);
450 	dest->size = src->size;
451 	dest->min_size = src->min_size;
452 	dest->sort_bitwise = src->sort_bitwise;
453 	dest->recovery_deletes = src->recovery_deletes;
454 
455 	dest->flags = src->flags;
456 	dest->used_replica = src->used_replica;
457 	dest->paused = src->paused;
458 
459 	dest->epoch = src->epoch;
460 	dest->last_force_resend = src->last_force_resend;
461 
462 	dest->osd = src->osd;
463 }
464 
465 static void target_destroy(struct ceph_osd_request_target *t)
466 {
467 	ceph_oid_destroy(&t->base_oid);
468 	ceph_oloc_destroy(&t->base_oloc);
469 	ceph_oid_destroy(&t->target_oid);
470 	ceph_oloc_destroy(&t->target_oloc);
471 }
472 
473 /*
474  * requests
475  */
476 static void request_release_checks(struct ceph_osd_request *req)
477 {
478 	WARN_ON(!RB_EMPTY_NODE(&req->r_node));
479 	WARN_ON(!RB_EMPTY_NODE(&req->r_mc_node));
480 	WARN_ON(!list_empty(&req->r_private_item));
481 	WARN_ON(req->r_osd);
482 }
483 
484 static void ceph_osdc_release_request(struct kref *kref)
485 {
486 	struct ceph_osd_request *req = container_of(kref,
487 					    struct ceph_osd_request, r_kref);
488 	unsigned int which;
489 
490 	dout("%s %p (r_request %p r_reply %p)\n", __func__, req,
491 	     req->r_request, req->r_reply);
492 	request_release_checks(req);
493 
494 	if (req->r_request)
495 		ceph_msg_put(req->r_request);
496 	if (req->r_reply)
497 		ceph_msg_put(req->r_reply);
498 
499 	for (which = 0; which < req->r_num_ops; which++)
500 		osd_req_op_data_release(req, which);
501 
502 	target_destroy(&req->r_t);
503 	ceph_put_snap_context(req->r_snapc);
504 
505 	if (req->r_mempool)
506 		mempool_free(req, req->r_osdc->req_mempool);
507 	else if (req->r_num_ops <= CEPH_OSD_SLAB_OPS)
508 		kmem_cache_free(ceph_osd_request_cache, req);
509 	else
510 		kfree(req);
511 }
512 
513 void ceph_osdc_get_request(struct ceph_osd_request *req)
514 {
515 	dout("%s %p (was %d)\n", __func__, req,
516 	     kref_read(&req->r_kref));
517 	kref_get(&req->r_kref);
518 }
519 EXPORT_SYMBOL(ceph_osdc_get_request);
520 
521 void ceph_osdc_put_request(struct ceph_osd_request *req)
522 {
523 	if (req) {
524 		dout("%s %p (was %d)\n", __func__, req,
525 		     kref_read(&req->r_kref));
526 		kref_put(&req->r_kref, ceph_osdc_release_request);
527 	}
528 }
529 EXPORT_SYMBOL(ceph_osdc_put_request);
530 
531 static void request_init(struct ceph_osd_request *req)
532 {
533 	/* req only, each op is zeroed in osd_req_op_init() */
534 	memset(req, 0, sizeof(*req));
535 
536 	kref_init(&req->r_kref);
537 	init_completion(&req->r_completion);
538 	RB_CLEAR_NODE(&req->r_node);
539 	RB_CLEAR_NODE(&req->r_mc_node);
540 	INIT_LIST_HEAD(&req->r_private_item);
541 
542 	target_init(&req->r_t);
543 }
544 
545 struct ceph_osd_request *ceph_osdc_alloc_request(struct ceph_osd_client *osdc,
546 					       struct ceph_snap_context *snapc,
547 					       unsigned int num_ops,
548 					       bool use_mempool,
549 					       gfp_t gfp_flags)
550 {
551 	struct ceph_osd_request *req;
552 
553 	if (use_mempool) {
554 		BUG_ON(num_ops > CEPH_OSD_SLAB_OPS);
555 		req = mempool_alloc(osdc->req_mempool, gfp_flags);
556 	} else if (num_ops <= CEPH_OSD_SLAB_OPS) {
557 		req = kmem_cache_alloc(ceph_osd_request_cache, gfp_flags);
558 	} else {
559 		BUG_ON(num_ops > CEPH_OSD_MAX_OPS);
560 		req = kmalloc_flex(*req, r_ops, num_ops, gfp_flags);
561 	}
562 	if (unlikely(!req))
563 		return NULL;
564 
565 	request_init(req);
566 	req->r_osdc = osdc;
567 	req->r_mempool = use_mempool;
568 	req->r_num_ops = num_ops;
569 	req->r_snapid = CEPH_NOSNAP;
570 	req->r_snapc = ceph_get_snap_context(snapc);
571 
572 	dout("%s req %p\n", __func__, req);
573 	return req;
574 }
575 EXPORT_SYMBOL(ceph_osdc_alloc_request);
576 
577 static int ceph_oloc_encoding_size(const struct ceph_object_locator *oloc)
578 {
579 	return 8 + 4 + 4 + 4 + (oloc->pool_ns ? oloc->pool_ns->len : 0);
580 }
581 
582 static int __ceph_osdc_alloc_messages(struct ceph_osd_request *req, gfp_t gfp,
583 				      int num_request_data_items,
584 				      int num_reply_data_items)
585 {
586 	struct ceph_osd_client *osdc = req->r_osdc;
587 	struct ceph_msg *msg;
588 	int msg_size;
589 
590 	WARN_ON(req->r_request || req->r_reply);
591 	WARN_ON(ceph_oid_empty(&req->r_base_oid));
592 	WARN_ON(ceph_oloc_empty(&req->r_base_oloc));
593 
594 	/* create request message */
595 	msg_size = CEPH_ENCODING_START_BLK_LEN +
596 			CEPH_PGID_ENCODING_LEN + 1; /* spgid */
597 	msg_size += 4 + 4 + 4; /* hash, osdmap_epoch, flags */
598 	msg_size += CEPH_ENCODING_START_BLK_LEN +
599 			sizeof(struct ceph_osd_reqid); /* reqid */
600 	msg_size += sizeof(struct ceph_blkin_trace_info); /* trace */
601 	msg_size += 4 + sizeof(struct ceph_timespec); /* client_inc, mtime */
602 	msg_size += CEPH_ENCODING_START_BLK_LEN +
603 			ceph_oloc_encoding_size(&req->r_base_oloc); /* oloc */
604 	msg_size += 4 + req->r_base_oid.name_len; /* oid */
605 	msg_size += 2 + req->r_num_ops * sizeof(struct ceph_osd_op);
606 	msg_size += 8; /* snapid */
607 	msg_size += 8; /* snap_seq */
608 	msg_size += 4 + 8 * (req->r_snapc ? req->r_snapc->num_snaps : 0);
609 	msg_size += 4 + 8; /* retry_attempt, features */
610 
611 	if (req->r_mempool)
612 		msg = ceph_msgpool_get(&osdc->msgpool_op, msg_size,
613 				       num_request_data_items);
614 	else
615 		msg = ceph_msg_new2(CEPH_MSG_OSD_OP, msg_size,
616 				    num_request_data_items, gfp, true);
617 	if (!msg)
618 		return -ENOMEM;
619 
620 	memset(msg->front.iov_base, 0, msg->front.iov_len);
621 	req->r_request = msg;
622 
623 	/* create reply message */
624 	msg_size = OSD_OPREPLY_FRONT_LEN;
625 	msg_size += req->r_base_oid.name_len;
626 	msg_size += req->r_num_ops * sizeof(struct ceph_osd_op);
627 
628 	if (req->r_mempool)
629 		msg = ceph_msgpool_get(&osdc->msgpool_op_reply, msg_size,
630 				       num_reply_data_items);
631 	else
632 		msg = ceph_msg_new2(CEPH_MSG_OSD_OPREPLY, msg_size,
633 				    num_reply_data_items, gfp, true);
634 	if (!msg)
635 		return -ENOMEM;
636 
637 	req->r_reply = msg;
638 
639 	return 0;
640 }
641 
642 static bool osd_req_opcode_valid(u16 opcode)
643 {
644 	switch (opcode) {
645 #define GENERATE_CASE(op, opcode, str)	case CEPH_OSD_OP_##op: return true;
646 __CEPH_FORALL_OSD_OPS(GENERATE_CASE)
647 #undef GENERATE_CASE
648 	default:
649 		return false;
650 	}
651 }
652 
653 static void get_num_data_items(struct ceph_osd_request *req,
654 			       int *num_request_data_items,
655 			       int *num_reply_data_items)
656 {
657 	struct ceph_osd_req_op *op;
658 
659 	*num_request_data_items = 0;
660 	*num_reply_data_items = 0;
661 
662 	for (op = req->r_ops; op != &req->r_ops[req->r_num_ops]; op++) {
663 		switch (op->op) {
664 		/* request */
665 		case CEPH_OSD_OP_WRITE:
666 		case CEPH_OSD_OP_WRITEFULL:
667 		case CEPH_OSD_OP_SETXATTR:
668 		case CEPH_OSD_OP_CMPXATTR:
669 		case CEPH_OSD_OP_NOTIFY_ACK:
670 		case CEPH_OSD_OP_COPY_FROM2:
671 			*num_request_data_items += 1;
672 			break;
673 
674 		/* reply */
675 		case CEPH_OSD_OP_STAT:
676 		case CEPH_OSD_OP_READ:
677 		case CEPH_OSD_OP_SPARSE_READ:
678 		case CEPH_OSD_OP_LIST_WATCHERS:
679 			*num_reply_data_items += 1;
680 			break;
681 
682 		/* both */
683 		case CEPH_OSD_OP_NOTIFY:
684 			*num_request_data_items += 1;
685 			*num_reply_data_items += 1;
686 			break;
687 		case CEPH_OSD_OP_CALL:
688 			*num_request_data_items += 2;
689 			*num_reply_data_items += 1;
690 			break;
691 
692 		default:
693 			WARN_ON(!osd_req_opcode_valid(op->op));
694 			break;
695 		}
696 	}
697 }
698 
699 /*
700  * oid, oloc and OSD op opcode(s) must be filled in before this function
701  * is called.
702  */
703 int ceph_osdc_alloc_messages(struct ceph_osd_request *req, gfp_t gfp)
704 {
705 	int num_request_data_items, num_reply_data_items;
706 
707 	get_num_data_items(req, &num_request_data_items, &num_reply_data_items);
708 	return __ceph_osdc_alloc_messages(req, gfp, num_request_data_items,
709 					  num_reply_data_items);
710 }
711 EXPORT_SYMBOL(ceph_osdc_alloc_messages);
712 
713 /*
714  * This is an osd op init function for opcodes that have no data or
715  * other information associated with them.  It also serves as a
716  * common init routine for all the other init functions, below.
717  */
718 struct ceph_osd_req_op *
719 osd_req_op_init(struct ceph_osd_request *osd_req, unsigned int which,
720 		 u16 opcode, u32 flags)
721 {
722 	struct ceph_osd_req_op *op;
723 
724 	BUG_ON(which >= osd_req->r_num_ops);
725 	BUG_ON(!osd_req_opcode_valid(opcode));
726 
727 	op = &osd_req->r_ops[which];
728 	memset(op, 0, sizeof (*op));
729 	op->op = opcode;
730 	op->flags = flags;
731 
732 	return op;
733 }
734 EXPORT_SYMBOL(osd_req_op_init);
735 
736 void osd_req_op_extent_init(struct ceph_osd_request *osd_req,
737 				unsigned int which, u16 opcode,
738 				u64 offset, u64 length,
739 				u64 truncate_size, u32 truncate_seq)
740 {
741 	struct ceph_osd_req_op *op = osd_req_op_init(osd_req, which,
742 						     opcode, 0);
743 	size_t payload_len = 0;
744 
745 	BUG_ON(opcode != CEPH_OSD_OP_READ && opcode != CEPH_OSD_OP_WRITE &&
746 	       opcode != CEPH_OSD_OP_WRITEFULL && opcode != CEPH_OSD_OP_ZERO &&
747 	       opcode != CEPH_OSD_OP_TRUNCATE && opcode != CEPH_OSD_OP_SPARSE_READ);
748 
749 	op->extent.offset = offset;
750 	op->extent.length = length;
751 	op->extent.truncate_size = truncate_size;
752 	op->extent.truncate_seq = truncate_seq;
753 	if (opcode == CEPH_OSD_OP_WRITE || opcode == CEPH_OSD_OP_WRITEFULL)
754 		payload_len += length;
755 
756 	op->indata_len = payload_len;
757 }
758 EXPORT_SYMBOL(osd_req_op_extent_init);
759 
760 void osd_req_op_extent_update(struct ceph_osd_request *osd_req,
761 				unsigned int which, u64 length)
762 {
763 	struct ceph_osd_req_op *op;
764 	u64 previous;
765 
766 	BUG_ON(which >= osd_req->r_num_ops);
767 	op = &osd_req->r_ops[which];
768 	previous = op->extent.length;
769 
770 	if (length == previous)
771 		return;		/* Nothing to do */
772 	BUG_ON(length > previous);
773 
774 	op->extent.length = length;
775 	if (op->op == CEPH_OSD_OP_WRITE || op->op == CEPH_OSD_OP_WRITEFULL)
776 		op->indata_len -= previous - length;
777 }
778 EXPORT_SYMBOL(osd_req_op_extent_update);
779 
780 void osd_req_op_extent_dup_last(struct ceph_osd_request *osd_req,
781 				unsigned int which, u64 offset_inc)
782 {
783 	struct ceph_osd_req_op *op, *prev_op;
784 
785 	BUG_ON(which + 1 >= osd_req->r_num_ops);
786 
787 	prev_op = &osd_req->r_ops[which];
788 	op = osd_req_op_init(osd_req, which + 1, prev_op->op, prev_op->flags);
789 	/* dup previous one */
790 	op->indata_len = prev_op->indata_len;
791 	op->outdata_len = prev_op->outdata_len;
792 	op->extent = prev_op->extent;
793 	/* adjust offset */
794 	op->extent.offset += offset_inc;
795 	op->extent.length -= offset_inc;
796 
797 	if (op->op == CEPH_OSD_OP_WRITE || op->op == CEPH_OSD_OP_WRITEFULL)
798 		op->indata_len -= offset_inc;
799 }
800 EXPORT_SYMBOL(osd_req_op_extent_dup_last);
801 
802 int osd_req_op_cls_init(struct ceph_osd_request *osd_req, unsigned int which,
803 			const char *class, const char *method)
804 {
805 	struct ceph_osd_req_op *op;
806 	struct ceph_pagelist *pagelist;
807 	size_t payload_len = 0;
808 	size_t size;
809 	int ret;
810 
811 	op = osd_req_op_init(osd_req, which, CEPH_OSD_OP_CALL, 0);
812 
813 	pagelist = ceph_pagelist_alloc(GFP_NOFS);
814 	if (!pagelist)
815 		return -ENOMEM;
816 
817 	op->cls.class_name = class;
818 	size = strlen(class);
819 	BUG_ON(size > (size_t) U8_MAX);
820 	op->cls.class_len = size;
821 	ret = ceph_pagelist_append(pagelist, class, size);
822 	if (ret)
823 		goto err_pagelist_free;
824 	payload_len += size;
825 
826 	op->cls.method_name = method;
827 	size = strlen(method);
828 	BUG_ON(size > (size_t) U8_MAX);
829 	op->cls.method_len = size;
830 	ret = ceph_pagelist_append(pagelist, method, size);
831 	if (ret)
832 		goto err_pagelist_free;
833 	payload_len += size;
834 
835 	osd_req_op_cls_request_info_pagelist(osd_req, which, pagelist);
836 	op->indata_len = payload_len;
837 	return 0;
838 
839 err_pagelist_free:
840 	ceph_pagelist_release(pagelist);
841 	return ret;
842 }
843 EXPORT_SYMBOL(osd_req_op_cls_init);
844 
845 int osd_req_op_xattr_init(struct ceph_osd_request *osd_req, unsigned int which,
846 			  u16 opcode, const char *name, const void *value,
847 			  size_t size, u8 cmp_op, u8 cmp_mode)
848 {
849 	struct ceph_osd_req_op *op = osd_req_op_init(osd_req, which,
850 						     opcode, 0);
851 	struct ceph_pagelist *pagelist;
852 	size_t payload_len;
853 	int ret;
854 
855 	BUG_ON(opcode != CEPH_OSD_OP_SETXATTR && opcode != CEPH_OSD_OP_CMPXATTR);
856 
857 	pagelist = ceph_pagelist_alloc(GFP_NOFS);
858 	if (!pagelist)
859 		return -ENOMEM;
860 
861 	payload_len = strlen(name);
862 	op->xattr.name_len = payload_len;
863 	ret = ceph_pagelist_append(pagelist, name, payload_len);
864 	if (ret)
865 		goto err_pagelist_free;
866 
867 	op->xattr.value_len = size;
868 	ret = ceph_pagelist_append(pagelist, value, size);
869 	if (ret)
870 		goto err_pagelist_free;
871 	payload_len += size;
872 
873 	op->xattr.cmp_op = cmp_op;
874 	op->xattr.cmp_mode = cmp_mode;
875 
876 	ceph_osd_data_pagelist_init(&op->xattr.osd_data, pagelist);
877 	op->indata_len = payload_len;
878 	return 0;
879 
880 err_pagelist_free:
881 	ceph_pagelist_release(pagelist);
882 	return ret;
883 }
884 EXPORT_SYMBOL(osd_req_op_xattr_init);
885 
886 /*
887  * @watch_opcode: CEPH_OSD_WATCH_OP_*
888  */
889 static void osd_req_op_watch_init(struct ceph_osd_request *req, int which,
890 				  u8 watch_opcode, u64 cookie, u32 gen)
891 {
892 	struct ceph_osd_req_op *op;
893 
894 	op = osd_req_op_init(req, which, CEPH_OSD_OP_WATCH, 0);
895 	op->watch.cookie = cookie;
896 	op->watch.op = watch_opcode;
897 	op->watch.gen = gen;
898 }
899 
900 /*
901  * prot_ver, timeout and notify payload (may be empty) should already be
902  * encoded in @request_pl
903  */
904 static void osd_req_op_notify_init(struct ceph_osd_request *req, int which,
905 				   u64 cookie, struct ceph_pagelist *request_pl)
906 {
907 	struct ceph_osd_req_op *op;
908 
909 	op = osd_req_op_init(req, which, CEPH_OSD_OP_NOTIFY, 0);
910 	op->notify.cookie = cookie;
911 
912 	ceph_osd_data_pagelist_init(&op->notify.request_data, request_pl);
913 	op->indata_len = request_pl->length;
914 }
915 
916 /*
917  * @flags: CEPH_OSD_OP_ALLOC_HINT_FLAG_*
918  */
919 void osd_req_op_alloc_hint_init(struct ceph_osd_request *osd_req,
920 				unsigned int which,
921 				u64 expected_object_size,
922 				u64 expected_write_size,
923 				u32 flags)
924 {
925 	struct ceph_osd_req_op *op;
926 
927 	op = osd_req_op_init(osd_req, which, CEPH_OSD_OP_SETALLOCHINT, 0);
928 	op->alloc_hint.expected_object_size = expected_object_size;
929 	op->alloc_hint.expected_write_size = expected_write_size;
930 	op->alloc_hint.flags = flags;
931 
932 	/*
933 	 * CEPH_OSD_OP_SETALLOCHINT op is advisory and therefore deemed
934 	 * not worth a feature bit.  Set FAILOK per-op flag to make
935 	 * sure older osds don't trip over an unsupported opcode.
936 	 */
937 	op->flags |= CEPH_OSD_OP_FLAG_FAILOK;
938 }
939 EXPORT_SYMBOL(osd_req_op_alloc_hint_init);
940 
941 static void ceph_osdc_msg_data_add(struct ceph_msg *msg,
942 				struct ceph_osd_data *osd_data)
943 {
944 	u64 length = ceph_osd_data_length(osd_data);
945 
946 	if (osd_data->type == CEPH_OSD_DATA_TYPE_PAGES) {
947 		BUG_ON(length > (u64) SIZE_MAX);
948 		if (length)
949 			ceph_msg_data_add_pages(msg, osd_data->pages,
950 					length, osd_data->alignment, false);
951 	} else if (osd_data->type == CEPH_OSD_DATA_TYPE_PAGELIST) {
952 		BUG_ON(!length);
953 		ceph_msg_data_add_pagelist(msg, osd_data->pagelist);
954 #ifdef CONFIG_BLOCK
955 	} else if (osd_data->type == CEPH_OSD_DATA_TYPE_BIO) {
956 		ceph_msg_data_add_bio(msg, &osd_data->bio_pos, length);
957 #endif
958 	} else if (osd_data->type == CEPH_OSD_DATA_TYPE_BVECS) {
959 		ceph_msg_data_add_bvecs(msg, &osd_data->bvec_pos);
960 	} else if (osd_data->type == CEPH_OSD_DATA_TYPE_ITER) {
961 		ceph_msg_data_add_iter(msg, &osd_data->iter);
962 	} else {
963 		BUG_ON(osd_data->type != CEPH_OSD_DATA_TYPE_NONE);
964 	}
965 }
966 
967 static u32 osd_req_encode_op(struct ceph_osd_op *dst,
968 			     const struct ceph_osd_req_op *src)
969 {
970 	switch (src->op) {
971 	case CEPH_OSD_OP_STAT:
972 		break;
973 	case CEPH_OSD_OP_READ:
974 	case CEPH_OSD_OP_SPARSE_READ:
975 	case CEPH_OSD_OP_WRITE:
976 	case CEPH_OSD_OP_WRITEFULL:
977 	case CEPH_OSD_OP_ZERO:
978 	case CEPH_OSD_OP_TRUNCATE:
979 		dst->extent.offset = cpu_to_le64(src->extent.offset);
980 		dst->extent.length = cpu_to_le64(src->extent.length);
981 		dst->extent.truncate_size =
982 			cpu_to_le64(src->extent.truncate_size);
983 		dst->extent.truncate_seq =
984 			cpu_to_le32(src->extent.truncate_seq);
985 		break;
986 	case CEPH_OSD_OP_CALL:
987 		dst->cls.class_len = src->cls.class_len;
988 		dst->cls.method_len = src->cls.method_len;
989 		dst->cls.indata_len = cpu_to_le32(src->cls.indata_len);
990 		break;
991 	case CEPH_OSD_OP_WATCH:
992 		dst->watch.cookie = cpu_to_le64(src->watch.cookie);
993 		dst->watch.ver = cpu_to_le64(0);
994 		dst->watch.op = src->watch.op;
995 		dst->watch.gen = cpu_to_le32(src->watch.gen);
996 		break;
997 	case CEPH_OSD_OP_NOTIFY_ACK:
998 		break;
999 	case CEPH_OSD_OP_NOTIFY:
1000 		dst->notify.cookie = cpu_to_le64(src->notify.cookie);
1001 		break;
1002 	case CEPH_OSD_OP_LIST_WATCHERS:
1003 		break;
1004 	case CEPH_OSD_OP_SETALLOCHINT:
1005 		dst->alloc_hint.expected_object_size =
1006 		    cpu_to_le64(src->alloc_hint.expected_object_size);
1007 		dst->alloc_hint.expected_write_size =
1008 		    cpu_to_le64(src->alloc_hint.expected_write_size);
1009 		dst->alloc_hint.flags = cpu_to_le32(src->alloc_hint.flags);
1010 		break;
1011 	case CEPH_OSD_OP_SETXATTR:
1012 	case CEPH_OSD_OP_CMPXATTR:
1013 		dst->xattr.name_len = cpu_to_le32(src->xattr.name_len);
1014 		dst->xattr.value_len = cpu_to_le32(src->xattr.value_len);
1015 		dst->xattr.cmp_op = src->xattr.cmp_op;
1016 		dst->xattr.cmp_mode = src->xattr.cmp_mode;
1017 		break;
1018 	case CEPH_OSD_OP_CREATE:
1019 	case CEPH_OSD_OP_DELETE:
1020 		break;
1021 	case CEPH_OSD_OP_COPY_FROM2:
1022 		dst->copy_from.snapid = cpu_to_le64(src->copy_from.snapid);
1023 		dst->copy_from.src_version =
1024 			cpu_to_le64(src->copy_from.src_version);
1025 		dst->copy_from.flags = src->copy_from.flags;
1026 		dst->copy_from.src_fadvise_flags =
1027 			cpu_to_le32(src->copy_from.src_fadvise_flags);
1028 		break;
1029 	case CEPH_OSD_OP_ASSERT_VER:
1030 		dst->assert_ver.unused = cpu_to_le64(0);
1031 		dst->assert_ver.ver = cpu_to_le64(src->assert_ver.ver);
1032 		break;
1033 	default:
1034 		pr_err("unsupported osd opcode %s\n",
1035 			ceph_osd_op_name(src->op));
1036 		WARN_ON(1);
1037 
1038 		return 0;
1039 	}
1040 
1041 	dst->op = cpu_to_le16(src->op);
1042 	dst->flags = cpu_to_le32(src->flags);
1043 	dst->payload_len = cpu_to_le32(src->indata_len);
1044 
1045 	return src->indata_len;
1046 }
1047 
1048 /*
1049  * build new request AND message, calculate layout, and adjust file
1050  * extent as needed.
1051  *
1052  * if the file was recently truncated, we include information about its
1053  * old and new size so that the object can be updated appropriately.  (we
1054  * avoid synchronously deleting truncated objects because it's slow.)
1055  */
1056 struct ceph_osd_request *ceph_osdc_new_request(struct ceph_osd_client *osdc,
1057 					       struct ceph_file_layout *layout,
1058 					       struct ceph_vino vino,
1059 					       u64 off, u64 *plen,
1060 					       unsigned int which, int num_ops,
1061 					       int opcode, int flags,
1062 					       struct ceph_snap_context *snapc,
1063 					       u32 truncate_seq,
1064 					       u64 truncate_size,
1065 					       bool use_mempool)
1066 {
1067 	struct ceph_osd_request *req;
1068 	u64 objnum = 0;
1069 	u64 objoff = 0;
1070 	u64 objlen = 0;
1071 	int r;
1072 
1073 	BUG_ON(opcode != CEPH_OSD_OP_READ && opcode != CEPH_OSD_OP_WRITE &&
1074 	       opcode != CEPH_OSD_OP_ZERO && opcode != CEPH_OSD_OP_TRUNCATE &&
1075 	       opcode != CEPH_OSD_OP_CREATE && opcode != CEPH_OSD_OP_DELETE &&
1076 	       opcode != CEPH_OSD_OP_SPARSE_READ);
1077 
1078 	req = ceph_osdc_alloc_request(osdc, snapc, num_ops, use_mempool,
1079 					GFP_NOFS);
1080 	if (!req) {
1081 		r = -ENOMEM;
1082 		goto fail;
1083 	}
1084 
1085 	/* calculate max write size */
1086 	r = calc_layout(layout, off, plen, &objnum, &objoff, &objlen);
1087 	if (r)
1088 		goto fail;
1089 
1090 	if (opcode == CEPH_OSD_OP_CREATE || opcode == CEPH_OSD_OP_DELETE) {
1091 		osd_req_op_init(req, which, opcode, 0);
1092 	} else {
1093 		u32 object_size = layout->object_size;
1094 		u32 object_base = off - objoff;
1095 		if (!(truncate_seq == 1 && truncate_size == -1ULL)) {
1096 			if (truncate_size <= object_base) {
1097 				truncate_size = 0;
1098 			} else {
1099 				truncate_size -= object_base;
1100 				if (truncate_size > object_size)
1101 					truncate_size = object_size;
1102 			}
1103 		}
1104 		osd_req_op_extent_init(req, which, opcode, objoff, objlen,
1105 				       truncate_size, truncate_seq);
1106 	}
1107 
1108 	req->r_base_oloc.pool = layout->pool_id;
1109 	req->r_base_oloc.pool_ns = ceph_try_get_string(layout->pool_ns);
1110 	ceph_oid_printf(&req->r_base_oid, "%llx.%08llx", vino.ino, objnum);
1111 	req->r_flags = flags;
1112 	if (flags & CEPH_OSD_FLAG_READ)
1113 		req->r_flags |= osdc->client->options->read_from_replica;
1114 
1115 	req->r_snapid = vino.snap;
1116 	if (flags & CEPH_OSD_FLAG_WRITE)
1117 		req->r_data_offset = off;
1118 
1119 	if (num_ops > 1) {
1120 		int num_req_ops, num_rep_ops;
1121 
1122 		/*
1123 		 * If this is a multi-op write request, assume that we'll need
1124 		 * request ops. If it's a multi-op read then assume we'll need
1125 		 * reply ops. Anything else and call it -EINVAL.
1126 		 */
1127 		if (flags & CEPH_OSD_FLAG_WRITE) {
1128 			num_req_ops = num_ops;
1129 			num_rep_ops = 0;
1130 		} else if (flags & CEPH_OSD_FLAG_READ) {
1131 			num_req_ops = 0;
1132 			num_rep_ops = num_ops;
1133 		} else {
1134 			r = -EINVAL;
1135 			goto fail;
1136 		}
1137 
1138 		r = __ceph_osdc_alloc_messages(req, GFP_NOFS, num_req_ops,
1139 					       num_rep_ops);
1140 	} else {
1141 		r = ceph_osdc_alloc_messages(req, GFP_NOFS);
1142 	}
1143 	if (r)
1144 		goto fail;
1145 
1146 	return req;
1147 
1148 fail:
1149 	ceph_osdc_put_request(req);
1150 	return ERR_PTR(r);
1151 }
1152 EXPORT_SYMBOL(ceph_osdc_new_request);
1153 
1154 int __ceph_alloc_sparse_ext_map(struct ceph_osd_req_op *op, int cnt)
1155 {
1156 	WARN_ON(op->op != CEPH_OSD_OP_SPARSE_READ);
1157 
1158 	op->extent.sparse_ext_cnt = cnt;
1159 	op->extent.sparse_ext = kmalloc_objs(*op->extent.sparse_ext, cnt,
1160 					     GFP_NOFS);
1161 	if (!op->extent.sparse_ext)
1162 		return -ENOMEM;
1163 	return 0;
1164 }
1165 EXPORT_SYMBOL(__ceph_alloc_sparse_ext_map);
1166 
1167 /*
1168  * We keep osd requests in an rbtree, sorted by ->r_tid.
1169  */
1170 DEFINE_RB_FUNCS(request, struct ceph_osd_request, r_tid, r_node)
1171 DEFINE_RB_FUNCS(request_mc, struct ceph_osd_request, r_tid, r_mc_node)
1172 
1173 /*
1174  * Call @fn on each OSD request as long as @fn returns 0.
1175  */
1176 static void for_each_request(struct ceph_osd_client *osdc,
1177 			int (*fn)(struct ceph_osd_request *req, void *arg),
1178 			void *arg)
1179 {
1180 	struct rb_node *n, *p;
1181 
1182 	for (n = rb_first(&osdc->osds); n; n = rb_next(n)) {
1183 		struct ceph_osd *osd = rb_entry(n, struct ceph_osd, o_node);
1184 
1185 		for (p = rb_first(&osd->o_requests); p; ) {
1186 			struct ceph_osd_request *req =
1187 			    rb_entry(p, struct ceph_osd_request, r_node);
1188 
1189 			p = rb_next(p);
1190 			if (fn(req, arg))
1191 				return;
1192 		}
1193 	}
1194 
1195 	for (p = rb_first(&osdc->homeless_osd.o_requests); p; ) {
1196 		struct ceph_osd_request *req =
1197 		    rb_entry(p, struct ceph_osd_request, r_node);
1198 
1199 		p = rb_next(p);
1200 		if (fn(req, arg))
1201 			return;
1202 	}
1203 }
1204 
1205 static bool osd_homeless(struct ceph_osd *osd)
1206 {
1207 	return osd->o_osd == CEPH_HOMELESS_OSD;
1208 }
1209 
1210 static bool osd_registered(struct ceph_osd *osd)
1211 {
1212 	verify_osdc_locked(osd->o_osdc);
1213 
1214 	return !RB_EMPTY_NODE(&osd->o_node);
1215 }
1216 
1217 /*
1218  * Assumes @osd is zero-initialized.
1219  */
1220 static void osd_init(struct ceph_osd *osd)
1221 {
1222 	refcount_set(&osd->o_ref, 1);
1223 	RB_CLEAR_NODE(&osd->o_node);
1224 	spin_lock_init(&osd->o_requests_lock);
1225 	osd->o_requests = RB_ROOT;
1226 	osd->o_linger_requests = RB_ROOT;
1227 	osd->o_backoff_mappings = RB_ROOT;
1228 	osd->o_backoffs_by_id = RB_ROOT;
1229 	INIT_LIST_HEAD(&osd->o_osd_lru);
1230 	INIT_LIST_HEAD(&osd->o_keepalive_item);
1231 	osd->o_incarnation = 1;
1232 	mutex_init(&osd->lock);
1233 }
1234 
1235 static void ceph_init_sparse_read(struct ceph_sparse_read *sr)
1236 {
1237 	kfree(sr->sr_extent);
1238 	memset(sr, '\0', sizeof(*sr));
1239 	sr->sr_state = CEPH_SPARSE_READ_HDR;
1240 }
1241 
1242 static void osd_cleanup(struct ceph_osd *osd)
1243 {
1244 	WARN_ON(!RB_EMPTY_NODE(&osd->o_node));
1245 	WARN_ON(!RB_EMPTY_ROOT(&osd->o_requests));
1246 	WARN_ON(!RB_EMPTY_ROOT(&osd->o_linger_requests));
1247 	WARN_ON(!RB_EMPTY_ROOT(&osd->o_backoff_mappings));
1248 	WARN_ON(!RB_EMPTY_ROOT(&osd->o_backoffs_by_id));
1249 	WARN_ON(!list_empty(&osd->o_osd_lru));
1250 	WARN_ON(!list_empty(&osd->o_keepalive_item));
1251 
1252 	ceph_init_sparse_read(&osd->o_sparse_read);
1253 
1254 	if (osd->o_auth.authorizer) {
1255 		WARN_ON(osd_homeless(osd));
1256 		ceph_auth_destroy_authorizer(osd->o_auth.authorizer);
1257 	}
1258 }
1259 
1260 /*
1261  * Track open sessions with osds.
1262  */
1263 static struct ceph_osd *create_osd(struct ceph_osd_client *osdc, int onum)
1264 {
1265 	struct ceph_osd *osd;
1266 
1267 	WARN_ON(onum == CEPH_HOMELESS_OSD);
1268 
1269 	osd = kzalloc_obj(*osd, GFP_NOIO | __GFP_NOFAIL);
1270 	osd_init(osd);
1271 	osd->o_osdc = osdc;
1272 	osd->o_osd = onum;
1273 	osd->o_sparse_op_idx = -1;
1274 
1275 	ceph_init_sparse_read(&osd->o_sparse_read);
1276 
1277 	ceph_con_init(&osd->o_con, osd, &osd_con_ops, &osdc->client->msgr);
1278 
1279 	return osd;
1280 }
1281 
1282 static struct ceph_osd *get_osd(struct ceph_osd *osd)
1283 {
1284 	if (refcount_inc_not_zero(&osd->o_ref)) {
1285 		dout("get_osd %p -> %d\n", osd, refcount_read(&osd->o_ref));
1286 		return osd;
1287 	} else {
1288 		dout("get_osd %p FAIL\n", osd);
1289 		return NULL;
1290 	}
1291 }
1292 
1293 static void put_osd(struct ceph_osd *osd)
1294 {
1295 	dout("put_osd %p -> %d\n", osd, refcount_read(&osd->o_ref) - 1);
1296 	if (refcount_dec_and_test(&osd->o_ref)) {
1297 		osd_cleanup(osd);
1298 		kfree(osd);
1299 	}
1300 }
1301 
1302 DEFINE_RB_FUNCS(osd, struct ceph_osd, o_osd, o_node)
1303 
1304 static void __move_osd_to_lru(struct ceph_osd *osd)
1305 {
1306 	struct ceph_osd_client *osdc = osd->o_osdc;
1307 
1308 	dout("%s osd %p osd%d\n", __func__, osd, osd->o_osd);
1309 	BUG_ON(!list_empty(&osd->o_osd_lru));
1310 
1311 	spin_lock(&osdc->osd_lru_lock);
1312 	list_add_tail(&osd->o_osd_lru, &osdc->osd_lru);
1313 	spin_unlock(&osdc->osd_lru_lock);
1314 
1315 	osd->lru_ttl = jiffies + osdc->client->options->osd_idle_ttl;
1316 }
1317 
1318 static void maybe_move_osd_to_lru(struct ceph_osd *osd)
1319 {
1320 	if (RB_EMPTY_ROOT(&osd->o_requests) &&
1321 	    RB_EMPTY_ROOT(&osd->o_linger_requests))
1322 		__move_osd_to_lru(osd);
1323 }
1324 
1325 static void __remove_osd_from_lru(struct ceph_osd *osd)
1326 {
1327 	struct ceph_osd_client *osdc = osd->o_osdc;
1328 
1329 	dout("%s osd %p osd%d\n", __func__, osd, osd->o_osd);
1330 
1331 	spin_lock(&osdc->osd_lru_lock);
1332 	if (!list_empty(&osd->o_osd_lru))
1333 		list_del_init(&osd->o_osd_lru);
1334 	spin_unlock(&osdc->osd_lru_lock);
1335 }
1336 
1337 /*
1338  * Close the connection and assign any leftover requests to the
1339  * homeless session.
1340  */
1341 static void close_osd(struct ceph_osd *osd)
1342 {
1343 	struct ceph_osd_client *osdc = osd->o_osdc;
1344 	struct rb_node *n;
1345 
1346 	verify_osdc_wrlocked(osdc);
1347 	dout("%s osd %p osd%d\n", __func__, osd, osd->o_osd);
1348 
1349 	ceph_con_close(&osd->o_con);
1350 
1351 	for (n = rb_first(&osd->o_requests); n; ) {
1352 		struct ceph_osd_request *req =
1353 		    rb_entry(n, struct ceph_osd_request, r_node);
1354 
1355 		n = rb_next(n); /* unlink_request() */
1356 
1357 		dout(" reassigning req %p tid %llu\n", req, req->r_tid);
1358 		unlink_request(osd, req);
1359 		link_request(&osdc->homeless_osd, req);
1360 	}
1361 	for (n = rb_first(&osd->o_linger_requests); n; ) {
1362 		struct ceph_osd_linger_request *lreq =
1363 		    rb_entry(n, struct ceph_osd_linger_request, node);
1364 
1365 		n = rb_next(n); /* unlink_linger() */
1366 
1367 		dout(" reassigning lreq %p linger_id %llu\n", lreq,
1368 		     lreq->linger_id);
1369 		unlink_linger(osd, lreq);
1370 		link_linger(&osdc->homeless_osd, lreq);
1371 	}
1372 	clear_backoffs(osd);
1373 
1374 	__remove_osd_from_lru(osd);
1375 	erase_osd(&osdc->osds, osd);
1376 	put_osd(osd);
1377 }
1378 
1379 /*
1380  * reset osd connect
1381  */
1382 static int reopen_osd(struct ceph_osd *osd)
1383 {
1384 	struct ceph_entity_addr *peer_addr;
1385 
1386 	dout("%s osd %p osd%d\n", __func__, osd, osd->o_osd);
1387 
1388 	if (RB_EMPTY_ROOT(&osd->o_requests) &&
1389 	    RB_EMPTY_ROOT(&osd->o_linger_requests)) {
1390 		close_osd(osd);
1391 		return -ENODEV;
1392 	}
1393 
1394 	peer_addr = &osd->o_osdc->osdmap->osd_addr[osd->o_osd];
1395 	if (!memcmp(peer_addr, &osd->o_con.peer_addr, sizeof (*peer_addr)) &&
1396 			!ceph_con_opened(&osd->o_con)) {
1397 		struct rb_node *n;
1398 
1399 		dout("osd addr hasn't changed and connection never opened, "
1400 		     "letting msgr retry\n");
1401 		/* touch each r_stamp for handle_timeout()'s benfit */
1402 		for (n = rb_first(&osd->o_requests); n; n = rb_next(n)) {
1403 			struct ceph_osd_request *req =
1404 			    rb_entry(n, struct ceph_osd_request, r_node);
1405 			req->r_stamp = jiffies;
1406 		}
1407 
1408 		return -EAGAIN;
1409 	}
1410 
1411 	ceph_con_close(&osd->o_con);
1412 	ceph_con_open(&osd->o_con, CEPH_ENTITY_TYPE_OSD, osd->o_osd, peer_addr);
1413 	osd->o_incarnation++;
1414 
1415 	return 0;
1416 }
1417 
1418 static struct ceph_osd *lookup_create_osd(struct ceph_osd_client *osdc, int o,
1419 					  bool wrlocked)
1420 {
1421 	struct ceph_osd *osd;
1422 
1423 	if (wrlocked)
1424 		verify_osdc_wrlocked(osdc);
1425 	else
1426 		verify_osdc_locked(osdc);
1427 
1428 	if (o != CEPH_HOMELESS_OSD)
1429 		osd = lookup_osd(&osdc->osds, o);
1430 	else
1431 		osd = &osdc->homeless_osd;
1432 	if (!osd) {
1433 		if (!wrlocked)
1434 			return ERR_PTR(-EAGAIN);
1435 
1436 		osd = create_osd(osdc, o);
1437 		insert_osd(&osdc->osds, osd);
1438 		ceph_con_open(&osd->o_con, CEPH_ENTITY_TYPE_OSD, osd->o_osd,
1439 			      &osdc->osdmap->osd_addr[osd->o_osd]);
1440 	}
1441 
1442 	dout("%s osdc %p osd%d -> osd %p\n", __func__, osdc, o, osd);
1443 	return osd;
1444 }
1445 
1446 /*
1447  * Create request <-> OSD session relation.
1448  *
1449  * @req has to be assigned a tid, @osd may be homeless.
1450  */
1451 static void link_request(struct ceph_osd *osd, struct ceph_osd_request *req)
1452 {
1453 	verify_osd_locked(osd);
1454 	WARN_ON(!req->r_tid || req->r_osd);
1455 	dout("%s osd %p osd%d req %p tid %llu\n", __func__, osd, osd->o_osd,
1456 	     req, req->r_tid);
1457 
1458 	if (!osd_homeless(osd))
1459 		__remove_osd_from_lru(osd);
1460 	else
1461 		atomic_inc(&osd->o_osdc->num_homeless);
1462 
1463 	get_osd(osd);
1464 	spin_lock(&osd->o_requests_lock);
1465 	insert_request(&osd->o_requests, req);
1466 	spin_unlock(&osd->o_requests_lock);
1467 	req->r_osd = osd;
1468 }
1469 
1470 static void unlink_request(struct ceph_osd *osd, struct ceph_osd_request *req)
1471 {
1472 	verify_osd_locked(osd);
1473 	WARN_ON(req->r_osd != osd);
1474 	dout("%s osd %p osd%d req %p tid %llu\n", __func__, osd, osd->o_osd,
1475 	     req, req->r_tid);
1476 
1477 	req->r_osd = NULL;
1478 	spin_lock(&osd->o_requests_lock);
1479 	erase_request(&osd->o_requests, req);
1480 	spin_unlock(&osd->o_requests_lock);
1481 	put_osd(osd);
1482 
1483 	if (!osd_homeless(osd))
1484 		maybe_move_osd_to_lru(osd);
1485 	else
1486 		atomic_dec(&osd->o_osdc->num_homeless);
1487 }
1488 
1489 static bool __pool_full(struct ceph_pg_pool_info *pi)
1490 {
1491 	return pi->flags & CEPH_POOL_FLAG_FULL;
1492 }
1493 
1494 static bool have_pool_full(struct ceph_osd_client *osdc)
1495 {
1496 	struct rb_node *n;
1497 
1498 	for (n = rb_first(&osdc->osdmap->pg_pools); n; n = rb_next(n)) {
1499 		struct ceph_pg_pool_info *pi =
1500 		    rb_entry(n, struct ceph_pg_pool_info, node);
1501 
1502 		if (__pool_full(pi))
1503 			return true;
1504 	}
1505 
1506 	return false;
1507 }
1508 
1509 static bool pool_full(struct ceph_osd_client *osdc, s64 pool_id)
1510 {
1511 	struct ceph_pg_pool_info *pi;
1512 
1513 	pi = ceph_pg_pool_by_id(osdc->osdmap, pool_id);
1514 	if (!pi)
1515 		return false;
1516 
1517 	return __pool_full(pi);
1518 }
1519 
1520 /*
1521  * Returns whether a request should be blocked from being sent
1522  * based on the current osdmap and osd_client settings.
1523  */
1524 static bool target_should_be_paused(struct ceph_osd_client *osdc,
1525 				    const struct ceph_osd_request_target *t,
1526 				    struct ceph_pg_pool_info *pi)
1527 {
1528 	bool pauserd = ceph_osdmap_flag(osdc, CEPH_OSDMAP_PAUSERD);
1529 	bool pausewr = ceph_osdmap_flag(osdc, CEPH_OSDMAP_PAUSEWR) ||
1530 		       ceph_osdmap_flag(osdc, CEPH_OSDMAP_FULL) ||
1531 		       __pool_full(pi);
1532 
1533 	WARN_ON(pi->id != t->target_oloc.pool);
1534 	return ((t->flags & CEPH_OSD_FLAG_READ) && pauserd) ||
1535 	       ((t->flags & CEPH_OSD_FLAG_WRITE) && pausewr) ||
1536 	       (osdc->osdmap->epoch < osdc->epoch_barrier);
1537 }
1538 
1539 static int pick_random_replica(const struct ceph_osds *acting)
1540 {
1541 	int i = get_random_u32_below(acting->size);
1542 
1543 	dout("%s picked osd%d, primary osd%d\n", __func__,
1544 	     acting->osds[i], acting->primary);
1545 	return i;
1546 }
1547 
1548 /*
1549  * Picks the closest replica based on client's location given by
1550  * crush_location option.  Prefers the primary if the locality is
1551  * the same.
1552  */
1553 static int pick_closest_replica(struct ceph_osd_client *osdc,
1554 				const struct ceph_osds *acting)
1555 {
1556 	struct ceph_options *opt = osdc->client->options;
1557 	int best_i, best_locality;
1558 	int i = 0, locality;
1559 
1560 	do {
1561 		locality = ceph_get_crush_locality(osdc->osdmap,
1562 						   acting->osds[i],
1563 						   &opt->crush_locs);
1564 		if (i == 0 ||
1565 		    (locality >= 0 && best_locality < 0) ||
1566 		    (locality >= 0 && best_locality >= 0 &&
1567 		     locality < best_locality)) {
1568 			best_i = i;
1569 			best_locality = locality;
1570 		}
1571 	} while (++i < acting->size);
1572 
1573 	dout("%s picked osd%d with locality %d, primary osd%d\n", __func__,
1574 	     acting->osds[best_i], best_locality, acting->primary);
1575 	return best_i;
1576 }
1577 
1578 enum calc_target_result {
1579 	CALC_TARGET_NO_ACTION = 0,
1580 	CALC_TARGET_NEED_RESEND,
1581 	CALC_TARGET_POOL_DNE,
1582 };
1583 
1584 static enum calc_target_result calc_target(struct ceph_osd_client *osdc,
1585 					   struct ceph_osd_request_target *t,
1586 					   bool any_change)
1587 {
1588 	struct ceph_pg_pool_info *pi;
1589 	struct ceph_pg pgid, last_pgid;
1590 	struct ceph_osds up, acting;
1591 	bool should_be_paused;
1592 	bool is_read = t->flags & CEPH_OSD_FLAG_READ;
1593 	bool is_write = t->flags & CEPH_OSD_FLAG_WRITE;
1594 	bool force_resend = false;
1595 	bool unpaused = false;
1596 	bool legacy_change = false;
1597 	bool split = false;
1598 	bool sort_bitwise = ceph_osdmap_flag(osdc, CEPH_OSDMAP_SORTBITWISE);
1599 	bool recovery_deletes = ceph_osdmap_flag(osdc,
1600 						 CEPH_OSDMAP_RECOVERY_DELETES);
1601 	enum calc_target_result ct_res;
1602 
1603 	t->epoch = osdc->osdmap->epoch;
1604 	pi = ceph_pg_pool_by_id(osdc->osdmap, t->base_oloc.pool);
1605 	if (!pi) {
1606 		t->osd = CEPH_HOMELESS_OSD;
1607 		ct_res = CALC_TARGET_POOL_DNE;
1608 		goto out;
1609 	}
1610 
1611 	if (osdc->osdmap->epoch == pi->last_force_request_resend) {
1612 		if (t->last_force_resend < pi->last_force_request_resend) {
1613 			t->last_force_resend = pi->last_force_request_resend;
1614 			force_resend = true;
1615 		} else if (t->last_force_resend == 0) {
1616 			force_resend = true;
1617 		}
1618 	}
1619 
1620 	/* apply tiering */
1621 	ceph_oid_copy(&t->target_oid, &t->base_oid);
1622 	ceph_oloc_copy(&t->target_oloc, &t->base_oloc);
1623 	if ((t->flags & CEPH_OSD_FLAG_IGNORE_OVERLAY) == 0) {
1624 		if (is_read && pi->read_tier >= 0)
1625 			t->target_oloc.pool = pi->read_tier;
1626 		if (is_write && pi->write_tier >= 0)
1627 			t->target_oloc.pool = pi->write_tier;
1628 
1629 		pi = ceph_pg_pool_by_id(osdc->osdmap, t->target_oloc.pool);
1630 		if (!pi) {
1631 			t->osd = CEPH_HOMELESS_OSD;
1632 			ct_res = CALC_TARGET_POOL_DNE;
1633 			goto out;
1634 		}
1635 	}
1636 
1637 	__ceph_object_locator_to_pg(pi, &t->target_oid, &t->target_oloc, &pgid);
1638 	last_pgid.pool = pgid.pool;
1639 	last_pgid.seed = ceph_stable_mod(pgid.seed, t->pg_num, t->pg_num_mask);
1640 
1641 	ceph_pg_to_up_acting_osds(osdc->osdmap, pi, &pgid, &up, &acting);
1642 	if (any_change &&
1643 	    ceph_is_new_interval(&t->acting,
1644 				 &acting,
1645 				 &t->up,
1646 				 &up,
1647 				 t->size,
1648 				 pi->size,
1649 				 t->min_size,
1650 				 pi->min_size,
1651 				 t->pg_num,
1652 				 pi->pg_num,
1653 				 t->sort_bitwise,
1654 				 sort_bitwise,
1655 				 t->recovery_deletes,
1656 				 recovery_deletes,
1657 				 &last_pgid))
1658 		force_resend = true;
1659 
1660 	should_be_paused = target_should_be_paused(osdc, t, pi);
1661 	if (t->paused && !should_be_paused) {
1662 		unpaused = true;
1663 	}
1664 	if (t->paused != should_be_paused) {
1665 		dout("%s t %p paused %d -> %d\n", __func__, t, t->paused,
1666 		     should_be_paused);
1667 		t->paused = should_be_paused;
1668 	}
1669 
1670 	legacy_change = ceph_pg_compare(&t->pgid, &pgid) ||
1671 			ceph_osds_changed(&t->acting, &acting,
1672 					  t->used_replica || any_change);
1673 	if (t->pg_num)
1674 		split = ceph_pg_is_split(&last_pgid, t->pg_num, pi->pg_num);
1675 
1676 	if (legacy_change || force_resend || split) {
1677 		t->pgid = pgid; /* struct */
1678 		ceph_pg_to_primary_shard(osdc->osdmap, pi, &pgid, &t->spgid);
1679 		ceph_osds_copy(&t->acting, &acting);
1680 		ceph_osds_copy(&t->up, &up);
1681 		t->size = pi->size;
1682 		t->min_size = pi->min_size;
1683 		t->pg_num = pi->pg_num;
1684 		t->pg_num_mask = pi->pg_num_mask;
1685 		t->sort_bitwise = sort_bitwise;
1686 		t->recovery_deletes = recovery_deletes;
1687 
1688 		if ((t->flags & (CEPH_OSD_FLAG_BALANCE_READS |
1689 				 CEPH_OSD_FLAG_LOCALIZE_READS)) &&
1690 		    !is_write && pi->type == CEPH_POOL_TYPE_REP &&
1691 		    acting.size > 1) {
1692 			int pos;
1693 
1694 			WARN_ON(!is_read || acting.osds[0] != acting.primary);
1695 			if (t->flags & CEPH_OSD_FLAG_BALANCE_READS) {
1696 				pos = pick_random_replica(&acting);
1697 			} else {
1698 				pos = pick_closest_replica(osdc, &acting);
1699 			}
1700 			t->osd = acting.osds[pos];
1701 			t->used_replica = pos > 0;
1702 		} else {
1703 			t->osd = acting.primary;
1704 			t->used_replica = false;
1705 		}
1706 	}
1707 
1708 	if (unpaused || legacy_change || force_resend || split)
1709 		ct_res = CALC_TARGET_NEED_RESEND;
1710 	else
1711 		ct_res = CALC_TARGET_NO_ACTION;
1712 
1713 out:
1714 	dout("%s t %p -> %d%d%d%d ct_res %d osd%d\n", __func__, t, unpaused,
1715 	     legacy_change, force_resend, split, ct_res, t->osd);
1716 	return ct_res;
1717 }
1718 
1719 static struct ceph_spg_mapping *alloc_spg_mapping(void)
1720 {
1721 	struct ceph_spg_mapping *spg;
1722 
1723 	spg = kmalloc_obj(*spg, GFP_NOIO);
1724 	if (!spg)
1725 		return NULL;
1726 
1727 	RB_CLEAR_NODE(&spg->node);
1728 	spg->backoffs = RB_ROOT;
1729 	return spg;
1730 }
1731 
1732 static void free_spg_mapping(struct ceph_spg_mapping *spg)
1733 {
1734 	WARN_ON(!RB_EMPTY_NODE(&spg->node));
1735 	WARN_ON(!RB_EMPTY_ROOT(&spg->backoffs));
1736 
1737 	kfree(spg);
1738 }
1739 
1740 /*
1741  * rbtree of ceph_spg_mapping for handling map<spg_t, ...>, similar to
1742  * ceph_pg_mapping.  Used to track OSD backoffs -- a backoff [range] is
1743  * defined only within a specific spgid; it does not pass anything to
1744  * children on split, or to another primary.
1745  */
1746 DEFINE_RB_FUNCS2(spg_mapping, struct ceph_spg_mapping, spgid, ceph_spg_compare,
1747 		 RB_BYPTR, const struct ceph_spg *, node)
1748 
1749 static u64 hoid_get_bitwise_key(const struct ceph_hobject_id *hoid)
1750 {
1751 	return hoid->is_max ? 0x100000000ull : hoid->hash_reverse_bits;
1752 }
1753 
1754 static void hoid_get_effective_key(const struct ceph_hobject_id *hoid,
1755 				   void **pkey, size_t *pkey_len)
1756 {
1757 	if (hoid->key_len) {
1758 		*pkey = hoid->key;
1759 		*pkey_len = hoid->key_len;
1760 	} else {
1761 		*pkey = hoid->oid;
1762 		*pkey_len = hoid->oid_len;
1763 	}
1764 }
1765 
1766 static int compare_names(const void *name1, size_t name1_len,
1767 			 const void *name2, size_t name2_len)
1768 {
1769 	int ret;
1770 
1771 	ret = memcmp(name1, name2, min(name1_len, name2_len));
1772 	if (!ret) {
1773 		if (name1_len < name2_len)
1774 			ret = -1;
1775 		else if (name1_len > name2_len)
1776 			ret = 1;
1777 	}
1778 	return ret;
1779 }
1780 
1781 static int hoid_compare(const struct ceph_hobject_id *lhs,
1782 			const struct ceph_hobject_id *rhs)
1783 {
1784 	void *effective_key1, *effective_key2;
1785 	size_t effective_key1_len, effective_key2_len;
1786 	int ret;
1787 
1788 	if (lhs->is_max < rhs->is_max)
1789 		return -1;
1790 	if (lhs->is_max > rhs->is_max)
1791 		return 1;
1792 
1793 	if (lhs->pool < rhs->pool)
1794 		return -1;
1795 	if (lhs->pool > rhs->pool)
1796 		return 1;
1797 
1798 	if (hoid_get_bitwise_key(lhs) < hoid_get_bitwise_key(rhs))
1799 		return -1;
1800 	if (hoid_get_bitwise_key(lhs) > hoid_get_bitwise_key(rhs))
1801 		return 1;
1802 
1803 	ret = compare_names(lhs->nspace, lhs->nspace_len,
1804 			    rhs->nspace, rhs->nspace_len);
1805 	if (ret)
1806 		return ret;
1807 
1808 	hoid_get_effective_key(lhs, &effective_key1, &effective_key1_len);
1809 	hoid_get_effective_key(rhs, &effective_key2, &effective_key2_len);
1810 	ret = compare_names(effective_key1, effective_key1_len,
1811 			    effective_key2, effective_key2_len);
1812 	if (ret)
1813 		return ret;
1814 
1815 	ret = compare_names(lhs->oid, lhs->oid_len, rhs->oid, rhs->oid_len);
1816 	if (ret)
1817 		return ret;
1818 
1819 	if (lhs->snapid < rhs->snapid)
1820 		return -1;
1821 	if (lhs->snapid > rhs->snapid)
1822 		return 1;
1823 
1824 	return 0;
1825 }
1826 
1827 /*
1828  * For decoding ->begin and ->end of MOSDBackoff only -- no MIN/MAX
1829  * compat stuff here.
1830  *
1831  * Assumes @hoid is zero-initialized.
1832  */
1833 static int decode_hoid(void **p, void *end, struct ceph_hobject_id *hoid)
1834 {
1835 	u8 struct_v;
1836 	u32 struct_len;
1837 	int ret;
1838 
1839 	ret = ceph_start_decoding(p, end, 4, "hobject_t", &struct_v,
1840 				  &struct_len);
1841 	if (ret)
1842 		return ret;
1843 
1844 	if (struct_v < 4) {
1845 		pr_err("got struct_v %d < 4 of hobject_t\n", struct_v);
1846 		goto e_inval;
1847 	}
1848 
1849 	hoid->key = ceph_extract_encoded_string(p, end, &hoid->key_len,
1850 						GFP_NOIO);
1851 	if (IS_ERR(hoid->key)) {
1852 		ret = PTR_ERR(hoid->key);
1853 		hoid->key = NULL;
1854 		return ret;
1855 	}
1856 
1857 	hoid->oid = ceph_extract_encoded_string(p, end, &hoid->oid_len,
1858 						GFP_NOIO);
1859 	if (IS_ERR(hoid->oid)) {
1860 		ret = PTR_ERR(hoid->oid);
1861 		hoid->oid = NULL;
1862 		return ret;
1863 	}
1864 
1865 	ceph_decode_64_safe(p, end, hoid->snapid, e_inval);
1866 	ceph_decode_32_safe(p, end, hoid->hash, e_inval);
1867 	ceph_decode_8_safe(p, end, hoid->is_max, e_inval);
1868 
1869 	hoid->nspace = ceph_extract_encoded_string(p, end, &hoid->nspace_len,
1870 						   GFP_NOIO);
1871 	if (IS_ERR(hoid->nspace)) {
1872 		ret = PTR_ERR(hoid->nspace);
1873 		hoid->nspace = NULL;
1874 		return ret;
1875 	}
1876 
1877 	ceph_decode_64_safe(p, end, hoid->pool, e_inval);
1878 
1879 	ceph_hoid_build_hash_cache(hoid);
1880 	return 0;
1881 
1882 e_inval:
1883 	return -EINVAL;
1884 }
1885 
1886 static int hoid_encoding_size(const struct ceph_hobject_id *hoid)
1887 {
1888 	return 8 + 4 + 1 + 8 + /* snapid, hash, is_max, pool */
1889 	       4 + hoid->key_len + 4 + hoid->oid_len + 4 + hoid->nspace_len;
1890 }
1891 
1892 static void encode_hoid(void **p, void *end, const struct ceph_hobject_id *hoid)
1893 {
1894 	ceph_start_encoding(p, 4, 3, hoid_encoding_size(hoid));
1895 	ceph_encode_string(p, end, hoid->key, hoid->key_len);
1896 	ceph_encode_string(p, end, hoid->oid, hoid->oid_len);
1897 	ceph_encode_64(p, hoid->snapid);
1898 	ceph_encode_32(p, hoid->hash);
1899 	ceph_encode_8(p, hoid->is_max);
1900 	ceph_encode_string(p, end, hoid->nspace, hoid->nspace_len);
1901 	ceph_encode_64(p, hoid->pool);
1902 }
1903 
1904 static void free_hoid(struct ceph_hobject_id *hoid)
1905 {
1906 	if (hoid) {
1907 		kfree(hoid->key);
1908 		kfree(hoid->oid);
1909 		kfree(hoid->nspace);
1910 		kfree(hoid);
1911 	}
1912 }
1913 
1914 static struct ceph_osd_backoff *alloc_backoff(void)
1915 {
1916 	struct ceph_osd_backoff *backoff;
1917 
1918 	backoff = kzalloc_obj(*backoff, GFP_NOIO);
1919 	if (!backoff)
1920 		return NULL;
1921 
1922 	RB_CLEAR_NODE(&backoff->spg_node);
1923 	RB_CLEAR_NODE(&backoff->id_node);
1924 	return backoff;
1925 }
1926 
1927 static void free_backoff(struct ceph_osd_backoff *backoff)
1928 {
1929 	WARN_ON(!RB_EMPTY_NODE(&backoff->spg_node));
1930 	WARN_ON(!RB_EMPTY_NODE(&backoff->id_node));
1931 
1932 	free_hoid(backoff->begin);
1933 	free_hoid(backoff->end);
1934 	kfree(backoff);
1935 }
1936 
1937 /*
1938  * Within a specific spgid, backoffs are managed by ->begin hoid.
1939  */
1940 DEFINE_RB_INSDEL_FUNCS2(backoff, struct ceph_osd_backoff, begin, hoid_compare,
1941 			RB_BYVAL, spg_node);
1942 
1943 static struct ceph_osd_backoff *lookup_containing_backoff(struct rb_root *root,
1944 					    const struct ceph_hobject_id *hoid)
1945 {
1946 	struct rb_node *n = root->rb_node;
1947 
1948 	while (n) {
1949 		struct ceph_osd_backoff *cur =
1950 		    rb_entry(n, struct ceph_osd_backoff, spg_node);
1951 		int cmp;
1952 
1953 		cmp = hoid_compare(hoid, cur->begin);
1954 		if (cmp < 0) {
1955 			n = n->rb_left;
1956 		} else if (cmp > 0) {
1957 			if (hoid_compare(hoid, cur->end) < 0)
1958 				return cur;
1959 
1960 			n = n->rb_right;
1961 		} else {
1962 			return cur;
1963 		}
1964 	}
1965 
1966 	return NULL;
1967 }
1968 
1969 /*
1970  * Each backoff has a unique id within its OSD session.
1971  */
1972 DEFINE_RB_FUNCS(backoff_by_id, struct ceph_osd_backoff, id, id_node)
1973 
1974 static void clear_backoffs(struct ceph_osd *osd)
1975 {
1976 	while (!RB_EMPTY_ROOT(&osd->o_backoff_mappings)) {
1977 		struct ceph_spg_mapping *spg =
1978 		    rb_entry(rb_first(&osd->o_backoff_mappings),
1979 			     struct ceph_spg_mapping, node);
1980 
1981 		while (!RB_EMPTY_ROOT(&spg->backoffs)) {
1982 			struct ceph_osd_backoff *backoff =
1983 			    rb_entry(rb_first(&spg->backoffs),
1984 				     struct ceph_osd_backoff, spg_node);
1985 
1986 			erase_backoff(&spg->backoffs, backoff);
1987 			erase_backoff_by_id(&osd->o_backoffs_by_id, backoff);
1988 			free_backoff(backoff);
1989 		}
1990 		erase_spg_mapping(&osd->o_backoff_mappings, spg);
1991 		free_spg_mapping(spg);
1992 	}
1993 }
1994 
1995 /*
1996  * Set up a temporary, non-owning view into @t.
1997  */
1998 static void hoid_fill_from_target(struct ceph_hobject_id *hoid,
1999 				  const struct ceph_osd_request_target *t)
2000 {
2001 	hoid->key = NULL;
2002 	hoid->key_len = 0;
2003 	hoid->oid = t->target_oid.name;
2004 	hoid->oid_len = t->target_oid.name_len;
2005 	hoid->snapid = CEPH_NOSNAP;
2006 	hoid->hash = t->pgid.seed;
2007 	hoid->is_max = false;
2008 	if (t->target_oloc.pool_ns) {
2009 		hoid->nspace = t->target_oloc.pool_ns->str;
2010 		hoid->nspace_len = t->target_oloc.pool_ns->len;
2011 	} else {
2012 		hoid->nspace = NULL;
2013 		hoid->nspace_len = 0;
2014 	}
2015 	hoid->pool = t->target_oloc.pool;
2016 	ceph_hoid_build_hash_cache(hoid);
2017 }
2018 
2019 static bool should_plug_request(struct ceph_osd_request *req)
2020 {
2021 	struct ceph_osd *osd = req->r_osd;
2022 	struct ceph_spg_mapping *spg;
2023 	struct ceph_osd_backoff *backoff;
2024 	struct ceph_hobject_id hoid;
2025 
2026 	spg = lookup_spg_mapping(&osd->o_backoff_mappings, &req->r_t.spgid);
2027 	if (!spg)
2028 		return false;
2029 
2030 	hoid_fill_from_target(&hoid, &req->r_t);
2031 	backoff = lookup_containing_backoff(&spg->backoffs, &hoid);
2032 	if (!backoff)
2033 		return false;
2034 
2035 	dout("%s req %p tid %llu backoff osd%d spgid %llu.%xs%d id %llu\n",
2036 	     __func__, req, req->r_tid, osd->o_osd, backoff->spgid.pgid.pool,
2037 	     backoff->spgid.pgid.seed, backoff->spgid.shard, backoff->id);
2038 	return true;
2039 }
2040 
2041 /*
2042  * Keep get_num_data_items() in sync with this function.
2043  */
2044 static void setup_request_data(struct ceph_osd_request *req)
2045 {
2046 	struct ceph_msg *request_msg = req->r_request;
2047 	struct ceph_msg *reply_msg = req->r_reply;
2048 	struct ceph_osd_req_op *op;
2049 
2050 	if (req->r_request->num_data_items || req->r_reply->num_data_items)
2051 		return;
2052 
2053 	WARN_ON(request_msg->data_length || reply_msg->data_length);
2054 	for (op = req->r_ops; op != &req->r_ops[req->r_num_ops]; op++) {
2055 		switch (op->op) {
2056 		/* request */
2057 		case CEPH_OSD_OP_WRITE:
2058 		case CEPH_OSD_OP_WRITEFULL:
2059 			WARN_ON(op->indata_len != op->extent.length);
2060 			ceph_osdc_msg_data_add(request_msg,
2061 					       &op->extent.osd_data);
2062 			break;
2063 		case CEPH_OSD_OP_SETXATTR:
2064 		case CEPH_OSD_OP_CMPXATTR:
2065 			WARN_ON(op->indata_len != op->xattr.name_len +
2066 						  op->xattr.value_len);
2067 			ceph_osdc_msg_data_add(request_msg,
2068 					       &op->xattr.osd_data);
2069 			break;
2070 		case CEPH_OSD_OP_NOTIFY_ACK:
2071 			ceph_osdc_msg_data_add(request_msg,
2072 					       &op->notify_ack.request_data);
2073 			break;
2074 		case CEPH_OSD_OP_COPY_FROM2:
2075 			ceph_osdc_msg_data_add(request_msg,
2076 					       &op->copy_from.osd_data);
2077 			break;
2078 
2079 		/* reply */
2080 		case CEPH_OSD_OP_STAT:
2081 			ceph_osdc_msg_data_add(reply_msg,
2082 					       &op->raw_data_in);
2083 			break;
2084 		case CEPH_OSD_OP_READ:
2085 		case CEPH_OSD_OP_SPARSE_READ:
2086 			ceph_osdc_msg_data_add(reply_msg,
2087 					       &op->extent.osd_data);
2088 			break;
2089 		case CEPH_OSD_OP_LIST_WATCHERS:
2090 			ceph_osdc_msg_data_add(reply_msg,
2091 					       &op->list_watchers.response_data);
2092 			break;
2093 
2094 		/* both */
2095 		case CEPH_OSD_OP_CALL:
2096 			WARN_ON(op->indata_len != op->cls.class_len +
2097 						  op->cls.method_len +
2098 						  op->cls.indata_len);
2099 			ceph_osdc_msg_data_add(request_msg,
2100 					       &op->cls.request_info);
2101 			/* optional, can be NONE */
2102 			ceph_osdc_msg_data_add(request_msg,
2103 					       &op->cls.request_data);
2104 			/* optional, can be NONE */
2105 			ceph_osdc_msg_data_add(reply_msg,
2106 					       &op->cls.response_data);
2107 			break;
2108 		case CEPH_OSD_OP_NOTIFY:
2109 			ceph_osdc_msg_data_add(request_msg,
2110 					       &op->notify.request_data);
2111 			ceph_osdc_msg_data_add(reply_msg,
2112 					       &op->notify.response_data);
2113 			break;
2114 		}
2115 	}
2116 }
2117 
2118 static void encode_pgid(void **p, const struct ceph_pg *pgid)
2119 {
2120 	ceph_encode_8(p, 1);
2121 	ceph_encode_64(p, pgid->pool);
2122 	ceph_encode_32(p, pgid->seed);
2123 	ceph_encode_32(p, -1); /* preferred */
2124 }
2125 
2126 static void encode_spgid(void **p, const struct ceph_spg *spgid)
2127 {
2128 	ceph_start_encoding(p, 1, 1, CEPH_PGID_ENCODING_LEN + 1);
2129 	encode_pgid(p, &spgid->pgid);
2130 	ceph_encode_8(p, spgid->shard);
2131 }
2132 
2133 static void encode_oloc(void **p, void *end,
2134 			const struct ceph_object_locator *oloc)
2135 {
2136 	ceph_start_encoding(p, 5, 4, ceph_oloc_encoding_size(oloc));
2137 	ceph_encode_64(p, oloc->pool);
2138 	ceph_encode_32(p, -1); /* preferred */
2139 	ceph_encode_32(p, 0);  /* key len */
2140 	if (oloc->pool_ns)
2141 		ceph_encode_string(p, end, oloc->pool_ns->str,
2142 				   oloc->pool_ns->len);
2143 	else
2144 		ceph_encode_32(p, 0);
2145 }
2146 
2147 static void encode_request_partial(struct ceph_osd_request *req,
2148 				   struct ceph_msg *msg)
2149 {
2150 	void *p = msg->front.iov_base;
2151 	void *const end = p + msg->front_alloc_len;
2152 	u32 data_len = 0;
2153 	int i;
2154 
2155 	if (req->r_flags & CEPH_OSD_FLAG_WRITE) {
2156 		/* snapshots aren't writeable */
2157 		WARN_ON(req->r_snapid != CEPH_NOSNAP);
2158 	} else {
2159 		WARN_ON(req->r_mtime.tv_sec || req->r_mtime.tv_nsec ||
2160 			req->r_data_offset || req->r_snapc);
2161 	}
2162 
2163 	setup_request_data(req);
2164 
2165 	encode_spgid(&p, &req->r_t.spgid); /* actual spg */
2166 	ceph_encode_32(&p, req->r_t.pgid.seed); /* raw hash */
2167 	ceph_encode_32(&p, req->r_osdc->osdmap->epoch);
2168 	ceph_encode_32(&p, req->r_flags);
2169 
2170 	/* reqid */
2171 	ceph_start_encoding(&p, 2, 2, sizeof(struct ceph_osd_reqid));
2172 	memset(p, 0, sizeof(struct ceph_osd_reqid));
2173 	p += sizeof(struct ceph_osd_reqid);
2174 
2175 	/* trace */
2176 	memset(p, 0, sizeof(struct ceph_blkin_trace_info));
2177 	p += sizeof(struct ceph_blkin_trace_info);
2178 
2179 	ceph_encode_32(&p, 0); /* client_inc, always 0 */
2180 	ceph_encode_timespec64(p, &req->r_mtime);
2181 	p += sizeof(struct ceph_timespec);
2182 
2183 	encode_oloc(&p, end, &req->r_t.target_oloc);
2184 	ceph_encode_string(&p, end, req->r_t.target_oid.name,
2185 			   req->r_t.target_oid.name_len);
2186 
2187 	/* ops, can imply data */
2188 	ceph_encode_16(&p, req->r_num_ops);
2189 	for (i = 0; i < req->r_num_ops; i++) {
2190 		data_len += osd_req_encode_op(p, &req->r_ops[i]);
2191 		p += sizeof(struct ceph_osd_op);
2192 	}
2193 
2194 	ceph_encode_64(&p, req->r_snapid); /* snapid */
2195 	if (req->r_snapc) {
2196 		ceph_encode_64(&p, req->r_snapc->seq);
2197 		ceph_encode_32(&p, req->r_snapc->num_snaps);
2198 		for (i = 0; i < req->r_snapc->num_snaps; i++)
2199 			ceph_encode_64(&p, req->r_snapc->snaps[i]);
2200 	} else {
2201 		ceph_encode_64(&p, 0); /* snap_seq */
2202 		ceph_encode_32(&p, 0); /* snaps len */
2203 	}
2204 
2205 	ceph_encode_32(&p, req->r_attempts); /* retry_attempt */
2206 	BUG_ON(p > end - 8); /* space for features */
2207 
2208 	msg->hdr.version = cpu_to_le16(8); /* MOSDOp v8 */
2209 	/* front_len is finalized in encode_request_finish() */
2210 	msg->front.iov_len = p - msg->front.iov_base;
2211 	msg->hdr.front_len = cpu_to_le32(msg->front.iov_len);
2212 	msg->hdr.data_len = cpu_to_le32(data_len);
2213 	/*
2214 	 * The header "data_off" is a hint to the receiver allowing it
2215 	 * to align received data into its buffers such that there's no
2216 	 * need to re-copy it before writing it to disk (direct I/O).
2217 	 */
2218 	msg->hdr.data_off = cpu_to_le16(req->r_data_offset);
2219 
2220 	dout("%s req %p msg %p oid %s oid_len %d\n", __func__, req, msg,
2221 	     req->r_t.target_oid.name, req->r_t.target_oid.name_len);
2222 }
2223 
2224 static void encode_request_finish(struct ceph_msg *msg)
2225 {
2226 	void *p = msg->front.iov_base;
2227 	void *const partial_end = p + msg->front.iov_len;
2228 	void *const end = p + msg->front_alloc_len;
2229 
2230 	if (CEPH_HAVE_FEATURE(msg->con->peer_features, RESEND_ON_SPLIT)) {
2231 		/* luminous OSD -- encode features and be done */
2232 		p = partial_end;
2233 		ceph_encode_64(&p, msg->con->peer_features);
2234 	} else {
2235 		struct {
2236 			char spgid[CEPH_ENCODING_START_BLK_LEN +
2237 				   CEPH_PGID_ENCODING_LEN + 1];
2238 			__le32 hash;
2239 			__le32 epoch;
2240 			__le32 flags;
2241 			char reqid[CEPH_ENCODING_START_BLK_LEN +
2242 				   sizeof(struct ceph_osd_reqid)];
2243 			char trace[sizeof(struct ceph_blkin_trace_info)];
2244 			__le32 client_inc;
2245 			struct ceph_timespec mtime;
2246 		} __packed head;
2247 		struct ceph_pg pgid;
2248 		void *oloc, *oid, *tail;
2249 		int oloc_len, oid_len, tail_len;
2250 		int len;
2251 
2252 		/*
2253 		 * Pre-luminous OSD -- reencode v8 into v4 using @head
2254 		 * as a temporary buffer.  Encode the raw PG; the rest
2255 		 * is just a matter of moving oloc, oid and tail blobs
2256 		 * around.
2257 		 */
2258 		memcpy(&head, p, sizeof(head));
2259 		p += sizeof(head);
2260 
2261 		oloc = p;
2262 		p += CEPH_ENCODING_START_BLK_LEN;
2263 		pgid.pool = ceph_decode_64(&p);
2264 		p += 4 + 4; /* preferred, key len */
2265 		len = ceph_decode_32(&p);
2266 		p += len;   /* nspace */
2267 		oloc_len = p - oloc;
2268 
2269 		oid = p;
2270 		len = ceph_decode_32(&p);
2271 		p += len;
2272 		oid_len = p - oid;
2273 
2274 		tail = p;
2275 		tail_len = partial_end - p;
2276 
2277 		p = msg->front.iov_base;
2278 		ceph_encode_copy(&p, &head.client_inc, sizeof(head.client_inc));
2279 		ceph_encode_copy(&p, &head.epoch, sizeof(head.epoch));
2280 		ceph_encode_copy(&p, &head.flags, sizeof(head.flags));
2281 		ceph_encode_copy(&p, &head.mtime, sizeof(head.mtime));
2282 
2283 		/* reassert_version */
2284 		memset(p, 0, sizeof(struct ceph_eversion));
2285 		p += sizeof(struct ceph_eversion);
2286 
2287 		BUG_ON(p >= oloc);
2288 		memmove(p, oloc, oloc_len);
2289 		p += oloc_len;
2290 
2291 		pgid.seed = le32_to_cpu(head.hash);
2292 		encode_pgid(&p, &pgid); /* raw pg */
2293 
2294 		BUG_ON(p >= oid);
2295 		memmove(p, oid, oid_len);
2296 		p += oid_len;
2297 
2298 		/* tail -- ops, snapid, snapc, retry_attempt */
2299 		BUG_ON(p >= tail);
2300 		memmove(p, tail, tail_len);
2301 		p += tail_len;
2302 
2303 		msg->hdr.version = cpu_to_le16(4); /* MOSDOp v4 */
2304 	}
2305 
2306 	BUG_ON(p > end);
2307 	msg->front.iov_len = p - msg->front.iov_base;
2308 	msg->hdr.front_len = cpu_to_le32(msg->front.iov_len);
2309 
2310 	dout("%s msg %p tid %llu %u+%u+%u v%d\n", __func__, msg,
2311 	     le64_to_cpu(msg->hdr.tid), le32_to_cpu(msg->hdr.front_len),
2312 	     le32_to_cpu(msg->hdr.middle_len), le32_to_cpu(msg->hdr.data_len),
2313 	     le16_to_cpu(msg->hdr.version));
2314 }
2315 
2316 /*
2317  * @req has to be assigned a tid and registered.
2318  */
2319 static void send_request(struct ceph_osd_request *req)
2320 {
2321 	struct ceph_osd *osd = req->r_osd;
2322 
2323 	verify_osd_locked(osd);
2324 	WARN_ON(osd->o_osd != req->r_t.osd);
2325 
2326 	/* backoff? */
2327 	if (should_plug_request(req))
2328 		return;
2329 
2330 	/*
2331 	 * We may have a previously queued request message hanging
2332 	 * around.  Cancel it to avoid corrupting the msgr.
2333 	 */
2334 	if (req->r_sent)
2335 		ceph_msg_revoke(req->r_request);
2336 
2337 	req->r_flags |= CEPH_OSD_FLAG_KNOWN_REDIR;
2338 	if (req->r_attempts)
2339 		req->r_flags |= CEPH_OSD_FLAG_RETRY;
2340 	else
2341 		WARN_ON(req->r_flags & CEPH_OSD_FLAG_RETRY);
2342 
2343 	encode_request_partial(req, req->r_request);
2344 
2345 	dout("%s req %p tid %llu to pgid %llu.%x spgid %llu.%xs%d osd%d e%u flags 0x%x attempt %d\n",
2346 	     __func__, req, req->r_tid, req->r_t.pgid.pool, req->r_t.pgid.seed,
2347 	     req->r_t.spgid.pgid.pool, req->r_t.spgid.pgid.seed,
2348 	     req->r_t.spgid.shard, osd->o_osd, req->r_t.epoch, req->r_flags,
2349 	     req->r_attempts);
2350 
2351 	req->r_t.paused = false;
2352 	req->r_stamp = jiffies;
2353 	req->r_attempts++;
2354 
2355 	req->r_sent = osd->o_incarnation;
2356 	req->r_request->hdr.tid = cpu_to_le64(req->r_tid);
2357 	ceph_con_send(&osd->o_con, ceph_msg_get(req->r_request));
2358 }
2359 
2360 static void maybe_request_map(struct ceph_osd_client *osdc)
2361 {
2362 	bool continuous = false;
2363 
2364 	verify_osdc_locked(osdc);
2365 	WARN_ON(!osdc->osdmap->epoch);
2366 
2367 	if (ceph_osdmap_flag(osdc, CEPH_OSDMAP_FULL) ||
2368 	    ceph_osdmap_flag(osdc, CEPH_OSDMAP_PAUSERD) ||
2369 	    ceph_osdmap_flag(osdc, CEPH_OSDMAP_PAUSEWR)) {
2370 		dout("%s osdc %p continuous\n", __func__, osdc);
2371 		continuous = true;
2372 	} else {
2373 		dout("%s osdc %p onetime\n", __func__, osdc);
2374 	}
2375 
2376 	if (ceph_monc_want_map(&osdc->client->monc, CEPH_SUB_OSDMAP,
2377 			       osdc->osdmap->epoch + 1, continuous))
2378 		ceph_monc_renew_subs(&osdc->client->monc);
2379 }
2380 
2381 static void complete_request(struct ceph_osd_request *req, int err);
2382 static void send_map_check(struct ceph_osd_request *req);
2383 
2384 static void __submit_request(struct ceph_osd_request *req, bool wrlocked)
2385 {
2386 	struct ceph_osd_client *osdc = req->r_osdc;
2387 	struct ceph_osd *osd;
2388 	enum calc_target_result ct_res;
2389 	int err = 0;
2390 	bool need_send = false;
2391 	bool promoted = false;
2392 
2393 	WARN_ON(req->r_tid);
2394 	dout("%s req %p wrlocked %d\n", __func__, req, wrlocked);
2395 
2396 again:
2397 	ct_res = calc_target(osdc, &req->r_t, false);
2398 	if (ct_res == CALC_TARGET_POOL_DNE && !wrlocked)
2399 		goto promote;
2400 
2401 	osd = lookup_create_osd(osdc, req->r_t.osd, wrlocked);
2402 	if (IS_ERR(osd)) {
2403 		WARN_ON(PTR_ERR(osd) != -EAGAIN || wrlocked);
2404 		goto promote;
2405 	}
2406 
2407 	if (osdc->abort_err) {
2408 		dout("req %p abort_err %d\n", req, osdc->abort_err);
2409 		err = osdc->abort_err;
2410 	} else if (osdc->osdmap->epoch < osdc->epoch_barrier) {
2411 		dout("req %p epoch %u barrier %u\n", req, osdc->osdmap->epoch,
2412 		     osdc->epoch_barrier);
2413 		req->r_t.paused = true;
2414 		maybe_request_map(osdc);
2415 	} else if ((req->r_flags & CEPH_OSD_FLAG_WRITE) &&
2416 		   ceph_osdmap_flag(osdc, CEPH_OSDMAP_PAUSEWR)) {
2417 		dout("req %p pausewr\n", req);
2418 		req->r_t.paused = true;
2419 		maybe_request_map(osdc);
2420 	} else if ((req->r_flags & CEPH_OSD_FLAG_READ) &&
2421 		   ceph_osdmap_flag(osdc, CEPH_OSDMAP_PAUSERD)) {
2422 		dout("req %p pauserd\n", req);
2423 		req->r_t.paused = true;
2424 		maybe_request_map(osdc);
2425 	} else if ((req->r_flags & CEPH_OSD_FLAG_WRITE) &&
2426 		   !(req->r_flags & (CEPH_OSD_FLAG_FULL_TRY |
2427 				     CEPH_OSD_FLAG_FULL_FORCE)) &&
2428 		   (ceph_osdmap_flag(osdc, CEPH_OSDMAP_FULL) ||
2429 		    pool_full(osdc, req->r_t.base_oloc.pool))) {
2430 		dout("req %p full/pool_full\n", req);
2431 		if (ceph_test_opt(osdc->client, ABORT_ON_FULL)) {
2432 			err = -ENOSPC;
2433 		} else {
2434 			if (ceph_osdmap_flag(osdc, CEPH_OSDMAP_FULL))
2435 				pr_warn_ratelimited("cluster is full (osdmap FULL)\n");
2436 			else
2437 				pr_warn_ratelimited("pool %lld is full or reached quota\n",
2438 						    req->r_t.base_oloc.pool);
2439 			req->r_t.paused = true;
2440 			maybe_request_map(osdc);
2441 		}
2442 	} else if (!osd_homeless(osd)) {
2443 		need_send = true;
2444 	} else {
2445 		maybe_request_map(osdc);
2446 	}
2447 
2448 	mutex_lock(&osd->lock);
2449 	/*
2450 	 * Assign the tid atomically with send_request() to protect
2451 	 * multiple writes to the same object from racing with each
2452 	 * other, resulting in out of order ops on the OSDs.
2453 	 */
2454 	req->r_tid = atomic64_inc_return(&osdc->last_tid);
2455 	link_request(osd, req);
2456 	if (need_send)
2457 		send_request(req);
2458 	else if (err)
2459 		complete_request(req, err);
2460 	mutex_unlock(&osd->lock);
2461 
2462 	if (!err && ct_res == CALC_TARGET_POOL_DNE)
2463 		send_map_check(req);
2464 
2465 	if (promoted)
2466 		downgrade_write(&osdc->lock);
2467 	return;
2468 
2469 promote:
2470 	up_read(&osdc->lock);
2471 	down_write(&osdc->lock);
2472 	wrlocked = true;
2473 	promoted = true;
2474 	goto again;
2475 }
2476 
2477 static void account_request(struct ceph_osd_request *req)
2478 {
2479 	WARN_ON(req->r_flags & (CEPH_OSD_FLAG_ACK | CEPH_OSD_FLAG_ONDISK));
2480 	WARN_ON(!(req->r_flags & (CEPH_OSD_FLAG_READ | CEPH_OSD_FLAG_WRITE)));
2481 
2482 	req->r_flags |= CEPH_OSD_FLAG_ONDISK;
2483 	atomic_inc(&req->r_osdc->num_requests);
2484 
2485 	req->r_start_stamp = jiffies;
2486 	req->r_start_latency = ktime_get();
2487 }
2488 
2489 static void submit_request(struct ceph_osd_request *req, bool wrlocked)
2490 {
2491 	ceph_osdc_get_request(req);
2492 	account_request(req);
2493 	__submit_request(req, wrlocked);
2494 }
2495 
2496 static void finish_request(struct ceph_osd_request *req)
2497 {
2498 	struct ceph_osd_client *osdc = req->r_osdc;
2499 
2500 	WARN_ON(lookup_request_mc(&osdc->map_checks, req->r_tid));
2501 	dout("%s req %p tid %llu\n", __func__, req, req->r_tid);
2502 
2503 	req->r_end_latency = ktime_get();
2504 
2505 	if (req->r_osd) {
2506 		ceph_init_sparse_read(&req->r_osd->o_sparse_read);
2507 		unlink_request(req->r_osd, req);
2508 	}
2509 	atomic_dec(&osdc->num_requests);
2510 
2511 	/*
2512 	 * If an OSD has failed or returned and a request has been sent
2513 	 * twice, it's possible to get a reply and end up here while the
2514 	 * request message is queued for delivery.  We will ignore the
2515 	 * reply, so not a big deal, but better to try and catch it.
2516 	 */
2517 	ceph_msg_revoke(req->r_request);
2518 	ceph_msg_revoke_incoming(req->r_reply);
2519 }
2520 
2521 static void __complete_request(struct ceph_osd_request *req)
2522 {
2523 	dout("%s req %p tid %llu cb %ps result %d\n", __func__, req,
2524 	     req->r_tid, req->r_callback, req->r_result);
2525 
2526 	if (req->r_callback)
2527 		req->r_callback(req);
2528 	complete_all(&req->r_completion);
2529 	ceph_osdc_put_request(req);
2530 }
2531 
2532 static void complete_request_workfn(struct work_struct *work)
2533 {
2534 	struct ceph_osd_request *req =
2535 	    container_of(work, struct ceph_osd_request, r_complete_work);
2536 
2537 	__complete_request(req);
2538 }
2539 
2540 /*
2541  * This is open-coded in handle_reply().
2542  */
2543 static void complete_request(struct ceph_osd_request *req, int err)
2544 {
2545 	dout("%s req %p tid %llu err %d\n", __func__, req, req->r_tid, err);
2546 
2547 	req->r_result = err;
2548 	finish_request(req);
2549 
2550 	INIT_WORK(&req->r_complete_work, complete_request_workfn);
2551 	queue_work(req->r_osdc->completion_wq, &req->r_complete_work);
2552 }
2553 
2554 static void cancel_map_check(struct ceph_osd_request *req)
2555 {
2556 	struct ceph_osd_client *osdc = req->r_osdc;
2557 	struct ceph_osd_request *lookup_req;
2558 
2559 	verify_osdc_wrlocked(osdc);
2560 
2561 	lookup_req = lookup_request_mc(&osdc->map_checks, req->r_tid);
2562 	if (!lookup_req)
2563 		return;
2564 
2565 	WARN_ON(lookup_req != req);
2566 	erase_request_mc(&osdc->map_checks, req);
2567 	ceph_osdc_put_request(req);
2568 }
2569 
2570 static void cancel_request(struct ceph_osd_request *req)
2571 {
2572 	dout("%s req %p tid %llu\n", __func__, req, req->r_tid);
2573 
2574 	cancel_map_check(req);
2575 	finish_request(req);
2576 	complete_all(&req->r_completion);
2577 	ceph_osdc_put_request(req);
2578 }
2579 
2580 static void abort_request(struct ceph_osd_request *req, int err)
2581 {
2582 	dout("%s req %p tid %llu err %d\n", __func__, req, req->r_tid, err);
2583 
2584 	cancel_map_check(req);
2585 	complete_request(req, err);
2586 }
2587 
2588 static int abort_fn(struct ceph_osd_request *req, void *arg)
2589 {
2590 	int err = *(int *)arg;
2591 
2592 	abort_request(req, err);
2593 	return 0; /* continue iteration */
2594 }
2595 
2596 /*
2597  * Abort all in-flight requests with @err and arrange for all future
2598  * requests to be failed immediately.
2599  */
2600 void ceph_osdc_abort_requests(struct ceph_osd_client *osdc, int err)
2601 {
2602 	dout("%s osdc %p err %d\n", __func__, osdc, err);
2603 	down_write(&osdc->lock);
2604 	for_each_request(osdc, abort_fn, &err);
2605 	osdc->abort_err = err;
2606 	up_write(&osdc->lock);
2607 }
2608 EXPORT_SYMBOL(ceph_osdc_abort_requests);
2609 
2610 void ceph_osdc_clear_abort_err(struct ceph_osd_client *osdc)
2611 {
2612 	down_write(&osdc->lock);
2613 	osdc->abort_err = 0;
2614 	up_write(&osdc->lock);
2615 }
2616 EXPORT_SYMBOL(ceph_osdc_clear_abort_err);
2617 
2618 static void update_epoch_barrier(struct ceph_osd_client *osdc, u32 eb)
2619 {
2620 	if (likely(eb > osdc->epoch_barrier)) {
2621 		dout("updating epoch_barrier from %u to %u\n",
2622 				osdc->epoch_barrier, eb);
2623 		osdc->epoch_barrier = eb;
2624 		/* Request map if we're not to the barrier yet */
2625 		if (eb > osdc->osdmap->epoch)
2626 			maybe_request_map(osdc);
2627 	}
2628 }
2629 
2630 void ceph_osdc_update_epoch_barrier(struct ceph_osd_client *osdc, u32 eb)
2631 {
2632 	down_read(&osdc->lock);
2633 	if (unlikely(eb > osdc->epoch_barrier)) {
2634 		up_read(&osdc->lock);
2635 		down_write(&osdc->lock);
2636 		update_epoch_barrier(osdc, eb);
2637 		up_write(&osdc->lock);
2638 	} else {
2639 		up_read(&osdc->lock);
2640 	}
2641 }
2642 EXPORT_SYMBOL(ceph_osdc_update_epoch_barrier);
2643 
2644 /*
2645  * We can end up releasing caps as a result of abort_request().
2646  * In that case, we probably want to ensure that the cap release message
2647  * has an updated epoch barrier in it, so set the epoch barrier prior to
2648  * aborting the first request.
2649  */
2650 static int abort_on_full_fn(struct ceph_osd_request *req, void *arg)
2651 {
2652 	struct ceph_osd_client *osdc = req->r_osdc;
2653 	bool *victims = arg;
2654 
2655 	if ((req->r_flags & CEPH_OSD_FLAG_WRITE) &&
2656 	    (ceph_osdmap_flag(osdc, CEPH_OSDMAP_FULL) ||
2657 	     pool_full(osdc, req->r_t.base_oloc.pool))) {
2658 		if (!*victims) {
2659 			update_epoch_barrier(osdc, osdc->osdmap->epoch);
2660 			*victims = true;
2661 		}
2662 		abort_request(req, -ENOSPC);
2663 	}
2664 
2665 	return 0; /* continue iteration */
2666 }
2667 
2668 /*
2669  * Drop all pending requests that are stalled waiting on a full condition to
2670  * clear, and complete them with ENOSPC as the return code. Set the
2671  * osdc->epoch_barrier to the latest map epoch that we've seen if any were
2672  * cancelled.
2673  */
2674 static void ceph_osdc_abort_on_full(struct ceph_osd_client *osdc)
2675 {
2676 	bool victims = false;
2677 
2678 	if (ceph_test_opt(osdc->client, ABORT_ON_FULL) &&
2679 	    (ceph_osdmap_flag(osdc, CEPH_OSDMAP_FULL) || have_pool_full(osdc)))
2680 		for_each_request(osdc, abort_on_full_fn, &victims);
2681 }
2682 
2683 static void check_pool_dne(struct ceph_osd_request *req)
2684 {
2685 	struct ceph_osd_client *osdc = req->r_osdc;
2686 	struct ceph_osdmap *map = osdc->osdmap;
2687 
2688 	verify_osdc_wrlocked(osdc);
2689 	WARN_ON(!map->epoch);
2690 
2691 	if (req->r_attempts) {
2692 		/*
2693 		 * We sent a request earlier, which means that
2694 		 * previously the pool existed, and now it does not
2695 		 * (i.e., it was deleted).
2696 		 */
2697 		req->r_map_dne_bound = map->epoch;
2698 		dout("%s req %p tid %llu pool disappeared\n", __func__, req,
2699 		     req->r_tid);
2700 	} else {
2701 		dout("%s req %p tid %llu map_dne_bound %u have %u\n", __func__,
2702 		     req, req->r_tid, req->r_map_dne_bound, map->epoch);
2703 	}
2704 
2705 	if (req->r_map_dne_bound) {
2706 		if (map->epoch >= req->r_map_dne_bound) {
2707 			/* we had a new enough map */
2708 			pr_info_ratelimited("tid %llu pool does not exist\n",
2709 					    req->r_tid);
2710 			complete_request(req, -ENOENT);
2711 		}
2712 	} else {
2713 		send_map_check(req);
2714 	}
2715 }
2716 
2717 static void map_check_cb(struct ceph_mon_generic_request *greq)
2718 {
2719 	struct ceph_osd_client *osdc = &greq->monc->client->osdc;
2720 	struct ceph_osd_request *req;
2721 	u64 tid = greq->private_data;
2722 
2723 	WARN_ON(greq->result || !greq->u.newest);
2724 
2725 	down_write(&osdc->lock);
2726 	req = lookup_request_mc(&osdc->map_checks, tid);
2727 	if (!req) {
2728 		dout("%s tid %llu dne\n", __func__, tid);
2729 		goto out_unlock;
2730 	}
2731 
2732 	dout("%s req %p tid %llu map_dne_bound %u newest %llu\n", __func__,
2733 	     req, req->r_tid, req->r_map_dne_bound, greq->u.newest);
2734 	if (!req->r_map_dne_bound)
2735 		req->r_map_dne_bound = greq->u.newest;
2736 	erase_request_mc(&osdc->map_checks, req);
2737 	check_pool_dne(req);
2738 
2739 	ceph_osdc_put_request(req);
2740 out_unlock:
2741 	up_write(&osdc->lock);
2742 }
2743 
2744 static void send_map_check(struct ceph_osd_request *req)
2745 {
2746 	struct ceph_osd_client *osdc = req->r_osdc;
2747 	struct ceph_osd_request *lookup_req;
2748 	int ret;
2749 
2750 	verify_osdc_wrlocked(osdc);
2751 
2752 	lookup_req = lookup_request_mc(&osdc->map_checks, req->r_tid);
2753 	if (lookup_req) {
2754 		WARN_ON(lookup_req != req);
2755 		return;
2756 	}
2757 
2758 	ceph_osdc_get_request(req);
2759 	insert_request_mc(&osdc->map_checks, req);
2760 	ret = ceph_monc_get_version_async(&osdc->client->monc, "osdmap",
2761 					  map_check_cb, req->r_tid);
2762 	WARN_ON(ret);
2763 }
2764 
2765 /*
2766  * lingering requests, watch/notify v2 infrastructure
2767  */
2768 static void linger_release(struct kref *kref)
2769 {
2770 	struct ceph_osd_linger_request *lreq =
2771 	    container_of(kref, struct ceph_osd_linger_request, kref);
2772 
2773 	dout("%s lreq %p reg_req %p ping_req %p\n", __func__, lreq,
2774 	     lreq->reg_req, lreq->ping_req);
2775 	WARN_ON(!RB_EMPTY_NODE(&lreq->node));
2776 	WARN_ON(!RB_EMPTY_NODE(&lreq->osdc_node));
2777 	WARN_ON(!RB_EMPTY_NODE(&lreq->mc_node));
2778 	WARN_ON(!list_empty(&lreq->scan_item));
2779 	WARN_ON(!list_empty(&lreq->pending_lworks));
2780 	WARN_ON(lreq->osd);
2781 
2782 	if (lreq->request_pl)
2783 		ceph_pagelist_release(lreq->request_pl);
2784 	if (lreq->notify_id_pages)
2785 		ceph_release_page_vector(lreq->notify_id_pages, 1);
2786 
2787 	ceph_osdc_put_request(lreq->reg_req);
2788 	ceph_osdc_put_request(lreq->ping_req);
2789 	target_destroy(&lreq->t);
2790 	kfree(lreq);
2791 }
2792 
2793 static void linger_put(struct ceph_osd_linger_request *lreq)
2794 {
2795 	if (lreq)
2796 		kref_put(&lreq->kref, linger_release);
2797 }
2798 
2799 static struct ceph_osd_linger_request *
2800 linger_get(struct ceph_osd_linger_request *lreq)
2801 {
2802 	kref_get(&lreq->kref);
2803 	return lreq;
2804 }
2805 
2806 static struct ceph_osd_linger_request *
2807 linger_alloc(struct ceph_osd_client *osdc)
2808 {
2809 	struct ceph_osd_linger_request *lreq;
2810 
2811 	lreq = kzalloc_obj(*lreq, GFP_NOIO);
2812 	if (!lreq)
2813 		return NULL;
2814 
2815 	kref_init(&lreq->kref);
2816 	mutex_init(&lreq->lock);
2817 	RB_CLEAR_NODE(&lreq->node);
2818 	RB_CLEAR_NODE(&lreq->osdc_node);
2819 	RB_CLEAR_NODE(&lreq->mc_node);
2820 	INIT_LIST_HEAD(&lreq->scan_item);
2821 	INIT_LIST_HEAD(&lreq->pending_lworks);
2822 	init_completion(&lreq->reg_commit_wait);
2823 	init_completion(&lreq->notify_finish_wait);
2824 
2825 	lreq->osdc = osdc;
2826 	target_init(&lreq->t);
2827 
2828 	dout("%s lreq %p\n", __func__, lreq);
2829 	return lreq;
2830 }
2831 
2832 DEFINE_RB_INSDEL_FUNCS(linger, struct ceph_osd_linger_request, linger_id, node)
2833 DEFINE_RB_FUNCS(linger_osdc, struct ceph_osd_linger_request, linger_id, osdc_node)
2834 DEFINE_RB_FUNCS(linger_mc, struct ceph_osd_linger_request, linger_id, mc_node)
2835 
2836 /*
2837  * Create linger request <-> OSD session relation.
2838  *
2839  * @lreq has to be registered, @osd may be homeless.
2840  */
2841 static void link_linger(struct ceph_osd *osd,
2842 			struct ceph_osd_linger_request *lreq)
2843 {
2844 	verify_osd_locked(osd);
2845 	WARN_ON(!lreq->linger_id || lreq->osd);
2846 	dout("%s osd %p osd%d lreq %p linger_id %llu\n", __func__, osd,
2847 	     osd->o_osd, lreq, lreq->linger_id);
2848 
2849 	if (!osd_homeless(osd))
2850 		__remove_osd_from_lru(osd);
2851 	else
2852 		atomic_inc(&osd->o_osdc->num_homeless);
2853 
2854 	get_osd(osd);
2855 	insert_linger(&osd->o_linger_requests, lreq);
2856 	lreq->osd = osd;
2857 }
2858 
2859 static void unlink_linger(struct ceph_osd *osd,
2860 			  struct ceph_osd_linger_request *lreq)
2861 {
2862 	verify_osd_locked(osd);
2863 	WARN_ON(lreq->osd != osd);
2864 	dout("%s osd %p osd%d lreq %p linger_id %llu\n", __func__, osd,
2865 	     osd->o_osd, lreq, lreq->linger_id);
2866 
2867 	lreq->osd = NULL;
2868 	erase_linger(&osd->o_linger_requests, lreq);
2869 	put_osd(osd);
2870 
2871 	if (!osd_homeless(osd))
2872 		maybe_move_osd_to_lru(osd);
2873 	else
2874 		atomic_dec(&osd->o_osdc->num_homeless);
2875 }
2876 
2877 static bool __linger_registered(struct ceph_osd_linger_request *lreq)
2878 {
2879 	verify_osdc_locked(lreq->osdc);
2880 
2881 	return !RB_EMPTY_NODE(&lreq->osdc_node);
2882 }
2883 
2884 static bool linger_registered(struct ceph_osd_linger_request *lreq)
2885 {
2886 	struct ceph_osd_client *osdc = lreq->osdc;
2887 	bool registered;
2888 
2889 	down_read(&osdc->lock);
2890 	registered = __linger_registered(lreq);
2891 	up_read(&osdc->lock);
2892 
2893 	return registered;
2894 }
2895 
2896 static void linger_register(struct ceph_osd_linger_request *lreq)
2897 {
2898 	struct ceph_osd_client *osdc = lreq->osdc;
2899 
2900 	verify_osdc_wrlocked(osdc);
2901 	WARN_ON(lreq->linger_id);
2902 
2903 	linger_get(lreq);
2904 	lreq->linger_id = ++osdc->last_linger_id;
2905 	insert_linger_osdc(&osdc->linger_requests, lreq);
2906 }
2907 
2908 static void linger_unregister(struct ceph_osd_linger_request *lreq)
2909 {
2910 	struct ceph_osd_client *osdc = lreq->osdc;
2911 
2912 	verify_osdc_wrlocked(osdc);
2913 
2914 	erase_linger_osdc(&osdc->linger_requests, lreq);
2915 	linger_put(lreq);
2916 }
2917 
2918 static void cancel_linger_request(struct ceph_osd_request *req)
2919 {
2920 	struct ceph_osd_linger_request *lreq = req->r_priv;
2921 
2922 	WARN_ON(!req->r_linger);
2923 	cancel_request(req);
2924 	linger_put(lreq);
2925 }
2926 
2927 struct linger_work {
2928 	struct work_struct work;
2929 	struct ceph_osd_linger_request *lreq;
2930 	struct list_head pending_item;
2931 	unsigned long queued_stamp;
2932 
2933 	union {
2934 		struct {
2935 			u64 notify_id;
2936 			u64 notifier_id;
2937 			void *payload; /* points into @msg front */
2938 			size_t payload_len;
2939 
2940 			struct ceph_msg *msg; /* for ceph_msg_put() */
2941 		} notify;
2942 		struct {
2943 			int err;
2944 		} error;
2945 	};
2946 };
2947 
2948 static struct linger_work *lwork_alloc(struct ceph_osd_linger_request *lreq,
2949 				       work_func_t workfn)
2950 {
2951 	struct linger_work *lwork;
2952 
2953 	lwork = kzalloc_obj(*lwork, GFP_NOIO);
2954 	if (!lwork)
2955 		return NULL;
2956 
2957 	INIT_WORK(&lwork->work, workfn);
2958 	INIT_LIST_HEAD(&lwork->pending_item);
2959 	lwork->lreq = linger_get(lreq);
2960 
2961 	return lwork;
2962 }
2963 
2964 static void lwork_free(struct linger_work *lwork)
2965 {
2966 	struct ceph_osd_linger_request *lreq = lwork->lreq;
2967 
2968 	mutex_lock(&lreq->lock);
2969 	list_del(&lwork->pending_item);
2970 	mutex_unlock(&lreq->lock);
2971 
2972 	linger_put(lreq);
2973 	kfree(lwork);
2974 }
2975 
2976 static void lwork_queue(struct linger_work *lwork)
2977 {
2978 	struct ceph_osd_linger_request *lreq = lwork->lreq;
2979 	struct ceph_osd_client *osdc = lreq->osdc;
2980 
2981 	verify_lreq_locked(lreq);
2982 	WARN_ON(!list_empty(&lwork->pending_item));
2983 
2984 	lwork->queued_stamp = jiffies;
2985 	list_add_tail(&lwork->pending_item, &lreq->pending_lworks);
2986 	queue_work(osdc->notify_wq, &lwork->work);
2987 }
2988 
2989 static void do_watch_notify(struct work_struct *w)
2990 {
2991 	struct linger_work *lwork = container_of(w, struct linger_work, work);
2992 	struct ceph_osd_linger_request *lreq = lwork->lreq;
2993 
2994 	if (!linger_registered(lreq)) {
2995 		dout("%s lreq %p not registered\n", __func__, lreq);
2996 		goto out;
2997 	}
2998 
2999 	WARN_ON(!lreq->is_watch);
3000 	dout("%s lreq %p notify_id %llu notifier_id %llu payload_len %zu\n",
3001 	     __func__, lreq, lwork->notify.notify_id, lwork->notify.notifier_id,
3002 	     lwork->notify.payload_len);
3003 	lreq->wcb(lreq->data, lwork->notify.notify_id, lreq->linger_id,
3004 		  lwork->notify.notifier_id, lwork->notify.payload,
3005 		  lwork->notify.payload_len);
3006 
3007 out:
3008 	ceph_msg_put(lwork->notify.msg);
3009 	lwork_free(lwork);
3010 }
3011 
3012 static void do_watch_error(struct work_struct *w)
3013 {
3014 	struct linger_work *lwork = container_of(w, struct linger_work, work);
3015 	struct ceph_osd_linger_request *lreq = lwork->lreq;
3016 
3017 	if (!linger_registered(lreq)) {
3018 		dout("%s lreq %p not registered\n", __func__, lreq);
3019 		goto out;
3020 	}
3021 
3022 	dout("%s lreq %p err %d\n", __func__, lreq, lwork->error.err);
3023 	lreq->errcb(lreq->data, lreq->linger_id, lwork->error.err);
3024 
3025 out:
3026 	lwork_free(lwork);
3027 }
3028 
3029 static void queue_watch_error(struct ceph_osd_linger_request *lreq)
3030 {
3031 	struct linger_work *lwork;
3032 
3033 	lwork = lwork_alloc(lreq, do_watch_error);
3034 	if (!lwork) {
3035 		pr_err("failed to allocate error-lwork\n");
3036 		return;
3037 	}
3038 
3039 	lwork->error.err = lreq->last_error;
3040 	lwork_queue(lwork);
3041 }
3042 
3043 static void linger_reg_commit_complete(struct ceph_osd_linger_request *lreq,
3044 				       int result)
3045 {
3046 	if (!completion_done(&lreq->reg_commit_wait)) {
3047 		lreq->reg_commit_error = (result <= 0 ? result : 0);
3048 		complete_all(&lreq->reg_commit_wait);
3049 	}
3050 }
3051 
3052 static void linger_commit_cb(struct ceph_osd_request *req)
3053 {
3054 	struct ceph_osd_linger_request *lreq = req->r_priv;
3055 
3056 	mutex_lock(&lreq->lock);
3057 	if (req != lreq->reg_req) {
3058 		dout("%s lreq %p linger_id %llu unknown req (%p != %p)\n",
3059 		     __func__, lreq, lreq->linger_id, req, lreq->reg_req);
3060 		goto out;
3061 	}
3062 
3063 	dout("%s lreq %p linger_id %llu result %d\n", __func__, lreq,
3064 	     lreq->linger_id, req->r_result);
3065 	linger_reg_commit_complete(lreq, req->r_result);
3066 	lreq->committed = true;
3067 
3068 	if (!lreq->is_watch) {
3069 		struct ceph_osd_data *osd_data =
3070 		    osd_req_op_data(req, 0, notify, response_data);
3071 		void *p = page_address(osd_data->pages[0]);
3072 
3073 		WARN_ON(req->r_ops[0].op != CEPH_OSD_OP_NOTIFY ||
3074 			osd_data->type != CEPH_OSD_DATA_TYPE_PAGES);
3075 
3076 		/* make note of the notify_id */
3077 		if (req->r_ops[0].outdata_len >= sizeof(u64)) {
3078 			lreq->notify_id = ceph_decode_64(&p);
3079 			dout("lreq %p notify_id %llu\n", lreq,
3080 			     lreq->notify_id);
3081 		} else {
3082 			dout("lreq %p no notify_id\n", lreq);
3083 		}
3084 	}
3085 
3086 out:
3087 	mutex_unlock(&lreq->lock);
3088 	linger_put(lreq);
3089 }
3090 
3091 static int normalize_watch_error(int err)
3092 {
3093 	/*
3094 	 * Translate ENOENT -> ENOTCONN so that a delete->disconnection
3095 	 * notification and a failure to reconnect because we raced with
3096 	 * the delete appear the same to the user.
3097 	 */
3098 	if (err == -ENOENT)
3099 		err = -ENOTCONN;
3100 
3101 	return err;
3102 }
3103 
3104 static void linger_reconnect_cb(struct ceph_osd_request *req)
3105 {
3106 	struct ceph_osd_linger_request *lreq = req->r_priv;
3107 
3108 	mutex_lock(&lreq->lock);
3109 	if (req != lreq->reg_req) {
3110 		dout("%s lreq %p linger_id %llu unknown req (%p != %p)\n",
3111 		     __func__, lreq, lreq->linger_id, req, lreq->reg_req);
3112 		goto out;
3113 	}
3114 
3115 	dout("%s lreq %p linger_id %llu result %d last_error %d\n", __func__,
3116 	     lreq, lreq->linger_id, req->r_result, lreq->last_error);
3117 	if (req->r_result < 0) {
3118 		if (!lreq->last_error) {
3119 			lreq->last_error = normalize_watch_error(req->r_result);
3120 			queue_watch_error(lreq);
3121 		}
3122 	}
3123 
3124 out:
3125 	mutex_unlock(&lreq->lock);
3126 	linger_put(lreq);
3127 }
3128 
3129 static void send_linger(struct ceph_osd_linger_request *lreq)
3130 {
3131 	struct ceph_osd_client *osdc = lreq->osdc;
3132 	struct ceph_osd_request *req;
3133 	int ret;
3134 
3135 	verify_osdc_wrlocked(osdc);
3136 	mutex_lock(&lreq->lock);
3137 	dout("%s lreq %p linger_id %llu\n", __func__, lreq, lreq->linger_id);
3138 
3139 	if (lreq->reg_req) {
3140 		if (lreq->reg_req->r_osd)
3141 			cancel_linger_request(lreq->reg_req);
3142 		ceph_osdc_put_request(lreq->reg_req);
3143 	}
3144 
3145 	req = ceph_osdc_alloc_request(osdc, NULL, 1, true, GFP_NOIO);
3146 	BUG_ON(!req);
3147 
3148 	target_copy(&req->r_t, &lreq->t);
3149 	req->r_mtime = lreq->mtime;
3150 
3151 	if (lreq->is_watch && lreq->committed) {
3152 		osd_req_op_watch_init(req, 0, CEPH_OSD_WATCH_OP_RECONNECT,
3153 				      lreq->linger_id, ++lreq->register_gen);
3154 		dout("lreq %p reconnect register_gen %u\n", lreq,
3155 		     req->r_ops[0].watch.gen);
3156 		req->r_callback = linger_reconnect_cb;
3157 	} else {
3158 		if (lreq->is_watch) {
3159 			osd_req_op_watch_init(req, 0, CEPH_OSD_WATCH_OP_WATCH,
3160 					      lreq->linger_id, 0);
3161 		} else {
3162 			lreq->notify_id = 0;
3163 
3164 			refcount_inc(&lreq->request_pl->refcnt);
3165 			osd_req_op_notify_init(req, 0, lreq->linger_id,
3166 					       lreq->request_pl);
3167 			ceph_osd_data_pages_init(
3168 			    osd_req_op_data(req, 0, notify, response_data),
3169 			    lreq->notify_id_pages, PAGE_SIZE, 0, false, false);
3170 		}
3171 		dout("lreq %p register\n", lreq);
3172 		req->r_callback = linger_commit_cb;
3173 	}
3174 
3175 	ret = ceph_osdc_alloc_messages(req, GFP_NOIO);
3176 	BUG_ON(ret);
3177 
3178 	req->r_priv = linger_get(lreq);
3179 	req->r_linger = true;
3180 	lreq->reg_req = req;
3181 	mutex_unlock(&lreq->lock);
3182 
3183 	submit_request(req, true);
3184 }
3185 
3186 static void linger_ping_cb(struct ceph_osd_request *req)
3187 {
3188 	struct ceph_osd_linger_request *lreq = req->r_priv;
3189 
3190 	mutex_lock(&lreq->lock);
3191 	if (req != lreq->ping_req) {
3192 		dout("%s lreq %p linger_id %llu unknown req (%p != %p)\n",
3193 		     __func__, lreq, lreq->linger_id, req, lreq->ping_req);
3194 		goto out;
3195 	}
3196 
3197 	dout("%s lreq %p linger_id %llu result %d ping_sent %lu last_error %d\n",
3198 	     __func__, lreq, lreq->linger_id, req->r_result, lreq->ping_sent,
3199 	     lreq->last_error);
3200 	if (lreq->register_gen == req->r_ops[0].watch.gen) {
3201 		if (!req->r_result) {
3202 			lreq->watch_valid_thru = lreq->ping_sent;
3203 		} else if (!lreq->last_error) {
3204 			lreq->last_error = normalize_watch_error(req->r_result);
3205 			queue_watch_error(lreq);
3206 		}
3207 	} else {
3208 		dout("lreq %p register_gen %u ignoring old pong %u\n", lreq,
3209 		     lreq->register_gen, req->r_ops[0].watch.gen);
3210 	}
3211 
3212 out:
3213 	mutex_unlock(&lreq->lock);
3214 	linger_put(lreq);
3215 }
3216 
3217 static void send_linger_ping(struct ceph_osd_linger_request *lreq)
3218 {
3219 	struct ceph_osd_client *osdc = lreq->osdc;
3220 	struct ceph_osd_request *req;
3221 	int ret;
3222 
3223 	if (ceph_osdmap_flag(osdc, CEPH_OSDMAP_PAUSERD)) {
3224 		dout("%s PAUSERD\n", __func__);
3225 		return;
3226 	}
3227 
3228 	lreq->ping_sent = jiffies;
3229 	dout("%s lreq %p linger_id %llu ping_sent %lu register_gen %u\n",
3230 	     __func__, lreq, lreq->linger_id, lreq->ping_sent,
3231 	     lreq->register_gen);
3232 
3233 	if (lreq->ping_req) {
3234 		if (lreq->ping_req->r_osd)
3235 			cancel_linger_request(lreq->ping_req);
3236 		ceph_osdc_put_request(lreq->ping_req);
3237 	}
3238 
3239 	req = ceph_osdc_alloc_request(osdc, NULL, 1, true, GFP_NOIO);
3240 	BUG_ON(!req);
3241 
3242 	target_copy(&req->r_t, &lreq->t);
3243 	osd_req_op_watch_init(req, 0, CEPH_OSD_WATCH_OP_PING, lreq->linger_id,
3244 			      lreq->register_gen);
3245 	req->r_callback = linger_ping_cb;
3246 
3247 	ret = ceph_osdc_alloc_messages(req, GFP_NOIO);
3248 	BUG_ON(ret);
3249 
3250 	req->r_priv = linger_get(lreq);
3251 	req->r_linger = true;
3252 	lreq->ping_req = req;
3253 
3254 	ceph_osdc_get_request(req);
3255 	account_request(req);
3256 	req->r_tid = atomic64_inc_return(&osdc->last_tid);
3257 	link_request(lreq->osd, req);
3258 	send_request(req);
3259 }
3260 
3261 static void linger_submit(struct ceph_osd_linger_request *lreq)
3262 {
3263 	struct ceph_osd_client *osdc = lreq->osdc;
3264 	struct ceph_osd *osd;
3265 
3266 	down_write(&osdc->lock);
3267 	linger_register(lreq);
3268 
3269 	calc_target(osdc, &lreq->t, false);
3270 	osd = lookup_create_osd(osdc, lreq->t.osd, true);
3271 	link_linger(osd, lreq);
3272 
3273 	send_linger(lreq);
3274 	up_write(&osdc->lock);
3275 }
3276 
3277 static void cancel_linger_map_check(struct ceph_osd_linger_request *lreq)
3278 {
3279 	struct ceph_osd_client *osdc = lreq->osdc;
3280 	struct ceph_osd_linger_request *lookup_lreq;
3281 
3282 	verify_osdc_wrlocked(osdc);
3283 
3284 	lookup_lreq = lookup_linger_mc(&osdc->linger_map_checks,
3285 				       lreq->linger_id);
3286 	if (!lookup_lreq)
3287 		return;
3288 
3289 	WARN_ON(lookup_lreq != lreq);
3290 	erase_linger_mc(&osdc->linger_map_checks, lreq);
3291 	linger_put(lreq);
3292 }
3293 
3294 /*
3295  * @lreq has to be both registered and linked.
3296  */
3297 static void __linger_cancel(struct ceph_osd_linger_request *lreq)
3298 {
3299 	if (lreq->ping_req && lreq->ping_req->r_osd)
3300 		cancel_linger_request(lreq->ping_req);
3301 	if (lreq->reg_req && lreq->reg_req->r_osd)
3302 		cancel_linger_request(lreq->reg_req);
3303 	cancel_linger_map_check(lreq);
3304 	unlink_linger(lreq->osd, lreq);
3305 	linger_unregister(lreq);
3306 }
3307 
3308 static void linger_cancel(struct ceph_osd_linger_request *lreq)
3309 {
3310 	struct ceph_osd_client *osdc = lreq->osdc;
3311 
3312 	down_write(&osdc->lock);
3313 	if (__linger_registered(lreq))
3314 		__linger_cancel(lreq);
3315 	up_write(&osdc->lock);
3316 }
3317 
3318 static void send_linger_map_check(struct ceph_osd_linger_request *lreq);
3319 
3320 static void check_linger_pool_dne(struct ceph_osd_linger_request *lreq)
3321 {
3322 	struct ceph_osd_client *osdc = lreq->osdc;
3323 	struct ceph_osdmap *map = osdc->osdmap;
3324 
3325 	verify_osdc_wrlocked(osdc);
3326 	WARN_ON(!map->epoch);
3327 
3328 	if (lreq->register_gen) {
3329 		lreq->map_dne_bound = map->epoch;
3330 		dout("%s lreq %p linger_id %llu pool disappeared\n", __func__,
3331 		     lreq, lreq->linger_id);
3332 	} else {
3333 		dout("%s lreq %p linger_id %llu map_dne_bound %u have %u\n",
3334 		     __func__, lreq, lreq->linger_id, lreq->map_dne_bound,
3335 		     map->epoch);
3336 	}
3337 
3338 	if (lreq->map_dne_bound) {
3339 		if (map->epoch >= lreq->map_dne_bound) {
3340 			/* we had a new enough map */
3341 			pr_info("linger_id %llu pool does not exist\n",
3342 				lreq->linger_id);
3343 			linger_reg_commit_complete(lreq, -ENOENT);
3344 			__linger_cancel(lreq);
3345 		}
3346 	} else {
3347 		send_linger_map_check(lreq);
3348 	}
3349 }
3350 
3351 static void linger_map_check_cb(struct ceph_mon_generic_request *greq)
3352 {
3353 	struct ceph_osd_client *osdc = &greq->monc->client->osdc;
3354 	struct ceph_osd_linger_request *lreq;
3355 	u64 linger_id = greq->private_data;
3356 
3357 	WARN_ON(greq->result || !greq->u.newest);
3358 
3359 	down_write(&osdc->lock);
3360 	lreq = lookup_linger_mc(&osdc->linger_map_checks, linger_id);
3361 	if (!lreq) {
3362 		dout("%s linger_id %llu dne\n", __func__, linger_id);
3363 		goto out_unlock;
3364 	}
3365 
3366 	dout("%s lreq %p linger_id %llu map_dne_bound %u newest %llu\n",
3367 	     __func__, lreq, lreq->linger_id, lreq->map_dne_bound,
3368 	     greq->u.newest);
3369 	if (!lreq->map_dne_bound)
3370 		lreq->map_dne_bound = greq->u.newest;
3371 	erase_linger_mc(&osdc->linger_map_checks, lreq);
3372 	check_linger_pool_dne(lreq);
3373 
3374 	linger_put(lreq);
3375 out_unlock:
3376 	up_write(&osdc->lock);
3377 }
3378 
3379 static void send_linger_map_check(struct ceph_osd_linger_request *lreq)
3380 {
3381 	struct ceph_osd_client *osdc = lreq->osdc;
3382 	struct ceph_osd_linger_request *lookup_lreq;
3383 	int ret;
3384 
3385 	verify_osdc_wrlocked(osdc);
3386 
3387 	lookup_lreq = lookup_linger_mc(&osdc->linger_map_checks,
3388 				       lreq->linger_id);
3389 	if (lookup_lreq) {
3390 		WARN_ON(lookup_lreq != lreq);
3391 		return;
3392 	}
3393 
3394 	linger_get(lreq);
3395 	insert_linger_mc(&osdc->linger_map_checks, lreq);
3396 	ret = ceph_monc_get_version_async(&osdc->client->monc, "osdmap",
3397 					  linger_map_check_cb, lreq->linger_id);
3398 	WARN_ON(ret);
3399 }
3400 
3401 static int linger_reg_commit_wait(struct ceph_osd_linger_request *lreq)
3402 {
3403 	int ret;
3404 
3405 	dout("%s lreq %p linger_id %llu\n", __func__, lreq, lreq->linger_id);
3406 	ret = wait_for_completion_killable(&lreq->reg_commit_wait);
3407 	return ret ?: lreq->reg_commit_error;
3408 }
3409 
3410 static int linger_notify_finish_wait(struct ceph_osd_linger_request *lreq,
3411 				     unsigned long timeout)
3412 {
3413 	long left;
3414 
3415 	dout("%s lreq %p linger_id %llu\n", __func__, lreq, lreq->linger_id);
3416 	left = wait_for_completion_killable_timeout(&lreq->notify_finish_wait,
3417 						ceph_timeout_jiffies(timeout));
3418 	if (left <= 0)
3419 		left = left ?: -ETIMEDOUT;
3420 	else
3421 		left = lreq->notify_finish_error; /* completed */
3422 
3423 	return left;
3424 }
3425 
3426 /*
3427  * Timeout callback, called every N seconds.  When 1 or more OSD
3428  * requests has been active for more than N seconds, we send a keepalive
3429  * (tag + timestamp) to its OSD to ensure any communications channel
3430  * reset is detected.
3431  */
3432 static void handle_timeout(struct work_struct *work)
3433 {
3434 	struct ceph_osd_client *osdc =
3435 		container_of(work, struct ceph_osd_client, timeout_work.work);
3436 	struct ceph_options *opts = osdc->client->options;
3437 	unsigned long cutoff = jiffies - opts->osd_keepalive_timeout;
3438 	unsigned long expiry_cutoff = jiffies - opts->osd_request_timeout;
3439 	LIST_HEAD(slow_osds);
3440 	struct rb_node *n, *p;
3441 
3442 	dout("%s osdc %p\n", __func__, osdc);
3443 	down_write(&osdc->lock);
3444 
3445 	/*
3446 	 * ping osds that are a bit slow.  this ensures that if there
3447 	 * is a break in the TCP connection we will notice, and reopen
3448 	 * a connection with that osd (from the fault callback).
3449 	 */
3450 	for (n = rb_first(&osdc->osds); n; n = rb_next(n)) {
3451 		struct ceph_osd *osd = rb_entry(n, struct ceph_osd, o_node);
3452 		bool found = false;
3453 
3454 		for (p = rb_first(&osd->o_requests); p; ) {
3455 			struct ceph_osd_request *req =
3456 			    rb_entry(p, struct ceph_osd_request, r_node);
3457 
3458 			p = rb_next(p); /* abort_request() */
3459 
3460 			if (time_before(req->r_stamp, cutoff)) {
3461 				dout(" req %p tid %llu on osd%d is laggy\n",
3462 				     req, req->r_tid, osd->o_osd);
3463 				found = true;
3464 			}
3465 			if (opts->osd_request_timeout &&
3466 			    time_before(req->r_start_stamp, expiry_cutoff)) {
3467 				pr_err_ratelimited("tid %llu on osd%d timeout\n",
3468 				       req->r_tid, osd->o_osd);
3469 				abort_request(req, -ETIMEDOUT);
3470 			}
3471 		}
3472 		for (p = rb_first(&osd->o_linger_requests); p; p = rb_next(p)) {
3473 			struct ceph_osd_linger_request *lreq =
3474 			    rb_entry(p, struct ceph_osd_linger_request, node);
3475 
3476 			dout(" lreq %p linger_id %llu is served by osd%d\n",
3477 			     lreq, lreq->linger_id, osd->o_osd);
3478 			found = true;
3479 
3480 			mutex_lock(&lreq->lock);
3481 			if (lreq->is_watch && lreq->committed && !lreq->last_error)
3482 				send_linger_ping(lreq);
3483 			mutex_unlock(&lreq->lock);
3484 		}
3485 
3486 		if (found)
3487 			list_move_tail(&osd->o_keepalive_item, &slow_osds);
3488 	}
3489 
3490 	if (opts->osd_request_timeout) {
3491 		for (p = rb_first(&osdc->homeless_osd.o_requests); p; ) {
3492 			struct ceph_osd_request *req =
3493 			    rb_entry(p, struct ceph_osd_request, r_node);
3494 
3495 			p = rb_next(p); /* abort_request() */
3496 
3497 			if (time_before(req->r_start_stamp, expiry_cutoff)) {
3498 				pr_err_ratelimited("tid %llu on osd%d timeout\n",
3499 				       req->r_tid, osdc->homeless_osd.o_osd);
3500 				abort_request(req, -ETIMEDOUT);
3501 			}
3502 		}
3503 	}
3504 
3505 	if (atomic_read(&osdc->num_homeless) || !list_empty(&slow_osds))
3506 		maybe_request_map(osdc);
3507 
3508 	while (!list_empty(&slow_osds)) {
3509 		struct ceph_osd *osd = list_first_entry(&slow_osds,
3510 							struct ceph_osd,
3511 							o_keepalive_item);
3512 		list_del_init(&osd->o_keepalive_item);
3513 		ceph_con_keepalive(&osd->o_con);
3514 	}
3515 
3516 	up_write(&osdc->lock);
3517 	schedule_delayed_work(&osdc->timeout_work,
3518 			      osdc->client->options->osd_keepalive_timeout);
3519 }
3520 
3521 static void handle_osds_timeout(struct work_struct *work)
3522 {
3523 	struct ceph_osd_client *osdc =
3524 		container_of(work, struct ceph_osd_client,
3525 			     osds_timeout_work.work);
3526 	unsigned long delay = osdc->client->options->osd_idle_ttl / 4;
3527 	struct ceph_osd *osd, *nosd;
3528 
3529 	dout("%s osdc %p\n", __func__, osdc);
3530 	down_write(&osdc->lock);
3531 	list_for_each_entry_safe(osd, nosd, &osdc->osd_lru, o_osd_lru) {
3532 		if (time_before(jiffies, osd->lru_ttl))
3533 			break;
3534 
3535 		WARN_ON(!RB_EMPTY_ROOT(&osd->o_requests));
3536 		WARN_ON(!RB_EMPTY_ROOT(&osd->o_linger_requests));
3537 		close_osd(osd);
3538 	}
3539 
3540 	up_write(&osdc->lock);
3541 	schedule_delayed_work(&osdc->osds_timeout_work,
3542 			      round_jiffies_relative(delay));
3543 }
3544 
3545 static int ceph_oloc_decode(void **p, void *end,
3546 			    struct ceph_object_locator *oloc)
3547 {
3548 	u8 struct_v, struct_cv;
3549 	u32 len;
3550 	void *struct_end;
3551 	int ret = 0;
3552 
3553 	ceph_decode_need(p, end, 1 + 1 + 4, e_inval);
3554 	struct_v = ceph_decode_8(p);
3555 	struct_cv = ceph_decode_8(p);
3556 	if (struct_v < 3) {
3557 		pr_warn("got v %d < 3 cv %d of ceph_object_locator\n",
3558 			struct_v, struct_cv);
3559 		goto e_inval;
3560 	}
3561 	if (struct_cv > 6) {
3562 		pr_warn("got v %d cv %d > 6 of ceph_object_locator\n",
3563 			struct_v, struct_cv);
3564 		goto e_inval;
3565 	}
3566 	len = ceph_decode_32(p);
3567 	ceph_decode_need(p, end, len, e_inval);
3568 	struct_end = *p + len;
3569 
3570 	ceph_decode_need(p, end, 8 + 4 + 4, e_inval);
3571 	oloc->pool = ceph_decode_64(p);
3572 	*p += 4; /* skip preferred */
3573 
3574 	len = ceph_decode_32(p);
3575 	if (len > 0) {
3576 		pr_warn("ceph_object_locator::key is set\n");
3577 		goto e_inval;
3578 	}
3579 
3580 	if (struct_v >= 5) {
3581 		bool changed = false;
3582 
3583 		ceph_decode_32_safe(p, end, len, e_inval);
3584 		if (len > 0) {
3585 			ceph_decode_need(p, end, len, e_inval);
3586 			if (!oloc->pool_ns ||
3587 			    ceph_compare_string(oloc->pool_ns, *p, len))
3588 				changed = true;
3589 			*p += len;
3590 		} else {
3591 			if (oloc->pool_ns)
3592 				changed = true;
3593 		}
3594 		if (changed) {
3595 			/* redirect changes namespace */
3596 			pr_warn("ceph_object_locator::nspace is changed\n");
3597 			goto e_inval;
3598 		}
3599 	}
3600 
3601 	if (struct_v >= 6) {
3602 		s64 hash;
3603 
3604 		ceph_decode_64_safe(p, end, hash, e_inval);
3605 		if (hash != -1) {
3606 			pr_warn("ceph_object_locator::hash is set\n");
3607 			goto e_inval;
3608 		}
3609 	}
3610 
3611 	/* skip the rest */
3612 	*p = struct_end;
3613 out:
3614 	return ret;
3615 
3616 e_inval:
3617 	ret = -EINVAL;
3618 	goto out;
3619 }
3620 
3621 static int ceph_redirect_decode(void **p, void *end,
3622 				struct ceph_request_redirect *redir)
3623 {
3624 	u8 struct_v, struct_cv;
3625 	u32 len;
3626 	void *struct_end;
3627 	int ret;
3628 
3629 	ceph_decode_need(p, end, 1 + 1 + 4, e_inval);
3630 	struct_v = ceph_decode_8(p);
3631 	struct_cv = ceph_decode_8(p);
3632 	if (struct_cv > 1) {
3633 		pr_warn("got v %d cv %d > 1 of ceph_request_redirect\n",
3634 			struct_v, struct_cv);
3635 		goto e_inval;
3636 	}
3637 	len = ceph_decode_32(p);
3638 	ceph_decode_need(p, end, len, e_inval);
3639 	struct_end = *p + len;
3640 
3641 	ret = ceph_oloc_decode(p, end, &redir->oloc);
3642 	if (ret)
3643 		goto out;
3644 
3645 	ceph_decode_32_safe(p, end, len, e_inval);
3646 	if (len > 0) {
3647 		pr_warn("ceph_request_redirect::object_name is set\n");
3648 		goto e_inval;
3649 	}
3650 
3651 	/* skip the rest */
3652 	*p = struct_end;
3653 out:
3654 	return ret;
3655 
3656 e_inval:
3657 	ret = -EINVAL;
3658 	goto out;
3659 }
3660 
3661 struct MOSDOpReply {
3662 	struct ceph_pg pgid;
3663 	u64 flags;
3664 	int result;
3665 	u32 epoch;
3666 	int num_ops;
3667 	u32 outdata_len[CEPH_OSD_MAX_OPS];
3668 	s32 rval[CEPH_OSD_MAX_OPS];
3669 	int retry_attempt;
3670 	struct ceph_eversion replay_version;
3671 	u64 user_version;
3672 	struct ceph_request_redirect redirect;
3673 };
3674 
3675 static int decode_MOSDOpReply(const struct ceph_msg *msg, struct MOSDOpReply *m)
3676 {
3677 	void *p = msg->front.iov_base;
3678 	void *const end = p + msg->front.iov_len;
3679 	u16 version = le16_to_cpu(msg->hdr.version);
3680 	struct ceph_eversion bad_replay_version;
3681 	u8 decode_redir;
3682 	u32 len;
3683 	int ret;
3684 	int i;
3685 
3686 	ceph_decode_32_safe(&p, end, len, e_inval);
3687 	ceph_decode_need(&p, end, len, e_inval);
3688 	p += len; /* skip oid */
3689 
3690 	ret = ceph_decode_pgid(&p, end, &m->pgid);
3691 	if (ret)
3692 		return ret;
3693 
3694 	ceph_decode_64_safe(&p, end, m->flags, e_inval);
3695 	ceph_decode_32_safe(&p, end, m->result, e_inval);
3696 	ceph_decode_need(&p, end, sizeof(bad_replay_version), e_inval);
3697 	memcpy(&bad_replay_version, p, sizeof(bad_replay_version));
3698 	p += sizeof(bad_replay_version);
3699 	ceph_decode_32_safe(&p, end, m->epoch, e_inval);
3700 
3701 	ceph_decode_32_safe(&p, end, m->num_ops, e_inval);
3702 	if (m->num_ops > ARRAY_SIZE(m->outdata_len))
3703 		goto e_inval;
3704 
3705 	ceph_decode_need(&p, end, m->num_ops * sizeof(struct ceph_osd_op),
3706 			 e_inval);
3707 	for (i = 0; i < m->num_ops; i++) {
3708 		struct ceph_osd_op *op = p;
3709 
3710 		m->outdata_len[i] = le32_to_cpu(op->payload_len);
3711 		p += sizeof(*op);
3712 	}
3713 
3714 	ceph_decode_32_safe(&p, end, m->retry_attempt, e_inval);
3715 	for (i = 0; i < m->num_ops; i++)
3716 		ceph_decode_32_safe(&p, end, m->rval[i], e_inval);
3717 
3718 	if (version >= 5) {
3719 		ceph_decode_need(&p, end, sizeof(m->replay_version), e_inval);
3720 		memcpy(&m->replay_version, p, sizeof(m->replay_version));
3721 		p += sizeof(m->replay_version);
3722 		ceph_decode_64_safe(&p, end, m->user_version, e_inval);
3723 	} else {
3724 		m->replay_version = bad_replay_version; /* struct */
3725 		m->user_version = le64_to_cpu(m->replay_version.version);
3726 	}
3727 
3728 	if (version >= 6) {
3729 		if (version >= 7)
3730 			ceph_decode_8_safe(&p, end, decode_redir, e_inval);
3731 		else
3732 			decode_redir = 1;
3733 	} else {
3734 		decode_redir = 0;
3735 	}
3736 
3737 	if (decode_redir) {
3738 		ret = ceph_redirect_decode(&p, end, &m->redirect);
3739 		if (ret)
3740 			return ret;
3741 	} else {
3742 		ceph_oloc_init(&m->redirect.oloc);
3743 	}
3744 
3745 	return 0;
3746 
3747 e_inval:
3748 	return -EINVAL;
3749 }
3750 
3751 /*
3752  * Handle MOSDOpReply.  Set ->r_result and call the callback if it is
3753  * specified.
3754  */
3755 static void handle_reply(struct ceph_osd *osd, struct ceph_msg *msg)
3756 {
3757 	struct ceph_osd_client *osdc = osd->o_osdc;
3758 	struct ceph_osd_request *req;
3759 	struct MOSDOpReply m;
3760 	u64 tid = le64_to_cpu(msg->hdr.tid);
3761 	u32 data_len = 0;
3762 	int ret;
3763 	int i;
3764 
3765 	dout("%s msg %p tid %llu\n", __func__, msg, tid);
3766 
3767 	down_read(&osdc->lock);
3768 	if (!osd_registered(osd)) {
3769 		dout("%s osd%d unknown\n", __func__, osd->o_osd);
3770 		goto out_unlock_osdc;
3771 	}
3772 	WARN_ON(osd->o_osd != le64_to_cpu(msg->hdr.src.num));
3773 
3774 	mutex_lock(&osd->lock);
3775 	req = lookup_request(&osd->o_requests, tid);
3776 	if (!req) {
3777 		dout("%s osd%d tid %llu unknown\n", __func__, osd->o_osd, tid);
3778 		goto out_unlock_session;
3779 	}
3780 
3781 	m.redirect.oloc.pool_ns = req->r_t.target_oloc.pool_ns;
3782 	ret = decode_MOSDOpReply(msg, &m);
3783 	m.redirect.oloc.pool_ns = NULL;
3784 	if (ret) {
3785 		pr_err("failed to decode MOSDOpReply for tid %llu: %d\n",
3786 		       req->r_tid, ret);
3787 		ceph_msg_dump(msg);
3788 		goto fail_request;
3789 	}
3790 	dout("%s req %p tid %llu flags 0x%llx pgid %llu.%x epoch %u attempt %d v %u'%llu uv %llu\n",
3791 	     __func__, req, req->r_tid, m.flags, m.pgid.pool, m.pgid.seed,
3792 	     m.epoch, m.retry_attempt, le32_to_cpu(m.replay_version.epoch),
3793 	     le64_to_cpu(m.replay_version.version), m.user_version);
3794 
3795 	if (m.retry_attempt >= 0) {
3796 		if (m.retry_attempt != req->r_attempts - 1) {
3797 			dout("req %p tid %llu retry_attempt %d != %d, ignoring\n",
3798 			     req, req->r_tid, m.retry_attempt,
3799 			     req->r_attempts - 1);
3800 			goto out_unlock_session;
3801 		}
3802 	} else {
3803 		WARN_ON(1); /* MOSDOpReply v4 is assumed */
3804 	}
3805 
3806 	if (!ceph_oloc_empty(&m.redirect.oloc)) {
3807 		dout("req %p tid %llu redirect pool %lld\n", req, req->r_tid,
3808 		     m.redirect.oloc.pool);
3809 		unlink_request(osd, req);
3810 		mutex_unlock(&osd->lock);
3811 
3812 		/*
3813 		 * Not ceph_oloc_copy() - changing pool_ns is not
3814 		 * supported.
3815 		 */
3816 		req->r_t.target_oloc.pool = m.redirect.oloc.pool;
3817 		req->r_flags |= CEPH_OSD_FLAG_REDIRECTED |
3818 				CEPH_OSD_FLAG_IGNORE_OVERLAY |
3819 				CEPH_OSD_FLAG_IGNORE_CACHE;
3820 		req->r_tid = 0;
3821 		__submit_request(req, false);
3822 		goto out_unlock_osdc;
3823 	}
3824 
3825 	if (m.result == -EAGAIN) {
3826 		dout("req %p tid %llu EAGAIN\n", req, req->r_tid);
3827 		unlink_request(osd, req);
3828 		mutex_unlock(&osd->lock);
3829 
3830 		/*
3831 		 * The object is missing on the replica or not (yet)
3832 		 * readable.  Clear pgid to force a resend to the primary
3833 		 * via legacy_change.
3834 		 */
3835 		req->r_t.pgid.pool = 0;
3836 		req->r_t.pgid.seed = 0;
3837 		WARN_ON(!req->r_t.used_replica);
3838 		req->r_flags &= ~(CEPH_OSD_FLAG_BALANCE_READS |
3839 				  CEPH_OSD_FLAG_LOCALIZE_READS);
3840 		req->r_tid = 0;
3841 		__submit_request(req, false);
3842 		goto out_unlock_osdc;
3843 	}
3844 
3845 	if (m.num_ops != req->r_num_ops) {
3846 		pr_err("num_ops %d != %d for tid %llu\n", m.num_ops,
3847 		       req->r_num_ops, req->r_tid);
3848 		goto fail_request;
3849 	}
3850 	for (i = 0; i < req->r_num_ops; i++) {
3851 		dout(" req %p tid %llu op %d rval %d len %u\n", req,
3852 		     req->r_tid, i, m.rval[i], m.outdata_len[i]);
3853 		req->r_ops[i].rval = m.rval[i];
3854 		req->r_ops[i].outdata_len = m.outdata_len[i];
3855 		data_len += m.outdata_len[i];
3856 	}
3857 	if (data_len != le32_to_cpu(msg->hdr.data_len)) {
3858 		pr_err("sum of lens %u != %u for tid %llu\n", data_len,
3859 		       le32_to_cpu(msg->hdr.data_len), req->r_tid);
3860 		goto fail_request;
3861 	}
3862 	dout("%s req %p tid %llu result %d data_len %u\n", __func__,
3863 	     req, req->r_tid, m.result, data_len);
3864 
3865 	/*
3866 	 * Since we only ever request ONDISK, we should only ever get
3867 	 * one (type of) reply back.
3868 	 */
3869 	WARN_ON(!(m.flags & CEPH_OSD_FLAG_ONDISK));
3870 	req->r_version = m.user_version;
3871 	req->r_result = m.result ?: data_len;
3872 	finish_request(req);
3873 	mutex_unlock(&osd->lock);
3874 	up_read(&osdc->lock);
3875 
3876 	__complete_request(req);
3877 	return;
3878 
3879 fail_request:
3880 	complete_request(req, -EIO);
3881 out_unlock_session:
3882 	mutex_unlock(&osd->lock);
3883 out_unlock_osdc:
3884 	up_read(&osdc->lock);
3885 }
3886 
3887 static void set_pool_was_full(struct ceph_osd_client *osdc)
3888 {
3889 	struct rb_node *n;
3890 
3891 	for (n = rb_first(&osdc->osdmap->pg_pools); n; n = rb_next(n)) {
3892 		struct ceph_pg_pool_info *pi =
3893 		    rb_entry(n, struct ceph_pg_pool_info, node);
3894 
3895 		pi->was_full = __pool_full(pi);
3896 	}
3897 }
3898 
3899 static bool pool_cleared_full(struct ceph_osd_client *osdc, s64 pool_id)
3900 {
3901 	struct ceph_pg_pool_info *pi;
3902 
3903 	pi = ceph_pg_pool_by_id(osdc->osdmap, pool_id);
3904 	if (!pi)
3905 		return false;
3906 
3907 	return pi->was_full && !__pool_full(pi);
3908 }
3909 
3910 static enum calc_target_result
3911 recalc_linger_target(struct ceph_osd_linger_request *lreq)
3912 {
3913 	struct ceph_osd_client *osdc = lreq->osdc;
3914 	enum calc_target_result ct_res;
3915 
3916 	ct_res = calc_target(osdc, &lreq->t, true);
3917 	if (ct_res == CALC_TARGET_NEED_RESEND) {
3918 		struct ceph_osd *osd;
3919 
3920 		osd = lookup_create_osd(osdc, lreq->t.osd, true);
3921 		if (osd != lreq->osd) {
3922 			unlink_linger(lreq->osd, lreq);
3923 			link_linger(osd, lreq);
3924 		}
3925 	}
3926 
3927 	return ct_res;
3928 }
3929 
3930 /*
3931  * Requeue requests whose mapping to an OSD has changed.
3932  */
3933 static void scan_requests(struct ceph_osd *osd,
3934 			  bool force_resend,
3935 			  bool cleared_full,
3936 			  bool check_pool_cleared_full,
3937 			  struct rb_root *need_resend,
3938 			  struct list_head *need_resend_linger)
3939 {
3940 	struct ceph_osd_client *osdc = osd->o_osdc;
3941 	struct rb_node *n;
3942 	bool force_resend_writes;
3943 
3944 	for (n = rb_first(&osd->o_linger_requests); n; ) {
3945 		struct ceph_osd_linger_request *lreq =
3946 		    rb_entry(n, struct ceph_osd_linger_request, node);
3947 		enum calc_target_result ct_res;
3948 
3949 		n = rb_next(n); /* recalc_linger_target() */
3950 
3951 		dout("%s lreq %p linger_id %llu\n", __func__, lreq,
3952 		     lreq->linger_id);
3953 		ct_res = recalc_linger_target(lreq);
3954 		switch (ct_res) {
3955 		case CALC_TARGET_NO_ACTION:
3956 			force_resend_writes = cleared_full ||
3957 			    (check_pool_cleared_full &&
3958 			     pool_cleared_full(osdc, lreq->t.base_oloc.pool));
3959 			if (!force_resend && !force_resend_writes)
3960 				break;
3961 
3962 			fallthrough;
3963 		case CALC_TARGET_NEED_RESEND:
3964 			cancel_linger_map_check(lreq);
3965 			/*
3966 			 * scan_requests() for the previous epoch(s)
3967 			 * may have already added it to the list, since
3968 			 * it's not unlinked here.
3969 			 */
3970 			if (list_empty(&lreq->scan_item))
3971 				list_add_tail(&lreq->scan_item, need_resend_linger);
3972 			break;
3973 		case CALC_TARGET_POOL_DNE:
3974 			list_del_init(&lreq->scan_item);
3975 			check_linger_pool_dne(lreq);
3976 			break;
3977 		}
3978 	}
3979 
3980 	for (n = rb_first(&osd->o_requests); n; ) {
3981 		struct ceph_osd_request *req =
3982 		    rb_entry(n, struct ceph_osd_request, r_node);
3983 		enum calc_target_result ct_res;
3984 
3985 		n = rb_next(n); /* unlink_request(), check_pool_dne() */
3986 
3987 		dout("%s req %p tid %llu\n", __func__, req, req->r_tid);
3988 		ct_res = calc_target(osdc, &req->r_t, false);
3989 		switch (ct_res) {
3990 		case CALC_TARGET_NO_ACTION:
3991 			force_resend_writes = cleared_full ||
3992 			    (check_pool_cleared_full &&
3993 			     pool_cleared_full(osdc, req->r_t.base_oloc.pool));
3994 			if (!force_resend &&
3995 			    (!(req->r_flags & CEPH_OSD_FLAG_WRITE) ||
3996 			     !force_resend_writes))
3997 				break;
3998 
3999 			fallthrough;
4000 		case CALC_TARGET_NEED_RESEND:
4001 			cancel_map_check(req);
4002 			unlink_request(osd, req);
4003 			insert_request(need_resend, req);
4004 			break;
4005 		case CALC_TARGET_POOL_DNE:
4006 			check_pool_dne(req);
4007 			break;
4008 		}
4009 	}
4010 }
4011 
4012 static int handle_one_map(struct ceph_osd_client *osdc,
4013 			  void *p, void *end, bool incremental,
4014 			  struct rb_root *need_resend,
4015 			  struct list_head *need_resend_linger)
4016 {
4017 	struct ceph_osdmap *newmap;
4018 	struct rb_node *n;
4019 	bool skipped_map = false;
4020 	bool was_full;
4021 
4022 	was_full = ceph_osdmap_flag(osdc, CEPH_OSDMAP_FULL);
4023 	set_pool_was_full(osdc);
4024 
4025 	if (incremental)
4026 		newmap = osdmap_apply_incremental(&p, end,
4027 						  ceph_msgr2(osdc->client),
4028 						  osdc->osdmap);
4029 	else
4030 		newmap = ceph_osdmap_decode(&p, end, ceph_msgr2(osdc->client));
4031 	if (IS_ERR(newmap))
4032 		return PTR_ERR(newmap);
4033 
4034 	if (newmap != osdc->osdmap) {
4035 		/*
4036 		 * Preserve ->was_full before destroying the old map.
4037 		 * For pools that weren't in the old map, ->was_full
4038 		 * should be false.
4039 		 */
4040 		for (n = rb_first(&newmap->pg_pools); n; n = rb_next(n)) {
4041 			struct ceph_pg_pool_info *pi =
4042 			    rb_entry(n, struct ceph_pg_pool_info, node);
4043 			struct ceph_pg_pool_info *old_pi;
4044 
4045 			old_pi = ceph_pg_pool_by_id(osdc->osdmap, pi->id);
4046 			if (old_pi)
4047 				pi->was_full = old_pi->was_full;
4048 			else
4049 				WARN_ON(pi->was_full);
4050 		}
4051 
4052 		if (osdc->osdmap->epoch &&
4053 		    osdc->osdmap->epoch + 1 < newmap->epoch) {
4054 			WARN_ON(incremental);
4055 			skipped_map = true;
4056 		}
4057 
4058 		ceph_osdmap_destroy(osdc->osdmap);
4059 		osdc->osdmap = newmap;
4060 	}
4061 
4062 	was_full &= !ceph_osdmap_flag(osdc, CEPH_OSDMAP_FULL);
4063 	scan_requests(&osdc->homeless_osd, skipped_map, was_full, true,
4064 		      need_resend, need_resend_linger);
4065 
4066 	for (n = rb_first(&osdc->osds); n; ) {
4067 		struct ceph_osd *osd = rb_entry(n, struct ceph_osd, o_node);
4068 
4069 		n = rb_next(n); /* close_osd() */
4070 
4071 		scan_requests(osd, skipped_map, was_full, true, need_resend,
4072 			      need_resend_linger);
4073 		if (!ceph_osd_is_up(osdc->osdmap, osd->o_osd) ||
4074 		    memcmp(&osd->o_con.peer_addr,
4075 			   ceph_osd_addr(osdc->osdmap, osd->o_osd),
4076 			   sizeof(struct ceph_entity_addr)))
4077 			close_osd(osd);
4078 	}
4079 
4080 	return 0;
4081 }
4082 
4083 static void kick_requests(struct ceph_osd_client *osdc,
4084 			  struct rb_root *need_resend,
4085 			  struct list_head *need_resend_linger)
4086 {
4087 	struct ceph_osd_linger_request *lreq, *nlreq;
4088 	enum calc_target_result ct_res;
4089 	struct rb_node *n;
4090 
4091 	/* make sure need_resend targets reflect latest map */
4092 	for (n = rb_first(need_resend); n; ) {
4093 		struct ceph_osd_request *req =
4094 		    rb_entry(n, struct ceph_osd_request, r_node);
4095 
4096 		n = rb_next(n);
4097 
4098 		if (req->r_t.epoch < osdc->osdmap->epoch) {
4099 			ct_res = calc_target(osdc, &req->r_t, false);
4100 			if (ct_res == CALC_TARGET_POOL_DNE) {
4101 				erase_request(need_resend, req);
4102 				check_pool_dne(req);
4103 			}
4104 		}
4105 	}
4106 
4107 	for (n = rb_first(need_resend); n; ) {
4108 		struct ceph_osd_request *req =
4109 		    rb_entry(n, struct ceph_osd_request, r_node);
4110 		struct ceph_osd *osd;
4111 
4112 		n = rb_next(n);
4113 		erase_request(need_resend, req); /* before link_request() */
4114 
4115 		osd = lookup_create_osd(osdc, req->r_t.osd, true);
4116 		link_request(osd, req);
4117 		if (!req->r_linger) {
4118 			if (!osd_homeless(osd) && !req->r_t.paused)
4119 				send_request(req);
4120 		} else {
4121 			cancel_linger_request(req);
4122 		}
4123 	}
4124 
4125 	list_for_each_entry_safe(lreq, nlreq, need_resend_linger, scan_item) {
4126 		if (!osd_homeless(lreq->osd))
4127 			send_linger(lreq);
4128 
4129 		list_del_init(&lreq->scan_item);
4130 	}
4131 }
4132 
4133 /*
4134  * Process updated osd map.
4135  *
4136  * The message contains any number of incremental and full maps, normally
4137  * indicating some sort of topology change in the cluster.  Kick requests
4138  * off to different OSDs as needed.
4139  */
4140 void ceph_osdc_handle_map(struct ceph_osd_client *osdc, struct ceph_msg *msg)
4141 {
4142 	void *p = msg->front.iov_base;
4143 	void *const end = p + msg->front.iov_len;
4144 	u32 nr_maps, maplen;
4145 	u32 epoch;
4146 	struct ceph_fsid fsid;
4147 	struct rb_root need_resend = RB_ROOT;
4148 	LIST_HEAD(need_resend_linger);
4149 	bool handled_incremental = false;
4150 	bool was_pauserd, was_pausewr;
4151 	bool pauserd, pausewr;
4152 	int err;
4153 
4154 	dout("%s have %u\n", __func__, osdc->osdmap->epoch);
4155 	down_write(&osdc->lock);
4156 
4157 	/* verify fsid */
4158 	ceph_decode_need(&p, end, sizeof(fsid), bad);
4159 	ceph_decode_copy(&p, &fsid, sizeof(fsid));
4160 	if (ceph_check_fsid(osdc->client, &fsid) < 0)
4161 		goto bad;
4162 
4163 	was_pauserd = ceph_osdmap_flag(osdc, CEPH_OSDMAP_PAUSERD);
4164 	was_pausewr = ceph_osdmap_flag(osdc, CEPH_OSDMAP_PAUSEWR) ||
4165 		      ceph_osdmap_flag(osdc, CEPH_OSDMAP_FULL) ||
4166 		      have_pool_full(osdc);
4167 
4168 	/* incremental maps */
4169 	ceph_decode_32_safe(&p, end, nr_maps, bad);
4170 	dout(" %d inc maps\n", nr_maps);
4171 	while (nr_maps > 0) {
4172 		ceph_decode_need(&p, end, 2*sizeof(u32), bad);
4173 		epoch = ceph_decode_32(&p);
4174 		maplen = ceph_decode_32(&p);
4175 		ceph_decode_need(&p, end, maplen, bad);
4176 		if (osdc->osdmap->epoch &&
4177 		    osdc->osdmap->epoch + 1 == epoch) {
4178 			dout("applying incremental map %u len %d\n",
4179 			     epoch, maplen);
4180 			err = handle_one_map(osdc, p, p + maplen, true,
4181 					     &need_resend, &need_resend_linger);
4182 			if (err)
4183 				goto bad;
4184 			handled_incremental = true;
4185 		} else {
4186 			dout("ignoring incremental map %u len %d\n",
4187 			     epoch, maplen);
4188 		}
4189 		p += maplen;
4190 		nr_maps--;
4191 	}
4192 	if (handled_incremental)
4193 		goto done;
4194 
4195 	/* full maps */
4196 	ceph_decode_32_safe(&p, end, nr_maps, bad);
4197 	dout(" %d full maps\n", nr_maps);
4198 	while (nr_maps) {
4199 		ceph_decode_need(&p, end, 2*sizeof(u32), bad);
4200 		epoch = ceph_decode_32(&p);
4201 		maplen = ceph_decode_32(&p);
4202 		ceph_decode_need(&p, end, maplen, bad);
4203 		if (nr_maps > 1) {
4204 			dout("skipping non-latest full map %u len %d\n",
4205 			     epoch, maplen);
4206 		} else if (osdc->osdmap->epoch >= epoch) {
4207 			dout("skipping full map %u len %d, "
4208 			     "older than our %u\n", epoch, maplen,
4209 			     osdc->osdmap->epoch);
4210 		} else {
4211 			dout("taking full map %u len %d\n", epoch, maplen);
4212 			err = handle_one_map(osdc, p, p + maplen, false,
4213 					     &need_resend, &need_resend_linger);
4214 			if (err)
4215 				goto bad;
4216 		}
4217 		p += maplen;
4218 		nr_maps--;
4219 	}
4220 
4221 done:
4222 	/*
4223 	 * subscribe to subsequent osdmap updates if full to ensure
4224 	 * we find out when we are no longer full and stop returning
4225 	 * ENOSPC.
4226 	 */
4227 	pauserd = ceph_osdmap_flag(osdc, CEPH_OSDMAP_PAUSERD);
4228 	pausewr = ceph_osdmap_flag(osdc, CEPH_OSDMAP_PAUSEWR) ||
4229 		  ceph_osdmap_flag(osdc, CEPH_OSDMAP_FULL) ||
4230 		  have_pool_full(osdc);
4231 	if (was_pauserd || was_pausewr || pauserd || pausewr ||
4232 	    osdc->osdmap->epoch < osdc->epoch_barrier)
4233 		maybe_request_map(osdc);
4234 
4235 	kick_requests(osdc, &need_resend, &need_resend_linger);
4236 
4237 	ceph_osdc_abort_on_full(osdc);
4238 	ceph_monc_got_map(&osdc->client->monc, CEPH_SUB_OSDMAP,
4239 			  osdc->osdmap->epoch);
4240 	up_write(&osdc->lock);
4241 	wake_up_all(&osdc->client->auth_wq);
4242 	return;
4243 
4244 bad:
4245 	pr_err("osdc handle_map corrupt msg\n");
4246 	ceph_msg_dump(msg);
4247 	up_write(&osdc->lock);
4248 }
4249 
4250 /*
4251  * Resubmit requests pending on the given osd.
4252  */
4253 static void kick_osd_requests(struct ceph_osd *osd)
4254 {
4255 	struct rb_node *n;
4256 
4257 	clear_backoffs(osd);
4258 
4259 	for (n = rb_first(&osd->o_requests); n; ) {
4260 		struct ceph_osd_request *req =
4261 		    rb_entry(n, struct ceph_osd_request, r_node);
4262 
4263 		n = rb_next(n); /* cancel_linger_request() */
4264 
4265 		if (!req->r_linger) {
4266 			if (!req->r_t.paused)
4267 				send_request(req);
4268 		} else {
4269 			cancel_linger_request(req);
4270 		}
4271 	}
4272 	for (n = rb_first(&osd->o_linger_requests); n; n = rb_next(n)) {
4273 		struct ceph_osd_linger_request *lreq =
4274 		    rb_entry(n, struct ceph_osd_linger_request, node);
4275 
4276 		send_linger(lreq);
4277 	}
4278 }
4279 
4280 /*
4281  * If the osd connection drops, we need to resubmit all requests.
4282  */
4283 static void osd_fault(struct ceph_connection *con)
4284 {
4285 	struct ceph_osd *osd = con->private;
4286 	struct ceph_osd_client *osdc = osd->o_osdc;
4287 
4288 	dout("%s osd %p osd%d\n", __func__, osd, osd->o_osd);
4289 
4290 	down_write(&osdc->lock);
4291 	if (!osd_registered(osd)) {
4292 		dout("%s osd%d unknown\n", __func__, osd->o_osd);
4293 		goto out_unlock;
4294 	}
4295 
4296 	osd->o_sparse_op_idx = -1;
4297 	ceph_init_sparse_read(&osd->o_sparse_read);
4298 
4299 	if (!reopen_osd(osd))
4300 		kick_osd_requests(osd);
4301 	maybe_request_map(osdc);
4302 
4303 out_unlock:
4304 	up_write(&osdc->lock);
4305 }
4306 
4307 struct MOSDBackoff {
4308 	struct ceph_spg spgid;
4309 	u32 map_epoch;
4310 	u8 op;
4311 	u64 id;
4312 	struct ceph_hobject_id *begin;
4313 	struct ceph_hobject_id *end;
4314 };
4315 
4316 static int decode_MOSDBackoff(const struct ceph_msg *msg, struct MOSDBackoff *m)
4317 {
4318 	void *p = msg->front.iov_base;
4319 	void *const end = p + msg->front.iov_len;
4320 	u8 struct_v;
4321 	u32 struct_len;
4322 	int ret;
4323 
4324 	ret = ceph_start_decoding(&p, end, 1, "spg_t", &struct_v, &struct_len);
4325 	if (ret)
4326 		return ret;
4327 
4328 	ret = ceph_decode_pgid(&p, end, &m->spgid.pgid);
4329 	if (ret)
4330 		return ret;
4331 
4332 	ceph_decode_8_safe(&p, end, m->spgid.shard, e_inval);
4333 	ceph_decode_32_safe(&p, end, m->map_epoch, e_inval);
4334 	ceph_decode_8_safe(&p, end, m->op, e_inval);
4335 	ceph_decode_64_safe(&p, end, m->id, e_inval);
4336 
4337 	m->begin = kzalloc_obj(*m->begin, GFP_NOIO);
4338 	if (!m->begin)
4339 		return -ENOMEM;
4340 
4341 	ret = decode_hoid(&p, end, m->begin);
4342 	if (ret) {
4343 		free_hoid(m->begin);
4344 		return ret;
4345 	}
4346 
4347 	m->end = kzalloc_obj(*m->end, GFP_NOIO);
4348 	if (!m->end) {
4349 		free_hoid(m->begin);
4350 		return -ENOMEM;
4351 	}
4352 
4353 	ret = decode_hoid(&p, end, m->end);
4354 	if (ret) {
4355 		free_hoid(m->begin);
4356 		free_hoid(m->end);
4357 		return ret;
4358 	}
4359 
4360 	return 0;
4361 
4362 e_inval:
4363 	return -EINVAL;
4364 }
4365 
4366 static struct ceph_msg *create_backoff_message(
4367 				const struct ceph_osd_backoff *backoff,
4368 				u32 map_epoch)
4369 {
4370 	struct ceph_msg *msg;
4371 	void *p, *end;
4372 	int msg_size;
4373 
4374 	msg_size = CEPH_ENCODING_START_BLK_LEN +
4375 			CEPH_PGID_ENCODING_LEN + 1; /* spgid */
4376 	msg_size += 4 + 1 + 8; /* map_epoch, op, id */
4377 	msg_size += CEPH_ENCODING_START_BLK_LEN +
4378 			hoid_encoding_size(backoff->begin);
4379 	msg_size += CEPH_ENCODING_START_BLK_LEN +
4380 			hoid_encoding_size(backoff->end);
4381 
4382 	msg = ceph_msg_new(CEPH_MSG_OSD_BACKOFF, msg_size, GFP_NOIO, true);
4383 	if (!msg)
4384 		return NULL;
4385 
4386 	p = msg->front.iov_base;
4387 	end = p + msg->front_alloc_len;
4388 
4389 	encode_spgid(&p, &backoff->spgid);
4390 	ceph_encode_32(&p, map_epoch);
4391 	ceph_encode_8(&p, CEPH_OSD_BACKOFF_OP_ACK_BLOCK);
4392 	ceph_encode_64(&p, backoff->id);
4393 	encode_hoid(&p, end, backoff->begin);
4394 	encode_hoid(&p, end, backoff->end);
4395 	BUG_ON(p != end);
4396 
4397 	msg->front.iov_len = p - msg->front.iov_base;
4398 	msg->hdr.version = cpu_to_le16(1); /* MOSDBackoff v1 */
4399 	msg->hdr.front_len = cpu_to_le32(msg->front.iov_len);
4400 
4401 	return msg;
4402 }
4403 
4404 static void handle_backoff_block(struct ceph_osd *osd, struct MOSDBackoff *m)
4405 {
4406 	struct ceph_spg_mapping *spg;
4407 	struct ceph_osd_backoff *backoff;
4408 	struct ceph_msg *msg;
4409 
4410 	dout("%s osd%d spgid %llu.%xs%d id %llu\n", __func__, osd->o_osd,
4411 	     m->spgid.pgid.pool, m->spgid.pgid.seed, m->spgid.shard, m->id);
4412 
4413 	spg = lookup_spg_mapping(&osd->o_backoff_mappings, &m->spgid);
4414 	if (!spg) {
4415 		spg = alloc_spg_mapping();
4416 		if (!spg) {
4417 			pr_err("%s failed to allocate spg\n", __func__);
4418 			return;
4419 		}
4420 		spg->spgid = m->spgid; /* struct */
4421 		insert_spg_mapping(&osd->o_backoff_mappings, spg);
4422 	}
4423 
4424 	backoff = alloc_backoff();
4425 	if (!backoff) {
4426 		pr_err("%s failed to allocate backoff\n", __func__);
4427 		return;
4428 	}
4429 	backoff->spgid = m->spgid; /* struct */
4430 	backoff->id = m->id;
4431 	backoff->begin = m->begin;
4432 	m->begin = NULL; /* backoff now owns this */
4433 	backoff->end = m->end;
4434 	m->end = NULL;   /* ditto */
4435 
4436 	insert_backoff(&spg->backoffs, backoff);
4437 	insert_backoff_by_id(&osd->o_backoffs_by_id, backoff);
4438 
4439 	/*
4440 	 * Ack with original backoff's epoch so that the OSD can
4441 	 * discard this if there was a PG split.
4442 	 */
4443 	msg = create_backoff_message(backoff, m->map_epoch);
4444 	if (!msg) {
4445 		pr_err("%s failed to allocate msg\n", __func__);
4446 		return;
4447 	}
4448 	ceph_con_send(&osd->o_con, msg);
4449 }
4450 
4451 static bool target_contained_by(const struct ceph_osd_request_target *t,
4452 				const struct ceph_hobject_id *begin,
4453 				const struct ceph_hobject_id *end)
4454 {
4455 	struct ceph_hobject_id hoid;
4456 	int cmp;
4457 
4458 	hoid_fill_from_target(&hoid, t);
4459 	cmp = hoid_compare(&hoid, begin);
4460 	return !cmp || (cmp > 0 && hoid_compare(&hoid, end) < 0);
4461 }
4462 
4463 static void handle_backoff_unblock(struct ceph_osd *osd,
4464 				   const struct MOSDBackoff *m)
4465 {
4466 	struct ceph_spg_mapping *spg;
4467 	struct ceph_osd_backoff *backoff;
4468 	struct rb_node *n;
4469 
4470 	dout("%s osd%d spgid %llu.%xs%d id %llu\n", __func__, osd->o_osd,
4471 	     m->spgid.pgid.pool, m->spgid.pgid.seed, m->spgid.shard, m->id);
4472 
4473 	backoff = lookup_backoff_by_id(&osd->o_backoffs_by_id, m->id);
4474 	if (!backoff) {
4475 		pr_err("%s osd%d spgid %llu.%xs%d id %llu backoff dne\n",
4476 		       __func__, osd->o_osd, m->spgid.pgid.pool,
4477 		       m->spgid.pgid.seed, m->spgid.shard, m->id);
4478 		return;
4479 	}
4480 
4481 	if (hoid_compare(backoff->begin, m->begin) &&
4482 	    hoid_compare(backoff->end, m->end)) {
4483 		pr_err("%s osd%d spgid %llu.%xs%d id %llu bad range?\n",
4484 		       __func__, osd->o_osd, m->spgid.pgid.pool,
4485 		       m->spgid.pgid.seed, m->spgid.shard, m->id);
4486 		/* unblock it anyway... */
4487 	}
4488 
4489 	spg = lookup_spg_mapping(&osd->o_backoff_mappings, &backoff->spgid);
4490 	BUG_ON(!spg);
4491 
4492 	erase_backoff(&spg->backoffs, backoff);
4493 	erase_backoff_by_id(&osd->o_backoffs_by_id, backoff);
4494 	free_backoff(backoff);
4495 
4496 	if (RB_EMPTY_ROOT(&spg->backoffs)) {
4497 		erase_spg_mapping(&osd->o_backoff_mappings, spg);
4498 		free_spg_mapping(spg);
4499 	}
4500 
4501 	for (n = rb_first(&osd->o_requests); n; n = rb_next(n)) {
4502 		struct ceph_osd_request *req =
4503 		    rb_entry(n, struct ceph_osd_request, r_node);
4504 
4505 		if (!ceph_spg_compare(&req->r_t.spgid, &m->spgid)) {
4506 			/*
4507 			 * Match against @m, not @backoff -- the PG may
4508 			 * have split on the OSD.
4509 			 */
4510 			if (target_contained_by(&req->r_t, m->begin, m->end)) {
4511 				/*
4512 				 * If no other installed backoff applies,
4513 				 * resend.
4514 				 */
4515 				send_request(req);
4516 			}
4517 		}
4518 	}
4519 }
4520 
4521 static void handle_backoff(struct ceph_osd *osd, struct ceph_msg *msg)
4522 {
4523 	struct ceph_osd_client *osdc = osd->o_osdc;
4524 	struct MOSDBackoff m;
4525 	int ret;
4526 
4527 	down_read(&osdc->lock);
4528 	if (!osd_registered(osd)) {
4529 		dout("%s osd%d unknown\n", __func__, osd->o_osd);
4530 		up_read(&osdc->lock);
4531 		return;
4532 	}
4533 	WARN_ON(osd->o_osd != le64_to_cpu(msg->hdr.src.num));
4534 
4535 	mutex_lock(&osd->lock);
4536 	ret = decode_MOSDBackoff(msg, &m);
4537 	if (ret) {
4538 		pr_err("failed to decode MOSDBackoff: %d\n", ret);
4539 		ceph_msg_dump(msg);
4540 		goto out_unlock;
4541 	}
4542 
4543 	switch (m.op) {
4544 	case CEPH_OSD_BACKOFF_OP_BLOCK:
4545 		handle_backoff_block(osd, &m);
4546 		break;
4547 	case CEPH_OSD_BACKOFF_OP_UNBLOCK:
4548 		handle_backoff_unblock(osd, &m);
4549 		break;
4550 	default:
4551 		pr_err("%s osd%d unknown op %d\n", __func__, osd->o_osd, m.op);
4552 	}
4553 
4554 	free_hoid(m.begin);
4555 	free_hoid(m.end);
4556 
4557 out_unlock:
4558 	mutex_unlock(&osd->lock);
4559 	up_read(&osdc->lock);
4560 }
4561 
4562 /*
4563  * Process osd watch notifications
4564  */
4565 static void handle_watch_notify(struct ceph_osd_client *osdc,
4566 				struct ceph_msg *msg)
4567 {
4568 	void *p = msg->front.iov_base;
4569 	void *const end = p + msg->front.iov_len;
4570 	struct ceph_osd_linger_request *lreq;
4571 	struct linger_work *lwork;
4572 	u8 proto_ver, opcode;
4573 	u64 cookie, notify_id;
4574 	u64 notifier_id = 0;
4575 	s32 return_code = 0;
4576 	void *payload = NULL;
4577 	u32 payload_len = 0;
4578 
4579 	ceph_decode_8_safe(&p, end, proto_ver, bad);
4580 	ceph_decode_8_safe(&p, end, opcode, bad);
4581 	ceph_decode_64_safe(&p, end, cookie, bad);
4582 	p += 8; /* skip ver */
4583 	ceph_decode_64_safe(&p, end, notify_id, bad);
4584 
4585 	if (proto_ver >= 1) {
4586 		ceph_decode_32_safe(&p, end, payload_len, bad);
4587 		ceph_decode_need(&p, end, payload_len, bad);
4588 		payload = p;
4589 		p += payload_len;
4590 	}
4591 
4592 	if (le16_to_cpu(msg->hdr.version) >= 2)
4593 		ceph_decode_32_safe(&p, end, return_code, bad);
4594 
4595 	if (le16_to_cpu(msg->hdr.version) >= 3)
4596 		ceph_decode_64_safe(&p, end, notifier_id, bad);
4597 
4598 	down_read(&osdc->lock);
4599 	lreq = lookup_linger_osdc(&osdc->linger_requests, cookie);
4600 	if (!lreq) {
4601 		dout("%s opcode %d cookie %llu dne\n", __func__, opcode,
4602 		     cookie);
4603 		goto out_unlock_osdc;
4604 	}
4605 
4606 	mutex_lock(&lreq->lock);
4607 	dout("%s opcode %d cookie %llu lreq %p is_watch %d\n", __func__,
4608 	     opcode, cookie, lreq, lreq->is_watch);
4609 	if (opcode == CEPH_WATCH_EVENT_DISCONNECT) {
4610 		if (!lreq->last_error) {
4611 			lreq->last_error = -ENOTCONN;
4612 			queue_watch_error(lreq);
4613 		}
4614 	} else if (!lreq->is_watch) {
4615 		/* CEPH_WATCH_EVENT_NOTIFY_COMPLETE */
4616 		if (lreq->notify_id && lreq->notify_id != notify_id) {
4617 			dout("lreq %p notify_id %llu != %llu, ignoring\n", lreq,
4618 			     lreq->notify_id, notify_id);
4619 		} else if (!completion_done(&lreq->notify_finish_wait)) {
4620 			struct ceph_msg_data *data =
4621 			    msg->num_data_items ? &msg->data[0] : NULL;
4622 
4623 			if (data) {
4624 				if (lreq->preply_pages) {
4625 					WARN_ON(data->type !=
4626 							CEPH_MSG_DATA_PAGES);
4627 					*lreq->preply_pages = data->pages;
4628 					*lreq->preply_len = data->length;
4629 					data->own_pages = false;
4630 				}
4631 			}
4632 			lreq->notify_finish_error = return_code;
4633 			complete_all(&lreq->notify_finish_wait);
4634 		}
4635 	} else {
4636 		/* CEPH_WATCH_EVENT_NOTIFY */
4637 		lwork = lwork_alloc(lreq, do_watch_notify);
4638 		if (!lwork) {
4639 			pr_err("failed to allocate notify-lwork\n");
4640 			goto out_unlock_lreq;
4641 		}
4642 
4643 		lwork->notify.notify_id = notify_id;
4644 		lwork->notify.notifier_id = notifier_id;
4645 		lwork->notify.payload = payload;
4646 		lwork->notify.payload_len = payload_len;
4647 		lwork->notify.msg = ceph_msg_get(msg);
4648 		lwork_queue(lwork);
4649 	}
4650 
4651 out_unlock_lreq:
4652 	mutex_unlock(&lreq->lock);
4653 out_unlock_osdc:
4654 	up_read(&osdc->lock);
4655 	return;
4656 
4657 bad:
4658 	pr_err("osdc handle_watch_notify corrupt msg\n");
4659 }
4660 
4661 /*
4662  * Register request, send initial attempt.
4663  */
4664 void ceph_osdc_start_request(struct ceph_osd_client *osdc,
4665 			     struct ceph_osd_request *req)
4666 {
4667 	down_read(&osdc->lock);
4668 	submit_request(req, false);
4669 	up_read(&osdc->lock);
4670 }
4671 EXPORT_SYMBOL(ceph_osdc_start_request);
4672 
4673 /*
4674  * Unregister request.  If @req was registered, it isn't completed:
4675  * r_result isn't set and __complete_request() isn't invoked.
4676  *
4677  * If @req wasn't registered, this call may have raced with
4678  * handle_reply(), in which case r_result would already be set and
4679  * __complete_request() would be getting invoked, possibly even
4680  * concurrently with this call.
4681  */
4682 void ceph_osdc_cancel_request(struct ceph_osd_request *req)
4683 {
4684 	struct ceph_osd_client *osdc = req->r_osdc;
4685 
4686 	down_write(&osdc->lock);
4687 	if (req->r_osd)
4688 		cancel_request(req);
4689 	up_write(&osdc->lock);
4690 }
4691 EXPORT_SYMBOL(ceph_osdc_cancel_request);
4692 
4693 /*
4694  * @timeout: in jiffies, 0 means "wait forever"
4695  */
4696 static int wait_request_timeout(struct ceph_osd_request *req,
4697 				unsigned long timeout)
4698 {
4699 	long left;
4700 
4701 	dout("%s req %p tid %llu\n", __func__, req, req->r_tid);
4702 	left = wait_for_completion_killable_timeout(&req->r_completion,
4703 						ceph_timeout_jiffies(timeout));
4704 	if (left <= 0) {
4705 		left = left ?: -ETIMEDOUT;
4706 		ceph_osdc_cancel_request(req);
4707 	} else {
4708 		left = req->r_result; /* completed */
4709 	}
4710 
4711 	return left;
4712 }
4713 
4714 /*
4715  * wait for a request to complete
4716  */
4717 int ceph_osdc_wait_request(struct ceph_osd_client *osdc,
4718 			   struct ceph_osd_request *req)
4719 {
4720 	return wait_request_timeout(req, 0);
4721 }
4722 EXPORT_SYMBOL(ceph_osdc_wait_request);
4723 
4724 /*
4725  * sync - wait for all in-flight requests to flush.  avoid starvation.
4726  */
4727 void ceph_osdc_sync(struct ceph_osd_client *osdc)
4728 {
4729 	struct rb_node *n, *p;
4730 	u64 last_tid = atomic64_read(&osdc->last_tid);
4731 
4732 again:
4733 	down_read(&osdc->lock);
4734 	for (n = rb_first(&osdc->osds); n; n = rb_next(n)) {
4735 		struct ceph_osd *osd = rb_entry(n, struct ceph_osd, o_node);
4736 
4737 		mutex_lock(&osd->lock);
4738 		for (p = rb_first(&osd->o_requests); p; p = rb_next(p)) {
4739 			struct ceph_osd_request *req =
4740 			    rb_entry(p, struct ceph_osd_request, r_node);
4741 
4742 			if (req->r_tid > last_tid)
4743 				break;
4744 
4745 			if (!(req->r_flags & CEPH_OSD_FLAG_WRITE))
4746 				continue;
4747 
4748 			ceph_osdc_get_request(req);
4749 			mutex_unlock(&osd->lock);
4750 			up_read(&osdc->lock);
4751 			dout("%s waiting on req %p tid %llu last_tid %llu\n",
4752 			     __func__, req, req->r_tid, last_tid);
4753 			wait_for_completion(&req->r_completion);
4754 			ceph_osdc_put_request(req);
4755 			goto again;
4756 		}
4757 
4758 		mutex_unlock(&osd->lock);
4759 	}
4760 
4761 	up_read(&osdc->lock);
4762 	dout("%s done last_tid %llu\n", __func__, last_tid);
4763 }
4764 EXPORT_SYMBOL(ceph_osdc_sync);
4765 
4766 /*
4767  * Returns a handle, caller owns a ref.
4768  */
4769 struct ceph_osd_linger_request *
4770 ceph_osdc_watch(struct ceph_osd_client *osdc,
4771 		struct ceph_object_id *oid,
4772 		struct ceph_object_locator *oloc,
4773 		rados_watchcb2_t wcb,
4774 		rados_watcherrcb_t errcb,
4775 		void *data)
4776 {
4777 	struct ceph_osd_linger_request *lreq;
4778 	int ret;
4779 
4780 	lreq = linger_alloc(osdc);
4781 	if (!lreq)
4782 		return ERR_PTR(-ENOMEM);
4783 
4784 	lreq->is_watch = true;
4785 	lreq->wcb = wcb;
4786 	lreq->errcb = errcb;
4787 	lreq->data = data;
4788 	lreq->watch_valid_thru = jiffies;
4789 
4790 	ceph_oid_copy(&lreq->t.base_oid, oid);
4791 	ceph_oloc_copy(&lreq->t.base_oloc, oloc);
4792 	lreq->t.flags = CEPH_OSD_FLAG_WRITE;
4793 	ktime_get_real_ts64(&lreq->mtime);
4794 
4795 	linger_submit(lreq);
4796 	ret = linger_reg_commit_wait(lreq);
4797 	if (ret) {
4798 		linger_cancel(lreq);
4799 		goto err_put_lreq;
4800 	}
4801 
4802 	return lreq;
4803 
4804 err_put_lreq:
4805 	linger_put(lreq);
4806 	return ERR_PTR(ret);
4807 }
4808 EXPORT_SYMBOL(ceph_osdc_watch);
4809 
4810 /*
4811  * Releases a ref.
4812  *
4813  * Times out after mount_timeout to preserve rbd unmap behaviour
4814  * introduced in 2894e1d76974 ("rbd: timeout watch teardown on unmap
4815  * with mount_timeout").
4816  */
4817 int ceph_osdc_unwatch(struct ceph_osd_client *osdc,
4818 		      struct ceph_osd_linger_request *lreq)
4819 {
4820 	struct ceph_options *opts = osdc->client->options;
4821 	struct ceph_osd_request *req;
4822 	int ret;
4823 
4824 	req = ceph_osdc_alloc_request(osdc, NULL, 1, false, GFP_NOIO);
4825 	if (!req)
4826 		return -ENOMEM;
4827 
4828 	ceph_oid_copy(&req->r_base_oid, &lreq->t.base_oid);
4829 	ceph_oloc_copy(&req->r_base_oloc, &lreq->t.base_oloc);
4830 	req->r_flags = CEPH_OSD_FLAG_WRITE;
4831 	ktime_get_real_ts64(&req->r_mtime);
4832 	osd_req_op_watch_init(req, 0, CEPH_OSD_WATCH_OP_UNWATCH,
4833 			      lreq->linger_id, 0);
4834 
4835 	ret = ceph_osdc_alloc_messages(req, GFP_NOIO);
4836 	if (ret)
4837 		goto out_put_req;
4838 
4839 	ceph_osdc_start_request(osdc, req);
4840 	linger_cancel(lreq);
4841 	linger_put(lreq);
4842 	ret = wait_request_timeout(req, opts->mount_timeout);
4843 
4844 out_put_req:
4845 	ceph_osdc_put_request(req);
4846 	return ret;
4847 }
4848 EXPORT_SYMBOL(ceph_osdc_unwatch);
4849 
4850 static int osd_req_op_notify_ack_init(struct ceph_osd_request *req, int which,
4851 				      u64 notify_id, u64 cookie, void *payload,
4852 				      u32 payload_len)
4853 {
4854 	struct ceph_osd_req_op *op;
4855 	struct ceph_pagelist *pl;
4856 	int ret;
4857 
4858 	op = osd_req_op_init(req, which, CEPH_OSD_OP_NOTIFY_ACK, 0);
4859 
4860 	pl = ceph_pagelist_alloc(GFP_NOIO);
4861 	if (!pl)
4862 		return -ENOMEM;
4863 
4864 	ret = ceph_pagelist_encode_64(pl, notify_id);
4865 	ret |= ceph_pagelist_encode_64(pl, cookie);
4866 	if (payload) {
4867 		ret |= ceph_pagelist_encode_32(pl, payload_len);
4868 		ret |= ceph_pagelist_append(pl, payload, payload_len);
4869 	} else {
4870 		ret |= ceph_pagelist_encode_32(pl, 0);
4871 	}
4872 	if (ret) {
4873 		ceph_pagelist_release(pl);
4874 		return -ENOMEM;
4875 	}
4876 
4877 	ceph_osd_data_pagelist_init(&op->notify_ack.request_data, pl);
4878 	op->indata_len = pl->length;
4879 	return 0;
4880 }
4881 
4882 int ceph_osdc_notify_ack(struct ceph_osd_client *osdc,
4883 			 struct ceph_object_id *oid,
4884 			 struct ceph_object_locator *oloc,
4885 			 u64 notify_id,
4886 			 u64 cookie,
4887 			 void *payload,
4888 			 u32 payload_len)
4889 {
4890 	struct ceph_osd_request *req;
4891 	int ret;
4892 
4893 	req = ceph_osdc_alloc_request(osdc, NULL, 1, false, GFP_NOIO);
4894 	if (!req)
4895 		return -ENOMEM;
4896 
4897 	ceph_oid_copy(&req->r_base_oid, oid);
4898 	ceph_oloc_copy(&req->r_base_oloc, oloc);
4899 	req->r_flags = CEPH_OSD_FLAG_READ;
4900 
4901 	ret = osd_req_op_notify_ack_init(req, 0, notify_id, cookie, payload,
4902 					 payload_len);
4903 	if (ret)
4904 		goto out_put_req;
4905 
4906 	ret = ceph_osdc_alloc_messages(req, GFP_NOIO);
4907 	if (ret)
4908 		goto out_put_req;
4909 
4910 	ceph_osdc_start_request(osdc, req);
4911 	ret = ceph_osdc_wait_request(osdc, req);
4912 
4913 out_put_req:
4914 	ceph_osdc_put_request(req);
4915 	return ret;
4916 }
4917 EXPORT_SYMBOL(ceph_osdc_notify_ack);
4918 
4919 /*
4920  * @timeout: in seconds
4921  *
4922  * @preply_{pages,len} are initialized both on success and error.
4923  * The caller is responsible for:
4924  *
4925  *     ceph_release_page_vector(reply_pages, calc_pages_for(0, reply_len))
4926  */
4927 int ceph_osdc_notify(struct ceph_osd_client *osdc,
4928 		     struct ceph_object_id *oid,
4929 		     struct ceph_object_locator *oloc,
4930 		     void *payload,
4931 		     u32 payload_len,
4932 		     u32 timeout,
4933 		     struct page ***preply_pages,
4934 		     size_t *preply_len)
4935 {
4936 	struct ceph_osd_linger_request *lreq;
4937 	int ret;
4938 
4939 	WARN_ON(!timeout);
4940 	if (preply_pages) {
4941 		*preply_pages = NULL;
4942 		*preply_len = 0;
4943 	}
4944 
4945 	lreq = linger_alloc(osdc);
4946 	if (!lreq)
4947 		return -ENOMEM;
4948 
4949 	lreq->request_pl = ceph_pagelist_alloc(GFP_NOIO);
4950 	if (!lreq->request_pl) {
4951 		ret = -ENOMEM;
4952 		goto out_put_lreq;
4953 	}
4954 
4955 	ret = ceph_pagelist_encode_32(lreq->request_pl, 1); /* prot_ver */
4956 	ret |= ceph_pagelist_encode_32(lreq->request_pl, timeout);
4957 	ret |= ceph_pagelist_encode_32(lreq->request_pl, payload_len);
4958 	ret |= ceph_pagelist_append(lreq->request_pl, payload, payload_len);
4959 	if (ret) {
4960 		ret = -ENOMEM;
4961 		goto out_put_lreq;
4962 	}
4963 
4964 	/* for notify_id */
4965 	lreq->notify_id_pages = ceph_alloc_page_vector(1, GFP_NOIO);
4966 	if (IS_ERR(lreq->notify_id_pages)) {
4967 		ret = PTR_ERR(lreq->notify_id_pages);
4968 		lreq->notify_id_pages = NULL;
4969 		goto out_put_lreq;
4970 	}
4971 
4972 	lreq->preply_pages = preply_pages;
4973 	lreq->preply_len = preply_len;
4974 
4975 	ceph_oid_copy(&lreq->t.base_oid, oid);
4976 	ceph_oloc_copy(&lreq->t.base_oloc, oloc);
4977 	lreq->t.flags = CEPH_OSD_FLAG_READ;
4978 
4979 	linger_submit(lreq);
4980 	ret = linger_reg_commit_wait(lreq);
4981 	if (!ret)
4982 		ret = linger_notify_finish_wait(lreq,
4983 				 msecs_to_jiffies(2 * timeout * MSEC_PER_SEC));
4984 	else
4985 		dout("lreq %p failed to initiate notify %d\n", lreq, ret);
4986 
4987 	linger_cancel(lreq);
4988 out_put_lreq:
4989 	linger_put(lreq);
4990 	return ret;
4991 }
4992 EXPORT_SYMBOL(ceph_osdc_notify);
4993 
4994 static int decode_watcher(void **p, void *end, struct ceph_watch_item *item)
4995 {
4996 	u8 struct_v;
4997 	u32 struct_len;
4998 	int ret;
4999 
5000 	ret = ceph_start_decoding(p, end, 2, "watch_item_t",
5001 				  &struct_v, &struct_len);
5002 	if (ret)
5003 		goto bad;
5004 
5005 	ret = -EINVAL;
5006 	ceph_decode_copy_safe(p, end, &item->name, sizeof(item->name), bad);
5007 	ceph_decode_64_safe(p, end, item->cookie, bad);
5008 	ceph_decode_skip_32(p, end, bad); /* skip timeout seconds */
5009 
5010 	if (struct_v >= 2) {
5011 		ret = ceph_decode_entity_addr(p, end, &item->addr);
5012 		if (ret)
5013 			goto bad;
5014 	} else {
5015 		ret = 0;
5016 	}
5017 
5018 	dout("%s %s%llu cookie %llu addr %s\n", __func__,
5019 	     ENTITY_NAME(item->name), item->cookie,
5020 	     ceph_pr_addr(&item->addr));
5021 bad:
5022 	return ret;
5023 }
5024 
5025 static int decode_watchers(void **p, void *end,
5026 			   struct ceph_watch_item **watchers,
5027 			   u32 *num_watchers)
5028 {
5029 	u8 struct_v;
5030 	u32 struct_len;
5031 	int i;
5032 	int ret;
5033 
5034 	ret = ceph_start_decoding(p, end, 1, "obj_list_watch_response_t",
5035 				  &struct_v, &struct_len);
5036 	if (ret)
5037 		return ret;
5038 
5039 	ceph_decode_32_safe(p, end, *num_watchers, bad);
5040 	*watchers = kzalloc_objs(**watchers, *num_watchers, GFP_NOIO);
5041 	if (!*watchers)
5042 		return -ENOMEM;
5043 
5044 	for (i = 0; i < *num_watchers; i++) {
5045 		ret = decode_watcher(p, end, *watchers + i);
5046 		if (ret) {
5047 			kfree(*watchers);
5048 			return ret;
5049 		}
5050 	}
5051 
5052 	return 0;
5053 
5054 bad:
5055 	return -EINVAL;
5056 }
5057 
5058 /*
5059  * On success, the caller is responsible for:
5060  *
5061  *     kfree(watchers);
5062  */
5063 int ceph_osdc_list_watchers(struct ceph_osd_client *osdc,
5064 			    struct ceph_object_id *oid,
5065 			    struct ceph_object_locator *oloc,
5066 			    struct ceph_watch_item **watchers,
5067 			    u32 *num_watchers)
5068 {
5069 	struct ceph_osd_request *req;
5070 	struct page **pages;
5071 	int ret;
5072 
5073 	req = ceph_osdc_alloc_request(osdc, NULL, 1, false, GFP_NOIO);
5074 	if (!req)
5075 		return -ENOMEM;
5076 
5077 	ceph_oid_copy(&req->r_base_oid, oid);
5078 	ceph_oloc_copy(&req->r_base_oloc, oloc);
5079 	req->r_flags = CEPH_OSD_FLAG_READ;
5080 
5081 	pages = ceph_alloc_page_vector(1, GFP_NOIO);
5082 	if (IS_ERR(pages)) {
5083 		ret = PTR_ERR(pages);
5084 		goto out_put_req;
5085 	}
5086 
5087 	osd_req_op_init(req, 0, CEPH_OSD_OP_LIST_WATCHERS, 0);
5088 	ceph_osd_data_pages_init(osd_req_op_data(req, 0, list_watchers,
5089 						 response_data),
5090 				 pages, PAGE_SIZE, 0, false, true);
5091 
5092 	ret = ceph_osdc_alloc_messages(req, GFP_NOIO);
5093 	if (ret)
5094 		goto out_put_req;
5095 
5096 	ceph_osdc_start_request(osdc, req);
5097 	ret = ceph_osdc_wait_request(osdc, req);
5098 	if (ret >= 0) {
5099 		void *p = page_address(pages[0]);
5100 		void *const end = p + req->r_ops[0].outdata_len;
5101 
5102 		ret = decode_watchers(&p, end, watchers, num_watchers);
5103 	}
5104 
5105 out_put_req:
5106 	ceph_osdc_put_request(req);
5107 	return ret;
5108 }
5109 EXPORT_SYMBOL(ceph_osdc_list_watchers);
5110 
5111 /*
5112  * Call all pending notify callbacks - for use after a watch is
5113  * unregistered, to make sure no more callbacks for it will be invoked
5114  */
5115 void ceph_osdc_flush_notifies(struct ceph_osd_client *osdc)
5116 {
5117 	dout("%s osdc %p\n", __func__, osdc);
5118 	flush_workqueue(osdc->notify_wq);
5119 }
5120 EXPORT_SYMBOL(ceph_osdc_flush_notifies);
5121 
5122 void ceph_osdc_maybe_request_map(struct ceph_osd_client *osdc)
5123 {
5124 	down_read(&osdc->lock);
5125 	maybe_request_map(osdc);
5126 	up_read(&osdc->lock);
5127 }
5128 EXPORT_SYMBOL(ceph_osdc_maybe_request_map);
5129 
5130 /*
5131  * Execute an OSD class method on an object.
5132  *
5133  * @flags: CEPH_OSD_FLAG_*
5134  * @resp_len: in/out param for reply length
5135  */
5136 int ceph_osdc_call(struct ceph_osd_client *osdc,
5137 		   struct ceph_object_id *oid,
5138 		   struct ceph_object_locator *oloc,
5139 		   const char *class, const char *method,
5140 		   unsigned int flags,
5141 		   struct page *req_page, size_t req_len,
5142 		   struct page **resp_pages, size_t *resp_len)
5143 {
5144 	struct ceph_osd_request *req;
5145 	int ret;
5146 
5147 	if (req_len > PAGE_SIZE)
5148 		return -E2BIG;
5149 
5150 	req = ceph_osdc_alloc_request(osdc, NULL, 1, false, GFP_NOIO);
5151 	if (!req)
5152 		return -ENOMEM;
5153 
5154 	ceph_oid_copy(&req->r_base_oid, oid);
5155 	ceph_oloc_copy(&req->r_base_oloc, oloc);
5156 	req->r_flags = flags;
5157 
5158 	ret = osd_req_op_cls_init(req, 0, class, method);
5159 	if (ret)
5160 		goto out_put_req;
5161 
5162 	if (req_page)
5163 		osd_req_op_cls_request_data_pages(req, 0, &req_page, req_len,
5164 						  0, false, false);
5165 	if (resp_pages)
5166 		osd_req_op_cls_response_data_pages(req, 0, resp_pages,
5167 						   *resp_len, 0, false, false);
5168 
5169 	ret = ceph_osdc_alloc_messages(req, GFP_NOIO);
5170 	if (ret)
5171 		goto out_put_req;
5172 
5173 	ceph_osdc_start_request(osdc, req);
5174 	ret = ceph_osdc_wait_request(osdc, req);
5175 	if (ret >= 0) {
5176 		ret = req->r_ops[0].rval;
5177 		if (resp_pages)
5178 			*resp_len = req->r_ops[0].outdata_len;
5179 	}
5180 
5181 out_put_req:
5182 	ceph_osdc_put_request(req);
5183 	return ret;
5184 }
5185 EXPORT_SYMBOL(ceph_osdc_call);
5186 
5187 /*
5188  * reset all osd connections
5189  */
5190 void ceph_osdc_reopen_osds(struct ceph_osd_client *osdc)
5191 {
5192 	struct rb_node *n;
5193 
5194 	down_write(&osdc->lock);
5195 	for (n = rb_first(&osdc->osds); n; ) {
5196 		struct ceph_osd *osd = rb_entry(n, struct ceph_osd, o_node);
5197 
5198 		n = rb_next(n);
5199 		if (!reopen_osd(osd))
5200 			kick_osd_requests(osd);
5201 	}
5202 	up_write(&osdc->lock);
5203 }
5204 
5205 /*
5206  * init, shutdown
5207  */
5208 int ceph_osdc_init(struct ceph_osd_client *osdc, struct ceph_client *client)
5209 {
5210 	int err;
5211 
5212 	dout("init\n");
5213 	osdc->client = client;
5214 	init_rwsem(&osdc->lock);
5215 	osdc->osds = RB_ROOT;
5216 	INIT_LIST_HEAD(&osdc->osd_lru);
5217 	spin_lock_init(&osdc->osd_lru_lock);
5218 	osd_init(&osdc->homeless_osd);
5219 	osdc->homeless_osd.o_osdc = osdc;
5220 	osdc->homeless_osd.o_osd = CEPH_HOMELESS_OSD;
5221 	osdc->last_linger_id = CEPH_LINGER_ID_START;
5222 	osdc->linger_requests = RB_ROOT;
5223 	osdc->map_checks = RB_ROOT;
5224 	osdc->linger_map_checks = RB_ROOT;
5225 	INIT_DELAYED_WORK(&osdc->timeout_work, handle_timeout);
5226 	INIT_DELAYED_WORK(&osdc->osds_timeout_work, handle_osds_timeout);
5227 
5228 	err = -ENOMEM;
5229 	osdc->osdmap = ceph_osdmap_alloc();
5230 	if (!osdc->osdmap)
5231 		goto out;
5232 
5233 	osdc->req_mempool = mempool_create_slab_pool(10,
5234 						     ceph_osd_request_cache);
5235 	if (!osdc->req_mempool)
5236 		goto out_map;
5237 
5238 	err = ceph_msgpool_init(&osdc->msgpool_op, CEPH_MSG_OSD_OP,
5239 				PAGE_SIZE, CEPH_OSD_SLAB_OPS, 10, "osd_op");
5240 	if (err < 0)
5241 		goto out_mempool;
5242 	err = ceph_msgpool_init(&osdc->msgpool_op_reply, CEPH_MSG_OSD_OPREPLY,
5243 				PAGE_SIZE, CEPH_OSD_SLAB_OPS, 10,
5244 				"osd_op_reply");
5245 	if (err < 0)
5246 		goto out_msgpool;
5247 
5248 	err = -ENOMEM;
5249 	osdc->notify_wq = create_singlethread_workqueue("ceph-watch-notify");
5250 	if (!osdc->notify_wq)
5251 		goto out_msgpool_reply;
5252 
5253 	osdc->completion_wq = create_singlethread_workqueue("ceph-completion");
5254 	if (!osdc->completion_wq)
5255 		goto out_notify_wq;
5256 
5257 	schedule_delayed_work(&osdc->timeout_work,
5258 			      osdc->client->options->osd_keepalive_timeout);
5259 	schedule_delayed_work(&osdc->osds_timeout_work,
5260 	    round_jiffies_relative(osdc->client->options->osd_idle_ttl));
5261 
5262 	return 0;
5263 
5264 out_notify_wq:
5265 	destroy_workqueue(osdc->notify_wq);
5266 out_msgpool_reply:
5267 	ceph_msgpool_destroy(&osdc->msgpool_op_reply);
5268 out_msgpool:
5269 	ceph_msgpool_destroy(&osdc->msgpool_op);
5270 out_mempool:
5271 	mempool_destroy(osdc->req_mempool);
5272 out_map:
5273 	ceph_osdmap_destroy(osdc->osdmap);
5274 out:
5275 	return err;
5276 }
5277 
5278 void ceph_osdc_stop(struct ceph_osd_client *osdc)
5279 {
5280 	destroy_workqueue(osdc->completion_wq);
5281 	destroy_workqueue(osdc->notify_wq);
5282 	cancel_delayed_work_sync(&osdc->timeout_work);
5283 	cancel_delayed_work_sync(&osdc->osds_timeout_work);
5284 
5285 	down_write(&osdc->lock);
5286 	while (!RB_EMPTY_ROOT(&osdc->osds)) {
5287 		struct ceph_osd *osd = rb_entry(rb_first(&osdc->osds),
5288 						struct ceph_osd, o_node);
5289 		close_osd(osd);
5290 	}
5291 	up_write(&osdc->lock);
5292 	WARN_ON(refcount_read(&osdc->homeless_osd.o_ref) != 1);
5293 	osd_cleanup(&osdc->homeless_osd);
5294 
5295 	WARN_ON(!list_empty(&osdc->osd_lru));
5296 	WARN_ON(!RB_EMPTY_ROOT(&osdc->linger_requests));
5297 	WARN_ON(!RB_EMPTY_ROOT(&osdc->map_checks));
5298 	WARN_ON(!RB_EMPTY_ROOT(&osdc->linger_map_checks));
5299 	WARN_ON(atomic_read(&osdc->num_requests));
5300 	WARN_ON(atomic_read(&osdc->num_homeless));
5301 
5302 	ceph_osdmap_destroy(osdc->osdmap);
5303 	mempool_destroy(osdc->req_mempool);
5304 	ceph_msgpool_destroy(&osdc->msgpool_op);
5305 	ceph_msgpool_destroy(&osdc->msgpool_op_reply);
5306 }
5307 
5308 int osd_req_op_copy_from_init(struct ceph_osd_request *req,
5309 			      u64 src_snapid, u64 src_version,
5310 			      struct ceph_object_id *src_oid,
5311 			      struct ceph_object_locator *src_oloc,
5312 			      u32 src_fadvise_flags,
5313 			      u32 dst_fadvise_flags,
5314 			      u32 truncate_seq, u64 truncate_size,
5315 			      u8 copy_from_flags)
5316 {
5317 	struct ceph_osd_req_op *op;
5318 	struct page **pages;
5319 	void *p, *end;
5320 
5321 	pages = ceph_alloc_page_vector(1, GFP_KERNEL);
5322 	if (IS_ERR(pages))
5323 		return PTR_ERR(pages);
5324 
5325 	op = osd_req_op_init(req, 0, CEPH_OSD_OP_COPY_FROM2,
5326 			     dst_fadvise_flags);
5327 	op->copy_from.snapid = src_snapid;
5328 	op->copy_from.src_version = src_version;
5329 	op->copy_from.flags = copy_from_flags;
5330 	op->copy_from.src_fadvise_flags = src_fadvise_flags;
5331 
5332 	p = page_address(pages[0]);
5333 	end = p + PAGE_SIZE;
5334 	ceph_encode_string(&p, end, src_oid->name, src_oid->name_len);
5335 	encode_oloc(&p, end, src_oloc);
5336 	ceph_encode_32(&p, truncate_seq);
5337 	ceph_encode_64(&p, truncate_size);
5338 	op->indata_len = PAGE_SIZE - (end - p);
5339 
5340 	ceph_osd_data_pages_init(&op->copy_from.osd_data, pages,
5341 				 op->indata_len, 0, false, true);
5342 	return 0;
5343 }
5344 EXPORT_SYMBOL(osd_req_op_copy_from_init);
5345 
5346 int __init ceph_osdc_setup(void)
5347 {
5348 	size_t size = sizeof(struct ceph_osd_request) +
5349 	    CEPH_OSD_SLAB_OPS * sizeof(struct ceph_osd_req_op);
5350 
5351 	BUG_ON(ceph_osd_request_cache);
5352 	ceph_osd_request_cache = kmem_cache_create("ceph_osd_request", size,
5353 						   0, 0, NULL);
5354 
5355 	return ceph_osd_request_cache ? 0 : -ENOMEM;
5356 }
5357 
5358 void ceph_osdc_cleanup(void)
5359 {
5360 	BUG_ON(!ceph_osd_request_cache);
5361 	kmem_cache_destroy(ceph_osd_request_cache);
5362 	ceph_osd_request_cache = NULL;
5363 }
5364 
5365 /*
5366  * handle incoming message
5367  */
5368 static void osd_dispatch(struct ceph_connection *con, struct ceph_msg *msg)
5369 {
5370 	struct ceph_osd *osd = con->private;
5371 	struct ceph_osd_client *osdc = osd->o_osdc;
5372 	int type = le16_to_cpu(msg->hdr.type);
5373 
5374 	switch (type) {
5375 	case CEPH_MSG_OSD_MAP:
5376 		ceph_osdc_handle_map(osdc, msg);
5377 		break;
5378 	case CEPH_MSG_OSD_OPREPLY:
5379 		handle_reply(osd, msg);
5380 		break;
5381 	case CEPH_MSG_OSD_BACKOFF:
5382 		handle_backoff(osd, msg);
5383 		break;
5384 	case CEPH_MSG_WATCH_NOTIFY:
5385 		handle_watch_notify(osdc, msg);
5386 		break;
5387 
5388 	default:
5389 		pr_err("received unknown message type %d %s\n", type,
5390 		       ceph_msg_type_name(type));
5391 	}
5392 
5393 	ceph_msg_put(msg);
5394 }
5395 
5396 /* How much sparse data was requested? */
5397 static u64 sparse_data_requested(struct ceph_osd_request *req)
5398 {
5399 	u64 len = 0;
5400 
5401 	if (req->r_flags & CEPH_OSD_FLAG_READ) {
5402 		int i;
5403 
5404 		for (i = 0; i < req->r_num_ops; ++i) {
5405 			struct ceph_osd_req_op *op = &req->r_ops[i];
5406 
5407 			if (op->op == CEPH_OSD_OP_SPARSE_READ)
5408 				len += op->extent.length;
5409 		}
5410 	}
5411 	return len;
5412 }
5413 
5414 /*
5415  * Lookup and return message for incoming reply.  Don't try to do
5416  * anything about a larger than preallocated data portion of the
5417  * message at the moment - for now, just skip the message.
5418  */
5419 static struct ceph_msg *get_reply(struct ceph_connection *con,
5420 				  struct ceph_msg_header *hdr,
5421 				  int *skip)
5422 {
5423 	struct ceph_osd *osd = con->private;
5424 	struct ceph_osd_client *osdc = osd->o_osdc;
5425 	struct ceph_msg *m = NULL;
5426 	struct ceph_osd_request *req;
5427 	int front_len = le32_to_cpu(hdr->front_len);
5428 	int data_len = le32_to_cpu(hdr->data_len);
5429 	u64 tid = le64_to_cpu(hdr->tid);
5430 	u64 srlen;
5431 
5432 	down_read(&osdc->lock);
5433 	if (!osd_registered(osd)) {
5434 		dout("%s osd%d unknown, skipping\n", __func__, osd->o_osd);
5435 		*skip = 1;
5436 		goto out_unlock_osdc;
5437 	}
5438 	WARN_ON(osd->o_osd != le64_to_cpu(hdr->src.num));
5439 
5440 	mutex_lock(&osd->lock);
5441 	req = lookup_request(&osd->o_requests, tid);
5442 	if (!req) {
5443 		dout("%s osd%d tid %llu unknown, skipping\n", __func__,
5444 		     osd->o_osd, tid);
5445 		*skip = 1;
5446 		goto out_unlock_session;
5447 	}
5448 
5449 	ceph_msg_revoke_incoming(req->r_reply);
5450 
5451 	if (front_len > req->r_reply->front_alloc_len) {
5452 		pr_warn("%s osd%d tid %llu front %d > preallocated %d\n",
5453 			__func__, osd->o_osd, req->r_tid, front_len,
5454 			req->r_reply->front_alloc_len);
5455 		m = ceph_msg_new(CEPH_MSG_OSD_OPREPLY, front_len, GFP_NOFS,
5456 				 false);
5457 		if (!m)
5458 			goto out_unlock_session;
5459 		ceph_msg_put(req->r_reply);
5460 		req->r_reply = m;
5461 	}
5462 
5463 	srlen = sparse_data_requested(req);
5464 	if (!srlen && data_len > req->r_reply->data_length) {
5465 		pr_warn("%s osd%d tid %llu data %d > preallocated %zu, skipping\n",
5466 			__func__, osd->o_osd, req->r_tid, data_len,
5467 			req->r_reply->data_length);
5468 		m = NULL;
5469 		*skip = 1;
5470 		goto out_unlock_session;
5471 	}
5472 
5473 	m = ceph_msg_get(req->r_reply);
5474 	m->sparse_read_total = srlen;
5475 
5476 	dout("get_reply tid %lld %p\n", tid, m);
5477 
5478 out_unlock_session:
5479 	mutex_unlock(&osd->lock);
5480 out_unlock_osdc:
5481 	up_read(&osdc->lock);
5482 	return m;
5483 }
5484 
5485 static struct ceph_msg *alloc_msg_with_page_vector(struct ceph_msg_header *hdr)
5486 {
5487 	struct ceph_msg *m;
5488 	int type = le16_to_cpu(hdr->type);
5489 	u32 front_len = le32_to_cpu(hdr->front_len);
5490 	u32 data_len = le32_to_cpu(hdr->data_len);
5491 
5492 	m = ceph_msg_new2(type, front_len, 1, GFP_NOIO, false);
5493 	if (!m)
5494 		return NULL;
5495 
5496 	if (data_len) {
5497 		struct page **pages;
5498 
5499 		pages = ceph_alloc_page_vector(calc_pages_for(0, data_len),
5500 					       GFP_NOIO);
5501 		if (IS_ERR(pages)) {
5502 			ceph_msg_put(m);
5503 			return NULL;
5504 		}
5505 
5506 		ceph_msg_data_add_pages(m, pages, data_len, 0, true);
5507 	}
5508 
5509 	return m;
5510 }
5511 
5512 static struct ceph_msg *osd_alloc_msg(struct ceph_connection *con,
5513 				      struct ceph_msg_header *hdr,
5514 				      int *skip)
5515 {
5516 	struct ceph_osd *osd = con->private;
5517 	int type = le16_to_cpu(hdr->type);
5518 
5519 	*skip = 0;
5520 	switch (type) {
5521 	case CEPH_MSG_OSD_MAP:
5522 	case CEPH_MSG_OSD_BACKOFF:
5523 	case CEPH_MSG_WATCH_NOTIFY:
5524 		return alloc_msg_with_page_vector(hdr);
5525 	case CEPH_MSG_OSD_OPREPLY:
5526 		return get_reply(con, hdr, skip);
5527 	default:
5528 		pr_warn("%s osd%d unknown msg type %d, skipping\n", __func__,
5529 			osd->o_osd, type);
5530 		*skip = 1;
5531 		return NULL;
5532 	}
5533 }
5534 
5535 /*
5536  * Wrappers to refcount containing ceph_osd struct
5537  */
5538 static struct ceph_connection *osd_get_con(struct ceph_connection *con)
5539 {
5540 	struct ceph_osd *osd = con->private;
5541 	if (get_osd(osd))
5542 		return con;
5543 	return NULL;
5544 }
5545 
5546 static void osd_put_con(struct ceph_connection *con)
5547 {
5548 	struct ceph_osd *osd = con->private;
5549 	put_osd(osd);
5550 }
5551 
5552 /*
5553  * authentication
5554  */
5555 
5556 /*
5557  * Note: returned pointer is the address of a structure that's
5558  * managed separately.  Caller must *not* attempt to free it.
5559  */
5560 static struct ceph_auth_handshake *
5561 osd_get_authorizer(struct ceph_connection *con, int *proto, int force_new)
5562 {
5563 	struct ceph_osd *o = con->private;
5564 	struct ceph_osd_client *osdc = o->o_osdc;
5565 	struct ceph_auth_client *ac = osdc->client->monc.auth;
5566 	struct ceph_auth_handshake *auth = &o->o_auth;
5567 	int ret;
5568 
5569 	ret = __ceph_auth_get_authorizer(ac, auth, CEPH_ENTITY_TYPE_OSD,
5570 					 force_new, proto, NULL, NULL);
5571 	if (ret)
5572 		return ERR_PTR(ret);
5573 
5574 	return auth;
5575 }
5576 
5577 static int osd_add_authorizer_challenge(struct ceph_connection *con,
5578 				    void *challenge_buf, int challenge_buf_len)
5579 {
5580 	struct ceph_osd *o = con->private;
5581 	struct ceph_osd_client *osdc = o->o_osdc;
5582 	struct ceph_auth_client *ac = osdc->client->monc.auth;
5583 
5584 	return ceph_auth_add_authorizer_challenge(ac, o->o_auth.authorizer,
5585 					    challenge_buf, challenge_buf_len);
5586 }
5587 
5588 static int osd_verify_authorizer_reply(struct ceph_connection *con)
5589 {
5590 	struct ceph_osd *o = con->private;
5591 	struct ceph_osd_client *osdc = o->o_osdc;
5592 	struct ceph_auth_client *ac = osdc->client->monc.auth;
5593 	struct ceph_auth_handshake *auth = &o->o_auth;
5594 
5595 	return ceph_auth_verify_authorizer_reply(ac, auth->authorizer,
5596 		auth->authorizer_reply_buf, auth->authorizer_reply_buf_len,
5597 		NULL, NULL, NULL, NULL);
5598 }
5599 
5600 static int osd_invalidate_authorizer(struct ceph_connection *con)
5601 {
5602 	struct ceph_osd *o = con->private;
5603 	struct ceph_osd_client *osdc = o->o_osdc;
5604 	struct ceph_auth_client *ac = osdc->client->monc.auth;
5605 
5606 	ceph_auth_invalidate_authorizer(ac, CEPH_ENTITY_TYPE_OSD);
5607 	return ceph_monc_validate_auth(&osdc->client->monc);
5608 }
5609 
5610 static int osd_get_auth_request(struct ceph_connection *con,
5611 				void *buf, int *buf_len,
5612 				void **authorizer, int *authorizer_len)
5613 {
5614 	struct ceph_osd *o = con->private;
5615 	struct ceph_auth_client *ac = o->o_osdc->client->monc.auth;
5616 	struct ceph_auth_handshake *auth = &o->o_auth;
5617 	int ret;
5618 
5619 	ret = ceph_auth_get_authorizer(ac, auth, CEPH_ENTITY_TYPE_OSD,
5620 				       buf, buf_len);
5621 	if (ret)
5622 		return ret;
5623 
5624 	*authorizer = auth->authorizer_buf;
5625 	*authorizer_len = auth->authorizer_buf_len;
5626 	return 0;
5627 }
5628 
5629 static int osd_handle_auth_reply_more(struct ceph_connection *con,
5630 				      void *reply, int reply_len,
5631 				      void *buf, int *buf_len,
5632 				      void **authorizer, int *authorizer_len)
5633 {
5634 	struct ceph_osd *o = con->private;
5635 	struct ceph_auth_client *ac = o->o_osdc->client->monc.auth;
5636 	struct ceph_auth_handshake *auth = &o->o_auth;
5637 	int ret;
5638 
5639 	ret = ceph_auth_handle_svc_reply_more(ac, auth, reply, reply_len,
5640 					      buf, buf_len);
5641 	if (ret)
5642 		return ret;
5643 
5644 	*authorizer = auth->authorizer_buf;
5645 	*authorizer_len = auth->authorizer_buf_len;
5646 	return 0;
5647 }
5648 
5649 static int osd_handle_auth_done(struct ceph_connection *con,
5650 				u64 global_id, void *reply, int reply_len,
5651 				u8 *session_key, int *session_key_len,
5652 				u8 *con_secret, int *con_secret_len)
5653 {
5654 	struct ceph_osd *o = con->private;
5655 	struct ceph_auth_client *ac = o->o_osdc->client->monc.auth;
5656 	struct ceph_auth_handshake *auth = &o->o_auth;
5657 
5658 	return ceph_auth_handle_svc_reply_done(ac, auth, reply, reply_len,
5659 					       session_key, session_key_len,
5660 					       con_secret, con_secret_len);
5661 }
5662 
5663 static int osd_handle_auth_bad_method(struct ceph_connection *con,
5664 				      int used_proto, int result,
5665 				      const int *allowed_protos, int proto_cnt,
5666 				      const int *allowed_modes, int mode_cnt)
5667 {
5668 	struct ceph_osd *o = con->private;
5669 	struct ceph_mon_client *monc = &o->o_osdc->client->monc;
5670 	int ret;
5671 
5672 	if (ceph_auth_handle_bad_authorizer(monc->auth, CEPH_ENTITY_TYPE_OSD,
5673 					    used_proto, result,
5674 					    allowed_protos, proto_cnt,
5675 					    allowed_modes, mode_cnt)) {
5676 		ret = ceph_monc_validate_auth(monc);
5677 		if (ret)
5678 			return ret;
5679 	}
5680 
5681 	return -EACCES;
5682 }
5683 
5684 static void osd_reencode_message(struct ceph_msg *msg)
5685 {
5686 	int type = le16_to_cpu(msg->hdr.type);
5687 
5688 	if (type == CEPH_MSG_OSD_OP)
5689 		encode_request_finish(msg);
5690 }
5691 
5692 static int osd_sign_message(struct ceph_msg *msg)
5693 {
5694 	struct ceph_osd *o = msg->con->private;
5695 	struct ceph_auth_handshake *auth = &o->o_auth;
5696 
5697 	return ceph_auth_sign_message(auth, msg);
5698 }
5699 
5700 static int osd_check_message_signature(struct ceph_msg *msg)
5701 {
5702 	struct ceph_osd *o = msg->con->private;
5703 	struct ceph_auth_handshake *auth = &o->o_auth;
5704 
5705 	return ceph_auth_check_message_signature(auth, msg);
5706 }
5707 
5708 static void advance_cursor(struct ceph_msg_data_cursor *cursor, size_t len,
5709 			   bool zero)
5710 {
5711 	while (len) {
5712 		struct page *page;
5713 		size_t poff, plen;
5714 
5715 		page = ceph_msg_data_next(cursor, &poff, &plen);
5716 		if (plen > len)
5717 			plen = len;
5718 		if (zero)
5719 			zero_user_segment(page, poff, poff + plen);
5720 		len -= plen;
5721 		ceph_msg_data_advance(cursor, plen);
5722 	}
5723 }
5724 
5725 static int prep_next_sparse_read(struct ceph_connection *con,
5726 				 struct ceph_msg_data_cursor *cursor)
5727 {
5728 	struct ceph_osd *o = con->private;
5729 	struct ceph_sparse_read *sr = &o->o_sparse_read;
5730 	struct ceph_osd_request *req;
5731 	struct ceph_osd_req_op *op;
5732 
5733 	spin_lock(&o->o_requests_lock);
5734 	req = lookup_request(&o->o_requests, le64_to_cpu(con->in_msg->hdr.tid));
5735 	if (!req) {
5736 		spin_unlock(&o->o_requests_lock);
5737 		return -EBADR;
5738 	}
5739 
5740 	if (o->o_sparse_op_idx < 0) {
5741 		dout("%s: [%d] starting new sparse read req\n",
5742 		     __func__, o->o_osd);
5743 	} else {
5744 		u64 end;
5745 
5746 		op = &req->r_ops[o->o_sparse_op_idx];
5747 
5748 		WARN_ON_ONCE(op->extent.sparse_ext);
5749 
5750 		/* hand back buffer we took earlier */
5751 		op->extent.sparse_ext = sr->sr_extent;
5752 		sr->sr_extent = NULL;
5753 		op->extent.sparse_ext_cnt = sr->sr_count;
5754 		sr->sr_ext_len = 0;
5755 		dout("%s: [%d] completed extent array len %d cursor->resid %zd\n",
5756 		     __func__, o->o_osd, op->extent.sparse_ext_cnt, cursor->resid);
5757 		/* Advance to end of data for this operation */
5758 		end = ceph_sparse_ext_map_end(op);
5759 		if (end < sr->sr_req_len)
5760 			advance_cursor(cursor, sr->sr_req_len - end, false);
5761 	}
5762 
5763 	ceph_init_sparse_read(sr);
5764 
5765 	/* find next op in this request (if any) */
5766 	while (++o->o_sparse_op_idx < req->r_num_ops) {
5767 		op = &req->r_ops[o->o_sparse_op_idx];
5768 		if (op->op == CEPH_OSD_OP_SPARSE_READ)
5769 			goto found;
5770 	}
5771 
5772 	/* reset for next sparse read request */
5773 	spin_unlock(&o->o_requests_lock);
5774 	o->o_sparse_op_idx = -1;
5775 	return 0;
5776 found:
5777 	sr->sr_req_off = op->extent.offset;
5778 	sr->sr_req_len = op->extent.length;
5779 	sr->sr_pos = sr->sr_req_off;
5780 	dout("%s: [%d] new sparse read op at idx %d 0x%llx~0x%llx\n", __func__,
5781 	     o->o_osd, o->o_sparse_op_idx, sr->sr_req_off, sr->sr_req_len);
5782 
5783 	/* hand off request's sparse extent map buffer */
5784 	sr->sr_ext_len = op->extent.sparse_ext_cnt;
5785 	op->extent.sparse_ext_cnt = 0;
5786 	sr->sr_extent = op->extent.sparse_ext;
5787 	op->extent.sparse_ext = NULL;
5788 
5789 	spin_unlock(&o->o_requests_lock);
5790 	return 1;
5791 }
5792 
5793 #ifdef __BIG_ENDIAN
5794 static inline void convert_extent_map(struct ceph_sparse_read *sr)
5795 {
5796 	int i;
5797 
5798 	for (i = 0; i < sr->sr_count; i++) {
5799 		struct ceph_sparse_extent *ext = &sr->sr_extent[i];
5800 
5801 		ext->off = le64_to_cpu((__force __le64)ext->off);
5802 		ext->len = le64_to_cpu((__force __le64)ext->len);
5803 	}
5804 }
5805 #else
5806 static inline void convert_extent_map(struct ceph_sparse_read *sr)
5807 {
5808 }
5809 #endif
5810 
5811 static bool sparse_extent_map_valid(struct ceph_sparse_read *sr)
5812 {
5813 	u64 req_end, pos;
5814 	int i;
5815 
5816 	if (check_add_overflow(sr->sr_req_off, sr->sr_req_len, &req_end))
5817 		return false;
5818 
5819 	pos = sr->sr_req_off;
5820 	for (i = 0; i < sr->sr_count; i++) {
5821 		struct ceph_sparse_extent *ext = &sr->sr_extent[i];
5822 		u64 end;
5823 
5824 		if (ext->off < pos)
5825 			return false;
5826 		if (check_add_overflow(ext->off, ext->len, &end))
5827 			return false;
5828 		if (end > req_end)
5829 			return false;
5830 		pos = end;
5831 	}
5832 
5833 	return true;
5834 }
5835 
5836 static int osd_sparse_read(struct ceph_connection *con,
5837 			   struct ceph_msg_data_cursor *cursor,
5838 			   char **pbuf)
5839 {
5840 	struct ceph_osd *o = con->private;
5841 	struct ceph_sparse_read *sr = &o->o_sparse_read;
5842 	u32 count = sr->sr_count;
5843 	u64 eoff, elen, len = 0;
5844 	int i, ret;
5845 
5846 	switch (sr->sr_state) {
5847 	case CEPH_SPARSE_READ_HDR:
5848 next_op:
5849 		ret = prep_next_sparse_read(con, cursor);
5850 		if (ret <= 0)
5851 			return ret;
5852 
5853 		/* number of extents */
5854 		ret = sizeof(sr->sr_count);
5855 		*pbuf = (char *)&sr->sr_count;
5856 		sr->sr_state = CEPH_SPARSE_READ_EXTENTS;
5857 		break;
5858 	case CEPH_SPARSE_READ_EXTENTS:
5859 		/* Convert sr_count to host-endian */
5860 		count = le32_to_cpu((__force __le32)sr->sr_count);
5861 		sr->sr_count = count;
5862 		dout("[%d] got %u extents\n", o->o_osd, count);
5863 
5864 		if (count > 0) {
5865 			if (!sr->sr_extent || count > sr->sr_ext_len) {
5866 				/* no extent array provided, or too short */
5867 				kfree(sr->sr_extent);
5868 				sr->sr_extent = kmalloc_objs(*sr->sr_extent,
5869 							     count, GFP_NOIO);
5870 				if (!sr->sr_extent) {
5871 					pr_err("%s: failed to allocate %u extents\n",
5872 					       __func__, count);
5873 					return -ENOMEM;
5874 				}
5875 				sr->sr_ext_len = count;
5876 			}
5877 			ret = count * sizeof(*sr->sr_extent);
5878 			*pbuf = (char *)sr->sr_extent;
5879 			sr->sr_state = CEPH_SPARSE_READ_DATA_LEN;
5880 			break;
5881 		}
5882 		/* No extents? Read data len */
5883 		fallthrough;
5884 	case CEPH_SPARSE_READ_DATA_LEN:
5885 		convert_extent_map(sr);
5886 		if (!sparse_extent_map_valid(sr)) {
5887 			pr_warn_ratelimited("invalid sparse extent map\n");
5888 			return -EREMOTEIO;
5889 		}
5890 		ret = sizeof(sr->sr_datalen);
5891 		*pbuf = (char *)&sr->sr_datalen;
5892 		sr->sr_state = CEPH_SPARSE_READ_DATA_PRE;
5893 		break;
5894 	case CEPH_SPARSE_READ_DATA_PRE:
5895 		/* Convert sr_datalen to host-endian */
5896 		sr->sr_datalen = le32_to_cpu((__force __le32)sr->sr_datalen);
5897 		for (i = 0; i < count; i++)
5898 			len += sr->sr_extent[i].len;
5899 		if (sr->sr_datalen != len) {
5900 			pr_warn_ratelimited("data len %u != extent len %llu\n",
5901 					    sr->sr_datalen, len);
5902 			return -EREMOTEIO;
5903 		}
5904 		sr->sr_state = CEPH_SPARSE_READ_DATA;
5905 		fallthrough;
5906 	case CEPH_SPARSE_READ_DATA:
5907 		if (sr->sr_index >= count) {
5908 			sr->sr_state = CEPH_SPARSE_READ_HDR;
5909 			goto next_op;
5910 		}
5911 
5912 		eoff = sr->sr_extent[sr->sr_index].off;
5913 		elen = sr->sr_extent[sr->sr_index].len;
5914 
5915 		dout("[%d] ext %d off 0x%llx len 0x%llx\n",
5916 		     o->o_osd, sr->sr_index, eoff, elen);
5917 
5918 		if (elen > INT_MAX) {
5919 			dout("Sparse read extent length too long (0x%llx)\n",
5920 			     elen);
5921 			return -EREMOTEIO;
5922 		}
5923 
5924 		/* zero out anything from sr_pos to start of extent */
5925 		if (sr->sr_pos < eoff)
5926 			advance_cursor(cursor, eoff - sr->sr_pos, true);
5927 
5928 		/* Set position to end of extent */
5929 		sr->sr_pos = eoff + elen;
5930 
5931 		/* send back the new length and nullify the ptr */
5932 		cursor->sr_resid = elen;
5933 		ret = elen;
5934 		*pbuf = NULL;
5935 
5936 		/* Bump the array index */
5937 		++sr->sr_index;
5938 		break;
5939 	}
5940 	return ret;
5941 }
5942 
5943 static const struct ceph_connection_operations osd_con_ops = {
5944 	.get = osd_get_con,
5945 	.put = osd_put_con,
5946 	.sparse_read = osd_sparse_read,
5947 	.alloc_msg = osd_alloc_msg,
5948 	.dispatch = osd_dispatch,
5949 	.fault = osd_fault,
5950 	.reencode_message = osd_reencode_message,
5951 	.get_authorizer = osd_get_authorizer,
5952 	.add_authorizer_challenge = osd_add_authorizer_challenge,
5953 	.verify_authorizer_reply = osd_verify_authorizer_reply,
5954 	.invalidate_authorizer = osd_invalidate_authorizer,
5955 	.sign_message = osd_sign_message,
5956 	.check_message_signature = osd_check_message_signature,
5957 	.get_auth_request = osd_get_auth_request,
5958 	.handle_auth_reply_more = osd_handle_auth_reply_more,
5959 	.handle_auth_done = osd_handle_auth_done,
5960 	.handle_auth_bad_method = osd_handle_auth_bad_method,
5961 };
5962