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