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