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