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