c3b2091075e2e4f829a846440bb3516acfdad903
[pandora-kernel.git] / net / ceph / messenger.c
1 #include <linux/ceph/ceph_debug.h>
2
3 #include <linux/crc32c.h>
4 #include <linux/ctype.h>
5 #include <linux/highmem.h>
6 #include <linux/inet.h>
7 #include <linux/kthread.h>
8 #include <linux/net.h>
9 #include <linux/slab.h>
10 #include <linux/socket.h>
11 #include <linux/string.h>
12 #include <linux/bio.h>
13 #include <linux/blkdev.h>
14 #include <linux/dns_resolver.h>
15 #include <net/tcp.h>
16
17 #include <linux/ceph/libceph.h>
18 #include <linux/ceph/messenger.h>
19 #include <linux/ceph/decode.h>
20 #include <linux/ceph/pagelist.h>
21 #include <linux/export.h>
22
23 /*
24  * Ceph uses the messenger to exchange ceph_msg messages with other
25  * hosts in the system.  The messenger provides ordered and reliable
26  * delivery.  We tolerate TCP disconnects by reconnecting (with
27  * exponential backoff) in the case of a fault (disconnection, bad
28  * crc, protocol error).  Acks allow sent messages to be discarded by
29  * the sender.
30  */
31
32 /* static tag bytes (protocol control messages) */
33 static char tag_msg = CEPH_MSGR_TAG_MSG;
34 static char tag_ack = CEPH_MSGR_TAG_ACK;
35 static char tag_keepalive = CEPH_MSGR_TAG_KEEPALIVE;
36
37 #ifdef CONFIG_LOCKDEP
38 static struct lock_class_key socket_class;
39 #endif
40
41
42 static void queue_con(struct ceph_connection *con);
43 static void con_work(struct work_struct *);
44 static void ceph_fault(struct ceph_connection *con);
45
46 /*
47  * nicely render a sockaddr as a string.
48  */
49 #define MAX_ADDR_STR 20
50 #define MAX_ADDR_STR_LEN 60
51 static char addr_str[MAX_ADDR_STR][MAX_ADDR_STR_LEN];
52 static DEFINE_SPINLOCK(addr_str_lock);
53 static int last_addr_str;
54
55 const char *ceph_pr_addr(const struct sockaddr_storage *ss)
56 {
57         int i;
58         char *s;
59         struct sockaddr_in *in4 = (void *)ss;
60         struct sockaddr_in6 *in6 = (void *)ss;
61
62         spin_lock(&addr_str_lock);
63         i = last_addr_str++;
64         if (last_addr_str == MAX_ADDR_STR)
65                 last_addr_str = 0;
66         spin_unlock(&addr_str_lock);
67         s = addr_str[i];
68
69         switch (ss->ss_family) {
70         case AF_INET:
71                 snprintf(s, MAX_ADDR_STR_LEN, "%pI4:%u", &in4->sin_addr,
72                          (unsigned int)ntohs(in4->sin_port));
73                 break;
74
75         case AF_INET6:
76                 snprintf(s, MAX_ADDR_STR_LEN, "[%pI6c]:%u", &in6->sin6_addr,
77                          (unsigned int)ntohs(in6->sin6_port));
78                 break;
79
80         default:
81                 snprintf(s, MAX_ADDR_STR_LEN, "(unknown sockaddr family %d)",
82                          (int)ss->ss_family);
83         }
84
85         return s;
86 }
87 EXPORT_SYMBOL(ceph_pr_addr);
88
89 static void encode_my_addr(struct ceph_messenger *msgr)
90 {
91         memcpy(&msgr->my_enc_addr, &msgr->inst.addr, sizeof(msgr->my_enc_addr));
92         ceph_encode_addr(&msgr->my_enc_addr);
93 }
94
95 /*
96  * work queue for all reading and writing to/from the socket.
97  */
98 struct workqueue_struct *ceph_msgr_wq;
99
100 int ceph_msgr_init(void)
101 {
102         ceph_msgr_wq = alloc_workqueue("ceph-msgr", WQ_NON_REENTRANT, 0);
103         if (!ceph_msgr_wq) {
104                 pr_err("msgr_init failed to create workqueue\n");
105                 return -ENOMEM;
106         }
107         return 0;
108 }
109 EXPORT_SYMBOL(ceph_msgr_init);
110
111 void ceph_msgr_exit(void)
112 {
113         destroy_workqueue(ceph_msgr_wq);
114 }
115 EXPORT_SYMBOL(ceph_msgr_exit);
116
117 void ceph_msgr_flush(void)
118 {
119         flush_workqueue(ceph_msgr_wq);
120 }
121 EXPORT_SYMBOL(ceph_msgr_flush);
122
123
124 /*
125  * socket callback functions
126  */
127
128 /* data available on socket, or listen socket received a connect */
129 static void ceph_data_ready(struct sock *sk, int count_unused)
130 {
131         struct ceph_connection *con =
132                 (struct ceph_connection *)sk->sk_user_data;
133         if (sk->sk_state != TCP_CLOSE_WAIT) {
134                 dout("ceph_data_ready on %p state = %lu, queueing work\n",
135                      con, con->state);
136                 queue_con(con);
137         }
138 }
139
140 /* socket has buffer space for writing */
141 static void ceph_write_space(struct sock *sk)
142 {
143         struct ceph_connection *con =
144                 (struct ceph_connection *)sk->sk_user_data;
145
146         /* only queue to workqueue if there is data we want to write. */
147         if (test_bit(WRITE_PENDING, &con->state)) {
148                 dout("ceph_write_space %p queueing write work\n", con);
149                 queue_con(con);
150         } else {
151                 dout("ceph_write_space %p nothing to write\n", con);
152         }
153
154         /* since we have our own write_space, clear the SOCK_NOSPACE flag */
155         clear_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
156 }
157
158 /* socket's state has changed */
159 static void ceph_state_change(struct sock *sk)
160 {
161         struct ceph_connection *con =
162                 (struct ceph_connection *)sk->sk_user_data;
163
164         dout("ceph_state_change %p state = %lu sk_state = %u\n",
165              con, con->state, sk->sk_state);
166
167         if (test_bit(CLOSED, &con->state))
168                 return;
169
170         switch (sk->sk_state) {
171         case TCP_CLOSE:
172                 dout("ceph_state_change TCP_CLOSE\n");
173         case TCP_CLOSE_WAIT:
174                 dout("ceph_state_change TCP_CLOSE_WAIT\n");
175                 if (test_and_set_bit(SOCK_CLOSED, &con->state) == 0) {
176                         if (test_bit(CONNECTING, &con->state))
177                                 con->error_msg = "connection failed";
178                         else
179                                 con->error_msg = "socket closed";
180                         queue_con(con);
181                 }
182                 break;
183         case TCP_ESTABLISHED:
184                 dout("ceph_state_change TCP_ESTABLISHED\n");
185                 queue_con(con);
186                 break;
187         }
188 }
189
190 /*
191  * set up socket callbacks
192  */
193 static void set_sock_callbacks(struct socket *sock,
194                                struct ceph_connection *con)
195 {
196         struct sock *sk = sock->sk;
197         sk->sk_user_data = (void *)con;
198         sk->sk_data_ready = ceph_data_ready;
199         sk->sk_write_space = ceph_write_space;
200         sk->sk_state_change = ceph_state_change;
201 }
202
203
204 /*
205  * socket helpers
206  */
207
208 /*
209  * initiate connection to a remote socket.
210  */
211 static struct socket *ceph_tcp_connect(struct ceph_connection *con)
212 {
213         struct sockaddr_storage *paddr = &con->peer_addr.in_addr;
214         struct socket *sock;
215         int ret;
216
217         BUG_ON(con->sock);
218         ret = sock_create_kern(con->peer_addr.in_addr.ss_family, SOCK_STREAM,
219                                IPPROTO_TCP, &sock);
220         if (ret)
221                 return ERR_PTR(ret);
222         con->sock = sock;
223         sock->sk->sk_allocation = GFP_NOFS;
224
225 #ifdef CONFIG_LOCKDEP
226         lockdep_set_class(&sock->sk->sk_lock, &socket_class);
227 #endif
228
229         set_sock_callbacks(sock, con);
230
231         dout("connect %s\n", ceph_pr_addr(&con->peer_addr.in_addr));
232
233         ret = sock->ops->connect(sock, (struct sockaddr *)paddr, sizeof(*paddr),
234                                  O_NONBLOCK);
235         if (ret == -EINPROGRESS) {
236                 dout("connect %s EINPROGRESS sk_state = %u\n",
237                      ceph_pr_addr(&con->peer_addr.in_addr),
238                      sock->sk->sk_state);
239                 ret = 0;
240         }
241         if (ret < 0) {
242                 pr_err("connect %s error %d\n",
243                        ceph_pr_addr(&con->peer_addr.in_addr), ret);
244                 sock_release(sock);
245                 con->sock = NULL;
246                 con->error_msg = "connect error";
247         }
248
249         if (ret < 0)
250                 return ERR_PTR(ret);
251         return sock;
252 }
253
254 static int ceph_tcp_recvmsg(struct socket *sock, void *buf, size_t len)
255 {
256         struct kvec iov = {buf, len};
257         struct msghdr msg = { .msg_flags = MSG_DONTWAIT | MSG_NOSIGNAL };
258         int r;
259
260         r = kernel_recvmsg(sock, &msg, &iov, 1, len, msg.msg_flags);
261         if (r == -EAGAIN)
262                 r = 0;
263         return r;
264 }
265
266 /*
267  * write something.  @more is true if caller will be sending more data
268  * shortly.
269  */
270 static int ceph_tcp_sendmsg(struct socket *sock, struct kvec *iov,
271                      size_t kvlen, size_t len, int more)
272 {
273         struct msghdr msg = { .msg_flags = MSG_DONTWAIT | MSG_NOSIGNAL };
274         int r;
275
276         if (more)
277                 msg.msg_flags |= MSG_MORE;
278         else
279                 msg.msg_flags |= MSG_EOR;  /* superfluous, but what the hell */
280
281         r = kernel_sendmsg(sock, &msg, iov, kvlen, len);
282         if (r == -EAGAIN)
283                 r = 0;
284         return r;
285 }
286
287 static int ceph_tcp_sendpage(struct socket *sock, struct page *page,
288                      int offset, size_t size, bool more)
289 {
290         int flags = MSG_DONTWAIT | MSG_NOSIGNAL | (more ? MSG_MORE : MSG_EOR);
291         int ret;
292
293         ret = kernel_sendpage(sock, page, offset, size, flags);
294         if (ret == -EAGAIN)
295                 ret = 0;
296
297         return ret;
298 }
299
300
301 /*
302  * Shutdown/close the socket for the given connection.
303  */
304 static int con_close_socket(struct ceph_connection *con)
305 {
306         int rc;
307
308         dout("con_close_socket on %p sock %p\n", con, con->sock);
309         if (!con->sock)
310                 return 0;
311         set_bit(SOCK_CLOSED, &con->state);
312         rc = con->sock->ops->shutdown(con->sock, SHUT_RDWR);
313         sock_release(con->sock);
314         con->sock = NULL;
315         clear_bit(SOCK_CLOSED, &con->state);
316         return rc;
317 }
318
319 /*
320  * Reset a connection.  Discard all incoming and outgoing messages
321  * and clear *_seq state.
322  */
323 static void ceph_msg_remove(struct ceph_msg *msg)
324 {
325         list_del_init(&msg->list_head);
326         ceph_msg_put(msg);
327 }
328 static void ceph_msg_remove_list(struct list_head *head)
329 {
330         while (!list_empty(head)) {
331                 struct ceph_msg *msg = list_first_entry(head, struct ceph_msg,
332                                                         list_head);
333                 ceph_msg_remove(msg);
334         }
335 }
336
337 static void reset_connection(struct ceph_connection *con)
338 {
339         /* reset connection, out_queue, msg_ and connect_seq */
340         /* discard existing out_queue and msg_seq */
341         ceph_msg_remove_list(&con->out_queue);
342         ceph_msg_remove_list(&con->out_sent);
343
344         if (con->in_msg) {
345                 ceph_msg_put(con->in_msg);
346                 con->in_msg = NULL;
347         }
348
349         con->connect_seq = 0;
350         con->out_seq = 0;
351         if (con->out_msg) {
352                 ceph_msg_put(con->out_msg);
353                 con->out_msg = NULL;
354         }
355         con->in_seq = 0;
356         con->in_seq_acked = 0;
357 }
358
359 /*
360  * mark a peer down.  drop any open connections.
361  */
362 void ceph_con_close(struct ceph_connection *con)
363 {
364         dout("con_close %p peer %s\n", con,
365              ceph_pr_addr(&con->peer_addr.in_addr));
366         set_bit(CLOSED, &con->state);  /* in case there's queued work */
367         clear_bit(STANDBY, &con->state);  /* avoid connect_seq bump */
368         clear_bit(LOSSYTX, &con->state);  /* so we retry next connect */
369         clear_bit(KEEPALIVE_PENDING, &con->state);
370         clear_bit(WRITE_PENDING, &con->state);
371         mutex_lock(&con->mutex);
372         reset_connection(con);
373         con->peer_global_seq = 0;
374         cancel_delayed_work(&con->work);
375         mutex_unlock(&con->mutex);
376         queue_con(con);
377 }
378 EXPORT_SYMBOL(ceph_con_close);
379
380 /*
381  * Reopen a closed connection, with a new peer address.
382  */
383 void ceph_con_open(struct ceph_connection *con, struct ceph_entity_addr *addr)
384 {
385         dout("con_open %p %s\n", con, ceph_pr_addr(&addr->in_addr));
386         set_bit(OPENING, &con->state);
387         clear_bit(CLOSED, &con->state);
388         memcpy(&con->peer_addr, addr, sizeof(*addr));
389         con->delay = 0;      /* reset backoff memory */
390         queue_con(con);
391 }
392 EXPORT_SYMBOL(ceph_con_open);
393
394 /*
395  * return true if this connection ever successfully opened
396  */
397 bool ceph_con_opened(struct ceph_connection *con)
398 {
399         return con->connect_seq > 0;
400 }
401
402 /*
403  * generic get/put
404  */
405 struct ceph_connection *ceph_con_get(struct ceph_connection *con)
406 {
407         dout("con_get %p nref = %d -> %d\n", con,
408              atomic_read(&con->nref), atomic_read(&con->nref) + 1);
409         if (atomic_inc_not_zero(&con->nref))
410                 return con;
411         return NULL;
412 }
413
414 void ceph_con_put(struct ceph_connection *con)
415 {
416         dout("con_put %p nref = %d -> %d\n", con,
417              atomic_read(&con->nref), atomic_read(&con->nref) - 1);
418         BUG_ON(atomic_read(&con->nref) == 0);
419         if (atomic_dec_and_test(&con->nref)) {
420                 BUG_ON(con->sock);
421                 kfree(con);
422         }
423 }
424
425 /*
426  * initialize a new connection.
427  */
428 void ceph_con_init(struct ceph_messenger *msgr, struct ceph_connection *con)
429 {
430         dout("con_init %p\n", con);
431         memset(con, 0, sizeof(*con));
432         atomic_set(&con->nref, 1);
433         con->msgr = msgr;
434         mutex_init(&con->mutex);
435         INIT_LIST_HEAD(&con->out_queue);
436         INIT_LIST_HEAD(&con->out_sent);
437         INIT_DELAYED_WORK(&con->work, con_work);
438 }
439 EXPORT_SYMBOL(ceph_con_init);
440
441
442 /*
443  * We maintain a global counter to order connection attempts.  Get
444  * a unique seq greater than @gt.
445  */
446 static u32 get_global_seq(struct ceph_messenger *msgr, u32 gt)
447 {
448         u32 ret;
449
450         spin_lock(&msgr->global_seq_lock);
451         if (msgr->global_seq < gt)
452                 msgr->global_seq = gt;
453         ret = ++msgr->global_seq;
454         spin_unlock(&msgr->global_seq_lock);
455         return ret;
456 }
457
458
459 /*
460  * Prepare footer for currently outgoing message, and finish things
461  * off.  Assumes out_kvec* are already valid.. we just add on to the end.
462  */
463 static void prepare_write_message_footer(struct ceph_connection *con, int v)
464 {
465         struct ceph_msg *m = con->out_msg;
466
467         dout("prepare_write_message_footer %p\n", con);
468         con->out_kvec_is_msg = true;
469         con->out_kvec[v].iov_base = &m->footer;
470         con->out_kvec[v].iov_len = sizeof(m->footer);
471         con->out_kvec_bytes += sizeof(m->footer);
472         con->out_kvec_left++;
473         con->out_more = m->more_to_follow;
474         con->out_msg_done = true;
475 }
476
477 /*
478  * Prepare headers for the next outgoing message.
479  */
480 static void prepare_write_message(struct ceph_connection *con)
481 {
482         struct ceph_msg *m;
483         int v = 0;
484
485         con->out_kvec_bytes = 0;
486         con->out_kvec_is_msg = true;
487         con->out_msg_done = false;
488
489         /* Sneak an ack in there first?  If we can get it into the same
490          * TCP packet that's a good thing. */
491         if (con->in_seq > con->in_seq_acked) {
492                 con->in_seq_acked = con->in_seq;
493                 con->out_kvec[v].iov_base = &tag_ack;
494                 con->out_kvec[v++].iov_len = 1;
495                 con->out_temp_ack = cpu_to_le64(con->in_seq_acked);
496                 con->out_kvec[v].iov_base = &con->out_temp_ack;
497                 con->out_kvec[v++].iov_len = sizeof(con->out_temp_ack);
498                 con->out_kvec_bytes = 1 + sizeof(con->out_temp_ack);
499         }
500
501         m = list_first_entry(&con->out_queue,
502                        struct ceph_msg, list_head);
503         con->out_msg = m;
504
505         /* put message on sent list */
506         ceph_msg_get(m);
507         list_move_tail(&m->list_head, &con->out_sent);
508
509         /*
510          * only assign outgoing seq # if we haven't sent this message
511          * yet.  if it is requeued, resend with it's original seq.
512          */
513         if (m->needs_out_seq) {
514                 m->hdr.seq = cpu_to_le64(++con->out_seq);
515                 m->needs_out_seq = false;
516         }
517
518         dout("prepare_write_message %p seq %lld type %d len %d+%d+%d %d pgs\n",
519              m, con->out_seq, le16_to_cpu(m->hdr.type),
520              le32_to_cpu(m->hdr.front_len), le32_to_cpu(m->hdr.middle_len),
521              le32_to_cpu(m->hdr.data_len),
522              m->nr_pages);
523         BUG_ON(le32_to_cpu(m->hdr.front_len) != m->front.iov_len);
524
525         /* tag + hdr + front + middle */
526         con->out_kvec[v].iov_base = &tag_msg;
527         con->out_kvec[v++].iov_len = 1;
528         con->out_kvec[v].iov_base = &m->hdr;
529         con->out_kvec[v++].iov_len = sizeof(m->hdr);
530         con->out_kvec[v++] = m->front;
531         if (m->middle)
532                 con->out_kvec[v++] = m->middle->vec;
533         con->out_kvec_left = v;
534         con->out_kvec_bytes += 1 + sizeof(m->hdr) + m->front.iov_len +
535                 (m->middle ? m->middle->vec.iov_len : 0);
536         con->out_kvec_cur = con->out_kvec;
537
538         /* fill in crc (except data pages), footer */
539         con->out_msg->hdr.crc =
540                 cpu_to_le32(crc32c(0, (void *)&m->hdr,
541                                       sizeof(m->hdr) - sizeof(m->hdr.crc)));
542         con->out_msg->footer.flags = CEPH_MSG_FOOTER_COMPLETE;
543         con->out_msg->footer.front_crc =
544                 cpu_to_le32(crc32c(0, m->front.iov_base, m->front.iov_len));
545         if (m->middle)
546                 con->out_msg->footer.middle_crc =
547                         cpu_to_le32(crc32c(0, m->middle->vec.iov_base,
548                                            m->middle->vec.iov_len));
549         else
550                 con->out_msg->footer.middle_crc = 0;
551         con->out_msg->footer.data_crc = 0;
552         dout("prepare_write_message front_crc %u data_crc %u\n",
553              le32_to_cpu(con->out_msg->footer.front_crc),
554              le32_to_cpu(con->out_msg->footer.middle_crc));
555
556         /* is there a data payload? */
557         if (le32_to_cpu(m->hdr.data_len) > 0) {
558                 /* initialize page iterator */
559                 con->out_msg_pos.page = 0;
560                 if (m->pages)
561                         con->out_msg_pos.page_pos = m->page_alignment;
562                 else
563                         con->out_msg_pos.page_pos = 0;
564                 con->out_msg_pos.data_pos = 0;
565                 con->out_msg_pos.did_page_crc = 0;
566                 con->out_more = 1;  /* data + footer will follow */
567         } else {
568                 /* no, queue up footer too and be done */
569                 prepare_write_message_footer(con, v);
570         }
571
572         set_bit(WRITE_PENDING, &con->state);
573 }
574
575 /*
576  * Prepare an ack.
577  */
578 static void prepare_write_ack(struct ceph_connection *con)
579 {
580         dout("prepare_write_ack %p %llu -> %llu\n", con,
581              con->in_seq_acked, con->in_seq);
582         con->in_seq_acked = con->in_seq;
583
584         con->out_kvec[0].iov_base = &tag_ack;
585         con->out_kvec[0].iov_len = 1;
586         con->out_temp_ack = cpu_to_le64(con->in_seq_acked);
587         con->out_kvec[1].iov_base = &con->out_temp_ack;
588         con->out_kvec[1].iov_len = sizeof(con->out_temp_ack);
589         con->out_kvec_left = 2;
590         con->out_kvec_bytes = 1 + sizeof(con->out_temp_ack);
591         con->out_kvec_cur = con->out_kvec;
592         con->out_more = 1;  /* more will follow.. eventually.. */
593         set_bit(WRITE_PENDING, &con->state);
594 }
595
596 /*
597  * Prepare to write keepalive byte.
598  */
599 static void prepare_write_keepalive(struct ceph_connection *con)
600 {
601         dout("prepare_write_keepalive %p\n", con);
602         con->out_kvec[0].iov_base = &tag_keepalive;
603         con->out_kvec[0].iov_len = 1;
604         con->out_kvec_left = 1;
605         con->out_kvec_bytes = 1;
606         con->out_kvec_cur = con->out_kvec;
607         set_bit(WRITE_PENDING, &con->state);
608 }
609
610 /*
611  * Connection negotiation.
612  */
613
614 static int prepare_connect_authorizer(struct ceph_connection *con)
615 {
616         void *auth_buf;
617         int auth_len = 0;
618         int auth_protocol = 0;
619
620         mutex_unlock(&con->mutex);
621         if (con->ops->get_authorizer)
622                 con->ops->get_authorizer(con, &auth_buf, &auth_len,
623                                          &auth_protocol, &con->auth_reply_buf,
624                                          &con->auth_reply_buf_len,
625                                          con->auth_retry);
626         mutex_lock(&con->mutex);
627
628         if (test_bit(CLOSED, &con->state) ||
629             test_bit(OPENING, &con->state))
630                 return -EAGAIN;
631
632         con->out_connect.authorizer_protocol = cpu_to_le32(auth_protocol);
633         con->out_connect.authorizer_len = cpu_to_le32(auth_len);
634
635         if (auth_len) {
636                 con->out_kvec[con->out_kvec_left].iov_base = auth_buf;
637                 con->out_kvec[con->out_kvec_left].iov_len = auth_len;
638                 con->out_kvec_left++;
639                 con->out_kvec_bytes += auth_len;
640         }
641         return 0;
642 }
643
644 /*
645  * We connected to a peer and are saying hello.
646  */
647 static void prepare_write_banner(struct ceph_messenger *msgr,
648                                  struct ceph_connection *con)
649 {
650         int len = strlen(CEPH_BANNER);
651
652         con->out_kvec[0].iov_base = CEPH_BANNER;
653         con->out_kvec[0].iov_len = len;
654         con->out_kvec[1].iov_base = &msgr->my_enc_addr;
655         con->out_kvec[1].iov_len = sizeof(msgr->my_enc_addr);
656         con->out_kvec_left = 2;
657         con->out_kvec_bytes = len + sizeof(msgr->my_enc_addr);
658         con->out_kvec_cur = con->out_kvec;
659         con->out_more = 0;
660         set_bit(WRITE_PENDING, &con->state);
661 }
662
663 static int prepare_write_connect(struct ceph_messenger *msgr,
664                                  struct ceph_connection *con,
665                                  int after_banner)
666 {
667         unsigned global_seq = get_global_seq(con->msgr, 0);
668         int proto;
669
670         switch (con->peer_name.type) {
671         case CEPH_ENTITY_TYPE_MON:
672                 proto = CEPH_MONC_PROTOCOL;
673                 break;
674         case CEPH_ENTITY_TYPE_OSD:
675                 proto = CEPH_OSDC_PROTOCOL;
676                 break;
677         case CEPH_ENTITY_TYPE_MDS:
678                 proto = CEPH_MDSC_PROTOCOL;
679                 break;
680         default:
681                 BUG();
682         }
683
684         dout("prepare_write_connect %p cseq=%d gseq=%d proto=%d\n", con,
685              con->connect_seq, global_seq, proto);
686
687         con->out_connect.features = cpu_to_le64(msgr->supported_features);
688         con->out_connect.host_type = cpu_to_le32(CEPH_ENTITY_TYPE_CLIENT);
689         con->out_connect.connect_seq = cpu_to_le32(con->connect_seq);
690         con->out_connect.global_seq = cpu_to_le32(global_seq);
691         con->out_connect.protocol_version = cpu_to_le32(proto);
692         con->out_connect.flags = 0;
693
694         if (!after_banner) {
695                 con->out_kvec_left = 0;
696                 con->out_kvec_bytes = 0;
697         }
698         con->out_kvec[con->out_kvec_left].iov_base = &con->out_connect;
699         con->out_kvec[con->out_kvec_left].iov_len = sizeof(con->out_connect);
700         con->out_kvec_left++;
701         con->out_kvec_bytes += sizeof(con->out_connect);
702         con->out_kvec_cur = con->out_kvec;
703         con->out_more = 0;
704         set_bit(WRITE_PENDING, &con->state);
705
706         return prepare_connect_authorizer(con);
707 }
708
709
710 /*
711  * write as much of pending kvecs to the socket as we can.
712  *  1 -> done
713  *  0 -> socket full, but more to do
714  * <0 -> error
715  */
716 static int write_partial_kvec(struct ceph_connection *con)
717 {
718         int ret;
719
720         dout("write_partial_kvec %p %d left\n", con, con->out_kvec_bytes);
721         while (con->out_kvec_bytes > 0) {
722                 ret = ceph_tcp_sendmsg(con->sock, con->out_kvec_cur,
723                                        con->out_kvec_left, con->out_kvec_bytes,
724                                        con->out_more);
725                 if (ret <= 0)
726                         goto out;
727                 con->out_kvec_bytes -= ret;
728                 if (con->out_kvec_bytes == 0)
729                         break;            /* done */
730                 while (ret > 0) {
731                         if (ret >= con->out_kvec_cur->iov_len) {
732                                 ret -= con->out_kvec_cur->iov_len;
733                                 con->out_kvec_cur++;
734                                 con->out_kvec_left--;
735                         } else {
736                                 con->out_kvec_cur->iov_len -= ret;
737                                 con->out_kvec_cur->iov_base += ret;
738                                 ret = 0;
739                                 break;
740                         }
741                 }
742         }
743         con->out_kvec_left = 0;
744         con->out_kvec_is_msg = false;
745         ret = 1;
746 out:
747         dout("write_partial_kvec %p %d left in %d kvecs ret = %d\n", con,
748              con->out_kvec_bytes, con->out_kvec_left, ret);
749         return ret;  /* done! */
750 }
751
752 #ifdef CONFIG_BLOCK
753 static void init_bio_iter(struct bio *bio, struct bio **iter, int *seg)
754 {
755         if (!bio) {
756                 *iter = NULL;
757                 *seg = 0;
758                 return;
759         }
760         *iter = bio;
761         *seg = bio->bi_idx;
762 }
763
764 static void iter_bio_next(struct bio **bio_iter, int *seg)
765 {
766         if (*bio_iter == NULL)
767                 return;
768
769         BUG_ON(*seg >= (*bio_iter)->bi_vcnt);
770
771         (*seg)++;
772         if (*seg == (*bio_iter)->bi_vcnt)
773                 init_bio_iter((*bio_iter)->bi_next, bio_iter, seg);
774 }
775 #endif
776
777 /*
778  * Write as much message data payload as we can.  If we finish, queue
779  * up the footer.
780  *  1 -> done, footer is now queued in out_kvec[].
781  *  0 -> socket full, but more to do
782  * <0 -> error
783  */
784 static int write_partial_msg_pages(struct ceph_connection *con)
785 {
786         struct ceph_msg *msg = con->out_msg;
787         unsigned data_len = le32_to_cpu(msg->hdr.data_len);
788         size_t len;
789         int crc = con->msgr->nocrc;
790         int ret;
791         int total_max_write;
792         int in_trail = 0;
793         size_t trail_len = (msg->trail ? msg->trail->length : 0);
794
795         dout("write_partial_msg_pages %p msg %p page %d/%d offset %d\n",
796              con, con->out_msg, con->out_msg_pos.page, con->out_msg->nr_pages,
797              con->out_msg_pos.page_pos);
798
799 #ifdef CONFIG_BLOCK
800         if (msg->bio && !msg->bio_iter)
801                 init_bio_iter(msg->bio, &msg->bio_iter, &msg->bio_seg);
802 #endif
803
804         while (data_len > con->out_msg_pos.data_pos) {
805                 struct page *page = NULL;
806                 void *kaddr = NULL;
807                 int max_write = PAGE_SIZE;
808                 int page_shift = 0;
809
810                 total_max_write = data_len - trail_len -
811                         con->out_msg_pos.data_pos;
812
813                 /*
814                  * if we are calculating the data crc (the default), we need
815                  * to map the page.  if our pages[] has been revoked, use the
816                  * zero page.
817                  */
818
819                 /* have we reached the trail part of the data? */
820                 if (con->out_msg_pos.data_pos >= data_len - trail_len) {
821                         in_trail = 1;
822
823                         total_max_write = data_len - con->out_msg_pos.data_pos;
824
825                         page = list_first_entry(&msg->trail->head,
826                                                 struct page, lru);
827                         if (crc)
828                                 kaddr = kmap(page);
829                         max_write = PAGE_SIZE;
830                 } else if (msg->pages) {
831                         page = msg->pages[con->out_msg_pos.page];
832                         if (crc)
833                                 kaddr = kmap(page);
834                 } else if (msg->pagelist) {
835                         page = list_first_entry(&msg->pagelist->head,
836                                                 struct page, lru);
837                         if (crc)
838                                 kaddr = kmap(page);
839 #ifdef CONFIG_BLOCK
840                 } else if (msg->bio) {
841                         struct bio_vec *bv;
842
843                         bv = bio_iovec_idx(msg->bio_iter, msg->bio_seg);
844                         page = bv->bv_page;
845                         page_shift = bv->bv_offset;
846                         if (crc)
847                                 kaddr = kmap(page) + page_shift;
848                         max_write = bv->bv_len;
849 #endif
850                 } else {
851                         page = con->msgr->zero_page;
852                         if (crc)
853                                 kaddr = page_address(con->msgr->zero_page);
854                 }
855                 len = min_t(int, max_write - con->out_msg_pos.page_pos,
856                             total_max_write);
857
858                 if (crc && !con->out_msg_pos.did_page_crc) {
859                         void *base = kaddr + con->out_msg_pos.page_pos;
860                         u32 tmpcrc = le32_to_cpu(con->out_msg->footer.data_crc);
861
862                         BUG_ON(kaddr == NULL);
863                         con->out_msg->footer.data_crc =
864                                 cpu_to_le32(crc32c(tmpcrc, base, len));
865                         con->out_msg_pos.did_page_crc = 1;
866                 }
867                 ret = ceph_tcp_sendpage(con->sock, page,
868                                       con->out_msg_pos.page_pos + page_shift,
869                                       len, 1);
870
871                 if (crc &&
872                     (msg->pages || msg->pagelist || msg->bio || in_trail))
873                         kunmap(page);
874
875                 if (ret <= 0)
876                         goto out;
877
878                 con->out_msg_pos.data_pos += ret;
879                 con->out_msg_pos.page_pos += ret;
880                 if (ret == len) {
881                         con->out_msg_pos.page_pos = 0;
882                         con->out_msg_pos.page++;
883                         con->out_msg_pos.did_page_crc = 0;
884                         if (in_trail)
885                                 list_move_tail(&page->lru,
886                                                &msg->trail->head);
887                         else if (msg->pagelist)
888                                 list_move_tail(&page->lru,
889                                                &msg->pagelist->head);
890 #ifdef CONFIG_BLOCK
891                         else if (msg->bio)
892                                 iter_bio_next(&msg->bio_iter, &msg->bio_seg);
893 #endif
894                 }
895         }
896
897         dout("write_partial_msg_pages %p msg %p done\n", con, msg);
898
899         /* prepare and queue up footer, too */
900         if (!crc)
901                 con->out_msg->footer.flags |= CEPH_MSG_FOOTER_NOCRC;
902         con->out_kvec_bytes = 0;
903         con->out_kvec_left = 0;
904         con->out_kvec_cur = con->out_kvec;
905         prepare_write_message_footer(con, 0);
906         ret = 1;
907 out:
908         return ret;
909 }
910
911 /*
912  * write some zeros
913  */
914 static int write_partial_skip(struct ceph_connection *con)
915 {
916         int ret;
917
918         while (con->out_skip > 0) {
919                 struct kvec iov = {
920                         .iov_base = page_address(con->msgr->zero_page),
921                         .iov_len = min(con->out_skip, (int)PAGE_CACHE_SIZE)
922                 };
923
924                 ret = ceph_tcp_sendmsg(con->sock, &iov, 1, iov.iov_len, 1);
925                 if (ret <= 0)
926                         goto out;
927                 con->out_skip -= ret;
928         }
929         ret = 1;
930 out:
931         return ret;
932 }
933
934 /*
935  * Prepare to read connection handshake, or an ack.
936  */
937 static void prepare_read_banner(struct ceph_connection *con)
938 {
939         dout("prepare_read_banner %p\n", con);
940         con->in_base_pos = 0;
941 }
942
943 static void prepare_read_connect(struct ceph_connection *con)
944 {
945         dout("prepare_read_connect %p\n", con);
946         con->in_base_pos = 0;
947 }
948
949 static void prepare_read_ack(struct ceph_connection *con)
950 {
951         dout("prepare_read_ack %p\n", con);
952         con->in_base_pos = 0;
953 }
954
955 static void prepare_read_tag(struct ceph_connection *con)
956 {
957         dout("prepare_read_tag %p\n", con);
958         con->in_base_pos = 0;
959         con->in_tag = CEPH_MSGR_TAG_READY;
960 }
961
962 /*
963  * Prepare to read a message.
964  */
965 static int prepare_read_message(struct ceph_connection *con)
966 {
967         dout("prepare_read_message %p\n", con);
968         BUG_ON(con->in_msg != NULL);
969         con->in_base_pos = 0;
970         con->in_front_crc = con->in_middle_crc = con->in_data_crc = 0;
971         return 0;
972 }
973
974
975 static int read_partial(struct ceph_connection *con,
976                         int *to, int size, void *object)
977 {
978         *to += size;
979         while (con->in_base_pos < *to) {
980                 int left = *to - con->in_base_pos;
981                 int have = size - left;
982                 int ret = ceph_tcp_recvmsg(con->sock, object + have, left);
983                 if (ret <= 0)
984                         return ret;
985                 con->in_base_pos += ret;
986         }
987         return 1;
988 }
989
990
991 /*
992  * Read all or part of the connect-side handshake on a new connection
993  */
994 static int read_partial_banner(struct ceph_connection *con)
995 {
996         int ret, to = 0;
997
998         dout("read_partial_banner %p at %d\n", con, con->in_base_pos);
999
1000         /* peer's banner */
1001         ret = read_partial(con, &to, strlen(CEPH_BANNER), con->in_banner);
1002         if (ret <= 0)
1003                 goto out;
1004         ret = read_partial(con, &to, sizeof(con->actual_peer_addr),
1005                            &con->actual_peer_addr);
1006         if (ret <= 0)
1007                 goto out;
1008         ret = read_partial(con, &to, sizeof(con->peer_addr_for_me),
1009                            &con->peer_addr_for_me);
1010         if (ret <= 0)
1011                 goto out;
1012 out:
1013         return ret;
1014 }
1015
1016 static int read_partial_connect(struct ceph_connection *con)
1017 {
1018         int ret, to = 0;
1019
1020         dout("read_partial_connect %p at %d\n", con, con->in_base_pos);
1021
1022         ret = read_partial(con, &to, sizeof(con->in_reply), &con->in_reply);
1023         if (ret <= 0)
1024                 goto out;
1025         ret = read_partial(con, &to, le32_to_cpu(con->in_reply.authorizer_len),
1026                            con->auth_reply_buf);
1027         if (ret <= 0)
1028                 goto out;
1029
1030         dout("read_partial_connect %p tag %d, con_seq = %u, g_seq = %u\n",
1031              con, (int)con->in_reply.tag,
1032              le32_to_cpu(con->in_reply.connect_seq),
1033              le32_to_cpu(con->in_reply.global_seq));
1034 out:
1035         return ret;
1036
1037 }
1038
1039 /*
1040  * Verify the hello banner looks okay.
1041  */
1042 static int verify_hello(struct ceph_connection *con)
1043 {
1044         if (memcmp(con->in_banner, CEPH_BANNER, strlen(CEPH_BANNER))) {
1045                 pr_err("connect to %s got bad banner\n",
1046                        ceph_pr_addr(&con->peer_addr.in_addr));
1047                 con->error_msg = "protocol error, bad banner";
1048                 return -1;
1049         }
1050         return 0;
1051 }
1052
1053 static bool addr_is_blank(struct sockaddr_storage *ss)
1054 {
1055         switch (ss->ss_family) {
1056         case AF_INET:
1057                 return ((struct sockaddr_in *)ss)->sin_addr.s_addr == 0;
1058         case AF_INET6:
1059                 return
1060                      ((struct sockaddr_in6 *)ss)->sin6_addr.s6_addr32[0] == 0 &&
1061                      ((struct sockaddr_in6 *)ss)->sin6_addr.s6_addr32[1] == 0 &&
1062                      ((struct sockaddr_in6 *)ss)->sin6_addr.s6_addr32[2] == 0 &&
1063                      ((struct sockaddr_in6 *)ss)->sin6_addr.s6_addr32[3] == 0;
1064         }
1065         return false;
1066 }
1067
1068 static int addr_port(struct sockaddr_storage *ss)
1069 {
1070         switch (ss->ss_family) {
1071         case AF_INET:
1072                 return ntohs(((struct sockaddr_in *)ss)->sin_port);
1073         case AF_INET6:
1074                 return ntohs(((struct sockaddr_in6 *)ss)->sin6_port);
1075         }
1076         return 0;
1077 }
1078
1079 static void addr_set_port(struct sockaddr_storage *ss, int p)
1080 {
1081         switch (ss->ss_family) {
1082         case AF_INET:
1083                 ((struct sockaddr_in *)ss)->sin_port = htons(p);
1084                 break;
1085         case AF_INET6:
1086                 ((struct sockaddr_in6 *)ss)->sin6_port = htons(p);
1087                 break;
1088         }
1089 }
1090
1091 /*
1092  * Unlike other *_pton function semantics, zero indicates success.
1093  */
1094 static int ceph_pton(const char *str, size_t len, struct sockaddr_storage *ss,
1095                 char delim, const char **ipend)
1096 {
1097         struct sockaddr_in *in4 = (void *)ss;
1098         struct sockaddr_in6 *in6 = (void *)ss;
1099
1100         memset(ss, 0, sizeof(*ss));
1101
1102         if (in4_pton(str, len, (u8 *)&in4->sin_addr.s_addr, delim, ipend)) {
1103                 ss->ss_family = AF_INET;
1104                 return 0;
1105         }
1106
1107         if (in6_pton(str, len, (u8 *)&in6->sin6_addr.s6_addr, delim, ipend)) {
1108                 ss->ss_family = AF_INET6;
1109                 return 0;
1110         }
1111
1112         return -EINVAL;
1113 }
1114
1115 /*
1116  * Extract hostname string and resolve using kernel DNS facility.
1117  */
1118 #ifdef CONFIG_CEPH_LIB_USE_DNS_RESOLVER
1119 static int ceph_dns_resolve_name(const char *name, size_t namelen,
1120                 struct sockaddr_storage *ss, char delim, const char **ipend)
1121 {
1122         const char *end, *delim_p;
1123         char *colon_p, *ip_addr = NULL;
1124         int ip_len, ret;
1125
1126         /*
1127          * The end of the hostname occurs immediately preceding the delimiter or
1128          * the port marker (':') where the delimiter takes precedence.
1129          */
1130         delim_p = memchr(name, delim, namelen);
1131         colon_p = memchr(name, ':', namelen);
1132
1133         if (delim_p && colon_p)
1134                 end = delim_p < colon_p ? delim_p : colon_p;
1135         else if (!delim_p && colon_p)
1136                 end = colon_p;
1137         else {
1138                 end = delim_p;
1139                 if (!end) /* case: hostname:/ */
1140                         end = name + namelen;
1141         }
1142
1143         if (end <= name)
1144                 return -EINVAL;
1145
1146         /* do dns_resolve upcall */
1147         ip_len = dns_query(NULL, name, end - name, NULL, &ip_addr, NULL);
1148         if (ip_len > 0)
1149                 ret = ceph_pton(ip_addr, ip_len, ss, -1, NULL);
1150         else
1151                 ret = -ESRCH;
1152
1153         kfree(ip_addr);
1154
1155         *ipend = end;
1156
1157         pr_info("resolve '%.*s' (ret=%d): %s\n", (int)(end - name), name,
1158                         ret, ret ? "failed" : ceph_pr_addr(ss));
1159
1160         return ret;
1161 }
1162 #else
1163 static inline int ceph_dns_resolve_name(const char *name, size_t namelen,
1164                 struct sockaddr_storage *ss, char delim, const char **ipend)
1165 {
1166         return -EINVAL;
1167 }
1168 #endif
1169
1170 /*
1171  * Parse a server name (IP or hostname). If a valid IP address is not found
1172  * then try to extract a hostname to resolve using userspace DNS upcall.
1173  */
1174 static int ceph_parse_server_name(const char *name, size_t namelen,
1175                         struct sockaddr_storage *ss, char delim, const char **ipend)
1176 {
1177         int ret;
1178
1179         ret = ceph_pton(name, namelen, ss, delim, ipend);
1180         if (ret)
1181                 ret = ceph_dns_resolve_name(name, namelen, ss, delim, ipend);
1182
1183         return ret;
1184 }
1185
1186 /*
1187  * Parse an ip[:port] list into an addr array.  Use the default
1188  * monitor port if a port isn't specified.
1189  */
1190 int ceph_parse_ips(const char *c, const char *end,
1191                    struct ceph_entity_addr *addr,
1192                    int max_count, int *count)
1193 {
1194         int i, ret = -EINVAL;
1195         const char *p = c;
1196
1197         dout("parse_ips on '%.*s'\n", (int)(end-c), c);
1198         for (i = 0; i < max_count; i++) {
1199                 const char *ipend;
1200                 struct sockaddr_storage *ss = &addr[i].in_addr;
1201                 int port;
1202                 char delim = ',';
1203
1204                 if (*p == '[') {
1205                         delim = ']';
1206                         p++;
1207                 }
1208
1209                 ret = ceph_parse_server_name(p, end - p, ss, delim, &ipend);
1210                 if (ret)
1211                         goto bad;
1212                 ret = -EINVAL;
1213
1214                 p = ipend;
1215
1216                 if (delim == ']') {
1217                         if (*p != ']') {
1218                                 dout("missing matching ']'\n");
1219                                 goto bad;
1220                         }
1221                         p++;
1222                 }
1223
1224                 /* port? */
1225                 if (p < end && *p == ':') {
1226                         port = 0;
1227                         p++;
1228                         while (p < end && *p >= '0' && *p <= '9') {
1229                                 port = (port * 10) + (*p - '0');
1230                                 p++;
1231                         }
1232                         if (port > 65535 || port == 0)
1233                                 goto bad;
1234                 } else {
1235                         port = CEPH_MON_PORT;
1236                 }
1237
1238                 addr_set_port(ss, port);
1239
1240                 dout("parse_ips got %s\n", ceph_pr_addr(ss));
1241
1242                 if (p == end)
1243                         break;
1244                 if (*p != ',')
1245                         goto bad;
1246                 p++;
1247         }
1248
1249         if (p != end)
1250                 goto bad;
1251
1252         if (count)
1253                 *count = i + 1;
1254         return 0;
1255
1256 bad:
1257         pr_err("parse_ips bad ip '%.*s'\n", (int)(end - c), c);
1258         return ret;
1259 }
1260 EXPORT_SYMBOL(ceph_parse_ips);
1261
1262 static int process_banner(struct ceph_connection *con)
1263 {
1264         dout("process_banner on %p\n", con);
1265
1266         if (verify_hello(con) < 0)
1267                 return -1;
1268
1269         ceph_decode_addr(&con->actual_peer_addr);
1270         ceph_decode_addr(&con->peer_addr_for_me);
1271
1272         /*
1273          * Make sure the other end is who we wanted.  note that the other
1274          * end may not yet know their ip address, so if it's 0.0.0.0, give
1275          * them the benefit of the doubt.
1276          */
1277         if (memcmp(&con->peer_addr, &con->actual_peer_addr,
1278                    sizeof(con->peer_addr)) != 0 &&
1279             !(addr_is_blank(&con->actual_peer_addr.in_addr) &&
1280               con->actual_peer_addr.nonce == con->peer_addr.nonce)) {
1281                 pr_warning("wrong peer, want %s/%d, got %s/%d\n",
1282                            ceph_pr_addr(&con->peer_addr.in_addr),
1283                            (int)le32_to_cpu(con->peer_addr.nonce),
1284                            ceph_pr_addr(&con->actual_peer_addr.in_addr),
1285                            (int)le32_to_cpu(con->actual_peer_addr.nonce));
1286                 con->error_msg = "wrong peer at address";
1287                 return -1;
1288         }
1289
1290         /*
1291          * did we learn our address?
1292          */
1293         if (addr_is_blank(&con->msgr->inst.addr.in_addr)) {
1294                 int port = addr_port(&con->msgr->inst.addr.in_addr);
1295
1296                 memcpy(&con->msgr->inst.addr.in_addr,
1297                        &con->peer_addr_for_me.in_addr,
1298                        sizeof(con->peer_addr_for_me.in_addr));
1299                 addr_set_port(&con->msgr->inst.addr.in_addr, port);
1300                 encode_my_addr(con->msgr);
1301                 dout("process_banner learned my addr is %s\n",
1302                      ceph_pr_addr(&con->msgr->inst.addr.in_addr));
1303         }
1304
1305         set_bit(NEGOTIATING, &con->state);
1306         prepare_read_connect(con);
1307         return 0;
1308 }
1309
1310 static void fail_protocol(struct ceph_connection *con)
1311 {
1312         reset_connection(con);
1313         set_bit(CLOSED, &con->state);  /* in case there's queued work */
1314
1315         mutex_unlock(&con->mutex);
1316         if (con->ops->bad_proto)
1317                 con->ops->bad_proto(con);
1318         mutex_lock(&con->mutex);
1319 }
1320
1321 static int process_connect(struct ceph_connection *con)
1322 {
1323         u64 sup_feat = con->msgr->supported_features;
1324         u64 req_feat = con->msgr->required_features;
1325         u64 server_feat = le64_to_cpu(con->in_reply.features);
1326         int ret;
1327
1328         dout("process_connect on %p tag %d\n", con, (int)con->in_tag);
1329
1330         switch (con->in_reply.tag) {
1331         case CEPH_MSGR_TAG_FEATURES:
1332                 pr_err("%s%lld %s feature set mismatch,"
1333                        " my %llx < server's %llx, missing %llx\n",
1334                        ENTITY_NAME(con->peer_name),
1335                        ceph_pr_addr(&con->peer_addr.in_addr),
1336                        sup_feat, server_feat, server_feat & ~sup_feat);
1337                 con->error_msg = "missing required protocol features";
1338                 fail_protocol(con);
1339                 return -1;
1340
1341         case CEPH_MSGR_TAG_BADPROTOVER:
1342                 pr_err("%s%lld %s protocol version mismatch,"
1343                        " my %d != server's %d\n",
1344                        ENTITY_NAME(con->peer_name),
1345                        ceph_pr_addr(&con->peer_addr.in_addr),
1346                        le32_to_cpu(con->out_connect.protocol_version),
1347                        le32_to_cpu(con->in_reply.protocol_version));
1348                 con->error_msg = "protocol version mismatch";
1349                 fail_protocol(con);
1350                 return -1;
1351
1352         case CEPH_MSGR_TAG_BADAUTHORIZER:
1353                 con->auth_retry++;
1354                 dout("process_connect %p got BADAUTHORIZER attempt %d\n", con,
1355                      con->auth_retry);
1356                 if (con->auth_retry == 2) {
1357                         con->error_msg = "connect authorization failure";
1358                         return -1;
1359                 }
1360                 con->auth_retry = 1;
1361                 ret = prepare_write_connect(con->msgr, con, 0);
1362                 if (ret < 0)
1363                         return ret;
1364                 prepare_read_connect(con);
1365                 break;
1366
1367         case CEPH_MSGR_TAG_RESETSESSION:
1368                 /*
1369                  * If we connected with a large connect_seq but the peer
1370                  * has no record of a session with us (no connection, or
1371                  * connect_seq == 0), they will send RESETSESION to indicate
1372                  * that they must have reset their session, and may have
1373                  * dropped messages.
1374                  */
1375                 dout("process_connect got RESET peer seq %u\n",
1376                      le32_to_cpu(con->in_connect.connect_seq));
1377                 pr_err("%s%lld %s connection reset\n",
1378                        ENTITY_NAME(con->peer_name),
1379                        ceph_pr_addr(&con->peer_addr.in_addr));
1380                 reset_connection(con);
1381                 prepare_write_connect(con->msgr, con, 0);
1382                 prepare_read_connect(con);
1383
1384                 /* Tell ceph about it. */
1385                 mutex_unlock(&con->mutex);
1386                 pr_info("reset on %s%lld\n", ENTITY_NAME(con->peer_name));
1387                 if (con->ops->peer_reset)
1388                         con->ops->peer_reset(con);
1389                 mutex_lock(&con->mutex);
1390                 if (test_bit(CLOSED, &con->state) ||
1391                     test_bit(OPENING, &con->state))
1392                         return -EAGAIN;
1393                 break;
1394
1395         case CEPH_MSGR_TAG_RETRY_SESSION:
1396                 /*
1397                  * If we sent a smaller connect_seq than the peer has, try
1398                  * again with a larger value.
1399                  */
1400                 dout("process_connect got RETRY my seq = %u, peer_seq = %u\n",
1401                      le32_to_cpu(con->out_connect.connect_seq),
1402                      le32_to_cpu(con->in_connect.connect_seq));
1403                 con->connect_seq = le32_to_cpu(con->in_connect.connect_seq);
1404                 prepare_write_connect(con->msgr, con, 0);
1405                 prepare_read_connect(con);
1406                 break;
1407
1408         case CEPH_MSGR_TAG_RETRY_GLOBAL:
1409                 /*
1410                  * If we sent a smaller global_seq than the peer has, try
1411                  * again with a larger value.
1412                  */
1413                 dout("process_connect got RETRY_GLOBAL my %u peer_gseq %u\n",
1414                      con->peer_global_seq,
1415                      le32_to_cpu(con->in_connect.global_seq));
1416                 get_global_seq(con->msgr,
1417                                le32_to_cpu(con->in_connect.global_seq));
1418                 prepare_write_connect(con->msgr, con, 0);
1419                 prepare_read_connect(con);
1420                 break;
1421
1422         case CEPH_MSGR_TAG_READY:
1423                 if (req_feat & ~server_feat) {
1424                         pr_err("%s%lld %s protocol feature mismatch,"
1425                                " my required %llx > server's %llx, need %llx\n",
1426                                ENTITY_NAME(con->peer_name),
1427                                ceph_pr_addr(&con->peer_addr.in_addr),
1428                                req_feat, server_feat, req_feat & ~server_feat);
1429                         con->error_msg = "missing required protocol features";
1430                         fail_protocol(con);
1431                         return -1;
1432                 }
1433                 clear_bit(CONNECTING, &con->state);
1434                 con->peer_global_seq = le32_to_cpu(con->in_reply.global_seq);
1435                 con->connect_seq++;
1436                 con->peer_features = server_feat;
1437                 dout("process_connect got READY gseq %d cseq %d (%d)\n",
1438                      con->peer_global_seq,
1439                      le32_to_cpu(con->in_reply.connect_seq),
1440                      con->connect_seq);
1441                 WARN_ON(con->connect_seq !=
1442                         le32_to_cpu(con->in_reply.connect_seq));
1443
1444                 if (con->in_reply.flags & CEPH_MSG_CONNECT_LOSSY)
1445                         set_bit(LOSSYTX, &con->state);
1446
1447                 prepare_read_tag(con);
1448                 break;
1449
1450         case CEPH_MSGR_TAG_WAIT:
1451                 /*
1452                  * If there is a connection race (we are opening
1453                  * connections to each other), one of us may just have
1454                  * to WAIT.  This shouldn't happen if we are the
1455                  * client.
1456                  */
1457                 pr_err("process_connect got WAIT as client\n");
1458                 con->error_msg = "protocol error, got WAIT as client";
1459                 return -1;
1460
1461         default:
1462                 pr_err("connect protocol error, will retry\n");
1463                 con->error_msg = "protocol error, garbage tag during connect";
1464                 return -1;
1465         }
1466         return 0;
1467 }
1468
1469
1470 /*
1471  * read (part of) an ack
1472  */
1473 static int read_partial_ack(struct ceph_connection *con)
1474 {
1475         int to = 0;
1476
1477         return read_partial(con, &to, sizeof(con->in_temp_ack),
1478                             &con->in_temp_ack);
1479 }
1480
1481
1482 /*
1483  * We can finally discard anything that's been acked.
1484  */
1485 static void process_ack(struct ceph_connection *con)
1486 {
1487         struct ceph_msg *m;
1488         u64 ack = le64_to_cpu(con->in_temp_ack);
1489         u64 seq;
1490
1491         while (!list_empty(&con->out_sent)) {
1492                 m = list_first_entry(&con->out_sent, struct ceph_msg,
1493                                      list_head);
1494                 seq = le64_to_cpu(m->hdr.seq);
1495                 if (seq > ack)
1496                         break;
1497                 dout("got ack for seq %llu type %d at %p\n", seq,
1498                      le16_to_cpu(m->hdr.type), m);
1499                 m->ack_stamp = jiffies;
1500                 ceph_msg_remove(m);
1501         }
1502         prepare_read_tag(con);
1503 }
1504
1505
1506
1507
1508 static int read_partial_message_section(struct ceph_connection *con,
1509                                         struct kvec *section,
1510                                         unsigned int sec_len, u32 *crc)
1511 {
1512         int ret, left;
1513
1514         BUG_ON(!section);
1515
1516         while (section->iov_len < sec_len) {
1517                 BUG_ON(section->iov_base == NULL);
1518                 left = sec_len - section->iov_len;
1519                 ret = ceph_tcp_recvmsg(con->sock, (char *)section->iov_base +
1520                                        section->iov_len, left);
1521                 if (ret <= 0)
1522                         return ret;
1523                 section->iov_len += ret;
1524                 if (section->iov_len == sec_len)
1525                         *crc = crc32c(0, section->iov_base,
1526                                       section->iov_len);
1527         }
1528
1529         return 1;
1530 }
1531
1532 static struct ceph_msg *ceph_alloc_msg(struct ceph_connection *con,
1533                                 struct ceph_msg_header *hdr,
1534                                 int *skip);
1535
1536
1537 static int read_partial_message_pages(struct ceph_connection *con,
1538                                       struct page **pages,
1539                                       unsigned data_len, int datacrc)
1540 {
1541         void *p;
1542         int ret;
1543         int left;
1544
1545         left = min((int)(data_len - con->in_msg_pos.data_pos),
1546                    (int)(PAGE_SIZE - con->in_msg_pos.page_pos));
1547         /* (page) data */
1548         BUG_ON(pages == NULL);
1549         p = kmap(pages[con->in_msg_pos.page]);
1550         ret = ceph_tcp_recvmsg(con->sock, p + con->in_msg_pos.page_pos,
1551                                left);
1552         if (ret > 0 && datacrc)
1553                 con->in_data_crc =
1554                         crc32c(con->in_data_crc,
1555                                   p + con->in_msg_pos.page_pos, ret);
1556         kunmap(pages[con->in_msg_pos.page]);
1557         if (ret <= 0)
1558                 return ret;
1559         con->in_msg_pos.data_pos += ret;
1560         con->in_msg_pos.page_pos += ret;
1561         if (con->in_msg_pos.page_pos == PAGE_SIZE) {
1562                 con->in_msg_pos.page_pos = 0;
1563                 con->in_msg_pos.page++;
1564         }
1565
1566         return ret;
1567 }
1568
1569 #ifdef CONFIG_BLOCK
1570 static int read_partial_message_bio(struct ceph_connection *con,
1571                                     struct bio **bio_iter, int *bio_seg,
1572                                     unsigned data_len, int datacrc)
1573 {
1574         struct bio_vec *bv = bio_iovec_idx(*bio_iter, *bio_seg);
1575         void *p;
1576         int ret, left;
1577
1578         if (IS_ERR(bv))
1579                 return PTR_ERR(bv);
1580
1581         left = min((int)(data_len - con->in_msg_pos.data_pos),
1582                    (int)(bv->bv_len - con->in_msg_pos.page_pos));
1583
1584         p = kmap(bv->bv_page) + bv->bv_offset;
1585
1586         ret = ceph_tcp_recvmsg(con->sock, p + con->in_msg_pos.page_pos,
1587                                left);
1588         if (ret > 0 && datacrc)
1589                 con->in_data_crc =
1590                         crc32c(con->in_data_crc,
1591                                   p + con->in_msg_pos.page_pos, ret);
1592         kunmap(bv->bv_page);
1593         if (ret <= 0)
1594                 return ret;
1595         con->in_msg_pos.data_pos += ret;
1596         con->in_msg_pos.page_pos += ret;
1597         if (con->in_msg_pos.page_pos == bv->bv_len) {
1598                 con->in_msg_pos.page_pos = 0;
1599                 iter_bio_next(bio_iter, bio_seg);
1600         }
1601
1602         return ret;
1603 }
1604 #endif
1605
1606 /*
1607  * read (part of) a message.
1608  */
1609 static int read_partial_message(struct ceph_connection *con)
1610 {
1611         struct ceph_msg *m = con->in_msg;
1612         int ret;
1613         int to, left;
1614         unsigned front_len, middle_len, data_len;
1615         int datacrc = con->msgr->nocrc;
1616         int skip;
1617         u64 seq;
1618
1619         dout("read_partial_message con %p msg %p\n", con, m);
1620
1621         /* header */
1622         while (con->in_base_pos < sizeof(con->in_hdr)) {
1623                 left = sizeof(con->in_hdr) - con->in_base_pos;
1624                 ret = ceph_tcp_recvmsg(con->sock,
1625                                        (char *)&con->in_hdr + con->in_base_pos,
1626                                        left);
1627                 if (ret <= 0)
1628                         return ret;
1629                 con->in_base_pos += ret;
1630                 if (con->in_base_pos == sizeof(con->in_hdr)) {
1631                         u32 crc = crc32c(0, (void *)&con->in_hdr,
1632                                  sizeof(con->in_hdr) - sizeof(con->in_hdr.crc));
1633                         if (crc != le32_to_cpu(con->in_hdr.crc)) {
1634                                 pr_err("read_partial_message bad hdr "
1635                                        " crc %u != expected %u\n",
1636                                        crc, con->in_hdr.crc);
1637                                 return -EBADMSG;
1638                         }
1639                 }
1640         }
1641         front_len = le32_to_cpu(con->in_hdr.front_len);
1642         if (front_len > CEPH_MSG_MAX_FRONT_LEN)
1643                 return -EIO;
1644         middle_len = le32_to_cpu(con->in_hdr.middle_len);
1645         if (middle_len > CEPH_MSG_MAX_DATA_LEN)
1646                 return -EIO;
1647         data_len = le32_to_cpu(con->in_hdr.data_len);
1648         if (data_len > CEPH_MSG_MAX_DATA_LEN)
1649                 return -EIO;
1650
1651         /* verify seq# */
1652         seq = le64_to_cpu(con->in_hdr.seq);
1653         if ((s64)seq - (s64)con->in_seq < 1) {
1654                 pr_info("skipping %s%lld %s seq %lld expected %lld\n",
1655                         ENTITY_NAME(con->peer_name),
1656                         ceph_pr_addr(&con->peer_addr.in_addr),
1657                         seq, con->in_seq + 1);
1658                 con->in_base_pos = -front_len - middle_len - data_len -
1659                         sizeof(m->footer);
1660                 con->in_tag = CEPH_MSGR_TAG_READY;
1661                 return 0;
1662         } else if ((s64)seq - (s64)con->in_seq > 1) {
1663                 pr_err("read_partial_message bad seq %lld expected %lld\n",
1664                        seq, con->in_seq + 1);
1665                 con->error_msg = "bad message sequence # for incoming message";
1666                 return -EBADMSG;
1667         }
1668
1669         /* allocate message? */
1670         if (!con->in_msg) {
1671                 dout("got hdr type %d front %d data %d\n", con->in_hdr.type,
1672                      con->in_hdr.front_len, con->in_hdr.data_len);
1673                 skip = 0;
1674                 con->in_msg = ceph_alloc_msg(con, &con->in_hdr, &skip);
1675                 if (skip) {
1676                         /* skip this message */
1677                         dout("alloc_msg said skip message\n");
1678                         BUG_ON(con->in_msg);
1679                         con->in_base_pos = -front_len - middle_len - data_len -
1680                                 sizeof(m->footer);
1681                         con->in_tag = CEPH_MSGR_TAG_READY;
1682                         con->in_seq++;
1683                         return 0;
1684                 }
1685                 if (!con->in_msg) {
1686                         con->error_msg =
1687                                 "error allocating memory for incoming message";
1688                         return -ENOMEM;
1689                 }
1690                 m = con->in_msg;
1691                 m->front.iov_len = 0;    /* haven't read it yet */
1692                 if (m->middle)
1693                         m->middle->vec.iov_len = 0;
1694
1695                 con->in_msg_pos.page = 0;
1696                 if (m->pages)
1697                         con->in_msg_pos.page_pos = m->page_alignment;
1698                 else
1699                         con->in_msg_pos.page_pos = 0;
1700                 con->in_msg_pos.data_pos = 0;
1701         }
1702
1703         /* front */
1704         ret = read_partial_message_section(con, &m->front, front_len,
1705                                            &con->in_front_crc);
1706         if (ret <= 0)
1707                 return ret;
1708
1709         /* middle */
1710         if (m->middle) {
1711                 ret = read_partial_message_section(con, &m->middle->vec,
1712                                                    middle_len,
1713                                                    &con->in_middle_crc);
1714                 if (ret <= 0)
1715                         return ret;
1716         }
1717 #ifdef CONFIG_BLOCK
1718         if (m->bio && !m->bio_iter)
1719                 init_bio_iter(m->bio, &m->bio_iter, &m->bio_seg);
1720 #endif
1721
1722         /* (page) data */
1723         while (con->in_msg_pos.data_pos < data_len) {
1724                 if (m->pages) {
1725                         ret = read_partial_message_pages(con, m->pages,
1726                                                  data_len, datacrc);
1727                         if (ret <= 0)
1728                                 return ret;
1729 #ifdef CONFIG_BLOCK
1730                 } else if (m->bio) {
1731
1732                         ret = read_partial_message_bio(con,
1733                                                  &m->bio_iter, &m->bio_seg,
1734                                                  data_len, datacrc);
1735                         if (ret <= 0)
1736                                 return ret;
1737 #endif
1738                 } else {
1739                         BUG_ON(1);
1740                 }
1741         }
1742
1743         /* footer */
1744         to = sizeof(m->hdr) + sizeof(m->footer);
1745         while (con->in_base_pos < to) {
1746                 left = to - con->in_base_pos;
1747                 ret = ceph_tcp_recvmsg(con->sock, (char *)&m->footer +
1748                                        (con->in_base_pos - sizeof(m->hdr)),
1749                                        left);
1750                 if (ret <= 0)
1751                         return ret;
1752                 con->in_base_pos += ret;
1753         }
1754         dout("read_partial_message got msg %p %d (%u) + %d (%u) + %d (%u)\n",
1755              m, front_len, m->footer.front_crc, middle_len,
1756              m->footer.middle_crc, data_len, m->footer.data_crc);
1757
1758         /* crc ok? */
1759         if (con->in_front_crc != le32_to_cpu(m->footer.front_crc)) {
1760                 pr_err("read_partial_message %p front crc %u != exp. %u\n",
1761                        m, con->in_front_crc, m->footer.front_crc);
1762                 return -EBADMSG;
1763         }
1764         if (con->in_middle_crc != le32_to_cpu(m->footer.middle_crc)) {
1765                 pr_err("read_partial_message %p middle crc %u != exp %u\n",
1766                        m, con->in_middle_crc, m->footer.middle_crc);
1767                 return -EBADMSG;
1768         }
1769         if (datacrc &&
1770             (m->footer.flags & CEPH_MSG_FOOTER_NOCRC) == 0 &&
1771             con->in_data_crc != le32_to_cpu(m->footer.data_crc)) {
1772                 pr_err("read_partial_message %p data crc %u != exp. %u\n", m,
1773                        con->in_data_crc, le32_to_cpu(m->footer.data_crc));
1774                 return -EBADMSG;
1775         }
1776
1777         return 1; /* done! */
1778 }
1779
1780 /*
1781  * Process message.  This happens in the worker thread.  The callback should
1782  * be careful not to do anything that waits on other incoming messages or it
1783  * may deadlock.
1784  */
1785 static void process_message(struct ceph_connection *con)
1786 {
1787         struct ceph_msg *msg;
1788
1789         msg = con->in_msg;
1790         con->in_msg = NULL;
1791
1792         /* if first message, set peer_name */
1793         if (con->peer_name.type == 0)
1794                 con->peer_name = msg->hdr.src;
1795
1796         con->in_seq++;
1797         mutex_unlock(&con->mutex);
1798
1799         dout("===== %p %llu from %s%lld %d=%s len %d+%d (%u %u %u) =====\n",
1800              msg, le64_to_cpu(msg->hdr.seq),
1801              ENTITY_NAME(msg->hdr.src),
1802              le16_to_cpu(msg->hdr.type),
1803              ceph_msg_type_name(le16_to_cpu(msg->hdr.type)),
1804              le32_to_cpu(msg->hdr.front_len),
1805              le32_to_cpu(msg->hdr.data_len),
1806              con->in_front_crc, con->in_middle_crc, con->in_data_crc);
1807         con->ops->dispatch(con, msg);
1808
1809         mutex_lock(&con->mutex);
1810         prepare_read_tag(con);
1811 }
1812
1813
1814 /*
1815  * Write something to the socket.  Called in a worker thread when the
1816  * socket appears to be writeable and we have something ready to send.
1817  */
1818 static int try_write(struct ceph_connection *con)
1819 {
1820         struct ceph_messenger *msgr = con->msgr;
1821         int ret = 1;
1822
1823         dout("try_write start %p state %lu nref %d\n", con, con->state,
1824              atomic_read(&con->nref));
1825
1826 more:
1827         dout("try_write out_kvec_bytes %d\n", con->out_kvec_bytes);
1828
1829         /* open the socket first? */
1830         if (con->sock == NULL) {
1831                 prepare_write_banner(msgr, con);
1832                 prepare_write_connect(msgr, con, 1);
1833                 prepare_read_banner(con);
1834                 set_bit(CONNECTING, &con->state);
1835                 clear_bit(NEGOTIATING, &con->state);
1836
1837                 BUG_ON(con->in_msg);
1838                 con->in_tag = CEPH_MSGR_TAG_READY;
1839                 dout("try_write initiating connect on %p new state %lu\n",
1840                      con, con->state);
1841                 con->sock = ceph_tcp_connect(con);
1842                 if (IS_ERR(con->sock)) {
1843                         con->sock = NULL;
1844                         con->error_msg = "connect error";
1845                         ret = -1;
1846                         goto out;
1847                 }
1848         }
1849
1850 more_kvec:
1851         /* kvec data queued? */
1852         if (con->out_skip) {
1853                 ret = write_partial_skip(con);
1854                 if (ret <= 0)
1855                         goto out;
1856         }
1857         if (con->out_kvec_left) {
1858                 ret = write_partial_kvec(con);
1859                 if (ret <= 0)
1860                         goto out;
1861         }
1862
1863         /* msg pages? */
1864         if (con->out_msg) {
1865                 if (con->out_msg_done) {
1866                         ceph_msg_put(con->out_msg);
1867                         con->out_msg = NULL;   /* we're done with this one */
1868                         goto do_next;
1869                 }
1870
1871                 ret = write_partial_msg_pages(con);
1872                 if (ret == 1)
1873                         goto more_kvec;  /* we need to send the footer, too! */
1874                 if (ret == 0)
1875                         goto out;
1876                 if (ret < 0) {
1877                         dout("try_write write_partial_msg_pages err %d\n",
1878                              ret);
1879                         goto out;
1880                 }
1881         }
1882
1883 do_next:
1884         if (!test_bit(CONNECTING, &con->state)) {
1885                 /* is anything else pending? */
1886                 if (!list_empty(&con->out_queue)) {
1887                         prepare_write_message(con);
1888                         goto more;
1889                 }
1890                 if (con->in_seq > con->in_seq_acked) {
1891                         prepare_write_ack(con);
1892                         goto more;
1893                 }
1894                 if (test_and_clear_bit(KEEPALIVE_PENDING, &con->state)) {
1895                         prepare_write_keepalive(con);
1896                         goto more;
1897                 }
1898         }
1899
1900         /* Nothing to do! */
1901         clear_bit(WRITE_PENDING, &con->state);
1902         dout("try_write nothing else to write.\n");
1903         ret = 0;
1904 out:
1905         dout("try_write done on %p ret %d\n", con, ret);
1906         return ret;
1907 }
1908
1909
1910
1911 /*
1912  * Read what we can from the socket.
1913  */
1914 static int try_read(struct ceph_connection *con)
1915 {
1916         int ret = -1;
1917
1918         if (!con->sock)
1919                 return 0;
1920
1921         if (test_bit(STANDBY, &con->state))
1922                 return 0;
1923
1924         dout("try_read start on %p\n", con);
1925
1926 more:
1927         dout("try_read tag %d in_base_pos %d\n", (int)con->in_tag,
1928              con->in_base_pos);
1929
1930         /*
1931          * process_connect and process_message drop and re-take
1932          * con->mutex.  make sure we handle a racing close or reopen.
1933          */
1934         if (test_bit(CLOSED, &con->state) ||
1935             test_bit(OPENING, &con->state)) {
1936                 ret = -EAGAIN;
1937                 goto out;
1938         }
1939
1940         if (test_bit(CONNECTING, &con->state)) {
1941                 if (!test_bit(NEGOTIATING, &con->state)) {
1942                         dout("try_read connecting\n");
1943                         ret = read_partial_banner(con);
1944                         if (ret <= 0)
1945                                 goto out;
1946                         ret = process_banner(con);
1947                         if (ret < 0)
1948                                 goto out;
1949                 }
1950                 ret = read_partial_connect(con);
1951                 if (ret <= 0)
1952                         goto out;
1953                 ret = process_connect(con);
1954                 if (ret < 0)
1955                         goto out;
1956                 goto more;
1957         }
1958
1959         if (con->in_base_pos < 0) {
1960                 /*
1961                  * skipping + discarding content.
1962                  *
1963                  * FIXME: there must be a better way to do this!
1964                  */
1965                 static char buf[1024];
1966                 int skip = min(1024, -con->in_base_pos);
1967                 dout("skipping %d / %d bytes\n", skip, -con->in_base_pos);
1968                 ret = ceph_tcp_recvmsg(con->sock, buf, skip);
1969                 if (ret <= 0)
1970                         goto out;
1971                 con->in_base_pos += ret;
1972                 if (con->in_base_pos)
1973                         goto more;
1974         }
1975         if (con->in_tag == CEPH_MSGR_TAG_READY) {
1976                 /*
1977                  * what's next?
1978                  */
1979                 ret = ceph_tcp_recvmsg(con->sock, &con->in_tag, 1);
1980                 if (ret <= 0)
1981                         goto out;
1982                 dout("try_read got tag %d\n", (int)con->in_tag);
1983                 switch (con->in_tag) {
1984                 case CEPH_MSGR_TAG_MSG:
1985                         prepare_read_message(con);
1986                         break;
1987                 case CEPH_MSGR_TAG_ACK:
1988                         prepare_read_ack(con);
1989                         break;
1990                 case CEPH_MSGR_TAG_CLOSE:
1991                         set_bit(CLOSED, &con->state);   /* fixme */
1992                         goto out;
1993                 default:
1994                         goto bad_tag;
1995                 }
1996         }
1997         if (con->in_tag == CEPH_MSGR_TAG_MSG) {
1998                 ret = read_partial_message(con);
1999                 if (ret <= 0) {
2000                         switch (ret) {
2001                         case -EBADMSG:
2002                                 con->error_msg = "bad crc";
2003                                 ret = -EIO;
2004                                 break;
2005                         case -EIO:
2006                                 con->error_msg = "io error";
2007                                 break;
2008                         }
2009                         goto out;
2010                 }
2011                 if (con->in_tag == CEPH_MSGR_TAG_READY)
2012                         goto more;
2013                 process_message(con);
2014                 goto more;
2015         }
2016         if (con->in_tag == CEPH_MSGR_TAG_ACK) {
2017                 ret = read_partial_ack(con);
2018                 if (ret <= 0)
2019                         goto out;
2020                 process_ack(con);
2021                 goto more;
2022         }
2023
2024 out:
2025         dout("try_read done on %p ret %d\n", con, ret);
2026         return ret;
2027
2028 bad_tag:
2029         pr_err("try_read bad con->in_tag = %d\n", (int)con->in_tag);
2030         con->error_msg = "protocol error, garbage tag";
2031         ret = -1;
2032         goto out;
2033 }
2034
2035
2036 /*
2037  * Atomically queue work on a connection.  Bump @con reference to
2038  * avoid races with connection teardown.
2039  */
2040 static void queue_con(struct ceph_connection *con)
2041 {
2042         if (test_bit(DEAD, &con->state)) {
2043                 dout("queue_con %p ignoring: DEAD\n",
2044                      con);
2045                 return;
2046         }
2047
2048         if (!con->ops->get(con)) {
2049                 dout("queue_con %p ref count 0\n", con);
2050                 return;
2051         }
2052
2053         if (!queue_delayed_work(ceph_msgr_wq, &con->work, 0)) {
2054                 dout("queue_con %p - already queued\n", con);
2055                 con->ops->put(con);
2056         } else {
2057                 dout("queue_con %p\n", con);
2058         }
2059 }
2060
2061 /*
2062  * Do some work on a connection.  Drop a connection ref when we're done.
2063  */
2064 static void con_work(struct work_struct *work)
2065 {
2066         struct ceph_connection *con = container_of(work, struct ceph_connection,
2067                                                    work.work);
2068         int ret;
2069
2070         mutex_lock(&con->mutex);
2071 restart:
2072         if (test_and_clear_bit(BACKOFF, &con->state)) {
2073                 dout("con_work %p backing off\n", con);
2074                 if (queue_delayed_work(ceph_msgr_wq, &con->work,
2075                                        round_jiffies_relative(con->delay))) {
2076                         dout("con_work %p backoff %lu\n", con, con->delay);
2077                         mutex_unlock(&con->mutex);
2078                         return;
2079                 } else {
2080                         con->ops->put(con);
2081                         dout("con_work %p FAILED to back off %lu\n", con,
2082                              con->delay);
2083                 }
2084         }
2085
2086         if (test_bit(STANDBY, &con->state)) {
2087                 dout("con_work %p STANDBY\n", con);
2088                 goto done;
2089         }
2090         if (test_bit(CLOSED, &con->state)) { /* e.g. if we are replaced */
2091                 dout("con_work CLOSED\n");
2092                 con_close_socket(con);
2093                 goto done;
2094         }
2095         if (test_and_clear_bit(OPENING, &con->state)) {
2096                 /* reopen w/ new peer */
2097                 dout("con_work OPENING\n");
2098                 con_close_socket(con);
2099         }
2100
2101         if (test_and_clear_bit(SOCK_CLOSED, &con->state))
2102                 goto fault;
2103
2104         ret = try_read(con);
2105         if (ret == -EAGAIN)
2106                 goto restart;
2107         if (ret < 0)
2108                 goto fault;
2109
2110         ret = try_write(con);
2111         if (ret == -EAGAIN)
2112                 goto restart;
2113         if (ret < 0)
2114                 goto fault;
2115
2116 done:
2117         mutex_unlock(&con->mutex);
2118 done_unlocked:
2119         con->ops->put(con);
2120         return;
2121
2122 fault:
2123         mutex_unlock(&con->mutex);
2124         ceph_fault(con);     /* error/fault path */
2125         goto done_unlocked;
2126 }
2127
2128
2129 /*
2130  * Generic error/fault handler.  A retry mechanism is used with
2131  * exponential backoff
2132  */
2133 static void ceph_fault(struct ceph_connection *con)
2134 {
2135         pr_err("%s%lld %s %s\n", ENTITY_NAME(con->peer_name),
2136                ceph_pr_addr(&con->peer_addr.in_addr), con->error_msg);
2137         dout("fault %p state %lu to peer %s\n",
2138              con, con->state, ceph_pr_addr(&con->peer_addr.in_addr));
2139
2140         if (test_bit(LOSSYTX, &con->state)) {
2141                 dout("fault on LOSSYTX channel\n");
2142                 goto out;
2143         }
2144
2145         mutex_lock(&con->mutex);
2146         if (test_bit(CLOSED, &con->state))
2147                 goto out_unlock;
2148
2149         con_close_socket(con);
2150
2151         if (con->in_msg) {
2152                 ceph_msg_put(con->in_msg);
2153                 con->in_msg = NULL;
2154         }
2155
2156         /* Requeue anything that hasn't been acked */
2157         list_splice_init(&con->out_sent, &con->out_queue);
2158
2159         /* If there are no messages queued or keepalive pending, place
2160          * the connection in a STANDBY state */
2161         if (list_empty(&con->out_queue) &&
2162             !test_bit(KEEPALIVE_PENDING, &con->state)) {
2163                 dout("fault %p setting STANDBY clearing WRITE_PENDING\n", con);
2164                 clear_bit(WRITE_PENDING, &con->state);
2165                 set_bit(STANDBY, &con->state);
2166         } else {
2167                 /* retry after a delay. */
2168                 if (con->delay == 0)
2169                         con->delay = BASE_DELAY_INTERVAL;
2170                 else if (con->delay < MAX_DELAY_INTERVAL)
2171                         con->delay *= 2;
2172                 con->ops->get(con);
2173                 if (queue_delayed_work(ceph_msgr_wq, &con->work,
2174                                        round_jiffies_relative(con->delay))) {
2175                         dout("fault queued %p delay %lu\n", con, con->delay);
2176                 } else {
2177                         con->ops->put(con);
2178                         dout("fault failed to queue %p delay %lu, backoff\n",
2179                              con, con->delay);
2180                         /*
2181                          * In many cases we see a socket state change
2182                          * while con_work is running and end up
2183                          * queuing (non-delayed) work, such that we
2184                          * can't backoff with a delay.  Set a flag so
2185                          * that when con_work restarts we schedule the
2186                          * delay then.
2187                          */
2188                         set_bit(BACKOFF, &con->state);
2189                 }
2190         }
2191
2192 out_unlock:
2193         mutex_unlock(&con->mutex);
2194 out:
2195         /*
2196          * in case we faulted due to authentication, invalidate our
2197          * current tickets so that we can get new ones.
2198          */
2199         if (con->auth_retry && con->ops->invalidate_authorizer) {
2200                 dout("calling invalidate_authorizer()\n");
2201                 con->ops->invalidate_authorizer(con);
2202         }
2203
2204         if (con->ops->fault)
2205                 con->ops->fault(con);
2206 }
2207
2208
2209
2210 /*
2211  * create a new messenger instance
2212  */
2213 struct ceph_messenger *ceph_messenger_create(struct ceph_entity_addr *myaddr,
2214                                              u32 supported_features,
2215                                              u32 required_features)
2216 {
2217         struct ceph_messenger *msgr;
2218
2219         msgr = kzalloc(sizeof(*msgr), GFP_KERNEL);
2220         if (msgr == NULL)
2221                 return ERR_PTR(-ENOMEM);
2222
2223         msgr->supported_features = supported_features;
2224         msgr->required_features = required_features;
2225
2226         spin_lock_init(&msgr->global_seq_lock);
2227
2228         /* the zero page is needed if a request is "canceled" while the message
2229          * is being written over the socket */
2230         msgr->zero_page = __page_cache_alloc(GFP_KERNEL | __GFP_ZERO);
2231         if (!msgr->zero_page) {
2232                 kfree(msgr);
2233                 return ERR_PTR(-ENOMEM);
2234         }
2235         kmap(msgr->zero_page);
2236
2237         if (myaddr)
2238                 msgr->inst.addr = *myaddr;
2239
2240         /* select a random nonce */
2241         msgr->inst.addr.type = 0;
2242         get_random_bytes(&msgr->inst.addr.nonce, sizeof(msgr->inst.addr.nonce));
2243         encode_my_addr(msgr);
2244
2245         dout("messenger_create %p\n", msgr);
2246         return msgr;
2247 }
2248 EXPORT_SYMBOL(ceph_messenger_create);
2249
2250 void ceph_messenger_destroy(struct ceph_messenger *msgr)
2251 {
2252         dout("destroy %p\n", msgr);
2253         kunmap(msgr->zero_page);
2254         __free_page(msgr->zero_page);
2255         kfree(msgr);
2256         dout("destroyed messenger %p\n", msgr);
2257 }
2258 EXPORT_SYMBOL(ceph_messenger_destroy);
2259
2260 static void clear_standby(struct ceph_connection *con)
2261 {
2262         /* come back from STANDBY? */
2263         if (test_and_clear_bit(STANDBY, &con->state)) {
2264                 mutex_lock(&con->mutex);
2265                 dout("clear_standby %p and ++connect_seq\n", con);
2266                 con->connect_seq++;
2267                 WARN_ON(test_bit(WRITE_PENDING, &con->state));
2268                 WARN_ON(test_bit(KEEPALIVE_PENDING, &con->state));
2269                 mutex_unlock(&con->mutex);
2270         }
2271 }
2272
2273 /*
2274  * Queue up an outgoing message on the given connection.
2275  */
2276 void ceph_con_send(struct ceph_connection *con, struct ceph_msg *msg)
2277 {
2278         if (test_bit(CLOSED, &con->state)) {
2279                 dout("con_send %p closed, dropping %p\n", con, msg);
2280                 ceph_msg_put(msg);
2281                 return;
2282         }
2283
2284         /* set src+dst */
2285         msg->hdr.src = con->msgr->inst.name;
2286
2287         BUG_ON(msg->front.iov_len != le32_to_cpu(msg->hdr.front_len));
2288
2289         msg->needs_out_seq = true;
2290
2291         /* queue */
2292         mutex_lock(&con->mutex);
2293         BUG_ON(!list_empty(&msg->list_head));
2294         list_add_tail(&msg->list_head, &con->out_queue);
2295         dout("----- %p to %s%lld %d=%s len %d+%d+%d -----\n", msg,
2296              ENTITY_NAME(con->peer_name), le16_to_cpu(msg->hdr.type),
2297              ceph_msg_type_name(le16_to_cpu(msg->hdr.type)),
2298              le32_to_cpu(msg->hdr.front_len),
2299              le32_to_cpu(msg->hdr.middle_len),
2300              le32_to_cpu(msg->hdr.data_len));
2301         mutex_unlock(&con->mutex);
2302
2303         /* if there wasn't anything waiting to send before, queue
2304          * new work */
2305         clear_standby(con);
2306         if (test_and_set_bit(WRITE_PENDING, &con->state) == 0)
2307                 queue_con(con);
2308 }
2309 EXPORT_SYMBOL(ceph_con_send);
2310
2311 /*
2312  * Revoke a message that was previously queued for send
2313  */
2314 void ceph_con_revoke(struct ceph_connection *con, struct ceph_msg *msg)
2315 {
2316         mutex_lock(&con->mutex);
2317         if (!list_empty(&msg->list_head)) {
2318                 dout("con_revoke %p msg %p - was on queue\n", con, msg);
2319                 list_del_init(&msg->list_head);
2320                 ceph_msg_put(msg);
2321                 msg->hdr.seq = 0;
2322         }
2323         if (con->out_msg == msg) {
2324                 dout("con_revoke %p msg %p - was sending\n", con, msg);
2325                 con->out_msg = NULL;
2326                 if (con->out_kvec_is_msg) {
2327                         con->out_skip = con->out_kvec_bytes;
2328                         con->out_kvec_is_msg = false;
2329                 }
2330                 ceph_msg_put(msg);
2331                 msg->hdr.seq = 0;
2332         }
2333         mutex_unlock(&con->mutex);
2334 }
2335
2336 /*
2337  * Revoke a message that we may be reading data into
2338  */
2339 void ceph_con_revoke_message(struct ceph_connection *con, struct ceph_msg *msg)
2340 {
2341         mutex_lock(&con->mutex);
2342         if (con->in_msg && con->in_msg == msg) {
2343                 unsigned front_len = le32_to_cpu(con->in_hdr.front_len);
2344                 unsigned middle_len = le32_to_cpu(con->in_hdr.middle_len);
2345                 unsigned data_len = le32_to_cpu(con->in_hdr.data_len);
2346
2347                 /* skip rest of message */
2348                 dout("con_revoke_pages %p msg %p revoked\n", con, msg);
2349                         con->in_base_pos = con->in_base_pos -
2350                                 sizeof(struct ceph_msg_header) -
2351                                 front_len -
2352                                 middle_len -
2353                                 data_len -
2354                                 sizeof(struct ceph_msg_footer);
2355                 ceph_msg_put(con->in_msg);
2356                 con->in_msg = NULL;
2357                 con->in_tag = CEPH_MSGR_TAG_READY;
2358                 con->in_seq++;
2359         } else {
2360                 dout("con_revoke_pages %p msg %p pages %p no-op\n",
2361                      con, con->in_msg, msg);
2362         }
2363         mutex_unlock(&con->mutex);
2364 }
2365
2366 /*
2367  * Queue a keepalive byte to ensure the tcp connection is alive.
2368  */
2369 void ceph_con_keepalive(struct ceph_connection *con)
2370 {
2371         dout("con_keepalive %p\n", con);
2372         clear_standby(con);
2373         if (test_and_set_bit(KEEPALIVE_PENDING, &con->state) == 0 &&
2374             test_and_set_bit(WRITE_PENDING, &con->state) == 0)
2375                 queue_con(con);
2376 }
2377 EXPORT_SYMBOL(ceph_con_keepalive);
2378
2379
2380 /*
2381  * construct a new message with given type, size
2382  * the new msg has a ref count of 1.
2383  */
2384 struct ceph_msg *ceph_msg_new(int type, int front_len, gfp_t flags,
2385                               bool can_fail)
2386 {
2387         struct ceph_msg *m;
2388
2389         m = kmalloc(sizeof(*m), flags);
2390         if (m == NULL)
2391                 goto out;
2392         kref_init(&m->kref);
2393         INIT_LIST_HEAD(&m->list_head);
2394
2395         m->hdr.tid = 0;
2396         m->hdr.type = cpu_to_le16(type);
2397         m->hdr.priority = cpu_to_le16(CEPH_MSG_PRIO_DEFAULT);
2398         m->hdr.version = 0;
2399         m->hdr.front_len = cpu_to_le32(front_len);
2400         m->hdr.middle_len = 0;
2401         m->hdr.data_len = 0;
2402         m->hdr.data_off = 0;
2403         m->hdr.reserved = 0;
2404         m->footer.front_crc = 0;
2405         m->footer.middle_crc = 0;
2406         m->footer.data_crc = 0;
2407         m->footer.flags = 0;
2408         m->front_max = front_len;
2409         m->front_is_vmalloc = false;
2410         m->more_to_follow = false;
2411         m->ack_stamp = 0;
2412         m->pool = NULL;
2413
2414         /* middle */
2415         m->middle = NULL;
2416
2417         /* data */
2418         m->nr_pages = 0;
2419         m->page_alignment = 0;
2420         m->pages = NULL;
2421         m->pagelist = NULL;
2422         m->bio = NULL;
2423         m->bio_iter = NULL;
2424         m->bio_seg = 0;
2425         m->trail = NULL;
2426
2427         /* front */
2428         if (front_len) {
2429                 if (front_len > PAGE_CACHE_SIZE) {
2430                         m->front.iov_base = __vmalloc(front_len, flags,
2431                                                       PAGE_KERNEL);
2432                         m->front_is_vmalloc = true;
2433                 } else {
2434                         m->front.iov_base = kmalloc(front_len, flags);
2435                 }
2436                 if (m->front.iov_base == NULL) {
2437                         dout("ceph_msg_new can't allocate %d bytes\n",
2438                              front_len);
2439                         goto out2;
2440                 }
2441         } else {
2442                 m->front.iov_base = NULL;
2443         }
2444         m->front.iov_len = front_len;
2445
2446         dout("ceph_msg_new %p front %d\n", m, front_len);
2447         return m;
2448
2449 out2:
2450         ceph_msg_put(m);
2451 out:
2452         if (!can_fail) {
2453                 pr_err("msg_new can't create type %d front %d\n", type,
2454                        front_len);
2455                 WARN_ON(1);
2456         } else {
2457                 dout("msg_new can't create type %d front %d\n", type,
2458                      front_len);
2459         }
2460         return NULL;
2461 }
2462 EXPORT_SYMBOL(ceph_msg_new);
2463
2464 /*
2465  * Allocate "middle" portion of a message, if it is needed and wasn't
2466  * allocated by alloc_msg.  This allows us to read a small fixed-size
2467  * per-type header in the front and then gracefully fail (i.e.,
2468  * propagate the error to the caller based on info in the front) when
2469  * the middle is too large.
2470  */
2471 static int ceph_alloc_middle(struct ceph_connection *con, struct ceph_msg *msg)
2472 {
2473         int type = le16_to_cpu(msg->hdr.type);
2474         int middle_len = le32_to_cpu(msg->hdr.middle_len);
2475
2476         dout("alloc_middle %p type %d %s middle_len %d\n", msg, type,
2477              ceph_msg_type_name(type), middle_len);
2478         BUG_ON(!middle_len);
2479         BUG_ON(msg->middle);
2480
2481         msg->middle = ceph_buffer_new(middle_len, GFP_NOFS);
2482         if (!msg->middle)
2483                 return -ENOMEM;
2484         return 0;
2485 }
2486
2487 /*
2488  * Generic message allocator, for incoming messages.
2489  */
2490 static struct ceph_msg *ceph_alloc_msg(struct ceph_connection *con,
2491                                 struct ceph_msg_header *hdr,
2492                                 int *skip)
2493 {
2494         int type = le16_to_cpu(hdr->type);
2495         int front_len = le32_to_cpu(hdr->front_len);
2496         int middle_len = le32_to_cpu(hdr->middle_len);
2497         struct ceph_msg *msg = NULL;
2498         int ret;
2499
2500         if (con->ops->alloc_msg) {
2501                 mutex_unlock(&con->mutex);
2502                 msg = con->ops->alloc_msg(con, hdr, skip);
2503                 mutex_lock(&con->mutex);
2504                 if (!msg || *skip)
2505                         return NULL;
2506         }
2507         if (!msg) {
2508                 *skip = 0;
2509                 msg = ceph_msg_new(type, front_len, GFP_NOFS, false);
2510                 if (!msg) {
2511                         pr_err("unable to allocate msg type %d len %d\n",
2512                                type, front_len);
2513                         return NULL;
2514                 }
2515                 msg->page_alignment = le16_to_cpu(hdr->data_off);
2516         }
2517         memcpy(&msg->hdr, &con->in_hdr, sizeof(con->in_hdr));
2518
2519         if (middle_len && !msg->middle) {
2520                 ret = ceph_alloc_middle(con, msg);
2521                 if (ret < 0) {
2522                         ceph_msg_put(msg);
2523                         return NULL;
2524                 }
2525         }
2526
2527         return msg;
2528 }
2529
2530
2531 /*
2532  * Free a generically kmalloc'd message.
2533  */
2534 void ceph_msg_kfree(struct ceph_msg *m)
2535 {
2536         dout("msg_kfree %p\n", m);
2537         if (m->front_is_vmalloc)
2538                 vfree(m->front.iov_base);
2539         else
2540                 kfree(m->front.iov_base);
2541         kfree(m);
2542 }
2543
2544 /*
2545  * Drop a msg ref.  Destroy as needed.
2546  */
2547 void ceph_msg_last_put(struct kref *kref)
2548 {
2549         struct ceph_msg *m = container_of(kref, struct ceph_msg, kref);
2550
2551         dout("ceph_msg_put last one on %p\n", m);
2552         WARN_ON(!list_empty(&m->list_head));
2553
2554         /* drop middle, data, if any */
2555         if (m->middle) {
2556                 ceph_buffer_put(m->middle);
2557                 m->middle = NULL;
2558         }
2559         m->nr_pages = 0;
2560         m->pages = NULL;
2561
2562         if (m->pagelist) {
2563                 ceph_pagelist_release(m->pagelist);
2564                 kfree(m->pagelist);
2565                 m->pagelist = NULL;
2566         }
2567
2568         m->trail = NULL;
2569
2570         if (m->pool)
2571                 ceph_msgpool_put(m->pool, m);
2572         else
2573                 ceph_msg_kfree(m);
2574 }
2575 EXPORT_SYMBOL(ceph_msg_last_put);
2576
2577 void ceph_msg_dump(struct ceph_msg *msg)
2578 {
2579         pr_debug("msg_dump %p (front_max %d nr_pages %d)\n", msg,
2580                  msg->front_max, msg->nr_pages);
2581         print_hex_dump(KERN_DEBUG, "header: ",
2582                        DUMP_PREFIX_OFFSET, 16, 1,
2583                        &msg->hdr, sizeof(msg->hdr), true);
2584         print_hex_dump(KERN_DEBUG, " front: ",
2585                        DUMP_PREFIX_OFFSET, 16, 1,
2586                        msg->front.iov_base, msg->front.iov_len, true);
2587         if (msg->middle)
2588                 print_hex_dump(KERN_DEBUG, "middle: ",
2589                                DUMP_PREFIX_OFFSET, 16, 1,
2590                                msg->middle->vec.iov_base,
2591                                msg->middle->vec.iov_len, true);
2592         print_hex_dump(KERN_DEBUG, "footer: ",
2593                        DUMP_PREFIX_OFFSET, 16, 1,
2594                        &msg->footer, sizeof(msg->footer), true);
2595 }
2596 EXPORT_SYMBOL(ceph_msg_dump);