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