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