GNU Linux-libre 4.19.245-gnu1
[releases.git] / net / ceph / messenger.c
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/ceph/ceph_debug.h>
3
4 #include <linux/crc32c.h>
5 #include <linux/ctype.h>
6 #include <linux/highmem.h>
7 #include <linux/inet.h>
8 #include <linux/kthread.h>
9 #include <linux/net.h>
10 #include <linux/nsproxy.h>
11 #include <linux/sched/mm.h>
12 #include <linux/slab.h>
13 #include <linux/socket.h>
14 #include <linux/string.h>
15 #ifdef  CONFIG_BLOCK
16 #include <linux/bio.h>
17 #endif  /* CONFIG_BLOCK */
18 #include <linux/dns_resolver.h>
19 #include <net/tcp.h>
20
21 #include <linux/ceph/ceph_features.h>
22 #include <linux/ceph/libceph.h>
23 #include <linux/ceph/messenger.h>
24 #include <linux/ceph/decode.h>
25 #include <linux/ceph/pagelist.h>
26 #include <linux/export.h>
27
28 /*
29  * Ceph uses the messenger to exchange ceph_msg messages with other
30  * hosts in the system.  The messenger provides ordered and reliable
31  * delivery.  We tolerate TCP disconnects by reconnecting (with
32  * exponential backoff) in the case of a fault (disconnection, bad
33  * crc, protocol error).  Acks allow sent messages to be discarded by
34  * the sender.
35  */
36
37 /*
38  * We track the state of the socket on a given connection using
39  * values defined below.  The transition to a new socket state is
40  * handled by a function which verifies we aren't coming from an
41  * unexpected state.
42  *
43  *      --------
44  *      | NEW* |  transient initial state
45  *      --------
46  *          | con_sock_state_init()
47  *          v
48  *      ----------
49  *      | CLOSED |  initialized, but no socket (and no
50  *      ----------  TCP connection)
51  *       ^      \
52  *       |       \ con_sock_state_connecting()
53  *       |        ----------------------
54  *       |                              \
55  *       + con_sock_state_closed()       \
56  *       |+---------------------------    \
57  *       | \                          \    \
58  *       |  -----------                \    \
59  *       |  | CLOSING |  socket event;  \    \
60  *       |  -----------  await close     \    \
61  *       |       ^                        \   |
62  *       |       |                         \  |
63  *       |       + con_sock_state_closing() \ |
64  *       |      / \                         | |
65  *       |     /   ---------------          | |
66  *       |    /                   \         v v
67  *       |   /                    --------------
68  *       |  /    -----------------| CONNECTING |  socket created, TCP
69  *       |  |   /                 --------------  connect initiated
70  *       |  |   | con_sock_state_connected()
71  *       |  |   v
72  *      -------------
73  *      | CONNECTED |  TCP connection established
74  *      -------------
75  *
76  * State values for ceph_connection->sock_state; NEW is assumed to be 0.
77  */
78
79 #define CON_SOCK_STATE_NEW              0       /* -> CLOSED */
80 #define CON_SOCK_STATE_CLOSED           1       /* -> CONNECTING */
81 #define CON_SOCK_STATE_CONNECTING       2       /* -> CONNECTED or -> CLOSING */
82 #define CON_SOCK_STATE_CONNECTED        3       /* -> CLOSING or -> CLOSED */
83 #define CON_SOCK_STATE_CLOSING          4       /* -> CLOSED */
84
85 /*
86  * connection states
87  */
88 #define CON_STATE_CLOSED        1  /* -> PREOPEN */
89 #define CON_STATE_PREOPEN       2  /* -> CONNECTING, CLOSED */
90 #define CON_STATE_CONNECTING    3  /* -> NEGOTIATING, CLOSED */
91 #define CON_STATE_NEGOTIATING   4  /* -> OPEN, CLOSED */
92 #define CON_STATE_OPEN          5  /* -> STANDBY, CLOSED */
93 #define CON_STATE_STANDBY       6  /* -> PREOPEN, CLOSED */
94
95 /*
96  * ceph_connection flag bits
97  */
98 #define CON_FLAG_LOSSYTX           0  /* we can close channel or drop
99                                        * messages on errors */
100 #define CON_FLAG_KEEPALIVE_PENDING 1  /* we need to send a keepalive */
101 #define CON_FLAG_WRITE_PENDING     2  /* we have data ready to send */
102 #define CON_FLAG_SOCK_CLOSED       3  /* socket state changed to closed */
103 #define CON_FLAG_BACKOFF           4  /* need to retry queuing delayed work */
104
105 static bool con_flag_valid(unsigned long con_flag)
106 {
107         switch (con_flag) {
108         case CON_FLAG_LOSSYTX:
109         case CON_FLAG_KEEPALIVE_PENDING:
110         case CON_FLAG_WRITE_PENDING:
111         case CON_FLAG_SOCK_CLOSED:
112         case CON_FLAG_BACKOFF:
113                 return true;
114         default:
115                 return false;
116         }
117 }
118
119 static void con_flag_clear(struct ceph_connection *con, unsigned long con_flag)
120 {
121         BUG_ON(!con_flag_valid(con_flag));
122
123         clear_bit(con_flag, &con->flags);
124 }
125
126 static void con_flag_set(struct ceph_connection *con, unsigned long con_flag)
127 {
128         BUG_ON(!con_flag_valid(con_flag));
129
130         set_bit(con_flag, &con->flags);
131 }
132
133 static bool con_flag_test(struct ceph_connection *con, unsigned long con_flag)
134 {
135         BUG_ON(!con_flag_valid(con_flag));
136
137         return test_bit(con_flag, &con->flags);
138 }
139
140 static bool con_flag_test_and_clear(struct ceph_connection *con,
141                                         unsigned long con_flag)
142 {
143         BUG_ON(!con_flag_valid(con_flag));
144
145         return test_and_clear_bit(con_flag, &con->flags);
146 }
147
148 static bool con_flag_test_and_set(struct ceph_connection *con,
149                                         unsigned long con_flag)
150 {
151         BUG_ON(!con_flag_valid(con_flag));
152
153         return test_and_set_bit(con_flag, &con->flags);
154 }
155
156 /* Slab caches for frequently-allocated structures */
157
158 static struct kmem_cache        *ceph_msg_cache;
159 static struct kmem_cache        *ceph_msg_data_cache;
160
161 /* static tag bytes (protocol control messages) */
162 static char tag_msg = CEPH_MSGR_TAG_MSG;
163 static char tag_ack = CEPH_MSGR_TAG_ACK;
164 static char tag_keepalive = CEPH_MSGR_TAG_KEEPALIVE;
165 static char tag_keepalive2 = CEPH_MSGR_TAG_KEEPALIVE2;
166
167 #ifdef CONFIG_LOCKDEP
168 static struct lock_class_key socket_class;
169 #endif
170
171 static void queue_con(struct ceph_connection *con);
172 static void cancel_con(struct ceph_connection *con);
173 static void ceph_con_workfn(struct work_struct *);
174 static void con_fault(struct ceph_connection *con);
175
176 /*
177  * Nicely render a sockaddr as a string.  An array of formatted
178  * strings is used, to approximate reentrancy.
179  */
180 #define ADDR_STR_COUNT_LOG      5       /* log2(# address strings in array) */
181 #define ADDR_STR_COUNT          (1 << ADDR_STR_COUNT_LOG)
182 #define ADDR_STR_COUNT_MASK     (ADDR_STR_COUNT - 1)
183 #define MAX_ADDR_STR_LEN        64      /* 54 is enough */
184
185 static char addr_str[ADDR_STR_COUNT][MAX_ADDR_STR_LEN];
186 static atomic_t addr_str_seq = ATOMIC_INIT(0);
187
188 static struct page *zero_page;          /* used in certain error cases */
189
190 const char *ceph_pr_addr(const struct sockaddr_storage *ss)
191 {
192         int i;
193         char *s;
194         struct sockaddr_in *in4 = (struct sockaddr_in *) ss;
195         struct sockaddr_in6 *in6 = (struct sockaddr_in6 *) ss;
196
197         i = atomic_inc_return(&addr_str_seq) & ADDR_STR_COUNT_MASK;
198         s = addr_str[i];
199
200         switch (ss->ss_family) {
201         case AF_INET:
202                 snprintf(s, MAX_ADDR_STR_LEN, "%pI4:%hu", &in4->sin_addr,
203                          ntohs(in4->sin_port));
204                 break;
205
206         case AF_INET6:
207                 snprintf(s, MAX_ADDR_STR_LEN, "[%pI6c]:%hu", &in6->sin6_addr,
208                          ntohs(in6->sin6_port));
209                 break;
210
211         default:
212                 snprintf(s, MAX_ADDR_STR_LEN, "(unknown sockaddr family %hu)",
213                          ss->ss_family);
214         }
215
216         return s;
217 }
218 EXPORT_SYMBOL(ceph_pr_addr);
219
220 static void encode_my_addr(struct ceph_messenger *msgr)
221 {
222         memcpy(&msgr->my_enc_addr, &msgr->inst.addr, sizeof(msgr->my_enc_addr));
223         ceph_encode_addr(&msgr->my_enc_addr);
224 }
225
226 /*
227  * work queue for all reading and writing to/from the socket.
228  */
229 static struct workqueue_struct *ceph_msgr_wq;
230
231 static int ceph_msgr_slab_init(void)
232 {
233         BUG_ON(ceph_msg_cache);
234         ceph_msg_cache = KMEM_CACHE(ceph_msg, 0);
235         if (!ceph_msg_cache)
236                 return -ENOMEM;
237
238         BUG_ON(ceph_msg_data_cache);
239         ceph_msg_data_cache = KMEM_CACHE(ceph_msg_data, 0);
240         if (ceph_msg_data_cache)
241                 return 0;
242
243         kmem_cache_destroy(ceph_msg_cache);
244         ceph_msg_cache = NULL;
245
246         return -ENOMEM;
247 }
248
249 static void ceph_msgr_slab_exit(void)
250 {
251         BUG_ON(!ceph_msg_data_cache);
252         kmem_cache_destroy(ceph_msg_data_cache);
253         ceph_msg_data_cache = NULL;
254
255         BUG_ON(!ceph_msg_cache);
256         kmem_cache_destroy(ceph_msg_cache);
257         ceph_msg_cache = NULL;
258 }
259
260 static void _ceph_msgr_exit(void)
261 {
262         if (ceph_msgr_wq) {
263                 destroy_workqueue(ceph_msgr_wq);
264                 ceph_msgr_wq = NULL;
265         }
266
267         BUG_ON(zero_page == NULL);
268         put_page(zero_page);
269         zero_page = NULL;
270
271         ceph_msgr_slab_exit();
272 }
273
274 int __init ceph_msgr_init(void)
275 {
276         if (ceph_msgr_slab_init())
277                 return -ENOMEM;
278
279         BUG_ON(zero_page != NULL);
280         zero_page = ZERO_PAGE(0);
281         get_page(zero_page);
282
283         /*
284          * The number of active work items is limited by the number of
285          * connections, so leave @max_active at default.
286          */
287         ceph_msgr_wq = alloc_workqueue("ceph-msgr", WQ_MEM_RECLAIM, 0);
288         if (ceph_msgr_wq)
289                 return 0;
290
291         pr_err("msgr_init failed to create workqueue\n");
292         _ceph_msgr_exit();
293
294         return -ENOMEM;
295 }
296
297 void ceph_msgr_exit(void)
298 {
299         BUG_ON(ceph_msgr_wq == NULL);
300
301         _ceph_msgr_exit();
302 }
303
304 void ceph_msgr_flush(void)
305 {
306         flush_workqueue(ceph_msgr_wq);
307 }
308 EXPORT_SYMBOL(ceph_msgr_flush);
309
310 /* Connection socket state transition functions */
311
312 static void con_sock_state_init(struct ceph_connection *con)
313 {
314         int old_state;
315
316         old_state = atomic_xchg(&con->sock_state, CON_SOCK_STATE_CLOSED);
317         if (WARN_ON(old_state != CON_SOCK_STATE_NEW))
318                 printk("%s: unexpected old state %d\n", __func__, old_state);
319         dout("%s con %p sock %d -> %d\n", __func__, con, old_state,
320              CON_SOCK_STATE_CLOSED);
321 }
322
323 static void con_sock_state_connecting(struct ceph_connection *con)
324 {
325         int old_state;
326
327         old_state = atomic_xchg(&con->sock_state, CON_SOCK_STATE_CONNECTING);
328         if (WARN_ON(old_state != CON_SOCK_STATE_CLOSED))
329                 printk("%s: unexpected old state %d\n", __func__, old_state);
330         dout("%s con %p sock %d -> %d\n", __func__, con, old_state,
331              CON_SOCK_STATE_CONNECTING);
332 }
333
334 static void con_sock_state_connected(struct ceph_connection *con)
335 {
336         int old_state;
337
338         old_state = atomic_xchg(&con->sock_state, CON_SOCK_STATE_CONNECTED);
339         if (WARN_ON(old_state != CON_SOCK_STATE_CONNECTING))
340                 printk("%s: unexpected old state %d\n", __func__, old_state);
341         dout("%s con %p sock %d -> %d\n", __func__, con, old_state,
342              CON_SOCK_STATE_CONNECTED);
343 }
344
345 static void con_sock_state_closing(struct ceph_connection *con)
346 {
347         int old_state;
348
349         old_state = atomic_xchg(&con->sock_state, CON_SOCK_STATE_CLOSING);
350         if (WARN_ON(old_state != CON_SOCK_STATE_CONNECTING &&
351                         old_state != CON_SOCK_STATE_CONNECTED &&
352                         old_state != CON_SOCK_STATE_CLOSING))
353                 printk("%s: unexpected old state %d\n", __func__, old_state);
354         dout("%s con %p sock %d -> %d\n", __func__, con, old_state,
355              CON_SOCK_STATE_CLOSING);
356 }
357
358 static void con_sock_state_closed(struct ceph_connection *con)
359 {
360         int old_state;
361
362         old_state = atomic_xchg(&con->sock_state, CON_SOCK_STATE_CLOSED);
363         if (WARN_ON(old_state != CON_SOCK_STATE_CONNECTED &&
364                     old_state != CON_SOCK_STATE_CLOSING &&
365                     old_state != CON_SOCK_STATE_CONNECTING &&
366                     old_state != CON_SOCK_STATE_CLOSED))
367                 printk("%s: unexpected old state %d\n", __func__, old_state);
368         dout("%s con %p sock %d -> %d\n", __func__, con, old_state,
369              CON_SOCK_STATE_CLOSED);
370 }
371
372 /*
373  * socket callback functions
374  */
375
376 /* data available on socket, or listen socket received a connect */
377 static void ceph_sock_data_ready(struct sock *sk)
378 {
379         struct ceph_connection *con = sk->sk_user_data;
380         if (atomic_read(&con->msgr->stopping)) {
381                 return;
382         }
383
384         if (sk->sk_state != TCP_CLOSE_WAIT) {
385                 dout("%s on %p state = %lu, queueing work\n", __func__,
386                      con, con->state);
387                 queue_con(con);
388         }
389 }
390
391 /* socket has buffer space for writing */
392 static void ceph_sock_write_space(struct sock *sk)
393 {
394         struct ceph_connection *con = sk->sk_user_data;
395
396         /* only queue to workqueue if there is data we want to write,
397          * and there is sufficient space in the socket buffer to accept
398          * more data.  clear SOCK_NOSPACE so that ceph_sock_write_space()
399          * doesn't get called again until try_write() fills the socket
400          * buffer. See net/ipv4/tcp_input.c:tcp_check_space()
401          * and net/core/stream.c:sk_stream_write_space().
402          */
403         if (con_flag_test(con, CON_FLAG_WRITE_PENDING)) {
404                 if (sk_stream_is_writeable(sk)) {
405                         dout("%s %p queueing write work\n", __func__, con);
406                         clear_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
407                         queue_con(con);
408                 }
409         } else {
410                 dout("%s %p nothing to write\n", __func__, con);
411         }
412 }
413
414 /* socket's state has changed */
415 static void ceph_sock_state_change(struct sock *sk)
416 {
417         struct ceph_connection *con = sk->sk_user_data;
418
419         dout("%s %p state = %lu sk_state = %u\n", __func__,
420              con, con->state, sk->sk_state);
421
422         switch (sk->sk_state) {
423         case TCP_CLOSE:
424                 dout("%s TCP_CLOSE\n", __func__);
425                 /* fall through */
426         case TCP_CLOSE_WAIT:
427                 dout("%s TCP_CLOSE_WAIT\n", __func__);
428                 con_sock_state_closing(con);
429                 con_flag_set(con, CON_FLAG_SOCK_CLOSED);
430                 queue_con(con);
431                 break;
432         case TCP_ESTABLISHED:
433                 dout("%s TCP_ESTABLISHED\n", __func__);
434                 con_sock_state_connected(con);
435                 queue_con(con);
436                 break;
437         default:        /* Everything else is uninteresting */
438                 break;
439         }
440 }
441
442 /*
443  * set up socket callbacks
444  */
445 static void set_sock_callbacks(struct socket *sock,
446                                struct ceph_connection *con)
447 {
448         struct sock *sk = sock->sk;
449         sk->sk_user_data = con;
450         sk->sk_data_ready = ceph_sock_data_ready;
451         sk->sk_write_space = ceph_sock_write_space;
452         sk->sk_state_change = ceph_sock_state_change;
453 }
454
455
456 /*
457  * socket helpers
458  */
459
460 /*
461  * initiate connection to a remote socket.
462  */
463 static int ceph_tcp_connect(struct ceph_connection *con)
464 {
465         struct sockaddr_storage *paddr = &con->peer_addr.in_addr;
466         struct socket *sock;
467         unsigned int noio_flag;
468         int ret;
469
470         BUG_ON(con->sock);
471
472         /* sock_create_kern() allocates with GFP_KERNEL */
473         noio_flag = memalloc_noio_save();
474         ret = sock_create_kern(read_pnet(&con->msgr->net), paddr->ss_family,
475                                SOCK_STREAM, IPPROTO_TCP, &sock);
476         memalloc_noio_restore(noio_flag);
477         if (ret)
478                 return ret;
479         sock->sk->sk_allocation = GFP_NOFS;
480
481 #ifdef CONFIG_LOCKDEP
482         lockdep_set_class(&sock->sk->sk_lock, &socket_class);
483 #endif
484
485         set_sock_callbacks(sock, con);
486
487         dout("connect %s\n", ceph_pr_addr(&con->peer_addr.in_addr));
488
489         con_sock_state_connecting(con);
490         ret = sock->ops->connect(sock, (struct sockaddr *)paddr, sizeof(*paddr),
491                                  O_NONBLOCK);
492         if (ret == -EINPROGRESS) {
493                 dout("connect %s EINPROGRESS sk_state = %u\n",
494                      ceph_pr_addr(&con->peer_addr.in_addr),
495                      sock->sk->sk_state);
496         } else if (ret < 0) {
497                 pr_err("connect %s error %d\n",
498                        ceph_pr_addr(&con->peer_addr.in_addr), ret);
499                 sock_release(sock);
500                 return ret;
501         }
502
503         if (ceph_test_opt(from_msgr(con->msgr), TCP_NODELAY)) {
504                 int optval = 1;
505
506                 ret = kernel_setsockopt(sock, SOL_TCP, TCP_NODELAY,
507                                         (char *)&optval, sizeof(optval));
508                 if (ret)
509                         pr_err("kernel_setsockopt(TCP_NODELAY) failed: %d",
510                                ret);
511         }
512
513         con->sock = sock;
514         return 0;
515 }
516
517 /*
518  * If @buf is NULL, discard up to @len bytes.
519  */
520 static int ceph_tcp_recvmsg(struct socket *sock, void *buf, size_t len)
521 {
522         struct kvec iov = {buf, len};
523         struct msghdr msg = { .msg_flags = MSG_DONTWAIT | MSG_NOSIGNAL };
524         int r;
525
526         if (!buf)
527                 msg.msg_flags |= MSG_TRUNC;
528
529         iov_iter_kvec(&msg.msg_iter, READ | ITER_KVEC, &iov, 1, len);
530         r = sock_recvmsg(sock, &msg, msg.msg_flags);
531         if (r == -EAGAIN)
532                 r = 0;
533         return r;
534 }
535
536 static int ceph_tcp_recvpage(struct socket *sock, struct page *page,
537                      int page_offset, size_t length)
538 {
539         struct bio_vec bvec = {
540                 .bv_page = page,
541                 .bv_offset = page_offset,
542                 .bv_len = length
543         };
544         struct msghdr msg = { .msg_flags = MSG_DONTWAIT | MSG_NOSIGNAL };
545         int r;
546
547         BUG_ON(page_offset + length > PAGE_SIZE);
548         iov_iter_bvec(&msg.msg_iter, READ | ITER_BVEC, &bvec, 1, length);
549         r = sock_recvmsg(sock, &msg, msg.msg_flags);
550         if (r == -EAGAIN)
551                 r = 0;
552         return r;
553 }
554
555 /*
556  * write something.  @more is true if caller will be sending more data
557  * shortly.
558  */
559 static int ceph_tcp_sendmsg(struct socket *sock, struct kvec *iov,
560                      size_t kvlen, size_t len, int more)
561 {
562         struct msghdr msg = { .msg_flags = MSG_DONTWAIT | MSG_NOSIGNAL };
563         int r;
564
565         if (more)
566                 msg.msg_flags |= MSG_MORE;
567         else
568                 msg.msg_flags |= MSG_EOR;  /* superfluous, but what the hell */
569
570         r = kernel_sendmsg(sock, &msg, iov, kvlen, len);
571         if (r == -EAGAIN)
572                 r = 0;
573         return r;
574 }
575
576 static int __ceph_tcp_sendpage(struct socket *sock, struct page *page,
577                      int offset, size_t size, bool more)
578 {
579         int flags = MSG_DONTWAIT | MSG_NOSIGNAL | (more ? MSG_MORE : MSG_EOR);
580         int ret;
581
582         ret = kernel_sendpage(sock, page, offset, size, flags);
583         if (ret == -EAGAIN)
584                 ret = 0;
585
586         return ret;
587 }
588
589 static int ceph_tcp_sendpage(struct socket *sock, struct page *page,
590                      int offset, size_t size, bool more)
591 {
592         struct msghdr msg = { .msg_flags = MSG_DONTWAIT | MSG_NOSIGNAL };
593         struct bio_vec bvec;
594         int ret;
595
596         /*
597          * sendpage cannot properly handle pages with page_count == 0,
598          * we need to fall back to sendmsg if that's the case.
599          *
600          * Same goes for slab pages: skb_can_coalesce() allows
601          * coalescing neighboring slab objects into a single frag which
602          * triggers one of hardened usercopy checks.
603          */
604         if (page_count(page) >= 1 && !PageSlab(page))
605                 return __ceph_tcp_sendpage(sock, page, offset, size, more);
606
607         bvec.bv_page = page;
608         bvec.bv_offset = offset;
609         bvec.bv_len = size;
610
611         if (more)
612                 msg.msg_flags |= MSG_MORE;
613         else
614                 msg.msg_flags |= MSG_EOR;  /* superfluous, but what the hell */
615
616         iov_iter_bvec(&msg.msg_iter, WRITE | ITER_BVEC, &bvec, 1, size);
617         ret = sock_sendmsg(sock, &msg);
618         if (ret == -EAGAIN)
619                 ret = 0;
620
621         return ret;
622 }
623
624 /*
625  * Shutdown/close the socket for the given connection.
626  */
627 static int con_close_socket(struct ceph_connection *con)
628 {
629         int rc = 0;
630
631         dout("con_close_socket on %p sock %p\n", con, con->sock);
632         if (con->sock) {
633                 rc = con->sock->ops->shutdown(con->sock, SHUT_RDWR);
634                 sock_release(con->sock);
635                 con->sock = NULL;
636         }
637
638         /*
639          * Forcibly clear the SOCK_CLOSED flag.  It gets set
640          * independent of the connection mutex, and we could have
641          * received a socket close event before we had the chance to
642          * shut the socket down.
643          */
644         con_flag_clear(con, CON_FLAG_SOCK_CLOSED);
645
646         con_sock_state_closed(con);
647         return rc;
648 }
649
650 /*
651  * Reset a connection.  Discard all incoming and outgoing messages
652  * and clear *_seq state.
653  */
654 static void ceph_msg_remove(struct ceph_msg *msg)
655 {
656         list_del_init(&msg->list_head);
657
658         ceph_msg_put(msg);
659 }
660 static void ceph_msg_remove_list(struct list_head *head)
661 {
662         while (!list_empty(head)) {
663                 struct ceph_msg *msg = list_first_entry(head, struct ceph_msg,
664                                                         list_head);
665                 ceph_msg_remove(msg);
666         }
667 }
668
669 static void reset_connection(struct ceph_connection *con)
670 {
671         /* reset connection, out_queue, msg_ and connect_seq */
672         /* discard existing out_queue and msg_seq */
673         dout("reset_connection %p\n", con);
674         ceph_msg_remove_list(&con->out_queue);
675         ceph_msg_remove_list(&con->out_sent);
676
677         if (con->in_msg) {
678                 BUG_ON(con->in_msg->con != con);
679                 ceph_msg_put(con->in_msg);
680                 con->in_msg = NULL;
681         }
682
683         con->connect_seq = 0;
684         con->out_seq = 0;
685         if (con->out_msg) {
686                 BUG_ON(con->out_msg->con != con);
687                 ceph_msg_put(con->out_msg);
688                 con->out_msg = NULL;
689         }
690         con->in_seq = 0;
691         con->in_seq_acked = 0;
692
693         con->out_skip = 0;
694 }
695
696 /*
697  * mark a peer down.  drop any open connections.
698  */
699 void ceph_con_close(struct ceph_connection *con)
700 {
701         mutex_lock(&con->mutex);
702         dout("con_close %p peer %s\n", con,
703              ceph_pr_addr(&con->peer_addr.in_addr));
704         con->state = CON_STATE_CLOSED;
705
706         con_flag_clear(con, CON_FLAG_LOSSYTX);  /* so we retry next connect */
707         con_flag_clear(con, CON_FLAG_KEEPALIVE_PENDING);
708         con_flag_clear(con, CON_FLAG_WRITE_PENDING);
709         con_flag_clear(con, CON_FLAG_BACKOFF);
710
711         reset_connection(con);
712         con->peer_global_seq = 0;
713         cancel_con(con);
714         con_close_socket(con);
715         mutex_unlock(&con->mutex);
716 }
717 EXPORT_SYMBOL(ceph_con_close);
718
719 /*
720  * Reopen a closed connection, with a new peer address.
721  */
722 void ceph_con_open(struct ceph_connection *con,
723                    __u8 entity_type, __u64 entity_num,
724                    struct ceph_entity_addr *addr)
725 {
726         mutex_lock(&con->mutex);
727         dout("con_open %p %s\n", con, ceph_pr_addr(&addr->in_addr));
728
729         WARN_ON(con->state != CON_STATE_CLOSED);
730         con->state = CON_STATE_PREOPEN;
731
732         con->peer_name.type = (__u8) entity_type;
733         con->peer_name.num = cpu_to_le64(entity_num);
734
735         memcpy(&con->peer_addr, addr, sizeof(*addr));
736         con->delay = 0;      /* reset backoff memory */
737         mutex_unlock(&con->mutex);
738         queue_con(con);
739 }
740 EXPORT_SYMBOL(ceph_con_open);
741
742 /*
743  * return true if this connection ever successfully opened
744  */
745 bool ceph_con_opened(struct ceph_connection *con)
746 {
747         return con->connect_seq > 0;
748 }
749
750 /*
751  * initialize a new connection.
752  */
753 void ceph_con_init(struct ceph_connection *con, void *private,
754         const struct ceph_connection_operations *ops,
755         struct ceph_messenger *msgr)
756 {
757         dout("con_init %p\n", con);
758         memset(con, 0, sizeof(*con));
759         con->private = private;
760         con->ops = ops;
761         con->msgr = msgr;
762
763         con_sock_state_init(con);
764
765         mutex_init(&con->mutex);
766         INIT_LIST_HEAD(&con->out_queue);
767         INIT_LIST_HEAD(&con->out_sent);
768         INIT_DELAYED_WORK(&con->work, ceph_con_workfn);
769
770         con->state = CON_STATE_CLOSED;
771 }
772 EXPORT_SYMBOL(ceph_con_init);
773
774
775 /*
776  * We maintain a global counter to order connection attempts.  Get
777  * a unique seq greater than @gt.
778  */
779 static u32 get_global_seq(struct ceph_messenger *msgr, u32 gt)
780 {
781         u32 ret;
782
783         spin_lock(&msgr->global_seq_lock);
784         if (msgr->global_seq < gt)
785                 msgr->global_seq = gt;
786         ret = ++msgr->global_seq;
787         spin_unlock(&msgr->global_seq_lock);
788         return ret;
789 }
790
791 static void con_out_kvec_reset(struct ceph_connection *con)
792 {
793         BUG_ON(con->out_skip);
794
795         con->out_kvec_left = 0;
796         con->out_kvec_bytes = 0;
797         con->out_kvec_cur = &con->out_kvec[0];
798 }
799
800 static void con_out_kvec_add(struct ceph_connection *con,
801                                 size_t size, void *data)
802 {
803         int index = con->out_kvec_left;
804
805         BUG_ON(con->out_skip);
806         BUG_ON(index >= ARRAY_SIZE(con->out_kvec));
807
808         con->out_kvec[index].iov_len = size;
809         con->out_kvec[index].iov_base = data;
810         con->out_kvec_left++;
811         con->out_kvec_bytes += size;
812 }
813
814 /*
815  * Chop off a kvec from the end.  Return residual number of bytes for
816  * that kvec, i.e. how many bytes would have been written if the kvec
817  * hadn't been nuked.
818  */
819 static int con_out_kvec_skip(struct ceph_connection *con)
820 {
821         int off = con->out_kvec_cur - con->out_kvec;
822         int skip = 0;
823
824         if (con->out_kvec_bytes > 0) {
825                 skip = con->out_kvec[off + con->out_kvec_left - 1].iov_len;
826                 BUG_ON(con->out_kvec_bytes < skip);
827                 BUG_ON(!con->out_kvec_left);
828                 con->out_kvec_bytes -= skip;
829                 con->out_kvec_left--;
830         }
831
832         return skip;
833 }
834
835 #ifdef CONFIG_BLOCK
836
837 /*
838  * For a bio data item, a piece is whatever remains of the next
839  * entry in the current bio iovec, or the first entry in the next
840  * bio in the list.
841  */
842 static void ceph_msg_data_bio_cursor_init(struct ceph_msg_data_cursor *cursor,
843                                         size_t length)
844 {
845         struct ceph_msg_data *data = cursor->data;
846         struct ceph_bio_iter *it = &cursor->bio_iter;
847
848         cursor->resid = min_t(size_t, length, data->bio_length);
849         *it = data->bio_pos;
850         if (cursor->resid < it->iter.bi_size)
851                 it->iter.bi_size = cursor->resid;
852
853         BUG_ON(cursor->resid < bio_iter_len(it->bio, it->iter));
854         cursor->last_piece = cursor->resid == bio_iter_len(it->bio, it->iter);
855 }
856
857 static struct page *ceph_msg_data_bio_next(struct ceph_msg_data_cursor *cursor,
858                                                 size_t *page_offset,
859                                                 size_t *length)
860 {
861         struct bio_vec bv = bio_iter_iovec(cursor->bio_iter.bio,
862                                            cursor->bio_iter.iter);
863
864         *page_offset = bv.bv_offset;
865         *length = bv.bv_len;
866         return bv.bv_page;
867 }
868
869 static bool ceph_msg_data_bio_advance(struct ceph_msg_data_cursor *cursor,
870                                         size_t bytes)
871 {
872         struct ceph_bio_iter *it = &cursor->bio_iter;
873
874         BUG_ON(bytes > cursor->resid);
875         BUG_ON(bytes > bio_iter_len(it->bio, it->iter));
876         cursor->resid -= bytes;
877         bio_advance_iter(it->bio, &it->iter, bytes);
878
879         if (!cursor->resid) {
880                 BUG_ON(!cursor->last_piece);
881                 return false;   /* no more data */
882         }
883
884         if (!bytes || (it->iter.bi_size && it->iter.bi_bvec_done))
885                 return false;   /* more bytes to process in this segment */
886
887         if (!it->iter.bi_size) {
888                 it->bio = it->bio->bi_next;
889                 it->iter = it->bio->bi_iter;
890                 if (cursor->resid < it->iter.bi_size)
891                         it->iter.bi_size = cursor->resid;
892         }
893
894         BUG_ON(cursor->last_piece);
895         BUG_ON(cursor->resid < bio_iter_len(it->bio, it->iter));
896         cursor->last_piece = cursor->resid == bio_iter_len(it->bio, it->iter);
897         return true;
898 }
899 #endif /* CONFIG_BLOCK */
900
901 static void ceph_msg_data_bvecs_cursor_init(struct ceph_msg_data_cursor *cursor,
902                                         size_t length)
903 {
904         struct ceph_msg_data *data = cursor->data;
905         struct bio_vec *bvecs = data->bvec_pos.bvecs;
906
907         cursor->resid = min_t(size_t, length, data->bvec_pos.iter.bi_size);
908         cursor->bvec_iter = data->bvec_pos.iter;
909         cursor->bvec_iter.bi_size = cursor->resid;
910
911         BUG_ON(cursor->resid < bvec_iter_len(bvecs, cursor->bvec_iter));
912         cursor->last_piece =
913             cursor->resid == bvec_iter_len(bvecs, cursor->bvec_iter);
914 }
915
916 static struct page *ceph_msg_data_bvecs_next(struct ceph_msg_data_cursor *cursor,
917                                                 size_t *page_offset,
918                                                 size_t *length)
919 {
920         struct bio_vec bv = bvec_iter_bvec(cursor->data->bvec_pos.bvecs,
921                                            cursor->bvec_iter);
922
923         *page_offset = bv.bv_offset;
924         *length = bv.bv_len;
925         return bv.bv_page;
926 }
927
928 static bool ceph_msg_data_bvecs_advance(struct ceph_msg_data_cursor *cursor,
929                                         size_t bytes)
930 {
931         struct bio_vec *bvecs = cursor->data->bvec_pos.bvecs;
932
933         BUG_ON(bytes > cursor->resid);
934         BUG_ON(bytes > bvec_iter_len(bvecs, cursor->bvec_iter));
935         cursor->resid -= bytes;
936         bvec_iter_advance(bvecs, &cursor->bvec_iter, bytes);
937
938         if (!cursor->resid) {
939                 BUG_ON(!cursor->last_piece);
940                 return false;   /* no more data */
941         }
942
943         if (!bytes || cursor->bvec_iter.bi_bvec_done)
944                 return false;   /* more bytes to process in this segment */
945
946         BUG_ON(cursor->last_piece);
947         BUG_ON(cursor->resid < bvec_iter_len(bvecs, cursor->bvec_iter));
948         cursor->last_piece =
949             cursor->resid == bvec_iter_len(bvecs, cursor->bvec_iter);
950         return true;
951 }
952
953 /*
954  * For a page array, a piece comes from the first page in the array
955  * that has not already been fully consumed.
956  */
957 static void ceph_msg_data_pages_cursor_init(struct ceph_msg_data_cursor *cursor,
958                                         size_t length)
959 {
960         struct ceph_msg_data *data = cursor->data;
961         int page_count;
962
963         BUG_ON(data->type != CEPH_MSG_DATA_PAGES);
964
965         BUG_ON(!data->pages);
966         BUG_ON(!data->length);
967
968         cursor->resid = min(length, data->length);
969         page_count = calc_pages_for(data->alignment, (u64)data->length);
970         cursor->page_offset = data->alignment & ~PAGE_MASK;
971         cursor->page_index = 0;
972         BUG_ON(page_count > (int)USHRT_MAX);
973         cursor->page_count = (unsigned short)page_count;
974         BUG_ON(length > SIZE_MAX - cursor->page_offset);
975         cursor->last_piece = cursor->page_offset + cursor->resid <= PAGE_SIZE;
976 }
977
978 static struct page *
979 ceph_msg_data_pages_next(struct ceph_msg_data_cursor *cursor,
980                                         size_t *page_offset, size_t *length)
981 {
982         struct ceph_msg_data *data = cursor->data;
983
984         BUG_ON(data->type != CEPH_MSG_DATA_PAGES);
985
986         BUG_ON(cursor->page_index >= cursor->page_count);
987         BUG_ON(cursor->page_offset >= PAGE_SIZE);
988
989         *page_offset = cursor->page_offset;
990         if (cursor->last_piece)
991                 *length = cursor->resid;
992         else
993                 *length = PAGE_SIZE - *page_offset;
994
995         return data->pages[cursor->page_index];
996 }
997
998 static bool ceph_msg_data_pages_advance(struct ceph_msg_data_cursor *cursor,
999                                                 size_t bytes)
1000 {
1001         BUG_ON(cursor->data->type != CEPH_MSG_DATA_PAGES);
1002
1003         BUG_ON(cursor->page_offset + bytes > PAGE_SIZE);
1004
1005         /* Advance the cursor page offset */
1006
1007         cursor->resid -= bytes;
1008         cursor->page_offset = (cursor->page_offset + bytes) & ~PAGE_MASK;
1009         if (!bytes || cursor->page_offset)
1010                 return false;   /* more bytes to process in the current page */
1011
1012         if (!cursor->resid)
1013                 return false;   /* no more data */
1014
1015         /* Move on to the next page; offset is already at 0 */
1016
1017         BUG_ON(cursor->page_index >= cursor->page_count);
1018         cursor->page_index++;
1019         cursor->last_piece = cursor->resid <= PAGE_SIZE;
1020
1021         return true;
1022 }
1023
1024 /*
1025  * For a pagelist, a piece is whatever remains to be consumed in the
1026  * first page in the list, or the front of the next page.
1027  */
1028 static void
1029 ceph_msg_data_pagelist_cursor_init(struct ceph_msg_data_cursor *cursor,
1030                                         size_t length)
1031 {
1032         struct ceph_msg_data *data = cursor->data;
1033         struct ceph_pagelist *pagelist;
1034         struct page *page;
1035
1036         BUG_ON(data->type != CEPH_MSG_DATA_PAGELIST);
1037
1038         pagelist = data->pagelist;
1039         BUG_ON(!pagelist);
1040
1041         if (!length)
1042                 return;         /* pagelist can be assigned but empty */
1043
1044         BUG_ON(list_empty(&pagelist->head));
1045         page = list_first_entry(&pagelist->head, struct page, lru);
1046
1047         cursor->resid = min(length, pagelist->length);
1048         cursor->page = page;
1049         cursor->offset = 0;
1050         cursor->last_piece = cursor->resid <= PAGE_SIZE;
1051 }
1052
1053 static struct page *
1054 ceph_msg_data_pagelist_next(struct ceph_msg_data_cursor *cursor,
1055                                 size_t *page_offset, size_t *length)
1056 {
1057         struct ceph_msg_data *data = cursor->data;
1058         struct ceph_pagelist *pagelist;
1059
1060         BUG_ON(data->type != CEPH_MSG_DATA_PAGELIST);
1061
1062         pagelist = data->pagelist;
1063         BUG_ON(!pagelist);
1064
1065         BUG_ON(!cursor->page);
1066         BUG_ON(cursor->offset + cursor->resid != pagelist->length);
1067
1068         /* offset of first page in pagelist is always 0 */
1069         *page_offset = cursor->offset & ~PAGE_MASK;
1070         if (cursor->last_piece)
1071                 *length = cursor->resid;
1072         else
1073                 *length = PAGE_SIZE - *page_offset;
1074
1075         return cursor->page;
1076 }
1077
1078 static bool ceph_msg_data_pagelist_advance(struct ceph_msg_data_cursor *cursor,
1079                                                 size_t bytes)
1080 {
1081         struct ceph_msg_data *data = cursor->data;
1082         struct ceph_pagelist *pagelist;
1083
1084         BUG_ON(data->type != CEPH_MSG_DATA_PAGELIST);
1085
1086         pagelist = data->pagelist;
1087         BUG_ON(!pagelist);
1088
1089         BUG_ON(cursor->offset + cursor->resid != pagelist->length);
1090         BUG_ON((cursor->offset & ~PAGE_MASK) + bytes > PAGE_SIZE);
1091
1092         /* Advance the cursor offset */
1093
1094         cursor->resid -= bytes;
1095         cursor->offset += bytes;
1096         /* offset of first page in pagelist is always 0 */
1097         if (!bytes || cursor->offset & ~PAGE_MASK)
1098                 return false;   /* more bytes to process in the current page */
1099
1100         if (!cursor->resid)
1101                 return false;   /* no more data */
1102
1103         /* Move on to the next page */
1104
1105         BUG_ON(list_is_last(&cursor->page->lru, &pagelist->head));
1106         cursor->page = list_next_entry(cursor->page, lru);
1107         cursor->last_piece = cursor->resid <= PAGE_SIZE;
1108
1109         return true;
1110 }
1111
1112 /*
1113  * Message data is handled (sent or received) in pieces, where each
1114  * piece resides on a single page.  The network layer might not
1115  * consume an entire piece at once.  A data item's cursor keeps
1116  * track of which piece is next to process and how much remains to
1117  * be processed in that piece.  It also tracks whether the current
1118  * piece is the last one in the data item.
1119  */
1120 static void __ceph_msg_data_cursor_init(struct ceph_msg_data_cursor *cursor)
1121 {
1122         size_t length = cursor->total_resid;
1123
1124         switch (cursor->data->type) {
1125         case CEPH_MSG_DATA_PAGELIST:
1126                 ceph_msg_data_pagelist_cursor_init(cursor, length);
1127                 break;
1128         case CEPH_MSG_DATA_PAGES:
1129                 ceph_msg_data_pages_cursor_init(cursor, length);
1130                 break;
1131 #ifdef CONFIG_BLOCK
1132         case CEPH_MSG_DATA_BIO:
1133                 ceph_msg_data_bio_cursor_init(cursor, length);
1134                 break;
1135 #endif /* CONFIG_BLOCK */
1136         case CEPH_MSG_DATA_BVECS:
1137                 ceph_msg_data_bvecs_cursor_init(cursor, length);
1138                 break;
1139         case CEPH_MSG_DATA_NONE:
1140         default:
1141                 /* BUG(); */
1142                 break;
1143         }
1144         cursor->need_crc = true;
1145 }
1146
1147 static void ceph_msg_data_cursor_init(struct ceph_msg *msg, size_t length)
1148 {
1149         struct ceph_msg_data_cursor *cursor = &msg->cursor;
1150         struct ceph_msg_data *data;
1151
1152         BUG_ON(!length);
1153         BUG_ON(length > msg->data_length);
1154         BUG_ON(list_empty(&msg->data));
1155
1156         cursor->data_head = &msg->data;
1157         cursor->total_resid = length;
1158         data = list_first_entry(&msg->data, struct ceph_msg_data, links);
1159         cursor->data = data;
1160
1161         __ceph_msg_data_cursor_init(cursor);
1162 }
1163
1164 /*
1165  * Return the page containing the next piece to process for a given
1166  * data item, and supply the page offset and length of that piece.
1167  * Indicate whether this is the last piece in this data item.
1168  */
1169 static struct page *ceph_msg_data_next(struct ceph_msg_data_cursor *cursor,
1170                                         size_t *page_offset, size_t *length,
1171                                         bool *last_piece)
1172 {
1173         struct page *page;
1174
1175         switch (cursor->data->type) {
1176         case CEPH_MSG_DATA_PAGELIST:
1177                 page = ceph_msg_data_pagelist_next(cursor, page_offset, length);
1178                 break;
1179         case CEPH_MSG_DATA_PAGES:
1180                 page = ceph_msg_data_pages_next(cursor, page_offset, length);
1181                 break;
1182 #ifdef CONFIG_BLOCK
1183         case CEPH_MSG_DATA_BIO:
1184                 page = ceph_msg_data_bio_next(cursor, page_offset, length);
1185                 break;
1186 #endif /* CONFIG_BLOCK */
1187         case CEPH_MSG_DATA_BVECS:
1188                 page = ceph_msg_data_bvecs_next(cursor, page_offset, length);
1189                 break;
1190         case CEPH_MSG_DATA_NONE:
1191         default:
1192                 page = NULL;
1193                 break;
1194         }
1195
1196         BUG_ON(!page);
1197         BUG_ON(*page_offset + *length > PAGE_SIZE);
1198         BUG_ON(!*length);
1199         BUG_ON(*length > cursor->resid);
1200         if (last_piece)
1201                 *last_piece = cursor->last_piece;
1202
1203         return page;
1204 }
1205
1206 /*
1207  * Returns true if the result moves the cursor on to the next piece
1208  * of the data item.
1209  */
1210 static void ceph_msg_data_advance(struct ceph_msg_data_cursor *cursor,
1211                                   size_t bytes)
1212 {
1213         bool new_piece;
1214
1215         BUG_ON(bytes > cursor->resid);
1216         switch (cursor->data->type) {
1217         case CEPH_MSG_DATA_PAGELIST:
1218                 new_piece = ceph_msg_data_pagelist_advance(cursor, bytes);
1219                 break;
1220         case CEPH_MSG_DATA_PAGES:
1221                 new_piece = ceph_msg_data_pages_advance(cursor, bytes);
1222                 break;
1223 #ifdef CONFIG_BLOCK
1224         case CEPH_MSG_DATA_BIO:
1225                 new_piece = ceph_msg_data_bio_advance(cursor, bytes);
1226                 break;
1227 #endif /* CONFIG_BLOCK */
1228         case CEPH_MSG_DATA_BVECS:
1229                 new_piece = ceph_msg_data_bvecs_advance(cursor, bytes);
1230                 break;
1231         case CEPH_MSG_DATA_NONE:
1232         default:
1233                 BUG();
1234                 break;
1235         }
1236         cursor->total_resid -= bytes;
1237
1238         if (!cursor->resid && cursor->total_resid) {
1239                 WARN_ON(!cursor->last_piece);
1240                 BUG_ON(list_is_last(&cursor->data->links, cursor->data_head));
1241                 cursor->data = list_next_entry(cursor->data, links);
1242                 __ceph_msg_data_cursor_init(cursor);
1243                 new_piece = true;
1244         }
1245         cursor->need_crc = new_piece;
1246 }
1247
1248 static size_t sizeof_footer(struct ceph_connection *con)
1249 {
1250         return (con->peer_features & CEPH_FEATURE_MSG_AUTH) ?
1251             sizeof(struct ceph_msg_footer) :
1252             sizeof(struct ceph_msg_footer_old);
1253 }
1254
1255 static void prepare_message_data(struct ceph_msg *msg, u32 data_len)
1256 {
1257         BUG_ON(!msg);
1258         BUG_ON(!data_len);
1259
1260         /* Initialize data cursor */
1261
1262         ceph_msg_data_cursor_init(msg, (size_t)data_len);
1263 }
1264
1265 /*
1266  * Prepare footer for currently outgoing message, and finish things
1267  * off.  Assumes out_kvec* are already valid.. we just add on to the end.
1268  */
1269 static void prepare_write_message_footer(struct ceph_connection *con)
1270 {
1271         struct ceph_msg *m = con->out_msg;
1272
1273         m->footer.flags |= CEPH_MSG_FOOTER_COMPLETE;
1274
1275         dout("prepare_write_message_footer %p\n", con);
1276         con_out_kvec_add(con, sizeof_footer(con), &m->footer);
1277         if (con->peer_features & CEPH_FEATURE_MSG_AUTH) {
1278                 if (con->ops->sign_message)
1279                         con->ops->sign_message(m);
1280                 else
1281                         m->footer.sig = 0;
1282         } else {
1283                 m->old_footer.flags = m->footer.flags;
1284         }
1285         con->out_more = m->more_to_follow;
1286         con->out_msg_done = true;
1287 }
1288
1289 /*
1290  * Prepare headers for the next outgoing message.
1291  */
1292 static void prepare_write_message(struct ceph_connection *con)
1293 {
1294         struct ceph_msg *m;
1295         u32 crc;
1296
1297         con_out_kvec_reset(con);
1298         con->out_msg_done = false;
1299
1300         /* Sneak an ack in there first?  If we can get it into the same
1301          * TCP packet that's a good thing. */
1302         if (con->in_seq > con->in_seq_acked) {
1303                 con->in_seq_acked = con->in_seq;
1304                 con_out_kvec_add(con, sizeof (tag_ack), &tag_ack);
1305                 con->out_temp_ack = cpu_to_le64(con->in_seq_acked);
1306                 con_out_kvec_add(con, sizeof (con->out_temp_ack),
1307                         &con->out_temp_ack);
1308         }
1309
1310         BUG_ON(list_empty(&con->out_queue));
1311         m = list_first_entry(&con->out_queue, struct ceph_msg, list_head);
1312         con->out_msg = m;
1313         BUG_ON(m->con != con);
1314
1315         /* put message on sent list */
1316         ceph_msg_get(m);
1317         list_move_tail(&m->list_head, &con->out_sent);
1318
1319         /*
1320          * only assign outgoing seq # if we haven't sent this message
1321          * yet.  if it is requeued, resend with it's original seq.
1322          */
1323         if (m->needs_out_seq) {
1324                 m->hdr.seq = cpu_to_le64(++con->out_seq);
1325                 m->needs_out_seq = false;
1326
1327                 if (con->ops->reencode_message)
1328                         con->ops->reencode_message(m);
1329         }
1330
1331         dout("prepare_write_message %p seq %lld type %d len %d+%d+%zd\n",
1332              m, con->out_seq, le16_to_cpu(m->hdr.type),
1333              le32_to_cpu(m->hdr.front_len), le32_to_cpu(m->hdr.middle_len),
1334              m->data_length);
1335         WARN_ON(m->front.iov_len != le32_to_cpu(m->hdr.front_len));
1336         WARN_ON(m->data_length != le32_to_cpu(m->hdr.data_len));
1337
1338         /* tag + hdr + front + middle */
1339         con_out_kvec_add(con, sizeof (tag_msg), &tag_msg);
1340         con_out_kvec_add(con, sizeof(con->out_hdr), &con->out_hdr);
1341         con_out_kvec_add(con, m->front.iov_len, m->front.iov_base);
1342
1343         if (m->middle)
1344                 con_out_kvec_add(con, m->middle->vec.iov_len,
1345                         m->middle->vec.iov_base);
1346
1347         /* fill in hdr crc and finalize hdr */
1348         crc = crc32c(0, &m->hdr, offsetof(struct ceph_msg_header, crc));
1349         con->out_msg->hdr.crc = cpu_to_le32(crc);
1350         memcpy(&con->out_hdr, &con->out_msg->hdr, sizeof(con->out_hdr));
1351
1352         /* fill in front and middle crc, footer */
1353         crc = crc32c(0, m->front.iov_base, m->front.iov_len);
1354         con->out_msg->footer.front_crc = cpu_to_le32(crc);
1355         if (m->middle) {
1356                 crc = crc32c(0, m->middle->vec.iov_base,
1357                                 m->middle->vec.iov_len);
1358                 con->out_msg->footer.middle_crc = cpu_to_le32(crc);
1359         } else
1360                 con->out_msg->footer.middle_crc = 0;
1361         dout("%s front_crc %u middle_crc %u\n", __func__,
1362              le32_to_cpu(con->out_msg->footer.front_crc),
1363              le32_to_cpu(con->out_msg->footer.middle_crc));
1364         con->out_msg->footer.flags = 0;
1365
1366         /* is there a data payload? */
1367         con->out_msg->footer.data_crc = 0;
1368         if (m->data_length) {
1369                 prepare_message_data(con->out_msg, m->data_length);
1370                 con->out_more = 1;  /* data + footer will follow */
1371         } else {
1372                 /* no, queue up footer too and be done */
1373                 prepare_write_message_footer(con);
1374         }
1375
1376         con_flag_set(con, CON_FLAG_WRITE_PENDING);
1377 }
1378
1379 /*
1380  * Prepare an ack.
1381  */
1382 static void prepare_write_ack(struct ceph_connection *con)
1383 {
1384         dout("prepare_write_ack %p %llu -> %llu\n", con,
1385              con->in_seq_acked, con->in_seq);
1386         con->in_seq_acked = con->in_seq;
1387
1388         con_out_kvec_reset(con);
1389
1390         con_out_kvec_add(con, sizeof (tag_ack), &tag_ack);
1391
1392         con->out_temp_ack = cpu_to_le64(con->in_seq_acked);
1393         con_out_kvec_add(con, sizeof (con->out_temp_ack),
1394                                 &con->out_temp_ack);
1395
1396         con->out_more = 1;  /* more will follow.. eventually.. */
1397         con_flag_set(con, CON_FLAG_WRITE_PENDING);
1398 }
1399
1400 /*
1401  * Prepare to share the seq during handshake
1402  */
1403 static void prepare_write_seq(struct ceph_connection *con)
1404 {
1405         dout("prepare_write_seq %p %llu -> %llu\n", con,
1406              con->in_seq_acked, con->in_seq);
1407         con->in_seq_acked = con->in_seq;
1408
1409         con_out_kvec_reset(con);
1410
1411         con->out_temp_ack = cpu_to_le64(con->in_seq_acked);
1412         con_out_kvec_add(con, sizeof (con->out_temp_ack),
1413                          &con->out_temp_ack);
1414
1415         con_flag_set(con, CON_FLAG_WRITE_PENDING);
1416 }
1417
1418 /*
1419  * Prepare to write keepalive byte.
1420  */
1421 static void prepare_write_keepalive(struct ceph_connection *con)
1422 {
1423         dout("prepare_write_keepalive %p\n", con);
1424         con_out_kvec_reset(con);
1425         if (con->peer_features & CEPH_FEATURE_MSGR_KEEPALIVE2) {
1426                 struct timespec64 now;
1427
1428                 ktime_get_real_ts64(&now);
1429                 con_out_kvec_add(con, sizeof(tag_keepalive2), &tag_keepalive2);
1430                 ceph_encode_timespec64(&con->out_temp_keepalive2, &now);
1431                 con_out_kvec_add(con, sizeof(con->out_temp_keepalive2),
1432                                  &con->out_temp_keepalive2);
1433         } else {
1434                 con_out_kvec_add(con, sizeof(tag_keepalive), &tag_keepalive);
1435         }
1436         con_flag_set(con, CON_FLAG_WRITE_PENDING);
1437 }
1438
1439 /*
1440  * Connection negotiation.
1441  */
1442
1443 static int get_connect_authorizer(struct ceph_connection *con)
1444 {
1445         struct ceph_auth_handshake *auth;
1446         int auth_proto;
1447
1448         if (!con->ops->get_authorizer) {
1449                 con->auth = NULL;
1450                 con->out_connect.authorizer_protocol = CEPH_AUTH_UNKNOWN;
1451                 con->out_connect.authorizer_len = 0;
1452                 return 0;
1453         }
1454
1455         auth = con->ops->get_authorizer(con, &auth_proto, con->auth_retry);
1456         if (IS_ERR(auth))
1457                 return PTR_ERR(auth);
1458
1459         con->auth = auth;
1460         con->out_connect.authorizer_protocol = cpu_to_le32(auth_proto);
1461         con->out_connect.authorizer_len = cpu_to_le32(auth->authorizer_buf_len);
1462         return 0;
1463 }
1464
1465 /*
1466  * We connected to a peer and are saying hello.
1467  */
1468 static void prepare_write_banner(struct ceph_connection *con)
1469 {
1470         con_out_kvec_add(con, strlen(CEPH_BANNER), CEPH_BANNER);
1471         con_out_kvec_add(con, sizeof (con->msgr->my_enc_addr),
1472                                         &con->msgr->my_enc_addr);
1473
1474         con->out_more = 0;
1475         con_flag_set(con, CON_FLAG_WRITE_PENDING);
1476 }
1477
1478 static void __prepare_write_connect(struct ceph_connection *con)
1479 {
1480         con_out_kvec_add(con, sizeof(con->out_connect), &con->out_connect);
1481         if (con->auth)
1482                 con_out_kvec_add(con, con->auth->authorizer_buf_len,
1483                                  con->auth->authorizer_buf);
1484
1485         con->out_more = 0;
1486         con_flag_set(con, CON_FLAG_WRITE_PENDING);
1487 }
1488
1489 static int prepare_write_connect(struct ceph_connection *con)
1490 {
1491         unsigned int global_seq = get_global_seq(con->msgr, 0);
1492         int proto;
1493         int ret;
1494
1495         switch (con->peer_name.type) {
1496         case CEPH_ENTITY_TYPE_MON:
1497                 proto = CEPH_MONC_PROTOCOL;
1498                 break;
1499         case CEPH_ENTITY_TYPE_OSD:
1500                 proto = CEPH_OSDC_PROTOCOL;
1501                 break;
1502         case CEPH_ENTITY_TYPE_MDS:
1503                 proto = CEPH_MDSC_PROTOCOL;
1504                 break;
1505         default:
1506                 BUG();
1507         }
1508
1509         dout("prepare_write_connect %p cseq=%d gseq=%d proto=%d\n", con,
1510              con->connect_seq, global_seq, proto);
1511
1512         con->out_connect.features =
1513             cpu_to_le64(from_msgr(con->msgr)->supported_features);
1514         con->out_connect.host_type = cpu_to_le32(CEPH_ENTITY_TYPE_CLIENT);
1515         con->out_connect.connect_seq = cpu_to_le32(con->connect_seq);
1516         con->out_connect.global_seq = cpu_to_le32(global_seq);
1517         con->out_connect.protocol_version = cpu_to_le32(proto);
1518         con->out_connect.flags = 0;
1519
1520         ret = get_connect_authorizer(con);
1521         if (ret)
1522                 return ret;
1523
1524         __prepare_write_connect(con);
1525         return 0;
1526 }
1527
1528 /*
1529  * write as much of pending kvecs to the socket as we can.
1530  *  1 -> done
1531  *  0 -> socket full, but more to do
1532  * <0 -> error
1533  */
1534 static int write_partial_kvec(struct ceph_connection *con)
1535 {
1536         int ret;
1537
1538         dout("write_partial_kvec %p %d left\n", con, con->out_kvec_bytes);
1539         while (con->out_kvec_bytes > 0) {
1540                 ret = ceph_tcp_sendmsg(con->sock, con->out_kvec_cur,
1541                                        con->out_kvec_left, con->out_kvec_bytes,
1542                                        con->out_more);
1543                 if (ret <= 0)
1544                         goto out;
1545                 con->out_kvec_bytes -= ret;
1546                 if (con->out_kvec_bytes == 0)
1547                         break;            /* done */
1548
1549                 /* account for full iov entries consumed */
1550                 while (ret >= con->out_kvec_cur->iov_len) {
1551                         BUG_ON(!con->out_kvec_left);
1552                         ret -= con->out_kvec_cur->iov_len;
1553                         con->out_kvec_cur++;
1554                         con->out_kvec_left--;
1555                 }
1556                 /* and for a partially-consumed entry */
1557                 if (ret) {
1558                         con->out_kvec_cur->iov_len -= ret;
1559                         con->out_kvec_cur->iov_base += ret;
1560                 }
1561         }
1562         con->out_kvec_left = 0;
1563         ret = 1;
1564 out:
1565         dout("write_partial_kvec %p %d left in %d kvecs ret = %d\n", con,
1566              con->out_kvec_bytes, con->out_kvec_left, ret);
1567         return ret;  /* done! */
1568 }
1569
1570 static u32 ceph_crc32c_page(u32 crc, struct page *page,
1571                                 unsigned int page_offset,
1572                                 unsigned int length)
1573 {
1574         char *kaddr;
1575
1576         kaddr = kmap(page);
1577         BUG_ON(kaddr == NULL);
1578         crc = crc32c(crc, kaddr + page_offset, length);
1579         kunmap(page);
1580
1581         return crc;
1582 }
1583 /*
1584  * Write as much message data payload as we can.  If we finish, queue
1585  * up the footer.
1586  *  1 -> done, footer is now queued in out_kvec[].
1587  *  0 -> socket full, but more to do
1588  * <0 -> error
1589  */
1590 static int write_partial_message_data(struct ceph_connection *con)
1591 {
1592         struct ceph_msg *msg = con->out_msg;
1593         struct ceph_msg_data_cursor *cursor = &msg->cursor;
1594         bool do_datacrc = !ceph_test_opt(from_msgr(con->msgr), NOCRC);
1595         u32 crc;
1596
1597         dout("%s %p msg %p\n", __func__, con, msg);
1598
1599         if (list_empty(&msg->data))
1600                 return -EINVAL;
1601
1602         /*
1603          * Iterate through each page that contains data to be
1604          * written, and send as much as possible for each.
1605          *
1606          * If we are calculating the data crc (the default), we will
1607          * need to map the page.  If we have no pages, they have
1608          * been revoked, so use the zero page.
1609          */
1610         crc = do_datacrc ? le32_to_cpu(msg->footer.data_crc) : 0;
1611         while (cursor->total_resid) {
1612                 struct page *page;
1613                 size_t page_offset;
1614                 size_t length;
1615                 bool last_piece;
1616                 int ret;
1617
1618                 if (!cursor->resid) {
1619                         ceph_msg_data_advance(cursor, 0);
1620                         continue;
1621                 }
1622
1623                 page = ceph_msg_data_next(cursor, &page_offset, &length,
1624                                           &last_piece);
1625                 ret = ceph_tcp_sendpage(con->sock, page, page_offset,
1626                                         length, !last_piece);
1627                 if (ret <= 0) {
1628                         if (do_datacrc)
1629                                 msg->footer.data_crc = cpu_to_le32(crc);
1630
1631                         return ret;
1632                 }
1633                 if (do_datacrc && cursor->need_crc)
1634                         crc = ceph_crc32c_page(crc, page, page_offset, length);
1635                 ceph_msg_data_advance(cursor, (size_t)ret);
1636         }
1637
1638         dout("%s %p msg %p done\n", __func__, con, msg);
1639
1640         /* prepare and queue up footer, too */
1641         if (do_datacrc)
1642                 msg->footer.data_crc = cpu_to_le32(crc);
1643         else
1644                 msg->footer.flags |= CEPH_MSG_FOOTER_NOCRC;
1645         con_out_kvec_reset(con);
1646         prepare_write_message_footer(con);
1647
1648         return 1;       /* must return > 0 to indicate success */
1649 }
1650
1651 /*
1652  * write some zeros
1653  */
1654 static int write_partial_skip(struct ceph_connection *con)
1655 {
1656         int ret;
1657
1658         dout("%s %p %d left\n", __func__, con, con->out_skip);
1659         while (con->out_skip > 0) {
1660                 size_t size = min(con->out_skip, (int) PAGE_SIZE);
1661
1662                 ret = ceph_tcp_sendpage(con->sock, zero_page, 0, size, true);
1663                 if (ret <= 0)
1664                         goto out;
1665                 con->out_skip -= ret;
1666         }
1667         ret = 1;
1668 out:
1669         return ret;
1670 }
1671
1672 /*
1673  * Prepare to read connection handshake, or an ack.
1674  */
1675 static void prepare_read_banner(struct ceph_connection *con)
1676 {
1677         dout("prepare_read_banner %p\n", con);
1678         con->in_base_pos = 0;
1679 }
1680
1681 static void prepare_read_connect(struct ceph_connection *con)
1682 {
1683         dout("prepare_read_connect %p\n", con);
1684         con->in_base_pos = 0;
1685 }
1686
1687 static void prepare_read_ack(struct ceph_connection *con)
1688 {
1689         dout("prepare_read_ack %p\n", con);
1690         con->in_base_pos = 0;
1691 }
1692
1693 static void prepare_read_seq(struct ceph_connection *con)
1694 {
1695         dout("prepare_read_seq %p\n", con);
1696         con->in_base_pos = 0;
1697         con->in_tag = CEPH_MSGR_TAG_SEQ;
1698 }
1699
1700 static void prepare_read_tag(struct ceph_connection *con)
1701 {
1702         dout("prepare_read_tag %p\n", con);
1703         con->in_base_pos = 0;
1704         con->in_tag = CEPH_MSGR_TAG_READY;
1705 }
1706
1707 static void prepare_read_keepalive_ack(struct ceph_connection *con)
1708 {
1709         dout("prepare_read_keepalive_ack %p\n", con);
1710         con->in_base_pos = 0;
1711 }
1712
1713 /*
1714  * Prepare to read a message.
1715  */
1716 static int prepare_read_message(struct ceph_connection *con)
1717 {
1718         dout("prepare_read_message %p\n", con);
1719         BUG_ON(con->in_msg != NULL);
1720         con->in_base_pos = 0;
1721         con->in_front_crc = con->in_middle_crc = con->in_data_crc = 0;
1722         return 0;
1723 }
1724
1725
1726 static int read_partial(struct ceph_connection *con,
1727                         int end, int size, void *object)
1728 {
1729         while (con->in_base_pos < end) {
1730                 int left = end - con->in_base_pos;
1731                 int have = size - left;
1732                 int ret = ceph_tcp_recvmsg(con->sock, object + have, left);
1733                 if (ret <= 0)
1734                         return ret;
1735                 con->in_base_pos += ret;
1736         }
1737         return 1;
1738 }
1739
1740
1741 /*
1742  * Read all or part of the connect-side handshake on a new connection
1743  */
1744 static int read_partial_banner(struct ceph_connection *con)
1745 {
1746         int size;
1747         int end;
1748         int ret;
1749
1750         dout("read_partial_banner %p at %d\n", con, con->in_base_pos);
1751
1752         /* peer's banner */
1753         size = strlen(CEPH_BANNER);
1754         end = size;
1755         ret = read_partial(con, end, size, con->in_banner);
1756         if (ret <= 0)
1757                 goto out;
1758
1759         size = sizeof (con->actual_peer_addr);
1760         end += size;
1761         ret = read_partial(con, end, size, &con->actual_peer_addr);
1762         if (ret <= 0)
1763                 goto out;
1764
1765         size = sizeof (con->peer_addr_for_me);
1766         end += size;
1767         ret = read_partial(con, end, size, &con->peer_addr_for_me);
1768         if (ret <= 0)
1769                 goto out;
1770
1771 out:
1772         return ret;
1773 }
1774
1775 static int read_partial_connect(struct ceph_connection *con)
1776 {
1777         int size;
1778         int end;
1779         int ret;
1780
1781         dout("read_partial_connect %p at %d\n", con, con->in_base_pos);
1782
1783         size = sizeof (con->in_reply);
1784         end = size;
1785         ret = read_partial(con, end, size, &con->in_reply);
1786         if (ret <= 0)
1787                 goto out;
1788
1789         if (con->auth) {
1790                 size = le32_to_cpu(con->in_reply.authorizer_len);
1791                 if (size > con->auth->authorizer_reply_buf_len) {
1792                         pr_err("authorizer reply too big: %d > %zu\n", size,
1793                                con->auth->authorizer_reply_buf_len);
1794                         ret = -EINVAL;
1795                         goto out;
1796                 }
1797
1798                 end += size;
1799                 ret = read_partial(con, end, size,
1800                                    con->auth->authorizer_reply_buf);
1801                 if (ret <= 0)
1802                         goto out;
1803         }
1804
1805         dout("read_partial_connect %p tag %d, con_seq = %u, g_seq = %u\n",
1806              con, (int)con->in_reply.tag,
1807              le32_to_cpu(con->in_reply.connect_seq),
1808              le32_to_cpu(con->in_reply.global_seq));
1809 out:
1810         return ret;
1811 }
1812
1813 /*
1814  * Verify the hello banner looks okay.
1815  */
1816 static int verify_hello(struct ceph_connection *con)
1817 {
1818         if (memcmp(con->in_banner, CEPH_BANNER, strlen(CEPH_BANNER))) {
1819                 pr_err("connect to %s got bad banner\n",
1820                        ceph_pr_addr(&con->peer_addr.in_addr));
1821                 con->error_msg = "protocol error, bad banner";
1822                 return -1;
1823         }
1824         return 0;
1825 }
1826
1827 static bool addr_is_blank(struct sockaddr_storage *ss)
1828 {
1829         struct in_addr *addr = &((struct sockaddr_in *)ss)->sin_addr;
1830         struct in6_addr *addr6 = &((struct sockaddr_in6 *)ss)->sin6_addr;
1831
1832         switch (ss->ss_family) {
1833         case AF_INET:
1834                 return addr->s_addr == htonl(INADDR_ANY);
1835         case AF_INET6:
1836                 return ipv6_addr_any(addr6);
1837         default:
1838                 return true;
1839         }
1840 }
1841
1842 static int addr_port(struct sockaddr_storage *ss)
1843 {
1844         switch (ss->ss_family) {
1845         case AF_INET:
1846                 return ntohs(((struct sockaddr_in *)ss)->sin_port);
1847         case AF_INET6:
1848                 return ntohs(((struct sockaddr_in6 *)ss)->sin6_port);
1849         }
1850         return 0;
1851 }
1852
1853 static void addr_set_port(struct sockaddr_storage *ss, int p)
1854 {
1855         switch (ss->ss_family) {
1856         case AF_INET:
1857                 ((struct sockaddr_in *)ss)->sin_port = htons(p);
1858                 break;
1859         case AF_INET6:
1860                 ((struct sockaddr_in6 *)ss)->sin6_port = htons(p);
1861                 break;
1862         }
1863 }
1864
1865 /*
1866  * Unlike other *_pton function semantics, zero indicates success.
1867  */
1868 static int ceph_pton(const char *str, size_t len, struct sockaddr_storage *ss,
1869                 char delim, const char **ipend)
1870 {
1871         struct sockaddr_in *in4 = (struct sockaddr_in *) ss;
1872         struct sockaddr_in6 *in6 = (struct sockaddr_in6 *) ss;
1873
1874         memset(ss, 0, sizeof(*ss));
1875
1876         if (in4_pton(str, len, (u8 *)&in4->sin_addr.s_addr, delim, ipend)) {
1877                 ss->ss_family = AF_INET;
1878                 return 0;
1879         }
1880
1881         if (in6_pton(str, len, (u8 *)&in6->sin6_addr.s6_addr, delim, ipend)) {
1882                 ss->ss_family = AF_INET6;
1883                 return 0;
1884         }
1885
1886         return -EINVAL;
1887 }
1888
1889 /*
1890  * Extract hostname string and resolve using kernel DNS facility.
1891  */
1892 #ifdef CONFIG_CEPH_LIB_USE_DNS_RESOLVER
1893 static int ceph_dns_resolve_name(const char *name, size_t namelen,
1894                 struct sockaddr_storage *ss, char delim, const char **ipend)
1895 {
1896         const char *end, *delim_p;
1897         char *colon_p, *ip_addr = NULL;
1898         int ip_len, ret;
1899
1900         /*
1901          * The end of the hostname occurs immediately preceding the delimiter or
1902          * the port marker (':') where the delimiter takes precedence.
1903          */
1904         delim_p = memchr(name, delim, namelen);
1905         colon_p = memchr(name, ':', namelen);
1906
1907         if (delim_p && colon_p)
1908                 end = delim_p < colon_p ? delim_p : colon_p;
1909         else if (!delim_p && colon_p)
1910                 end = colon_p;
1911         else {
1912                 end = delim_p;
1913                 if (!end) /* case: hostname:/ */
1914                         end = name + namelen;
1915         }
1916
1917         if (end <= name)
1918                 return -EINVAL;
1919
1920         /* do dns_resolve upcall */
1921         ip_len = dns_query(NULL, name, end - name, NULL, &ip_addr, NULL);
1922         if (ip_len > 0)
1923                 ret = ceph_pton(ip_addr, ip_len, ss, -1, NULL);
1924         else
1925                 ret = -ESRCH;
1926
1927         kfree(ip_addr);
1928
1929         *ipend = end;
1930
1931         pr_info("resolve '%.*s' (ret=%d): %s\n", (int)(end - name), name,
1932                         ret, ret ? "failed" : ceph_pr_addr(ss));
1933
1934         return ret;
1935 }
1936 #else
1937 static inline int ceph_dns_resolve_name(const char *name, size_t namelen,
1938                 struct sockaddr_storage *ss, char delim, const char **ipend)
1939 {
1940         return -EINVAL;
1941 }
1942 #endif
1943
1944 /*
1945  * Parse a server name (IP or hostname). If a valid IP address is not found
1946  * then try to extract a hostname to resolve using userspace DNS upcall.
1947  */
1948 static int ceph_parse_server_name(const char *name, size_t namelen,
1949                         struct sockaddr_storage *ss, char delim, const char **ipend)
1950 {
1951         int ret;
1952
1953         ret = ceph_pton(name, namelen, ss, delim, ipend);
1954         if (ret)
1955                 ret = ceph_dns_resolve_name(name, namelen, ss, delim, ipend);
1956
1957         return ret;
1958 }
1959
1960 /*
1961  * Parse an ip[:port] list into an addr array.  Use the default
1962  * monitor port if a port isn't specified.
1963  */
1964 int ceph_parse_ips(const char *c, const char *end,
1965                    struct ceph_entity_addr *addr,
1966                    int max_count, int *count)
1967 {
1968         int i, ret = -EINVAL;
1969         const char *p = c;
1970
1971         dout("parse_ips on '%.*s'\n", (int)(end-c), c);
1972         for (i = 0; i < max_count; i++) {
1973                 const char *ipend;
1974                 struct sockaddr_storage *ss = &addr[i].in_addr;
1975                 int port;
1976                 char delim = ',';
1977
1978                 if (*p == '[') {
1979                         delim = ']';
1980                         p++;
1981                 }
1982
1983                 ret = ceph_parse_server_name(p, end - p, ss, delim, &ipend);
1984                 if (ret)
1985                         goto bad;
1986                 ret = -EINVAL;
1987
1988                 p = ipend;
1989
1990                 if (delim == ']') {
1991                         if (*p != ']') {
1992                                 dout("missing matching ']'\n");
1993                                 goto bad;
1994                         }
1995                         p++;
1996                 }
1997
1998                 /* port? */
1999                 if (p < end && *p == ':') {
2000                         port = 0;
2001                         p++;
2002                         while (p < end && *p >= '0' && *p <= '9') {
2003                                 port = (port * 10) + (*p - '0');
2004                                 p++;
2005                         }
2006                         if (port == 0)
2007                                 port = CEPH_MON_PORT;
2008                         else if (port > 65535)
2009                                 goto bad;
2010                 } else {
2011                         port = CEPH_MON_PORT;
2012                 }
2013
2014                 addr_set_port(ss, port);
2015
2016                 dout("parse_ips got %s\n", ceph_pr_addr(ss));
2017
2018                 if (p == end)
2019                         break;
2020                 if (*p != ',')
2021                         goto bad;
2022                 p++;
2023         }
2024
2025         if (p != end)
2026                 goto bad;
2027
2028         if (count)
2029                 *count = i + 1;
2030         return 0;
2031
2032 bad:
2033         pr_err("parse_ips bad ip '%.*s'\n", (int)(end - c), c);
2034         return ret;
2035 }
2036 EXPORT_SYMBOL(ceph_parse_ips);
2037
2038 static int process_banner(struct ceph_connection *con)
2039 {
2040         dout("process_banner on %p\n", con);
2041
2042         if (verify_hello(con) < 0)
2043                 return -1;
2044
2045         ceph_decode_addr(&con->actual_peer_addr);
2046         ceph_decode_addr(&con->peer_addr_for_me);
2047
2048         /*
2049          * Make sure the other end is who we wanted.  note that the other
2050          * end may not yet know their ip address, so if it's 0.0.0.0, give
2051          * them the benefit of the doubt.
2052          */
2053         if (memcmp(&con->peer_addr, &con->actual_peer_addr,
2054                    sizeof(con->peer_addr)) != 0 &&
2055             !(addr_is_blank(&con->actual_peer_addr.in_addr) &&
2056               con->actual_peer_addr.nonce == con->peer_addr.nonce)) {
2057                 pr_warn("wrong peer, want %s/%d, got %s/%d\n",
2058                         ceph_pr_addr(&con->peer_addr.in_addr),
2059                         (int)le32_to_cpu(con->peer_addr.nonce),
2060                         ceph_pr_addr(&con->actual_peer_addr.in_addr),
2061                         (int)le32_to_cpu(con->actual_peer_addr.nonce));
2062                 con->error_msg = "wrong peer at address";
2063                 return -1;
2064         }
2065
2066         /*
2067          * did we learn our address?
2068          */
2069         if (addr_is_blank(&con->msgr->inst.addr.in_addr)) {
2070                 int port = addr_port(&con->msgr->inst.addr.in_addr);
2071
2072                 memcpy(&con->msgr->inst.addr.in_addr,
2073                        &con->peer_addr_for_me.in_addr,
2074                        sizeof(con->peer_addr_for_me.in_addr));
2075                 addr_set_port(&con->msgr->inst.addr.in_addr, port);
2076                 encode_my_addr(con->msgr);
2077                 dout("process_banner learned my addr is %s\n",
2078                      ceph_pr_addr(&con->msgr->inst.addr.in_addr));
2079         }
2080
2081         return 0;
2082 }
2083
2084 static int process_connect(struct ceph_connection *con)
2085 {
2086         u64 sup_feat = from_msgr(con->msgr)->supported_features;
2087         u64 req_feat = from_msgr(con->msgr)->required_features;
2088         u64 server_feat = le64_to_cpu(con->in_reply.features);
2089         int ret;
2090
2091         dout("process_connect on %p tag %d\n", con, (int)con->in_tag);
2092
2093         if (con->auth) {
2094                 int len = le32_to_cpu(con->in_reply.authorizer_len);
2095
2096                 /*
2097                  * Any connection that defines ->get_authorizer()
2098                  * should also define ->add_authorizer_challenge() and
2099                  * ->verify_authorizer_reply().
2100                  *
2101                  * See get_connect_authorizer().
2102                  */
2103                 if (con->in_reply.tag == CEPH_MSGR_TAG_CHALLENGE_AUTHORIZER) {
2104                         ret = con->ops->add_authorizer_challenge(
2105                                     con, con->auth->authorizer_reply_buf, len);
2106                         if (ret < 0)
2107                                 return ret;
2108
2109                         con_out_kvec_reset(con);
2110                         __prepare_write_connect(con);
2111                         prepare_read_connect(con);
2112                         return 0;
2113                 }
2114
2115                 if (len) {
2116                         ret = con->ops->verify_authorizer_reply(con);
2117                         if (ret < 0) {
2118                                 con->error_msg = "bad authorize reply";
2119                                 return ret;
2120                         }
2121                 }
2122         }
2123
2124         switch (con->in_reply.tag) {
2125         case CEPH_MSGR_TAG_FEATURES:
2126                 pr_err("%s%lld %s feature set mismatch,"
2127                        " my %llx < server's %llx, missing %llx\n",
2128                        ENTITY_NAME(con->peer_name),
2129                        ceph_pr_addr(&con->peer_addr.in_addr),
2130                        sup_feat, server_feat, server_feat & ~sup_feat);
2131                 con->error_msg = "missing required protocol features";
2132                 reset_connection(con);
2133                 return -1;
2134
2135         case CEPH_MSGR_TAG_BADPROTOVER:
2136                 pr_err("%s%lld %s protocol version mismatch,"
2137                        " my %d != server's %d\n",
2138                        ENTITY_NAME(con->peer_name),
2139                        ceph_pr_addr(&con->peer_addr.in_addr),
2140                        le32_to_cpu(con->out_connect.protocol_version),
2141                        le32_to_cpu(con->in_reply.protocol_version));
2142                 con->error_msg = "protocol version mismatch";
2143                 reset_connection(con);
2144                 return -1;
2145
2146         case CEPH_MSGR_TAG_BADAUTHORIZER:
2147                 con->auth_retry++;
2148                 dout("process_connect %p got BADAUTHORIZER attempt %d\n", con,
2149                      con->auth_retry);
2150                 if (con->auth_retry == 2) {
2151                         con->error_msg = "connect authorization failure";
2152                         return -1;
2153                 }
2154                 con_out_kvec_reset(con);
2155                 ret = prepare_write_connect(con);
2156                 if (ret < 0)
2157                         return ret;
2158                 prepare_read_connect(con);
2159                 break;
2160
2161         case CEPH_MSGR_TAG_RESETSESSION:
2162                 /*
2163                  * If we connected with a large connect_seq but the peer
2164                  * has no record of a session with us (no connection, or
2165                  * connect_seq == 0), they will send RESETSESION to indicate
2166                  * that they must have reset their session, and may have
2167                  * dropped messages.
2168                  */
2169                 dout("process_connect got RESET peer seq %u\n",
2170                      le32_to_cpu(con->in_reply.connect_seq));
2171                 pr_err("%s%lld %s connection reset\n",
2172                        ENTITY_NAME(con->peer_name),
2173                        ceph_pr_addr(&con->peer_addr.in_addr));
2174                 reset_connection(con);
2175                 con_out_kvec_reset(con);
2176                 ret = prepare_write_connect(con);
2177                 if (ret < 0)
2178                         return ret;
2179                 prepare_read_connect(con);
2180
2181                 /* Tell ceph about it. */
2182                 mutex_unlock(&con->mutex);
2183                 pr_info("reset on %s%lld\n", ENTITY_NAME(con->peer_name));
2184                 if (con->ops->peer_reset)
2185                         con->ops->peer_reset(con);
2186                 mutex_lock(&con->mutex);
2187                 if (con->state != CON_STATE_NEGOTIATING)
2188                         return -EAGAIN;
2189                 break;
2190
2191         case CEPH_MSGR_TAG_RETRY_SESSION:
2192                 /*
2193                  * If we sent a smaller connect_seq than the peer has, try
2194                  * again with a larger value.
2195                  */
2196                 dout("process_connect got RETRY_SESSION my seq %u, peer %u\n",
2197                      le32_to_cpu(con->out_connect.connect_seq),
2198                      le32_to_cpu(con->in_reply.connect_seq));
2199                 con->connect_seq = le32_to_cpu(con->in_reply.connect_seq);
2200                 con_out_kvec_reset(con);
2201                 ret = prepare_write_connect(con);
2202                 if (ret < 0)
2203                         return ret;
2204                 prepare_read_connect(con);
2205                 break;
2206
2207         case CEPH_MSGR_TAG_RETRY_GLOBAL:
2208                 /*
2209                  * If we sent a smaller global_seq than the peer has, try
2210                  * again with a larger value.
2211                  */
2212                 dout("process_connect got RETRY_GLOBAL my %u peer_gseq %u\n",
2213                      con->peer_global_seq,
2214                      le32_to_cpu(con->in_reply.global_seq));
2215                 get_global_seq(con->msgr,
2216                                le32_to_cpu(con->in_reply.global_seq));
2217                 con_out_kvec_reset(con);
2218                 ret = prepare_write_connect(con);
2219                 if (ret < 0)
2220                         return ret;
2221                 prepare_read_connect(con);
2222                 break;
2223
2224         case CEPH_MSGR_TAG_SEQ:
2225         case CEPH_MSGR_TAG_READY:
2226                 if (req_feat & ~server_feat) {
2227                         pr_err("%s%lld %s protocol feature mismatch,"
2228                                " my required %llx > server's %llx, need %llx\n",
2229                                ENTITY_NAME(con->peer_name),
2230                                ceph_pr_addr(&con->peer_addr.in_addr),
2231                                req_feat, server_feat, req_feat & ~server_feat);
2232                         con->error_msg = "missing required protocol features";
2233                         reset_connection(con);
2234                         return -1;
2235                 }
2236
2237                 WARN_ON(con->state != CON_STATE_NEGOTIATING);
2238                 con->state = CON_STATE_OPEN;
2239                 con->auth_retry = 0;    /* we authenticated; clear flag */
2240                 con->peer_global_seq = le32_to_cpu(con->in_reply.global_seq);
2241                 con->connect_seq++;
2242                 con->peer_features = server_feat;
2243                 dout("process_connect got READY gseq %d cseq %d (%d)\n",
2244                      con->peer_global_seq,
2245                      le32_to_cpu(con->in_reply.connect_seq),
2246                      con->connect_seq);
2247                 WARN_ON(con->connect_seq !=
2248                         le32_to_cpu(con->in_reply.connect_seq));
2249
2250                 if (con->in_reply.flags & CEPH_MSG_CONNECT_LOSSY)
2251                         con_flag_set(con, CON_FLAG_LOSSYTX);
2252
2253                 con->delay = 0;      /* reset backoff memory */
2254
2255                 if (con->in_reply.tag == CEPH_MSGR_TAG_SEQ) {
2256                         prepare_write_seq(con);
2257                         prepare_read_seq(con);
2258                 } else {
2259                         prepare_read_tag(con);
2260                 }
2261                 break;
2262
2263         case CEPH_MSGR_TAG_WAIT:
2264                 /*
2265                  * If there is a connection race (we are opening
2266                  * connections to each other), one of us may just have
2267                  * to WAIT.  This shouldn't happen if we are the
2268                  * client.
2269                  */
2270                 con->error_msg = "protocol error, got WAIT as client";
2271                 return -1;
2272
2273         default:
2274                 con->error_msg = "protocol error, garbage tag during connect";
2275                 return -1;
2276         }
2277         return 0;
2278 }
2279
2280
2281 /*
2282  * read (part of) an ack
2283  */
2284 static int read_partial_ack(struct ceph_connection *con)
2285 {
2286         int size = sizeof (con->in_temp_ack);
2287         int end = size;
2288
2289         return read_partial(con, end, size, &con->in_temp_ack);
2290 }
2291
2292 /*
2293  * We can finally discard anything that's been acked.
2294  */
2295 static void process_ack(struct ceph_connection *con)
2296 {
2297         struct ceph_msg *m;
2298         u64 ack = le64_to_cpu(con->in_temp_ack);
2299         u64 seq;
2300         bool reconnect = (con->in_tag == CEPH_MSGR_TAG_SEQ);
2301         struct list_head *list = reconnect ? &con->out_queue : &con->out_sent;
2302
2303         /*
2304          * In the reconnect case, con_fault() has requeued messages
2305          * in out_sent. We should cleanup old messages according to
2306          * the reconnect seq.
2307          */
2308         while (!list_empty(list)) {
2309                 m = list_first_entry(list, struct ceph_msg, list_head);
2310                 if (reconnect && m->needs_out_seq)
2311                         break;
2312                 seq = le64_to_cpu(m->hdr.seq);
2313                 if (seq > ack)
2314                         break;
2315                 dout("got ack for seq %llu type %d at %p\n", seq,
2316                      le16_to_cpu(m->hdr.type), m);
2317                 m->ack_stamp = jiffies;
2318                 ceph_msg_remove(m);
2319         }
2320
2321         prepare_read_tag(con);
2322 }
2323
2324
2325 static int read_partial_message_section(struct ceph_connection *con,
2326                                         struct kvec *section,
2327                                         unsigned int sec_len, u32 *crc)
2328 {
2329         int ret, left;
2330
2331         BUG_ON(!section);
2332
2333         while (section->iov_len < sec_len) {
2334                 BUG_ON(section->iov_base == NULL);
2335                 left = sec_len - section->iov_len;
2336                 ret = ceph_tcp_recvmsg(con->sock, (char *)section->iov_base +
2337                                        section->iov_len, left);
2338                 if (ret <= 0)
2339                         return ret;
2340                 section->iov_len += ret;
2341         }
2342         if (section->iov_len == sec_len)
2343                 *crc = crc32c(0, section->iov_base, section->iov_len);
2344
2345         return 1;
2346 }
2347
2348 static int read_partial_msg_data(struct ceph_connection *con)
2349 {
2350         struct ceph_msg *msg = con->in_msg;
2351         struct ceph_msg_data_cursor *cursor = &msg->cursor;
2352         bool do_datacrc = !ceph_test_opt(from_msgr(con->msgr), NOCRC);
2353         struct page *page;
2354         size_t page_offset;
2355         size_t length;
2356         u32 crc = 0;
2357         int ret;
2358
2359         BUG_ON(!msg);
2360         if (list_empty(&msg->data))
2361                 return -EIO;
2362
2363         if (do_datacrc)
2364                 crc = con->in_data_crc;
2365         while (cursor->total_resid) {
2366                 if (!cursor->resid) {
2367                         ceph_msg_data_advance(cursor, 0);
2368                         continue;
2369                 }
2370
2371                 page = ceph_msg_data_next(cursor, &page_offset, &length, NULL);
2372                 ret = ceph_tcp_recvpage(con->sock, page, page_offset, length);
2373                 if (ret <= 0) {
2374                         if (do_datacrc)
2375                                 con->in_data_crc = crc;
2376
2377                         return ret;
2378                 }
2379
2380                 if (do_datacrc)
2381                         crc = ceph_crc32c_page(crc, page, page_offset, ret);
2382                 ceph_msg_data_advance(cursor, (size_t)ret);
2383         }
2384         if (do_datacrc)
2385                 con->in_data_crc = crc;
2386
2387         return 1;       /* must return > 0 to indicate success */
2388 }
2389
2390 /*
2391  * read (part of) a message.
2392  */
2393 static int ceph_con_in_msg_alloc(struct ceph_connection *con, int *skip);
2394
2395 static int read_partial_message(struct ceph_connection *con)
2396 {
2397         struct ceph_msg *m = con->in_msg;
2398         int size;
2399         int end;
2400         int ret;
2401         unsigned int front_len, middle_len, data_len;
2402         bool do_datacrc = !ceph_test_opt(from_msgr(con->msgr), NOCRC);
2403         bool need_sign = (con->peer_features & CEPH_FEATURE_MSG_AUTH);
2404         u64 seq;
2405         u32 crc;
2406
2407         dout("read_partial_message con %p msg %p\n", con, m);
2408
2409         /* header */
2410         size = sizeof (con->in_hdr);
2411         end = size;
2412         ret = read_partial(con, end, size, &con->in_hdr);
2413         if (ret <= 0)
2414                 return ret;
2415
2416         crc = crc32c(0, &con->in_hdr, offsetof(struct ceph_msg_header, crc));
2417         if (cpu_to_le32(crc) != con->in_hdr.crc) {
2418                 pr_err("read_partial_message bad hdr crc %u != expected %u\n",
2419                        crc, con->in_hdr.crc);
2420                 return -EBADMSG;
2421         }
2422
2423         front_len = le32_to_cpu(con->in_hdr.front_len);
2424         if (front_len > CEPH_MSG_MAX_FRONT_LEN)
2425                 return -EIO;
2426         middle_len = le32_to_cpu(con->in_hdr.middle_len);
2427         if (middle_len > CEPH_MSG_MAX_MIDDLE_LEN)
2428                 return -EIO;
2429         data_len = le32_to_cpu(con->in_hdr.data_len);
2430         if (data_len > CEPH_MSG_MAX_DATA_LEN)
2431                 return -EIO;
2432
2433         /* verify seq# */
2434         seq = le64_to_cpu(con->in_hdr.seq);
2435         if ((s64)seq - (s64)con->in_seq < 1) {
2436                 pr_info("skipping %s%lld %s seq %lld expected %lld\n",
2437                         ENTITY_NAME(con->peer_name),
2438                         ceph_pr_addr(&con->peer_addr.in_addr),
2439                         seq, con->in_seq + 1);
2440                 con->in_base_pos = -front_len - middle_len - data_len -
2441                         sizeof_footer(con);
2442                 con->in_tag = CEPH_MSGR_TAG_READY;
2443                 return 1;
2444         } else if ((s64)seq - (s64)con->in_seq > 1) {
2445                 pr_err("read_partial_message bad seq %lld expected %lld\n",
2446                        seq, con->in_seq + 1);
2447                 con->error_msg = "bad message sequence # for incoming message";
2448                 return -EBADE;
2449         }
2450
2451         /* allocate message? */
2452         if (!con->in_msg) {
2453                 int skip = 0;
2454
2455                 dout("got hdr type %d front %d data %d\n", con->in_hdr.type,
2456                      front_len, data_len);
2457                 ret = ceph_con_in_msg_alloc(con, &skip);
2458                 if (ret < 0)
2459                         return ret;
2460
2461                 BUG_ON(!con->in_msg ^ skip);
2462                 if (skip) {
2463                         /* skip this message */
2464                         dout("alloc_msg said skip message\n");
2465                         con->in_base_pos = -front_len - middle_len - data_len -
2466                                 sizeof_footer(con);
2467                         con->in_tag = CEPH_MSGR_TAG_READY;
2468                         con->in_seq++;
2469                         return 1;
2470                 }
2471
2472                 BUG_ON(!con->in_msg);
2473                 BUG_ON(con->in_msg->con != con);
2474                 m = con->in_msg;
2475                 m->front.iov_len = 0;    /* haven't read it yet */
2476                 if (m->middle)
2477                         m->middle->vec.iov_len = 0;
2478
2479                 /* prepare for data payload, if any */
2480
2481                 if (data_len)
2482                         prepare_message_data(con->in_msg, data_len);
2483         }
2484
2485         /* front */
2486         ret = read_partial_message_section(con, &m->front, front_len,
2487                                            &con->in_front_crc);
2488         if (ret <= 0)
2489                 return ret;
2490
2491         /* middle */
2492         if (m->middle) {
2493                 ret = read_partial_message_section(con, &m->middle->vec,
2494                                                    middle_len,
2495                                                    &con->in_middle_crc);
2496                 if (ret <= 0)
2497                         return ret;
2498         }
2499
2500         /* (page) data */
2501         if (data_len) {
2502                 ret = read_partial_msg_data(con);
2503                 if (ret <= 0)
2504                         return ret;
2505         }
2506
2507         /* footer */
2508         size = sizeof_footer(con);
2509         end += size;
2510         ret = read_partial(con, end, size, &m->footer);
2511         if (ret <= 0)
2512                 return ret;
2513
2514         if (!need_sign) {
2515                 m->footer.flags = m->old_footer.flags;
2516                 m->footer.sig = 0;
2517         }
2518
2519         dout("read_partial_message got msg %p %d (%u) + %d (%u) + %d (%u)\n",
2520              m, front_len, m->footer.front_crc, middle_len,
2521              m->footer.middle_crc, data_len, m->footer.data_crc);
2522
2523         /* crc ok? */
2524         if (con->in_front_crc != le32_to_cpu(m->footer.front_crc)) {
2525                 pr_err("read_partial_message %p front crc %u != exp. %u\n",
2526                        m, con->in_front_crc, m->footer.front_crc);
2527                 return -EBADMSG;
2528         }
2529         if (con->in_middle_crc != le32_to_cpu(m->footer.middle_crc)) {
2530                 pr_err("read_partial_message %p middle crc %u != exp %u\n",
2531                        m, con->in_middle_crc, m->footer.middle_crc);
2532                 return -EBADMSG;
2533         }
2534         if (do_datacrc &&
2535             (m->footer.flags & CEPH_MSG_FOOTER_NOCRC) == 0 &&
2536             con->in_data_crc != le32_to_cpu(m->footer.data_crc)) {
2537                 pr_err("read_partial_message %p data crc %u != exp. %u\n", m,
2538                        con->in_data_crc, le32_to_cpu(m->footer.data_crc));
2539                 return -EBADMSG;
2540         }
2541
2542         if (need_sign && con->ops->check_message_signature &&
2543             con->ops->check_message_signature(m)) {
2544                 pr_err("read_partial_message %p signature check failed\n", m);
2545                 return -EBADMSG;
2546         }
2547
2548         return 1; /* done! */
2549 }
2550
2551 /*
2552  * Process message.  This happens in the worker thread.  The callback should
2553  * be careful not to do anything that waits on other incoming messages or it
2554  * may deadlock.
2555  */
2556 static void process_message(struct ceph_connection *con)
2557 {
2558         struct ceph_msg *msg = con->in_msg;
2559
2560         BUG_ON(con->in_msg->con != con);
2561         con->in_msg = NULL;
2562
2563         /* if first message, set peer_name */
2564         if (con->peer_name.type == 0)
2565                 con->peer_name = msg->hdr.src;
2566
2567         con->in_seq++;
2568         mutex_unlock(&con->mutex);
2569
2570         dout("===== %p %llu from %s%lld %d=%s len %d+%d (%u %u %u) =====\n",
2571              msg, le64_to_cpu(msg->hdr.seq),
2572              ENTITY_NAME(msg->hdr.src),
2573              le16_to_cpu(msg->hdr.type),
2574              ceph_msg_type_name(le16_to_cpu(msg->hdr.type)),
2575              le32_to_cpu(msg->hdr.front_len),
2576              le32_to_cpu(msg->hdr.data_len),
2577              con->in_front_crc, con->in_middle_crc, con->in_data_crc);
2578         con->ops->dispatch(con, msg);
2579
2580         mutex_lock(&con->mutex);
2581 }
2582
2583 static int read_keepalive_ack(struct ceph_connection *con)
2584 {
2585         struct ceph_timespec ceph_ts;
2586         size_t size = sizeof(ceph_ts);
2587         int ret = read_partial(con, size, size, &ceph_ts);
2588         if (ret <= 0)
2589                 return ret;
2590         ceph_decode_timespec64(&con->last_keepalive_ack, &ceph_ts);
2591         prepare_read_tag(con);
2592         return 1;
2593 }
2594
2595 /*
2596  * Write something to the socket.  Called in a worker thread when the
2597  * socket appears to be writeable and we have something ready to send.
2598  */
2599 static int try_write(struct ceph_connection *con)
2600 {
2601         int ret = 1;
2602
2603         dout("try_write start %p state %lu\n", con, con->state);
2604         if (con->state != CON_STATE_PREOPEN &&
2605             con->state != CON_STATE_CONNECTING &&
2606             con->state != CON_STATE_NEGOTIATING &&
2607             con->state != CON_STATE_OPEN)
2608                 return 0;
2609
2610         /* open the socket first? */
2611         if (con->state == CON_STATE_PREOPEN) {
2612                 BUG_ON(con->sock);
2613                 con->state = CON_STATE_CONNECTING;
2614
2615                 con_out_kvec_reset(con);
2616                 prepare_write_banner(con);
2617                 prepare_read_banner(con);
2618
2619                 BUG_ON(con->in_msg);
2620                 con->in_tag = CEPH_MSGR_TAG_READY;
2621                 dout("try_write initiating connect on %p new state %lu\n",
2622                      con, con->state);
2623                 ret = ceph_tcp_connect(con);
2624                 if (ret < 0) {
2625                         con->error_msg = "connect error";
2626                         goto out;
2627                 }
2628         }
2629
2630 more:
2631         dout("try_write out_kvec_bytes %d\n", con->out_kvec_bytes);
2632         BUG_ON(!con->sock);
2633
2634         /* kvec data queued? */
2635         if (con->out_kvec_left) {
2636                 ret = write_partial_kvec(con);
2637                 if (ret <= 0)
2638                         goto out;
2639         }
2640         if (con->out_skip) {
2641                 ret = write_partial_skip(con);
2642                 if (ret <= 0)
2643                         goto out;
2644         }
2645
2646         /* msg pages? */
2647         if (con->out_msg) {
2648                 if (con->out_msg_done) {
2649                         ceph_msg_put(con->out_msg);
2650                         con->out_msg = NULL;   /* we're done with this one */
2651                         goto do_next;
2652                 }
2653
2654                 ret = write_partial_message_data(con);
2655                 if (ret == 1)
2656                         goto more;  /* we need to send the footer, too! */
2657                 if (ret == 0)
2658                         goto out;
2659                 if (ret < 0) {
2660                         dout("try_write write_partial_message_data err %d\n",
2661                              ret);
2662                         goto out;
2663                 }
2664         }
2665
2666 do_next:
2667         if (con->state == CON_STATE_OPEN) {
2668                 if (con_flag_test_and_clear(con, CON_FLAG_KEEPALIVE_PENDING)) {
2669                         prepare_write_keepalive(con);
2670                         goto more;
2671                 }
2672                 /* is anything else pending? */
2673                 if (!list_empty(&con->out_queue)) {
2674                         prepare_write_message(con);
2675                         goto more;
2676                 }
2677                 if (con->in_seq > con->in_seq_acked) {
2678                         prepare_write_ack(con);
2679                         goto more;
2680                 }
2681         }
2682
2683         /* Nothing to do! */
2684         con_flag_clear(con, CON_FLAG_WRITE_PENDING);
2685         dout("try_write nothing else to write.\n");
2686         ret = 0;
2687 out:
2688         dout("try_write done on %p ret %d\n", con, ret);
2689         return ret;
2690 }
2691
2692 /*
2693  * Read what we can from the socket.
2694  */
2695 static int try_read(struct ceph_connection *con)
2696 {
2697         int ret = -1;
2698
2699 more:
2700         dout("try_read start on %p state %lu\n", con, con->state);
2701         if (con->state != CON_STATE_CONNECTING &&
2702             con->state != CON_STATE_NEGOTIATING &&
2703             con->state != CON_STATE_OPEN)
2704                 return 0;
2705
2706         BUG_ON(!con->sock);
2707
2708         dout("try_read tag %d in_base_pos %d\n", (int)con->in_tag,
2709              con->in_base_pos);
2710
2711         if (con->state == CON_STATE_CONNECTING) {
2712                 dout("try_read connecting\n");
2713                 ret = read_partial_banner(con);
2714                 if (ret <= 0)
2715                         goto out;
2716                 ret = process_banner(con);
2717                 if (ret < 0)
2718                         goto out;
2719
2720                 con->state = CON_STATE_NEGOTIATING;
2721
2722                 /*
2723                  * Received banner is good, exchange connection info.
2724                  * Do not reset out_kvec, as sending our banner raced
2725                  * with receiving peer banner after connect completed.
2726                  */
2727                 ret = prepare_write_connect(con);
2728                 if (ret < 0)
2729                         goto out;
2730                 prepare_read_connect(con);
2731
2732                 /* Send connection info before awaiting response */
2733                 goto out;
2734         }
2735
2736         if (con->state == CON_STATE_NEGOTIATING) {
2737                 dout("try_read negotiating\n");
2738                 ret = read_partial_connect(con);
2739                 if (ret <= 0)
2740                         goto out;
2741                 ret = process_connect(con);
2742                 if (ret < 0)
2743                         goto out;
2744                 goto more;
2745         }
2746
2747         WARN_ON(con->state != CON_STATE_OPEN);
2748
2749         if (con->in_base_pos < 0) {
2750                 /*
2751                  * skipping + discarding content.
2752                  */
2753                 ret = ceph_tcp_recvmsg(con->sock, NULL, -con->in_base_pos);
2754                 if (ret <= 0)
2755                         goto out;
2756                 dout("skipped %d / %d bytes\n", ret, -con->in_base_pos);
2757                 con->in_base_pos += ret;
2758                 if (con->in_base_pos)
2759                         goto more;
2760         }
2761         if (con->in_tag == CEPH_MSGR_TAG_READY) {
2762                 /*
2763                  * what's next?
2764                  */
2765                 ret = ceph_tcp_recvmsg(con->sock, &con->in_tag, 1);
2766                 if (ret <= 0)
2767                         goto out;
2768                 dout("try_read got tag %d\n", (int)con->in_tag);
2769                 switch (con->in_tag) {
2770                 case CEPH_MSGR_TAG_MSG:
2771                         prepare_read_message(con);
2772                         break;
2773                 case CEPH_MSGR_TAG_ACK:
2774                         prepare_read_ack(con);
2775                         break;
2776                 case CEPH_MSGR_TAG_KEEPALIVE2_ACK:
2777                         prepare_read_keepalive_ack(con);
2778                         break;
2779                 case CEPH_MSGR_TAG_CLOSE:
2780                         con_close_socket(con);
2781                         con->state = CON_STATE_CLOSED;
2782                         goto out;
2783                 default:
2784                         goto bad_tag;
2785                 }
2786         }
2787         if (con->in_tag == CEPH_MSGR_TAG_MSG) {
2788                 ret = read_partial_message(con);
2789                 if (ret <= 0) {
2790                         switch (ret) {
2791                         case -EBADMSG:
2792                                 con->error_msg = "bad crc/signature";
2793                                 /* fall through */
2794                         case -EBADE:
2795                                 ret = -EIO;
2796                                 break;
2797                         case -EIO:
2798                                 con->error_msg = "io error";
2799                                 break;
2800                         }
2801                         goto out;
2802                 }
2803                 if (con->in_tag == CEPH_MSGR_TAG_READY)
2804                         goto more;
2805                 process_message(con);
2806                 if (con->state == CON_STATE_OPEN)
2807                         prepare_read_tag(con);
2808                 goto more;
2809         }
2810         if (con->in_tag == CEPH_MSGR_TAG_ACK ||
2811             con->in_tag == CEPH_MSGR_TAG_SEQ) {
2812                 /*
2813                  * the final handshake seq exchange is semantically
2814                  * equivalent to an ACK
2815                  */
2816                 ret = read_partial_ack(con);
2817                 if (ret <= 0)
2818                         goto out;
2819                 process_ack(con);
2820                 goto more;
2821         }
2822         if (con->in_tag == CEPH_MSGR_TAG_KEEPALIVE2_ACK) {
2823                 ret = read_keepalive_ack(con);
2824                 if (ret <= 0)
2825                         goto out;
2826                 goto more;
2827         }
2828
2829 out:
2830         dout("try_read done on %p ret %d\n", con, ret);
2831         return ret;
2832
2833 bad_tag:
2834         pr_err("try_read bad con->in_tag = %d\n", (int)con->in_tag);
2835         con->error_msg = "protocol error, garbage tag";
2836         ret = -1;
2837         goto out;
2838 }
2839
2840
2841 /*
2842  * Atomically queue work on a connection after the specified delay.
2843  * Bump @con reference to avoid races with connection teardown.
2844  * Returns 0 if work was queued, or an error code otherwise.
2845  */
2846 static int queue_con_delay(struct ceph_connection *con, unsigned long delay)
2847 {
2848         if (!con->ops->get(con)) {
2849                 dout("%s %p ref count 0\n", __func__, con);
2850                 return -ENOENT;
2851         }
2852
2853         if (!queue_delayed_work(ceph_msgr_wq, &con->work, delay)) {
2854                 dout("%s %p - already queued\n", __func__, con);
2855                 con->ops->put(con);
2856                 return -EBUSY;
2857         }
2858
2859         dout("%s %p %lu\n", __func__, con, delay);
2860         return 0;
2861 }
2862
2863 static void queue_con(struct ceph_connection *con)
2864 {
2865         (void) queue_con_delay(con, 0);
2866 }
2867
2868 static void cancel_con(struct ceph_connection *con)
2869 {
2870         if (cancel_delayed_work(&con->work)) {
2871                 dout("%s %p\n", __func__, con);
2872                 con->ops->put(con);
2873         }
2874 }
2875
2876 static bool con_sock_closed(struct ceph_connection *con)
2877 {
2878         if (!con_flag_test_and_clear(con, CON_FLAG_SOCK_CLOSED))
2879                 return false;
2880
2881 #define CASE(x)                                                         \
2882         case CON_STATE_ ## x:                                           \
2883                 con->error_msg = "socket closed (con state " #x ")";    \
2884                 break;
2885
2886         switch (con->state) {
2887         CASE(CLOSED);
2888         CASE(PREOPEN);
2889         CASE(CONNECTING);
2890         CASE(NEGOTIATING);
2891         CASE(OPEN);
2892         CASE(STANDBY);
2893         default:
2894                 pr_warn("%s con %p unrecognized state %lu\n",
2895                         __func__, con, con->state);
2896                 con->error_msg = "unrecognized con state";
2897                 BUG();
2898                 break;
2899         }
2900 #undef CASE
2901
2902         return true;
2903 }
2904
2905 static bool con_backoff(struct ceph_connection *con)
2906 {
2907         int ret;
2908
2909         if (!con_flag_test_and_clear(con, CON_FLAG_BACKOFF))
2910                 return false;
2911
2912         ret = queue_con_delay(con, round_jiffies_relative(con->delay));
2913         if (ret) {
2914                 dout("%s: con %p FAILED to back off %lu\n", __func__,
2915                         con, con->delay);
2916                 BUG_ON(ret == -ENOENT);
2917                 con_flag_set(con, CON_FLAG_BACKOFF);
2918         }
2919
2920         return true;
2921 }
2922
2923 /* Finish fault handling; con->mutex must *not* be held here */
2924
2925 static void con_fault_finish(struct ceph_connection *con)
2926 {
2927         dout("%s %p\n", __func__, con);
2928
2929         /*
2930          * in case we faulted due to authentication, invalidate our
2931          * current tickets so that we can get new ones.
2932          */
2933         if (con->auth_retry) {
2934                 dout("auth_retry %d, invalidating\n", con->auth_retry);
2935                 if (con->ops->invalidate_authorizer)
2936                         con->ops->invalidate_authorizer(con);
2937                 con->auth_retry = 0;
2938         }
2939
2940         if (con->ops->fault)
2941                 con->ops->fault(con);
2942 }
2943
2944 /*
2945  * Do some work on a connection.  Drop a connection ref when we're done.
2946  */
2947 static void ceph_con_workfn(struct work_struct *work)
2948 {
2949         struct ceph_connection *con = container_of(work, struct ceph_connection,
2950                                                    work.work);
2951         bool fault;
2952
2953         mutex_lock(&con->mutex);
2954         while (true) {
2955                 int ret;
2956
2957                 if ((fault = con_sock_closed(con))) {
2958                         dout("%s: con %p SOCK_CLOSED\n", __func__, con);
2959                         break;
2960                 }
2961                 if (con_backoff(con)) {
2962                         dout("%s: con %p BACKOFF\n", __func__, con);
2963                         break;
2964                 }
2965                 if (con->state == CON_STATE_STANDBY) {
2966                         dout("%s: con %p STANDBY\n", __func__, con);
2967                         break;
2968                 }
2969                 if (con->state == CON_STATE_CLOSED) {
2970                         dout("%s: con %p CLOSED\n", __func__, con);
2971                         BUG_ON(con->sock);
2972                         break;
2973                 }
2974                 if (con->state == CON_STATE_PREOPEN) {
2975                         dout("%s: con %p PREOPEN\n", __func__, con);
2976                         BUG_ON(con->sock);
2977                 }
2978
2979                 ret = try_read(con);
2980                 if (ret < 0) {
2981                         if (ret == -EAGAIN)
2982                                 continue;
2983                         if (!con->error_msg)
2984                                 con->error_msg = "socket error on read";
2985                         fault = true;
2986                         break;
2987                 }
2988
2989                 ret = try_write(con);
2990                 if (ret < 0) {
2991                         if (ret == -EAGAIN)
2992                                 continue;
2993                         if (!con->error_msg)
2994                                 con->error_msg = "socket error on write";
2995                         fault = true;
2996                 }
2997
2998                 break;  /* If we make it to here, we're done */
2999         }
3000         if (fault)
3001                 con_fault(con);
3002         mutex_unlock(&con->mutex);
3003
3004         if (fault)
3005                 con_fault_finish(con);
3006
3007         con->ops->put(con);
3008 }
3009
3010 /*
3011  * Generic error/fault handler.  A retry mechanism is used with
3012  * exponential backoff
3013  */
3014 static void con_fault(struct ceph_connection *con)
3015 {
3016         dout("fault %p state %lu to peer %s\n",
3017              con, con->state, ceph_pr_addr(&con->peer_addr.in_addr));
3018
3019         pr_warn("%s%lld %s %s\n", ENTITY_NAME(con->peer_name),
3020                 ceph_pr_addr(&con->peer_addr.in_addr), con->error_msg);
3021         con->error_msg = NULL;
3022
3023         WARN_ON(con->state != CON_STATE_CONNECTING &&
3024                con->state != CON_STATE_NEGOTIATING &&
3025                con->state != CON_STATE_OPEN);
3026
3027         con_close_socket(con);
3028
3029         if (con_flag_test(con, CON_FLAG_LOSSYTX)) {
3030                 dout("fault on LOSSYTX channel, marking CLOSED\n");
3031                 con->state = CON_STATE_CLOSED;
3032                 return;
3033         }
3034
3035         if (con->in_msg) {
3036                 BUG_ON(con->in_msg->con != con);
3037                 ceph_msg_put(con->in_msg);
3038                 con->in_msg = NULL;
3039         }
3040         if (con->out_msg) {
3041                 BUG_ON(con->out_msg->con != con);
3042                 ceph_msg_put(con->out_msg);
3043                 con->out_msg = NULL;
3044         }
3045
3046         /* Requeue anything that hasn't been acked */
3047         list_splice_init(&con->out_sent, &con->out_queue);
3048
3049         /* If there are no messages queued or keepalive pending, place
3050          * the connection in a STANDBY state */
3051         if (list_empty(&con->out_queue) &&
3052             !con_flag_test(con, CON_FLAG_KEEPALIVE_PENDING)) {
3053                 dout("fault %p setting STANDBY clearing WRITE_PENDING\n", con);
3054                 con_flag_clear(con, CON_FLAG_WRITE_PENDING);
3055                 con->state = CON_STATE_STANDBY;
3056         } else {
3057                 /* retry after a delay. */
3058                 con->state = CON_STATE_PREOPEN;
3059                 if (con->delay == 0)
3060                         con->delay = BASE_DELAY_INTERVAL;
3061                 else if (con->delay < MAX_DELAY_INTERVAL)
3062                         con->delay *= 2;
3063                 con_flag_set(con, CON_FLAG_BACKOFF);
3064                 queue_con(con);
3065         }
3066 }
3067
3068
3069
3070 /*
3071  * initialize a new messenger instance
3072  */
3073 void ceph_messenger_init(struct ceph_messenger *msgr,
3074                          struct ceph_entity_addr *myaddr)
3075 {
3076         spin_lock_init(&msgr->global_seq_lock);
3077
3078         if (myaddr)
3079                 msgr->inst.addr = *myaddr;
3080
3081         /* select a random nonce */
3082         msgr->inst.addr.type = 0;
3083         get_random_bytes(&msgr->inst.addr.nonce, sizeof(msgr->inst.addr.nonce));
3084         encode_my_addr(msgr);
3085
3086         atomic_set(&msgr->stopping, 0);
3087         write_pnet(&msgr->net, get_net(current->nsproxy->net_ns));
3088
3089         dout("%s %p\n", __func__, msgr);
3090 }
3091 EXPORT_SYMBOL(ceph_messenger_init);
3092
3093 void ceph_messenger_fini(struct ceph_messenger *msgr)
3094 {
3095         put_net(read_pnet(&msgr->net));
3096 }
3097 EXPORT_SYMBOL(ceph_messenger_fini);
3098
3099 static void msg_con_set(struct ceph_msg *msg, struct ceph_connection *con)
3100 {
3101         if (msg->con)
3102                 msg->con->ops->put(msg->con);
3103
3104         msg->con = con ? con->ops->get(con) : NULL;
3105         BUG_ON(msg->con != con);
3106 }
3107
3108 static void clear_standby(struct ceph_connection *con)
3109 {
3110         /* come back from STANDBY? */
3111         if (con->state == CON_STATE_STANDBY) {
3112                 dout("clear_standby %p and ++connect_seq\n", con);
3113                 con->state = CON_STATE_PREOPEN;
3114                 con->connect_seq++;
3115                 WARN_ON(con_flag_test(con, CON_FLAG_WRITE_PENDING));
3116                 WARN_ON(con_flag_test(con, CON_FLAG_KEEPALIVE_PENDING));
3117         }
3118 }
3119
3120 /*
3121  * Queue up an outgoing message on the given connection.
3122  */
3123 void ceph_con_send(struct ceph_connection *con, struct ceph_msg *msg)
3124 {
3125         /* set src+dst */
3126         msg->hdr.src = con->msgr->inst.name;
3127         BUG_ON(msg->front.iov_len != le32_to_cpu(msg->hdr.front_len));
3128         msg->needs_out_seq = true;
3129
3130         mutex_lock(&con->mutex);
3131
3132         if (con->state == CON_STATE_CLOSED) {
3133                 dout("con_send %p closed, dropping %p\n", con, msg);
3134                 ceph_msg_put(msg);
3135                 mutex_unlock(&con->mutex);
3136                 return;
3137         }
3138
3139         msg_con_set(msg, con);
3140
3141         BUG_ON(!list_empty(&msg->list_head));
3142         list_add_tail(&msg->list_head, &con->out_queue);
3143         dout("----- %p to %s%lld %d=%s len %d+%d+%d -----\n", msg,
3144              ENTITY_NAME(con->peer_name), le16_to_cpu(msg->hdr.type),
3145              ceph_msg_type_name(le16_to_cpu(msg->hdr.type)),
3146              le32_to_cpu(msg->hdr.front_len),
3147              le32_to_cpu(msg->hdr.middle_len),
3148              le32_to_cpu(msg->hdr.data_len));
3149
3150         clear_standby(con);
3151         mutex_unlock(&con->mutex);
3152
3153         /* if there wasn't anything waiting to send before, queue
3154          * new work */
3155         if (con_flag_test_and_set(con, CON_FLAG_WRITE_PENDING) == 0)
3156                 queue_con(con);
3157 }
3158 EXPORT_SYMBOL(ceph_con_send);
3159
3160 /*
3161  * Revoke a message that was previously queued for send
3162  */
3163 void ceph_msg_revoke(struct ceph_msg *msg)
3164 {
3165         struct ceph_connection *con = msg->con;
3166
3167         if (!con) {
3168                 dout("%s msg %p null con\n", __func__, msg);
3169                 return;         /* Message not in our possession */
3170         }
3171
3172         mutex_lock(&con->mutex);
3173         if (!list_empty(&msg->list_head)) {
3174                 dout("%s %p msg %p - was on queue\n", __func__, con, msg);
3175                 list_del_init(&msg->list_head);
3176                 msg->hdr.seq = 0;
3177
3178                 ceph_msg_put(msg);
3179         }
3180         if (con->out_msg == msg) {
3181                 BUG_ON(con->out_skip);
3182                 /* footer */
3183                 if (con->out_msg_done) {
3184                         con->out_skip += con_out_kvec_skip(con);
3185                 } else {
3186                         BUG_ON(!msg->data_length);
3187                         con->out_skip += sizeof_footer(con);
3188                 }
3189                 /* data, middle, front */
3190                 if (msg->data_length)
3191                         con->out_skip += msg->cursor.total_resid;
3192                 if (msg->middle)
3193                         con->out_skip += con_out_kvec_skip(con);
3194                 con->out_skip += con_out_kvec_skip(con);
3195
3196                 dout("%s %p msg %p - was sending, will write %d skip %d\n",
3197                      __func__, con, msg, con->out_kvec_bytes, con->out_skip);
3198                 msg->hdr.seq = 0;
3199                 con->out_msg = NULL;
3200                 ceph_msg_put(msg);
3201         }
3202
3203         mutex_unlock(&con->mutex);
3204 }
3205
3206 /*
3207  * Revoke a message that we may be reading data into
3208  */
3209 void ceph_msg_revoke_incoming(struct ceph_msg *msg)
3210 {
3211         struct ceph_connection *con = msg->con;
3212
3213         if (!con) {
3214                 dout("%s msg %p null con\n", __func__, msg);
3215                 return;         /* Message not in our possession */
3216         }
3217
3218         mutex_lock(&con->mutex);
3219         if (con->in_msg == msg) {
3220                 unsigned int front_len = le32_to_cpu(con->in_hdr.front_len);
3221                 unsigned int middle_len = le32_to_cpu(con->in_hdr.middle_len);
3222                 unsigned int data_len = le32_to_cpu(con->in_hdr.data_len);
3223
3224                 /* skip rest of message */
3225                 dout("%s %p msg %p revoked\n", __func__, con, msg);
3226                 con->in_base_pos = con->in_base_pos -
3227                                 sizeof(struct ceph_msg_header) -
3228                                 front_len -
3229                                 middle_len -
3230                                 data_len -
3231                                 sizeof(struct ceph_msg_footer);
3232                 ceph_msg_put(con->in_msg);
3233                 con->in_msg = NULL;
3234                 con->in_tag = CEPH_MSGR_TAG_READY;
3235                 con->in_seq++;
3236         } else {
3237                 dout("%s %p in_msg %p msg %p no-op\n",
3238                      __func__, con, con->in_msg, msg);
3239         }
3240         mutex_unlock(&con->mutex);
3241 }
3242
3243 /*
3244  * Queue a keepalive byte to ensure the tcp connection is alive.
3245  */
3246 void ceph_con_keepalive(struct ceph_connection *con)
3247 {
3248         dout("con_keepalive %p\n", con);
3249         mutex_lock(&con->mutex);
3250         clear_standby(con);
3251         con_flag_set(con, CON_FLAG_KEEPALIVE_PENDING);
3252         mutex_unlock(&con->mutex);
3253
3254         if (con_flag_test_and_set(con, CON_FLAG_WRITE_PENDING) == 0)
3255                 queue_con(con);
3256 }
3257 EXPORT_SYMBOL(ceph_con_keepalive);
3258
3259 bool ceph_con_keepalive_expired(struct ceph_connection *con,
3260                                unsigned long interval)
3261 {
3262         if (interval > 0 &&
3263             (con->peer_features & CEPH_FEATURE_MSGR_KEEPALIVE2)) {
3264                 struct timespec64 now;
3265                 struct timespec64 ts;
3266                 ktime_get_real_ts64(&now);
3267                 jiffies_to_timespec64(interval, &ts);
3268                 ts = timespec64_add(con->last_keepalive_ack, ts);
3269                 return timespec64_compare(&now, &ts) >= 0;
3270         }
3271         return false;
3272 }
3273
3274 static struct ceph_msg_data *ceph_msg_data_create(enum ceph_msg_data_type type)
3275 {
3276         struct ceph_msg_data *data;
3277
3278         if (WARN_ON(!ceph_msg_data_type_valid(type)))
3279                 return NULL;
3280
3281         data = kmem_cache_zalloc(ceph_msg_data_cache, GFP_NOFS);
3282         if (!data)
3283                 return NULL;
3284
3285         data->type = type;
3286         INIT_LIST_HEAD(&data->links);
3287
3288         return data;
3289 }
3290
3291 static void ceph_msg_data_destroy(struct ceph_msg_data *data)
3292 {
3293         if (!data)
3294                 return;
3295
3296         WARN_ON(!list_empty(&data->links));
3297         if (data->type == CEPH_MSG_DATA_PAGELIST)
3298                 ceph_pagelist_release(data->pagelist);
3299         kmem_cache_free(ceph_msg_data_cache, data);
3300 }
3301
3302 void ceph_msg_data_add_pages(struct ceph_msg *msg, struct page **pages,
3303                 size_t length, size_t alignment)
3304 {
3305         struct ceph_msg_data *data;
3306
3307         BUG_ON(!pages);
3308         BUG_ON(!length);
3309
3310         data = ceph_msg_data_create(CEPH_MSG_DATA_PAGES);
3311         BUG_ON(!data);
3312         data->pages = pages;
3313         data->length = length;
3314         data->alignment = alignment & ~PAGE_MASK;
3315
3316         list_add_tail(&data->links, &msg->data);
3317         msg->data_length += length;
3318 }
3319 EXPORT_SYMBOL(ceph_msg_data_add_pages);
3320
3321 void ceph_msg_data_add_pagelist(struct ceph_msg *msg,
3322                                 struct ceph_pagelist *pagelist)
3323 {
3324         struct ceph_msg_data *data;
3325
3326         BUG_ON(!pagelist);
3327         BUG_ON(!pagelist->length);
3328
3329         data = ceph_msg_data_create(CEPH_MSG_DATA_PAGELIST);
3330         BUG_ON(!data);
3331         data->pagelist = pagelist;
3332
3333         list_add_tail(&data->links, &msg->data);
3334         msg->data_length += pagelist->length;
3335 }
3336 EXPORT_SYMBOL(ceph_msg_data_add_pagelist);
3337
3338 #ifdef  CONFIG_BLOCK
3339 void ceph_msg_data_add_bio(struct ceph_msg *msg, struct ceph_bio_iter *bio_pos,
3340                            u32 length)
3341 {
3342         struct ceph_msg_data *data;
3343
3344         data = ceph_msg_data_create(CEPH_MSG_DATA_BIO);
3345         BUG_ON(!data);
3346         data->bio_pos = *bio_pos;
3347         data->bio_length = length;
3348
3349         list_add_tail(&data->links, &msg->data);
3350         msg->data_length += length;
3351 }
3352 EXPORT_SYMBOL(ceph_msg_data_add_bio);
3353 #endif  /* CONFIG_BLOCK */
3354
3355 void ceph_msg_data_add_bvecs(struct ceph_msg *msg,
3356                              struct ceph_bvec_iter *bvec_pos)
3357 {
3358         struct ceph_msg_data *data;
3359
3360         data = ceph_msg_data_create(CEPH_MSG_DATA_BVECS);
3361         BUG_ON(!data);
3362         data->bvec_pos = *bvec_pos;
3363
3364         list_add_tail(&data->links, &msg->data);
3365         msg->data_length += bvec_pos->iter.bi_size;
3366 }
3367 EXPORT_SYMBOL(ceph_msg_data_add_bvecs);
3368
3369 /*
3370  * construct a new message with given type, size
3371  * the new msg has a ref count of 1.
3372  */
3373 struct ceph_msg *ceph_msg_new(int type, int front_len, gfp_t flags,
3374                               bool can_fail)
3375 {
3376         struct ceph_msg *m;
3377
3378         m = kmem_cache_zalloc(ceph_msg_cache, flags);
3379         if (m == NULL)
3380                 goto out;
3381
3382         m->hdr.type = cpu_to_le16(type);
3383         m->hdr.priority = cpu_to_le16(CEPH_MSG_PRIO_DEFAULT);
3384         m->hdr.front_len = cpu_to_le32(front_len);
3385
3386         INIT_LIST_HEAD(&m->list_head);
3387         kref_init(&m->kref);
3388         INIT_LIST_HEAD(&m->data);
3389
3390         /* front */
3391         if (front_len) {
3392                 m->front.iov_base = ceph_kvmalloc(front_len, flags);
3393                 if (m->front.iov_base == NULL) {
3394                         dout("ceph_msg_new can't allocate %d bytes\n",
3395                              front_len);
3396                         goto out2;
3397                 }
3398         } else {
3399                 m->front.iov_base = NULL;
3400         }
3401         m->front_alloc_len = m->front.iov_len = front_len;
3402
3403         dout("ceph_msg_new %p front %d\n", m, front_len);
3404         return m;
3405
3406 out2:
3407         ceph_msg_put(m);
3408 out:
3409         if (!can_fail) {
3410                 pr_err("msg_new can't create type %d front %d\n", type,
3411                        front_len);
3412                 WARN_ON(1);
3413         } else {
3414                 dout("msg_new can't create type %d front %d\n", type,
3415                      front_len);
3416         }
3417         return NULL;
3418 }
3419 EXPORT_SYMBOL(ceph_msg_new);
3420
3421 /*
3422  * Allocate "middle" portion of a message, if it is needed and wasn't
3423  * allocated by alloc_msg.  This allows us to read a small fixed-size
3424  * per-type header in the front and then gracefully fail (i.e.,
3425  * propagate the error to the caller based on info in the front) when
3426  * the middle is too large.
3427  */
3428 static int ceph_alloc_middle(struct ceph_connection *con, struct ceph_msg *msg)
3429 {
3430         int type = le16_to_cpu(msg->hdr.type);
3431         int middle_len = le32_to_cpu(msg->hdr.middle_len);
3432
3433         dout("alloc_middle %p type %d %s middle_len %d\n", msg, type,
3434              ceph_msg_type_name(type), middle_len);
3435         BUG_ON(!middle_len);
3436         BUG_ON(msg->middle);
3437
3438         msg->middle = ceph_buffer_new(middle_len, GFP_NOFS);
3439         if (!msg->middle)
3440                 return -ENOMEM;
3441         return 0;
3442 }
3443
3444 /*
3445  * Allocate a message for receiving an incoming message on a
3446  * connection, and save the result in con->in_msg.  Uses the
3447  * connection's private alloc_msg op if available.
3448  *
3449  * Returns 0 on success, or a negative error code.
3450  *
3451  * On success, if we set *skip = 1:
3452  *  - the next message should be skipped and ignored.
3453  *  - con->in_msg == NULL
3454  * or if we set *skip = 0:
3455  *  - con->in_msg is non-null.
3456  * On error (ENOMEM, EAGAIN, ...),
3457  *  - con->in_msg == NULL
3458  */
3459 static int ceph_con_in_msg_alloc(struct ceph_connection *con, int *skip)
3460 {
3461         struct ceph_msg_header *hdr = &con->in_hdr;
3462         int middle_len = le32_to_cpu(hdr->middle_len);
3463         struct ceph_msg *msg;
3464         int ret = 0;
3465
3466         BUG_ON(con->in_msg != NULL);
3467         BUG_ON(!con->ops->alloc_msg);
3468
3469         mutex_unlock(&con->mutex);
3470         msg = con->ops->alloc_msg(con, hdr, skip);
3471         mutex_lock(&con->mutex);
3472         if (con->state != CON_STATE_OPEN) {
3473                 if (msg)
3474                         ceph_msg_put(msg);
3475                 return -EAGAIN;
3476         }
3477         if (msg) {
3478                 BUG_ON(*skip);
3479                 msg_con_set(msg, con);
3480                 con->in_msg = msg;
3481         } else {
3482                 /*
3483                  * Null message pointer means either we should skip
3484                  * this message or we couldn't allocate memory.  The
3485                  * former is not an error.
3486                  */
3487                 if (*skip)
3488                         return 0;
3489
3490                 con->error_msg = "error allocating memory for incoming message";
3491                 return -ENOMEM;
3492         }
3493         memcpy(&con->in_msg->hdr, &con->in_hdr, sizeof(con->in_hdr));
3494
3495         if (middle_len && !con->in_msg->middle) {
3496                 ret = ceph_alloc_middle(con, con->in_msg);
3497                 if (ret < 0) {
3498                         ceph_msg_put(con->in_msg);
3499                         con->in_msg = NULL;
3500                 }
3501         }
3502
3503         return ret;
3504 }
3505
3506
3507 /*
3508  * Free a generically kmalloc'd message.
3509  */
3510 static void ceph_msg_free(struct ceph_msg *m)
3511 {
3512         dout("%s %p\n", __func__, m);
3513         kvfree(m->front.iov_base);
3514         kmem_cache_free(ceph_msg_cache, m);
3515 }
3516
3517 static void ceph_msg_release(struct kref *kref)
3518 {
3519         struct ceph_msg *m = container_of(kref, struct ceph_msg, kref);
3520         struct ceph_msg_data *data, *next;
3521
3522         dout("%s %p\n", __func__, m);
3523         WARN_ON(!list_empty(&m->list_head));
3524
3525         msg_con_set(m, NULL);
3526
3527         /* drop middle, data, if any */
3528         if (m->middle) {
3529                 ceph_buffer_put(m->middle);
3530                 m->middle = NULL;
3531         }
3532
3533         list_for_each_entry_safe(data, next, &m->data, links) {
3534                 list_del_init(&data->links);
3535                 ceph_msg_data_destroy(data);
3536         }
3537         m->data_length = 0;
3538
3539         if (m->pool)
3540                 ceph_msgpool_put(m->pool, m);
3541         else
3542                 ceph_msg_free(m);
3543 }
3544
3545 struct ceph_msg *ceph_msg_get(struct ceph_msg *msg)
3546 {
3547         dout("%s %p (was %d)\n", __func__, msg,
3548              kref_read(&msg->kref));
3549         kref_get(&msg->kref);
3550         return msg;
3551 }
3552 EXPORT_SYMBOL(ceph_msg_get);
3553
3554 void ceph_msg_put(struct ceph_msg *msg)
3555 {
3556         dout("%s %p (was %d)\n", __func__, msg,
3557              kref_read(&msg->kref));
3558         kref_put(&msg->kref, ceph_msg_release);
3559 }
3560 EXPORT_SYMBOL(ceph_msg_put);
3561
3562 void ceph_msg_dump(struct ceph_msg *msg)
3563 {
3564         pr_debug("msg_dump %p (front_alloc_len %d length %zd)\n", msg,
3565                  msg->front_alloc_len, msg->data_length);
3566         print_hex_dump(KERN_DEBUG, "header: ",
3567                        DUMP_PREFIX_OFFSET, 16, 1,
3568                        &msg->hdr, sizeof(msg->hdr), true);
3569         print_hex_dump(KERN_DEBUG, " front: ",
3570                        DUMP_PREFIX_OFFSET, 16, 1,
3571                        msg->front.iov_base, msg->front.iov_len, true);
3572         if (msg->middle)
3573                 print_hex_dump(KERN_DEBUG, "middle: ",
3574                                DUMP_PREFIX_OFFSET, 16, 1,
3575                                msg->middle->vec.iov_base,
3576                                msg->middle->vec.iov_len, true);
3577         print_hex_dump(KERN_DEBUG, "footer: ",
3578                        DUMP_PREFIX_OFFSET, 16, 1,
3579                        &msg->footer, sizeof(msg->footer), true);
3580 }
3581 EXPORT_SYMBOL(ceph_msg_dump);