Whamcloud - gitweb
LU-16035 kfilnd: Initial kfilnd implementation
[fs/lustre-release.git] / lnet / klnds / kfilnd / kfilnd_tn.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright 2022 Hewlett Packard Enterprise Development LP
24  */
25 /*
26  * This file is part of Lustre, http://www.lustre.org/
27  */
28 /*
29  * kfilnd transaction and state machine processing.
30  */
31
32 #include "kfilnd_tn.h"
33 #include "kfilnd_ep.h"
34 #include "kfilnd_dev.h"
35 #include "kfilnd_dom.h"
36 #include "kfilnd_peer.h"
37 #include <asm/checksum.h>
38
39 static struct kmem_cache *tn_cache;
40 static struct kmem_cache *imm_buf_cache;
41
42 static __sum16 kfilnd_tn_cksum(void *ptr, int nob)
43 {
44         if (cksum)
45                 return csum_fold(csum_partial(ptr, nob, 0));
46         return NO_CHECKSUM;
47 }
48
49 static int kfilnd_tn_msgtype2size(enum kfilnd_msg_type type)
50 {
51         const int hdr_size = offsetof(struct kfilnd_msg, proto);
52
53         switch (type) {
54         case KFILND_MSG_IMMEDIATE:
55                 return offsetof(struct kfilnd_msg, proto.immed.payload[0]);
56
57         case KFILND_MSG_BULK_PUT_REQ:
58         case KFILND_MSG_BULK_GET_REQ:
59                 return hdr_size + sizeof(struct kfilnd_bulk_req_msg);
60
61         default:
62                 return -1;
63         }
64 }
65
66 static void kfilnd_tn_pack_hello_req(struct kfilnd_transaction *tn)
67 {
68         struct kfilnd_msg *msg = tn->tn_tx_msg.msg;
69
70         /* Pack the protocol header and payload. */
71         msg->proto.hello.version = KFILND_MSG_VERSION;
72         msg->proto.hello.rx_base = kfilnd_peer_target_rx_base(tn->peer);
73         msg->proto.hello.session_key = tn->peer->local_session_key;
74
75         /* TODO: Support multiple RX contexts per peer. */
76         msg->proto.hello.rx_count = 1;
77
78         /* Pack the transport header. */
79         msg->magic = KFILND_MSG_MAGIC;
80
81         /* Mesage version zero is only valid for hello requests. */
82         msg->version = 0;
83         msg->type = KFILND_MSG_HELLO_REQ;
84         msg->nob = sizeof(struct kfilnd_hello_msg) +
85                 offsetof(struct kfilnd_msg, proto);
86         msg->cksum = NO_CHECKSUM;
87         msg->srcnid = lnet_nid_to_nid4(&tn->tn_ep->end_dev->kfd_ni->ni_nid);
88         msg->dstnid = tn->peer->nid;
89
90         /* Checksum entire message. */
91         msg->cksum = kfilnd_tn_cksum(msg, msg->nob);
92
93         tn->tn_tx_msg.length = msg->nob;
94 }
95
96 static void kfilnd_tn_pack_hello_rsp(struct kfilnd_transaction *tn)
97 {
98         struct kfilnd_msg *msg = tn->tn_tx_msg.msg;
99
100         /* Pack the protocol header and payload. */
101         msg->proto.hello.version = tn->peer->version;
102         msg->proto.hello.rx_base = kfilnd_peer_target_rx_base(tn->peer);
103         msg->proto.hello.session_key = tn->peer->local_session_key;
104
105         /* TODO: Support multiple RX contexts per peer. */
106         msg->proto.hello.rx_count = 1;
107
108         /* Pack the transport header. */
109         msg->magic = KFILND_MSG_MAGIC;
110
111         /* Mesage version zero is only valid for hello requests. */
112         msg->version = 0;
113         msg->type = KFILND_MSG_HELLO_RSP;
114         msg->nob = sizeof(struct kfilnd_hello_msg) +
115                 offsetof(struct kfilnd_msg, proto);
116         msg->cksum = NO_CHECKSUM;
117         msg->srcnid = lnet_nid_to_nid4(&tn->tn_ep->end_dev->kfd_ni->ni_nid);
118         msg->dstnid = tn->peer->nid;
119
120         /* Checksum entire message. */
121         msg->cksum = kfilnd_tn_cksum(msg, msg->nob);
122
123         tn->tn_tx_msg.length = msg->nob;
124 }
125
126 static void kfilnd_tn_pack_bulk_req(struct kfilnd_transaction *tn)
127 {
128         struct kfilnd_msg *msg = tn->tn_tx_msg.msg;
129
130         /* Pack the protocol header and payload. */
131         lnet_hdr_to_nid4(&tn->tn_lntmsg->msg_hdr, &msg->proto.bulk_req.hdr);
132         msg->proto.bulk_req.key = tn->tn_mr_key;
133         msg->proto.bulk_req.response_rx = tn->tn_response_rx;
134
135         /* Pack the transport header. */
136         msg->magic = KFILND_MSG_MAGIC;
137         msg->version = KFILND_MSG_VERSION;
138         msg->type = tn->msg_type;
139         msg->nob = sizeof(struct kfilnd_bulk_req_msg) +
140                 offsetof(struct kfilnd_msg, proto);
141         msg->cksum = NO_CHECKSUM;
142         msg->srcnid = lnet_nid_to_nid4(&tn->tn_ep->end_dev->kfd_ni->ni_nid);
143         msg->dstnid = tn->peer->nid;
144
145         /* Checksum entire message. */
146         msg->cksum = kfilnd_tn_cksum(msg, msg->nob);
147
148         tn->tn_tx_msg.length = msg->nob;
149 }
150
151 static void kfilnd_tn_pack_immed_msg(struct kfilnd_transaction *tn)
152 {
153         struct kfilnd_msg *msg = tn->tn_tx_msg.msg;
154
155         /* Pack the protocol header and payload. */
156         lnet_hdr_to_nid4(&tn->tn_lntmsg->msg_hdr, &msg->proto.immed.hdr);
157
158         lnet_copy_kiov2flat(KFILND_IMMEDIATE_MSG_SIZE,
159                             msg,
160                             offsetof(struct kfilnd_msg,
161                                      proto.immed.payload),
162                             tn->tn_num_iovec, tn->tn_kiov, 0,
163                             tn->tn_nob);
164
165         /* Pack the transport header. */
166         msg->magic = KFILND_MSG_MAGIC;
167         msg->version = KFILND_MSG_VERSION;
168         msg->type = tn->msg_type;
169         msg->nob = offsetof(struct kfilnd_msg, proto.immed.payload[tn->tn_nob]);
170         msg->cksum = NO_CHECKSUM;
171         msg->srcnid = lnet_nid_to_nid4(&tn->tn_ep->end_dev->kfd_ni->ni_nid);
172         msg->dstnid = tn->peer->nid;
173
174         /* Checksum entire message. */
175         msg->cksum = kfilnd_tn_cksum(msg, msg->nob);
176
177         tn->tn_tx_msg.length = msg->nob;
178 }
179
180 static int kfilnd_tn_unpack_msg(struct kfilnd_ep *ep, struct kfilnd_msg *msg,
181                                 unsigned int nob)
182 {
183         const unsigned int hdr_size = offsetof(struct kfilnd_msg, proto);
184
185         if (nob < hdr_size) {
186                 KFILND_EP_ERROR(ep, "Short message: %u", nob);
187                 return -EPROTO;
188         }
189
190         /* TODO: Support byte swapping on mixed endian systems. */
191         if (msg->magic != KFILND_MSG_MAGIC) {
192                 KFILND_EP_ERROR(ep, "Bad magic: %#x", msg->magic);
193                 return -EPROTO;
194         }
195
196         /* TODO: Allow for older versions. */
197         if (msg->version > KFILND_MSG_VERSION) {
198                 KFILND_EP_ERROR(ep, "Bad version: %#x", msg->version);
199                 return -EPROTO;
200         }
201
202         if (msg->nob > nob) {
203                 KFILND_EP_ERROR(ep, "Short message: got=%u, expected=%u", nob,
204                                 msg->nob);
205                 return -EPROTO;
206         }
207
208         /* If kfilnd_tn_cksum() returns a non-zero value, checksum is bad. */
209         if (msg->cksum != NO_CHECKSUM && kfilnd_tn_cksum(msg, msg->nob)) {
210                 KFILND_EP_ERROR(ep, "Bad checksum");
211                 return -EPROTO;
212         }
213
214         if (msg->dstnid != lnet_nid_to_nid4(&ep->end_dev->kfd_ni->ni_nid)) {
215                 KFILND_EP_ERROR(ep, "Bad destination nid: %s",
216                                 libcfs_nid2str(msg->dstnid));
217                 return -EPROTO;
218         }
219
220         if (msg->srcnid == LNET_NID_ANY) {
221                 KFILND_EP_ERROR(ep, "Bad source nid: %s",
222                                 libcfs_nid2str(msg->srcnid));
223                 return -EPROTO;
224         }
225
226         if (msg->nob < kfilnd_tn_msgtype2size(msg->type)) {
227                 KFILND_EP_ERROR(ep, "Short %s: %d(%d)\n",
228                                 msg_type_to_str(msg->type),
229                                 msg->nob, kfilnd_tn_msgtype2size(msg->type));
230                 return -EPROTO;
231         }
232
233         switch ((enum kfilnd_msg_type)msg->type) {
234         case KFILND_MSG_IMMEDIATE:
235         case KFILND_MSG_BULK_PUT_REQ:
236         case KFILND_MSG_BULK_GET_REQ:
237                 if (msg->version == 0) {
238                         KFILND_EP_ERROR(ep,
239                                         "Bad message type and version: type=%s version=%u",
240                                         msg_type_to_str(msg->type),
241                                         msg->version);
242                         return -EPROTO;
243                 }
244                 break;
245
246         case KFILND_MSG_HELLO_REQ:
247         case KFILND_MSG_HELLO_RSP:
248                 if (msg->version != 0) {
249                         KFILND_EP_ERROR(ep,
250                                         "Bad message type and version: type=%s version=%u",
251                                         msg_type_to_str(msg->type),
252                                         msg->version);
253                         return -EPROTO;
254                 }
255                 break;
256
257         default:
258                 CERROR("Unknown message type %x\n", msg->type);
259                 return -EPROTO;
260         }
261         return 0;
262 }
263
264 static void kfilnd_tn_record_state_change(struct kfilnd_transaction *tn)
265 {
266         unsigned int data_size_bucket =
267                 kfilnd_msg_len_to_data_size_bucket(tn->lnet_msg_len);
268         struct kfilnd_tn_duration_stat *stat;
269
270         if (tn->is_initiator)
271                 stat = &tn->tn_ep->end_dev->initiator_state_stats.state[tn->tn_state].data_size[data_size_bucket];
272         else
273                 stat = &tn->tn_ep->end_dev->target_state_stats.state[tn->tn_state].data_size[data_size_bucket];
274
275         atomic64_add(ktime_to_ns(ktime_sub(ktime_get(), tn->tn_state_ts)),
276                      &stat->accumulated_duration);
277         atomic_inc(&stat->accumulated_count);
278 }
279
280 static void kfilnd_tn_state_change(struct kfilnd_transaction *tn,
281                                    enum tn_states new_state)
282 {
283         KFILND_TN_DEBUG(tn, "%s -> %s state change",
284                         tn_state_to_str(tn->tn_state),
285                         tn_state_to_str(new_state));
286
287         kfilnd_tn_record_state_change(tn);
288
289         tn->tn_state = new_state;
290         tn->tn_state_ts = ktime_get();
291 }
292
293 static void kfilnd_tn_status_update(struct kfilnd_transaction *tn, int status,
294                                     enum lnet_msg_hstatus hstatus)
295 {
296         /* Only the first non-ok status will take. */
297         if (tn->tn_status == 0) {
298                 KFILND_TN_DEBUG(tn, "%d -> %d status change", tn->tn_status,
299                                 status);
300                 tn->tn_status = status;
301         }
302
303         if (tn->hstatus == LNET_MSG_STATUS_OK) {
304                 KFILND_TN_DEBUG(tn, "%d -> %d health status change",
305                                 tn->hstatus, hstatus);
306                 tn->hstatus = hstatus;
307         }
308 }
309
310 static bool kfilnd_tn_has_failed(struct kfilnd_transaction *tn)
311 {
312         return tn->tn_status != 0;
313 }
314
315 /**
316  * kfilnd_tn_process_rx_event() - Process an immediate receive event.
317  *
318  * For each immediate receive, a transaction structure needs to be allocated to
319  * process the receive.
320  */
321 void kfilnd_tn_process_rx_event(struct kfilnd_immediate_buffer *bufdesc,
322                                 struct kfilnd_msg *rx_msg, int msg_size)
323 {
324         struct kfilnd_transaction *tn;
325         bool alloc_msg = true;
326         int rc;
327         enum tn_events event = TN_EVENT_RX_HELLO;
328
329         /* Increment buf ref count for this work */
330         atomic_inc(&bufdesc->immed_ref);
331
332         /* Unpack the message */
333         rc = kfilnd_tn_unpack_msg(bufdesc->immed_end, rx_msg, msg_size);
334         if (rc || CFS_FAIL_CHECK(CFS_KFI_FAIL_MSG_UNPACK)) {
335                 kfilnd_ep_imm_buffer_put(bufdesc);
336                 KFILND_EP_ERROR(bufdesc->immed_end,
337                                 "Failed to unpack message %d", rc);
338                 return;
339         }
340
341         switch ((enum kfilnd_msg_type)rx_msg->type) {
342         case KFILND_MSG_IMMEDIATE:
343         case KFILND_MSG_BULK_PUT_REQ:
344         case KFILND_MSG_BULK_GET_REQ:
345                 event = TN_EVENT_RX_OK;
346                 fallthrough;
347         case KFILND_MSG_HELLO_RSP:
348                 alloc_msg = false;
349                 fallthrough;
350         case KFILND_MSG_HELLO_REQ:
351                 /* Context points to a received buffer and status is the length.
352                  * Allocate a Tn structure, set its values, then launch the
353                  * receive.
354                  */
355                 tn = kfilnd_tn_alloc(bufdesc->immed_end->end_dev,
356                                      bufdesc->immed_end->end_cpt,
357                                      rx_msg->srcnid, alloc_msg, false,
358                                      false);
359                 if (IS_ERR(tn)) {
360                         kfilnd_ep_imm_buffer_put(bufdesc);
361                         KFILND_EP_ERROR(bufdesc->immed_end,
362                                         "Failed to allocate transaction struct: rc=%ld",
363                                         PTR_ERR(tn));
364                         return;
365                 }
366
367                 tn->tn_rx_msg.msg = rx_msg;
368                 tn->tn_rx_msg.length = msg_size;
369                 tn->tn_posted_buf = bufdesc;
370
371                 KFILND_EP_DEBUG(bufdesc->immed_end, "%s transaction ID %u",
372                                 msg_type_to_str((enum kfilnd_msg_type)rx_msg->type),
373                                 tn->tn_mr_key);
374                 break;
375
376         default:
377                 KFILND_EP_ERROR(bufdesc->immed_end,
378                                 "Unhandled kfilnd message type: %d",
379                                 (enum kfilnd_msg_type)rx_msg->type);
380                 LBUG();
381         };
382
383         kfilnd_tn_event_handler(tn, event, 0);
384 }
385
386 static void kfilnd_tn_record_duration(struct kfilnd_transaction *tn)
387 {
388         unsigned int data_size_bucket =
389                 kfilnd_msg_len_to_data_size_bucket(tn->lnet_msg_len);
390         struct kfilnd_tn_duration_stat *stat;
391
392         if (tn->is_initiator)
393                 stat = &tn->tn_ep->end_dev->initiator_stats.data_size[data_size_bucket];
394         else
395                 stat = &tn->tn_ep->end_dev->target_stats.data_size[data_size_bucket];
396
397         atomic64_add(ktime_to_ns(ktime_sub(ktime_get(), tn->tn_alloc_ts)),
398                      &stat->accumulated_duration);
399         atomic_inc(&stat->accumulated_count);
400 }
401
402 /**
403  * kfilnd_tn_finalize() - Cleanup resources and finalize LNet operation.
404  *
405  * All state machine functions should call kfilnd_tn_finalize() instead of
406  * kfilnd_tn_free(). Once all expected asynchronous events have been received,
407  * if the transaction lock has not been released, it will now be released,
408  * transaction resources cleaned up, and LNet finalized will be called.
409  */
410 static void kfilnd_tn_finalize(struct kfilnd_transaction *tn, bool *tn_released)
411 {
412         if (!*tn_released) {
413                 mutex_unlock(&tn->tn_lock);
414                 *tn_released = true;
415         }
416
417         /* Release the reference on the multi-receive buffer. */
418         if (tn->tn_posted_buf)
419                 kfilnd_ep_imm_buffer_put(tn->tn_posted_buf);
420
421         /* Finalize LNet operation. */
422         if (tn->tn_lntmsg) {
423                 tn->tn_lntmsg->msg_health_status = tn->hstatus;
424                 lnet_finalize(tn->tn_lntmsg, tn->tn_status);
425         }
426
427         if (tn->tn_getreply) {
428                 tn->tn_getreply->msg_health_status = tn->hstatus;
429                 lnet_set_reply_msg_len(tn->tn_ep->end_dev->kfd_ni,
430                                        tn->tn_getreply,
431                                        tn->tn_status ? 0 : tn->tn_nob);
432                 lnet_finalize(tn->tn_getreply, tn->tn_status);
433         }
434
435         if (KFILND_TN_PEER_VALID(tn))
436                 kfilnd_peer_put(tn->peer);
437
438         kfilnd_tn_record_state_change(tn);
439         kfilnd_tn_record_duration(tn);
440
441         kfilnd_tn_free(tn);
442 }
443
444 /**
445  * kfilnd_tn_cancel_tag_recv() - Attempt to cancel a tagged receive.
446  * @tn: Transaction to have tagged received cancelled.
447  *
448  * Return: 0 on success. Else, negative errno. If an error occurs, resources may
449  * be leaked.
450  */
451 static int kfilnd_tn_cancel_tag_recv(struct kfilnd_transaction *tn)
452 {
453         int rc;
454
455         /* Issue a cancel. A return code of zero means the operation issued an
456          * async cancel. A return code of -ENOENT means the tagged receive was
457          * not found. The assumption here is that a tagged send landed thus
458          * removing the tagged receive buffer from hardware. For both cases,
459          * async events should occur.
460          */
461         rc = kfilnd_ep_cancel_tagged_recv(tn->tn_ep, tn);
462         if (rc != 0 && rc != -ENOENT) {
463                 KFILND_TN_ERROR(tn, "Failed to cancel tag receive. Resources may leak.");
464                 return rc;
465         }
466
467         return 0;
468 }
469
470 static void kfilnd_tn_timeout_work(struct work_struct *work)
471 {
472         struct kfilnd_transaction *tn =
473                 container_of(work, struct kfilnd_transaction, timeout_work);
474
475         KFILND_TN_ERROR(tn, "Bulk operation timeout");
476         kfilnd_tn_event_handler(tn, TN_EVENT_TIMEOUT, 0);
477 }
478
479 static void kfilnd_tn_timeout(cfs_timer_cb_arg_t data)
480 {
481         struct kfilnd_transaction *tn = cfs_from_timer(tn, data, timeout_timer);
482
483         queue_work(kfilnd_wq, &tn->timeout_work);
484 }
485
486 static bool kfilnd_tn_timeout_cancel(struct kfilnd_transaction *tn)
487 {
488         return del_timer(&tn->timeout_timer);
489 }
490
491 static void kfilnd_tn_timeout_enable(struct kfilnd_transaction *tn)
492 {
493         ktime_t remaining_time = max_t(ktime_t, 0,
494                                        tn->deadline - ktime_get_seconds());
495         unsigned long expires = remaining_time * HZ + jiffies;
496
497         if (CFS_FAIL_CHECK(CFS_KFI_FAIL_BULK_TIMEOUT))
498                 expires = jiffies;
499
500         cfs_timer_setup(&tn->timeout_timer, kfilnd_tn_timeout,
501                         (unsigned long)tn, 0);
502         mod_timer(&tn->timeout_timer, expires);
503 }
504
505 /*  The following are the state machine routines for the transactions. */
506 static int kfilnd_tn_state_send_failed(struct kfilnd_transaction *tn,
507                                        enum tn_events event, int status,
508                                        bool *tn_released)
509 {
510         int rc;
511
512         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
513                         status);
514
515         switch (event) {
516         case TN_EVENT_INIT_BULK:
517                 /* Need to cancel the tagged receive to prevent resources from
518                  * being leaked.
519                  */
520                 rc = kfilnd_tn_cancel_tag_recv(tn);
521
522                 switch (rc) {
523                 /* Async event will progress transaction. */
524                 case 0:
525                         kfilnd_tn_state_change(tn, TN_STATE_FAIL);
526                         return 0;
527
528                 /* Need to replay TN_EVENT_INIT_BULK event while in the
529                  * TN_STATE_SEND_FAILED state.
530                  */
531                 case -EAGAIN:
532                         KFILND_TN_DEBUG(tn,
533                                         "Need to replay cancel tagged recv");
534                         return -EAGAIN;
535
536                 default:
537                         KFILND_TN_ERROR(tn,
538                                         "Unexpected error during cancel tagged receive: rc=%d",
539                                         rc);
540                         LBUG();
541                 }
542                 break;
543
544         default:
545                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
546                 LBUG();
547         }
548 }
549
550 static int kfilnd_tn_state_tagged_recv_posted(struct kfilnd_transaction *tn,
551                                               enum tn_events event, int status,
552                                               bool *tn_released)
553 {
554         int rc;
555
556         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
557                         status);
558
559         switch (event) {
560         case TN_EVENT_INIT_BULK:
561                 tn->tn_target_addr = kfilnd_peer_get_kfi_addr(tn->peer);
562                 KFILND_TN_DEBUG(tn, "Using peer %s(%#llx)",
563                                 libcfs_nid2str(tn->peer->nid),
564                                 tn->tn_target_addr);
565
566                 kfilnd_tn_pack_bulk_req(tn);
567
568                 rc = kfilnd_ep_post_send(tn->tn_ep, tn);
569                 switch (rc) {
570                 /* Async event will progress immediate send. */
571                 case 0:
572                         kfilnd_tn_state_change(tn, TN_STATE_WAIT_COMP);
573                         return 0;
574
575                 /* Need to replay TN_EVENT_INIT_BULK event while in the
576                  * TN_STATE_TAGGED_RECV_POSTED state.
577                  */
578                 case -EAGAIN:
579                         KFILND_TN_DEBUG(tn,
580                                         "Need to replay post send to %s(%#llx)",
581                                         libcfs_nid2str(tn->peer->nid),
582                                         tn->tn_target_addr);
583                         return -EAGAIN;
584
585                 /* Need to transition to the TN_STATE_SEND_FAILED to cleanup
586                  * posted tagged receive buffer.
587                  */
588                 default:
589                         KFILND_TN_ERROR(tn,
590                                         "Failed to post send to %s(%#llx): rc=%d",
591                                         libcfs_nid2str(tn->peer->nid),
592                                         tn->tn_target_addr, rc);
593                         kfilnd_tn_status_update(tn, rc,
594                                                 LNET_MSG_STATUS_LOCAL_ERROR);
595                         kfilnd_tn_state_change(tn, TN_STATE_SEND_FAILED);
596
597                         /* Propogate TN_EVENT_INIT_BULK event to
598                          * TN_STATE_SEND_FAILED handler.
599                          */
600                         return kfilnd_tn_state_send_failed(tn, event, rc,
601                                                            tn_released);
602                 }
603
604         default:
605                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
606                 LBUG();
607         }
608 }
609
610 static int kfilnd_tn_state_idle(struct kfilnd_transaction *tn,
611                                 enum tn_events event, int status,
612                                 bool *tn_released)
613 {
614         struct kfilnd_msg *msg;
615         int rc;
616         bool finalize = false;
617         ktime_t remaining_time;
618         struct lnet_hdr hdr;
619         struct lnet_nid srcnid;
620
621         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
622                         status);
623
624         /* For new peers, send a hello request message and queue the true LNet
625          * message for replay.
626          */
627         if (kfilnd_peer_is_new_peer(tn->peer) &&
628             (event == TN_EVENT_INIT_IMMEDIATE || event == TN_EVENT_INIT_BULK)) {
629                 remaining_time = max_t(ktime_t, 0,
630                                        tn->deadline - ktime_get_seconds());
631
632                 /* If transaction deadline has not be met, return -EAGAIN. This
633                  * will cause this transaction event to be replayed. During this
634                  * time, an async message from the peer should occur at which
635                  * point the kfilnd version should be negotiated.
636                  */
637                 if (remaining_time > 0) {
638                         KFILND_TN_DEBUG(tn, "%s hello response pending",
639                                         libcfs_nid2str(tn->peer->nid));
640                         return -EAGAIN;
641                 }
642
643                 rc = 0;
644                 kfilnd_tn_status_update(tn, -ETIMEDOUT,
645                                         LNET_MSG_STATUS_NETWORK_TIMEOUT);
646                 goto out;
647         }
648
649         switch (event) {
650         case TN_EVENT_INIT_IMMEDIATE:
651         case TN_EVENT_TX_HELLO:
652                 tn->tn_target_addr = kfilnd_peer_get_kfi_addr(tn->peer);
653                 KFILND_TN_DEBUG(tn, "Using peer %s(%#llx)",
654                                 libcfs_nid2str(tn->peer->nid),
655                                 tn->tn_target_addr);
656
657                 if (event == TN_EVENT_INIT_IMMEDIATE)
658                         kfilnd_tn_pack_immed_msg(tn);
659                 else
660                         kfilnd_tn_pack_hello_req(tn);
661
662                 /* Send immediate message. */
663                 rc = kfilnd_ep_post_send(tn->tn_ep, tn);
664                 switch (rc) {
665                 /* Async event will progress immediate send. */
666                 case 0:
667                         kfilnd_tn_state_change(tn, TN_STATE_IMM_SEND);
668                         return 0;
669
670                 /* Need to TN_EVENT_INIT_IMMEDIATE event while in TN_STATE_IDLE
671                  * state.
672                  */
673                 case -EAGAIN:
674                         KFILND_TN_DEBUG(tn, "Need to replay send to %s(%#llx)",
675                                         libcfs_nid2str(tn->peer->nid),
676                                         tn->tn_target_addr);
677                         return -EAGAIN;
678
679                 default:
680                         KFILND_TN_ERROR(tn,
681                                         "Failed to post send to %s(%#llx): rc=%d",
682                                         libcfs_nid2str(tn->peer->nid),
683                                         tn->tn_target_addr, rc);
684                         kfilnd_tn_status_update(tn, rc,
685                                                 LNET_MSG_STATUS_LOCAL_ERROR);
686                 }
687                 break;
688
689         case TN_EVENT_INIT_BULK:
690                 /* Post tagged receive buffer used to land bulk response. */
691                 rc = kfilnd_ep_post_tagged_recv(tn->tn_ep, tn);
692
693                 switch (rc) {
694                 /* Transition to TN_STATE_TAGGED_RECV_POSTED on success. */
695                 case 0:
696                         kfilnd_tn_state_change(tn, TN_STATE_TAGGED_RECV_POSTED);
697
698                         /* Propogate TN_EVENT_INIT_BULK event to
699                          * TN_STATE_TAGGED_RECV_POSTED handler.
700                          */
701                         return kfilnd_tn_state_tagged_recv_posted(tn, event,
702                                                                   rc,
703                                                                   tn_released);
704
705                 /* Need to replay TN_EVENT_INIT_BULK event in the TN_STATE_IDLE
706                  * state.
707                  */
708                 case -EAGAIN:
709                         KFILND_TN_DEBUG(tn, "Need to replay tagged recv");
710                         return -EAGAIN;
711
712                 default:
713                         KFILND_TN_ERROR(tn, "Failed to post tagged recv %d",
714                                         rc);
715                         kfilnd_tn_status_update(tn, rc,
716                                                 LNET_MSG_STATUS_LOCAL_ERROR);
717                 }
718                 break;
719
720         case TN_EVENT_RX_OK:
721                 /* If TN_EVENT_RX_OK occurs on a new peer, this is a sign of a
722                  * peer having a stale peer structure. Stale peer structures
723                  * requires dropping the incoming message and initiating a hello
724                  * handshake.
725                  */
726                 if (kfilnd_peer_is_new_peer(tn->peer)) {
727                         rc = kfilnd_send_hello_request(tn->tn_ep->end_dev,
728                                                        tn->tn_ep->end_cpt,
729                                                        tn->peer->nid);
730                         if (rc)
731                                 KFILND_TN_ERROR(tn,
732                                                 "Failed to send hello request: rc=%d",
733                                                 rc);
734
735                         /* Need to drop this message since it is uses stale
736                          * peer.
737                          */
738                         KFILND_TN_ERROR(tn,
739                                         "Dropping message from %s due to stale peer",
740                                         libcfs_nid2str(tn->peer->nid));
741                         kfilnd_tn_status_update(tn, -EPROTO,
742                                                 LNET_MSG_STATUS_LOCAL_DROPPED);
743                         rc = 0;
744                         goto out;
745                 }
746
747                 LASSERT(kfilnd_peer_is_new_peer(tn->peer) == false);
748                 msg = tn->tn_rx_msg.msg;
749
750                 /* Update the NID address with the new preferred RX context. */
751                 kfilnd_peer_alive(tn->peer);
752
753                 /* Pass message up to LNet
754                  * The TN will be reused in this call chain so we need to
755                  * release the lock on the TN before proceeding.
756                  */
757                 KFILND_TN_DEBUG(tn, "%s -> TN_STATE_IMM_RECV state change",
758                                 tn_state_to_str(tn->tn_state));
759
760                 /* TODO: Do not manually update this state change. */
761                 tn->tn_state = TN_STATE_IMM_RECV;
762                 mutex_unlock(&tn->tn_lock);
763                 *tn_released = true;
764                 lnet_nid4_to_nid(msg->srcnid, &srcnid);
765                 if (msg->type == KFILND_MSG_IMMEDIATE) {
766                         lnet_hdr_from_nid4(&hdr, &msg->proto.immed.hdr);
767                         rc = lnet_parse(tn->tn_ep->end_dev->kfd_ni,
768                                         &hdr, &srcnid, tn, 0);
769                 } else {
770                         lnet_hdr_from_nid4(&hdr, &msg->proto.bulk_req.hdr);
771                         rc = lnet_parse(tn->tn_ep->end_dev->kfd_ni,
772                                         &hdr, &srcnid, tn, 1);
773                 }
774
775                 /* If successful, transaction has been accepted by LNet and we
776                  * cannot process the transaction anymore within this context.
777                  */
778                 if (!rc)
779                         return 0;
780
781                 KFILND_TN_ERROR(tn, "Failed to parse LNet message: rc=%d", rc);
782                 kfilnd_tn_status_update(tn, rc, LNET_MSG_STATUS_LOCAL_ERROR);
783                 break;
784
785         case TN_EVENT_RX_HELLO:
786                 msg = tn->tn_rx_msg.msg;
787
788                 switch (msg->type) {
789                 case KFILND_MSG_HELLO_REQ:
790                         kfilnd_peer_update_rx_contexts(tn->peer,
791                                                        msg->proto.hello.rx_base,
792                                                        msg->proto.hello.rx_count);
793                         kfilnd_peer_set_remote_session_key(tn->peer,
794                                                            msg->proto.hello.session_key);
795
796                         /* Negotiate kfilnd version used between peers. Fallback
797                          * to the minimum implemented kfilnd version.
798                          */
799                         kfilnd_peer_set_version(tn->peer,
800                                                 min_t(__u16, KFILND_MSG_VERSION,
801                                                     msg->proto.hello.version));
802                         KFILND_TN_DEBUG(tn,
803                                         "Peer kfilnd version: %u; Local kfilnd version: %u; Negotiated kfilnd verions: %u",
804                                         msg->proto.hello.version,
805                                         KFILND_MSG_VERSION, tn->peer->version);
806
807                         tn->tn_target_addr = kfilnd_peer_get_kfi_addr(tn->peer);
808                         KFILND_TN_DEBUG(tn, "Using peer %s(%#llx)",
809                                         libcfs_nid2str(tn->peer->nid),
810                                         tn->tn_target_addr);
811
812                         kfilnd_tn_pack_hello_rsp(tn);
813
814                         /* Send immediate message. */
815                         rc = kfilnd_ep_post_send(tn->tn_ep, tn);
816                         switch (rc) {
817                         case 0:
818                                 kfilnd_tn_state_change(tn, TN_STATE_IMM_SEND);
819                                 return 0;
820
821                         case -EAGAIN:
822                                 KFILND_TN_DEBUG(tn, "Need to replay send to %s(%#llx)",
823                                                 libcfs_nid2str(tn->peer->nid),
824                                                 tn->tn_target_addr);
825                                 return -EAGAIN;
826
827                         default:
828                                 KFILND_TN_ERROR(tn,
829                                                 "Failed to post send to %s(%#llx): rc=%d",
830                                                 libcfs_nid2str(tn->peer->nid),
831                                                 tn->tn_target_addr, rc);
832                                 kfilnd_tn_status_update(tn, rc,
833                                                         LNET_MSG_STATUS_LOCAL_ERROR);
834                         }
835                         break;
836
837                 case KFILND_MSG_HELLO_RSP:
838                         rc = 0;
839                         kfilnd_peer_update_rx_contexts(tn->peer,
840                                                        msg->proto.hello.rx_base,
841                                                        msg->proto.hello.rx_count);
842                         kfilnd_peer_set_remote_session_key(tn->peer,
843                                                            msg->proto.hello.session_key);
844                         kfilnd_peer_set_version(tn->peer,
845                                                 msg->proto.hello.version);
846                         KFILND_TN_DEBUG(tn, "Negotiated kfilnd version: %u",
847                                         msg->proto.hello.version);
848                         finalize = true;
849                         break;
850
851                 default:
852                         KFILND_TN_ERROR(tn, "Invalid message type: %s",
853                                         msg_type_to_str(msg->type));
854                         LBUG();
855                 }
856                 break;
857
858         default:
859                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
860                 LBUG();
861         }
862
863 out:
864         if (kfilnd_tn_has_failed(tn))
865                 finalize = true;
866
867         if (finalize)
868                 kfilnd_tn_finalize(tn, tn_released);
869
870         return rc;
871 }
872
873 static int kfilnd_tn_state_imm_send(struct kfilnd_transaction *tn,
874                                     enum tn_events event, int status,
875                                     bool *tn_released)
876 {
877         enum lnet_msg_hstatus hstatus;
878
879         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
880                         status);
881
882         switch (event) {
883         case TN_EVENT_TX_FAIL:
884                 if (status == -ETIMEDOUT || status == -EIO)
885                         hstatus = LNET_MSG_STATUS_NETWORK_TIMEOUT;
886                 else
887                         hstatus = LNET_MSG_STATUS_REMOTE_ERROR;
888
889                 kfilnd_tn_status_update(tn, status, hstatus);
890                 kfilnd_peer_down(tn->peer);
891                 break;
892
893         case TN_EVENT_TX_OK:
894                 kfilnd_peer_alive(tn->peer);
895                 break;
896
897         default:
898                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
899                 LBUG();
900         }
901
902         kfilnd_tn_finalize(tn, tn_released);
903
904         return 0;
905 }
906
907 static int kfilnd_tn_state_imm_recv(struct kfilnd_transaction *tn,
908                                     enum tn_events event, int status,
909                                     bool *tn_released)
910 {
911         int rc = 0;
912         bool finalize = false;
913
914         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
915                         status);
916
917         switch (event) {
918         case TN_EVENT_INIT_TAG_RMA:
919         case TN_EVENT_SKIP_TAG_RMA:
920                 /* Release the buffer we received the request on. All relevant
921                  * information to perform the RMA operation is stored in the
922                  * transaction structure. This should be done before the RMA
923                  * operation to prevent two contexts from potentially processing
924                  * the same transaction.
925                  *
926                  * TODO: Prevent this from returning -EAGAIN.
927                  */
928                 if (tn->tn_posted_buf) {
929                         kfilnd_ep_imm_buffer_put(tn->tn_posted_buf);
930                         tn->tn_posted_buf = NULL;
931                 }
932
933                 /* Update the KFI address to use the response RX context. */
934                 tn->tn_target_addr =
935                         kfi_rx_addr(KFILND_BASE_ADDR(tn->peer->addr),
936                                     tn->tn_response_rx, KFILND_FAB_RX_CTX_BITS);
937                 KFILND_TN_DEBUG(tn, "Using peer %s(0x%llx)",
938                                 libcfs_nid2str(tn->peer->nid),
939                                 tn->tn_target_addr);
940
941                 /* Initiate the RMA operation to push/pull the LNet payload or
942                  * send a tagged message to finalize the bulk operation if the
943                  * RMA operation should be skipped.
944                  */
945                 if (event == TN_EVENT_INIT_TAG_RMA) {
946                         if (tn->sink_buffer)
947                                 rc = kfilnd_ep_post_read(tn->tn_ep, tn);
948                         else
949                                 rc = kfilnd_ep_post_write(tn->tn_ep, tn);
950
951                         switch (rc) {
952                         /* Async tagged RMA event will progress transaction. */
953                         case 0:
954                                 kfilnd_tn_state_change(tn,
955                                                        TN_STATE_WAIT_TAG_RMA_COMP);
956                                 return 0;
957
958                         /* Need to replay TN_EVENT_INIT_TAG_RMA event while in
959                          * the TN_STATE_IMM_RECV state.
960                          */
961                         case -EAGAIN:
962                                 KFILND_TN_DEBUG(tn,
963                                                 "Need to replay tagged %s to %s(%#llx)",
964                                                 tn->sink_buffer ? "read" : "write",
965                                                 libcfs_nid2str(tn->peer->nid),
966                                                 tn->tn_target_addr);
967                                 return -EAGAIN;
968
969                         default:
970                                 KFILND_TN_ERROR(tn,
971                                                 "Failed to post tagged %s to %s(%#llx): rc=%d",
972                                                 tn->sink_buffer ? "read" : "write",
973                                                 libcfs_nid2str(tn->peer->nid),
974                                                 tn->tn_target_addr, rc);
975                                 kfilnd_tn_status_update(tn, rc,
976                                                         LNET_MSG_STATUS_LOCAL_ERROR);
977                         }
978                 } else {
979                         kfilnd_tn_status_update(tn, status,
980                                                 LNET_MSG_STATUS_OK);
981
982                         /* Since the LNet initiator has posted a unique tagged
983                          * buffer specific for this LNet transaction and the
984                          * LNet target has decide not to push/pull to/for the
985                          * LNet initiator tagged buffer, a noop operation is
986                          * done to this tagged buffer (i/e payload transfer size
987                          * is zero). But, immediate data, which contains the
988                          * LNet target status for the transaction, is sent to
989                          * the LNet initiator. Immediate data only appears in
990                          * the completion event at the LNet initiator and not in
991                          * the tagged buffer.
992                          */
993                         tn->tagged_data = cpu_to_be64(abs(tn->tn_status));
994
995                         rc = kfilnd_ep_post_tagged_send(tn->tn_ep, tn);
996                         switch (rc) {
997                         /* Async tagged RMA event will progress transaction. */
998                         case 0:
999                                 kfilnd_tn_state_change(tn,
1000                                                        TN_STATE_WAIT_TAG_COMP);
1001                                 return 0;
1002
1003                         /* Need to replay TN_EVENT_SKIP_TAG_RMA event while in
1004                          * the TN_STATE_IMM_RECV state.
1005                          */
1006                         case -EAGAIN:
1007                                 KFILND_TN_DEBUG(tn,
1008                                                 "Need to replay tagged send to %s(%#llx)",
1009                                                 libcfs_nid2str(tn->peer->nid),
1010                                                 tn->tn_target_addr);
1011                                 return -EAGAIN;
1012
1013                         default:
1014                                 KFILND_TN_ERROR(tn,
1015                                                 "Failed to post tagged send to %s(%#llx): rc=%d",
1016                                                 libcfs_nid2str(tn->peer->nid),
1017                                                 tn->tn_target_addr, rc);
1018                                 kfilnd_tn_status_update(tn, rc,
1019                                                         LNET_MSG_STATUS_LOCAL_ERROR);
1020                         }
1021                 }
1022                 break;
1023
1024         case TN_EVENT_RX_OK:
1025                 finalize = true;
1026                 break;
1027
1028         default:
1029                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
1030                 LBUG();
1031         }
1032
1033         if (kfilnd_tn_has_failed(tn))
1034                 finalize = true;
1035
1036         if (finalize)
1037                 kfilnd_tn_finalize(tn, tn_released);
1038
1039         return rc;
1040 }
1041
1042 static int kfilnd_tn_state_wait_comp(struct kfilnd_transaction *tn,
1043                                      enum tn_events event, int status,
1044                                      bool *tn_released)
1045 {
1046         int rc;
1047         enum lnet_msg_hstatus hstatus;
1048
1049         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
1050                         status);
1051
1052         switch (event) {
1053         case TN_EVENT_TX_OK:
1054                 kfilnd_peer_alive(tn->peer);
1055                 kfilnd_tn_timeout_enable(tn);
1056                 kfilnd_tn_state_change(tn, TN_STATE_WAIT_TAG_COMP);
1057                 break;
1058
1059         case TN_EVENT_TAG_RX_OK:
1060                 kfilnd_tn_state_change(tn, TN_STATE_WAIT_SEND_COMP);
1061                 break;
1062
1063         case TN_EVENT_TX_FAIL:
1064                 if (status == -ETIMEDOUT)
1065                         hstatus = LNET_MSG_STATUS_NETWORK_TIMEOUT;
1066                 else
1067                         hstatus = LNET_MSG_STATUS_REMOTE_ERROR;
1068
1069                 kfilnd_tn_status_update(tn, status, hstatus);
1070                 kfilnd_peer_down(tn->peer);
1071
1072                 /* Need to cancel the tagged receive to prevent resources from
1073                  * being leaked.
1074                  */
1075                 rc = kfilnd_tn_cancel_tag_recv(tn);
1076
1077                 switch (rc) {
1078                 /* Async cancel event will progress transaction. */
1079                 case 0:
1080                         kfilnd_tn_status_update(tn, status,
1081                                                 LNET_MSG_STATUS_LOCAL_ERROR);
1082                         kfilnd_tn_state_change(tn, TN_STATE_FAIL);
1083                         return 0;
1084
1085                 /* Need to replay TN_EVENT_INIT_BULK event while in the
1086                  * TN_STATE_SEND_FAILED state.
1087                  */
1088                 case -EAGAIN:
1089                         KFILND_TN_DEBUG(tn,
1090                                         "Need to replay cancel tagged recv");
1091                         return -EAGAIN;
1092
1093                 default:
1094                         KFILND_TN_ERROR(tn,
1095                                         "Unexpected error during cancel tagged receive: rc=%d",
1096                                         rc);
1097                         LBUG();
1098                 }
1099                 break;
1100
1101         case TN_EVENT_TAG_RX_FAIL:
1102                 kfilnd_tn_status_update(tn, status,
1103                                         LNET_MSG_STATUS_LOCAL_ERROR);
1104                 kfilnd_tn_state_change(tn, TN_STATE_FAIL);
1105                 break;
1106
1107         default:
1108                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
1109                 LBUG();
1110         }
1111
1112         return 0;
1113 }
1114
1115 static int kfilnd_tn_state_wait_send_comp(struct kfilnd_transaction *tn,
1116                                           enum tn_events event, int status,
1117                                           bool *tn_released)
1118 {
1119         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
1120                         status);
1121
1122         if (event == TN_EVENT_TX_OK) {
1123                 kfilnd_peer_alive(tn->peer);
1124                 kfilnd_tn_finalize(tn, tn_released);
1125         } else {
1126                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
1127                 LBUG();
1128         }
1129
1130         return 0;
1131 }
1132
1133 static int kfilnd_tn_state_wait_tag_rma_comp(struct kfilnd_transaction *tn,
1134                                              enum tn_events event, int status,
1135                                              bool *tn_released)
1136 {
1137         enum lnet_msg_hstatus hstatus;
1138
1139         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
1140                         status);
1141
1142         switch (event) {
1143         case TN_EVENT_TAG_TX_OK:
1144                 kfilnd_peer_alive(tn->peer);
1145                 break;
1146
1147         case TN_EVENT_TAG_TX_FAIL:
1148                 if (status == -ETIMEDOUT)
1149                         hstatus = LNET_MSG_STATUS_NETWORK_TIMEOUT;
1150                 else
1151                         hstatus = LNET_MSG_STATUS_REMOTE_ERROR;
1152
1153                 kfilnd_tn_status_update(tn, status, hstatus);
1154                 kfilnd_peer_down(tn->peer);
1155                 break;
1156
1157         default:
1158                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
1159                 LBUG();
1160         }
1161
1162         kfilnd_tn_finalize(tn, tn_released);
1163
1164         return 0;
1165 }
1166
1167 static int kfilnd_tn_state_wait_tag_comp(struct kfilnd_transaction *tn,
1168                                          enum tn_events event, int status,
1169                                          bool *tn_released)
1170 {
1171         int rc;
1172         enum lnet_msg_hstatus hstatus;
1173
1174         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
1175                         status);
1176
1177         switch (event) {
1178         case TN_EVENT_TAG_RX_FAIL:
1179         case TN_EVENT_TAG_RX_OK:
1180                 /* Status can be set for both TN_EVENT_TAG_RX_FAIL and
1181                  * TN_EVENT_TAG_RX_OK. For TN_EVENT_TAG_RX_OK, if status is set,
1182                  * LNet target returned -ENODATA.
1183                  */
1184                 if (status) {
1185                         if (event == TN_EVENT_TAG_RX_FAIL)
1186                                 kfilnd_tn_status_update(tn, status,
1187                                                         LNET_MSG_STATUS_LOCAL_ERROR);
1188                         else
1189                                 kfilnd_tn_status_update(tn, status,
1190                                                         LNET_MSG_STATUS_OK);
1191                 }
1192
1193                 if (!kfilnd_tn_timeout_cancel(tn)) {
1194                         kfilnd_tn_state_change(tn, TN_STATE_WAIT_TIMEOUT_COMP);
1195                         return 0;
1196                 }
1197                 break;
1198
1199         case TN_EVENT_TIMEOUT:
1200                 /* Need to cancel the tagged receive to prevent resources from
1201                  * being leaked.
1202                  */
1203                 rc = kfilnd_tn_cancel_tag_recv(tn);
1204
1205                 switch (rc) {
1206                 /* Async cancel event will progress transaction. */
1207                 case 0:
1208                         kfilnd_tn_state_change(tn,
1209                                                TN_STATE_WAIT_TIMEOUT_TAG_COMP);
1210                         return 0;
1211
1212                 /* Need to replay TN_EVENT_INIT_BULK event while in the
1213                  * TN_STATE_WAIT_TAG_COMP state.
1214                  */
1215                 case -EAGAIN:
1216                         KFILND_TN_DEBUG(tn,
1217                                         "Need to replay cancel tagged recv");
1218                         return -EAGAIN;
1219
1220                 default:
1221                         KFILND_TN_ERROR(tn,
1222                                         "Unexpected error during cancel tagged receive: rc=%d",
1223                                         rc);
1224                         LBUG();
1225                 }
1226                 break;
1227
1228         case TN_EVENT_TAG_TX_FAIL:
1229                 if (status == -ETIMEDOUT)
1230                         hstatus = LNET_MSG_STATUS_NETWORK_TIMEOUT;
1231                 else
1232                         hstatus = LNET_MSG_STATUS_REMOTE_ERROR;
1233
1234                 kfilnd_tn_status_update(tn, status, hstatus);
1235                 kfilnd_peer_down(tn->peer);
1236                 break;
1237
1238         case TN_EVENT_TAG_TX_OK:
1239                 kfilnd_peer_alive(tn->peer);
1240                 break;
1241
1242         default:
1243                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
1244                 LBUG();
1245         }
1246
1247         kfilnd_tn_finalize(tn, tn_released);
1248
1249         return 0;
1250 }
1251
1252 static int kfilnd_tn_state_fail(struct kfilnd_transaction *tn,
1253                                 enum tn_events event, int status,
1254                                 bool *tn_released)
1255 {
1256         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
1257                         status);
1258
1259         switch (event) {
1260         case TN_EVENT_TX_FAIL:
1261                 kfilnd_peer_down(tn->peer);
1262                 break;
1263
1264         case TN_EVENT_TX_OK:
1265                 kfilnd_peer_alive(tn->peer);
1266                 break;
1267
1268         case TN_EVENT_TAG_RX_FAIL:
1269         case TN_EVENT_TAG_RX_CANCEL:
1270                 break;
1271
1272         default:
1273                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
1274                 LBUG();
1275         }
1276
1277         kfilnd_tn_finalize(tn, tn_released);
1278
1279         return 0;
1280 }
1281
1282 static int kfilnd_tn_state_wait_timeout_tag_comp(struct kfilnd_transaction *tn,
1283                                                  enum tn_events event,
1284                                                  int status, bool *tn_released)
1285 {
1286         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
1287                         status);
1288
1289         switch (event) {
1290         case TN_EVENT_TAG_RX_CANCEL:
1291                 kfilnd_tn_status_update(tn, -ETIMEDOUT,
1292                                         LNET_MSG_STATUS_REMOTE_TIMEOUT);
1293                 kfilnd_peer_down(tn->peer);
1294                 break;
1295
1296         case TN_EVENT_TAG_RX_FAIL:
1297                 kfilnd_tn_status_update(tn, status,
1298                                         LNET_MSG_STATUS_LOCAL_ERROR);
1299                 break;
1300
1301         case TN_EVENT_TAG_RX_OK:
1302                 break;
1303
1304         default:
1305                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
1306                 LBUG();
1307         }
1308
1309         kfilnd_tn_finalize(tn, tn_released);
1310
1311         return 0;
1312 }
1313
1314 static int kfilnd_tn_state_wait_timeout_comp(struct kfilnd_transaction *tn,
1315                                              enum tn_events event, int status,
1316                                              bool *tn_released)
1317 {
1318         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
1319                         status);
1320
1321         if (event == TN_EVENT_TIMEOUT) {
1322                 kfilnd_tn_finalize(tn, tn_released);
1323         } else {
1324                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
1325                 LBUG();
1326         }
1327
1328         return 0;
1329 }
1330
1331 static int
1332 (* const kfilnd_tn_state_dispatch_table[TN_STATE_MAX])(struct kfilnd_transaction *tn,
1333                                                        enum tn_events event,
1334                                                        int status,
1335                                                        bool *tn_released) = {
1336         [TN_STATE_IDLE] = kfilnd_tn_state_idle,
1337         [TN_STATE_WAIT_TAG_COMP] = kfilnd_tn_state_wait_tag_comp,
1338         [TN_STATE_IMM_SEND] = kfilnd_tn_state_imm_send,
1339         [TN_STATE_TAGGED_RECV_POSTED] = kfilnd_tn_state_tagged_recv_posted,
1340         [TN_STATE_SEND_FAILED] = kfilnd_tn_state_send_failed,
1341         [TN_STATE_WAIT_COMP] = kfilnd_tn_state_wait_comp,
1342         [TN_STATE_WAIT_TIMEOUT_COMP] = kfilnd_tn_state_wait_timeout_comp,
1343         [TN_STATE_WAIT_SEND_COMP] = kfilnd_tn_state_wait_send_comp,
1344         [TN_STATE_WAIT_TIMEOUT_TAG_COMP] =
1345                 kfilnd_tn_state_wait_timeout_tag_comp,
1346         [TN_STATE_FAIL] = kfilnd_tn_state_fail,
1347         [TN_STATE_IMM_RECV] = kfilnd_tn_state_imm_recv,
1348         [TN_STATE_WAIT_TAG_RMA_COMP] = kfilnd_tn_state_wait_tag_rma_comp,
1349 };
1350
1351 /**
1352  * kfilnd_tn_event_handler() - Update transaction state machine with an event.
1353  * @tn: Transaction to be updated.
1354  * @event: Transaction event.
1355  * @status: Errno status associated with the event.
1356  *
1357  * When the transaction event handler is first called on a new transaction, the
1358  * transaction is now own by the transaction system. This means that will be
1359  * freed by the system as the transaction is progressed through the state
1360  * machine.
1361  */
1362 void kfilnd_tn_event_handler(struct kfilnd_transaction *tn,
1363                              enum tn_events event, int status)
1364 {
1365         bool tn_released = false;
1366         int rc;
1367
1368         if (!tn)
1369                 return;
1370
1371         mutex_lock(&tn->tn_lock);
1372         rc = kfilnd_tn_state_dispatch_table[tn->tn_state](tn, event, status,
1373                                                           &tn_released);
1374         if (rc == -EAGAIN) {
1375                 tn->replay_event = event;
1376                 tn->replay_status = status;
1377                 kfilnd_ep_queue_tn_replay(tn->tn_ep, tn);
1378         }
1379
1380         if (!tn_released)
1381                 mutex_unlock(&tn->tn_lock);
1382 }
1383
1384 /**
1385  * kfilnd_tn_free() - Free a transaction.
1386  */
1387 void kfilnd_tn_free(struct kfilnd_transaction *tn)
1388 {
1389         spin_lock(&tn->tn_ep->tn_list_lock);
1390         list_del(&tn->tn_entry);
1391         spin_unlock(&tn->tn_ep->tn_list_lock);
1392
1393         KFILND_TN_DEBUG(tn, "Transaction freed");
1394
1395         if (tn->tn_mr_key)
1396                 kfilnd_ep_put_key(tn->tn_ep, tn->tn_mr_key);
1397
1398         /* Free send message buffer if needed. */
1399         if (tn->tn_tx_msg.msg)
1400                 kmem_cache_free(imm_buf_cache, tn->tn_tx_msg.msg);
1401
1402         kmem_cache_free(tn_cache, tn);
1403 }
1404
1405 /**
1406  * kfilnd_tn_alloc() - Allocate a new KFI LND transaction.
1407  * @dev: KFI LND device used to look the KFI LND endpoint to associate with the
1408  * transaction.
1409  * @cpt: CPT of the transaction.
1410  * @target_nid: Target NID of the transaction.
1411  * @alloc_msg: Allocate an immediate message for the transaction.
1412  * @is_initiator: Is initiator of LNet transaction.
1413  * @key: Is transaction memory region key need.
1414  *
1415  * During transaction allocation, each transaction is associated with a KFI LND
1416  * endpoint use to post data transfer operations. The CPT argument is used to
1417  * lookup the KFI LND endpoint within the KFI LND device.
1418  *
1419  * Return: On success, valid pointer. Else, negative errno pointer.
1420  */
1421 struct kfilnd_transaction *kfilnd_tn_alloc(struct kfilnd_dev *dev, int cpt,
1422                                            lnet_nid_t target_nid,
1423                                            bool alloc_msg, bool is_initiator,
1424                                            bool key)
1425 {
1426         struct kfilnd_transaction *tn;
1427         struct kfilnd_ep *ep;
1428         int rc;
1429         ktime_t tn_alloc_ts;
1430
1431         if (!dev) {
1432                 rc = -EINVAL;
1433                 goto err;
1434         }
1435
1436         tn_alloc_ts = ktime_get();
1437
1438         /* If the CPT does not fall into the LNet NI CPT range, force the CPT
1439          * into the LNet NI CPT range. This should never happen.
1440          */
1441         ep = dev->cpt_to_endpoint[cpt];
1442         if (!ep) {
1443                 CWARN("%s used invalid cpt=%d\n",
1444                       libcfs_nidstr(&dev->kfd_ni->ni_nid), cpt);
1445                 ep = dev->kfd_endpoints[0];
1446         }
1447
1448         tn = kmem_cache_zalloc(tn_cache, GFP_KERNEL);
1449         if (!tn) {
1450                 rc = -ENOMEM;
1451                 goto err;
1452         }
1453
1454         if (alloc_msg) {
1455                 tn->tn_tx_msg.msg = kmem_cache_alloc(imm_buf_cache, GFP_KERNEL);
1456                 if (!tn->tn_tx_msg.msg) {
1457                         rc = -ENOMEM;
1458                         goto err_free_tn;
1459                 }
1460         }
1461
1462         if (key) {
1463                 rc = kfilnd_ep_get_key(ep);
1464                 if (rc < 0)
1465                         goto err_free_tn;
1466                 tn->tn_mr_key = rc;
1467         }
1468
1469         tn->peer = kfilnd_peer_get(dev, target_nid);
1470         if (IS_ERR(tn->peer)) {
1471                 rc = PTR_ERR(tn->peer);
1472                 goto err_put_mr_key;
1473         }
1474
1475         mutex_init(&tn->tn_lock);
1476         tn->tn_ep = ep;
1477         tn->tn_response_rx = ep->end_context_id;
1478         tn->tn_state = TN_STATE_IDLE;
1479         tn->hstatus = LNET_MSG_STATUS_OK;
1480         tn->deadline = ktime_get_seconds() + lnet_get_lnd_timeout();
1481         tn->is_initiator = is_initiator;
1482         INIT_WORK(&tn->timeout_work, kfilnd_tn_timeout_work);
1483
1484         /* Add the transaction to an endpoint.  This is like
1485          * incrementing a ref counter.
1486          */
1487         spin_lock(&ep->tn_list_lock);
1488         list_add_tail(&tn->tn_entry, &ep->tn_list);
1489         spin_unlock(&ep->tn_list_lock);
1490
1491         tn->tn_alloc_ts = tn_alloc_ts;
1492         tn->tn_state_ts = ktime_get();
1493
1494         KFILND_EP_DEBUG(ep, "Transaction ID %u allocated", tn->tn_mr_key);
1495
1496         return tn;
1497
1498 err_put_mr_key:
1499         if (key)
1500                 kfilnd_ep_put_key(ep, tn->tn_mr_key);
1501 err_free_tn:
1502         if (tn->tn_tx_msg.msg)
1503                 kmem_cache_free(imm_buf_cache, tn->tn_tx_msg.msg);
1504         kmem_cache_free(tn_cache, tn);
1505 err:
1506         return ERR_PTR(rc);
1507 }
1508
1509 /**
1510  * kfilnd_tn_cleanup() - Cleanup KFI LND transaction system.
1511  *
1512  * This function should only be called when there are no outstanding
1513  * transactions.
1514  */
1515 void kfilnd_tn_cleanup(void)
1516 {
1517         kmem_cache_destroy(imm_buf_cache);
1518         kmem_cache_destroy(tn_cache);
1519 }
1520
1521 /**
1522  * kfilnd_tn_init() - Initialize KFI LND transaction system.
1523  *
1524  * Return: On success, zero. Else, negative errno.
1525  */
1526 int kfilnd_tn_init(void)
1527 {
1528         tn_cache = kmem_cache_create("kfilnd_tn",
1529                                      sizeof(struct kfilnd_transaction), 0,
1530                                      SLAB_HWCACHE_ALIGN, NULL);
1531         if (!tn_cache)
1532                 goto err;
1533
1534         imm_buf_cache = kmem_cache_create("kfilnd_imm_buf",
1535                                           KFILND_IMMEDIATE_MSG_SIZE, 0,
1536                                           SLAB_HWCACHE_ALIGN, NULL);
1537         if (!imm_buf_cache)
1538                 goto err_tn_cache_destroy;
1539
1540         return 0;
1541
1542 err_tn_cache_destroy:
1543         kmem_cache_destroy(tn_cache);
1544 err:
1545         return -ENOMEM;
1546 }
1547
1548 /**
1549  * kfilnd_tn_set_kiov_buf() - Set the buffer used for a transaction.
1550  * @tn: Transaction to have buffer set.
1551  * @kiov: LNet KIOV buffer.
1552  * @num_iov: Number of IOVs.
1553  * @offset: Offset into IOVs where the buffer starts.
1554  * @len: Length of the buffer.
1555  *
1556  * This function takes the user provided IOV, offset, and len, and sets the
1557  * transaction buffer. The user provided IOV is an LNet KIOV. When the
1558  * transaction buffer is configured, the user provided offset is applied
1559  * when the transaction buffer is configured (i.e. the transaction buffer
1560  * offset is zero).
1561  */
1562 int kfilnd_tn_set_kiov_buf(struct kfilnd_transaction *tn,
1563                            struct bio_vec *kiov, size_t num_iov,
1564                            size_t offset, size_t len)
1565 {
1566         size_t i;
1567         size_t cur_len = 0;
1568         size_t cur_offset = offset;
1569         size_t cur_iov = 0;
1570         size_t tmp_len;
1571         size_t tmp_offset;
1572
1573         for (i = 0; (i < num_iov) && (cur_len < len); i++) {
1574                 /* Skip KIOVs until a KIOV with a length less than the current
1575                  * offset is found.
1576                  */
1577                 if (kiov[i].bv_len <= cur_offset) {
1578                         cur_offset -= kiov[i].bv_len;
1579                         continue;
1580                 }
1581
1582                 tmp_len = kiov[i].bv_len - cur_offset;
1583                 tmp_offset = kiov[i].bv_len - tmp_len + kiov[i].bv_offset;
1584
1585                 if (tmp_len + cur_len > len)
1586                         tmp_len = len - cur_len;
1587
1588                 /* tn_kiov is an array of size LNET_MAX_IOV */
1589                 if (cur_iov >= LNET_MAX_IOV)
1590                         return -EINVAL;
1591
1592                 tn->tn_kiov[cur_iov].bv_page = kiov[i].bv_page;
1593                 tn->tn_kiov[cur_iov].bv_len = tmp_len;
1594                 tn->tn_kiov[cur_iov].bv_offset = tmp_offset;
1595
1596                 cur_iov++;
1597                 cur_len += tmp_len;
1598                 cur_offset = 0;
1599         }
1600
1601         tn->tn_num_iovec = cur_iov;
1602         tn->tn_nob = cur_len;
1603
1604         return 0;
1605 }