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