GNU Linux-libre 4.9.333-gnu1
[releases.git] / drivers / staging / lustre / lustre / include / lustre_net.h
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) 2010, 2015, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  */
32 /** \defgroup PtlRPC Portal RPC and networking module.
33  *
34  * PortalRPC is the layer used by rest of lustre code to achieve network
35  * communications: establish connections with corresponding export and import
36  * states, listen for a service, send and receive RPCs.
37  * PortalRPC also includes base recovery framework: packet resending and
38  * replaying, reconnections, pinger.
39  *
40  * PortalRPC utilizes LNet as its transport layer.
41  *
42  * @{
43  */
44
45 #ifndef _LUSTRE_NET_H
46 #define _LUSTRE_NET_H
47
48 /** \defgroup net net
49  *
50  * @{
51  */
52
53 #include "../../include/linux/libcfs/libcfs.h"
54 #include "../../include/linux/lnet/nidstr.h"
55 #include "../../include/linux/lnet/api.h"
56 #include "lustre/lustre_idl.h"
57 #include "lustre_ha.h"
58 #include "lustre_sec.h"
59 #include "lustre_import.h"
60 #include "lprocfs_status.h"
61 #include "lu_object.h"
62 #include "lustre_req_layout.h"
63
64 #include "obd_support.h"
65 #include "lustre_ver.h"
66
67 /* MD flags we _always_ use */
68 #define PTLRPC_MD_OPTIONS  0
69
70 /**
71  * Max # of bulk operations in one request.
72  * In order for the client and server to properly negotiate the maximum
73  * possible transfer size, PTLRPC_BULK_OPS_COUNT must be a power-of-two
74  * value.  The client is free to limit the actual RPC size for any bulk
75  * transfer via cl_max_pages_per_rpc to some non-power-of-two value.
76  */
77 #define PTLRPC_BULK_OPS_BITS    2
78 #define PTLRPC_BULK_OPS_COUNT   (1U << PTLRPC_BULK_OPS_BITS)
79 /**
80  * PTLRPC_BULK_OPS_MASK is for the convenience of the client only, and
81  * should not be used on the server at all.  Otherwise, it imposes a
82  * protocol limitation on the maximum RPC size that can be used by any
83  * RPC sent to that server in the future.  Instead, the server should
84  * use the negotiated per-client ocd_brw_size to determine the bulk
85  * RPC count.
86  */
87 #define PTLRPC_BULK_OPS_MASK    (~((__u64)PTLRPC_BULK_OPS_COUNT - 1))
88
89 /**
90  * Define maxima for bulk I/O.
91  *
92  * A single PTLRPC BRW request is sent via up to PTLRPC_BULK_OPS_COUNT
93  * of LNET_MTU sized RDMA transfers.  Clients and servers negotiate the
94  * currently supported maximum between peers at connect via ocd_brw_size.
95  */
96 #define PTLRPC_MAX_BRW_BITS     (LNET_MTU_BITS + PTLRPC_BULK_OPS_BITS)
97 #define PTLRPC_MAX_BRW_SIZE     (1 << PTLRPC_MAX_BRW_BITS)
98 #define PTLRPC_MAX_BRW_PAGES    (PTLRPC_MAX_BRW_SIZE >> PAGE_SHIFT)
99
100 #define ONE_MB_BRW_SIZE         (1 << LNET_MTU_BITS)
101 #define MD_MAX_BRW_SIZE         (1 << LNET_MTU_BITS)
102 #define MD_MAX_BRW_PAGES        (MD_MAX_BRW_SIZE >> PAGE_SHIFT)
103 #define DT_MAX_BRW_SIZE         PTLRPC_MAX_BRW_SIZE
104 #define DT_MAX_BRW_PAGES        (DT_MAX_BRW_SIZE >> PAGE_SHIFT)
105 #define OFD_MAX_BRW_SIZE        (1 << LNET_MTU_BITS)
106
107 /* When PAGE_SIZE is a constant, we can check our arithmetic here with cpp! */
108 # if ((PTLRPC_MAX_BRW_PAGES & (PTLRPC_MAX_BRW_PAGES - 1)) != 0)
109 #  error "PTLRPC_MAX_BRW_PAGES isn't a power of two"
110 # endif
111 # if (PTLRPC_MAX_BRW_SIZE != (PTLRPC_MAX_BRW_PAGES * PAGE_SIZE))
112 #  error "PTLRPC_MAX_BRW_SIZE isn't PTLRPC_MAX_BRW_PAGES * PAGE_SIZE"
113 # endif
114 # if (PTLRPC_MAX_BRW_SIZE > LNET_MTU * PTLRPC_BULK_OPS_COUNT)
115 #  error "PTLRPC_MAX_BRW_SIZE too big"
116 # endif
117 # if (PTLRPC_MAX_BRW_PAGES > LNET_MAX_IOV * PTLRPC_BULK_OPS_COUNT)
118 #  error "PTLRPC_MAX_BRW_PAGES too big"
119 # endif
120
121 #define PTLRPC_NTHRS_INIT       2
122
123 /**
124  * Buffer Constants
125  *
126  * Constants determine how memory is used to buffer incoming service requests.
127  *
128  * ?_NBUFS            # buffers to allocate when growing the pool
129  * ?_BUFSIZE        # bytes in a single request buffer
130  * ?_MAXREQSIZE  # maximum request service will receive
131  *
132  * When fewer than ?_NBUFS/2 buffers are posted for receive, another chunk
133  * of ?_NBUFS is added to the pool.
134  *
135  * Messages larger than ?_MAXREQSIZE are dropped.  Request buffers are
136  * considered full when less than ?_MAXREQSIZE is left in them.
137  */
138 /**
139  * Thread Constants
140  *
141  * Constants determine how threads are created for ptlrpc service.
142  *
143  * ?_NTHRS_INIT         # threads to create for each service partition on
144  *                        initializing. If it's non-affinity service and
145  *                        there is only one partition, it's the overall #
146  *                        threads for the service while initializing.
147  * ?_NTHRS_BASE         # threads should be created at least for each
148  *                        ptlrpc partition to keep the service healthy.
149  *                        It's the low-water mark of threads upper-limit
150  *                        for each partition.
151  * ?_THR_FACTOR  # threads can be added on threads upper-limit for
152  *                        each CPU core. This factor is only for reference,
153  *                        we might decrease value of factor if number of cores
154  *                        per CPT is above a limit.
155  * ?_NTHRS_MAX          # overall threads can be created for a service,
156  *                        it's a soft limit because if service is running
157  *                        on machine with hundreds of cores and tens of
158  *                        CPU partitions, we need to guarantee each partition
159  *                        has ?_NTHRS_BASE threads, which means total threads
160  *                        will be ?_NTHRS_BASE * number_of_cpts which can
161  *                        exceed ?_NTHRS_MAX.
162  *
163  * Examples
164  *
165  * #define MDS_NTHRS_INIT       2
166  * #define MDS_NTHRS_BASE       64
167  * #define MDS_NTHRS_FACTOR     8
168  * #define MDS_NTHRS_MAX        1024
169  *
170  * Example 1):
171  * ---------------------------------------------------------------------
172  * Server(A) has 16 cores, user configured it to 4 partitions so each
173  * partition has 4 cores, then actual number of service threads on each
174  * partition is:
175  *     MDS_NTHRS_BASE(64) + cores(4) * MDS_NTHRS_FACTOR(8) = 96
176  *
177  * Total number of threads for the service is:
178  *     96 * partitions(4) = 384
179  *
180  * Example 2):
181  * ---------------------------------------------------------------------
182  * Server(B) has 32 cores, user configured it to 4 partitions so each
183  * partition has 8 cores, then actual number of service threads on each
184  * partition is:
185  *     MDS_NTHRS_BASE(64) + cores(8) * MDS_NTHRS_FACTOR(8) = 128
186  *
187  * Total number of threads for the service is:
188  *     128 * partitions(4) = 512
189  *
190  * Example 3):
191  * ---------------------------------------------------------------------
192  * Server(B) has 96 cores, user configured it to 8 partitions so each
193  * partition has 12 cores, then actual number of service threads on each
194  * partition is:
195  *     MDS_NTHRS_BASE(64) + cores(12) * MDS_NTHRS_FACTOR(8) = 160
196  *
197  * Total number of threads for the service is:
198  *     160 * partitions(8) = 1280
199  *
200  * However, it's above the soft limit MDS_NTHRS_MAX, so we choose this number
201  * as upper limit of threads number for each partition:
202  *     MDS_NTHRS_MAX(1024) / partitions(8) = 128
203  *
204  * Example 4):
205  * ---------------------------------------------------------------------
206  * Server(C) have a thousand of cores and user configured it to 32 partitions
207  *     MDS_NTHRS_BASE(64) * 32 = 2048
208  *
209  * which is already above soft limit MDS_NTHRS_MAX(1024), but we still need
210  * to guarantee that each partition has at least MDS_NTHRS_BASE(64) threads
211  * to keep service healthy, so total number of threads will just be 2048.
212  *
213  * NB: we don't suggest to choose server with that many cores because backend
214  *     filesystem itself, buffer cache, or underlying network stack might
215  *     have some SMP scalability issues at that large scale.
216  *
217  *     If user already has a fat machine with hundreds or thousands of cores,
218  *     there are two choices for configuration:
219  *     a) create CPU table from subset of all CPUs and run Lustre on
220  *      top of this subset
221  *     b) bind service threads on a few partitions, see modparameters of
222  *      MDS and OSS for details
223 *
224  * NB: these calculations (and examples below) are simplified to help
225  *     understanding, the real implementation is a little more complex,
226  *     please see ptlrpc_server_nthreads_check() for details.
227  *
228  */
229
230  /*
231   * LDLM threads constants:
232   *
233   * Given 8 as factor and 24 as base threads number
234   *
235   * example 1)
236   * On 4-core machine we will have 24 + 8 * 4 = 56 threads.
237   *
238   * example 2)
239   * On 8-core machine with 2 partitions we will have 24 + 4 * 8 = 56
240   * threads for each partition and total threads number will be 112.
241   *
242   * example 3)
243   * On 64-core machine with 8 partitions we will need LDLM_NTHRS_BASE(24)
244   * threads for each partition to keep service healthy, so total threads
245   * number should be 24 * 8 = 192.
246   *
247   * So with these constants, threads number will be at the similar level
248   * of old versions, unless target machine has over a hundred cores
249   */
250 #define LDLM_THR_FACTOR         8
251 #define LDLM_NTHRS_INIT         PTLRPC_NTHRS_INIT
252 #define LDLM_NTHRS_BASE         24
253 #define LDLM_NTHRS_MAX          (num_online_cpus() == 1 ? 64 : 128)
254
255 #define LDLM_BL_THREADS   LDLM_NTHRS_AUTO_INIT
256 #define LDLM_CLIENT_NBUFS 1
257 #define LDLM_SERVER_NBUFS 64
258 #define LDLM_BUFSIZE      (8 * 1024)
259 #define LDLM_MAXREQSIZE   (5 * 1024)
260 #define LDLM_MAXREPSIZE   (1024)
261
262 #define MDS_MAXREQSIZE          (5 * 1024)      /* >= 4736 */
263
264 /**
265  * FIEMAP request can be 4K+ for now
266  */
267 #define OST_MAXREQSIZE          (16 * 1024)
268
269 /* Macro to hide a typecast. */
270 #define ptlrpc_req_async_args(req) ((void *)&req->rq_async_args)
271
272 struct ptlrpc_replay_async_args {
273         int             praa_old_state;
274         int             praa_old_status;
275 };
276
277 /**
278  * Structure to single define portal connection.
279  */
280 struct ptlrpc_connection {
281         /** linkage for connections hash table */
282         struct hlist_node       c_hash;
283         /** Our own lnet nid for this connection */
284         lnet_nid_t            c_self;
285         /** Remote side nid for this connection */
286         lnet_process_id_t       c_peer;
287         /** UUID of the other side */
288         struct obd_uuid  c_remote_uuid;
289         /** reference counter for this connection */
290         atomic_t            c_refcount;
291 };
292
293 /** Client definition for PortalRPC */
294 struct ptlrpc_client {
295         /** What lnet portal does this client send messages to by default */
296         __u32              cli_request_portal;
297         /** What portal do we expect replies on */
298         __u32              cli_reply_portal;
299         /** Name of the client */
300         char               *cli_name;
301 };
302
303 /** state flags of requests */
304 /* XXX only ones left are those used by the bulk descs as well! */
305 #define PTL_RPC_FL_INTR      (1 << 0)  /* reply wait was interrupted by user */
306 #define PTL_RPC_FL_TIMEOUT   (1 << 7)  /* request timed out waiting for reply */
307
308 #define REQ_MAX_ACK_LOCKS 8
309
310 union ptlrpc_async_args {
311         /**
312          * Scratchpad for passing args to completion interpreter. Users
313          * cast to the struct of their choosing, and CLASSERT that this is
314          * big enough.  For _tons_ of context, kmalloc a struct and store
315          * a pointer to it here.  The pointer_arg ensures this struct is at
316          * least big enough for that.
317          */
318         void      *pointer_arg[11];
319         __u64      space[7];
320 };
321
322 struct ptlrpc_request_set;
323 typedef int (*set_interpreter_func)(struct ptlrpc_request_set *, void *, int);
324 typedef int (*set_producer_func)(struct ptlrpc_request_set *, void *);
325
326 /**
327  * Definition of request set structure.
328  * Request set is a list of requests (not necessary to the same target) that
329  * once populated with RPCs could be sent in parallel.
330  * There are two kinds of request sets. General purpose and with dedicated
331  * serving thread. Example of the latter is ptlrpcd set.
332  * For general purpose sets once request set started sending it is impossible
333  * to add new requests to such set.
334  * Provides a way to call "completion callbacks" when all requests in the set
335  * returned.
336  */
337 struct ptlrpc_request_set {
338         atomic_t          set_refcount;
339         /** number of in queue requests */
340         atomic_t          set_new_count;
341         /** number of uncompleted requests */
342         atomic_t          set_remaining;
343         /** wait queue to wait on for request events */
344         wait_queue_head_t          set_waitq;
345         wait_queue_head_t         *set_wakeup_ptr;
346         /** List of requests in the set */
347         struct list_head            set_requests;
348         /**
349          * List of completion callbacks to be called when the set is completed
350          * This is only used if \a set_interpret is NULL.
351          * Links struct ptlrpc_set_cbdata.
352          */
353         struct list_head            set_cblist;
354         /** Completion callback, if only one. */
355         set_interpreter_func  set_interpret;
356         /** opaq argument passed to completion \a set_interpret callback. */
357         void             *set_arg;
358         /**
359          * Lock for \a set_new_requests manipulations
360          * locked so that any old caller can communicate requests to
361          * the set holder who can then fold them into the lock-free set
362          */
363         spinlock_t              set_new_req_lock;
364         /** List of new yet unsent requests. Only used with ptlrpcd now. */
365         struct list_head            set_new_requests;
366
367         /** rq_status of requests that have been freed already */
368         int                set_rc;
369         /** Additional fields used by the flow control extension */
370         /** Maximum number of RPCs in flight */
371         int                set_max_inflight;
372         /** Callback function used to generate RPCs */
373         set_producer_func     set_producer;
374         /** opaq argument passed to the producer callback */
375         void             *set_producer_arg;
376 };
377
378 /**
379  * Description of a single ptrlrpc_set callback
380  */
381 struct ptlrpc_set_cbdata {
382         /** List linkage item */
383         struct list_head              psc_item;
384         /** Pointer to interpreting function */
385         set_interpreter_func    psc_interpret;
386         /** Opaq argument to pass to the callback */
387         void               *psc_data;
388 };
389
390 struct ptlrpc_bulk_desc;
391 struct ptlrpc_service_part;
392 struct ptlrpc_service;
393
394 /**
395  * ptlrpc callback & work item stuff
396  */
397 struct ptlrpc_cb_id {
398         void   (*cbid_fn)(lnet_event_t *ev);     /* specific callback fn */
399         void    *cbid_arg;                    /* additional arg */
400 };
401
402 /** Maximum number of locks to fit into reply state */
403 #define RS_MAX_LOCKS 8
404 #define RS_DEBUG     0
405
406 /**
407  * Structure to define reply state on the server
408  * Reply state holds various reply message information. Also for "difficult"
409  * replies (rep-ack case) we store the state after sending reply and wait
410  * for the client to acknowledge the reception. In these cases locks could be
411  * added to the state for replay/failover consistency guarantees.
412  */
413 struct ptlrpc_reply_state {
414         /** Callback description */
415         struct ptlrpc_cb_id    rs_cb_id;
416         /** Linkage for list of all reply states in a system */
417         struct list_head             rs_list;
418         /** Linkage for list of all reply states on same export */
419         struct list_head             rs_exp_list;
420         /** Linkage for list of all reply states for same obd */
421         struct list_head             rs_obd_list;
422 #if RS_DEBUG
423         struct list_head             rs_debug_list;
424 #endif
425         /** A spinlock to protect the reply state flags */
426         spinlock_t              rs_lock;
427         /** Reply state flags */
428         unsigned long     rs_difficult:1; /* ACK/commit stuff */
429         unsigned long     rs_no_ack:1;    /* no ACK, even for
430                                            * difficult requests
431                                            */
432         unsigned long     rs_scheduled:1;     /* being handled? */
433         unsigned long     rs_scheduled_ever:1;/* any schedule attempts? */
434         unsigned long     rs_handled:1;  /* been handled yet? */
435         unsigned long     rs_on_net:1;   /* reply_out_callback pending? */
436         unsigned long     rs_prealloc:1; /* rs from prealloc list */
437         unsigned long     rs_committed:1;/* the transaction was committed
438                                           * and the rs was dispatched
439                                           */
440         /** Size of the state */
441         int                 rs_size;
442         /** opcode */
443         __u32             rs_opc;
444         /** Transaction number */
445         __u64             rs_transno;
446         /** xid */
447         __u64             rs_xid;
448         struct obd_export     *rs_export;
449         struct ptlrpc_service_part *rs_svcpt;
450         /** Lnet metadata handle for the reply */
451         lnet_handle_md_t       rs_md_h;
452         atomic_t           rs_refcount;
453
454         /** Context for the service thread */
455         struct ptlrpc_svc_ctx *rs_svc_ctx;
456         /** Reply buffer (actually sent to the client), encoded if needed */
457         struct lustre_msg     *rs_repbuf;       /* wrapper */
458         /** Size of the reply buffer */
459         int                 rs_repbuf_len;   /* wrapper buf length */
460         /** Size of the reply message */
461         int                 rs_repdata_len;  /* wrapper msg length */
462         /**
463          * Actual reply message. Its content is encrypted (if needed) to
464          * produce reply buffer for actual sending. In simple case
465          * of no network encryption we just set \a rs_repbuf to \a rs_msg
466          */
467         struct lustre_msg     *rs_msg;    /* reply message */
468
469         /** Number of locks awaiting client ACK */
470         int                 rs_nlocks;
471         /** Handles of locks awaiting client reply ACK */
472         struct lustre_handle   rs_locks[RS_MAX_LOCKS];
473         /** Lock modes of locks in \a rs_locks */
474         enum ldlm_mode      rs_modes[RS_MAX_LOCKS];
475 };
476
477 struct ptlrpc_thread;
478
479 /** RPC stages */
480 enum rq_phase {
481         RQ_PHASE_NEW        = 0xebc0de00,
482         RQ_PHASE_RPC        = 0xebc0de01,
483         RQ_PHASE_BULK      = 0xebc0de02,
484         RQ_PHASE_INTERPRET      = 0xebc0de03,
485         RQ_PHASE_COMPLETE       = 0xebc0de04,
486         RQ_PHASE_UNREG_RPC      = 0xebc0de05,
487         RQ_PHASE_UNREG_BULK     = 0xebc0de06,
488         RQ_PHASE_UNDEFINED      = 0xebc0de07
489 };
490
491 /** Type of request interpreter call-back */
492 typedef int (*ptlrpc_interpterer_t)(const struct lu_env *env,
493                                     struct ptlrpc_request *req,
494                                     void *arg, int rc);
495
496 /**
497  * Definition of request pool structure.
498  * The pool is used to store empty preallocated requests for the case
499  * when we would actually need to send something without performing
500  * any allocations (to avoid e.g. OOM).
501  */
502 struct ptlrpc_request_pool {
503         /** Locks the list */
504         spinlock_t prp_lock;
505         /** list of ptlrpc_request structs */
506         struct list_head prp_req_list;
507         /** Maximum message size that would fit into a request from this pool */
508         int prp_rq_size;
509         /** Function to allocate more requests for this pool */
510         int (*prp_populate)(struct ptlrpc_request_pool *, int);
511 };
512
513 struct lu_context;
514 struct lu_env;
515
516 struct ldlm_lock;
517
518 /**
519  * \defgroup nrs Network Request Scheduler
520  * @{
521  */
522 struct ptlrpc_nrs_policy;
523 struct ptlrpc_nrs_resource;
524 struct ptlrpc_nrs_request;
525
526 /**
527  * NRS control operations.
528  *
529  * These are common for all policies.
530  */
531 enum ptlrpc_nrs_ctl {
532         /**
533          * Not a valid opcode.
534          */
535         PTLRPC_NRS_CTL_INVALID,
536         /**
537          * Activate the policy.
538          */
539         PTLRPC_NRS_CTL_START,
540         /**
541          * Reserved for multiple primary policies, which may be a possibility
542          * in the future.
543          */
544         PTLRPC_NRS_CTL_STOP,
545         /**
546          * Policies can start using opcodes from this value and onwards for
547          * their own purposes; the assigned value itself is arbitrary.
548          */
549         PTLRPC_NRS_CTL_1ST_POL_SPEC = 0x20,
550 };
551
552 /**
553  * ORR policy operations
554  */
555 enum nrs_ctl_orr {
556         NRS_CTL_ORR_RD_QUANTUM = PTLRPC_NRS_CTL_1ST_POL_SPEC,
557         NRS_CTL_ORR_WR_QUANTUM,
558         NRS_CTL_ORR_RD_OFF_TYPE,
559         NRS_CTL_ORR_WR_OFF_TYPE,
560         NRS_CTL_ORR_RD_SUPP_REQ,
561         NRS_CTL_ORR_WR_SUPP_REQ,
562 };
563
564 /**
565  * NRS policy operations.
566  *
567  * These determine the behaviour of a policy, and are called in response to
568  * NRS core events.
569  */
570 struct ptlrpc_nrs_pol_ops {
571         /**
572          * Called during policy registration; this operation is optional.
573          *
574          * \param[in,out] policy The policy being initialized
575          */
576         int     (*op_policy_init)(struct ptlrpc_nrs_policy *policy);
577         /**
578          * Called during policy unregistration; this operation is optional.
579          *
580          * \param[in,out] policy The policy being unregistered/finalized
581          */
582         void    (*op_policy_fini)(struct ptlrpc_nrs_policy *policy);
583         /**
584          * Called when activating a policy via lprocfs; policies allocate and
585          * initialize their resources here; this operation is optional.
586          *
587          * \param[in,out] policy The policy being started
588          *
589          * \see nrs_policy_start_locked()
590          */
591         int     (*op_policy_start)(struct ptlrpc_nrs_policy *policy);
592         /**
593          * Called when deactivating a policy via lprocfs; policies deallocate
594          * their resources here; this operation is optional
595          *
596          * \param[in,out] policy The policy being stopped
597          *
598          * \see nrs_policy_stop0()
599          */
600         void    (*op_policy_stop)(struct ptlrpc_nrs_policy *policy);
601         /**
602          * Used for policy-specific operations; i.e. not generic ones like
603          * \e PTLRPC_NRS_CTL_START and \e PTLRPC_NRS_CTL_GET_INFO; analogous
604          * to an ioctl; this operation is optional.
605          *
606          * \param[in,out]        policy The policy carrying out operation \a opc
607          * \param[in]     opc    The command operation being carried out
608          * \param[in,out] arg    An generic buffer for communication between the
609          *                       user and the control operation
610          *
611          * \retval -ve error
612          * \retval   0 success
613          *
614          * \see ptlrpc_nrs_policy_control()
615          */
616         int     (*op_policy_ctl)(struct ptlrpc_nrs_policy *policy,
617                                  enum ptlrpc_nrs_ctl opc, void *arg);
618
619         /**
620          * Called when obtaining references to the resources of the resource
621          * hierarchy for a request that has arrived for handling at the PTLRPC
622          * service. Policies should return -ve for requests they do not wish
623          * to handle. This operation is mandatory.
624          *
625          * \param[in,out] policy  The policy we're getting resources for.
626          * \param[in,out] nrq     The request we are getting resources for.
627          * \param[in]     parent  The parent resource of the resource being
628          *                        requested; set to NULL if none.
629          * \param[out]    resp    The resource is to be returned here; the
630          *                        fallback policy in an NRS head should
631          *                        \e always return a non-NULL pointer value.
632          * \param[in]  moving_req When set, signifies that this is an attempt
633          *                        to obtain resources for a request being moved
634          *                        to the high-priority NRS head by
635          *                        ldlm_lock_reorder_req().
636          *                        This implies two things:
637          *                        1. We are under obd_export::exp_rpc_lock and
638          *                        so should not sleep.
639          *                        2. We should not perform non-idempotent or can
640          *                        skip performing idempotent operations that
641          *                        were carried out when resources were first
642          *                        taken for the request when it was initialized
643          *                        in ptlrpc_nrs_req_initialize().
644          *
645          * \retval 0, +ve The level of the returned resource in the resource
646          *                hierarchy; currently only 0 (for a non-leaf resource)
647          *                and 1 (for a leaf resource) are supported by the
648          *                framework.
649          * \retval -ve    error
650          *
651          * \see ptlrpc_nrs_req_initialize()
652          * \see ptlrpc_nrs_hpreq_add_nolock()
653          */
654         int     (*op_res_get)(struct ptlrpc_nrs_policy *policy,
655                               struct ptlrpc_nrs_request *nrq,
656                               const struct ptlrpc_nrs_resource *parent,
657                               struct ptlrpc_nrs_resource **resp,
658                               bool moving_req);
659         /**
660          * Called when releasing references taken for resources in the resource
661          * hierarchy for the request; this operation is optional.
662          *
663          * \param[in,out] policy The policy the resource belongs to
664          * \param[in] res        The resource to be freed
665          *
666          * \see ptlrpc_nrs_req_finalize()
667          * \see ptlrpc_nrs_hpreq_add_nolock()
668          */
669         void    (*op_res_put)(struct ptlrpc_nrs_policy *policy,
670                               const struct ptlrpc_nrs_resource *res);
671
672         /**
673          * Obtains a request for handling from the policy, and optionally
674          * removes the request from the policy; this operation is mandatory.
675          *
676          * \param[in,out] policy The policy to poll
677          * \param[in]     peek   When set, signifies that we just want to
678          *                       examine the request, and not handle it, so the
679          *                       request is not removed from the policy.
680          * \param[in]     force  When set, it will force a policy to return a
681          *                       request if it has one queued.
682          *
683          * \retval NULL No request available for handling
684          * \retval valid-pointer The request polled for handling
685          *
686          * \see ptlrpc_nrs_req_get_nolock()
687          */
688         struct ptlrpc_nrs_request *
689                 (*op_req_get)(struct ptlrpc_nrs_policy *policy, bool peek,
690                               bool force);
691         /**
692          * Called when attempting to add a request to a policy for later
693          * handling; this operation is mandatory.
694          *
695          * \param[in,out] policy  The policy on which to enqueue \a nrq
696          * \param[in,out] nrq The request to enqueue
697          *
698          * \retval 0    success
699          * \retval != 0 error
700          *
701          * \see ptlrpc_nrs_req_add_nolock()
702          */
703         int     (*op_req_enqueue)(struct ptlrpc_nrs_policy *policy,
704                                   struct ptlrpc_nrs_request *nrq);
705         /**
706          * Removes a request from the policy's set of pending requests. Normally
707          * called after a request has been polled successfully from the policy
708          * for handling; this operation is mandatory.
709          *
710          * \param[in,out] policy The policy the request \a nrq belongs to
711          * \param[in,out] nrq    The request to dequeue
712          */
713         void    (*op_req_dequeue)(struct ptlrpc_nrs_policy *policy,
714                                   struct ptlrpc_nrs_request *nrq);
715         /**
716          * Called after the request being carried out. Could be used for
717          * job/resource control; this operation is optional.
718          *
719          * \param[in,out] policy The policy which is stopping to handle request
720          *                       \a nrq
721          * \param[in,out] nrq    The request
722          *
723          * \pre assert_spin_locked(&svcpt->scp_req_lock)
724          *
725          * \see ptlrpc_nrs_req_stop_nolock()
726          */
727         void    (*op_req_stop)(struct ptlrpc_nrs_policy *policy,
728                                struct ptlrpc_nrs_request *nrq);
729         /**
730          * Registers the policy's lprocfs interface with a PTLRPC service.
731          *
732          * \param[in] svc The service
733          *
734          * \retval 0    success
735          * \retval != 0 error
736          */
737         int     (*op_lprocfs_init)(struct ptlrpc_service *svc);
738         /**
739          * Unegisters the policy's lprocfs interface with a PTLRPC service.
740          *
741          * In cases of failed policy registration in
742          * \e ptlrpc_nrs_policy_register(), this function may be called for a
743          * service which has not registered the policy successfully, so
744          * implementations of this method should make sure their operations are
745          * safe in such cases.
746          *
747          * \param[in] svc The service
748          */
749         void    (*op_lprocfs_fini)(struct ptlrpc_service *svc);
750 };
751
752 /**
753  * Policy flags
754  */
755 enum nrs_policy_flags {
756         /**
757          * Fallback policy, use this flag only on a single supported policy per
758          * service. The flag cannot be used on policies that use
759          * \e PTLRPC_NRS_FL_REG_EXTERN
760          */
761         PTLRPC_NRS_FL_FALLBACK          = (1 << 0),
762         /**
763          * Start policy immediately after registering.
764          */
765         PTLRPC_NRS_FL_REG_START         = (1 << 1),
766         /**
767          * This is a policy registering from a module different to the one NRS
768          * core ships in (currently ptlrpc).
769          */
770         PTLRPC_NRS_FL_REG_EXTERN        = (1 << 2),
771 };
772
773 /**
774  * NRS queue type.
775  *
776  * Denotes whether an NRS instance is for handling normal or high-priority
777  * RPCs, or whether an operation pertains to one or both of the NRS instances
778  * in a service.
779  */
780 enum ptlrpc_nrs_queue_type {
781         PTLRPC_NRS_QUEUE_REG    = (1 << 0),
782         PTLRPC_NRS_QUEUE_HP     = (1 << 1),
783         PTLRPC_NRS_QUEUE_BOTH   = (PTLRPC_NRS_QUEUE_REG | PTLRPC_NRS_QUEUE_HP)
784 };
785
786 /**
787  * NRS head
788  *
789  * A PTLRPC service has at least one NRS head instance for handling normal
790  * priority RPCs, and may optionally have a second NRS head instance for
791  * handling high-priority RPCs. Each NRS head maintains a list of available
792  * policies, of which one and only one policy is acting as the fallback policy,
793  * and optionally a different policy may be acting as the primary policy. For
794  * all RPCs handled by this NRS head instance, NRS core will first attempt to
795  * enqueue the RPC using the primary policy (if any). The fallback policy is
796  * used in the following cases:
797  * - when there was no primary policy in the
798  *   ptlrpc_nrs_pol_state::NRS_POL_STATE_STARTED state at the time the request
799  *   was initialized.
800  * - when the primary policy that was at the
801  *   ptlrpc_nrs_pol_state::PTLRPC_NRS_POL_STATE_STARTED state at the time the
802  *   RPC was initialized, denoted it did not wish, or for some other reason was
803  *   not able to handle the request, by returning a non-valid NRS resource
804  *   reference.
805  * - when the primary policy that was at the
806  *   ptlrpc_nrs_pol_state::PTLRPC_NRS_POL_STATE_STARTED state at the time the
807  *   RPC was initialized, fails later during the request enqueueing stage.
808  *
809  * \see nrs_resource_get_safe()
810  * \see nrs_request_enqueue()
811  */
812 struct ptlrpc_nrs {
813         spinlock_t                      nrs_lock;
814         /** XXX Possibly replace svcpt->scp_req_lock with another lock here. */
815         /**
816          * List of registered policies
817          */
818         struct list_head                        nrs_policy_list;
819         /**
820          * List of policies with queued requests. Policies that have any
821          * outstanding requests are queued here, and this list is queried
822          * in a round-robin manner from NRS core when obtaining a request
823          * for handling. This ensures that requests from policies that at some
824          * point transition away from the
825          * ptlrpc_nrs_pol_state::NRS_POL_STATE_STARTED state are drained.
826          */
827         struct list_head                        nrs_policy_queued;
828         /**
829          * Service partition for this NRS head
830          */
831         struct ptlrpc_service_part     *nrs_svcpt;
832         /**
833          * Primary policy, which is the preferred policy for handling RPCs
834          */
835         struct ptlrpc_nrs_policy       *nrs_policy_primary;
836         /**
837          * Fallback policy, which is the backup policy for handling RPCs
838          */
839         struct ptlrpc_nrs_policy       *nrs_policy_fallback;
840         /**
841          * This NRS head handles either HP or regular requests
842          */
843         enum ptlrpc_nrs_queue_type      nrs_queue_type;
844         /**
845          * # queued requests from all policies in this NRS head
846          */
847         unsigned long                   nrs_req_queued;
848         /**
849          * # scheduled requests from all policies in this NRS head
850          */
851         unsigned long                   nrs_req_started;
852         /**
853          * # policies on this NRS
854          */
855         unsigned                        nrs_num_pols;
856         /**
857          * This NRS head is in progress of starting a policy
858          */
859         unsigned                        nrs_policy_starting:1;
860         /**
861          * In progress of shutting down the whole NRS head; used during
862          * unregistration
863          */
864         unsigned                        nrs_stopping:1;
865 };
866
867 #define NRS_POL_NAME_MAX                16
868
869 struct ptlrpc_nrs_pol_desc;
870
871 /**
872  * Service compatibility predicate; this determines whether a policy is adequate
873  * for handling RPCs of a particular PTLRPC service.
874  *
875  * XXX:This should give the same result during policy registration and
876  * unregistration, and for all partitions of a service; so the result should not
877  * depend on temporal service or other properties, that may influence the
878  * result.
879  */
880 typedef bool (*nrs_pol_desc_compat_t) (const struct ptlrpc_service *svc,
881                                        const struct ptlrpc_nrs_pol_desc *desc);
882
883 struct ptlrpc_nrs_pol_conf {
884         /**
885          * Human-readable policy name
886          */
887         char                               nc_name[NRS_POL_NAME_MAX];
888         /**
889          * NRS operations for this policy
890          */
891         const struct ptlrpc_nrs_pol_ops   *nc_ops;
892         /**
893          * Service compatibility predicate
894          */
895         nrs_pol_desc_compat_t              nc_compat;
896         /**
897          * Set for policies that support a single ptlrpc service, i.e. ones that
898          * have \a pd_compat set to nrs_policy_compat_one(). The variable value
899          * depicts the name of the single service that such policies are
900          * compatible with.
901          */
902         const char                        *nc_compat_svc_name;
903         /**
904          * Owner module for this policy descriptor; policies registering from a
905          * different module to the one the NRS framework is held within
906          * (currently ptlrpc), should set this field to THIS_MODULE.
907          */
908         struct module                     *nc_owner;
909         /**
910          * Policy registration flags; a bitmask of \e nrs_policy_flags
911          */
912         unsigned                           nc_flags;
913 };
914
915 /**
916  * NRS policy registering descriptor
917  *
918  * Is used to hold a description of a policy that can be passed to NRS core in
919  * order to register the policy with NRS heads in different PTLRPC services.
920  */
921 struct ptlrpc_nrs_pol_desc {
922         /**
923          * Human-readable policy name
924          */
925         char                                    pd_name[NRS_POL_NAME_MAX];
926         /**
927          * Link into nrs_core::nrs_policies
928          */
929         struct list_head                                pd_list;
930         /**
931          * NRS operations for this policy
932          */
933         const struct ptlrpc_nrs_pol_ops        *pd_ops;
934         /**
935          * Service compatibility predicate
936          */
937         nrs_pol_desc_compat_t                   pd_compat;
938         /**
939          * Set for policies that are compatible with only one PTLRPC service.
940          *
941          * \see ptlrpc_nrs_pol_conf::nc_compat_svc_name
942          */
943         const char                             *pd_compat_svc_name;
944         /**
945          * Owner module for this policy descriptor.
946          *
947          * We need to hold a reference to the module whenever we might make use
948          * of any of the module's contents, i.e.
949          * - If one or more instances of the policy are at a state where they
950          *   might be handling a request, i.e.
951          *   ptlrpc_nrs_pol_state::NRS_POL_STATE_STARTED or
952          *   ptlrpc_nrs_pol_state::NRS_POL_STATE_STOPPING as we will have to
953          *   call into the policy's ptlrpc_nrs_pol_ops() handlers. A reference
954          *   is taken on the module when
955          *   \e ptlrpc_nrs_pol_desc::pd_refs becomes 1, and released when it
956          *   becomes 0, so that we hold only one reference to the module maximum
957          *   at any time.
958          *
959          *   We do not need to hold a reference to the module, even though we
960          *   might use code and data from the module, in the following cases:
961          * - During external policy registration, because this should happen in
962          *   the module's init() function, in which case the module is safe from
963          *   removal because a reference is being held on the module by the
964          *   kernel, and iirc kmod (and I guess module-init-tools also) will
965          *   serialize any racing processes properly anyway.
966          * - During external policy unregistration, because this should happen
967          *   in a module's exit() function, and any attempts to start a policy
968          *   instance would need to take a reference on the module, and this is
969          *   not possible once we have reached the point where the exit()
970          *   handler is called.
971          * - During service registration and unregistration, as service setup
972          *   and cleanup, and policy registration, unregistration and policy
973          *   instance starting, are serialized by \e nrs_core::nrs_mutex, so
974          *   as long as users adhere to the convention of registering policies
975          *   in init() and unregistering them in module exit() functions, there
976          *   should not be a race between these operations.
977          * - During any policy-specific lprocfs operations, because a reference
978          *   is held by the kernel on a proc entry that has been entered by a
979          *   syscall, so as long as proc entries are removed during unregistration time,
980          *   then unregistration and lprocfs operations will be properly
981          *   serialized.
982          */
983         struct module                          *pd_owner;
984         /**
985          * Bitmask of \e nrs_policy_flags
986          */
987         unsigned                                pd_flags;
988         /**
989          * # of references on this descriptor
990          */
991         atomic_t                                pd_refs;
992 };
993
994 /**
995  * NRS policy state
996  *
997  * Policies transition from one state to the other during their lifetime
998  */
999 enum ptlrpc_nrs_pol_state {
1000         /**
1001          * Not a valid policy state.
1002          */
1003         NRS_POL_STATE_INVALID,
1004         /**
1005          * Policies are at this state either at the start of their life, or
1006          * transition here when the user selects a different policy to act
1007          * as the primary one.
1008          */
1009         NRS_POL_STATE_STOPPED,
1010         /**
1011          * Policy is progress of stopping
1012          */
1013         NRS_POL_STATE_STOPPING,
1014         /**
1015          * Policy is in progress of starting
1016          */
1017         NRS_POL_STATE_STARTING,
1018         /**
1019          * A policy is in this state in two cases:
1020          * - it is the fallback policy, which is always in this state.
1021          * - it has been activated by the user; i.e. it is the primary policy,
1022          */
1023         NRS_POL_STATE_STARTED,
1024 };
1025
1026 /**
1027  * NRS policy information
1028  *
1029  * Used for obtaining information for the status of a policy via lprocfs
1030  */
1031 struct ptlrpc_nrs_pol_info {
1032         /**
1033          * Policy name
1034          */
1035         char                            pi_name[NRS_POL_NAME_MAX];
1036         /**
1037          * Current policy state
1038          */
1039         enum ptlrpc_nrs_pol_state       pi_state;
1040         /**
1041          * # RPCs enqueued for later dispatching by the policy
1042          */
1043         long                            pi_req_queued;
1044         /**
1045          * # RPCs started for dispatch by the policy
1046          */
1047         long                            pi_req_started;
1048         /**
1049          * Is this a fallback policy?
1050          */
1051         unsigned                        pi_fallback:1;
1052 };
1053
1054 /**
1055  * NRS policy
1056  *
1057  * There is one instance of this for each policy in each NRS head of each
1058  * PTLRPC service partition.
1059  */
1060 struct ptlrpc_nrs_policy {
1061         /**
1062          * Linkage into the NRS head's list of policies,
1063          * ptlrpc_nrs:nrs_policy_list
1064          */
1065         struct list_head                        pol_list;
1066         /**
1067          * Linkage into the NRS head's list of policies with enqueued
1068          * requests ptlrpc_nrs:nrs_policy_queued
1069          */
1070         struct list_head                        pol_list_queued;
1071         /**
1072          * Current state of this policy
1073          */
1074         enum ptlrpc_nrs_pol_state       pol_state;
1075         /**
1076          * Bitmask of nrs_policy_flags
1077          */
1078         unsigned                        pol_flags;
1079         /**
1080          * # RPCs enqueued for later dispatching by the policy
1081          */
1082         long                            pol_req_queued;
1083         /**
1084          * # RPCs started for dispatch by the policy
1085          */
1086         long                            pol_req_started;
1087         /**
1088          * Usage Reference count taken on the policy instance
1089          */
1090         long                            pol_ref;
1091         /**
1092          * The NRS head this policy has been created at
1093          */
1094         struct ptlrpc_nrs              *pol_nrs;
1095         /**
1096          * Private policy data; varies by policy type
1097          */
1098         void                           *pol_private;
1099         /**
1100          * Policy descriptor for this policy instance.
1101          */
1102         struct ptlrpc_nrs_pol_desc     *pol_desc;
1103 };
1104
1105 /**
1106  * NRS resource
1107  *
1108  * Resources are embedded into two types of NRS entities:
1109  * - Inside NRS policies, in the policy's private data in
1110  *   ptlrpc_nrs_policy::pol_private
1111  * - In objects that act as prime-level scheduling entities in different NRS
1112  *   policies; e.g. on a policy that performs round robin or similar order
1113  *   scheduling across client NIDs, there would be one NRS resource per unique
1114  *   client NID. On a policy which performs round robin scheduling across
1115  *   backend filesystem objects, there would be one resource associated with
1116  *   each of the backend filesystem objects partaking in the scheduling
1117  *   performed by the policy.
1118  *
1119  * NRS resources share a parent-child relationship, in which resources embedded
1120  * in policy instances are the parent entities, with all scheduling entities
1121  * a policy schedules across being the children, thus forming a simple resource
1122  * hierarchy. This hierarchy may be extended with one or more levels in the
1123  * future if the ability to have more than one primary policy is added.
1124  *
1125  * Upon request initialization, references to the then active NRS policies are
1126  * taken and used to later handle the dispatching of the request with one of
1127  * these policies.
1128  *
1129  * \see nrs_resource_get_safe()
1130  * \see ptlrpc_nrs_req_add()
1131  */
1132 struct ptlrpc_nrs_resource {
1133         /**
1134          * This NRS resource's parent; is NULL for resources embedded in NRS
1135          * policy instances; i.e. those are top-level ones.
1136          */
1137         struct ptlrpc_nrs_resource     *res_parent;
1138         /**
1139          * The policy associated with this resource.
1140          */
1141         struct ptlrpc_nrs_policy       *res_policy;
1142 };
1143
1144 enum {
1145         NRS_RES_FALLBACK,
1146         NRS_RES_PRIMARY,
1147         NRS_RES_MAX
1148 };
1149
1150 /* \name fifo
1151  *
1152  * FIFO policy
1153  *
1154  * This policy is a logical wrapper around previous, non-NRS functionality.
1155  * It dispatches RPCs in the same order as they arrive from the network. This
1156  * policy is currently used as the fallback policy, and the only enabled policy
1157  * on all NRS heads of all PTLRPC service partitions.
1158  * @{
1159  */
1160
1161 /**
1162  * Private data structure for the FIFO policy
1163  */
1164 struct nrs_fifo_head {
1165         /**
1166          * Resource object for policy instance.
1167          */
1168         struct ptlrpc_nrs_resource      fh_res;
1169         /**
1170          * List of queued requests.
1171          */
1172         struct list_head                        fh_list;
1173         /**
1174          * For debugging purposes.
1175          */
1176         __u64                           fh_sequence;
1177 };
1178
1179 struct nrs_fifo_req {
1180         struct list_head                fr_list;
1181         __u64                   fr_sequence;
1182 };
1183
1184 /** @} fifo */
1185
1186 /**
1187  * NRS request
1188  *
1189  * Instances of this object exist embedded within ptlrpc_request; the main
1190  * purpose of this object is to hold references to the request's resources
1191  * for the lifetime of the request, and to hold properties that policies use
1192  * use for determining the request's scheduling priority.
1193  */
1194 struct ptlrpc_nrs_request {
1195         /**
1196          * The request's resource hierarchy.
1197          */
1198         struct ptlrpc_nrs_resource     *nr_res_ptrs[NRS_RES_MAX];
1199         /**
1200          * Index into ptlrpc_nrs_request::nr_res_ptrs of the resource of the
1201          * policy that was used to enqueue the request.
1202          *
1203          * \see nrs_request_enqueue()
1204          */
1205         unsigned                        nr_res_idx;
1206         unsigned                        nr_initialized:1;
1207         unsigned                        nr_enqueued:1;
1208         unsigned                        nr_started:1;
1209         unsigned                        nr_finalized:1;
1210
1211         /**
1212          * Policy-specific fields, used for determining a request's scheduling
1213          * priority, and other supporting functionality.
1214          */
1215         union {
1216                 /**
1217                  * Fields for the FIFO policy
1218                  */
1219                 struct nrs_fifo_req     fifo;
1220         } nr_u;
1221         /**
1222          * Externally-registering policies may want to use this to allocate
1223          * their own request properties.
1224          */
1225         void                           *ext;
1226 };
1227
1228 /** @} nrs */
1229
1230 /**
1231  * Basic request prioritization operations structure.
1232  * The whole idea is centered around locks and RPCs that might affect locks.
1233  * When a lock is contended we try to give priority to RPCs that might lead
1234  * to fastest release of that lock.
1235  * Currently only implemented for OSTs only in a way that makes all
1236  * IO and truncate RPCs that are coming from a locked region where a lock is
1237  * contended a priority over other requests.
1238  */
1239 struct ptlrpc_hpreq_ops {
1240         /**
1241          * Check if the lock handle of the given lock is the same as
1242          * taken from the request.
1243          */
1244         int  (*hpreq_lock_match)(struct ptlrpc_request *, struct ldlm_lock *);
1245         /**
1246          * Check if the request is a high priority one.
1247          */
1248         int  (*hpreq_check)(struct ptlrpc_request *);
1249         /**
1250          * Called after the request has been handled.
1251          */
1252         void (*hpreq_fini)(struct ptlrpc_request *);
1253 };
1254
1255 struct ptlrpc_cli_req {
1256         /** For bulk requests on client only: bulk descriptor */
1257         struct ptlrpc_bulk_desc         *cr_bulk;
1258         /** optional time limit for send attempts */
1259         long                             cr_delay_limit;
1260         /** time request was first queued */
1261         time_t                           cr_queued_time;
1262         /** request sent timeval */
1263         struct timespec64                cr_sent_tv;
1264         /** time for request really sent out */
1265         time_t                           cr_sent_out;
1266         /** when req reply unlink must finish. */
1267         time_t                           cr_reply_deadline;
1268         /** when req bulk unlink must finish. */
1269         time_t                           cr_bulk_deadline;
1270         /** when req unlink must finish. */
1271         time_t                           cr_req_deadline;
1272         /** Portal to which this request would be sent */
1273         short                            cr_req_ptl;
1274         /** Portal where to wait for reply and where reply would be sent */
1275         short                            cr_rep_ptl;
1276         /** request resending number */
1277         unsigned int                     cr_resend_nr;
1278         /** What was import generation when this request was sent */
1279         int                              cr_imp_gen;
1280         enum lustre_imp_state            cr_send_state;
1281         /** Per-request waitq introduced by bug 21938 for recovery waiting */
1282         wait_queue_head_t                cr_set_waitq;
1283         /** Link item for request set lists */
1284         struct list_head                 cr_set_chain;
1285         /** link to waited ctx */
1286         struct list_head                 cr_ctx_chain;
1287
1288         /** client's half ctx */
1289         struct ptlrpc_cli_ctx           *cr_cli_ctx;
1290         /** Link back to the request set */
1291         struct ptlrpc_request_set       *cr_set;
1292         /** outgoing request MD handle */
1293         lnet_handle_md_t                 cr_req_md_h;
1294         /** request-out callback parameter */
1295         struct ptlrpc_cb_id              cr_req_cbid;
1296         /** incoming reply MD handle */
1297         lnet_handle_md_t                 cr_reply_md_h;
1298         wait_queue_head_t                cr_reply_waitq;
1299         /** reply callback parameter */
1300         struct ptlrpc_cb_id              cr_reply_cbid;
1301         /** Async completion handler, called when reply is received */
1302         ptlrpc_interpterer_t             cr_reply_interp;
1303         /** Async completion context */
1304         union ptlrpc_async_args          cr_async_args;
1305         /** Opaq data for replay and commit callbacks. */
1306         void                            *cr_cb_data;
1307         /**
1308          * Commit callback, called when request is committed and about to be
1309          * freed.
1310          */
1311         void (*cr_commit_cb)(struct ptlrpc_request *);
1312         /** Replay callback, called after request is replayed at recovery */
1313         void (*cr_replay_cb)(struct ptlrpc_request *);
1314 };
1315
1316 /** client request member alias */
1317 /* NB: these alias should NOT be used by any new code, instead they should
1318  * be removed step by step to avoid potential abuse
1319  */
1320 #define rq_bulk                 rq_cli.cr_bulk
1321 #define rq_delay_limit          rq_cli.cr_delay_limit
1322 #define rq_queued_time          rq_cli.cr_queued_time
1323 #define rq_sent_tv              rq_cli.cr_sent_tv
1324 #define rq_real_sent            rq_cli.cr_sent_out
1325 #define rq_reply_deadline       rq_cli.cr_reply_deadline
1326 #define rq_bulk_deadline        rq_cli.cr_bulk_deadline
1327 #define rq_req_deadline         rq_cli.cr_req_deadline
1328 #define rq_nr_resend            rq_cli.cr_resend_nr
1329 #define rq_request_portal       rq_cli.cr_req_ptl
1330 #define rq_reply_portal         rq_cli.cr_rep_ptl
1331 #define rq_import_generation    rq_cli.cr_imp_gen
1332 #define rq_send_state           rq_cli.cr_send_state
1333 #define rq_set_chain            rq_cli.cr_set_chain
1334 #define rq_ctx_chain            rq_cli.cr_ctx_chain
1335 #define rq_set                  rq_cli.cr_set
1336 #define rq_set_waitq            rq_cli.cr_set_waitq
1337 #define rq_cli_ctx              rq_cli.cr_cli_ctx
1338 #define rq_req_md_h             rq_cli.cr_req_md_h
1339 #define rq_req_cbid             rq_cli.cr_req_cbid
1340 #define rq_reply_md_h           rq_cli.cr_reply_md_h
1341 #define rq_reply_waitq          rq_cli.cr_reply_waitq
1342 #define rq_reply_cbid           rq_cli.cr_reply_cbid
1343 #define rq_interpret_reply      rq_cli.cr_reply_interp
1344 #define rq_async_args           rq_cli.cr_async_args
1345 #define rq_cb_data              rq_cli.cr_cb_data
1346 #define rq_commit_cb            rq_cli.cr_commit_cb
1347 #define rq_replay_cb            rq_cli.cr_replay_cb
1348
1349 struct ptlrpc_srv_req {
1350         /** initial thread servicing this request */
1351         struct ptlrpc_thread            *sr_svc_thread;
1352         /**
1353          * Server side list of incoming unserved requests sorted by arrival
1354          * time.  Traversed from time to time to notice about to expire
1355          * requests and sent back "early replies" to clients to let them
1356          * know server is alive and well, just very busy to service their
1357          * requests in time
1358          */
1359         struct list_head                sr_timed_list;
1360         /** server-side per-export list */
1361         struct list_head                sr_exp_list;
1362         /** server-side history, used for debuging purposes. */
1363         struct list_head                sr_hist_list;
1364         /** history sequence # */
1365         __u64                           sr_hist_seq;
1366         /** the index of service's srv_at_array into which request is linked */
1367         time_t                          sr_at_index;
1368         /** authed uid */
1369         uid_t                           sr_auth_uid;
1370         /** authed uid mapped to */
1371         uid_t                           sr_auth_mapped_uid;
1372         /** RPC is generated from what part of Lustre */
1373         enum lustre_sec_part            sr_sp_from;
1374         /** request session context */
1375         struct lu_context               sr_ses;
1376         /** \addtogroup  nrs
1377          * @{
1378          */
1379         /** stub for NRS request */
1380         struct ptlrpc_nrs_request       sr_nrq;
1381         /** @} nrs */
1382         /** request arrival time */
1383         struct timespec64               sr_arrival_time;
1384         /** server's half ctx */
1385         struct ptlrpc_svc_ctx           *sr_svc_ctx;
1386         /** (server side), pointed directly into req buffer */
1387         struct ptlrpc_user_desc         *sr_user_desc;
1388         /** separated reply state */
1389         struct ptlrpc_reply_state       *sr_reply_state;
1390         /** server-side hp handlers */
1391         struct ptlrpc_hpreq_ops         *sr_ops;
1392         /** incoming request buffer */
1393         struct ptlrpc_request_buffer_desc *sr_rqbd;
1394 };
1395
1396 /** server request member alias */
1397 /* NB: these alias should NOT be used by any new code, instead they should
1398  * be removed step by step to avoid potential abuse
1399  */
1400 #define rq_svc_thread           rq_srv.sr_svc_thread
1401 #define rq_timed_list           rq_srv.sr_timed_list
1402 #define rq_exp_list             rq_srv.sr_exp_list
1403 #define rq_history_list         rq_srv.sr_hist_list
1404 #define rq_history_seq          rq_srv.sr_hist_seq
1405 #define rq_at_index             rq_srv.sr_at_index
1406 #define rq_auth_uid             rq_srv.sr_auth_uid
1407 #define rq_auth_mapped_uid      rq_srv.sr_auth_mapped_uid
1408 #define rq_sp_from              rq_srv.sr_sp_from
1409 #define rq_session              rq_srv.sr_ses
1410 #define rq_nrq                  rq_srv.sr_nrq
1411 #define rq_arrival_time         rq_srv.sr_arrival_time
1412 #define rq_reply_state          rq_srv.sr_reply_state
1413 #define rq_svc_ctx              rq_srv.sr_svc_ctx
1414 #define rq_user_desc            rq_srv.sr_user_desc
1415 #define rq_ops                  rq_srv.sr_ops
1416 #define rq_rqbd                 rq_srv.sr_rqbd
1417
1418 /**
1419  * Represents remote procedure call.
1420  *
1421  * This is a staple structure used by everybody wanting to send a request
1422  * in Lustre.
1423  */
1424 struct ptlrpc_request {
1425         /* Request type: one of PTL_RPC_MSG_* */
1426         int                              rq_type;
1427         /** Result of request processing */
1428         int                              rq_status;
1429         /**
1430          * Linkage item through which this request is included into
1431          * sending/delayed lists on client and into rqbd list on server
1432          */
1433         struct list_head                 rq_list;
1434         /** Lock to protect request flags and some other important bits, like
1435          * rq_list
1436          */
1437         spinlock_t rq_lock;
1438         /** client-side flags are serialized by rq_lock @{ */
1439         unsigned int rq_intr:1, rq_replied:1, rq_err:1,
1440                 rq_timedout:1, rq_resend:1, rq_restart:1,
1441                 /**
1442                  * when ->rq_replay is set, request is kept by the client even
1443                  * after server commits corresponding transaction. This is
1444                  * used for operations that require sequence of multiple
1445                  * requests to be replayed. The only example currently is file
1446                  * open/close. When last request in such a sequence is
1447                  * committed, ->rq_replay is cleared on all requests in the
1448                  * sequence.
1449                  */
1450                 rq_replay:1,
1451                 rq_no_resend:1, rq_waiting:1, rq_receiving_reply:1,
1452                 rq_no_delay:1, rq_net_err:1, rq_wait_ctx:1,
1453                 rq_early:1,
1454                 rq_req_unlinked:1,      /* unlinked request buffer from lnet */
1455                 rq_reply_unlinked:1,    /* unlinked reply buffer from lnet */
1456                 rq_memalloc:1,      /* req originated from "kswapd" */
1457                 rq_committed:1,
1458                 rq_reply_truncated:1,
1459                 /** whether the "rq_set" is a valid one */
1460                 rq_invalid_rqset:1,
1461                 rq_generation_set:1,
1462                 /** do not resend request on -EINPROGRESS */
1463                 rq_no_retry_einprogress:1,
1464                 /* allow the req to be sent if the import is in recovery
1465                  * status
1466                  */
1467                 rq_allow_replay:1,
1468                 /* bulk request, sent to server, but uncommitted */
1469                 rq_unstable:1;
1470         /** @} */
1471
1472         /** server-side flags @{ */
1473         unsigned int
1474                 rq_hp:1,                /**< high priority RPC */
1475                 rq_at_linked:1,         /**< link into service's srv_at_array */
1476                 rq_packed_final:1;      /**< packed final reply */
1477         /** @} */
1478
1479         /** one of RQ_PHASE_* */
1480         enum rq_phase                   rq_phase;
1481         /** one of RQ_PHASE_* to be used next */
1482         enum rq_phase                   rq_next_phase;
1483         /**
1484          * client-side refcount for SENT race, server-side refcount
1485          * for multiple replies
1486          */
1487         atomic_t                        rq_refcount;
1488         /**
1489          * client-side:
1490          * !rq_truncate : # reply bytes actually received,
1491          *  rq_truncate : required repbuf_len for resend
1492          */
1493         int rq_nob_received;
1494         /** Request length */
1495         int rq_reqlen;
1496         /** Reply length */
1497         int rq_replen;
1498         /** Pool if request is from preallocated list */
1499         struct ptlrpc_request_pool     *rq_pool;
1500         /** Request message - what client sent */
1501         struct lustre_msg *rq_reqmsg;
1502         /** Reply message - server response */
1503         struct lustre_msg *rq_repmsg;
1504         /** Transaction number */
1505         __u64 rq_transno;
1506         /** xid */
1507         __u64 rq_xid;
1508         /**
1509          * List item to for replay list. Not yet committed requests get linked
1510          * there.
1511          * Also see \a rq_replay comment above.
1512          * It's also link chain on obd_export::exp_req_replay_queue
1513          */
1514         struct list_head rq_replay_list;
1515         /** non-shared members for client & server request*/
1516         union {
1517                 struct ptlrpc_cli_req    rq_cli;
1518                 struct ptlrpc_srv_req    rq_srv;
1519         };
1520         /**
1521          * security and encryption data
1522          * @{
1523          */
1524         /** description of flavors for client & server */
1525         struct sptlrpc_flavor           rq_flvr;
1526
1527         /* client/server security flags */
1528         unsigned int
1529                                  rq_ctx_init:1,      /* context initiation */
1530                                  rq_ctx_fini:1,      /* context destroy */
1531                                  rq_bulk_read:1,     /* request bulk read */
1532                                  rq_bulk_write:1,    /* request bulk write */
1533                                  /* server authentication flags */
1534                                  rq_auth_gss:1,      /* authenticated by gss */
1535                                  rq_auth_usr_root:1, /* authed as root */
1536                                  rq_auth_usr_mdt:1,  /* authed as mdt */
1537                                  rq_auth_usr_ost:1,  /* authed as ost */
1538                                  /* security tfm flags */
1539                                  rq_pack_udesc:1,
1540                                  rq_pack_bulk:1,
1541                                  /* doesn't expect reply FIXME */
1542                                  rq_no_reply:1,
1543                                  rq_pill_init:1, /* pill initialized */
1544                                  rq_srv_req:1; /* server request */
1545
1546         /** various buffer pointers */
1547         struct lustre_msg       *rq_reqbuf;     /**< req wrapper */
1548         char                    *rq_repbuf;     /**< rep buffer */
1549         struct lustre_msg       *rq_repdata;    /**< rep wrapper msg */
1550         /** only in priv mode */
1551         struct lustre_msg       *rq_clrbuf;
1552         int                   rq_reqbuf_len;  /* req wrapper buf len */
1553         int                   rq_reqdata_len; /* req wrapper msg len */
1554         int                   rq_repbuf_len;  /* rep buffer len */
1555         int                   rq_repdata_len; /* rep wrapper msg len */
1556         int                   rq_clrbuf_len;  /* only in priv mode */
1557         int                   rq_clrdata_len; /* only in priv mode */
1558
1559         /** early replies go to offset 0, regular replies go after that */
1560         unsigned int         rq_reply_off;
1561
1562         /** @} */
1563
1564         /** Fields that help to see if request and reply were swabbed or not */
1565         __u32 rq_req_swab_mask;
1566         __u32 rq_rep_swab_mask;
1567
1568         /** how many early replies (for stats) */
1569         int rq_early_count;
1570
1571         /** Server-side, export on which request was received */
1572         struct obd_export               *rq_export;
1573         /** import where request is being sent */
1574         struct obd_import               *rq_import;
1575         /** our LNet NID */
1576         lnet_nid_t         rq_self;
1577         /** Peer description (the other side) */
1578         lnet_process_id_t    rq_peer;
1579         /**
1580          * service time estimate (secs)
1581          * If the request is not served by this time, it is marked as timed out.
1582          */
1583         int                     rq_timeout;
1584         /**
1585          * when request/reply sent (secs), or time when request should be sent
1586          */
1587         time64_t rq_sent;
1588         /** when request must finish. */
1589         time64_t                  rq_deadline;
1590         /** request format description */
1591         struct req_capsule        rq_pill;
1592 };
1593
1594 /**
1595  * Call completion handler for rpc if any, return it's status or original
1596  * rc if there was no handler defined for this request.
1597  */
1598 static inline int ptlrpc_req_interpret(const struct lu_env *env,
1599                                        struct ptlrpc_request *req, int rc)
1600 {
1601         if (req->rq_interpret_reply) {
1602                 req->rq_status = req->rq_interpret_reply(env, req,
1603                                                          &req->rq_async_args,
1604                                                          rc);
1605                 return req->rq_status;
1606         }
1607         return rc;
1608 }
1609
1610 /*
1611  * Can the request be moved from the regular NRS head to the high-priority NRS
1612  * head (of the same PTLRPC service partition), if any?
1613  *
1614  * For a reliable result, this should be checked under svcpt->scp_req lock.
1615  */
1616 static inline bool ptlrpc_nrs_req_can_move(struct ptlrpc_request *req)
1617 {
1618         struct ptlrpc_nrs_request *nrq = &req->rq_nrq;
1619
1620         /**
1621          * LU-898: Check ptlrpc_nrs_request::nr_enqueued to make sure the
1622          * request has been enqueued first, and ptlrpc_nrs_request::nr_started
1623          * to make sure it has not been scheduled yet (analogous to previous
1624          * (non-NRS) checking of !list_empty(&ptlrpc_request::rq_list).
1625          */
1626         return nrq->nr_enqueued && !nrq->nr_started && !req->rq_hp;
1627 }
1628
1629 /** @} nrs */
1630
1631 /**
1632  * Returns 1 if request buffer at offset \a index was already swabbed
1633  */
1634 static inline int lustre_req_swabbed(struct ptlrpc_request *req, size_t index)
1635 {
1636         LASSERT(index < sizeof(req->rq_req_swab_mask) * 8);
1637         return req->rq_req_swab_mask & (1 << index);
1638 }
1639
1640 /**
1641  * Returns 1 if request reply buffer at offset \a index was already swabbed
1642  */
1643 static inline int lustre_rep_swabbed(struct ptlrpc_request *req, size_t index)
1644 {
1645         LASSERT(index < sizeof(req->rq_rep_swab_mask) * 8);
1646         return req->rq_rep_swab_mask & (1 << index);
1647 }
1648
1649 /**
1650  * Returns 1 if request needs to be swabbed into local cpu byteorder
1651  */
1652 static inline int ptlrpc_req_need_swab(struct ptlrpc_request *req)
1653 {
1654         return lustre_req_swabbed(req, MSG_PTLRPC_HEADER_OFF);
1655 }
1656
1657 /**
1658  * Returns 1 if request reply needs to be swabbed into local cpu byteorder
1659  */
1660 static inline int ptlrpc_rep_need_swab(struct ptlrpc_request *req)
1661 {
1662         return lustre_rep_swabbed(req, MSG_PTLRPC_HEADER_OFF);
1663 }
1664
1665 /**
1666  * Mark request buffer at offset \a index that it was already swabbed
1667  */
1668 static inline void lustre_set_req_swabbed(struct ptlrpc_request *req,
1669                                           size_t index)
1670 {
1671         LASSERT(index < sizeof(req->rq_req_swab_mask) * 8);
1672         LASSERT((req->rq_req_swab_mask & (1 << index)) == 0);
1673         req->rq_req_swab_mask |= 1 << index;
1674 }
1675
1676 /**
1677  * Mark request reply buffer at offset \a index that it was already swabbed
1678  */
1679 static inline void lustre_set_rep_swabbed(struct ptlrpc_request *req,
1680                                           size_t index)
1681 {
1682         LASSERT(index < sizeof(req->rq_rep_swab_mask) * 8);
1683         LASSERT((req->rq_rep_swab_mask & (1 << index)) == 0);
1684         req->rq_rep_swab_mask |= 1 << index;
1685 }
1686
1687 /**
1688  * Convert numerical request phase value \a phase into text string description
1689  */
1690 static inline const char *
1691 ptlrpc_phase2str(enum rq_phase phase)
1692 {
1693         switch (phase) {
1694         case RQ_PHASE_NEW:
1695                 return "New";
1696         case RQ_PHASE_RPC:
1697                 return "Rpc";
1698         case RQ_PHASE_BULK:
1699                 return "Bulk";
1700         case RQ_PHASE_INTERPRET:
1701                 return "Interpret";
1702         case RQ_PHASE_COMPLETE:
1703                 return "Complete";
1704         case RQ_PHASE_UNREG_RPC:
1705                 return "UnregRPC";
1706         case RQ_PHASE_UNREG_BULK:
1707                 return "UnregBULK";
1708         default:
1709                 return "?Phase?";
1710         }
1711 }
1712
1713 /**
1714  * Convert numerical request phase of the request \a req into text stringi
1715  * description
1716  */
1717 static inline const char *
1718 ptlrpc_rqphase2str(struct ptlrpc_request *req)
1719 {
1720         return ptlrpc_phase2str(req->rq_phase);
1721 }
1722
1723 /**
1724  * Debugging functions and helpers to print request structure into debug log
1725  * @{
1726  */
1727 /* Spare the preprocessor, spoil the bugs. */
1728 #define FLAG(field, str) (field ? str : "")
1729
1730 /** Convert bit flags into a string */
1731 #define DEBUG_REQ_FLAGS(req)                                                \
1732         ptlrpc_rqphase2str(req),                                                \
1733         FLAG(req->rq_intr, "I"), FLAG(req->rq_replied, "R"),                \
1734         FLAG(req->rq_err, "E"), FLAG(req->rq_net_err, "e"),                 \
1735         FLAG(req->rq_timedout, "X") /* eXpired */, FLAG(req->rq_resend, "S"),   \
1736         FLAG(req->rq_restart, "T"), FLAG(req->rq_replay, "P"),            \
1737         FLAG(req->rq_no_resend, "N"),                                      \
1738         FLAG(req->rq_waiting, "W"),                                          \
1739         FLAG(req->rq_wait_ctx, "C"), FLAG(req->rq_hp, "H"),                  \
1740         FLAG(req->rq_committed, "M")
1741
1742 #define REQ_FLAGS_FMT "%s:%s%s%s%s%s%s%s%s%s%s%s%s%s"
1743
1744 void _debug_req(struct ptlrpc_request *req,
1745                 struct libcfs_debug_msg_data *data, const char *fmt, ...)
1746         __printf(3, 4);
1747
1748 /**
1749  * Helper that decides if we need to print request according to current debug
1750  * level settings
1751  */
1752 #define debug_req(msgdata, mask, cdls, req, fmt, a...)                  \
1753 do {                                                                      \
1754         CFS_CHECK_STACK(msgdata, mask, cdls);                            \
1755                                                                               \
1756         if (((mask) & D_CANTMASK) != 0 ||                                    \
1757             ((libcfs_debug & (mask)) != 0 &&                              \
1758              (libcfs_subsystem_debug & DEBUG_SUBSYSTEM) != 0))          \
1759                 _debug_req((req), msgdata, fmt, ##a);                    \
1760 } while (0)
1761
1762 /**
1763  * This is the debug print function you need to use to print request structure
1764  * content into lustre debug log.
1765  * for most callers (level is a constant) this is resolved at compile time
1766  */
1767 #define DEBUG_REQ(level, req, fmt, args...)                                \
1768 do {                                                                      \
1769         if ((level) & (D_ERROR | D_WARNING)) {                          \
1770                 static struct cfs_debug_limit_state cdls;                         \
1771                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, level, &cdls);          \
1772                 debug_req(&msgdata, level, &cdls, req, "@@@ "fmt" ", ## args);\
1773         } else {                                                              \
1774                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, level, NULL);            \
1775                 debug_req(&msgdata, level, NULL, req, "@@@ "fmt" ", ## args); \
1776         }                                                                    \
1777 } while (0)
1778 /** @} */
1779
1780 /**
1781  * Structure that defines a single page of a bulk transfer
1782  */
1783 struct ptlrpc_bulk_page {
1784         /** Linkage to list of pages in a bulk */
1785         struct list_head       bp_link;
1786         /**
1787          * Number of bytes in a page to transfer starting from \a bp_pageoffset
1788          */
1789         int           bp_buflen;
1790         /** offset within a page */
1791         int           bp_pageoffset;
1792         /** The page itself */
1793         struct page     *bp_page;
1794 };
1795
1796 #define BULK_GET_SOURCE   0
1797 #define BULK_PUT_SINK     1
1798 #define BULK_GET_SINK     2
1799 #define BULK_PUT_SOURCE   3
1800
1801 /**
1802  * Definition of bulk descriptor.
1803  * Bulks are special "Two phase" RPCs where initial request message
1804  * is sent first and it is followed bt a transfer (o receiving) of a large
1805  * amount of data to be settled into pages referenced from the bulk descriptors.
1806  * Bulks transfers (the actual data following the small requests) are done
1807  * on separate LNet portals.
1808  * In lustre we use bulk transfers for READ and WRITE transfers from/to OSTs.
1809  *  Another user is readpage for MDT.
1810  */
1811 struct ptlrpc_bulk_desc {
1812         /** completed with failure */
1813         unsigned long bd_failure:1;
1814         /** {put,get}{source,sink} */
1815         unsigned long bd_type:2;
1816         /** client side */
1817         unsigned long bd_registered:1;
1818         /** For serialization with callback */
1819         spinlock_t bd_lock;
1820         /** Import generation when request for this bulk was sent */
1821         int bd_import_generation;
1822         /** LNet portal for this bulk */
1823         __u32 bd_portal;
1824         /** Server side - export this bulk created for */
1825         struct obd_export *bd_export;
1826         /** Client side - import this bulk was sent on */
1827         struct obd_import *bd_import;
1828         /** Back pointer to the request */
1829         struct ptlrpc_request *bd_req;
1830         wait_queue_head_t           bd_waitq;   /* server side only WQ */
1831         int                 bd_iov_count;    /* # entries in bd_iov */
1832         int                 bd_max_iov;      /* allocated size of bd_iov */
1833         int                 bd_nob;       /* # bytes covered */
1834         int                 bd_nob_transferred; /* # bytes GOT/PUT */
1835
1836         __u64             bd_last_xid;
1837
1838         struct ptlrpc_cb_id    bd_cbid;  /* network callback info */
1839         lnet_nid_t           bd_sender;       /* stash event::sender */
1840         int                     bd_md_count;    /* # valid entries in bd_mds */
1841         int                     bd_md_max_brw;  /* max entries in bd_mds */
1842         /** array of associated MDs */
1843         lnet_handle_md_t        bd_mds[PTLRPC_BULK_OPS_COUNT];
1844
1845         /*
1846          * encrypt iov, size is either 0 or bd_iov_count.
1847          */
1848         lnet_kiov_t        *bd_enc_iov;
1849
1850         lnet_kiov_t         bd_iov[0];
1851 };
1852
1853 enum {
1854         SVC_STOPPED     = 1 << 0,
1855         SVC_STOPPING    = 1 << 1,
1856         SVC_STARTING    = 1 << 2,
1857         SVC_RUNNING     = 1 << 3,
1858         SVC_EVENT       = 1 << 4,
1859         SVC_SIGNAL      = 1 << 5,
1860 };
1861
1862 #define PTLRPC_THR_NAME_LEN             32
1863 /**
1864  * Definition of server service thread structure
1865  */
1866 struct ptlrpc_thread {
1867         /**
1868          * List of active threads in svc->srv_threads
1869          */
1870         struct list_head t_link;
1871         /**
1872          * thread-private data (preallocated memory)
1873          */
1874         void *t_data;
1875         __u32 t_flags;
1876         /**
1877          * service thread index, from ptlrpc_start_threads
1878          */
1879         unsigned int t_id;
1880         /**
1881          * service thread pid
1882          */
1883         pid_t t_pid;
1884         /**
1885          * put watchdog in the structure per thread b=14840
1886          *
1887          * Lustre watchdog is removed for client in the hope
1888          * of a generic watchdog can be merged in kernel.
1889          * When that happens, we should add below back.
1890          *
1891          * struct lc_watchdog *t_watchdog;
1892          */
1893         /**
1894          * the svc this thread belonged to b=18582
1895          */
1896         struct ptlrpc_service_part      *t_svcpt;
1897         wait_queue_head_t                       t_ctl_waitq;
1898         struct lu_env                   *t_env;
1899         char                            t_name[PTLRPC_THR_NAME_LEN];
1900 };
1901
1902 static inline int thread_is_init(struct ptlrpc_thread *thread)
1903 {
1904         return thread->t_flags == 0;
1905 }
1906
1907 static inline int thread_is_stopped(struct ptlrpc_thread *thread)
1908 {
1909         return !!(thread->t_flags & SVC_STOPPED);
1910 }
1911
1912 static inline int thread_is_stopping(struct ptlrpc_thread *thread)
1913 {
1914         return !!(thread->t_flags & SVC_STOPPING);
1915 }
1916
1917 static inline int thread_is_starting(struct ptlrpc_thread *thread)
1918 {
1919         return !!(thread->t_flags & SVC_STARTING);
1920 }
1921
1922 static inline int thread_is_running(struct ptlrpc_thread *thread)
1923 {
1924         return !!(thread->t_flags & SVC_RUNNING);
1925 }
1926
1927 static inline int thread_is_event(struct ptlrpc_thread *thread)
1928 {
1929         return !!(thread->t_flags & SVC_EVENT);
1930 }
1931
1932 static inline int thread_is_signal(struct ptlrpc_thread *thread)
1933 {
1934         return !!(thread->t_flags & SVC_SIGNAL);
1935 }
1936
1937 static inline void thread_clear_flags(struct ptlrpc_thread *thread, __u32 flags)
1938 {
1939         thread->t_flags &= ~flags;
1940 }
1941
1942 static inline void thread_set_flags(struct ptlrpc_thread *thread, __u32 flags)
1943 {
1944         thread->t_flags = flags;
1945 }
1946
1947 static inline void thread_add_flags(struct ptlrpc_thread *thread, __u32 flags)
1948 {
1949         thread->t_flags |= flags;
1950 }
1951
1952 static inline int thread_test_and_clear_flags(struct ptlrpc_thread *thread,
1953                                               __u32 flags)
1954 {
1955         if (thread->t_flags & flags) {
1956                 thread->t_flags &= ~flags;
1957                 return 1;
1958         }
1959         return 0;
1960 }
1961
1962 /**
1963  * Request buffer descriptor structure.
1964  * This is a structure that contains one posted request buffer for service.
1965  * Once data land into a buffer, event callback creates actual request and
1966  * notifies wakes one of the service threads to process new incoming request.
1967  * More than one request can fit into the buffer.
1968  */
1969 struct ptlrpc_request_buffer_desc {
1970         /** Link item for rqbds on a service */
1971         struct list_head             rqbd_list;
1972         /** History of requests for this buffer */
1973         struct list_head             rqbd_reqs;
1974         /** Back pointer to service for which this buffer is registered */
1975         struct ptlrpc_service_part *rqbd_svcpt;
1976         /** LNet descriptor */
1977         lnet_handle_md_t       rqbd_md_h;
1978         int                 rqbd_refcount;
1979         /** The buffer itself */
1980         char              *rqbd_buffer;
1981         struct ptlrpc_cb_id    rqbd_cbid;
1982         /**
1983          * This "embedded" request structure is only used for the
1984          * last request to fit into the buffer
1985          */
1986         struct ptlrpc_request  rqbd_req;
1987 };
1988
1989 typedef int  (*svc_handler_t)(struct ptlrpc_request *req);
1990
1991 struct ptlrpc_service_ops {
1992         /**
1993          * if non-NULL called during thread creation (ptlrpc_start_thread())
1994          * to initialize service specific per-thread state.
1995          */
1996         int             (*so_thr_init)(struct ptlrpc_thread *thr);
1997         /**
1998          * if non-NULL called during thread shutdown (ptlrpc_main()) to
1999          * destruct state created by ->srv_init().
2000          */
2001         void            (*so_thr_done)(struct ptlrpc_thread *thr);
2002         /**
2003          * Handler function for incoming requests for this service
2004          */
2005         int             (*so_req_handler)(struct ptlrpc_request *req);
2006         /**
2007          * function to determine priority of the request, it's called
2008          * on every new request
2009          */
2010         int             (*so_hpreq_handler)(struct ptlrpc_request *);
2011         /**
2012          * service-specific print fn
2013          */
2014         void            (*so_req_printer)(void *, struct ptlrpc_request *);
2015 };
2016
2017 #ifndef __cfs_cacheline_aligned
2018 /* NB: put it here for reducing patche dependence */
2019 # define __cfs_cacheline_aligned
2020 #endif
2021
2022 /**
2023  * How many high priority requests to serve before serving one normal
2024  * priority request
2025  */
2026 #define PTLRPC_SVC_HP_RATIO 10
2027
2028 /**
2029  * Definition of PortalRPC service.
2030  * The service is listening on a particular portal (like tcp port)
2031  * and perform actions for a specific server like IO service for OST
2032  * or general metadata service for MDS.
2033  */
2034 struct ptlrpc_service {
2035         /** serialize sysfs operations */
2036         spinlock_t                      srv_lock;
2037         /** most often accessed fields */
2038         /** chain thru all services */
2039         struct list_head                      srv_list;
2040         /** service operations table */
2041         struct ptlrpc_service_ops       srv_ops;
2042         /** only statically allocated strings here; we don't clean them */
2043         char                       *srv_name;
2044         /** only statically allocated strings here; we don't clean them */
2045         char                       *srv_thread_name;
2046         /** service thread list */
2047         struct list_head                      srv_threads;
2048         /** threads # should be created for each partition on initializing */
2049         int                             srv_nthrs_cpt_init;
2050         /** limit of threads number for each partition */
2051         int                             srv_nthrs_cpt_limit;
2052         /** Root of debugfs dir tree for this service */
2053         struct dentry              *srv_debugfs_entry;
2054         /** Pointer to statistic data for this service */
2055         struct lprocfs_stats       *srv_stats;
2056         /** # hp per lp reqs to handle */
2057         int                          srv_hpreq_ratio;
2058         /** biggest request to receive */
2059         int                          srv_max_req_size;
2060         /** biggest reply to send */
2061         int                          srv_max_reply_size;
2062         /** size of individual buffers */
2063         int                          srv_buf_size;
2064         /** # buffers to allocate in 1 group */
2065         int                          srv_nbuf_per_group;
2066         /** Local portal on which to receive requests */
2067         __u32                      srv_req_portal;
2068         /** Portal on the client to send replies to */
2069         __u32                      srv_rep_portal;
2070         /**
2071          * Tags for lu_context associated with this thread, see struct
2072          * lu_context.
2073          */
2074         __u32                      srv_ctx_tags;
2075         /** soft watchdog timeout multiplier */
2076         int                          srv_watchdog_factor;
2077         /** under unregister_service */
2078         unsigned                        srv_is_stopping:1;
2079
2080         /** max # request buffers in history per partition */
2081         int                             srv_hist_nrqbds_cpt_max;
2082         /** number of CPTs this service bound on */
2083         int                             srv_ncpts;
2084         /** CPTs array this service bound on */
2085         __u32                           *srv_cpts;
2086         /** 2^srv_cptab_bits >= cfs_cpt_numbert(srv_cptable) */
2087         int                             srv_cpt_bits;
2088         /** CPT table this service is running over */
2089         struct cfs_cpt_table            *srv_cptable;
2090
2091         /* sysfs object */
2092         struct kobject                   srv_kobj;
2093         struct completion                srv_kobj_unregister;
2094         /**
2095          * partition data for ptlrpc service
2096          */
2097         struct ptlrpc_service_part      *srv_parts[0];
2098 };
2099
2100 /**
2101  * Definition of PortalRPC service partition data.
2102  * Although a service only has one instance of it right now, but we
2103  * will have multiple instances very soon (instance per CPT).
2104  *
2105  * it has four locks:
2106  * \a scp_lock
2107  *    serialize operations on rqbd and requests waiting for preprocess
2108  * \a scp_req_lock
2109  *    serialize operations active requests sent to this portal
2110  * \a scp_at_lock
2111  *    serialize adaptive timeout stuff
2112  * \a scp_rep_lock
2113  *    serialize operations on RS list (reply states)
2114  *
2115  * We don't have any use-case to take two or more locks at the same time
2116  * for now, so there is no lock order issue.
2117  */
2118 struct ptlrpc_service_part {
2119         /** back reference to owner */
2120         struct ptlrpc_service           *scp_service __cfs_cacheline_aligned;
2121         /* CPT id, reserved */
2122         int                             scp_cpt;
2123         /** always increasing number */
2124         int                             scp_thr_nextid;
2125         /** # of starting threads */
2126         int                             scp_nthrs_starting;
2127         /** # of stopping threads, reserved for shrinking threads */
2128         int                             scp_nthrs_stopping;
2129         /** # running threads */
2130         int                             scp_nthrs_running;
2131         /** service threads list */
2132         struct list_head                        scp_threads;
2133
2134         /**
2135          * serialize the following fields, used for protecting
2136          * rqbd list and incoming requests waiting for preprocess,
2137          * threads starting & stopping are also protected by this lock.
2138          */
2139         spinlock_t scp_lock __cfs_cacheline_aligned;
2140         /** total # req buffer descs allocated */
2141         int                             scp_nrqbds_total;
2142         /** # posted request buffers for receiving */
2143         int                             scp_nrqbds_posted;
2144         /** in progress of allocating rqbd */
2145         int                             scp_rqbd_allocating;
2146         /** # incoming reqs */
2147         int                             scp_nreqs_incoming;
2148         /** request buffers to be reposted */
2149         struct list_head                        scp_rqbd_idle;
2150         /** req buffers receiving */
2151         struct list_head                        scp_rqbd_posted;
2152         /** incoming reqs */
2153         struct list_head                        scp_req_incoming;
2154         /** timeout before re-posting reqs, in tick */
2155         long                    scp_rqbd_timeout;
2156         /**
2157          * all threads sleep on this. This wait-queue is signalled when new
2158          * incoming request arrives and when difficult reply has to be handled.
2159          */
2160         wait_queue_head_t                       scp_waitq;
2161
2162         /** request history */
2163         struct list_head                        scp_hist_reqs;
2164         /** request buffer history */
2165         struct list_head                        scp_hist_rqbds;
2166         /** # request buffers in history */
2167         int                             scp_hist_nrqbds;
2168         /** sequence number for request */
2169         __u64                           scp_hist_seq;
2170         /** highest seq culled from history */
2171         __u64                           scp_hist_seq_culled;
2172
2173         /**
2174          * serialize the following fields, used for processing requests
2175          * sent to this portal
2176          */
2177         spinlock_t                      scp_req_lock __cfs_cacheline_aligned;
2178         /** # reqs in either of the NRS heads below */
2179         /** # reqs being served */
2180         int                             scp_nreqs_active;
2181         /** # HPreqs being served */
2182         int                             scp_nhreqs_active;
2183         /** # hp requests handled */
2184         int                             scp_hreq_count;
2185
2186         /** NRS head for regular requests */
2187         struct ptlrpc_nrs               scp_nrs_reg;
2188         /** NRS head for HP requests; this is only valid for services that can
2189          *  handle HP requests
2190          */
2191         struct ptlrpc_nrs              *scp_nrs_hp;
2192
2193         /** AT stuff */
2194         /** @{ */
2195         /**
2196          * serialize the following fields, used for changes on
2197          * adaptive timeout
2198          */
2199         spinlock_t                      scp_at_lock __cfs_cacheline_aligned;
2200         /** estimated rpc service time */
2201         struct adaptive_timeout         scp_at_estimate;
2202         /** reqs waiting for replies */
2203         struct ptlrpc_at_array          scp_at_array;
2204         /** early reply timer */
2205         struct timer_list               scp_at_timer;
2206         /** debug */
2207         unsigned long                   scp_at_checktime;
2208         /** check early replies */
2209         unsigned                        scp_at_check;
2210         /** @} */
2211
2212         /**
2213          * serialize the following fields, used for processing
2214          * replies for this portal
2215          */
2216         spinlock_t                      scp_rep_lock __cfs_cacheline_aligned;
2217         /** all the active replies */
2218         struct list_head                        scp_rep_active;
2219         /** List of free reply_states */
2220         struct list_head                        scp_rep_idle;
2221         /** waitq to run, when adding stuff to srv_free_rs_list */
2222         wait_queue_head_t                       scp_rep_waitq;
2223         /** # 'difficult' replies */
2224         atomic_t                        scp_nreps_difficult;
2225 };
2226
2227 #define ptlrpc_service_for_each_part(part, i, svc)                      \
2228         for (i = 0;                                                     \
2229              i < (svc)->srv_ncpts &&                                    \
2230              (svc)->srv_parts &&                                        \
2231              ((part) = (svc)->srv_parts[i]); i++)
2232
2233 /**
2234  * Declaration of ptlrpcd control structure
2235  */
2236 struct ptlrpcd_ctl {
2237         /**
2238          * Ptlrpc thread control flags (LIOD_START, LIOD_STOP, LIOD_FORCE)
2239          */
2240         unsigned long                   pc_flags;
2241         /**
2242          * Thread lock protecting structure fields.
2243          */
2244         spinlock_t                      pc_lock;
2245         /**
2246          * Start completion.
2247          */
2248         struct completion               pc_starting;
2249         /**
2250          * Stop completion.
2251          */
2252         struct completion               pc_finishing;
2253         /**
2254          * Thread requests set.
2255          */
2256         struct ptlrpc_request_set  *pc_set;
2257         /**
2258          * Thread name used in kthread_run()
2259          */
2260         char                    pc_name[16];
2261         /**
2262          * Environment for request interpreters to run in.
2263          */
2264         struct lu_env          pc_env;
2265         /**
2266          * CPT the thread is bound on.
2267          */
2268         int                             pc_cpt;
2269         /**
2270          * Index of ptlrpcd thread in the array.
2271          */
2272         int                             pc_index;
2273         /**
2274          * Pointer to the array of partners' ptlrpcd_ctl structure.
2275          */
2276         struct ptlrpcd_ctl      **pc_partners;
2277         /**
2278          * Number of the ptlrpcd's partners.
2279          */
2280         int                             pc_npartners;
2281         /**
2282          * Record the partner index to be processed next.
2283          */
2284         int                      pc_cursor;
2285         /**
2286          * Error code if the thread failed to fully start.
2287          */
2288         int                             pc_error;
2289 };
2290
2291 /* Bits for pc_flags */
2292 enum ptlrpcd_ctl_flags {
2293         /**
2294          * Ptlrpc thread start flag.
2295          */
2296         LIOD_START       = 1 << 0,
2297         /**
2298          * Ptlrpc thread stop flag.
2299          */
2300         LIOD_STOP       = 1 << 1,
2301         /**
2302          * Ptlrpc thread force flag (only stop force so far).
2303          * This will cause aborting any inflight rpcs handled
2304          * by thread if LIOD_STOP is specified.
2305          */
2306         LIOD_FORCE       = 1 << 2,
2307         /**
2308          * This is a recovery ptlrpc thread.
2309          */
2310         LIOD_RECOVERY    = 1 << 3,
2311 };
2312
2313 /**
2314  * \addtogroup nrs
2315  * @{
2316  *
2317  * Service compatibility function; the policy is compatible with all services.
2318  *
2319  * \param[in] svc  The service the policy is attempting to register with.
2320  * \param[in] desc The policy descriptor
2321  *
2322  * \retval true The policy is compatible with the service
2323  *
2324  * \see ptlrpc_nrs_pol_desc::pd_compat()
2325  */
2326 static inline bool nrs_policy_compat_all(const struct ptlrpc_service *svc,
2327                                          const struct ptlrpc_nrs_pol_desc *desc)
2328 {
2329         return true;
2330 }
2331
2332 /**
2333  * Service compatibility function; the policy is compatible with only a specific
2334  * service which is identified by its human-readable name at
2335  * ptlrpc_service::srv_name.
2336  *
2337  * \param[in] svc  The service the policy is attempting to register with.
2338  * \param[in] desc The policy descriptor
2339  *
2340  * \retval false The policy is not compatible with the service
2341  * \retval true  The policy is compatible with the service
2342  *
2343  * \see ptlrpc_nrs_pol_desc::pd_compat()
2344  */
2345 static inline bool nrs_policy_compat_one(const struct ptlrpc_service *svc,
2346                                          const struct ptlrpc_nrs_pol_desc *desc)
2347 {
2348         return strcmp(svc->srv_name, desc->pd_compat_svc_name) == 0;
2349 }
2350
2351 /** @} nrs */
2352
2353 /* ptlrpc/events.c */
2354 extern lnet_handle_eq_t ptlrpc_eq_h;
2355 int ptlrpc_uuid_to_peer(struct obd_uuid *uuid,
2356                         lnet_process_id_t *peer, lnet_nid_t *self);
2357 /**
2358  * These callbacks are invoked by LNet when something happened to
2359  * underlying buffer
2360  * @{
2361  */
2362 void request_out_callback(lnet_event_t *ev);
2363 void reply_in_callback(lnet_event_t *ev);
2364 void client_bulk_callback(lnet_event_t *ev);
2365 void request_in_callback(lnet_event_t *ev);
2366 void reply_out_callback(lnet_event_t *ev);
2367 /** @} */
2368
2369 /* ptlrpc/connection.c */
2370 struct ptlrpc_connection *ptlrpc_connection_get(lnet_process_id_t peer,
2371                                                 lnet_nid_t self,
2372                                                 struct obd_uuid *uuid);
2373 int ptlrpc_connection_put(struct ptlrpc_connection *c);
2374 struct ptlrpc_connection *ptlrpc_connection_addref(struct ptlrpc_connection *);
2375 int ptlrpc_connection_init(void);
2376 void ptlrpc_connection_fini(void);
2377
2378 /* ptlrpc/niobuf.c */
2379 /**
2380  * Actual interfacing with LNet to put/get/register/unregister stuff
2381  * @{
2382  */
2383
2384 int ptlrpc_unregister_bulk(struct ptlrpc_request *req, int async);
2385
2386 static inline int ptlrpc_client_bulk_active(struct ptlrpc_request *req)
2387 {
2388         struct ptlrpc_bulk_desc *desc;
2389         int                   rc;
2390
2391         desc = req->rq_bulk;
2392
2393         if (req->rq_bulk_deadline > ktime_get_real_seconds())
2394                 return 1;
2395
2396         if (!desc)
2397                 return 0;
2398
2399         spin_lock(&desc->bd_lock);
2400         rc = desc->bd_md_count;
2401         spin_unlock(&desc->bd_lock);
2402         return rc;
2403 }
2404
2405 #define PTLRPC_REPLY_MAYBE_DIFFICULT 0x01
2406 #define PTLRPC_REPLY_EARLY         0x02
2407 int ptlrpc_send_reply(struct ptlrpc_request *req, int flags);
2408 int ptlrpc_reply(struct ptlrpc_request *req);
2409 int ptlrpc_send_error(struct ptlrpc_request *req, int difficult);
2410 int ptlrpc_error(struct ptlrpc_request *req);
2411 int ptlrpc_at_get_net_latency(struct ptlrpc_request *req);
2412 int ptl_send_rpc(struct ptlrpc_request *request, int noreply);
2413 int ptlrpc_register_rqbd(struct ptlrpc_request_buffer_desc *rqbd);
2414 /** @} */
2415
2416 /* ptlrpc/client.c */
2417 /**
2418  * Client-side portals API. Everything to send requests, receive replies,
2419  * request queues, request management, etc.
2420  * @{
2421  */
2422 void ptlrpc_request_committed(struct ptlrpc_request *req, int force);
2423
2424 void ptlrpc_init_client(int req_portal, int rep_portal, char *name,
2425                         struct ptlrpc_client *);
2426 struct ptlrpc_connection *ptlrpc_uuid_to_connection(struct obd_uuid *uuid);
2427
2428 int ptlrpc_queue_wait(struct ptlrpc_request *req);
2429 int ptlrpc_replay_req(struct ptlrpc_request *req);
2430 void ptlrpc_abort_inflight(struct obd_import *imp);
2431 void ptlrpc_abort_set(struct ptlrpc_request_set *set);
2432
2433 struct ptlrpc_request_set *ptlrpc_prep_set(void);
2434 struct ptlrpc_request_set *ptlrpc_prep_fcset(int max, set_producer_func func,
2435                                              void *arg);
2436 int ptlrpc_check_set(const struct lu_env *env, struct ptlrpc_request_set *set);
2437 int ptlrpc_set_wait(struct ptlrpc_request_set *);
2438 void ptlrpc_mark_interrupted(struct ptlrpc_request *req);
2439 void ptlrpc_set_destroy(struct ptlrpc_request_set *);
2440 void ptlrpc_set_add_req(struct ptlrpc_request_set *, struct ptlrpc_request *);
2441
2442 void ptlrpc_free_rq_pool(struct ptlrpc_request_pool *pool);
2443 int ptlrpc_add_rqs_to_pool(struct ptlrpc_request_pool *pool, int num_rq);
2444
2445 struct ptlrpc_request_pool *
2446 ptlrpc_init_rq_pool(int, int,
2447                     int (*populate_pool)(struct ptlrpc_request_pool *, int));
2448
2449 void ptlrpc_at_set_req_timeout(struct ptlrpc_request *req);
2450 struct ptlrpc_request *ptlrpc_request_alloc(struct obd_import *imp,
2451                                             const struct req_format *format);
2452 struct ptlrpc_request *ptlrpc_request_alloc_pool(struct obd_import *imp,
2453                                                  struct ptlrpc_request_pool *,
2454                                                  const struct req_format *);
2455 void ptlrpc_request_free(struct ptlrpc_request *request);
2456 int ptlrpc_request_pack(struct ptlrpc_request *request,
2457                         __u32 version, int opcode);
2458 struct ptlrpc_request *ptlrpc_request_alloc_pack(struct obd_import *,
2459                                                  const struct req_format *,
2460                                                  __u32, int);
2461 int ptlrpc_request_bufs_pack(struct ptlrpc_request *request,
2462                              __u32 version, int opcode, char **bufs,
2463                              struct ptlrpc_cli_ctx *ctx);
2464 void ptlrpc_req_finished(struct ptlrpc_request *request);
2465 struct ptlrpc_request *ptlrpc_request_addref(struct ptlrpc_request *req);
2466 struct ptlrpc_bulk_desc *ptlrpc_prep_bulk_imp(struct ptlrpc_request *req,
2467                                               unsigned npages, unsigned max_brw,
2468                                               unsigned type, unsigned portal);
2469 void __ptlrpc_free_bulk(struct ptlrpc_bulk_desc *bulk, int pin);
2470 static inline void ptlrpc_free_bulk_pin(struct ptlrpc_bulk_desc *bulk)
2471 {
2472         __ptlrpc_free_bulk(bulk, 1);
2473 }
2474
2475 static inline void ptlrpc_free_bulk_nopin(struct ptlrpc_bulk_desc *bulk)
2476 {
2477         __ptlrpc_free_bulk(bulk, 0);
2478 }
2479
2480 void __ptlrpc_prep_bulk_page(struct ptlrpc_bulk_desc *desc,
2481                              struct page *page, int pageoffset, int len, int);
2482 static inline void ptlrpc_prep_bulk_page_pin(struct ptlrpc_bulk_desc *desc,
2483                                              struct page *page, int pageoffset,
2484                                              int len)
2485 {
2486         __ptlrpc_prep_bulk_page(desc, page, pageoffset, len, 1);
2487 }
2488
2489 static inline void ptlrpc_prep_bulk_page_nopin(struct ptlrpc_bulk_desc *desc,
2490                                                struct page *page, int pageoffset,
2491                                                int len)
2492 {
2493         __ptlrpc_prep_bulk_page(desc, page, pageoffset, len, 0);
2494 }
2495
2496 void ptlrpc_retain_replayable_request(struct ptlrpc_request *req,
2497                                       struct obd_import *imp);
2498 __u64 ptlrpc_next_xid(void);
2499 __u64 ptlrpc_sample_next_xid(void);
2500 __u64 ptlrpc_req_xid(struct ptlrpc_request *request);
2501
2502 /* Set of routines to run a function in ptlrpcd context */
2503 void *ptlrpcd_alloc_work(struct obd_import *imp,
2504                          int (*cb)(const struct lu_env *, void *), void *data);
2505 void ptlrpcd_destroy_work(void *handler);
2506 int ptlrpcd_queue_work(void *handler);
2507
2508 /** @} */
2509 struct ptlrpc_service_buf_conf {
2510         /* nbufs is buffers # to allocate when growing the pool */
2511         unsigned int                    bc_nbufs;
2512         /* buffer size to post */
2513         unsigned int                    bc_buf_size;
2514         /* portal to listed for requests on */
2515         unsigned int                    bc_req_portal;
2516         /* portal of where to send replies to */
2517         unsigned int                    bc_rep_portal;
2518         /* maximum request size to be accepted for this service */
2519         unsigned int                    bc_req_max_size;
2520         /* maximum reply size this service can ever send */
2521         unsigned int                    bc_rep_max_size;
2522 };
2523
2524 struct ptlrpc_service_thr_conf {
2525         /* threadname should be 8 characters or less - 6 will be added on */
2526         char                            *tc_thr_name;
2527         /* threads increasing factor for each CPU */
2528         unsigned int                    tc_thr_factor;
2529         /* service threads # to start on each partition while initializing */
2530         unsigned int                    tc_nthrs_init;
2531         /*
2532          * low water of threads # upper-limit on each partition while running,
2533          * service availability may be impacted if threads number is lower
2534          * than this value. It can be ZERO if the service doesn't require
2535          * CPU affinity or there is only one partition.
2536          */
2537         unsigned int                    tc_nthrs_base;
2538         /* "soft" limit for total threads number */
2539         unsigned int                    tc_nthrs_max;
2540         /* user specified threads number, it will be validated due to
2541          * other members of this structure.
2542          */
2543         unsigned int                    tc_nthrs_user;
2544         /* set NUMA node affinity for service threads */
2545         unsigned int                    tc_cpu_affinity;
2546         /* Tags for lu_context associated with service thread */
2547         __u32                           tc_ctx_tags;
2548 };
2549
2550 struct ptlrpc_service_cpt_conf {
2551         struct cfs_cpt_table            *cc_cptable;
2552         /* string pattern to describe CPTs for a service */
2553         char                            *cc_pattern;
2554 };
2555
2556 struct ptlrpc_service_conf {
2557         /* service name */
2558         char                            *psc_name;
2559         /* soft watchdog timeout multiplifier to print stuck service traces */
2560         unsigned int                    psc_watchdog_factor;
2561         /* buffer information */
2562         struct ptlrpc_service_buf_conf  psc_buf;
2563         /* thread information */
2564         struct ptlrpc_service_thr_conf  psc_thr;
2565         /* CPU partition information */
2566         struct ptlrpc_service_cpt_conf  psc_cpt;
2567         /* function table */
2568         struct ptlrpc_service_ops       psc_ops;
2569 };
2570
2571 /* ptlrpc/service.c */
2572 /**
2573  * Server-side services API. Register/unregister service, request state
2574  * management, service thread management
2575  *
2576  * @{
2577  */
2578 void ptlrpc_dispatch_difficult_reply(struct ptlrpc_reply_state *rs);
2579 void ptlrpc_schedule_difficult_reply(struct ptlrpc_reply_state *rs);
2580 struct ptlrpc_service *ptlrpc_register_service(struct ptlrpc_service_conf *conf,
2581                                                struct kset *parent,
2582                                                struct dentry *debugfs_entry);
2583
2584 int ptlrpc_start_threads(struct ptlrpc_service *svc);
2585 int ptlrpc_unregister_service(struct ptlrpc_service *service);
2586
2587 int ptlrpc_hr_init(void);
2588 void ptlrpc_hr_fini(void);
2589
2590 /** @} */
2591
2592 /* ptlrpc/import.c */
2593 /**
2594  * Import API
2595  * @{
2596  */
2597 int ptlrpc_connect_import(struct obd_import *imp);
2598 int ptlrpc_init_import(struct obd_import *imp);
2599 int ptlrpc_disconnect_import(struct obd_import *imp, int noclose);
2600 int ptlrpc_import_recovery_state_machine(struct obd_import *imp);
2601
2602 /* ptlrpc/pack_generic.c */
2603 int ptlrpc_reconnect_import(struct obd_import *imp);
2604 /** @} */
2605
2606 /**
2607  * ptlrpc msg buffer and swab interface
2608  *
2609  * @{
2610  */
2611 int ptlrpc_buf_need_swab(struct ptlrpc_request *req, const int inout,
2612                          u32 index);
2613 void ptlrpc_buf_set_swabbed(struct ptlrpc_request *req, const int inout,
2614                             u32 index);
2615 int ptlrpc_unpack_rep_msg(struct ptlrpc_request *req, int len);
2616 int ptlrpc_unpack_req_msg(struct ptlrpc_request *req, int len);
2617
2618 void lustre_init_msg_v2(struct lustre_msg_v2 *msg, int count, __u32 *lens,
2619                         char **bufs);
2620 int lustre_pack_request(struct ptlrpc_request *, __u32 magic, int count,
2621                         __u32 *lens, char **bufs);
2622 int lustre_pack_reply(struct ptlrpc_request *, int count, __u32 *lens,
2623                       char **bufs);
2624 int lustre_pack_reply_v2(struct ptlrpc_request *req, int count,
2625                          __u32 *lens, char **bufs, int flags);
2626 #define LPRFL_EARLY_REPLY 1
2627 int lustre_pack_reply_flags(struct ptlrpc_request *, int count, __u32 *lens,
2628                             char **bufs, int flags);
2629 int lustre_shrink_msg(struct lustre_msg *msg, int segment,
2630                       unsigned int newlen, int move_data);
2631 void lustre_free_reply_state(struct ptlrpc_reply_state *rs);
2632 int __lustre_unpack_msg(struct lustre_msg *m, int len);
2633 u32 lustre_msg_hdr_size(__u32 magic, u32 count);
2634 u32 lustre_msg_size(__u32 magic, int count, __u32 *lengths);
2635 u32 lustre_msg_size_v2(int count, __u32 *lengths);
2636 u32 lustre_packed_msg_size(struct lustre_msg *msg);
2637 u32 lustre_msg_early_size(void);
2638 void *lustre_msg_buf_v2(struct lustre_msg_v2 *m, u32 n, u32 min_size);
2639 void *lustre_msg_buf(struct lustre_msg *m, u32 n, u32 minlen);
2640 u32 lustre_msg_buflen(struct lustre_msg *m, u32 n);
2641 u32 lustre_msg_bufcount(struct lustre_msg *m);
2642 char *lustre_msg_string(struct lustre_msg *m, u32 n, u32 max_len);
2643 __u32 lustre_msghdr_get_flags(struct lustre_msg *msg);
2644 void lustre_msghdr_set_flags(struct lustre_msg *msg, __u32 flags);
2645 __u32 lustre_msg_get_flags(struct lustre_msg *msg);
2646 void lustre_msg_add_flags(struct lustre_msg *msg, u32 flags);
2647 void lustre_msg_set_flags(struct lustre_msg *msg, u32 flags);
2648 void lustre_msg_clear_flags(struct lustre_msg *msg, u32 flags);
2649 __u32 lustre_msg_get_op_flags(struct lustre_msg *msg);
2650 void lustre_msg_add_op_flags(struct lustre_msg *msg, u32 flags);
2651 struct lustre_handle *lustre_msg_get_handle(struct lustre_msg *msg);
2652 __u32 lustre_msg_get_type(struct lustre_msg *msg);
2653 void lustre_msg_add_version(struct lustre_msg *msg, u32 version);
2654 __u32 lustre_msg_get_opc(struct lustre_msg *msg);
2655 __u64 lustre_msg_get_last_committed(struct lustre_msg *msg);
2656 __u64 *lustre_msg_get_versions(struct lustre_msg *msg);
2657 __u64 lustre_msg_get_transno(struct lustre_msg *msg);
2658 __u64 lustre_msg_get_slv(struct lustre_msg *msg);
2659 __u32 lustre_msg_get_limit(struct lustre_msg *msg);
2660 void lustre_msg_set_slv(struct lustre_msg *msg, __u64 slv);
2661 void lustre_msg_set_limit(struct lustre_msg *msg, __u64 limit);
2662 int lustre_msg_get_status(struct lustre_msg *msg);
2663 __u32 lustre_msg_get_conn_cnt(struct lustre_msg *msg);
2664 __u32 lustre_msg_get_magic(struct lustre_msg *msg);
2665 __u32 lustre_msg_get_timeout(struct lustre_msg *msg);
2666 __u32 lustre_msg_get_service_time(struct lustre_msg *msg);
2667 __u32 lustre_msg_get_cksum(struct lustre_msg *msg);
2668 __u32 lustre_msg_calc_cksum(struct lustre_msg *msg);
2669 void lustre_msg_set_handle(struct lustre_msg *msg,
2670                            struct lustre_handle *handle);
2671 void lustre_msg_set_type(struct lustre_msg *msg, __u32 type);
2672 void lustre_msg_set_opc(struct lustre_msg *msg, __u32 opc);
2673 void lustre_msg_set_versions(struct lustre_msg *msg, __u64 *versions);
2674 void lustre_msg_set_transno(struct lustre_msg *msg, __u64 transno);
2675 void lustre_msg_set_status(struct lustre_msg *msg, __u32 status);
2676 void lustre_msg_set_conn_cnt(struct lustre_msg *msg, __u32 conn_cnt);
2677 void ptlrpc_request_set_replen(struct ptlrpc_request *req);
2678 void lustre_msg_set_timeout(struct lustre_msg *msg, __u32 timeout);
2679 void lustre_msg_set_service_time(struct lustre_msg *msg, __u32 service_time);
2680 void lustre_msg_set_jobid(struct lustre_msg *msg, char *jobid);
2681 void lustre_msg_set_cksum(struct lustre_msg *msg, __u32 cksum);
2682
2683 static inline void
2684 lustre_shrink_reply(struct ptlrpc_request *req, int segment,
2685                     unsigned int newlen, int move_data)
2686 {
2687         LASSERT(req->rq_reply_state);
2688         LASSERT(req->rq_repmsg);
2689         req->rq_replen = lustre_shrink_msg(req->rq_repmsg, segment,
2690                                            newlen, move_data);
2691 }
2692
2693 #ifdef CONFIG_LUSTRE_TRANSLATE_ERRNOS
2694
2695 static inline int ptlrpc_status_hton(int h)
2696 {
2697         /*
2698          * Positive errnos must be network errnos, such as LUSTRE_EDEADLK,
2699          * ELDLM_LOCK_ABORTED, etc.
2700          */
2701         if (h < 0)
2702                 return -lustre_errno_hton(-h);
2703         else
2704                 return h;
2705 }
2706
2707 static inline int ptlrpc_status_ntoh(int n)
2708 {
2709         /*
2710          * See the comment in ptlrpc_status_hton().
2711          */
2712         if (n < 0)
2713                 return -lustre_errno_ntoh(-n);
2714         else
2715                 return n;
2716 }
2717
2718 #else
2719
2720 #define ptlrpc_status_hton(h) (h)
2721 #define ptlrpc_status_ntoh(n) (n)
2722
2723 #endif
2724 /** @} */
2725
2726 /** Change request phase of \a req to \a new_phase */
2727 static inline void
2728 ptlrpc_rqphase_move(struct ptlrpc_request *req, enum rq_phase new_phase)
2729 {
2730         if (req->rq_phase == new_phase)
2731                 return;
2732
2733         if (new_phase == RQ_PHASE_UNREG_RPC ||
2734             new_phase == RQ_PHASE_UNREG_BULK) {
2735                 /* No embedded unregistering phases */
2736                 if (req->rq_phase == RQ_PHASE_UNREG_RPC ||
2737                     req->rq_phase == RQ_PHASE_UNREG_BULK)
2738                         return;
2739
2740                 req->rq_next_phase = req->rq_phase;
2741                 if (req->rq_import)
2742                         atomic_inc(&req->rq_import->imp_unregistering);
2743         }
2744
2745         if (req->rq_phase == RQ_PHASE_UNREG_RPC ||
2746             req->rq_phase == RQ_PHASE_UNREG_BULK) {
2747                 if (req->rq_import)
2748                         atomic_dec(&req->rq_import->imp_unregistering);
2749         }
2750
2751         DEBUG_REQ(D_INFO, req, "move req \"%s\" -> \"%s\"",
2752                   ptlrpc_rqphase2str(req), ptlrpc_phase2str(new_phase));
2753
2754         req->rq_phase = new_phase;
2755 }
2756
2757 /**
2758  * Returns true if request \a req got early reply and hard deadline is not met
2759  */
2760 static inline int
2761 ptlrpc_client_early(struct ptlrpc_request *req)
2762 {
2763         return req->rq_early;
2764 }
2765
2766 /**
2767  * Returns true if we got real reply from server for this request
2768  */
2769 static inline int
2770 ptlrpc_client_replied(struct ptlrpc_request *req)
2771 {
2772         if (req->rq_reply_deadline > ktime_get_real_seconds())
2773                 return 0;
2774         return req->rq_replied;
2775 }
2776
2777 /** Returns true if request \a req is in process of receiving server reply */
2778 static inline int
2779 ptlrpc_client_recv(struct ptlrpc_request *req)
2780 {
2781         if (req->rq_reply_deadline > ktime_get_real_seconds())
2782                 return 1;
2783         return req->rq_receiving_reply;
2784 }
2785
2786 static inline int
2787 ptlrpc_client_recv_or_unlink(struct ptlrpc_request *req)
2788 {
2789         int rc;
2790
2791         spin_lock(&req->rq_lock);
2792         if (req->rq_reply_deadline > ktime_get_real_seconds()) {
2793                 spin_unlock(&req->rq_lock);
2794                 return 1;
2795         }
2796         if (req->rq_req_deadline > ktime_get_real_seconds()) {
2797                 spin_unlock(&req->rq_lock);
2798                 return 1;
2799         }
2800         rc = !req->rq_req_unlinked || !req->rq_reply_unlinked ||
2801              req->rq_receiving_reply;
2802         spin_unlock(&req->rq_lock);
2803         return rc;
2804 }
2805
2806 static inline void
2807 ptlrpc_client_wake_req(struct ptlrpc_request *req)
2808 {
2809         if (!req->rq_set)
2810                 wake_up(&req->rq_reply_waitq);
2811         else
2812                 wake_up(&req->rq_set->set_waitq);
2813 }
2814
2815 static inline void
2816 ptlrpc_rs_addref(struct ptlrpc_reply_state *rs)
2817 {
2818         LASSERT(atomic_read(&rs->rs_refcount) > 0);
2819         atomic_inc(&rs->rs_refcount);
2820 }
2821
2822 static inline void
2823 ptlrpc_rs_decref(struct ptlrpc_reply_state *rs)
2824 {
2825         LASSERT(atomic_read(&rs->rs_refcount) > 0);
2826         if (atomic_dec_and_test(&rs->rs_refcount))
2827                 lustre_free_reply_state(rs);
2828 }
2829
2830 /* Should only be called once per req */
2831 static inline void ptlrpc_req_drop_rs(struct ptlrpc_request *req)
2832 {
2833         if (!req->rq_reply_state)
2834                 return; /* shouldn't occur */
2835         ptlrpc_rs_decref(req->rq_reply_state);
2836         req->rq_reply_state = NULL;
2837         req->rq_repmsg = NULL;
2838 }
2839
2840 static inline __u32 lustre_request_magic(struct ptlrpc_request *req)
2841 {
2842         return lustre_msg_get_magic(req->rq_reqmsg);
2843 }
2844
2845 static inline int ptlrpc_req_get_repsize(struct ptlrpc_request *req)
2846 {
2847         switch (req->rq_reqmsg->lm_magic) {
2848         case LUSTRE_MSG_MAGIC_V2:
2849                 return req->rq_reqmsg->lm_repsize;
2850         default:
2851                 LASSERTF(0, "incorrect message magic: %08x\n",
2852                          req->rq_reqmsg->lm_magic);
2853                 return -EFAULT;
2854         }
2855 }
2856
2857 static inline int ptlrpc_send_limit_expired(struct ptlrpc_request *req)
2858 {
2859         if (req->rq_delay_limit != 0 &&
2860             time_before(cfs_time_add(req->rq_queued_time,
2861                                      cfs_time_seconds(req->rq_delay_limit)),
2862                         cfs_time_current())) {
2863                 return 1;
2864         }
2865         return 0;
2866 }
2867
2868 static inline int ptlrpc_no_resend(struct ptlrpc_request *req)
2869 {
2870         if (!req->rq_no_resend && ptlrpc_send_limit_expired(req)) {
2871                 spin_lock(&req->rq_lock);
2872                 req->rq_no_resend = 1;
2873                 spin_unlock(&req->rq_lock);
2874         }
2875         return req->rq_no_resend;
2876 }
2877
2878 static inline int
2879 ptlrpc_server_get_timeout(struct ptlrpc_service_part *svcpt)
2880 {
2881         int at = AT_OFF ? 0 : at_get(&svcpt->scp_at_estimate);
2882
2883         return svcpt->scp_service->srv_watchdog_factor *
2884                max_t(int, at, obd_timeout);
2885 }
2886
2887 static inline struct ptlrpc_service *
2888 ptlrpc_req2svc(struct ptlrpc_request *req)
2889 {
2890         return req->rq_rqbd->rqbd_svcpt->scp_service;
2891 }
2892
2893 /* ldlm/ldlm_lib.c */
2894 /**
2895  * Target client logic
2896  * @{
2897  */
2898 int client_obd_setup(struct obd_device *obddev, struct lustre_cfg *lcfg);
2899 int client_obd_cleanup(struct obd_device *obddev);
2900 int client_connect_import(const struct lu_env *env,
2901                           struct obd_export **exp, struct obd_device *obd,
2902                           struct obd_uuid *cluuid, struct obd_connect_data *,
2903                           void *localdata);
2904 int client_disconnect_export(struct obd_export *exp);
2905 int client_import_add_conn(struct obd_import *imp, struct obd_uuid *uuid,
2906                            int priority);
2907 int client_import_del_conn(struct obd_import *imp, struct obd_uuid *uuid);
2908 int client_import_find_conn(struct obd_import *imp, lnet_nid_t peer,
2909                             struct obd_uuid *uuid);
2910 int import_set_conn_priority(struct obd_import *imp, struct obd_uuid *uuid);
2911 void client_destroy_import(struct obd_import *imp);
2912 /** @} */
2913
2914 /* ptlrpc/pinger.c */
2915 /**
2916  * Pinger API (client side only)
2917  * @{
2918  */
2919 enum timeout_event {
2920         TIMEOUT_GRANT = 1
2921 };
2922
2923 struct timeout_item;
2924 typedef int (*timeout_cb_t)(struct timeout_item *, void *);
2925 int ptlrpc_pinger_add_import(struct obd_import *imp);
2926 int ptlrpc_pinger_del_import(struct obd_import *imp);
2927 int ptlrpc_add_timeout_client(int time, enum timeout_event event,
2928                               timeout_cb_t cb, void *data,
2929                               struct list_head *obd_list);
2930 int ptlrpc_del_timeout_client(struct list_head *obd_list,
2931                               enum timeout_event event);
2932 struct ptlrpc_request *ptlrpc_prep_ping(struct obd_import *imp);
2933 int ptlrpc_obd_ping(struct obd_device *obd);
2934 void ptlrpc_pinger_ir_up(void);
2935 void ptlrpc_pinger_ir_down(void);
2936 /** @} */
2937 int ptlrpc_pinger_suppress_pings(void);
2938
2939 /* ptlrpc/ptlrpcd.c */
2940 void ptlrpcd_stop(struct ptlrpcd_ctl *pc, int force);
2941 void ptlrpcd_free(struct ptlrpcd_ctl *pc);
2942 void ptlrpcd_wake(struct ptlrpc_request *req);
2943 void ptlrpcd_add_req(struct ptlrpc_request *req);
2944 int ptlrpcd_addref(void);
2945 void ptlrpcd_decref(void);
2946
2947 /* ptlrpc/lproc_ptlrpc.c */
2948 /**
2949  * procfs output related functions
2950  * @{
2951  */
2952 const char *ll_opcode2str(__u32 opcode);
2953 void ptlrpc_lprocfs_register_obd(struct obd_device *obd);
2954 void ptlrpc_lprocfs_unregister_obd(struct obd_device *obd);
2955 void ptlrpc_lprocfs_brw(struct ptlrpc_request *req, int bytes);
2956 /** @} */
2957
2958 /* ptlrpc/llog_client.c */
2959 extern struct llog_operations llog_client_ops;
2960 /** @} net */
2961
2962 #endif
2963 /** @} PtlRPC */