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