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