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