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