Whamcloud - gitweb
LU-16451 kfilnd: Throttle traffic to down peers
[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->tn_kp);
73         msg->proto.hello.session_key = tn->tn_kp->kp_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->tn_kp->kp_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->tn_kp->kp_version;
102         msg->proto.hello.rx_base = kfilnd_peer_target_rx_base(tn->tn_kp);
103         msg->proto.hello.session_key = tn->tn_kp->kp_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->tn_kp->kp_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->tn_kp->kp_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->tn_kp->kp_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->tn_kp);
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->tn_kp);
562                 KFILND_TN_DEBUG(tn, "Using peer %s(%#llx)",
563                                 libcfs_nid2str(tn->tn_kp->kp_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->tn_kp->kp_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->tn_kp->kp_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         struct lnet_hdr hdr;
618         struct lnet_nid srcnid;
619
620         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
621                         status);
622
623         /* For new peers, send a hello request message and queue the true LNet
624          * message for replay.
625          */
626         if (kfilnd_peer_needs_throttle(tn->tn_kp) &&
627             (event == TN_EVENT_INIT_IMMEDIATE || event == TN_EVENT_INIT_BULK)) {
628                 if (kfilnd_peer_deleted(tn->tn_kp)) {
629                         /* We'll assign a NETWORK_TIMEOUT message health status
630                          * below because we don't know why this peer was marked
631                          * for removal
632                          */
633                         rc = -ESTALE;
634                         KFILND_TN_DEBUG(tn, "Drop message to deleted peer");
635                 } else if (kfilnd_peer_needs_hello(tn->tn_kp, false)) {
636                         /* We're throttling transactions to this peer until
637                          * a handshake can be completed, but there is no HELLO
638                          * currently in flight. This implies the HELLO has
639                          * failed, and we should cancel this TN. Otherwise we
640                          * are stuck waiting for the TN deadline.
641                          *
642                          * We assign NETWORK_TIMEOUT health status below because
643                          * we do not know why the HELLO failed.
644                          */
645                         rc = -ECANCELED;
646                         KFILND_TN_DEBUG(tn, "Cancel throttled TN");
647                 } else if (ktime_after(tn->deadline, ktime_get_seconds())) {
648                         /* If transaction deadline has not been met, return
649                          * -EAGAIN. This will cause this transaction event to be
650                          * replayed. During this time, an async message from the
651                          * peer should occur at which point the kfilnd version
652                          * should be negotiated.
653                          */
654                         KFILND_TN_DEBUG(tn, "hello response pending");
655                         return -EAGAIN;
656                 } else {
657                         rc = -ETIMEDOUT;
658                 }
659
660                 kfilnd_tn_status_update(tn, rc,
661                                         LNET_MSG_STATUS_NETWORK_TIMEOUT);
662                 rc = 0;
663                 goto out;
664         }
665
666         switch (event) {
667         case TN_EVENT_INIT_IMMEDIATE:
668         case TN_EVENT_TX_HELLO:
669                 tn->tn_target_addr = kfilnd_peer_get_kfi_addr(tn->tn_kp);
670                 KFILND_TN_DEBUG(tn, "Using peer %s(%#llx)",
671                                 libcfs_nid2str(tn->tn_kp->kp_nid),
672                                 tn->tn_target_addr);
673
674                 if (event == TN_EVENT_INIT_IMMEDIATE)
675                         kfilnd_tn_pack_immed_msg(tn);
676                 else
677                         kfilnd_tn_pack_hello_req(tn);
678
679                 /* Send immediate message. */
680                 rc = kfilnd_ep_post_send(tn->tn_ep, tn);
681                 switch (rc) {
682                 /* Async event will progress immediate send. */
683                 case 0:
684                         kfilnd_tn_state_change(tn, TN_STATE_IMM_SEND);
685                         return 0;
686
687                 /* Need to TN_EVENT_INIT_IMMEDIATE event while in TN_STATE_IDLE
688                  * state.
689                  */
690                 case -EAGAIN:
691                         KFILND_TN_DEBUG(tn, "Need to replay send to %s(%#llx)",
692                                         libcfs_nid2str(tn->tn_kp->kp_nid),
693                                         tn->tn_target_addr);
694                         return -EAGAIN;
695
696                 default:
697                         KFILND_TN_ERROR(tn,
698                                         "Failed to post send to %s(%#llx): rc=%d",
699                                         libcfs_nid2str(tn->tn_kp->kp_nid),
700                                         tn->tn_target_addr, rc);
701                         if (event == TN_EVENT_TX_HELLO)
702                                 kfilnd_peer_clear_hello_pending(tn->tn_kp);
703                         kfilnd_tn_status_update(tn, rc,
704                                                 LNET_MSG_STATUS_LOCAL_ERROR);
705                 }
706                 break;
707
708         case TN_EVENT_INIT_BULK:
709                 /* Post tagged receive buffer used to land bulk response. */
710                 rc = kfilnd_ep_post_tagged_recv(tn->tn_ep, tn);
711
712                 switch (rc) {
713                 /* Transition to TN_STATE_TAGGED_RECV_POSTED on success. */
714                 case 0:
715                         kfilnd_tn_state_change(tn, TN_STATE_TAGGED_RECV_POSTED);
716
717                         /* Propogate TN_EVENT_INIT_BULK event to
718                          * TN_STATE_TAGGED_RECV_POSTED handler.
719                          */
720                         return kfilnd_tn_state_tagged_recv_posted(tn, event,
721                                                                   rc,
722                                                                   tn_released);
723
724                 /* Need to replay TN_EVENT_INIT_BULK event in the TN_STATE_IDLE
725                  * state.
726                  */
727                 case -EAGAIN:
728                         KFILND_TN_DEBUG(tn, "Need to replay tagged recv");
729                         return -EAGAIN;
730
731                 default:
732                         KFILND_TN_ERROR(tn, "Failed to post tagged recv %d",
733                                         rc);
734                         kfilnd_tn_status_update(tn, rc,
735                                                 LNET_MSG_STATUS_LOCAL_ERROR);
736                 }
737                 break;
738
739         case TN_EVENT_RX_OK:
740                 if (kfilnd_peer_needs_hello(tn->tn_kp, false)) {
741                         rc = kfilnd_send_hello_request(tn->tn_ep->end_dev,
742                                                        tn->tn_ep->end_cpt,
743                                                        tn->tn_kp);
744                         if (rc)
745                                 KFILND_TN_ERROR(tn,
746                                                 "Failed to send hello request: rc=%d",
747                                                 rc);
748                         rc = 0;
749                 }
750
751                 /* If this is a new peer then we cannot progress the transaction
752                  * and must drop it
753                  */
754                 if (kfilnd_peer_is_new_peer(tn->tn_kp)) {
755                         KFILND_TN_ERROR(tn,
756                                         "Dropping message from %s due to stale peer",
757                                         libcfs_nid2str(tn->tn_kp->kp_nid));
758                         kfilnd_tn_status_update(tn, -EPROTO,
759                                                 LNET_MSG_STATUS_LOCAL_DROPPED);
760                         rc = 0;
761                         goto out;
762                 }
763
764                 LASSERT(kfilnd_peer_is_new_peer(tn->tn_kp) == false);
765                 msg = tn->tn_rx_msg.msg;
766
767                 /* Update the NID address with the new preferred RX context. */
768                 kfilnd_peer_alive(tn->tn_kp);
769
770                 /* Pass message up to LNet
771                  * The TN will be reused in this call chain so we need to
772                  * release the lock on the TN before proceeding.
773                  */
774                 KFILND_TN_DEBUG(tn, "%s -> TN_STATE_IMM_RECV state change",
775                                 tn_state_to_str(tn->tn_state));
776
777                 /* TODO: Do not manually update this state change. */
778                 tn->tn_state = TN_STATE_IMM_RECV;
779                 mutex_unlock(&tn->tn_lock);
780                 *tn_released = true;
781                 lnet_nid4_to_nid(msg->srcnid, &srcnid);
782                 if (msg->type == KFILND_MSG_IMMEDIATE) {
783                         lnet_hdr_from_nid4(&hdr, &msg->proto.immed.hdr);
784                         rc = lnet_parse(tn->tn_ep->end_dev->kfd_ni,
785                                         &hdr, &srcnid, tn, 0);
786                 } else {
787                         lnet_hdr_from_nid4(&hdr, &msg->proto.bulk_req.hdr);
788                         rc = lnet_parse(tn->tn_ep->end_dev->kfd_ni,
789                                         &hdr, &srcnid, tn, 1);
790                 }
791
792                 /* If successful, transaction has been accepted by LNet and we
793                  * cannot process the transaction anymore within this context.
794                  */
795                 if (!rc)
796                         return 0;
797
798                 KFILND_TN_ERROR(tn, "Failed to parse LNet message: rc=%d", rc);
799                 kfilnd_tn_status_update(tn, rc, LNET_MSG_STATUS_LOCAL_ERROR);
800                 break;
801
802         case TN_EVENT_RX_HELLO:
803                 msg = tn->tn_rx_msg.msg;
804
805                 kfilnd_peer_alive(tn->tn_kp);
806
807                 switch (msg->type) {
808                 case KFILND_MSG_HELLO_REQ:
809                         kfilnd_peer_process_hello(tn->tn_kp, msg);
810                         tn->tn_target_addr = kfilnd_peer_get_kfi_addr(tn->tn_kp);
811                         KFILND_TN_DEBUG(tn, "Using peer %s(%#llx)",
812                                         libcfs_nid2str(tn->tn_kp->kp_nid),
813                                         tn->tn_target_addr);
814
815                         kfilnd_tn_pack_hello_rsp(tn);
816
817                         /* Send immediate message. */
818                         rc = kfilnd_ep_post_send(tn->tn_ep, tn);
819                         switch (rc) {
820                         case 0:
821                                 kfilnd_tn_state_change(tn, TN_STATE_IMM_SEND);
822                                 return 0;
823
824                         case -EAGAIN:
825                                 KFILND_TN_DEBUG(tn, "Need to replay send to %s(%#llx)",
826                                                 libcfs_nid2str(tn->tn_kp->kp_nid),
827                                                 tn->tn_target_addr);
828                                 return -EAGAIN;
829
830                         default:
831                                 KFILND_TN_ERROR(tn,
832                                                 "Failed to post send to %s(%#llx): rc=%d",
833                                                 libcfs_nid2str(tn->tn_kp->kp_nid),
834                                                 tn->tn_target_addr, rc);
835                                 kfilnd_tn_status_update(tn, rc,
836                                                         LNET_MSG_STATUS_LOCAL_ERROR);
837                         }
838                         break;
839
840                 case KFILND_MSG_HELLO_RSP:
841                         rc = 0;
842                         kfilnd_peer_process_hello(tn->tn_kp, msg);
843                         finalize = true;
844                         break;
845
846                 default:
847                         KFILND_TN_ERROR(tn, "Invalid message type: %s",
848                                         msg_type_to_str(msg->type));
849                         LBUG();
850                 }
851                 break;
852
853         default:
854                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
855                 LBUG();
856         }
857
858 out:
859         if (kfilnd_tn_has_failed(tn))
860                 finalize = true;
861
862         if (finalize)
863                 kfilnd_tn_finalize(tn, tn_released);
864
865         return rc;
866 }
867
868 static int kfilnd_tn_state_imm_send(struct kfilnd_transaction *tn,
869                                     enum tn_events event, int status,
870                                     bool *tn_released)
871 {
872         enum lnet_msg_hstatus hstatus;
873
874         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
875                         status);
876
877         switch (event) {
878         case TN_EVENT_TX_FAIL:
879                 if (status == -ETIMEDOUT || status == -EIO)
880                         hstatus = LNET_MSG_STATUS_NETWORK_TIMEOUT;
881                 else
882                         hstatus = LNET_MSG_STATUS_REMOTE_ERROR;
883
884                 kfilnd_tn_status_update(tn, status, hstatus);
885                 kfilnd_peer_tn_failed(tn->tn_kp, status);
886                 if (tn->msg_type == KFILND_MSG_HELLO_REQ)
887                         kfilnd_peer_clear_hello_pending(tn->tn_kp);
888                 break;
889
890         case TN_EVENT_TX_OK:
891                 kfilnd_peer_alive(tn->tn_kp);
892                 break;
893
894         default:
895                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
896                 LBUG();
897         }
898
899         kfilnd_tn_finalize(tn, tn_released);
900
901         return 0;
902 }
903
904 static int kfilnd_tn_state_imm_recv(struct kfilnd_transaction *tn,
905                                     enum tn_events event, int status,
906                                     bool *tn_released)
907 {
908         int rc = 0;
909         bool finalize = false;
910
911         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
912                         status);
913
914         switch (event) {
915         case TN_EVENT_INIT_TAG_RMA:
916         case TN_EVENT_SKIP_TAG_RMA:
917                 /* Release the buffer we received the request on. All relevant
918                  * information to perform the RMA operation is stored in the
919                  * transaction structure. This should be done before the RMA
920                  * operation to prevent two contexts from potentially processing
921                  * the same transaction.
922                  *
923                  * TODO: Prevent this from returning -EAGAIN.
924                  */
925                 if (tn->tn_posted_buf) {
926                         kfilnd_ep_imm_buffer_put(tn->tn_posted_buf);
927                         tn->tn_posted_buf = NULL;
928                 }
929
930                 /* Update the KFI address to use the response RX context. */
931                 tn->tn_target_addr =
932                         kfi_rx_addr(KFILND_BASE_ADDR(tn->tn_kp->kp_addr),
933                                     tn->tn_response_rx, KFILND_FAB_RX_CTX_BITS);
934                 KFILND_TN_DEBUG(tn, "Using peer %s(0x%llx)",
935                                 libcfs_nid2str(tn->tn_kp->kp_nid),
936                                 tn->tn_target_addr);
937
938                 /* Initiate the RMA operation to push/pull the LNet payload or
939                  * send a tagged message to finalize the bulk operation if the
940                  * RMA operation should be skipped.
941                  */
942                 if (event == TN_EVENT_INIT_TAG_RMA) {
943                         if (tn->sink_buffer)
944                                 rc = kfilnd_ep_post_read(tn->tn_ep, tn);
945                         else
946                                 rc = kfilnd_ep_post_write(tn->tn_ep, tn);
947
948                         switch (rc) {
949                         /* Async tagged RMA event will progress transaction. */
950                         case 0:
951                                 kfilnd_tn_state_change(tn,
952                                                        TN_STATE_WAIT_TAG_RMA_COMP);
953                                 return 0;
954
955                         /* Need to replay TN_EVENT_INIT_TAG_RMA event while in
956                          * the TN_STATE_IMM_RECV state.
957                          */
958                         case -EAGAIN:
959                                 KFILND_TN_DEBUG(tn,
960                                                 "Need to replay tagged %s to %s(%#llx)",
961                                                 tn->sink_buffer ? "read" : "write",
962                                                 libcfs_nid2str(tn->tn_kp->kp_nid),
963                                                 tn->tn_target_addr);
964                                 return -EAGAIN;
965
966                         default:
967                                 KFILND_TN_ERROR(tn,
968                                                 "Failed to post tagged %s to %s(%#llx): rc=%d",
969                                                 tn->sink_buffer ? "read" : "write",
970                                                 libcfs_nid2str(tn->tn_kp->kp_nid),
971                                                 tn->tn_target_addr, rc);
972                                 kfilnd_tn_status_update(tn, rc,
973                                                         LNET_MSG_STATUS_LOCAL_ERROR);
974                         }
975                 } else {
976                         kfilnd_tn_status_update(tn, status,
977                                                 LNET_MSG_STATUS_OK);
978
979                         /* Since the LNet initiator has posted a unique tagged
980                          * buffer specific for this LNet transaction and the
981                          * LNet target has decide not to push/pull to/for the
982                          * LNet initiator tagged buffer, a noop operation is
983                          * done to this tagged buffer (i/e payload transfer size
984                          * is zero). But, immediate data, which contains the
985                          * LNet target status for the transaction, is sent to
986                          * the LNet initiator. Immediate data only appears in
987                          * the completion event at the LNet initiator and not in
988                          * the tagged buffer.
989                          */
990                         tn->tagged_data = cpu_to_be64(abs(tn->tn_status));
991
992                         rc = kfilnd_ep_post_tagged_send(tn->tn_ep, tn);
993                         switch (rc) {
994                         /* Async tagged RMA event will progress transaction. */
995                         case 0:
996                                 kfilnd_tn_state_change(tn,
997                                                        TN_STATE_WAIT_TAG_COMP);
998                                 return 0;
999
1000                         /* Need to replay TN_EVENT_SKIP_TAG_RMA event while in
1001                          * the TN_STATE_IMM_RECV state.
1002                          */
1003                         case -EAGAIN:
1004                                 KFILND_TN_DEBUG(tn,
1005                                                 "Need to replay tagged send to %s(%#llx)",
1006                                                 libcfs_nid2str(tn->tn_kp->kp_nid),
1007                                                 tn->tn_target_addr);
1008                                 return -EAGAIN;
1009
1010                         default:
1011                                 KFILND_TN_ERROR(tn,
1012                                                 "Failed to post tagged send to %s(%#llx): rc=%d",
1013                                                 libcfs_nid2str(tn->tn_kp->kp_nid),
1014                                                 tn->tn_target_addr, rc);
1015                                 kfilnd_tn_status_update(tn, rc,
1016                                                         LNET_MSG_STATUS_LOCAL_ERROR);
1017                         }
1018                 }
1019                 break;
1020
1021         case TN_EVENT_RX_OK:
1022                 finalize = true;
1023                 break;
1024
1025         default:
1026                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
1027                 LBUG();
1028         }
1029
1030         if (kfilnd_tn_has_failed(tn))
1031                 finalize = true;
1032
1033         if (finalize)
1034                 kfilnd_tn_finalize(tn, tn_released);
1035
1036         return rc;
1037 }
1038
1039 static int kfilnd_tn_state_wait_comp(struct kfilnd_transaction *tn,
1040                                      enum tn_events event, int status,
1041                                      bool *tn_released)
1042 {
1043         int rc;
1044         enum lnet_msg_hstatus hstatus;
1045
1046         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
1047                         status);
1048
1049         switch (event) {
1050         case TN_EVENT_TX_OK:
1051                 kfilnd_peer_alive(tn->tn_kp);
1052                 kfilnd_tn_timeout_enable(tn);
1053                 kfilnd_tn_state_change(tn, TN_STATE_WAIT_TAG_COMP);
1054                 break;
1055
1056         case TN_EVENT_TAG_RX_OK:
1057                 kfilnd_tn_state_change(tn, TN_STATE_WAIT_SEND_COMP);
1058                 break;
1059
1060         case TN_EVENT_TX_FAIL:
1061                 if (status == -ETIMEDOUT)
1062                         hstatus = LNET_MSG_STATUS_NETWORK_TIMEOUT;
1063                 else
1064                         hstatus = LNET_MSG_STATUS_REMOTE_ERROR;
1065
1066                 kfilnd_tn_status_update(tn, status, hstatus);
1067                 kfilnd_peer_tn_failed(tn->tn_kp, status);
1068
1069                 /* Need to cancel the tagged receive to prevent resources from
1070                  * being leaked.
1071                  */
1072                 rc = kfilnd_tn_cancel_tag_recv(tn);
1073
1074                 switch (rc) {
1075                 /* Async cancel event will progress transaction. */
1076                 case 0:
1077                         kfilnd_tn_status_update(tn, status,
1078                                                 LNET_MSG_STATUS_LOCAL_ERROR);
1079                         kfilnd_tn_state_change(tn, TN_STATE_FAIL);
1080                         return 0;
1081
1082                 /* Need to replay TN_EVENT_INIT_BULK event while in the
1083                  * TN_STATE_SEND_FAILED state.
1084                  */
1085                 case -EAGAIN:
1086                         KFILND_TN_DEBUG(tn,
1087                                         "Need to replay cancel tagged recv");
1088                         return -EAGAIN;
1089
1090                 default:
1091                         KFILND_TN_ERROR(tn,
1092                                         "Unexpected error during cancel tagged receive: rc=%d",
1093                                         rc);
1094                         LBUG();
1095                 }
1096                 break;
1097
1098         case TN_EVENT_TAG_RX_FAIL:
1099                 kfilnd_tn_status_update(tn, status,
1100                                         LNET_MSG_STATUS_LOCAL_ERROR);
1101                 kfilnd_tn_state_change(tn, TN_STATE_FAIL);
1102                 break;
1103
1104         default:
1105                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
1106                 LBUG();
1107         }
1108
1109         return 0;
1110 }
1111
1112 static int kfilnd_tn_state_wait_send_comp(struct kfilnd_transaction *tn,
1113                                           enum tn_events event, int status,
1114                                           bool *tn_released)
1115 {
1116         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
1117                         status);
1118
1119         if (event == TN_EVENT_TX_OK) {
1120                 kfilnd_peer_alive(tn->tn_kp);
1121                 kfilnd_tn_finalize(tn, tn_released);
1122         } else {
1123                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
1124                 LBUG();
1125         }
1126
1127         return 0;
1128 }
1129
1130 static int kfilnd_tn_state_wait_tag_rma_comp(struct kfilnd_transaction *tn,
1131                                              enum tn_events event, int status,
1132                                              bool *tn_released)
1133 {
1134         enum lnet_msg_hstatus hstatus;
1135
1136         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
1137                         status);
1138
1139         switch (event) {
1140         case TN_EVENT_TAG_TX_OK:
1141                 kfilnd_peer_alive(tn->tn_kp);
1142                 break;
1143
1144         case TN_EVENT_TAG_TX_FAIL:
1145                 if (status == -ETIMEDOUT)
1146                         hstatus = LNET_MSG_STATUS_NETWORK_TIMEOUT;
1147                 else
1148                         hstatus = LNET_MSG_STATUS_REMOTE_ERROR;
1149
1150                 kfilnd_tn_status_update(tn, status, hstatus);
1151                 kfilnd_peer_tn_failed(tn->tn_kp, status);
1152                 break;
1153
1154         default:
1155                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
1156                 LBUG();
1157         }
1158
1159         kfilnd_tn_finalize(tn, tn_released);
1160
1161         return 0;
1162 }
1163
1164 static int kfilnd_tn_state_wait_tag_comp(struct kfilnd_transaction *tn,
1165                                          enum tn_events event, int status,
1166                                          bool *tn_released)
1167 {
1168         int rc;
1169         enum lnet_msg_hstatus hstatus;
1170
1171         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
1172                         status);
1173
1174         switch (event) {
1175         case TN_EVENT_TAG_RX_FAIL:
1176         case TN_EVENT_TAG_RX_OK:
1177                 /* Status can be set for both TN_EVENT_TAG_RX_FAIL and
1178                  * TN_EVENT_TAG_RX_OK. For TN_EVENT_TAG_RX_OK, if status is set,
1179                  * LNet target returned -ENODATA.
1180                  */
1181                 if (status) {
1182                         if (event == TN_EVENT_TAG_RX_FAIL)
1183                                 kfilnd_tn_status_update(tn, status,
1184                                                         LNET_MSG_STATUS_LOCAL_ERROR);
1185                         else
1186                                 kfilnd_tn_status_update(tn, status,
1187                                                         LNET_MSG_STATUS_OK);
1188                 }
1189
1190                 if (!kfilnd_tn_timeout_cancel(tn)) {
1191                         kfilnd_tn_state_change(tn, TN_STATE_WAIT_TIMEOUT_COMP);
1192                         return 0;
1193                 }
1194                 break;
1195
1196         case TN_EVENT_TIMEOUT:
1197                 /* Need to cancel the tagged receive to prevent resources from
1198                  * being leaked.
1199                  */
1200                 rc = kfilnd_tn_cancel_tag_recv(tn);
1201
1202                 switch (rc) {
1203                 /* Async cancel event will progress transaction. */
1204                 case 0:
1205                         kfilnd_tn_state_change(tn,
1206                                                TN_STATE_WAIT_TIMEOUT_TAG_COMP);
1207                         return 0;
1208
1209                 /* Need to replay TN_EVENT_INIT_BULK event while in the
1210                  * TN_STATE_WAIT_TAG_COMP state.
1211                  */
1212                 case -EAGAIN:
1213                         KFILND_TN_DEBUG(tn,
1214                                         "Need to replay cancel tagged recv");
1215                         return -EAGAIN;
1216
1217                 default:
1218                         KFILND_TN_ERROR(tn,
1219                                         "Unexpected error during cancel tagged receive: rc=%d",
1220                                         rc);
1221                         LBUG();
1222                 }
1223                 break;
1224
1225         case TN_EVENT_TAG_TX_FAIL:
1226                 if (status == -ETIMEDOUT)
1227                         hstatus = LNET_MSG_STATUS_NETWORK_TIMEOUT;
1228                 else
1229                         hstatus = LNET_MSG_STATUS_REMOTE_ERROR;
1230
1231                 kfilnd_tn_status_update(tn, status, hstatus);
1232                 kfilnd_peer_tn_failed(tn->tn_kp, status);
1233                 break;
1234
1235         case TN_EVENT_TAG_TX_OK:
1236                 kfilnd_peer_alive(tn->tn_kp);
1237                 break;
1238
1239         default:
1240                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
1241                 LBUG();
1242         }
1243
1244         kfilnd_tn_finalize(tn, tn_released);
1245
1246         return 0;
1247 }
1248
1249 static int kfilnd_tn_state_fail(struct kfilnd_transaction *tn,
1250                                 enum tn_events event, int status,
1251                                 bool *tn_released)
1252 {
1253         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
1254                         status);
1255
1256         switch (event) {
1257         case TN_EVENT_TX_FAIL:
1258                 kfilnd_peer_tn_failed(tn->tn_kp, status);
1259                 break;
1260
1261         case TN_EVENT_TX_OK:
1262                 kfilnd_peer_alive(tn->tn_kp);
1263                 break;
1264
1265         case TN_EVENT_TAG_RX_FAIL:
1266         case TN_EVENT_TAG_RX_CANCEL:
1267                 break;
1268
1269         default:
1270                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
1271                 LBUG();
1272         }
1273
1274         kfilnd_tn_finalize(tn, tn_released);
1275
1276         return 0;
1277 }
1278
1279 static int kfilnd_tn_state_wait_timeout_tag_comp(struct kfilnd_transaction *tn,
1280                                                  enum tn_events event,
1281                                                  int status, bool *tn_released)
1282 {
1283         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
1284                         status);
1285
1286         switch (event) {
1287         case TN_EVENT_TAG_RX_CANCEL:
1288                 kfilnd_tn_status_update(tn, -ETIMEDOUT,
1289                                         LNET_MSG_STATUS_REMOTE_TIMEOUT);
1290                 kfilnd_peer_tn_failed(tn->tn_kp, -ETIMEDOUT);
1291                 break;
1292
1293         case TN_EVENT_TAG_RX_FAIL:
1294                 kfilnd_tn_status_update(tn, status,
1295                                         LNET_MSG_STATUS_LOCAL_ERROR);
1296                 break;
1297
1298         case TN_EVENT_TAG_RX_OK:
1299                 break;
1300
1301         default:
1302                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
1303                 LBUG();
1304         }
1305
1306         kfilnd_tn_finalize(tn, tn_released);
1307
1308         return 0;
1309 }
1310
1311 static int kfilnd_tn_state_wait_timeout_comp(struct kfilnd_transaction *tn,
1312                                              enum tn_events event, int status,
1313                                              bool *tn_released)
1314 {
1315         KFILND_TN_DEBUG(tn, "%s event status %d", tn_event_to_str(event),
1316                         status);
1317
1318         if (event == TN_EVENT_TIMEOUT) {
1319                 kfilnd_tn_finalize(tn, tn_released);
1320         } else {
1321                 KFILND_TN_ERROR(tn, "Invalid %s event", tn_event_to_str(event));
1322                 LBUG();
1323         }
1324
1325         return 0;
1326 }
1327
1328 static int
1329 (* const kfilnd_tn_state_dispatch_table[TN_STATE_MAX])(struct kfilnd_transaction *tn,
1330                                                        enum tn_events event,
1331                                                        int status,
1332                                                        bool *tn_released) = {
1333         [TN_STATE_IDLE] = kfilnd_tn_state_idle,
1334         [TN_STATE_WAIT_TAG_COMP] = kfilnd_tn_state_wait_tag_comp,
1335         [TN_STATE_IMM_SEND] = kfilnd_tn_state_imm_send,
1336         [TN_STATE_TAGGED_RECV_POSTED] = kfilnd_tn_state_tagged_recv_posted,
1337         [TN_STATE_SEND_FAILED] = kfilnd_tn_state_send_failed,
1338         [TN_STATE_WAIT_COMP] = kfilnd_tn_state_wait_comp,
1339         [TN_STATE_WAIT_TIMEOUT_COMP] = kfilnd_tn_state_wait_timeout_comp,
1340         [TN_STATE_WAIT_SEND_COMP] = kfilnd_tn_state_wait_send_comp,
1341         [TN_STATE_WAIT_TIMEOUT_TAG_COMP] =
1342                 kfilnd_tn_state_wait_timeout_tag_comp,
1343         [TN_STATE_FAIL] = kfilnd_tn_state_fail,
1344         [TN_STATE_IMM_RECV] = kfilnd_tn_state_imm_recv,
1345         [TN_STATE_WAIT_TAG_RMA_COMP] = kfilnd_tn_state_wait_tag_rma_comp,
1346 };
1347
1348 /**
1349  * kfilnd_tn_event_handler() - Update transaction state machine with an event.
1350  * @tn: Transaction to be updated.
1351  * @event: Transaction event.
1352  * @status: Errno status associated with the event.
1353  *
1354  * When the transaction event handler is first called on a new transaction, the
1355  * transaction is now own by the transaction system. This means that will be
1356  * freed by the system as the transaction is progressed through the state
1357  * machine.
1358  */
1359 void kfilnd_tn_event_handler(struct kfilnd_transaction *tn,
1360                              enum tn_events event, int status)
1361 {
1362         bool tn_released = false;
1363         int rc;
1364
1365         if (!tn)
1366                 return;
1367
1368         mutex_lock(&tn->tn_lock);
1369         rc = kfilnd_tn_state_dispatch_table[tn->tn_state](tn, event, status,
1370                                                           &tn_released);
1371         if (rc == -EAGAIN) {
1372                 tn->replay_event = event;
1373                 tn->replay_status = status;
1374                 kfilnd_ep_queue_tn_replay(tn->tn_ep, tn);
1375         }
1376
1377         if (!tn_released)
1378                 mutex_unlock(&tn->tn_lock);
1379 }
1380
1381 /**
1382  * kfilnd_tn_free() - Free a transaction.
1383  */
1384 void kfilnd_tn_free(struct kfilnd_transaction *tn)
1385 {
1386         spin_lock(&tn->tn_ep->tn_list_lock);
1387         list_del(&tn->tn_entry);
1388         spin_unlock(&tn->tn_ep->tn_list_lock);
1389
1390         KFILND_TN_DEBUG(tn, "Transaction freed");
1391
1392         if (tn->tn_mr_key)
1393                 kfilnd_ep_put_key(tn->tn_ep, tn->tn_mr_key);
1394
1395         /* Free send message buffer if needed. */
1396         if (tn->tn_tx_msg.msg)
1397                 kmem_cache_free(imm_buf_cache, tn->tn_tx_msg.msg);
1398
1399         kmem_cache_free(tn_cache, tn);
1400 }
1401
1402 /**
1403  * kfilnd_tn_alloc() - Allocate a new KFI LND transaction.
1404  * @dev: KFI LND device used to look the KFI LND endpoint to associate with the
1405  * transaction.
1406  * @cpt: CPT of the transaction.
1407  * @target_nid: Target NID of the transaction.
1408  * @alloc_msg: Allocate an immediate message for the transaction.
1409  * @is_initiator: Is initiator of LNet transaction.
1410  * @key: Is transaction memory region key need.
1411  *
1412  * During transaction allocation, each transaction is associated with a KFI LND
1413  * endpoint use to post data transfer operations. The CPT argument is used to
1414  * lookup the KFI LND endpoint within the KFI LND device.
1415  *
1416  * Return: On success, valid pointer. Else, negative errno pointer.
1417  */
1418 struct kfilnd_transaction *kfilnd_tn_alloc(struct kfilnd_dev *dev, int cpt,
1419                                            lnet_nid_t target_nid,
1420                                            bool alloc_msg, bool is_initiator,
1421                                            bool key)
1422 {
1423         struct kfilnd_transaction *tn;
1424         struct kfilnd_peer *kp;
1425         int rc;
1426
1427         if (!dev) {
1428                 rc = -EINVAL;
1429                 goto err;
1430         }
1431
1432         kp = kfilnd_peer_get(dev, target_nid);
1433         if (IS_ERR(kp)) {
1434                 rc = PTR_ERR(kp);
1435                 goto err;
1436         }
1437
1438         tn = kfilnd_tn_alloc_for_peer(dev, cpt, kp, alloc_msg, is_initiator,
1439                                       key);
1440         if (IS_ERR(tn)) {
1441                 rc = PTR_ERR(tn);
1442                 kfilnd_peer_put(kp);
1443                 goto err;
1444         }
1445
1446         return tn;
1447
1448 err:
1449         return ERR_PTR(rc);
1450 }
1451
1452 /* See kfilnd_tn_alloc()
1453  * Note: Caller must have a reference on @kp
1454  */
1455 struct kfilnd_transaction *kfilnd_tn_alloc_for_peer(struct kfilnd_dev *dev,
1456                                                     int cpt,
1457                                                     struct kfilnd_peer *kp,
1458                                                     bool alloc_msg,
1459                                                     bool is_initiator,
1460                                                     bool key)
1461 {
1462         struct kfilnd_transaction *tn;
1463         struct kfilnd_ep *ep;
1464         int rc;
1465         ktime_t tn_alloc_ts;
1466
1467         if (!dev) {
1468                 rc = -EINVAL;
1469                 goto err;
1470         }
1471
1472         tn_alloc_ts = ktime_get();
1473
1474         /* If the CPT does not fall into the LNet NI CPT range, force the CPT
1475          * into the LNet NI CPT range. This should never happen.
1476          */
1477         ep = dev->cpt_to_endpoint[cpt];
1478         if (!ep) {
1479                 CWARN("%s used invalid cpt=%d\n",
1480                       libcfs_nidstr(&dev->kfd_ni->ni_nid), cpt);
1481                 ep = dev->kfd_endpoints[0];
1482         }
1483
1484         tn = kmem_cache_zalloc(tn_cache, GFP_KERNEL);
1485         if (!tn) {
1486                 rc = -ENOMEM;
1487                 goto err;
1488         }
1489
1490         if (alloc_msg) {
1491                 tn->tn_tx_msg.msg = kmem_cache_alloc(imm_buf_cache, GFP_KERNEL);
1492                 if (!tn->tn_tx_msg.msg) {
1493                         rc = -ENOMEM;
1494                         goto err_free_tn;
1495                 }
1496         }
1497
1498         if (key) {
1499                 rc = kfilnd_ep_get_key(ep);
1500                 if (rc < 0)
1501                         goto err_free_tn;
1502                 tn->tn_mr_key = rc;
1503         }
1504
1505         tn->tn_kp = kp;
1506         refcount_inc(&kp->kp_cnt);
1507
1508         mutex_init(&tn->tn_lock);
1509         tn->tn_ep = ep;
1510         tn->tn_response_rx = ep->end_context_id;
1511         tn->tn_state = TN_STATE_IDLE;
1512         tn->hstatus = LNET_MSG_STATUS_OK;
1513         tn->deadline = ktime_get_seconds() + lnet_get_lnd_timeout();
1514         tn->is_initiator = is_initiator;
1515         INIT_WORK(&tn->timeout_work, kfilnd_tn_timeout_work);
1516
1517         /* Add the transaction to an endpoint.  This is like
1518          * incrementing a ref counter.
1519          */
1520         spin_lock(&ep->tn_list_lock);
1521         list_add_tail(&tn->tn_entry, &ep->tn_list);
1522         spin_unlock(&ep->tn_list_lock);
1523
1524         tn->tn_alloc_ts = tn_alloc_ts;
1525         tn->tn_state_ts = ktime_get();
1526
1527         KFILND_EP_DEBUG(ep, "Transaction ID %u allocated", tn->tn_mr_key);
1528
1529         return tn;
1530
1531 err_free_tn:
1532         if (tn->tn_tx_msg.msg)
1533                 kmem_cache_free(imm_buf_cache, tn->tn_tx_msg.msg);
1534         kmem_cache_free(tn_cache, tn);
1535 err:
1536         return ERR_PTR(rc);
1537 }
1538
1539 /**
1540  * kfilnd_tn_cleanup() - Cleanup KFI LND transaction system.
1541  *
1542  * This function should only be called when there are no outstanding
1543  * transactions.
1544  */
1545 void kfilnd_tn_cleanup(void)
1546 {
1547         kmem_cache_destroy(imm_buf_cache);
1548         kmem_cache_destroy(tn_cache);
1549 }
1550
1551 /**
1552  * kfilnd_tn_init() - Initialize KFI LND transaction system.
1553  *
1554  * Return: On success, zero. Else, negative errno.
1555  */
1556 int kfilnd_tn_init(void)
1557 {
1558         tn_cache = kmem_cache_create("kfilnd_tn",
1559                                      sizeof(struct kfilnd_transaction), 0,
1560                                      SLAB_HWCACHE_ALIGN, NULL);
1561         if (!tn_cache)
1562                 goto err;
1563
1564         imm_buf_cache = kmem_cache_create("kfilnd_imm_buf",
1565                                           KFILND_IMMEDIATE_MSG_SIZE, 0,
1566                                           SLAB_HWCACHE_ALIGN, NULL);
1567         if (!imm_buf_cache)
1568                 goto err_tn_cache_destroy;
1569
1570         return 0;
1571
1572 err_tn_cache_destroy:
1573         kmem_cache_destroy(tn_cache);
1574 err:
1575         return -ENOMEM;
1576 }
1577
1578 /**
1579  * kfilnd_tn_set_kiov_buf() - Set the buffer used for a transaction.
1580  * @tn: Transaction to have buffer set.
1581  * @kiov: LNet KIOV buffer.
1582  * @num_iov: Number of IOVs.
1583  * @offset: Offset into IOVs where the buffer starts.
1584  * @len: Length of the buffer.
1585  *
1586  * This function takes the user provided IOV, offset, and len, and sets the
1587  * transaction buffer. The user provided IOV is an LNet KIOV. When the
1588  * transaction buffer is configured, the user provided offset is applied
1589  * when the transaction buffer is configured (i.e. the transaction buffer
1590  * offset is zero).
1591  */
1592 int kfilnd_tn_set_kiov_buf(struct kfilnd_transaction *tn,
1593                            struct bio_vec *kiov, size_t num_iov,
1594                            size_t offset, size_t len)
1595 {
1596         size_t i;
1597         size_t cur_len = 0;
1598         size_t cur_offset = offset;
1599         size_t cur_iov = 0;
1600         size_t tmp_len;
1601         size_t tmp_offset;
1602
1603         for (i = 0; (i < num_iov) && (cur_len < len); i++) {
1604                 /* Skip KIOVs until a KIOV with a length less than the current
1605                  * offset is found.
1606                  */
1607                 if (kiov[i].bv_len <= cur_offset) {
1608                         cur_offset -= kiov[i].bv_len;
1609                         continue;
1610                 }
1611
1612                 tmp_len = kiov[i].bv_len - cur_offset;
1613                 tmp_offset = kiov[i].bv_len - tmp_len + kiov[i].bv_offset;
1614
1615                 if (tmp_len + cur_len > len)
1616                         tmp_len = len - cur_len;
1617
1618                 /* tn_kiov is an array of size LNET_MAX_IOV */
1619                 if (cur_iov >= LNET_MAX_IOV)
1620                         return -EINVAL;
1621
1622                 tn->tn_kiov[cur_iov].bv_page = kiov[i].bv_page;
1623                 tn->tn_kiov[cur_iov].bv_len = tmp_len;
1624                 tn->tn_kiov[cur_iov].bv_offset = tmp_offset;
1625
1626                 cur_iov++;
1627                 cur_len += tmp_len;
1628                 cur_offset = 0;
1629         }
1630
1631         tn->tn_num_iovec = cur_iov;
1632         tn->tn_nob = cur_len;
1633
1634         return 0;
1635 }