Whamcloud - gitweb
LU-6142 lnet: use list_first_entry() where appropriate.
[fs/lustre-release.git] / lnet / selftest / rpc.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 (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lnet/selftest/rpc.c
32  *
33  * Author: Isaac Huang <isaac@clusterfs.com>
34  *
35  * 2012-05-13: Liang Zhen <liang@whamcloud.com>
36  * - percpt data for service to improve smp performance
37  * - code cleanup
38  */
39
40 #define DEBUG_SUBSYSTEM S_LNET
41
42 #include "selftest.h"
43
44 enum srpc_state {
45         SRPC_STATE_NONE,
46         SRPC_STATE_NI_INIT,
47         SRPC_STATE_EQ_INIT,
48         SRPC_STATE_RUNNING,
49         SRPC_STATE_STOPPING,
50 };
51
52 enum rpc_counter_32 {
53         SRPC_ERROR,
54         SRPC_RPC_SENT,
55         SRPC_RPC_RCVD,
56         SRPC_RPC_DROP,
57         SRPC_RPC_EXPIRED,
58         SRPC_COUNTER32_MAX,
59 };
60
61 enum rpc_counter_64 {
62         SRPC_BULK_GET,
63         SRPC_BULK_PUT,
64         SRPC_COUNTER64_MAX,
65 };
66
67 static struct smoketest_rpc {
68         spinlock_t       rpc_glock;     /* global lock */
69         struct srpc_service     *rpc_services[SRPC_SERVICE_MAX_ID + 1];
70         lnet_handler_t           rpc_lnet_handler;/* _the_ LNet event handler */
71         enum srpc_state          rpc_state;
72         atomic_t                 rpc_counters32[SRPC_COUNTER32_MAX];
73         atomic64_t               rpc_counters64[SRPC_COUNTER64_MAX];
74         atomic64_t               rpc_matchbits; /* matchbits counter */
75
76 } srpc_data;
77
78 #define RPC_STAT32(a) \
79         srpc_data.rpc_counters32[(a)]
80
81 #define GET_RPC_STAT32(a) \
82         atomic_read(&srpc_data.rpc_counters32[(a)])
83
84 #define GET_RPC_STAT64(a) \
85         atomic64_read(&srpc_data.rpc_counters64[(a)])
86
87 static inline int
88 srpc_serv_portal(int svc_id)
89 {
90         return svc_id < SRPC_FRAMEWORK_SERVICE_MAX_ID ?
91                SRPC_FRAMEWORK_REQUEST_PORTAL : SRPC_REQUEST_PORTAL;
92 }
93
94 /* forward ref's */
95 static void srpc_handle_rpc(struct swi_workitem *wi);
96
97
98 void srpc_get_counters(struct srpc_counters *cnt)
99 {
100         cnt->errors = GET_RPC_STAT32(SRPC_ERROR);
101         cnt->rpcs_sent = GET_RPC_STAT32(SRPC_RPC_SENT);
102         cnt->rpcs_rcvd = GET_RPC_STAT32(SRPC_RPC_RCVD);
103         cnt->rpcs_dropped = GET_RPC_STAT32(SRPC_RPC_DROP);
104         cnt->rpcs_expired = GET_RPC_STAT32(SRPC_RPC_EXPIRED);
105
106         cnt->bulk_get = GET_RPC_STAT64(SRPC_BULK_GET);
107         cnt->bulk_put = GET_RPC_STAT64(SRPC_BULK_PUT);
108 }
109
110 static int
111 srpc_add_bulk_page(struct srpc_bulk *bk, struct page *pg, int i, int off,
112                    int nob)
113 {
114         LASSERT(off < PAGE_SIZE);
115         LASSERT(nob > 0 && nob <= PAGE_SIZE);
116
117         bk->bk_iovs[i].bv_offset = off;
118         bk->bk_iovs[i].bv_page   = pg;
119         bk->bk_iovs[i].bv_len    = nob;
120         return nob;
121 }
122
123 void
124 srpc_free_bulk(struct srpc_bulk *bk)
125 {
126         int i;
127         struct page *pg;
128
129         LASSERT(bk != NULL);
130
131         for (i = 0; i < bk->bk_niov; i++) {
132                 pg = bk->bk_iovs[i].bv_page;
133                 if (pg == NULL)
134                         break;
135
136                 __free_page(pg);
137         }
138
139         LIBCFS_FREE(bk, offsetof(struct srpc_bulk, bk_iovs[bk->bk_niov]));
140 }
141
142 struct srpc_bulk *
143 srpc_alloc_bulk(int cpt, unsigned bulk_off, unsigned bulk_npg,
144                 unsigned bulk_len, int sink)
145 {
146         struct srpc_bulk *bk;
147         int i;
148
149         LASSERT(bulk_npg > 0 && bulk_npg <= LNET_MAX_IOV);
150
151         LIBCFS_CPT_ALLOC(bk, lnet_cpt_table(), cpt,
152                          offsetof(struct srpc_bulk, bk_iovs[bulk_npg]));
153         if (bk == NULL) {
154                 CERROR("Can't allocate descriptor for %d pages\n", bulk_npg);
155                 return NULL;
156         }
157
158         memset(bk, 0, offsetof(struct srpc_bulk, bk_iovs[bulk_npg]));
159         bk->bk_sink   = sink;
160         bk->bk_len    = bulk_len;
161         bk->bk_niov   = bulk_npg;
162
163         for (i = 0; i < bulk_npg; i++) {
164                 struct page *pg;
165                 int nob;
166
167                 pg = cfs_page_cpt_alloc(lnet_cpt_table(), cpt, GFP_KERNEL);
168                 if (pg == NULL) {
169                         CERROR("Can't allocate page %d of %d\n", i, bulk_npg);
170                         srpc_free_bulk(bk);
171                         return NULL;
172                 }
173
174                 nob = min_t(unsigned, bulk_off + bulk_len, PAGE_SIZE) -
175                       bulk_off;
176
177                 srpc_add_bulk_page(bk, pg, i, bulk_off, nob);
178                 bulk_len -= nob;
179                 bulk_off = 0;
180         }
181
182         return bk;
183 }
184
185 static inline __u64
186 srpc_next_id (void)
187 {
188         return atomic64_inc_return(&srpc_data.rpc_matchbits);
189 }
190
191 static void
192 srpc_init_server_rpc(struct srpc_server_rpc *rpc,
193                      struct srpc_service_cd *scd,
194                      struct srpc_buffer *buffer)
195 {
196         memset(rpc, 0, sizeof(*rpc));
197         swi_init_workitem(&rpc->srpc_wi, srpc_handle_rpc,
198                           srpc_serv_is_framework(scd->scd_svc) ?
199                           lst_serial_wq : lst_test_wq[scd->scd_cpt]);
200
201         rpc->srpc_ev.ev_fired = 1; /* no event expected now */
202
203         rpc->srpc_scd      = scd;
204         rpc->srpc_reqstbuf = buffer;
205         rpc->srpc_peer     = buffer->buf_peer;
206         rpc->srpc_self     = buffer->buf_self;
207         LNetInvalidateMDHandle(&rpc->srpc_replymdh);
208 }
209
210 static void
211 srpc_service_fini(struct srpc_service *svc)
212 {
213         struct srpc_service_cd *scd;
214         struct srpc_server_rpc *rpc;
215         struct srpc_buffer *buf;
216         struct list_head *q;
217         int i;
218
219         if (svc->sv_cpt_data == NULL)
220                 return;
221
222         cfs_percpt_for_each(scd, i, svc->sv_cpt_data) {
223                 while (1) {
224                         if (!list_empty(&scd->scd_buf_posted))
225                                 q = &scd->scd_buf_posted;
226                         else if (!list_empty(&scd->scd_buf_blocked))
227                                 q = &scd->scd_buf_blocked;
228                         else
229                                 break;
230
231                         while (!list_empty(q)) {
232                                 buf = list_first_entry(q,
233                                                        struct srpc_buffer,
234                                                        buf_list);
235                                 list_del(&buf->buf_list);
236                                 LIBCFS_FREE(buf, sizeof(*buf));
237                         }
238                 }
239
240                 LASSERT(list_empty(&scd->scd_rpc_active));
241
242                 while (!list_empty(&scd->scd_rpc_free)) {
243                         rpc = list_first_entry(&scd->scd_rpc_free,
244                                                struct srpc_server_rpc,
245                                                srpc_list);
246                         list_del(&rpc->srpc_list);
247                         LIBCFS_FREE(rpc, sizeof(*rpc));
248                 }
249         }
250
251         cfs_percpt_free(svc->sv_cpt_data);
252         svc->sv_cpt_data = NULL;
253 }
254
255 static int
256 srpc_service_nrpcs(struct srpc_service *svc)
257 {
258         int nrpcs = svc->sv_wi_total / svc->sv_ncpts;
259
260         return srpc_serv_is_framework(svc) ?
261                max(nrpcs, SFW_FRWK_WI_MIN) : max(nrpcs, SFW_TEST_WI_MIN);
262 }
263
264 void srpc_add_buffer(struct swi_workitem *wi);
265
266 static int
267 srpc_service_init(struct srpc_service *svc)
268 {
269         struct srpc_service_cd *scd;
270         struct srpc_server_rpc *rpc;
271         int nrpcs;
272         int i;
273         int j;
274
275         svc->sv_shuttingdown = 0;
276
277         svc->sv_cpt_data = cfs_percpt_alloc(lnet_cpt_table(),
278                                             sizeof(struct srpc_service_cd));
279         if (svc->sv_cpt_data == NULL)
280                 return -ENOMEM;
281
282         svc->sv_ncpts = srpc_serv_is_framework(svc) ?
283                         1 : cfs_cpt_number(lnet_cpt_table());
284         nrpcs = srpc_service_nrpcs(svc);
285
286         cfs_percpt_for_each(scd, i, svc->sv_cpt_data) {
287                 scd->scd_cpt = i;
288                 scd->scd_svc = svc;
289                 spin_lock_init(&scd->scd_lock);
290                 INIT_LIST_HEAD(&scd->scd_rpc_free);
291                 INIT_LIST_HEAD(&scd->scd_rpc_active);
292                 INIT_LIST_HEAD(&scd->scd_buf_posted);
293                 INIT_LIST_HEAD(&scd->scd_buf_blocked);
294
295                 scd->scd_ev.ev_data = scd;
296                 scd->scd_ev.ev_type = SRPC_REQUEST_RCVD;
297
298                 /* NB: don't use lst_serial_wq for adding buffer,
299                  * see details in srpc_service_add_buffers() */
300                 swi_init_workitem(&scd->scd_buf_wi,
301                                   srpc_add_buffer, lst_test_wq[i]);
302
303                 if (i != 0 && srpc_serv_is_framework(svc)) {
304                         /* NB: framework service only needs srpc_service_cd for
305                          * one partition, but we allocate for all to make
306                          * it easier to implement, it will waste a little
307                          * memory but nobody should care about this */
308                         continue;
309                 }
310
311                 for (j = 0; j < nrpcs; j++) {
312                         LIBCFS_CPT_ALLOC(rpc, lnet_cpt_table(),
313                                          i, sizeof(*rpc));
314                         if (rpc == NULL) {
315                                 srpc_service_fini(svc);
316                                 return -ENOMEM;
317                         }
318                         list_add(&rpc->srpc_list, &scd->scd_rpc_free);
319                 }
320         }
321
322         return 0;
323 }
324
325 int
326 srpc_add_service(struct srpc_service *sv)
327 {
328         int id = sv->sv_id;
329
330         LASSERT(0 <= id && id <= SRPC_SERVICE_MAX_ID);
331
332         if (srpc_service_init(sv) != 0)
333                 return -ENOMEM;
334
335         spin_lock(&srpc_data.rpc_glock);
336
337         LASSERT(srpc_data.rpc_state == SRPC_STATE_RUNNING);
338
339         if (srpc_data.rpc_services[id] != NULL) {
340                 spin_unlock(&srpc_data.rpc_glock);
341                 goto failed;
342         }
343
344         srpc_data.rpc_services[id] = sv;
345         spin_unlock(&srpc_data.rpc_glock);
346
347         CDEBUG(D_NET, "Adding service: id %d, name %s\n", id, sv->sv_name);
348         return 0;
349
350 failed:
351         srpc_service_fini(sv);
352         return -EBUSY;
353 }
354
355 int
356 srpc_remove_service(struct srpc_service *sv)
357 {
358         int id = sv->sv_id;
359
360         spin_lock(&srpc_data.rpc_glock);
361
362         if (srpc_data.rpc_services[id] != sv) {
363                 spin_unlock(&srpc_data.rpc_glock);
364                 return -ENOENT;
365         }
366
367         srpc_data.rpc_services[id] = NULL;
368         spin_unlock(&srpc_data.rpc_glock);
369         return 0;
370 }
371
372 static int
373 srpc_post_passive_rdma(int portal, int local, __u64 matchbits, void *buf,
374                        int len, int options, struct lnet_process_id peer4,
375                        struct lnet_handle_md *mdh, struct srpc_event *ev)
376 {
377         int rc;
378         struct lnet_md md;
379         struct lnet_me *me;
380         struct lnet_processid peer;
381
382         peer.pid = peer4.pid;
383         lnet_nid4_to_nid(peer4.nid, &peer.nid);
384
385         me = LNetMEAttach(portal, &peer, matchbits, 0, LNET_UNLINK,
386                           local ? LNET_INS_LOCAL : LNET_INS_AFTER);
387         if (IS_ERR(me)) {
388                 rc = PTR_ERR(me);
389                 CERROR("LNetMEAttach failed: %d\n", rc);
390                 LASSERT(rc == -ENOMEM);
391                 return -ENOMEM;
392         }
393
394         md.threshold = 1;
395         md.user_ptr  = ev;
396         md.start     = buf;
397         md.length    = len;
398         md.options   = options;
399         md.handler   = srpc_data.rpc_lnet_handler;
400
401         rc = LNetMDAttach(me, &md, LNET_UNLINK, mdh);
402         if (rc != 0) {
403                 CERROR("LNetMDAttach failed: %d\n", rc);
404                 LASSERT(rc == -ENOMEM);
405
406                 return -ENOMEM;
407         }
408
409         CDEBUG(D_NET,
410                "Posted passive RDMA: peer %s, portal %d, matchbits %#llx\n",
411                libcfs_id2str(peer4), portal, matchbits);
412         return 0;
413 }
414
415 static int
416 srpc_post_active_rdma(int portal, __u64 matchbits, void *buf, int len,
417                       int options, struct lnet_process_id peer4,
418                       lnet_nid_t self4, struct lnet_handle_md *mdh,
419                       struct srpc_event *ev)
420 {
421         int rc;
422         struct lnet_md md;
423         struct lnet_nid self;
424         struct lnet_processid peer;
425
426         lnet_nid4_to_nid(self4, &self);
427         lnet_pid4_to_pid(peer4, &peer);
428
429         md.user_ptr  = ev;
430         md.start     = buf;
431         md.length    = len;
432         md.handler   = srpc_data.rpc_lnet_handler;
433         md.threshold = ((options & LNET_MD_OP_GET) != 0) ? 2 : 1;
434         md.options   = options & ~(LNET_MD_OP_PUT | LNET_MD_OP_GET);
435
436         rc = LNetMDBind(&md, LNET_UNLINK, mdh);
437         if (rc != 0) {
438                 CERROR("LNetMDBind failed: %d\n", rc);
439                 LASSERT(rc == -ENOMEM);
440                 return -ENOMEM;
441         }
442
443         /* this is kind of an abuse of the LNET_MD_OP_{PUT,GET} options.
444          * they're only meaningful for MDs attached to an ME (i.e. passive
445          * buffers...
446          */
447         if ((options & LNET_MD_OP_PUT) != 0) {
448                 rc = LNetPut(&self, *mdh, LNET_NOACK_REQ, &peer,
449                              portal, matchbits, 0, 0);
450         } else {
451                 LASSERT((options & LNET_MD_OP_GET) != 0);
452
453                 rc = LNetGet(&self, *mdh, &peer, portal, matchbits, 0, false);
454         }
455
456         if (rc != 0) {
457                 CERROR("LNet%s(%s, %d, %lld) failed: %d\n",
458                        ((options & LNET_MD_OP_PUT) != 0) ? "Put" : "Get",
459                        libcfs_id2str(peer4), portal, matchbits, rc);
460
461                 /* The forthcoming unlink event will complete this operation
462                  * with failure, so fall through and return success here.
463                  */
464                 rc = LNetMDUnlink(*mdh);
465                 LASSERT(rc == 0);
466         } else {
467                 CDEBUG(D_NET,
468                        "Posted active RDMA: peer %s, portal %u, matchbits %#llx\n",
469                        libcfs_id2str(peer4), portal, matchbits);
470         }
471         return 0;
472 }
473
474 static int
475 srpc_post_passive_rqtbuf(int service, int local, void *buf, int len,
476                          struct lnet_handle_md *mdh, struct srpc_event *ev)
477 {
478         struct lnet_process_id any = {0};
479
480         any.nid = LNET_NID_ANY;
481         any.pid = LNET_PID_ANY;
482
483         return srpc_post_passive_rdma(srpc_serv_portal(service),
484                                       local, service, buf, len,
485                                       LNET_MD_OP_PUT, any, mdh, ev);
486 }
487
488 static int
489 srpc_service_post_buffer(struct srpc_service_cd *scd, struct srpc_buffer *buf)
490 __must_hold(&scd->scd_lock)
491 {
492         struct srpc_service *sv = scd->scd_svc;
493         struct srpc_msg *msg = &buf->buf_msg;
494         int rc;
495
496         LNetInvalidateMDHandle(&buf->buf_mdh);
497         list_add(&buf->buf_list, &scd->scd_buf_posted);
498         scd->scd_buf_nposted++;
499         spin_unlock(&scd->scd_lock);
500
501         rc = srpc_post_passive_rqtbuf(sv->sv_id,
502                                       !srpc_serv_is_framework(sv),
503                                       msg, sizeof(*msg), &buf->buf_mdh,
504                                       &scd->scd_ev);
505
506         /* At this point, a RPC (new or delayed) may have arrived in
507          * msg and its event handler has been called. So we must add
508          * buf to scd_buf_posted _before_ dropping scd_lock */
509
510         spin_lock(&scd->scd_lock);
511
512         if (rc == 0) {
513                 if (!sv->sv_shuttingdown)
514                         return 0;
515
516                 spin_unlock(&scd->scd_lock);
517                 /* srpc_shutdown_service might have tried to unlink me
518                  * when my buf_mdh was still invalid */
519                 LNetMDUnlink(buf->buf_mdh);
520                 spin_lock(&scd->scd_lock);
521                 return 0;
522         }
523
524         scd->scd_buf_nposted--;
525         if (sv->sv_shuttingdown)
526                 return rc; /* don't allow to change scd_buf_posted */
527
528         list_del(&buf->buf_list);
529         spin_unlock(&scd->scd_lock);
530
531         LIBCFS_FREE(buf, sizeof(*buf));
532
533         spin_lock(&scd->scd_lock);
534         return rc;
535 }
536
537 void
538 srpc_add_buffer(struct swi_workitem *wi)
539 {
540         struct srpc_service_cd *scd = container_of(wi, struct srpc_service_cd,
541                                                    scd_buf_wi);
542         struct srpc_buffer *buf;
543         int rc = 0;
544
545         /* it's called by workitem scheduler threads, these threads
546          * should have been set CPT affinity, so buffers will be posted
547          * on CPT local list of Portal */
548         spin_lock(&scd->scd_lock);
549
550         while (scd->scd_buf_adjust > 0 &&
551                !scd->scd_svc->sv_shuttingdown) {
552                 scd->scd_buf_adjust--; /* consume it */
553                 scd->scd_buf_posting++;
554
555                 spin_unlock(&scd->scd_lock);
556
557                 LIBCFS_ALLOC(buf, sizeof(*buf));
558                 if (buf == NULL) {
559                         CERROR("Failed to add new buf to service: %s\n",
560                                scd->scd_svc->sv_name);
561                         spin_lock(&scd->scd_lock);
562                         rc = -ENOMEM;
563                         break;
564                 }
565
566                 spin_lock(&scd->scd_lock);
567                 if (scd->scd_svc->sv_shuttingdown) {
568                         spin_unlock(&scd->scd_lock);
569                         LIBCFS_FREE(buf, sizeof(*buf));
570
571                         spin_lock(&scd->scd_lock);
572                         rc = -ESHUTDOWN;
573                         break;
574                 }
575
576                 rc = srpc_service_post_buffer(scd, buf);
577                 if (rc != 0)
578                         break; /* buf has been freed inside */
579
580                 LASSERT(scd->scd_buf_posting > 0);
581                 scd->scd_buf_posting--;
582                 scd->scd_buf_total++;
583                 scd->scd_buf_low = max(2, scd->scd_buf_total / 4);
584         }
585
586         if (rc != 0) {
587                 scd->scd_buf_err_stamp = ktime_get_real_seconds();
588                 scd->scd_buf_err = rc;
589
590                 LASSERT(scd->scd_buf_posting > 0);
591                 scd->scd_buf_posting--;
592         }
593
594         wi->swi_state = SWI_STATE_RUNNING;
595         spin_unlock(&scd->scd_lock);
596 }
597
598 int
599 srpc_service_add_buffers(struct srpc_service *sv, int nbuffer)
600 {
601         struct srpc_service_cd *scd;
602         int rc = 0;
603         int i;
604
605         LASSERTF(nbuffer > 0, "nbuffer must be positive: %d\n", nbuffer);
606
607         cfs_percpt_for_each(scd, i, sv->sv_cpt_data) {
608                 spin_lock(&scd->scd_lock);
609
610                 scd->scd_buf_err = 0;
611                 scd->scd_buf_err_stamp = 0;
612                 scd->scd_buf_posting = 0;
613                 scd->scd_buf_adjust = nbuffer;
614                 /* start to post buffers */
615                 swi_schedule_workitem(&scd->scd_buf_wi);
616                 spin_unlock(&scd->scd_lock);
617
618                 /* framework service only post buffer for one partition  */
619                 if (srpc_serv_is_framework(sv))
620                         break;
621         }
622
623         cfs_percpt_for_each(scd, i, sv->sv_cpt_data) {
624                 spin_lock(&scd->scd_lock);
625                 /*
626                  * NB: srpc_service_add_buffers() can be called inside
627                  * thread context of lst_serial_wq, and we don't normally
628                  * allow to sleep inside thread context of WI scheduler
629                  * because it will block current scheduler thread from doing
630                  * anything else, even worse, it could deadlock if it's
631                  * waiting on result from another WI of the same scheduler.
632                  * However, it's safe at here because scd_buf_wi is scheduled
633                  * by thread in a different WI scheduler (lst_test_wq),
634                  * so we don't have any risk of deadlock, though this could
635                  * block all WIs pending on lst_serial_wq for a moment
636                  * which is not good but not fatal.
637                  */
638                 lst_wait_until(scd->scd_buf_err != 0 ||
639                                (scd->scd_buf_adjust == 0 &&
640                                 scd->scd_buf_posting == 0),
641                                scd->scd_lock, "waiting for adding buffer\n");
642
643                 if (scd->scd_buf_err != 0 && rc == 0)
644                         rc = scd->scd_buf_err;
645
646                 spin_unlock(&scd->scd_lock);
647         }
648
649         return rc;
650 }
651
652 void
653 srpc_service_remove_buffers(struct srpc_service *sv, int nbuffer)
654 {
655         struct srpc_service_cd *scd;
656         int num;
657         int i;
658
659         LASSERT(!sv->sv_shuttingdown);
660
661         cfs_percpt_for_each(scd, i, sv->sv_cpt_data) {
662                 spin_lock(&scd->scd_lock);
663
664                 num = scd->scd_buf_total + scd->scd_buf_posting;
665                 scd->scd_buf_adjust -= min(nbuffer, num);
666
667                 spin_unlock(&scd->scd_lock);
668         }
669 }
670
671 /* returns 1 if sv has finished, otherwise 0 */
672 int
673 srpc_finish_service(struct srpc_service *sv)
674 {
675         struct srpc_service_cd *scd;
676         struct srpc_server_rpc *rpc;
677         int i;
678
679         LASSERT(sv->sv_shuttingdown); /* srpc_shutdown_service called */
680
681         cfs_percpt_for_each(scd, i, sv->sv_cpt_data) {
682                 swi_cancel_workitem(&scd->scd_buf_wi);
683
684                 spin_lock(&scd->scd_lock);
685                 if (scd->scd_buf_nposted > 0) {
686                         CDEBUG(D_NET, "waiting for %d posted buffers to unlink\n",
687                                scd->scd_buf_nposted);
688                         spin_unlock(&scd->scd_lock);
689                         return 0;
690                 }
691
692                 if (list_empty(&scd->scd_rpc_active)) {
693                         spin_unlock(&scd->scd_lock);
694                         continue;
695                 }
696
697                 rpc = list_first_entry(&scd->scd_rpc_active,
698                                        struct srpc_server_rpc, srpc_list);
699                 CNETERR("Active RPC %p on shutdown: sv %s, peer %s, wi %s, ev fired %d type %d status %d lnet %d\n",
700                         rpc, sv->sv_name, libcfs_id2str(rpc->srpc_peer),
701                         swi_state2str(rpc->srpc_wi.swi_state),
702                         rpc->srpc_ev.ev_fired, rpc->srpc_ev.ev_type,
703                         rpc->srpc_ev.ev_status, rpc->srpc_ev.ev_lnet);
704                 spin_unlock(&scd->scd_lock);
705                 return 0;
706         }
707
708         /* no lock needed from now on */
709         srpc_service_fini(sv);
710         return 1;
711 }
712
713 /* called with sv->sv_lock held */
714 static void
715 srpc_service_recycle_buffer(struct srpc_service_cd *scd,
716                             struct srpc_buffer *buf)
717 __must_hold(&scd->scd_lock)
718 {
719         if (!scd->scd_svc->sv_shuttingdown && scd->scd_buf_adjust >= 0) {
720                 if (srpc_service_post_buffer(scd, buf) != 0) {
721                         CWARN("Failed to post %s buffer\n",
722                               scd->scd_svc->sv_name);
723                 }
724                 return;
725         }
726
727         /* service is shutting down, or we want to recycle some buffers */
728         scd->scd_buf_total--;
729
730         if (scd->scd_buf_adjust < 0) {
731                 scd->scd_buf_adjust++;
732                 if (scd->scd_buf_adjust < 0 &&
733                     scd->scd_buf_total == 0 && scd->scd_buf_posting == 0) {
734                         CDEBUG(D_INFO,
735                                "Try to recyle %d buffers but nothing left\n",
736                                scd->scd_buf_adjust);
737                         scd->scd_buf_adjust = 0;
738                 }
739         }
740
741         spin_unlock(&scd->scd_lock);
742         LIBCFS_FREE(buf, sizeof(*buf));
743         spin_lock(&scd->scd_lock);
744 }
745
746 void
747 srpc_abort_service(struct srpc_service *sv)
748 {
749         struct srpc_service_cd *scd;
750         struct srpc_server_rpc *rpc;
751         int i;
752
753         CDEBUG(D_NET, "Aborting service: id %d, name %s\n",
754                sv->sv_id, sv->sv_name);
755
756         cfs_percpt_for_each(scd, i, sv->sv_cpt_data) {
757                 spin_lock(&scd->scd_lock);
758
759                 /* schedule in-flight RPCs to notice the abort, NB:
760                  * racing with incoming RPCs; complete fix should make test
761                  * RPCs carry session ID in its headers
762                  */
763                 list_for_each_entry(rpc, &scd->scd_rpc_active, srpc_list) {
764                         rpc->srpc_aborted = 1;
765                         swi_schedule_workitem(&rpc->srpc_wi);
766                 }
767
768                 spin_unlock(&scd->scd_lock);
769         }
770 }
771
772 void
773 srpc_shutdown_service(struct srpc_service *sv)
774 {
775         struct srpc_service_cd *scd;
776         struct srpc_server_rpc *rpc;
777         struct srpc_buffer *buf;
778         int i;
779
780         CDEBUG(D_NET, "Shutting down service: id %d, name %s\n",
781                sv->sv_id, sv->sv_name);
782
783         cfs_percpt_for_each(scd, i, sv->sv_cpt_data)
784                 spin_lock(&scd->scd_lock);
785
786         sv->sv_shuttingdown = 1; /* i.e. no new active RPC */
787
788         cfs_percpt_for_each(scd, i, sv->sv_cpt_data)
789                 spin_unlock(&scd->scd_lock);
790
791         cfs_percpt_for_each(scd, i, sv->sv_cpt_data) {
792                 spin_lock(&scd->scd_lock);
793
794                 /* schedule in-flight RPCs to notice the shutdown */
795                 list_for_each_entry(rpc, &scd->scd_rpc_active, srpc_list)
796                         swi_schedule_workitem(&rpc->srpc_wi);
797
798                 spin_unlock(&scd->scd_lock);
799
800                 /* OK to traverse scd_buf_posted without lock, since no one
801                  * touches scd_buf_posted now
802                  */
803                 list_for_each_entry(buf, &scd->scd_buf_posted, buf_list)
804                         LNetMDUnlink(buf->buf_mdh);
805         }
806 }
807
808 static int
809 srpc_send_request(struct srpc_client_rpc *rpc)
810 {
811         struct srpc_event *ev = &rpc->crpc_reqstev;
812         int rc;
813
814         ev->ev_fired = 0;
815         ev->ev_data  = rpc;
816         ev->ev_type  = SRPC_REQUEST_SENT;
817
818         rc = srpc_post_active_rdma(srpc_serv_portal(rpc->crpc_service),
819                                    rpc->crpc_service, &rpc->crpc_reqstmsg,
820                                    sizeof(struct srpc_msg), LNET_MD_OP_PUT,
821                                    rpc->crpc_dest, LNET_NID_ANY,
822                                    &rpc->crpc_reqstmdh, ev);
823         if (rc != 0) {
824                 LASSERT(rc == -ENOMEM);
825                 ev->ev_fired = 1;  /* no more event expected */
826         }
827         return rc;
828 }
829
830 static int
831 srpc_prepare_reply(struct srpc_client_rpc *rpc)
832 {
833         struct srpc_event *ev = &rpc->crpc_replyev;
834         u64 *id = &rpc->crpc_reqstmsg.msg_body.reqst.rpyid;
835         int rc;
836
837         ev->ev_fired = 0;
838         ev->ev_data  = rpc;
839         ev->ev_type  = SRPC_REPLY_RCVD;
840
841         *id = srpc_next_id();
842
843         rc = srpc_post_passive_rdma(SRPC_RDMA_PORTAL, 0, *id,
844                                     &rpc->crpc_replymsg,
845                                     sizeof(struct srpc_msg),
846                                     LNET_MD_OP_PUT, rpc->crpc_dest,
847                                     &rpc->crpc_replymdh, ev);
848         if (rc != 0) {
849                 LASSERT(rc == -ENOMEM);
850                 ev->ev_fired = 1;  /* no more event expected */
851         }
852         return rc;
853 }
854
855 static int
856 srpc_prepare_bulk(struct srpc_client_rpc *rpc)
857 {
858         struct srpc_bulk *bk = &rpc->crpc_bulk;
859         struct srpc_event *ev = &rpc->crpc_bulkev;
860         __u64 *id = &rpc->crpc_reqstmsg.msg_body.reqst.bulkid;
861         int rc;
862         int opt;
863
864         LASSERT(bk->bk_niov <= LNET_MAX_IOV);
865
866         /* nothing to do */
867         if (bk->bk_niov == 0)
868                 return 0;
869
870         opt = bk->bk_sink ? LNET_MD_OP_PUT : LNET_MD_OP_GET;
871         opt |= LNET_MD_KIOV;
872
873         ev->ev_fired = 0;
874         ev->ev_data  = rpc;
875         ev->ev_type  = SRPC_BULK_REQ_RCVD;
876
877         *id = srpc_next_id();
878
879         rc = srpc_post_passive_rdma(SRPC_RDMA_PORTAL, 0, *id,
880                                     &bk->bk_iovs[0], bk->bk_niov, opt,
881                                     rpc->crpc_dest, &bk->bk_mdh, ev);
882         if (rc != 0) {
883                 LASSERT(rc == -ENOMEM);
884                 ev->ev_fired = 1;  /* no more event expected */
885         }
886         return rc;
887 }
888
889 static int
890 srpc_do_bulk(struct srpc_server_rpc *rpc)
891 {
892         struct srpc_event *ev = &rpc->srpc_ev;
893         struct srpc_bulk *bk = rpc->srpc_bulk;
894         __u64 id = rpc->srpc_reqstbuf->buf_msg.msg_body.reqst.bulkid;
895         int rc;
896         int opt;
897
898         LASSERT(bk != NULL);
899
900         opt = bk->bk_sink ? LNET_MD_OP_GET : LNET_MD_OP_PUT;
901         opt |= LNET_MD_KIOV;
902
903         ev->ev_fired = 0;
904         ev->ev_data  = rpc;
905         ev->ev_type  = bk->bk_sink ? SRPC_BULK_GET_RPLD : SRPC_BULK_PUT_SENT;
906
907         rc = srpc_post_active_rdma(SRPC_RDMA_PORTAL, id,
908                                    &bk->bk_iovs[0], bk->bk_niov, opt,
909                                    rpc->srpc_peer, rpc->srpc_self,
910                                    &bk->bk_mdh, ev);
911         if (rc != 0)
912                 ev->ev_fired = 1;  /* no more event expected */
913         return rc;
914 }
915
916 /* only called from srpc_handle_rpc */
917 static void
918 srpc_server_rpc_done(struct srpc_server_rpc *rpc, int status)
919 {
920         struct srpc_service_cd  *scd = rpc->srpc_scd;
921         struct srpc_service     *sv  = scd->scd_svc;
922         struct srpc_buffer *buffer;
923
924         rpc->srpc_status = status;
925
926         CDEBUG_LIMIT(status == 0 ? D_NET : D_NETERROR,
927                      "Server RPC %p done: service %s, peer %s, status %s:%d\n",
928                      rpc, sv->sv_name, libcfs_id2str(rpc->srpc_peer),
929                      swi_state2str(rpc->srpc_wi.swi_state), status);
930
931         if (status != 0)
932                 atomic_inc(&RPC_STAT32(SRPC_RPC_DROP));
933
934         if (rpc->srpc_done != NULL)
935                 (*rpc->srpc_done) (rpc);
936         LASSERT(rpc->srpc_bulk == NULL);
937
938         spin_lock(&scd->scd_lock);
939
940         if (rpc->srpc_reqstbuf != NULL) {
941                 /* NB might drop sv_lock in srpc_service_recycle_buffer, but
942                  * sv won't go away for scd_rpc_active must not be empty
943                  */
944                 srpc_service_recycle_buffer(scd, rpc->srpc_reqstbuf);
945                 rpc->srpc_reqstbuf = NULL;
946         }
947
948         list_del(&rpc->srpc_list); /* from scd->scd_rpc_active */
949
950         /*
951          * No one can schedule me now since:
952          * - I'm not on scd_rpc_active.
953          * - all LNet events have been fired.
954          * Cancel pending schedules and prevent future schedule attempts:
955          */
956         LASSERT(rpc->srpc_ev.ev_fired);
957         rpc->srpc_wi.swi_state = SWI_STATE_DONE;
958
959         if (!sv->sv_shuttingdown && !list_empty(&scd->scd_buf_blocked)) {
960                 buffer = list_first_entry(&scd->scd_buf_blocked,
961                                           struct srpc_buffer, buf_list);
962                 list_del(&buffer->buf_list);
963
964                 srpc_init_server_rpc(rpc, scd, buffer);
965                 list_add_tail(&rpc->srpc_list, &scd->scd_rpc_active);
966                 swi_schedule_workitem(&rpc->srpc_wi);
967         } else {
968                 list_add(&rpc->srpc_list, &scd->scd_rpc_free);
969         }
970
971         spin_unlock(&scd->scd_lock);
972 }
973
974 /* handles an incoming RPC */
975 static void srpc_handle_rpc(struct swi_workitem *wi)
976 {
977         struct srpc_server_rpc *rpc = container_of(wi, struct srpc_server_rpc,
978                                                    srpc_wi);
979         struct srpc_service_cd *scd = rpc->srpc_scd;
980         struct srpc_service *sv = scd->scd_svc;
981         struct srpc_event *ev = &rpc->srpc_ev;
982         int rc = 0;
983
984         spin_lock(&scd->scd_lock);
985         if (wi->swi_state == SWI_STATE_DONE) {
986                 spin_unlock(&scd->scd_lock);
987                 return;
988         }
989
990         if (sv->sv_shuttingdown || rpc->srpc_aborted) {
991                 wi->swi_state = SWI_STATE_DONE;
992                 spin_unlock(&scd->scd_lock);
993
994                 if (rpc->srpc_bulk != NULL)
995                         LNetMDUnlink(rpc->srpc_bulk->bk_mdh);
996                 LNetMDUnlink(rpc->srpc_replymdh);
997
998                 if (ev->ev_fired) /* no more event, OK to finish */
999                         srpc_server_rpc_done(rpc, -ESHUTDOWN);
1000                 return;
1001         }
1002
1003         spin_unlock(&scd->scd_lock);
1004
1005         switch (wi->swi_state) {
1006         default:
1007                 LBUG();
1008                 fallthrough;
1009         case SWI_STATE_NEWBORN: {
1010                 struct srpc_msg *msg;
1011                 struct srpc_generic_reply *reply;
1012
1013                 msg = &rpc->srpc_reqstbuf->buf_msg;
1014                 reply = &rpc->srpc_replymsg.msg_body.reply;
1015
1016                 if (msg->msg_magic == 0) {
1017                         /* moaned already in srpc_lnet_ev_handler */
1018                         srpc_server_rpc_done(rpc, EBADMSG);
1019                         return;
1020                 }
1021
1022                 srpc_unpack_msg_hdr(msg);
1023                 if (msg->msg_version != SRPC_MSG_VERSION) {
1024                         CWARN("Version mismatch: %u, %u expected, from %s\n",
1025                               msg->msg_version, SRPC_MSG_VERSION,
1026                               libcfs_id2str(rpc->srpc_peer));
1027                         reply->status = EPROTO;
1028                         /* drop through and send reply */
1029                 } else {
1030                         reply->status = 0;
1031                         rc = (*sv->sv_handler)(rpc);
1032                         LASSERT(reply->status == 0 || !rpc->srpc_bulk);
1033                         if (rc != 0) {
1034                                 srpc_server_rpc_done(rpc, rc);
1035                                 return;
1036                         }
1037                 }
1038
1039                 wi->swi_state = SWI_STATE_BULK_STARTED;
1040
1041                 if (rpc->srpc_bulk != NULL) {
1042                         rc = srpc_do_bulk(rpc);
1043                         if (rc == 0)
1044                                 return; /* wait for bulk */
1045
1046                         LASSERT(ev->ev_fired);
1047                         ev->ev_status = rc;
1048                 }
1049         }
1050         fallthrough;
1051         case SWI_STATE_BULK_STARTED:
1052                 LASSERT(rpc->srpc_bulk == NULL || ev->ev_fired);
1053
1054                 if (rpc->srpc_bulk != NULL) {
1055                         rc = ev->ev_status;
1056
1057                         if (sv->sv_bulk_ready != NULL)
1058                                 rc = (*sv->sv_bulk_ready) (rpc, rc);
1059
1060                         if (rc != 0) {
1061                                 srpc_server_rpc_done(rpc, rc);
1062                                 return;
1063                         }
1064                 }
1065
1066                 wi->swi_state = SWI_STATE_REPLY_SUBMITTED;
1067                 rc = srpc_send_reply(rpc);
1068                 if (rc == 0)
1069                         return; /* wait for reply */
1070                 srpc_server_rpc_done(rpc, rc);
1071                 return;
1072
1073         case SWI_STATE_REPLY_SUBMITTED:
1074                 if (!ev->ev_fired) {
1075                         CERROR("RPC %p: bulk %p, service %d\n",
1076                                rpc, rpc->srpc_bulk, sv->sv_id);
1077                         CERROR("Event: status %d, type %d, lnet %d\n",
1078                                ev->ev_status, ev->ev_type, ev->ev_lnet);
1079                         LASSERT(ev->ev_fired);
1080                 }
1081
1082                 wi->swi_state = SWI_STATE_DONE;
1083                 srpc_server_rpc_done(rpc, ev->ev_status);
1084                 return;
1085         }
1086 }
1087
1088 static void
1089 srpc_client_rpc_expired (void *data)
1090 {
1091         struct srpc_client_rpc *rpc = data;
1092
1093         CWARN("Client RPC expired: service %d, peer %s, timeout %d.\n",
1094               rpc->crpc_service, libcfs_id2str(rpc->crpc_dest),
1095               rpc->crpc_timeout);
1096
1097         spin_lock(&rpc->crpc_lock);
1098
1099         rpc->crpc_timeout = 0;
1100         srpc_abort_rpc(rpc, -ETIMEDOUT);
1101
1102         spin_unlock(&rpc->crpc_lock);
1103
1104         atomic_inc(&RPC_STAT32(SRPC_RPC_EXPIRED));
1105 }
1106
1107 static void
1108 srpc_add_client_rpc_timer(struct srpc_client_rpc *rpc)
1109 {
1110         struct stt_timer *timer = &rpc->crpc_timer;
1111
1112         if (rpc->crpc_timeout == 0)
1113                 return;
1114
1115         INIT_LIST_HEAD(&timer->stt_list);
1116         timer->stt_data    = rpc;
1117         timer->stt_func    = srpc_client_rpc_expired;
1118         timer->stt_expires = ktime_get_real_seconds() + rpc->crpc_timeout;
1119         stt_add_timer(timer);
1120 }
1121
1122 /*
1123  * Called with rpc->crpc_lock held.
1124  *
1125  * Upon exit the RPC expiry timer is not queued and the handler is not
1126  * running on any CPU.
1127  */
1128 static void
1129 srpc_del_client_rpc_timer(struct srpc_client_rpc *rpc)
1130 {
1131         /* timer not planted or already exploded */
1132         if (rpc->crpc_timeout == 0)
1133                 return;
1134
1135         /* timer successfully defused */
1136         if (stt_del_timer(&rpc->crpc_timer))
1137                 return;
1138
1139         /* timer detonated, wait for it to explode */
1140         while (rpc->crpc_timeout != 0) {
1141                 spin_unlock(&rpc->crpc_lock);
1142
1143                 schedule();
1144
1145                 spin_lock(&rpc->crpc_lock);
1146         }
1147 }
1148
1149 static void
1150 srpc_client_rpc_done(struct srpc_client_rpc *rpc, int status)
1151 {
1152         struct swi_workitem *wi = &rpc->crpc_wi;
1153
1154         spin_lock(&rpc->crpc_lock);
1155
1156         rpc->crpc_closed = 1;
1157         if (rpc->crpc_status == 0)
1158                 rpc->crpc_status = status;
1159
1160         srpc_del_client_rpc_timer(rpc);
1161
1162         CDEBUG_LIMIT((status == 0) ? D_NET : D_NETERROR,
1163                      "Client RPC done: service %d, peer %s, status %s:%d:%d\n",
1164                      rpc->crpc_service, libcfs_id2str(rpc->crpc_dest),
1165                      swi_state2str(wi->swi_state), rpc->crpc_aborted, status);
1166
1167         /*
1168          * No one can schedule me now since:
1169          * - RPC timer has been defused.
1170          * - all LNet events have been fired.
1171          * - crpc_closed has been set, preventing srpc_abort_rpc from
1172          *   scheduling me.
1173          * Cancel pending schedules and prevent future schedule attempts:
1174          */
1175         LASSERT(!srpc_event_pending(rpc));
1176         wi->swi_state = SWI_STATE_DONE;
1177
1178         spin_unlock(&rpc->crpc_lock);
1179
1180         (*rpc->crpc_done)(rpc);
1181 }
1182
1183 /* sends an outgoing RPC */
1184 void
1185 srpc_send_rpc(struct swi_workitem *wi)
1186 {
1187         int rc = 0;
1188         struct srpc_client_rpc *rpc;
1189         struct srpc_msg *reply;
1190         int do_bulk;
1191
1192         LASSERT(wi != NULL);
1193
1194         rpc = container_of(wi, struct srpc_client_rpc, crpc_wi);
1195
1196         LASSERT(rpc != NULL);
1197         LASSERT(wi == &rpc->crpc_wi);
1198
1199         reply = &rpc->crpc_replymsg;
1200         do_bulk = rpc->crpc_bulk.bk_niov > 0;
1201
1202         spin_lock(&rpc->crpc_lock);
1203         if (wi->swi_state == SWI_STATE_DONE) {
1204                 spin_unlock(&rpc->crpc_lock);
1205                 return;
1206         }
1207
1208         if (rpc->crpc_aborted) {
1209                 spin_unlock(&rpc->crpc_lock);
1210                 goto abort;
1211         }
1212
1213         spin_unlock(&rpc->crpc_lock);
1214
1215         switch (wi->swi_state) {
1216         default:
1217                 LBUG();
1218         case SWI_STATE_NEWBORN:
1219                 LASSERT(!srpc_event_pending(rpc));
1220
1221                 rc = srpc_prepare_reply(rpc);
1222                 if (rc != 0) {
1223                         srpc_client_rpc_done(rpc, rc);
1224                         return;
1225                 }
1226
1227                 rc = srpc_prepare_bulk(rpc);
1228                 if (rc != 0)
1229                         break;
1230
1231                 wi->swi_state = SWI_STATE_REQUEST_SUBMITTED;
1232                 rc = srpc_send_request(rpc);
1233                 break;
1234
1235         case SWI_STATE_REQUEST_SUBMITTED:
1236                 /* CAVEAT EMPTOR: rqtev, rpyev, and bulkev may come in any
1237                  * order; however, they're processed in a strict order:
1238                  * rqt, rpy, and bulk.
1239                  */
1240                 if (!rpc->crpc_reqstev.ev_fired)
1241                         break;
1242
1243                 rc = rpc->crpc_reqstev.ev_status;
1244                 if (rc != 0)
1245                         break;
1246
1247                 wi->swi_state = SWI_STATE_REQUEST_SENT;
1248                 fallthrough;
1249         case SWI_STATE_REQUEST_SENT: {
1250                 enum srpc_msg_type type;
1251
1252                 type = srpc_service2reply(rpc->crpc_service);
1253
1254                 if (!rpc->crpc_replyev.ev_fired)
1255                         break;
1256
1257                 rc = rpc->crpc_replyev.ev_status;
1258                 if (rc != 0)
1259                         break;
1260
1261                 srpc_unpack_msg_hdr(reply);
1262                 if (reply->msg_type != type ||
1263                     (reply->msg_magic != SRPC_MSG_MAGIC &&
1264                      reply->msg_magic != __swab32(SRPC_MSG_MAGIC))) {
1265                         CWARN("Bad message from %s: type %u (%d expected), magic %u (%d expected).\n",
1266                               libcfs_id2str(rpc->crpc_dest),
1267                               reply->msg_type, type,
1268                               reply->msg_magic, SRPC_MSG_MAGIC);
1269                         rc = -EBADMSG;
1270                         break;
1271                 }
1272
1273                 if (do_bulk && reply->msg_body.reply.status != 0) {
1274                         CWARN("Remote error %d at %s, unlink bulk buffer in case peer didn't initiate bulk transfer\n",
1275                               reply->msg_body.reply.status,
1276                               libcfs_id2str(rpc->crpc_dest));
1277                         LNetMDUnlink(rpc->crpc_bulk.bk_mdh);
1278                 }
1279
1280                 wi->swi_state = SWI_STATE_REPLY_RECEIVED;
1281         }
1282         fallthrough;
1283         case SWI_STATE_REPLY_RECEIVED:
1284                 if (do_bulk && !rpc->crpc_bulkev.ev_fired)
1285                         break;
1286
1287                 rc = do_bulk ? rpc->crpc_bulkev.ev_status : 0;
1288
1289                 /* Bulk buffer was unlinked due to remote error. Clear error
1290                  * since reply buffer still contains valid data.
1291                  * NB rpc->crpc_done shouldn't look into bulk data in case of
1292                  * remote error.
1293                  */
1294                 if (do_bulk && rpc->crpc_bulkev.ev_lnet == LNET_EVENT_UNLINK &&
1295                     rpc->crpc_status == 0 && reply->msg_body.reply.status != 0)
1296                         rc = 0;
1297
1298                 wi->swi_state = SWI_STATE_DONE;
1299                 srpc_client_rpc_done(rpc, rc);
1300                 return;
1301         }
1302
1303         if (rc != 0) {
1304                 spin_lock(&rpc->crpc_lock);
1305                 srpc_abort_rpc(rpc, rc);
1306                 spin_unlock(&rpc->crpc_lock);
1307         }
1308
1309 abort:
1310         if (rpc->crpc_aborted) {
1311                 LNetMDUnlink(rpc->crpc_reqstmdh);
1312                 LNetMDUnlink(rpc->crpc_replymdh);
1313                 LNetMDUnlink(rpc->crpc_bulk.bk_mdh);
1314
1315                 if (!srpc_event_pending(rpc)) {
1316                         srpc_client_rpc_done(rpc, -EINTR);
1317                         return;
1318                 }
1319         }
1320 }
1321
1322 struct srpc_client_rpc *
1323 srpc_create_client_rpc(struct lnet_process_id peer, int service,
1324                        int nbulkiov, int bulklen,
1325                        void (*rpc_done)(struct srpc_client_rpc *),
1326                        void (*rpc_fini)(struct srpc_client_rpc *), void *priv)
1327 {
1328         struct srpc_client_rpc *rpc;
1329
1330         LIBCFS_ALLOC(rpc, offsetof(struct srpc_client_rpc,
1331                                    crpc_bulk.bk_iovs[nbulkiov]));
1332         if (rpc == NULL)
1333                 return NULL;
1334
1335         srpc_init_client_rpc(rpc, peer, service, nbulkiov,
1336                              bulklen, rpc_done, rpc_fini, priv);
1337         return rpc;
1338 }
1339
1340 /* called with rpc->crpc_lock held */
1341 void
1342 srpc_abort_rpc(struct srpc_client_rpc *rpc, int why)
1343 {
1344         LASSERT(why != 0);
1345
1346         if (rpc->crpc_aborted || /* already aborted */
1347             rpc->crpc_closed)    /* callback imminent */
1348                 return;
1349
1350         CDEBUG(D_NET,
1351                "Aborting RPC: service %d, peer %s, state %s, why %d\n",
1352                rpc->crpc_service, libcfs_id2str(rpc->crpc_dest),
1353                swi_state2str(rpc->crpc_wi.swi_state), why);
1354
1355         rpc->crpc_aborted = 1;
1356         rpc->crpc_status  = why;
1357         swi_schedule_workitem(&rpc->crpc_wi);
1358 }
1359
1360 /* called with rpc->crpc_lock held */
1361 void
1362 srpc_post_rpc(struct srpc_client_rpc *rpc)
1363 {
1364         LASSERT(!rpc->crpc_aborted);
1365         LASSERT(srpc_data.rpc_state == SRPC_STATE_RUNNING);
1366
1367         CDEBUG(D_NET, "Posting RPC: peer %s, service %d, timeout %d\n",
1368                libcfs_id2str(rpc->crpc_dest), rpc->crpc_service,
1369                rpc->crpc_timeout);
1370
1371         srpc_add_client_rpc_timer(rpc);
1372         swi_schedule_workitem(&rpc->crpc_wi);
1373 }
1374
1375
1376 int
1377 srpc_send_reply(struct srpc_server_rpc *rpc)
1378 {
1379         struct srpc_event *ev = &rpc->srpc_ev;
1380         struct srpc_msg *msg = &rpc->srpc_replymsg;
1381         struct srpc_buffer *buffer = rpc->srpc_reqstbuf;
1382         struct srpc_service_cd *scd = rpc->srpc_scd;
1383         struct srpc_service *sv = scd->scd_svc;
1384         __u64 rpyid;
1385         int rc;
1386
1387         LASSERT(buffer != NULL);
1388         rpyid = buffer->buf_msg.msg_body.reqst.rpyid;
1389
1390         spin_lock(&scd->scd_lock);
1391
1392         if (!sv->sv_shuttingdown && !srpc_serv_is_framework(sv)) {
1393                 /* Repost buffer before replying since test client
1394                  * might send me another RPC once it gets the reply
1395                  */
1396                 if (srpc_service_post_buffer(scd, buffer) != 0)
1397                         CWARN("Failed to repost %s buffer\n", sv->sv_name);
1398                 rpc->srpc_reqstbuf = NULL;
1399         }
1400
1401         spin_unlock(&scd->scd_lock);
1402
1403         ev->ev_fired = 0;
1404         ev->ev_data  = rpc;
1405         ev->ev_type  = SRPC_REPLY_SENT;
1406
1407         msg->msg_magic   = SRPC_MSG_MAGIC;
1408         msg->msg_version = SRPC_MSG_VERSION;
1409         msg->msg_type    = srpc_service2reply(sv->sv_id);
1410
1411         rc = srpc_post_active_rdma(SRPC_RDMA_PORTAL, rpyid, msg,
1412                                    sizeof(*msg), LNET_MD_OP_PUT,
1413                                    rpc->srpc_peer, rpc->srpc_self,
1414                                    &rpc->srpc_replymdh, ev);
1415         if (rc != 0)
1416                 ev->ev_fired = 1;  /* no more event expected */
1417         return rc;
1418 }
1419
1420 /* when in kernel always called with LNET_LOCK() held, and in thread context */
1421 static void
1422 srpc_lnet_ev_handler(struct lnet_event *ev)
1423 {
1424         struct srpc_service_cd *scd;
1425         struct srpc_event *rpcev = ev->md_user_ptr;
1426         struct srpc_client_rpc *crpc;
1427         struct srpc_server_rpc *srpc;
1428         struct srpc_buffer *buffer;
1429         struct srpc_service *sv;
1430         struct srpc_msg *msg;
1431         enum srpc_msg_type type;
1432
1433         LASSERT(!in_interrupt());
1434
1435         if (ev->status != 0) {
1436                 __u32 errors;
1437
1438
1439                 if (ev->status != -ECANCELED) /* cancellation is not error */
1440                         errors = atomic_inc_return(&RPC_STAT32(SRPC_ERROR));
1441                 else
1442                         errors = atomic_read(&RPC_STAT32(SRPC_ERROR));
1443
1444                 CNETERR("LNet event status %d type %d, RPC errors %u\n",
1445                         ev->status, ev->type, errors);
1446         }
1447
1448         rpcev->ev_lnet = ev->type;
1449
1450         switch (rpcev->ev_type) {
1451         default:
1452                 CERROR("Unknown event: status %d, type %d, lnet %d\n",
1453                        rpcev->ev_status, rpcev->ev_type, rpcev->ev_lnet);
1454                 LBUG();
1455                 fallthrough;
1456         case SRPC_REQUEST_SENT:
1457                 if (ev->status == 0 && ev->type != LNET_EVENT_UNLINK)
1458                         atomic_inc(&RPC_STAT32(SRPC_RPC_SENT));
1459
1460                 fallthrough;
1461         case SRPC_REPLY_RCVD:
1462         case SRPC_BULK_REQ_RCVD:
1463                 crpc = rpcev->ev_data;
1464
1465                 if (rpcev != &crpc->crpc_reqstev &&
1466                     rpcev != &crpc->crpc_replyev &&
1467                     rpcev != &crpc->crpc_bulkev) {
1468                         CERROR("rpcev %p, crpc %p, reqstev %p, replyev %p, bulkev %p\n",
1469                                rpcev, crpc, &crpc->crpc_reqstev,
1470                                &crpc->crpc_replyev, &crpc->crpc_bulkev);
1471                         CERROR("Bad event: status %d, type %d, lnet %d\n",
1472                                rpcev->ev_status, rpcev->ev_type,
1473                                rpcev->ev_lnet);
1474                         LBUG();
1475                 }
1476
1477                 spin_lock(&crpc->crpc_lock);
1478
1479                 LASSERT(rpcev->ev_fired == 0);
1480                 rpcev->ev_fired  = 1;
1481                 rpcev->ev_status = (ev->type == LNET_EVENT_UNLINK) ?
1482                                    -EINTR : ev->status;
1483                 swi_schedule_workitem(&crpc->crpc_wi);
1484
1485                 spin_unlock(&crpc->crpc_lock);
1486                 break;
1487
1488         case SRPC_REQUEST_RCVD:
1489                 scd = rpcev->ev_data;
1490                 sv = scd->scd_svc;
1491
1492                 LASSERT(rpcev == &scd->scd_ev);
1493
1494                 spin_lock(&scd->scd_lock);
1495
1496                 LASSERT(ev->unlinked);
1497                 LASSERT(ev->type == LNET_EVENT_PUT ||
1498                         ev->type == LNET_EVENT_UNLINK);
1499                 LASSERT(ev->type != LNET_EVENT_UNLINK ||
1500                         sv->sv_shuttingdown);
1501
1502                 buffer = container_of(ev->md_start, struct srpc_buffer,
1503                                       buf_msg);
1504                 buffer->buf_peer = lnet_pid_to_pid4(&ev->source);
1505                 buffer->buf_self = lnet_nid_to_nid4(&ev->target.nid);
1506
1507                 LASSERT(scd->scd_buf_nposted > 0);
1508                 scd->scd_buf_nposted--;
1509
1510                 if (sv->sv_shuttingdown) {
1511                         /* Leave buffer on scd->scd_buf_nposted since
1512                          * srpc_finish_service needs to traverse it.
1513                          */
1514                         spin_unlock(&scd->scd_lock);
1515                         break;
1516                 }
1517
1518                 if (scd->scd_buf_err_stamp != 0 &&
1519                     scd->scd_buf_err_stamp < ktime_get_real_seconds()) {
1520                         /* re-enable adding buffer */
1521                         scd->scd_buf_err_stamp = 0;
1522                         scd->scd_buf_err = 0;
1523                 }
1524
1525                 if (scd->scd_buf_err == 0 && /* adding buffer is enabled */
1526                     scd->scd_buf_adjust == 0 &&
1527                     scd->scd_buf_nposted < scd->scd_buf_low) {
1528                         scd->scd_buf_adjust = max(scd->scd_buf_total / 2,
1529                                                   SFW_TEST_WI_MIN);
1530                         swi_schedule_workitem(&scd->scd_buf_wi);
1531                 }
1532
1533                 list_del(&buffer->buf_list); /* from scd->scd_buf_posted */
1534                 msg = &buffer->buf_msg;
1535                 type = srpc_service2request(sv->sv_id);
1536
1537                 if (ev->status != 0 || ev->mlength != sizeof(*msg) ||
1538                     (msg->msg_type != type &&
1539                      msg->msg_type != __swab32(type)) ||
1540                     (msg->msg_magic != SRPC_MSG_MAGIC &&
1541                      msg->msg_magic != __swab32(SRPC_MSG_MAGIC))) {
1542                         CERROR("Dropping RPC (%s) from %s: status %d mlength %d type %u magic %u.\n",
1543                                sv->sv_name, libcfs_idstr(&ev->initiator),
1544                                ev->status, ev->mlength,
1545                                msg->msg_type, msg->msg_magic);
1546
1547                         /* NB can't call srpc_service_recycle_buffer here since
1548                          * it may call LNetM[DE]Attach. The invalid magic tells
1549                          * srpc_handle_rpc to drop this RPC
1550                          */
1551                         msg->msg_magic = 0;
1552                 }
1553
1554                 if (!list_empty(&scd->scd_rpc_free)) {
1555                         srpc = list_first_entry(&scd->scd_rpc_free,
1556                                                 struct srpc_server_rpc,
1557                                                 srpc_list);
1558                         list_del(&srpc->srpc_list);
1559
1560                         srpc_init_server_rpc(srpc, scd, buffer);
1561                         list_add_tail(&srpc->srpc_list,
1562                                       &scd->scd_rpc_active);
1563                         swi_schedule_workitem(&srpc->srpc_wi);
1564                 } else {
1565                         list_add_tail(&buffer->buf_list,
1566                                       &scd->scd_buf_blocked);
1567                 }
1568
1569                 spin_unlock(&scd->scd_lock);
1570
1571                 atomic_inc(&RPC_STAT32(SRPC_RPC_RCVD));
1572                 break;
1573
1574         case SRPC_BULK_GET_RPLD:
1575                 LASSERT(ev->type == LNET_EVENT_SEND ||
1576                         ev->type == LNET_EVENT_REPLY ||
1577                         ev->type == LNET_EVENT_UNLINK);
1578
1579                 if (!ev->unlinked)
1580                         break; /* wait for final event */
1581                 fallthrough;
1582         case SRPC_BULK_PUT_SENT:
1583                 if (ev->status == 0 && ev->type != LNET_EVENT_UNLINK) {
1584                         atomic64_t *data;
1585
1586                         if (rpcev->ev_type == SRPC_BULK_GET_RPLD)
1587                                 data = &srpc_data.rpc_counters64[SRPC_BULK_GET];
1588                         else
1589                                 data = &srpc_data.rpc_counters64[SRPC_BULK_PUT];
1590
1591                         atomic64_add(ev->mlength, data);
1592                 }
1593                 fallthrough;
1594         case SRPC_REPLY_SENT:
1595                 srpc = rpcev->ev_data;
1596                 scd  = srpc->srpc_scd;
1597
1598                 LASSERT(rpcev == &srpc->srpc_ev);
1599
1600                 spin_lock(&scd->scd_lock);
1601
1602                 rpcev->ev_fired  = 1;
1603                 rpcev->ev_status = (ev->type == LNET_EVENT_UNLINK) ?
1604                                    -EINTR : ev->status;
1605                 swi_schedule_workitem(&srpc->srpc_wi);
1606
1607                 spin_unlock(&scd->scd_lock);
1608                 break;
1609         }
1610 }
1611
1612
1613 int
1614 srpc_startup (void)
1615 {
1616         int rc;
1617
1618         memset(&srpc_data, 0, sizeof(struct smoketest_rpc));
1619         spin_lock_init(&srpc_data.rpc_glock);
1620
1621         /* 1 second pause to avoid timestamp reuse */
1622         schedule_timeout_uninterruptible(cfs_time_seconds(1));
1623         atomic64_set(&srpc_data.rpc_matchbits,
1624                         ((__u64)ktime_get_real_seconds() << 48));
1625
1626         srpc_data.rpc_state = SRPC_STATE_NONE;
1627
1628         rc = LNetNIInit(LNET_PID_LUSTRE);
1629         if (rc < 0) {
1630                 CERROR("LNetNIInit() has failed: %d\n", rc);
1631                 return rc;
1632         }
1633
1634         srpc_data.rpc_state = SRPC_STATE_NI_INIT;
1635
1636         srpc_data.rpc_lnet_handler = srpc_lnet_ev_handler;
1637
1638         rc = LNetSetLazyPortal(SRPC_FRAMEWORK_REQUEST_PORTAL);
1639         LASSERT(rc == 0);
1640         rc = LNetSetLazyPortal(SRPC_REQUEST_PORTAL);
1641         LASSERT(rc == 0);
1642
1643         srpc_data.rpc_state = SRPC_STATE_EQ_INIT;
1644
1645         rc = stt_startup();
1646
1647         if (rc != 0)
1648                 srpc_shutdown();
1649         else
1650                 srpc_data.rpc_state = SRPC_STATE_RUNNING;
1651
1652         return rc;
1653 }
1654
1655 void
1656 srpc_shutdown (void)
1657 {
1658         int i;
1659         int rc;
1660         int state;
1661
1662         state = srpc_data.rpc_state;
1663         srpc_data.rpc_state = SRPC_STATE_STOPPING;
1664
1665         switch (state) {
1666         default:
1667                 LBUG();
1668                 fallthrough;
1669         case SRPC_STATE_RUNNING:
1670                 spin_lock(&srpc_data.rpc_glock);
1671
1672                 for (i = 0; i <= SRPC_SERVICE_MAX_ID; i++) {
1673                         struct srpc_service *sv = srpc_data.rpc_services[i];
1674
1675                         LASSERTF(sv == NULL,
1676                                  "service not empty: id %d, name %s\n",
1677                                  i, sv->sv_name);
1678                 }
1679
1680                 spin_unlock(&srpc_data.rpc_glock);
1681
1682                 stt_shutdown();
1683                 fallthrough;
1684
1685         case SRPC_STATE_EQ_INIT:
1686                 rc = LNetClearLazyPortal(SRPC_FRAMEWORK_REQUEST_PORTAL);
1687                 rc = LNetClearLazyPortal(SRPC_REQUEST_PORTAL);
1688                 LASSERT(rc == 0);
1689                 lnet_assert_handler_unused(srpc_data.rpc_lnet_handler);
1690                 fallthrough;
1691
1692         case SRPC_STATE_NI_INIT:
1693                 LNetNIFini();
1694         }
1695 }