Whamcloud - gitweb
LU-15068 ptlrpc: Do not unlink difficult reply until sent
[fs/lustre-release.git] / 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, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  */
31 /** \defgroup PtlRPC Portal RPC and networking module.
32  *
33  * PortalRPC is the layer used by rest of lustre code to achieve network
34  * communications: establish connections with corresponding export and import
35  * states, listen for a service, send and receive RPCs.
36  * PortalRPC also includes base recovery framework: packet resending and
37  * replaying, reconnections, pinger.
38  *
39  * PortalRPC utilizes LNet as its transport layer.
40  *
41  * @{
42  */
43
44
45 #ifndef _LUSTRE_NET_H
46 #define _LUSTRE_NET_H
47
48 /** \defgroup net net
49  *
50  * @{
51  */
52 #include <linux/kobject.h>
53 #include <linux/rhashtable.h>
54 #include <linux/uio.h>
55 #include <libcfs/libcfs.h>
56 #include <lnet/api.h>
57 #include <lnet/lib-types.h>
58 #include <uapi/linux/lnet/nidstr.h>
59 #include <uapi/linux/lustre/lustre_idl.h>
60 #include <lustre_ha.h>
61 #include <lustre_sec.h>
62 #include <lustre_import.h>
63 #include <lprocfs_status.h>
64 #include <lu_object.h>
65 #include <lustre_req_layout.h>
66 #include <obd_support.h>
67 #include <uapi/linux/lustre/lustre_ver.h>
68
69 /* MD flags we _always_ use */
70 #define PTLRPC_MD_OPTIONS  0
71
72 /**
73  * log2 max # of bulk operations in one request: 2=4MB/RPC, 5=32MB/RPC, ...
74  * In order for the client and server to properly negotiate the maximum
75  * possible transfer size, PTLRPC_BULK_OPS_COUNT must be a power-of-two
76  * value.  The client is free to limit the actual RPC size for any bulk
77  * transfer via cl_max_pages_per_rpc to some non-power-of-two value.
78  * NOTE: This is limited to 16 (=64GB RPCs) by IOOBJ_MAX_BRW_BITS. */
79 #define PTLRPC_BULK_OPS_BITS    6
80 #if PTLRPC_BULK_OPS_BITS > 16
81 #error "More than 65536 BRW RPCs not allowed by IOOBJ_MAX_BRW_BITS."
82 #endif
83 #define PTLRPC_BULK_OPS_COUNT   (1U << PTLRPC_BULK_OPS_BITS)
84 /**
85  * PTLRPC_BULK_OPS_MASK is for the convenience of the client only, and
86  * should not be used on the server at all.  Otherwise, it imposes a
87  * protocol limitation on the maximum RPC size that can be used by any
88  * RPC sent to that server in the future.  Instead, the server should
89  * use the negotiated per-client ocd_brw_size to determine the bulk
90  * RPC count. */
91 #define PTLRPC_BULK_OPS_MASK    (~((__u64)PTLRPC_BULK_OPS_COUNT - 1))
92
93 /**
94  * Define maxima for bulk I/O.
95  *
96  * A single PTLRPC BRW request is sent via up to PTLRPC_BULK_OPS_COUNT
97  * of LNET_MTU sized RDMA transfers.  Clients and servers negotiate the
98  * currently supported maximum between peers at connect via ocd_brw_size.
99  */
100 #define PTLRPC_MAX_BRW_BITS     (LNET_MTU_BITS + PTLRPC_BULK_OPS_BITS)
101 #define PTLRPC_MAX_BRW_SIZE     (1U << PTLRPC_MAX_BRW_BITS)
102 #define PTLRPC_MAX_BRW_PAGES    (PTLRPC_MAX_BRW_SIZE >> PAGE_SHIFT)
103
104 #define ONE_MB_BRW_SIZE         (1U << LNET_MTU_BITS)
105 #define MD_MAX_BRW_SIZE         (1U << LNET_MTU_BITS)
106 #define MD_MAX_BRW_PAGES        (MD_MAX_BRW_SIZE >> PAGE_SHIFT)
107 #define DT_MAX_BRW_SIZE         PTLRPC_MAX_BRW_SIZE
108 #define DT_DEF_BRW_SIZE         (4 * ONE_MB_BRW_SIZE)
109 #define DT_MAX_BRW_PAGES        (DT_MAX_BRW_SIZE >> PAGE_SHIFT)
110 #define OFD_MAX_BRW_SIZE        (1U << LNET_MTU_BITS)
111
112 /* When PAGE_SIZE is a constant, we can check our arithmetic here with cpp! */
113 #if ((PTLRPC_MAX_BRW_PAGES & (PTLRPC_MAX_BRW_PAGES - 1)) != 0)
114 # error "PTLRPC_MAX_BRW_PAGES isn't a power of two"
115 #endif
116 #if (PTLRPC_MAX_BRW_SIZE != (PTLRPC_MAX_BRW_PAGES * PAGE_SIZE))
117 # error "PTLRPC_MAX_BRW_SIZE isn't PTLRPC_MAX_BRW_PAGES * PAGE_SIZE"
118 #endif
119 #if (PTLRPC_MAX_BRW_SIZE > LNET_MTU * PTLRPC_BULK_OPS_COUNT)
120 # error "PTLRPC_MAX_BRW_SIZE too big"
121 #endif
122 #if (PTLRPC_MAX_BRW_PAGES > LNET_MAX_IOV * PTLRPC_BULK_OPS_COUNT)
123 # error "PTLRPC_MAX_BRW_PAGES too big"
124 #endif
125
126 #define PTLRPC_NTHRS_INIT       2
127
128 /**
129  * Buffer Constants
130  *
131  * Constants determine how memory is used to buffer incoming service requests.
132  *
133  * ?_NBUFS              # buffers to allocate when growing the pool
134  * ?_BUFSIZE            # bytes in a single request buffer
135  * ?_MAXREQSIZE         # maximum request service will receive
136  *
137  * When fewer than ?_NBUFS/2 buffers are posted for receive, another chunk
138  * of ?_NBUFS is added to the pool.
139  *
140  * Messages larger than ?_MAXREQSIZE are dropped.  Request buffers are
141  * considered full when less than ?_MAXREQSIZE is left in them.
142  */
143 /**
144  * Thread Constants
145  *
146  * Constants determine how threads are created for ptlrpc service.
147  *
148  * ?_NTHRS_INIT         # threads to create for each service partition on
149  *                        initializing. If it's non-affinity service and
150  *                        there is only one partition, it's the overall #
151  *                        threads for the service while initializing.
152  * ?_NTHRS_BASE         # threads should be created at least for each
153  *                        ptlrpc partition to keep the service healthy.
154  *                        It's the low-water mark of threads upper-limit
155  *                        for each partition.
156  * ?_THR_FACTOR         # threads can be added on threads upper-limit for
157  *                        each CPU core. This factor is only for reference,
158  *                        we might decrease value of factor if number of cores
159  *                        per CPT is above a limit.
160  * ?_NTHRS_MAX          # overall threads can be created for a service,
161  *                        it's a soft limit because if service is running
162  *                        on machine with hundreds of cores and tens of
163  *                        CPU partitions, we need to guarantee each partition
164  *                        has ?_NTHRS_BASE threads, which means total threads
165  *                        will be ?_NTHRS_BASE * number_of_cpts which can
166  *                        exceed ?_NTHRS_MAX.
167  *
168  * Examples
169  *
170  * #define MDS_NTHRS_INIT       2
171  * #define MDS_NTHRS_BASE       64
172  * #define MDS_NTHRS_FACTOR     8
173  * #define MDS_NTHRS_MAX        1024
174  *
175  * Example 1):
176  * ---------------------------------------------------------------------
177  * Server(A) has 16 cores, user configured it to 4 partitions so each
178  * partition has 4 cores, then actual number of service threads on each
179  * partition is:
180  *     MDS_NTHRS_BASE(64) + cores(4) * MDS_NTHRS_FACTOR(8) = 96
181  *
182  * Total number of threads for the service is:
183  *     96 * partitions(4) = 384
184  *
185  * Example 2):
186  * ---------------------------------------------------------------------
187  * Server(B) has 32 cores, user configured it to 4 partitions so each
188  * partition has 8 cores, then actual number of service threads on each
189  * partition is:
190  *     MDS_NTHRS_BASE(64) + cores(8) * MDS_NTHRS_FACTOR(8) = 128
191  *
192  * Total number of threads for the service is:
193  *     128 * partitions(4) = 512
194  *
195  * Example 3):
196  * ---------------------------------------------------------------------
197  * Server(B) has 96 cores, user configured it to 8 partitions so each
198  * partition has 12 cores, then actual number of service threads on each
199  * partition is:
200  *     MDS_NTHRS_BASE(64) + cores(12) * MDS_NTHRS_FACTOR(8) = 160
201  *
202  * Total number of threads for the service is:
203  *     160 * partitions(8) = 1280
204  *
205  * However, it's above the soft limit MDS_NTHRS_MAX, so we choose this number
206  * as upper limit of threads number for each partition:
207  *     MDS_NTHRS_MAX(1024) / partitions(8) = 128
208  *
209  * Example 4):
210  * ---------------------------------------------------------------------
211  * Server(C) have a thousand of cores and user configured it to 32 partitions
212  *     MDS_NTHRS_BASE(64) * 32 = 2048
213  *
214  * which is already above soft limit MDS_NTHRS_MAX(1024), but we still need
215  * to guarantee that each partition has at least MDS_NTHRS_BASE(64) threads
216  * to keep service healthy, so total number of threads will just be 2048.
217  *
218  * NB: we don't suggest to choose server with that many cores because backend
219  *     filesystem itself, buffer cache, or underlying network stack might
220  *     have some SMP scalability issues at that large scale.
221  *
222  *     If user already has a fat machine with hundreds or thousands of cores,
223  *     there are two choices for configuration:
224  *     a) create CPU table from subset of all CPUs and run Lustre on
225  *        top of this subset
226  *     b) bind service threads on a few partitions, see modparameters of
227  *        MDS and OSS for details
228 *
229  * NB: these calculations (and examples below) are simplified to help
230  *     understanding, the real implementation is a little more complex,
231  *     please see ptlrpc_server_nthreads_check() for details.
232  *
233  */
234
235  /*
236   * LDLM threads constants:
237   *
238   * Given 8 as factor and 24 as base threads number
239   *
240   * example 1)
241   * On 4-core machine we will have 24 + 8 * 4 = 56 threads.
242   *
243   * example 2)
244   * On 8-core machine with 2 partitions we will have 24 + 4 * 8 = 56
245   * threads for each partition and total threads number will be 112.
246   *
247   * example 3)
248   * On 64-core machine with 8 partitions we will need LDLM_NTHRS_BASE(24)
249   * threads for each partition to keep service healthy, so total threads
250   * number should be 24 * 8 = 192.
251   *
252   * So with these constants, threads number will be at the similar level
253   * of old versions, unless target machine has over a hundred cores
254   */
255 #define LDLM_THR_FACTOR         8
256 #define LDLM_NTHRS_INIT         PTLRPC_NTHRS_INIT
257 #define LDLM_NTHRS_BASE         24
258 #define LDLM_NTHRS_MAX          (num_online_cpus() == 1 ? 64 : 128)
259
260 #define LDLM_BL_THREADS   LDLM_NTHRS_AUTO_INIT
261 #define LDLM_CLIENT_NBUFS 1
262 #define LDLM_SERVER_NBUFS 64
263 #define LDLM_BUFSIZE      (8 * 1024)
264 #define LDLM_MAXREQSIZE   (5 * 1024)
265 #define LDLM_MAXREPSIZE   (1024)
266
267  /*
268   * MDS threads constants:
269   *
270   * Please see examples in "Thread Constants", MDS threads number will be at
271   * the comparable level of old versions, unless the server has many cores.
272   */
273 #ifndef MDS_MAX_THREADS
274 #define MDS_MAX_THREADS         1024
275 #define MDS_MAX_OTHR_THREADS    256
276
277 #else /* MDS_MAX_THREADS */
278 #if MDS_MAX_THREADS < PTLRPC_NTHRS_INIT
279 #undef MDS_MAX_THREADS
280 #define MDS_MAX_THREADS PTLRPC_NTHRS_INIT
281 #endif
282 #define MDS_MAX_OTHR_THREADS    max(PTLRPC_NTHRS_INIT, MDS_MAX_THREADS / 2)
283 #endif
284
285 /* default service */
286 #define MDS_THR_FACTOR          8
287 #define MDS_NTHRS_INIT          PTLRPC_NTHRS_INIT
288 #define MDS_NTHRS_MAX           MDS_MAX_THREADS
289 #define MDS_NTHRS_BASE          min(64, MDS_NTHRS_MAX)
290
291 /* read-page service */
292 #define MDS_RDPG_THR_FACTOR     4
293 #define MDS_RDPG_NTHRS_INIT     PTLRPC_NTHRS_INIT
294 #define MDS_RDPG_NTHRS_MAX      MDS_MAX_OTHR_THREADS
295 #define MDS_RDPG_NTHRS_BASE     min(48, MDS_RDPG_NTHRS_MAX)
296
297 /* these should be removed when we remove setattr service in the future */
298 #define MDS_SETA_THR_FACTOR     4
299 #define MDS_SETA_NTHRS_INIT     PTLRPC_NTHRS_INIT
300 #define MDS_SETA_NTHRS_MAX      MDS_MAX_OTHR_THREADS
301 #define MDS_SETA_NTHRS_BASE     min(48, MDS_SETA_NTHRS_MAX)
302
303 /* non-affinity threads */
304 #define MDS_OTHR_NTHRS_INIT     PTLRPC_NTHRS_INIT
305 #define MDS_OTHR_NTHRS_MAX      MDS_MAX_OTHR_THREADS
306
307 #define MDS_NBUFS               64
308
309 /**
310  * Assume file name length = FNAME_MAX = 256 (true for ext3).
311  *        path name length = PATH_MAX = 4096
312  *        LOV MD size max  = EA_MAX = 24 * 2000
313  *              (NB: 24 is size of lov_ost_data)
314  *        LOV LOGCOOKIE size max = 32 * 2000
315  *              (NB: 32 is size of llog_cookie)
316  * symlink:  FNAME_MAX + PATH_MAX  <- largest
317  * link:     FNAME_MAX + PATH_MAX  (mds_rec_link < mds_rec_create)
318  * rename:   FNAME_MAX + FNAME_MAX
319  * open:     FNAME_MAX + EA_MAX
320  *
321  * MDS_MAXREQSIZE ~= 4736 bytes =
322  * lustre_msg + ldlm_request + mdt_body + mds_rec_create + FNAME_MAX + PATH_MAX
323  * MDS_MAXREPSIZE ~= 8300 bytes = lustre_msg + llog_header
324  *
325  * Realistic size is about 512 bytes (20 character name + 128 char symlink),
326  * except in the open case where there are a large number of OSTs in a LOV.
327  */
328 #define MDS_MAXREQSIZE          (5 * 1024)      /* >= 4736 */
329 #define MDS_MAXREPSIZE          (9 * 1024)      /* >= 8300 */
330
331 /**
332  * MDS incoming request with LOV EA
333  * 24 = sizeof(struct lov_ost_data), i.e: replay of opencreate
334  */
335 #define MDS_LOV_MAXREQSIZE      max(MDS_MAXREQSIZE, \
336                                     362 + LOV_MAX_STRIPE_COUNT * 24)
337 /**
338  * MDS outgoing reply with LOV EA
339  *
340  * NB: max reply size Lustre 2.4+ client can get from old MDS is:
341  * LOV_MAX_STRIPE_COUNT * (llog_cookie + lov_ost_data) + extra bytes
342  *
343  * but 2.4 or later MDS will never send reply with llog_cookie to any
344  * version client. This macro is defined for server side reply buffer size.
345  */
346 #define MDS_LOV_MAXREPSIZE      MDS_LOV_MAXREQSIZE
347
348 /**
349  * This is the size of a maximum REINT_SETXATTR request:
350  *
351  *   lustre_msg          56 (32 + 4 x 5 + 4)
352  *   ptlrpc_body        184
353  *   mdt_rec_setxattr   136
354  *   lustre_capa        120
355  *   name               256 (XATTR_NAME_MAX)
356  *   value            65536 (XATTR_SIZE_MAX)
357  */
358 #define MDS_EA_MAXREQSIZE       66288
359
360 /**
361  * These are the maximum request and reply sizes (rounded up to 1 KB
362  * boundaries) for the "regular" MDS_REQUEST_PORTAL and MDS_REPLY_PORTAL.
363  */
364 #define MDS_REG_MAXREQSIZE      (((max(MDS_EA_MAXREQSIZE, \
365                                        MDS_LOV_MAXREQSIZE) + 1023) >> 10) << 10)
366 #define MDS_REG_MAXREPSIZE      MDS_REG_MAXREQSIZE
367
368 /**
369  * The update request includes all of updates from the create, which might
370  * include linkea (4K maxim), together with other updates, we set it to 1000K:
371  * lustre_msg + ptlrpc_body + OUT_UPDATE_BUFFER_SIZE_MAX
372  */
373 #define OUT_MAXREQSIZE  (1000 * 1024)
374 #define OUT_MAXREPSIZE  MDS_MAXREPSIZE
375
376 /** MDS_BUFSIZE = max_reqsize (w/o LOV EA) + max sptlrpc payload size */
377 #define MDS_BUFSIZE             max(MDS_MAXREQSIZE + SPTLRPC_MAX_PAYLOAD, \
378                                     8 * 1024)
379
380 /**
381  * MDS_REG_BUFSIZE should at least be MDS_REG_MAXREQSIZE + SPTLRPC_MAX_PAYLOAD.
382  * However, we need to allocate a much larger buffer for it because LNet
383  * requires each MD(rqbd) has at least MDS_REQ_MAXREQSIZE bytes left to avoid
384  * dropping of maximum-sized incoming request.  So if MDS_REG_BUFSIZE is only a
385  * little larger than MDS_REG_MAXREQSIZE, then it can only fit in one request
386  * even there are about MDS_REG_MAX_REQSIZE bytes left in a rqbd, and memory
387  * utilization is very low.
388  *
389  * In the meanwhile, size of rqbd can't be too large, because rqbd can't be
390  * reused until all requests fit in it have been processed and released,
391  * which means one long blocked request can prevent the rqbd be reused.
392  * Now we set request buffer size to 160 KB, so even each rqbd is unlinked
393  * from LNet with unused 65 KB, buffer utilization will be about 59%.
394  * Please check LU-2432 for details.
395  */
396 #define MDS_REG_BUFSIZE         max(MDS_REG_MAXREQSIZE + SPTLRPC_MAX_PAYLOAD, \
397                                     160 * 1024)
398
399 /**
400  * OUT_BUFSIZE = max_out_reqsize + max sptlrpc payload (~1K) which is
401  * about 10K, for the same reason as MDS_REG_BUFSIZE, we also give some
402  * extra bytes to each request buffer to improve buffer utilization rate.
403   */
404 #define OUT_BUFSIZE             max(OUT_MAXREQSIZE + SPTLRPC_MAX_PAYLOAD, \
405                                     24 * 1024)
406
407 /** FLD_MAXREQSIZE == lustre_msg + __u32 padding + ptlrpc_body + opc */
408 #define FLD_MAXREQSIZE  (160)
409
410 /** FLD_MAXREPSIZE == lustre_msg + ptlrpc_body */
411 #define FLD_MAXREPSIZE  (152)
412 #define FLD_BUFSIZE     (1 << 12)
413
414 /**
415  * SEQ_MAXREQSIZE == lustre_msg + __u32 padding + ptlrpc_body + opc + lu_range +
416  * __u32 padding */
417 #define SEQ_MAXREQSIZE  (160)
418
419 /** SEQ_MAXREPSIZE == lustre_msg + ptlrpc_body + lu_range */
420 #define SEQ_MAXREPSIZE  (152)
421 #define SEQ_BUFSIZE     (1 << 12)
422
423 /** MGS threads must be >= 3, see bug 22458 comment #28 */
424 #define MGS_NTHRS_INIT  (PTLRPC_NTHRS_INIT + 1)
425 #define MGS_NTHRS_MAX   32
426
427 #define MGS_NBUFS       64
428 #define MGS_BUFSIZE     (8 * 1024)
429 #define MGS_MAXREQSIZE  (7 * 1024)
430 #define MGS_MAXREPSIZE  (9 * 1024)
431
432  /*
433   * OSS threads constants:
434   *
435   * Given 8 as factor and 64 as base threads number
436   *
437   * example 1):
438   * On 8-core server configured to 2 partitions, we will have
439   * 64 + 8 * 4 = 96 threads for each partition, 192 total threads.
440   *
441   * example 2):
442   * On 32-core machine configured to 4 partitions, we will have
443   * 64 + 8 * 8 = 112 threads for each partition, so total threads number
444   * will be 112 * 4 = 448.
445   *
446   * example 3):
447   * On 64-core machine configured to 4 partitions, we will have
448   * 64 + 16 * 8 = 192 threads for each partition, so total threads number
449   * will be 192 * 4 = 768 which is above limit OSS_NTHRS_MAX(512), so we
450   * cut off the value to OSS_NTHRS_MAX(512) / 4 which is 128 threads
451   * for each partition.
452   *
453   * So we can see that with these constants, threads number wil be at the
454   * similar level of old versions, unless the server has many cores.
455   */
456  /* depress threads factor for VM with small memory size */
457 #define OSS_THR_FACTOR          min_t(int, 8, \
458                                 NUM_CACHEPAGES >> (28 - PAGE_SHIFT))
459 #define OSS_NTHRS_INIT          (PTLRPC_NTHRS_INIT + 1)
460 #define OSS_NTHRS_BASE          64
461
462 /* threads for handling "create" request */
463 #define OSS_CR_THR_FACTOR       1
464 #define OSS_CR_NTHRS_INIT       PTLRPC_NTHRS_INIT
465 #define OSS_CR_NTHRS_BASE       8
466 #define OSS_CR_NTHRS_MAX        64
467
468 /**
469  * OST_IO_MAXREQSIZE ~=
470  *      lustre_msg + ptlrpc_body + obdo + obd_ioobj +
471  *      DT_MAX_BRW_PAGES * niobuf_remote
472  *
473  * - single object with 16 pages is 512 bytes
474  * - OST_IO_MAXREQSIZE must be at least 1 niobuf per page of data
475  * - Must be a multiple of 1024
476  * - should allow a reasonably large SHORT_IO_BYTES size (64KB)
477  */
478 #define _OST_MAXREQSIZE_BASE ((unsigned long)(sizeof(struct lustre_msg)   + \
479                              /* lm_buflens */ sizeof(__u32) * 4           + \
480                                               sizeof(struct ptlrpc_body)  + \
481                                               sizeof(struct obdo)         + \
482                                               sizeof(struct obd_ioobj)    + \
483                                               sizeof(struct niobuf_remote)))
484 #define _OST_MAXREQSIZE_SUM ((unsigned long)(_OST_MAXREQSIZE_BASE         + \
485                                              sizeof(struct niobuf_remote) * \
486                                              DT_MAX_BRW_PAGES))
487 /**
488  * FIEMAP request can be 4K+ for now
489  */
490 #define OST_MAXREQSIZE          (16UL * 1024UL)
491 #define OST_IO_MAXREQSIZE       max(OST_MAXREQSIZE,                     \
492                                    ((_OST_MAXREQSIZE_SUM - 1) |         \
493                                     (1024UL - 1)) + 1)
494 /* Safe estimate of free space in standard RPC, provides upper limit for # of
495  * bytes of i/o to pack in RPC (skipping bulk transfer). */
496 #define OST_MAX_SHORT_IO_BYTES  ((OST_IO_MAXREQSIZE - _OST_MAXREQSIZE_BASE) & \
497                                  PAGE_MASK)
498
499 /* Actual size used for short i/o buffer.  Calculation means this:
500  * At least one page (for large PAGE_SIZE), or 16 KiB, but not more
501  * than the available space aligned to a page boundary. */
502 #define OBD_DEF_SHORT_IO_BYTES  min(max(PAGE_SIZE, 16UL * 1024UL), \
503                                     OST_MAX_SHORT_IO_BYTES)
504
505 #define OST_MAXREPSIZE          (9 * 1024)
506 #define OST_IO_MAXREPSIZE       OST_MAXREPSIZE
507
508 #define OST_NBUFS               64
509 /** OST_BUFSIZE = max_reqsize + max sptlrpc payload size */
510 #define OST_BUFSIZE             max_t(int, OST_MAXREQSIZE + 1024, 32 * 1024)
511 /**
512  * OST_IO_MAXREQSIZE is 18K, giving extra 46K can increase buffer utilization
513  * rate of request buffer, please check comment of MDS_LOV_BUFSIZE for details.
514  */
515 #define OST_IO_BUFSIZE          max_t(int, OST_IO_MAXREQSIZE + 1024, 64 * 1024)
516
517 /* Macro to hide a typecast and BUILD_BUG. */
518 #define ptlrpc_req_async_args(_var, req) ({                             \
519                 BUILD_BUG_ON(sizeof(*_var) > sizeof(req->rq_async_args)); \
520                 (typeof(_var))&req->rq_async_args;                      \
521         })
522
523 struct ptlrpc_replay_async_args {
524         int             praa_old_state;
525         int             praa_old_status;
526 };
527
528 /**
529  * Structure to single define portal connection.
530  */
531 struct ptlrpc_connection {
532         /** linkage for connections hash table */
533         struct rhash_head       c_hash;
534         /** Our own lnet nid for this connection */
535         lnet_nid_t              c_self;
536         /** Remote side nid for this connection */
537         struct lnet_process_id       c_peer;
538         /** UUID of the other side */
539         struct obd_uuid         c_remote_uuid;
540         /** reference counter for this connection */
541         atomic_t            c_refcount;
542 };
543
544 /** Client definition for PortalRPC */
545 struct ptlrpc_client {
546         /** What lnet portal does this client send messages to by default */
547         __u32                   cli_request_portal;
548         /** What portal do we expect replies on */
549         __u32                   cli_reply_portal;
550         /** Name of the client */
551         const char              *cli_name;
552 };
553
554 /** state flags of requests */
555 /* XXX only ones left are those used by the bulk descs as well! */
556 #define PTL_RPC_FL_INTR         BIT(0)  /* reply wait was interrupted by user */
557 #define PTL_RPC_FL_TIMEOUT      BIT(7)  /* request timed out waiting for reply */
558
559 #define REQ_MAX_ACK_LOCKS 8
560
561 union ptlrpc_async_args {
562         /**
563          * Scratchpad for passing args to completion interpreter. Users
564          * cast to the struct of their choosing, and BUILD_BUG_ON that this is
565          * big enough.  For _tons_ of context, OBD_ALLOC a struct and store
566          * a pointer to it here.  The pointer_arg ensures this struct is at
567          * least big enough for that.
568          */
569         void    *pointer_arg[11];
570         __u64   space[7];
571 };
572
573 struct ptlrpc_request_set;
574 typedef int (*set_producer_func)(struct ptlrpc_request_set *, void *);
575
576 /**
577  * Definition of request set structure.
578  * Request set is a list of requests (not necessary to the same target) that
579  * once populated with RPCs could be sent in parallel.
580  * There are two kinds of request sets. General purpose and with dedicated
581  * serving thread. Example of the latter is ptlrpcd set.
582  * For general purpose sets once request set started sending it is impossible
583  * to add new requests to such set.
584  * Provides a way to call "completion callbacks" when all requests in the set
585  * returned.
586  */
587 struct ptlrpc_request_set {
588         atomic_t                set_refcount;
589         /** number of in queue requests */
590         atomic_t                set_new_count;
591         /** number of uncompleted requests */
592         atomic_t                set_remaining;
593         /** wait queue to wait on for request events */
594         wait_queue_head_t       set_waitq;
595         /** List of requests in the set */
596         struct list_head        set_requests;
597         /**
598          * Lock for \a set_new_requests manipulations
599          * locked so that any old caller can communicate requests to
600          * the set holder who can then fold them into the lock-free set
601          */
602         spinlock_t              set_new_req_lock;
603         /** List of new yet unsent requests. Only used with ptlrpcd now. */
604         struct list_head        set_new_requests;
605
606         /** rq_status of requests that have been freed already */
607         int                     set_rc;
608         /** Additional fields used by the flow control extension */
609         /** Maximum number of RPCs in flight */
610         int                     set_max_inflight;
611         /** Callback function used to generate RPCs */
612         set_producer_func       set_producer;
613         /** opaq argument passed to the producer callback */
614         void                    *set_producer_arg;
615         unsigned int             set_allow_intr:1;
616 };
617
618 struct ptlrpc_bulk_desc;
619 struct ptlrpc_service_part;
620 struct ptlrpc_service;
621
622 /**
623  * ptlrpc callback & work item stuff
624  */
625 struct ptlrpc_cb_id {
626         void (*cbid_fn)(struct lnet_event *ev); /* specific callback fn */
627         void *cbid_arg;                         /* additional arg */
628 };
629
630 /** Maximum number of locks to fit into reply state */
631 #define RS_MAX_LOCKS 8
632 #define RS_DEBUG     0
633
634 /**
635  * Structure to define reply state on the server
636  * Reply state holds various reply message information. Also for "difficult"
637  * replies (rep-ack case) we store the state after sending reply and wait
638  * for the client to acknowledge the reception. In these cases locks could be
639  * added to the state for replay/failover consistency guarantees.
640  */
641 struct ptlrpc_reply_state {
642         /** Callback description */
643         struct ptlrpc_cb_id     rs_cb_id;
644         /** Linkage for list of all reply states in a system */
645         struct list_head        rs_list;
646         /** Linkage for list of all reply states on same export */
647         struct list_head        rs_exp_list;
648         /** Linkage for list of all reply states for same obd */
649         struct list_head        rs_obd_list;
650 #if RS_DEBUG
651         struct list_head        rs_debug_list;
652 #endif
653         /** A spinlock to protect the reply state flags */
654         spinlock_t              rs_lock;
655         /** Reply state flags */
656         unsigned long           rs_difficult:1;     /* ACK/commit stuff */
657         unsigned long           rs_no_ack:1;    /* no ACK, even for
658                                                   difficult requests */
659         unsigned long           rs_scheduled:1;     /* being handled? */
660         unsigned long           rs_scheduled_ever:1;/* any schedule attempts? */
661         unsigned long           rs_handled:1;  /* been handled yet? */
662         unsigned long           rs_sent:1;   /* Got LNET_EVENT_SEND? */
663         unsigned long           rs_unlinked:1; /* Reply MD unlinked? */
664         unsigned long           rs_prealloc:1; /* rs from prealloc list */
665         unsigned long           rs_committed:1;/* the transaction was committed
666                                                  and the rs was dispatched
667                                                  by ptlrpc_commit_replies */
668         unsigned long           rs_convert_lock:1; /* need to convert saved
669                                                     * locks to COS mode */
670         atomic_t                rs_refcount;    /* number of users */
671         /** Number of locks awaiting client ACK */
672         int                     rs_nlocks;
673
674         /** Size of the state */
675         int                     rs_size;
676         /** opcode */
677         __u32                   rs_opc;
678         /** Transaction number */
679         __u64                   rs_transno;
680         /** xid */
681         __u64                   rs_xid;
682         struct obd_export       *rs_export;
683         struct ptlrpc_service_part *rs_svcpt;
684         /** Lnet metadata handle for the reply */
685         struct lnet_handle_md   rs_md_h;
686
687         /** Context for the sevice thread */
688         struct ptlrpc_svc_ctx   *rs_svc_ctx;
689         /** Reply buffer (actually sent to the client), encoded if needed */
690         struct lustre_msg       *rs_repbuf;     /* wrapper */
691         /** Size of the reply buffer */
692         int                     rs_repbuf_len;  /* wrapper buf length */
693         /** Size of the reply message */
694         int                     rs_repdata_len; /* wrapper msg length */
695         /**
696          * Actual reply message. Its content is encrupted (if needed) to
697          * produce reply buffer for actual sending. In simple case
698          * of no network encryption we jus set \a rs_repbuf to \a rs_msg
699          */
700         struct lustre_msg       *rs_msg;        /* reply message */
701
702         /** Handles of locks awaiting client reply ACK */
703         struct lustre_handle    rs_locks[RS_MAX_LOCKS];
704         /** Lock modes of locks in \a rs_locks */
705         enum ldlm_mode          rs_modes[RS_MAX_LOCKS];
706 };
707
708 struct ptlrpc_thread;
709
710 /** RPC stages */
711 enum rq_phase {
712         RQ_PHASE_NEW            = 0xebc0de00,
713         RQ_PHASE_RPC            = 0xebc0de01,
714         RQ_PHASE_BULK           = 0xebc0de02,
715         RQ_PHASE_INTERPRET      = 0xebc0de03,
716         RQ_PHASE_COMPLETE       = 0xebc0de04,
717         RQ_PHASE_UNREG_RPC      = 0xebc0de05,
718         RQ_PHASE_UNREG_BULK     = 0xebc0de06,
719         RQ_PHASE_UNDEFINED      = 0xebc0de07
720 };
721
722 /** Type of request interpreter call-back */
723 typedef int (*ptlrpc_interpterer_t)(const struct lu_env *env,
724                                     struct ptlrpc_request *req,
725                                     void *arg, int rc);
726 /** Type of request resend call-back */
727 typedef void (*ptlrpc_resend_cb_t)(struct ptlrpc_request *req,
728                                    void *arg);
729
730 /**
731  * Definition of request pool structure.
732  * The pool is used to store empty preallocated requests for the case
733  * when we would actually need to send something without performing
734  * any allocations (to avoid e.g. OOM).
735  */
736 struct ptlrpc_request_pool {
737         /** Locks the list */
738         spinlock_t              prp_lock;
739         /** list of ptlrpc_request structs */
740         struct list_head        prp_req_list;
741         /** Maximum message size that would fit into a rquest from this pool */
742         int                     prp_rq_size;
743         /** Function to allocate more requests for this pool */
744         int (*prp_populate)(struct ptlrpc_request_pool *, int);
745 };
746
747 struct lu_context;
748 struct lu_env;
749
750 struct ldlm_lock;
751
752 #include <lustre_nrs.h>
753
754 /**
755  * Basic request prioritization operations structure.
756  * The whole idea is centered around locks and RPCs that might affect locks.
757  * When a lock is contended we try to give priority to RPCs that might lead
758  * to fastest release of that lock.
759  * Currently only implemented for OSTs only in a way that makes all
760  * IO and truncate RPCs that are coming from a locked region where a lock is
761  * contended a priority over other requests.
762  */
763 struct ptlrpc_hpreq_ops {
764         /**
765          * Check if the lock handle of the given lock is the same as
766          * taken from the request.
767          */
768         int  (*hpreq_lock_match)(struct ptlrpc_request *, struct ldlm_lock *);
769         /**
770          * Check if the request is a high priority one.
771          */
772         int  (*hpreq_check)(struct ptlrpc_request *);
773         /**
774          * Called after the request has been handled.
775          */
776         void (*hpreq_fini)(struct ptlrpc_request *);
777 };
778
779 struct ptlrpc_cli_req {
780         /** For bulk requests on client only: bulk descriptor */
781         struct ptlrpc_bulk_desc         *cr_bulk;
782         /** optional time limit for send attempts. This is a timeout
783          *  not a timestamp so timeout_t (s32) is used instead of time64_t
784          */
785         timeout_t                        cr_delay_limit;
786         /** time request was first queued */
787         time64_t                         cr_queued_time;
788         /** request sent in nanoseconds */
789         ktime_t                          cr_sent_ns;
790         /** time for request really sent out */
791         time64_t                         cr_sent_out;
792         /** when req reply unlink must finish. */
793         time64_t                         cr_reply_deadline;
794         /** when req bulk unlink must finish. */
795         time64_t                         cr_bulk_deadline;
796         /** when req unlink must finish. */
797         time64_t                         cr_req_deadline;
798         /** Portal to which this request would be sent */
799         short                            cr_req_ptl;
800         /** Portal where to wait for reply and where reply would be sent */
801         short                            cr_rep_ptl;
802         /** request resending number */
803         unsigned int                     cr_resend_nr;
804         /** What was import generation when this request was sent */
805         int                              cr_imp_gen;
806         enum lustre_imp_state            cr_send_state;
807         /** Per-request waitq introduced by bug 21938 for recovery waiting */
808         wait_queue_head_t                cr_set_waitq;
809         /** Link item for request set lists */
810         struct list_head                 cr_set_chain;
811         /** link to waited ctx */
812         struct list_head                 cr_ctx_chain;
813
814         /** client's half ctx */
815         struct ptlrpc_cli_ctx           *cr_cli_ctx;
816         /** Link back to the request set */
817         struct ptlrpc_request_set       *cr_set;
818         /** outgoing request MD handle */
819         struct lnet_handle_md            cr_req_md_h;
820         /** request-out callback parameter */
821         struct ptlrpc_cb_id              cr_req_cbid;
822         /** incoming reply MD handle */
823         struct lnet_handle_md            cr_reply_md_h;
824         wait_queue_head_t                cr_reply_waitq;
825         /** reply callback parameter */
826         struct ptlrpc_cb_id              cr_reply_cbid;
827         /** Async completion handler, called when reply is received */
828         ptlrpc_interpterer_t             cr_reply_interp;
829         /** Resend handler, called when request is resend to update RPC data */
830         ptlrpc_resend_cb_t               cr_resend_cb;
831         /** Async completion context */
832         union ptlrpc_async_args          cr_async_args;
833         /** Opaq data for replay and commit callbacks. */
834         void                            *cr_cb_data;
835         /** Link to the imp->imp_unreplied_list */
836         struct list_head                 cr_unreplied_list;
837         /**
838          * Commit callback, called when request is committed and about to be
839          * freed.
840          */
841         void (*cr_commit_cb)(struct ptlrpc_request *);
842         /** Replay callback, called after request is replayed at recovery */
843         void (*cr_replay_cb)(struct ptlrpc_request *);
844 };
845
846 /** client request member alias */
847 /* NB: these alias should NOT be used by any new code, instead they should
848  * be removed step by step to avoid potential abuse */
849 #define rq_bulk                 rq_cli.cr_bulk
850 #define rq_delay_limit          rq_cli.cr_delay_limit
851 #define rq_queued_time          rq_cli.cr_queued_time
852 #define rq_sent_ns              rq_cli.cr_sent_ns
853 #define rq_real_sent            rq_cli.cr_sent_out
854 #define rq_reply_deadline       rq_cli.cr_reply_deadline
855 #define rq_bulk_deadline        rq_cli.cr_bulk_deadline
856 #define rq_req_deadline         rq_cli.cr_req_deadline
857 #define rq_nr_resend            rq_cli.cr_resend_nr
858 #define rq_request_portal       rq_cli.cr_req_ptl
859 #define rq_reply_portal         rq_cli.cr_rep_ptl
860 #define rq_import_generation    rq_cli.cr_imp_gen
861 #define rq_send_state           rq_cli.cr_send_state
862 #define rq_set_chain            rq_cli.cr_set_chain
863 #define rq_ctx_chain            rq_cli.cr_ctx_chain
864 #define rq_set                  rq_cli.cr_set
865 #define rq_set_waitq            rq_cli.cr_set_waitq
866 #define rq_cli_ctx              rq_cli.cr_cli_ctx
867 #define rq_req_md_h             rq_cli.cr_req_md_h
868 #define rq_req_cbid             rq_cli.cr_req_cbid
869 #define rq_reply_md_h           rq_cli.cr_reply_md_h
870 #define rq_reply_waitq          rq_cli.cr_reply_waitq
871 #define rq_reply_cbid           rq_cli.cr_reply_cbid
872 #define rq_interpret_reply      rq_cli.cr_reply_interp
873 #define rq_resend_cb            rq_cli.cr_resend_cb
874 #define rq_async_args           rq_cli.cr_async_args
875 #define rq_cb_data              rq_cli.cr_cb_data
876 #define rq_unreplied_list       rq_cli.cr_unreplied_list
877 #define rq_commit_cb            rq_cli.cr_commit_cb
878 #define rq_replay_cb            rq_cli.cr_replay_cb
879
880 struct ptlrpc_srv_req {
881         /** initial thread servicing this request */
882         struct ptlrpc_thread            *sr_svc_thread;
883         /**
884          * Server side list of incoming unserved requests sorted by arrival
885          * time.  Traversed from time to time to notice about to expire
886          * requests and sent back "early replies" to clients to let them
887          * know server is alive and well, just very busy to service their
888          * requests in time
889          */
890         struct list_head                 sr_timed_list;
891         /** server-side per-export list */
892         struct list_head                 sr_exp_list;
893         /** server-side history, used for debuging purposes. */
894         struct list_head                 sr_hist_list;
895         /** history sequence # */
896         __u64                            sr_hist_seq;
897         /** the index of service's srv_at_array into which request is linked */
898         __u32                            sr_at_index;
899         /** authed uid */
900         uid_t                            sr_auth_uid;
901         /** authed uid mapped to */
902         uid_t                            sr_auth_mapped_uid;
903         /** RPC is generated from what part of Lustre */
904         enum lustre_sec_part             sr_sp_from;
905         /** request session context */
906         struct lu_context                sr_ses;
907         /** \addtogroup  nrs
908          * @{
909          */
910         /** stub for NRS request */
911         struct ptlrpc_nrs_request        sr_nrq;
912         /** @} nrs */
913         /** request arrival time */
914         struct timespec64                sr_arrival_time;
915         /** server's half ctx */
916         struct ptlrpc_svc_ctx           *sr_svc_ctx;
917         /** (server side), pointed directly into req buffer */
918         struct ptlrpc_user_desc         *sr_user_desc;
919         /** separated reply state, may be vmalloc'd */
920         struct ptlrpc_reply_state       *sr_reply_state;
921         /** server-side hp handlers */
922         struct ptlrpc_hpreq_ops         *sr_ops;
923         /** incoming request buffer */
924         struct ptlrpc_request_buffer_desc *sr_rqbd;
925 };
926
927 /** server request member alias */
928 /* NB: these alias should NOT be used by any new code, instead they should
929  * be removed step by step to avoid potential abuse */
930 #define rq_svc_thread           rq_srv.sr_svc_thread
931 #define rq_timed_list           rq_srv.sr_timed_list
932 #define rq_exp_list             rq_srv.sr_exp_list
933 #define rq_history_list         rq_srv.sr_hist_list
934 #define rq_history_seq          rq_srv.sr_hist_seq
935 #define rq_at_index             rq_srv.sr_at_index
936 #define rq_auth_uid             rq_srv.sr_auth_uid
937 #define rq_auth_mapped_uid      rq_srv.sr_auth_mapped_uid
938 #define rq_sp_from              rq_srv.sr_sp_from
939 #define rq_session              rq_srv.sr_ses
940 #define rq_nrq                  rq_srv.sr_nrq
941 #define rq_arrival_time         rq_srv.sr_arrival_time
942 #define rq_reply_state          rq_srv.sr_reply_state
943 #define rq_svc_ctx              rq_srv.sr_svc_ctx
944 #define rq_user_desc            rq_srv.sr_user_desc
945 #define rq_ops                  rq_srv.sr_ops
946 #define rq_rqbd                 rq_srv.sr_rqbd
947 #define rq_reqmsg               rq_pill.rc_reqmsg
948 #define rq_repmsg               rq_pill.rc_repmsg
949 #define rq_req_swab_mask        rq_pill.rc_req_swab_mask
950 #define rq_rep_swab_mask        rq_pill.rc_rep_swab_mask
951
952 /**
953  * Represents remote procedure call.
954  *
955  * This is a staple structure used by everybody wanting to send a request
956  * in Lustre.
957  */
958 struct ptlrpc_request {
959         /* Request type: one of PTL_RPC_MSG_* */
960         int                              rq_type;
961         /** Result of request processing */
962         int                              rq_status;
963         /**
964          * Linkage item through which this request is included into
965          * sending/delayed lists on client and into rqbd list on server
966          */
967         struct list_head                 rq_list;
968         /** Lock to protect request flags and some other important bits, like
969          * rq_list
970          */
971         spinlock_t                       rq_lock;
972         spinlock_t                       rq_early_free_lock;
973         /** client-side flags are serialized by rq_lock @{ */
974         unsigned int rq_intr:1, rq_replied:1, rq_err:1,
975                 rq_timedout:1, rq_resend:1, rq_restart:1,
976                 /**
977                  * when ->rq_replay is set, request is kept by the client even
978                  * after server commits corresponding transaction. This is
979                  * used for operations that require sequence of multiple
980                  * requests to be replayed. The only example currently is file
981                  * open/close. When last request in such a sequence is
982                  * committed, ->rq_replay is cleared on all requests in the
983                  * sequence.
984                  */
985                 rq_replay:1,
986                 rq_no_resend:1, rq_waiting:1, rq_receiving_reply:1,
987                 rq_no_delay:1, rq_net_err:1, rq_wait_ctx:1,
988                 rq_early:1,
989                 rq_req_unlinked:1,      /* unlinked request buffer from lnet */
990                 rq_reply_unlinked:1,    /* unlinked reply buffer from lnet */
991                 rq_memalloc:1,      /* req originated from "kswapd" */
992                 rq_committed:1,
993                 rq_reply_truncated:1,
994                 /** whether the "rq_set" is a valid one */
995                 rq_invalid_rqset:1,
996                 rq_generation_set:1,
997                 /** do not resend request on -EINPROGRESS */
998                 rq_no_retry_einprogress:1,
999                 /* allow the req to be sent if the import is in recovery
1000                  * status */
1001                 rq_allow_replay:1,
1002                 /* bulk request, sent to server, but uncommitted */
1003                 rq_unstable:1,
1004                 rq_early_free_repbuf:1, /* free reply buffer in advance */
1005                 rq_allow_intr:1;
1006         /** @} */
1007
1008         /** server-side flags @{ */
1009         unsigned int
1010                 rq_hp:1,                /**< high priority RPC */
1011                 rq_at_linked:1,         /**< link into service's srv_at_array */
1012                 rq_packed_final:1,      /**< packed final reply */
1013                 rq_obsolete:1;          /* aborted by a signal on a client */
1014         /** @} */
1015
1016         /** one of RQ_PHASE_* */
1017         enum rq_phase                    rq_phase;
1018         /** one of RQ_PHASE_* to be used next */
1019         enum rq_phase                    rq_next_phase;
1020         /**
1021          * client-side refcount for SENT race, server-side refcounf
1022          * for multiple replies
1023          */
1024         atomic_t                         rq_refcount;
1025         /**
1026          * client-side:
1027          * !rq_truncate : # reply bytes actually received,
1028          *  rq_truncate : required repbuf_len for resend
1029          */
1030         int rq_nob_received;
1031         /** Request length */
1032         int rq_reqlen;
1033         /** Reply length */
1034         int rq_replen;
1035         /** Pool if request is from preallocated list */
1036         struct ptlrpc_request_pool      *rq_pool;
1037         /** Transaction number */
1038         __u64 rq_transno;
1039         /** xid */
1040         __u64                            rq_xid;
1041         /** bulk match bits */
1042         __u64                            rq_mbits;
1043         /** reply match bits */
1044         __u64                            rq_rep_mbits;
1045         /**
1046          * List item to for replay list. Not yet committed requests get linked
1047          * there.
1048          * Also see \a rq_replay comment above.
1049          * It's also link chain on obd_export::exp_req_replay_queue
1050          */
1051         struct list_head                 rq_replay_list;
1052         /** non-shared members for client & server request*/
1053         union {
1054                 struct ptlrpc_cli_req    rq_cli;
1055                 struct ptlrpc_srv_req    rq_srv;
1056         };
1057         /**
1058          * security and encryption data
1059          * @{ */
1060         /** description of flavors for client & server */
1061         struct sptlrpc_flavor            rq_flvr;
1062
1063         /**
1064          * SELinux policy info at the time of the request
1065          * sepol string format is:
1066          * <mode>:<policy name>:<policy version>:<policy hash>
1067          */
1068         char rq_sepol[LUSTRE_NODEMAP_SEPOL_LENGTH + 1];
1069
1070         /* client/server security flags */
1071         unsigned int
1072                                  rq_ctx_init:1,      /* context initiation */
1073                                  rq_ctx_fini:1,      /* context destroy */
1074                                  rq_bulk_read:1,     /* request bulk read */
1075                                  rq_bulk_write:1,    /* request bulk write */
1076                                  /* server authentication flags */
1077                                  rq_auth_gss:1,      /* authenticated by gss */
1078                                  rq_auth_usr_root:1, /* authed as root */
1079                                  rq_auth_usr_mdt:1,  /* authed as mdt */
1080                                  rq_auth_usr_ost:1,  /* authed as ost */
1081                                  /* security tfm flags */
1082                                  rq_pack_udesc:1,
1083                                  rq_pack_bulk:1,
1084                                  /* doesn't expect reply FIXME */
1085                                  rq_no_reply:1,
1086                                  rq_pill_init:1, /* pill initialized */
1087                                  rq_srv_req:1; /* server request */
1088
1089
1090         /** various buffer pointers */
1091         struct lustre_msg               *rq_reqbuf;  /**< req wrapper, vmalloc*/
1092         char                            *rq_repbuf;  /**< rep buffer, vmalloc */
1093         struct lustre_msg               *rq_repdata; /**< rep wrapper msg */
1094         /** only in priv mode */
1095         struct lustre_msg               *rq_clrbuf;
1096         int                      rq_reqbuf_len;  /* req wrapper buf len */
1097         int                      rq_reqdata_len; /* req wrapper msg len */
1098         int                      rq_repbuf_len;  /* rep buffer len */
1099         int                      rq_repdata_len; /* rep wrapper msg len */
1100         int                      rq_clrbuf_len;  /* only in priv mode */
1101         int                      rq_clrdata_len; /* only in priv mode */
1102
1103         /** early replies go to offset 0, regular replies go after that */
1104         unsigned int                     rq_reply_off;
1105         /** @} */
1106
1107         /** how many early replies (for stats) */
1108         int                              rq_early_count;
1109         /** Server-side, export on which request was received */
1110         struct obd_export               *rq_export;
1111         /** import where request is being sent */
1112         struct obd_import               *rq_import;
1113         /** our LNet NID */
1114         lnet_nid_t                       rq_self;
1115         /** Peer description (the other side) */
1116         struct lnet_process_id           rq_peer;
1117         /** Descriptor for the NID from which the peer sent the request. */
1118         struct lnet_process_id           rq_source;
1119         /**
1120          * service time estimate (secs)
1121          * If the request is not served by this time, it is marked as timed out.
1122          * Do not change to time64_t since this is transmitted over the wire.
1123          *
1124          * The linux kernel handles timestamps with time64_t and timeouts
1125          * are normally done with jiffies. Lustre shares the rq_timeout between
1126          * nodes. Since jiffies can vary from node to node Lustre instead
1127          * will express the timeout value in seconds. To avoid confusion with
1128          * timestamps (time64_t) and jiffy timeouts (long) Lustre timeouts
1129          * are expressed in s32 (timeout_t). Also what is transmitted over
1130          * the wire is 32 bits.
1131          */
1132         timeout_t                        rq_timeout;
1133         /**
1134          * when request/reply sent (secs), or time when request should be sent
1135          */
1136         time64_t                         rq_sent;
1137         /** when request must finish. */
1138         time64_t                         rq_deadline;
1139         /** request format description */
1140         struct req_capsule               rq_pill;
1141 };
1142
1143 /**
1144  * Call completion handler for rpc if any, return it's status or original
1145  * rc if there was no handler defined for this request.
1146  */
1147 static inline int ptlrpc_req_interpret(const struct lu_env *env,
1148                                        struct ptlrpc_request *req, int rc)
1149 {
1150         if (req->rq_interpret_reply != NULL) {
1151                 req->rq_status = req->rq_interpret_reply(env, req,
1152                                                          &req->rq_async_args,
1153                                                          rc);
1154                 return req->rq_status;
1155         }
1156
1157         return rc;
1158 }
1159
1160 /** \addtogroup  nrs
1161  * @{
1162  */
1163 void ptlrpc_nrs_req_hp_move(struct ptlrpc_request *req);
1164
1165 /*
1166  * Can the request be moved from the regular NRS head to the high-priority NRS
1167  * head (of the same PTLRPC service partition), if any?
1168  *
1169  * For a reliable result, this should be checked under svcpt->scp_req lock.
1170  */
1171 static inline bool ptlrpc_nrs_req_can_move(struct ptlrpc_request *req)
1172 {
1173         struct ptlrpc_nrs_request *nrq = &req->rq_nrq;
1174
1175         /**
1176          * LU-898: Check ptlrpc_nrs_request::nr_enqueued to make sure the
1177          * request has been enqueued first, and ptlrpc_nrs_request::nr_started
1178          * to make sure it has not been scheduled yet (analogous to previous
1179          * (non-NRS) checking of !list_empty(&ptlrpc_request::rq_list).
1180          */
1181         return nrq->nr_enqueued && !nrq->nr_started && !req->rq_hp;
1182 }
1183 /** @} nrs */
1184
1185 /**
1186  * Convert numerical request phase value \a phase into text string description
1187  */
1188 static inline const char *
1189 ptlrpc_phase2str(enum rq_phase phase)
1190 {
1191         switch (phase) {
1192         case RQ_PHASE_NEW:
1193                 return "New";
1194         case RQ_PHASE_RPC:
1195                 return "Rpc";
1196         case RQ_PHASE_BULK:
1197                 return "Bulk";
1198         case RQ_PHASE_INTERPRET:
1199                 return "Interpret";
1200         case RQ_PHASE_COMPLETE:
1201                 return "Complete";
1202         case RQ_PHASE_UNREG_RPC:
1203                 return "UnregRPC";
1204         case RQ_PHASE_UNREG_BULK:
1205                 return "UnregBULK";
1206         default:
1207                 return "?Phase?";
1208         }
1209 }
1210
1211 /**
1212  * Convert numerical request phase of the request \a req into text stringi
1213  * description
1214  */
1215 static inline const char *
1216 ptlrpc_rqphase2str(struct ptlrpc_request *req)
1217 {
1218         return ptlrpc_phase2str(req->rq_phase);
1219 }
1220
1221 /**
1222  * Debugging functions and helpers to print request structure into debug log
1223  * @{
1224  */
1225 /* Spare the preprocessor, spoil the bugs. */
1226 #define FLAG(field, str) (field ? str : "")
1227
1228 /** Convert bit flags into a string */
1229 #define DEBUG_REQ_FLAGS(req)                                                   \
1230         ptlrpc_rqphase2str(req),                                               \
1231         FLAG(req->rq_intr, "I"), FLAG(req->rq_replied, "R"),                   \
1232         FLAG(req->rq_err, "E"), FLAG(req->rq_net_err, "e"),                    \
1233         FLAG(req->rq_timedout, "X") /* eXpired */, FLAG(req->rq_resend, "S"),  \
1234         FLAG(req->rq_restart, "T"), FLAG(req->rq_replay, "P"),                 \
1235         FLAG(req->rq_no_resend, "N"), FLAG(req->rq_no_reply, "n"),            \
1236         FLAG(req->rq_waiting, "W"),                                            \
1237         FLAG(req->rq_wait_ctx, "C"), FLAG(req->rq_hp, "H"),                    \
1238         FLAG(req->rq_committed, "M"),                                          \
1239         FLAG(req->rq_req_unlinked, "Q"),                                       \
1240         FLAG(req->rq_reply_unlinked, "U"),                                     \
1241         FLAG(req->rq_receiving_reply, "r")
1242
1243 #define REQ_FLAGS_FMT "%s:%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s"
1244
1245 void _debug_req(struct ptlrpc_request *req,
1246                 struct libcfs_debug_msg_data *data, const char *fmt, ...)
1247         __attribute__ ((format (printf, 3, 4)));
1248
1249 /**
1250  * Helper that decides if we need to print request accordig to current debug
1251  * level settings
1252  */
1253 #define debug_req(msgdata, mask, cdls, req, fmt, a...)                        \
1254 do {                                                                          \
1255         CFS_CHECK_STACK(msgdata, mask, cdls);                                 \
1256                                                                               \
1257         if (((mask) & D_CANTMASK) != 0 ||                                     \
1258             ((libcfs_debug & (mask)) != 0 &&                                  \
1259              (libcfs_subsystem_debug & DEBUG_SUBSYSTEM) != 0))                \
1260                 _debug_req((req), msgdata, fmt, ##a);                         \
1261 } while(0)
1262
1263 /**
1264  * This is the debug print function you need to use to print request sturucture
1265  * content into lustre debug log.
1266  * for most callers (level is a constant) this is resolved at compile time */
1267 #define DEBUG_REQ(level, req, fmt, args...)                                   \
1268 do {                                                                          \
1269         if ((level) & (D_ERROR | D_WARNING)) {                                \
1270                 static struct cfs_debug_limit_state cdls;                     \
1271                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, level, &cdls);            \
1272                 debug_req(&msgdata, level, &cdls, req, "@@@ "fmt" ", ## args);\
1273         } else {                                                              \
1274                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, level, NULL);             \
1275                 debug_req(&msgdata, level, NULL, req, "@@@ "fmt" ", ## args); \
1276         }                                                                     \
1277 } while (0)
1278 /** @} */
1279
1280 enum ptlrpc_bulk_op_type {
1281         PTLRPC_BULK_OP_ACTIVE =  0x00000001,
1282         PTLRPC_BULK_OP_PASSIVE = 0x00000002,
1283         PTLRPC_BULK_OP_PUT =     0x00000004,
1284         PTLRPC_BULK_OP_GET =     0x00000008,
1285         PTLRPC_BULK_GET_SOURCE = PTLRPC_BULK_OP_PASSIVE | PTLRPC_BULK_OP_GET,
1286         PTLRPC_BULK_PUT_SINK =   PTLRPC_BULK_OP_PASSIVE | PTLRPC_BULK_OP_PUT,
1287         PTLRPC_BULK_GET_SINK =   PTLRPC_BULK_OP_ACTIVE | PTLRPC_BULK_OP_GET,
1288         PTLRPC_BULK_PUT_SOURCE = PTLRPC_BULK_OP_ACTIVE | PTLRPC_BULK_OP_PUT,
1289 };
1290
1291 static inline bool ptlrpc_is_bulk_op_get(enum ptlrpc_bulk_op_type type)
1292 {
1293         return (type & PTLRPC_BULK_OP_GET) == PTLRPC_BULK_OP_GET;
1294 }
1295
1296 static inline bool ptlrpc_is_bulk_get_source(enum ptlrpc_bulk_op_type type)
1297 {
1298         return (type & PTLRPC_BULK_GET_SOURCE) == PTLRPC_BULK_GET_SOURCE;
1299 }
1300
1301 static inline bool ptlrpc_is_bulk_put_sink(enum ptlrpc_bulk_op_type type)
1302 {
1303         return (type & PTLRPC_BULK_PUT_SINK) == PTLRPC_BULK_PUT_SINK;
1304 }
1305
1306 static inline bool ptlrpc_is_bulk_get_sink(enum ptlrpc_bulk_op_type type)
1307 {
1308         return (type & PTLRPC_BULK_GET_SINK) == PTLRPC_BULK_GET_SINK;
1309 }
1310
1311 static inline bool ptlrpc_is_bulk_put_source(enum ptlrpc_bulk_op_type type)
1312 {
1313         return (type & PTLRPC_BULK_PUT_SOURCE) == PTLRPC_BULK_PUT_SOURCE;
1314 }
1315
1316 static inline bool ptlrpc_is_bulk_op_active(enum ptlrpc_bulk_op_type type)
1317 {
1318         return ((type & PTLRPC_BULK_OP_ACTIVE) |
1319                 (type & PTLRPC_BULK_OP_PASSIVE))
1320                         == PTLRPC_BULK_OP_ACTIVE;
1321 }
1322
1323 static inline bool ptlrpc_is_bulk_op_passive(enum ptlrpc_bulk_op_type type)
1324 {
1325         return ((type & PTLRPC_BULK_OP_ACTIVE) |
1326                 (type & PTLRPC_BULK_OP_PASSIVE))
1327                         == PTLRPC_BULK_OP_PASSIVE;
1328 }
1329
1330 struct ptlrpc_bulk_frag_ops {
1331         /**
1332          * Add a page \a page to the bulk descriptor \a desc
1333          * Data to transfer in the page starts at offset \a pageoffset and
1334          * amount of data to transfer from the page is \a len
1335          */
1336         void (*add_kiov_frag)(struct ptlrpc_bulk_desc *desc,
1337                               struct page *page, int pageoffset, int len);
1338
1339         /*
1340          * Add a \a fragment to the bulk descriptor \a desc.
1341          * Data to transfer in the fragment is pointed to by \a frag
1342          * The size of the fragment is \a len
1343          */
1344         int (*add_iov_frag)(struct ptlrpc_bulk_desc *desc, void *frag, int len);
1345
1346         /**
1347          * Uninitialize and free bulk descriptor \a desc.
1348          * Works on bulk descriptors both from server and client side.
1349          */
1350         void (*release_frags)(struct ptlrpc_bulk_desc *desc);
1351 };
1352
1353 extern const struct ptlrpc_bulk_frag_ops ptlrpc_bulk_kiov_pin_ops;
1354 extern const struct ptlrpc_bulk_frag_ops ptlrpc_bulk_kiov_nopin_ops;
1355
1356 /*
1357  * Definition of bulk descriptor.
1358  * Bulks are special "Two phase" RPCs where initial request message
1359  * is sent first and it is followed bt a transfer (o receiving) of a large
1360  * amount of data to be settled into pages referenced from the bulk descriptors.
1361  * Bulks transfers (the actual data following the small requests) are done
1362  * on separate LNet portals.
1363  * In lustre we use bulk transfers for READ and WRITE transfers from/to OSTs.
1364  *  Another user is readpage for MDT.
1365  */
1366 struct ptlrpc_bulk_desc {
1367         unsigned int    bd_refs; /* number MD's assigned including zero-sends */
1368         /** completed with failure */
1369         unsigned long bd_failure:1;
1370         /** client side */
1371         unsigned long bd_registered:1;
1372         /** For serialization with callback */
1373         spinlock_t bd_lock;
1374         /** {put,get}{source,sink}{kvec,kiov} */
1375         enum ptlrpc_bulk_op_type bd_type;
1376         /** LNet portal for this bulk */
1377         __u32 bd_portal;
1378         /** Server side - export this bulk created for */
1379         struct obd_export *bd_export;
1380         /** Client side - import this bulk was sent on */
1381         struct obd_import *bd_import;
1382         /** Back pointer to the request */
1383         struct ptlrpc_request *bd_req;
1384         const struct ptlrpc_bulk_frag_ops *bd_frag_ops;
1385         wait_queue_head_t      bd_waitq;        /* server side only WQ */
1386         int                    bd_iov_count;    /* # entries in bd_iov */
1387         int                    bd_max_iov;      /* allocated size of bd_iov */
1388         int                    bd_nob;          /* # bytes covered */
1389         int                    bd_nob_transferred; /* # bytes GOT/PUT */
1390         unsigned int            bd_nob_last;    /* # bytes in last MD */
1391
1392         __u64                  bd_last_mbits;
1393
1394         struct ptlrpc_cb_id    bd_cbid;         /* network callback info */
1395         lnet_nid_t             bd_sender;       /* stash event::sender */
1396         int                     bd_md_count;    /* # valid entries in bd_mds */
1397         int                     bd_md_max_brw;  /* max entries in bd_mds */
1398
1399         /** array of offsets for each MD */
1400         unsigned int            bd_mds_off[PTLRPC_BULK_OPS_COUNT];
1401         /** array of associated MDs */
1402         struct lnet_handle_md   bd_mds[PTLRPC_BULK_OPS_COUNT];
1403
1404         /* encrypted iov, size is either 0 or bd_iov_count. */
1405         struct bio_vec *bd_enc_vec;
1406         struct bio_vec *bd_vec;
1407 };
1408
1409 enum {
1410         SVC_INIT        = 0,
1411         SVC_STOPPED     = BIT(0),
1412         SVC_STOPPING    = BIT(1),
1413         SVC_STARTING    = BIT(2),
1414         SVC_RUNNING     = BIT(3),
1415 };
1416
1417 #define PTLRPC_THR_NAME_LEN             32
1418 /**
1419  * Definition of server service thread structure
1420  */
1421 struct ptlrpc_thread {
1422         /**
1423          * List of active threads in svcpt->scp_threads
1424          */
1425         struct list_head t_link;
1426         /**
1427          * thread-private data (preallocated vmalloc'd memory)
1428          */
1429         void *t_data;
1430         __u32 t_flags;
1431         /**
1432          * service thread index, from ptlrpc_start_threads
1433          */
1434         unsigned int t_id;
1435         /**
1436          * service thread
1437          */
1438         struct task_struct *t_task;
1439         pid_t t_pid;
1440         ktime_t t_touched;
1441         /**
1442          * put watchdog in the structure per thread b=14840
1443          */
1444         struct delayed_work t_watchdog;
1445         /**
1446          * the svc this thread belonged to b=18582
1447          */
1448         struct ptlrpc_service_part      *t_svcpt;
1449         wait_queue_head_t               t_ctl_waitq;
1450         struct lu_env                   *t_env;
1451         char                            t_name[PTLRPC_THR_NAME_LEN];
1452 };
1453
1454 static inline int thread_is_init(struct ptlrpc_thread *thread)
1455 {
1456         return thread->t_flags == 0;
1457 }
1458
1459 static inline int thread_is_stopped(struct ptlrpc_thread *thread)
1460 {
1461         return !!(thread->t_flags & SVC_STOPPED);
1462 }
1463
1464 static inline int thread_is_stopping(struct ptlrpc_thread *thread)
1465 {
1466         return !!(thread->t_flags & SVC_STOPPING);
1467 }
1468
1469 static inline int thread_is_starting(struct ptlrpc_thread *thread)
1470 {
1471         return !!(thread->t_flags & SVC_STARTING);
1472 }
1473
1474 static inline int thread_is_running(struct ptlrpc_thread *thread)
1475 {
1476         return !!(thread->t_flags & SVC_RUNNING);
1477 }
1478
1479 static inline void thread_clear_flags(struct ptlrpc_thread *thread, __u32 flags)
1480 {
1481         thread->t_flags &= ~flags;
1482 }
1483
1484 static inline void thread_set_flags(struct ptlrpc_thread *thread, __u32 flags)
1485 {
1486         thread->t_flags = flags;
1487 }
1488
1489 static inline void thread_add_flags(struct ptlrpc_thread *thread, __u32 flags)
1490 {
1491         thread->t_flags |= flags;
1492 }
1493
1494 static inline int thread_test_and_clear_flags(struct ptlrpc_thread *thread,
1495                                               __u32 flags)
1496 {
1497         if (thread->t_flags & flags) {
1498                 thread->t_flags &= ~flags;
1499                 return 1;
1500         }
1501         return 0;
1502 }
1503
1504 /**
1505  * Request buffer descriptor structure.
1506  * This is a structure that contains one posted request buffer for service.
1507  * Once data land into a buffer, event callback creates actual request and
1508  * notifies wakes one of the service threads to process new incoming request.
1509  * More than one request can fit into the buffer.
1510  */
1511 struct ptlrpc_request_buffer_desc {
1512         /** Link item for rqbds on a service */
1513         struct list_head                rqbd_list;
1514         /** History of requests for this buffer */
1515         struct list_head                rqbd_reqs;
1516         /** Back pointer to service for which this buffer is registered */
1517         struct ptlrpc_service_part      *rqbd_svcpt;
1518         /** LNet descriptor */
1519         struct lnet_handle_md           rqbd_md_h;
1520         int                             rqbd_refcount;
1521         /** The buffer itself */
1522         char                            *rqbd_buffer;
1523         struct ptlrpc_cb_id             rqbd_cbid;
1524         /**
1525          * This "embedded" request structure is only used for the
1526          * last request to fit into the buffer
1527          */
1528         struct ptlrpc_request           rqbd_req;
1529 };
1530
1531 typedef int  (*svc_handler_t)(struct ptlrpc_request *req);
1532
1533 struct ptlrpc_service_ops {
1534         /**
1535          * if non-NULL called during thread creation (ptlrpc_start_thread())
1536          * to initialize service specific per-thread state.
1537          */
1538         int             (*so_thr_init)(struct ptlrpc_thread *thr);
1539         /**
1540          * if non-NULL called during thread shutdown (ptlrpc_main()) to
1541          * destruct state created by ->srv_init().
1542          */
1543         void            (*so_thr_done)(struct ptlrpc_thread *thr);
1544         /**
1545          * Handler function for incoming requests for this service
1546          */
1547         int             (*so_req_handler)(struct ptlrpc_request *req);
1548         /**
1549          * function to determine priority of the request, it's called
1550          * on every new request
1551          */
1552         int             (*so_hpreq_handler)(struct ptlrpc_request *);
1553         /**
1554          * service-specific print fn
1555          */
1556         void            (*so_req_printer)(void *, struct ptlrpc_request *);
1557 };
1558
1559 #ifndef __cfs_cacheline_aligned
1560 /* NB: put it here for reducing patche dependence */
1561 # define __cfs_cacheline_aligned
1562 #endif
1563
1564 /**
1565  * How many high priority requests to serve before serving one normal
1566  * priority request
1567  */
1568 #define PTLRPC_SVC_HP_RATIO 10
1569
1570 /**
1571  * Definition of PortalRPC service.
1572  * The service is listening on a particular portal (like tcp port)
1573  * and perform actions for a specific server like IO service for OST
1574  * or general metadata service for MDS.
1575  */
1576 struct ptlrpc_service {
1577         /** serialize /proc operations */
1578         spinlock_t                      srv_lock;
1579         /** most often accessed fields */
1580         /** chain thru all services */
1581         struct list_head                srv_list;
1582         /** service operations table */
1583         struct ptlrpc_service_ops       srv_ops;
1584         /** only statically allocated strings here; we don't clean them */
1585         char                           *srv_name;
1586         /** only statically allocated strings here; we don't clean them */
1587         char                           *srv_thread_name;
1588         /** threads # should be created for each partition on initializing */
1589         int                             srv_nthrs_cpt_init;
1590         /** limit of threads number for each partition */
1591         int                             srv_nthrs_cpt_limit;
1592         /** Root of debugfs dir tree for this service */
1593         struct dentry                  *srv_debugfs_entry;
1594         /** Pointer to statistic data for this service */
1595         struct lprocfs_stats           *srv_stats;
1596         /** # hp per lp reqs to handle */
1597         int                             srv_hpreq_ratio;
1598         /** biggest request to receive */
1599         int                             srv_max_req_size;
1600         /** biggest reply to send */
1601         int                             srv_max_reply_size;
1602         /** size of individual buffers */
1603         int                             srv_buf_size;
1604         /** # buffers to allocate in 1 group */
1605         int                             srv_nbuf_per_group;
1606         /** Local portal on which to receive requests */
1607         __u32                           srv_req_portal;
1608         /** Portal on the client to send replies to */
1609         __u32                           srv_rep_portal;
1610         /**
1611          * Tags for lu_context associated with this thread, see struct
1612          * lu_context.
1613          */
1614         __u32                           srv_ctx_tags;
1615         /** soft watchdog timeout multiplier */
1616         int                             srv_watchdog_factor;
1617         /** under unregister_service */
1618         unsigned                        srv_is_stopping:1;
1619         /** Whether or not to restrict service threads to CPUs in this CPT */
1620         unsigned                        srv_cpt_bind:1;
1621
1622         /** max # request buffers */
1623         int                             srv_nrqbds_max;
1624         /** max # request buffers in history per partition */
1625         int                             srv_hist_nrqbds_cpt_max;
1626         /** number of CPTs this service associated with */
1627         int                             srv_ncpts;
1628         /** CPTs array this service associated with */
1629         __u32                           *srv_cpts;
1630         /** 2^srv_cptab_bits >= cfs_cpt_numbert(srv_cptable) */
1631         int                             srv_cpt_bits;
1632         /** CPT table this service is running over */
1633         struct cfs_cpt_table            *srv_cptable;
1634
1635         /* sysfs object */
1636         struct kobject                  srv_kobj;
1637         struct completion               srv_kobj_unregister;
1638         /**
1639          * partition data for ptlrpc service
1640          */
1641         struct ptlrpc_service_part      *srv_parts[0];
1642 };
1643
1644 /**
1645  * Definition of PortalRPC service partition data.
1646  * Although a service only has one instance of it right now, but we
1647  * will have multiple instances very soon (instance per CPT).
1648  *
1649  * it has four locks:
1650  * \a scp_lock
1651  *    serialize operations on rqbd and requests waiting for preprocess
1652  * \a scp_req_lock
1653  *    serialize operations active requests sent to this portal
1654  * \a scp_at_lock
1655  *    serialize adaptive timeout stuff
1656  * \a scp_rep_lock
1657  *    serialize operations on RS list (reply states)
1658  *
1659  * We don't have any use-case to take two or more locks at the same time
1660  * for now, so there is no lock order issue.
1661  */
1662 struct ptlrpc_service_part {
1663         /** back reference to owner */
1664         struct ptlrpc_service           *scp_service __cfs_cacheline_aligned;
1665         /* CPT id, reserved */
1666         int                             scp_cpt;
1667         /** always increasing number */
1668         int                             scp_thr_nextid;
1669         /** # of starting threads */
1670         int                             scp_nthrs_starting;
1671         /** # running threads */
1672         int                             scp_nthrs_running;
1673         /** service threads list */
1674         struct list_head                scp_threads;
1675
1676         /**
1677          * serialize the following fields, used for protecting
1678          * rqbd list and incoming requests waiting for preprocess,
1679          * threads starting & stopping are also protected by this lock.
1680          */
1681         spinlock_t                      scp_lock  __cfs_cacheline_aligned;
1682         /** userland serialization */
1683         struct mutex                    scp_mutex;
1684         /** total # req buffer descs allocated */
1685         int                             scp_nrqbds_total;
1686         /** # posted request buffers for receiving */
1687         int                             scp_nrqbds_posted;
1688         /** in progress of allocating rqbd */
1689         int                             scp_rqbd_allocating;
1690         /** # incoming reqs */
1691         int                             scp_nreqs_incoming;
1692         /** request buffers to be reposted */
1693         struct list_head                scp_rqbd_idle;
1694         /** req buffers receiving */
1695         struct list_head                scp_rqbd_posted;
1696         /** incoming reqs */
1697         struct list_head                scp_req_incoming;
1698         /** timeout before re-posting reqs, in jiffies */
1699         long                            scp_rqbd_timeout;
1700         /**
1701          * all threads sleep on this. This wait-queue is signalled when new
1702          * incoming request arrives and when difficult reply has to be handled.
1703          */
1704         wait_queue_head_t               scp_waitq;
1705
1706         /** request history */
1707         struct list_head                scp_hist_reqs;
1708         /** request buffer history */
1709         struct list_head                scp_hist_rqbds;
1710         /** # request buffers in history */
1711         int                             scp_hist_nrqbds;
1712         /** sequence number for request */
1713         __u64                           scp_hist_seq;
1714         /** highest seq culled from history */
1715         __u64                           scp_hist_seq_culled;
1716
1717         /**
1718          * serialize the following fields, used for processing requests
1719          * sent to this portal
1720          */
1721         spinlock_t                      scp_req_lock __cfs_cacheline_aligned;
1722         /** # reqs in either of the NRS heads below */
1723         /** # reqs being served */
1724         int                             scp_nreqs_active;
1725         /** # HPreqs being served */
1726         int                             scp_nhreqs_active;
1727         /** # hp requests handled */
1728         int                             scp_hreq_count;
1729
1730         /** NRS head for regular requests */
1731         struct ptlrpc_nrs               scp_nrs_reg;
1732         /** NRS head for HP requests; this is only valid for services that can
1733          *  handle HP requests */
1734         struct ptlrpc_nrs              *scp_nrs_hp;
1735
1736         /** AT stuff */
1737         /** @{ */
1738         /**
1739          * serialize the following fields, used for changes on
1740          * adaptive timeout
1741          */
1742         spinlock_t                      scp_at_lock __cfs_cacheline_aligned;
1743         /** estimated rpc service time */
1744         struct adaptive_timeout         scp_at_estimate;
1745         /** reqs waiting for replies */
1746         struct ptlrpc_at_array          scp_at_array;
1747         /** early reply timer */
1748         struct timer_list               scp_at_timer;
1749         /** debug */
1750         ktime_t                         scp_at_checktime;
1751         /** check early replies */
1752         unsigned                        scp_at_check;
1753         /** @} */
1754
1755         /**
1756          * serialize the following fields, used for processing
1757          * replies for this portal
1758          */
1759         spinlock_t                      scp_rep_lock __cfs_cacheline_aligned;
1760         /** all the active replies */
1761         struct list_head                scp_rep_active;
1762         /** List of free reply_states */
1763         struct list_head                scp_rep_idle;
1764         /** waitq to run, when adding stuff to srv_free_rs_list */
1765         wait_queue_head_t               scp_rep_waitq;
1766         /** # 'difficult' replies */
1767         atomic_t                        scp_nreps_difficult;
1768 };
1769
1770 #define ptlrpc_service_for_each_part(part, i, svc)                      \
1771         for (i = 0;                                                     \
1772              i < (svc)->srv_ncpts &&                                    \
1773              (svc)->srv_parts != NULL &&                                \
1774              ((part) = (svc)->srv_parts[i]) != NULL; i++)
1775
1776 /**
1777  * Declaration of ptlrpcd control structure
1778  */
1779 struct ptlrpcd_ctl {
1780         /**
1781          * Ptlrpc thread control flags (LIOD_START, LIOD_STOP, LIOD_FORCE)
1782          */
1783         unsigned long                   pc_flags;
1784         /**
1785          * Thread lock protecting structure fields.
1786          */
1787         spinlock_t                      pc_lock;
1788         /**
1789          * Start completion.
1790          */
1791         struct completion               pc_starting;
1792         /**
1793          * Stop completion.
1794          */
1795         struct completion               pc_finishing;
1796         /**
1797          * Thread requests set.
1798          */
1799         struct ptlrpc_request_set       *pc_set;
1800         /**
1801          * Thread name used in kthread_run()
1802          */
1803         char                            pc_name[16];
1804         /**
1805          * CPT the thread is bound on.
1806          */
1807         int                             pc_cpt;
1808         /**
1809          * Index of ptlrpcd thread in the array.
1810          */
1811         int                             pc_index;
1812         /**
1813          * Pointer to the array of partners' ptlrpcd_ctl structure.
1814          */
1815         struct ptlrpcd_ctl              **pc_partners;
1816         /**
1817          * Number of the ptlrpcd's partners.
1818          */
1819         int                             pc_npartners;
1820         /**
1821          * Record the partner index to be processed next.
1822          */
1823         int                             pc_cursor;
1824         /**
1825          * Error code if the thread failed to fully start.
1826          */
1827         int                             pc_error;
1828 };
1829
1830 /* Bits for pc_flags */
1831 enum ptlrpcd_ctl_flags {
1832         /**
1833          * Ptlrpc thread start flag.
1834          */
1835         LIOD_START      = BIT(0),
1836         /**
1837          * Ptlrpc thread stop flag.
1838          */
1839         LIOD_STOP       = BIT(1),
1840         /**
1841          * Ptlrpc thread force flag (only stop force so far).
1842          * This will cause aborting any inflight rpcs handled
1843          * by thread if LIOD_STOP is specified.
1844          */
1845         LIOD_FORCE      = BIT(2),
1846         /**
1847          * This is a recovery ptlrpc thread.
1848          */
1849         LIOD_RECOVERY   = BIT(3),
1850 };
1851
1852 /**
1853  * \addtogroup nrs
1854  * @{
1855  *
1856  * Service compatibility function; the policy is compatible with all services.
1857  *
1858  * \param[in] svc  The service the policy is attempting to register with.
1859  * \param[in] desc The policy descriptor
1860  *
1861  * \retval true The policy is compatible with the service
1862  *
1863  * \see ptlrpc_nrs_pol_desc::pd_compat()
1864  */
1865 static inline bool nrs_policy_compat_all(const struct ptlrpc_service *svc,
1866                                          const struct ptlrpc_nrs_pol_desc *desc)
1867 {
1868         return true;
1869 }
1870
1871 /**
1872  * Service compatibility function; the policy is compatible with only a specific
1873  * service which is identified by its human-readable name at
1874  * ptlrpc_service::srv_name.
1875  *
1876  * \param[in] svc  The service the policy is attempting to register with.
1877  * \param[in] desc The policy descriptor
1878  *
1879  * \retval false The policy is not compatible with the service
1880  * \retval true  The policy is compatible with the service
1881  *
1882  * \see ptlrpc_nrs_pol_desc::pd_compat()
1883  */
1884 static inline bool nrs_policy_compat_one(const struct ptlrpc_service *svc,
1885                                          const struct ptlrpc_nrs_pol_desc *desc)
1886 {
1887         LASSERT(desc->pd_compat_svc_name != NULL);
1888         return strcmp(svc->srv_name, desc->pd_compat_svc_name) == 0;
1889 }
1890
1891 /** @} nrs */
1892
1893 /* ptlrpc/events.c */
1894 extern int ptlrpc_uuid_to_peer(struct obd_uuid *uuid,
1895                                struct lnet_process_id *peer, lnet_nid_t *self);
1896 /**
1897  * These callbacks are invoked by LNet when something happened to
1898  * underlying buffer
1899  * @{
1900  */
1901 extern void request_out_callback(struct lnet_event *ev);
1902 extern void reply_in_callback(struct lnet_event *ev);
1903 extern void client_bulk_callback(struct lnet_event *ev);
1904 extern void request_in_callback(struct lnet_event *ev);
1905 extern void reply_out_callback(struct lnet_event *ev);
1906 #ifdef HAVE_SERVER_SUPPORT
1907 extern void server_bulk_callback(struct lnet_event *ev);
1908 #endif
1909 /** @} */
1910
1911 /* ptlrpc/connection.c */
1912 struct ptlrpc_connection *ptlrpc_connection_get(struct lnet_process_id peer,
1913                                                 lnet_nid_t self,
1914                                                 struct obd_uuid *uuid);
1915
1916 static inline void  ptlrpc_connection_put(struct ptlrpc_connection *conn)
1917 {
1918         if (!conn)
1919                 return;
1920
1921         LASSERT(atomic_read(&conn->c_refcount) > 0);
1922
1923         /*
1924          * We do not remove connection from hashtable and
1925          * do not free it even if last caller released ref,
1926          * as we want to have it cached for the case it is
1927          * needed again.
1928          *
1929          * Deallocating it and later creating new connection
1930          * again would be wastful. This way we also avoid
1931          * expensive locking to protect things from get/put
1932          * race when found cached connection is freed by
1933          * ptlrpc_connection_put().
1934          *
1935          * It will be freed later in module unload time,
1936          * when ptlrpc_connection_fini()->lh_exit->conn_exit()
1937          * path is called.
1938          */
1939         atomic_dec(&conn->c_refcount);
1940
1941         CDEBUG(D_INFO, "PUT conn=%p refcount %d to %s\n",
1942                conn, atomic_read(&conn->c_refcount),
1943                libcfs_nid2str(conn->c_peer.nid));
1944 }
1945
1946 struct ptlrpc_connection *ptlrpc_connection_addref(struct ptlrpc_connection *);
1947 int ptlrpc_connection_init(void);
1948 void ptlrpc_connection_fini(void);
1949 extern lnet_pid_t ptl_get_pid(void);
1950
1951 /*
1952  * Check if the peer connection is on the local node.  We need to use GFP_NOFS
1953  * for requests from a local client to avoid recursing into the filesystem
1954  * as we might end up waiting on a page sent in the request we're serving.
1955  *
1956  * Use __GFP_HIGHMEM so that the pages can use all of the available memory
1957  * on 32-bit machines.  Use more aggressive GFP_HIGHUSER flags from non-local
1958  * clients to be able to generate more memory pressure on the OSS and allow
1959  * inactive pages to be reclaimed, since it doesn't have any other processes
1960  * or allocations that generate memory reclaim pressure.
1961  *
1962  * See b=17576 (bdf50dc9) and b=19529 (3dcf18d3) for details.
1963  */
1964 static inline bool ptlrpc_connection_is_local(struct ptlrpc_connection *conn)
1965 {
1966         if (!conn)
1967                 return false;
1968
1969         if (conn->c_peer.nid == conn->c_self)
1970                 return true;
1971
1972         RETURN(LNetIsPeerLocal(conn->c_peer.nid));
1973 }
1974
1975 /* ptlrpc/niobuf.c */
1976 /**
1977  * Actual interfacing with LNet to put/get/register/unregister stuff
1978  * @{
1979  */
1980 #ifdef HAVE_SERVER_SUPPORT
1981 struct ptlrpc_bulk_desc *ptlrpc_prep_bulk_exp(struct ptlrpc_request *req,
1982                                               unsigned nfrags, unsigned max_brw,
1983                                               unsigned int type,
1984                                               unsigned portal,
1985                                               const struct ptlrpc_bulk_frag_ops
1986                                                 *ops);
1987 int ptlrpc_start_bulk_transfer(struct ptlrpc_bulk_desc *desc);
1988 void ptlrpc_abort_bulk(struct ptlrpc_bulk_desc *desc);
1989
1990 static inline int ptlrpc_server_bulk_active(struct ptlrpc_bulk_desc *desc)
1991 {
1992         int rc;
1993
1994         LASSERT(desc != NULL);
1995
1996         spin_lock(&desc->bd_lock);
1997         rc = desc->bd_refs;
1998         spin_unlock(&desc->bd_lock);
1999         return rc;
2000 }
2001 #endif
2002
2003 int ptlrpc_register_bulk(struct ptlrpc_request *req);
2004 int ptlrpc_unregister_bulk(struct ptlrpc_request *req, int async);
2005
2006 static inline int ptlrpc_client_bulk_active(struct ptlrpc_request *req)
2007 {
2008         struct ptlrpc_bulk_desc *desc;
2009         int rc;
2010
2011         LASSERT(req != NULL);
2012         desc = req->rq_bulk;
2013
2014         if (!desc)
2015                 return 0;
2016
2017         if (req->rq_bulk_deadline > ktime_get_real_seconds())
2018                 return 1;
2019
2020
2021         spin_lock(&desc->bd_lock);
2022         rc = desc->bd_refs;
2023         spin_unlock(&desc->bd_lock);
2024         return rc;
2025 }
2026
2027 #define PTLRPC_REPLY_MAYBE_DIFFICULT 0x01
2028 #define PTLRPC_REPLY_EARLY           0x02
2029 int ptlrpc_send_reply(struct ptlrpc_request *req, int flags);
2030 int ptlrpc_reply(struct ptlrpc_request *req);
2031 int ptlrpc_send_error(struct ptlrpc_request *req, int difficult);
2032 int ptlrpc_error(struct ptlrpc_request *req);
2033 int ptlrpc_at_get_net_latency(struct ptlrpc_request *req);
2034 int ptl_send_rpc(struct ptlrpc_request *request, int noreply);
2035 int ptlrpc_register_rqbd(struct ptlrpc_request_buffer_desc *rqbd);
2036 /** @} */
2037
2038 /* ptlrpc/client.c */
2039 /**
2040  * Client-side portals API. Everything to send requests, receive replies,
2041  * request queues, request management, etc.
2042  * @{
2043  */
2044 void ptlrpc_request_committed(struct ptlrpc_request *req, int force);
2045
2046 void ptlrpc_init_client(int req_portal, int rep_portal, const char *name,
2047                         struct ptlrpc_client *);
2048 void ptlrpc_cleanup_client(struct obd_import *imp);
2049 struct ptlrpc_connection *ptlrpc_uuid_to_connection(struct obd_uuid *uuid,
2050                                                     lnet_nid_t nid4refnet);
2051
2052 int ptlrpc_queue_wait(struct ptlrpc_request *req);
2053 int ptlrpc_replay_req(struct ptlrpc_request *req);
2054 void ptlrpc_restart_req(struct ptlrpc_request *req);
2055 void ptlrpc_abort_inflight(struct obd_import *imp);
2056 void ptlrpc_cleanup_imp(struct obd_import *imp);
2057 void ptlrpc_abort_set(struct ptlrpc_request_set *set);
2058
2059 struct ptlrpc_request_set *ptlrpc_prep_set(void);
2060 struct ptlrpc_request_set *ptlrpc_prep_fcset(int max, set_producer_func func,
2061                                              void *arg);
2062 int ptlrpc_check_set(const struct lu_env *env, struct ptlrpc_request_set *set);
2063 int ptlrpc_set_wait(const struct lu_env *env, struct ptlrpc_request_set *);
2064 void ptlrpc_set_destroy(struct ptlrpc_request_set *);
2065 void ptlrpc_set_add_req(struct ptlrpc_request_set *, struct ptlrpc_request *);
2066 #define PTLRPCD_SET ((struct ptlrpc_request_set *)1)
2067
2068 void ptlrpc_free_rq_pool(struct ptlrpc_request_pool *pool);
2069 int ptlrpc_add_rqs_to_pool(struct ptlrpc_request_pool *pool, int num_rq);
2070
2071 struct ptlrpc_request_pool *
2072 ptlrpc_init_rq_pool(int, int,
2073                     int (*populate_pool)(struct ptlrpc_request_pool *, int));
2074
2075 void ptlrpc_at_set_req_timeout(struct ptlrpc_request *req);
2076 struct ptlrpc_request *ptlrpc_request_alloc(struct obd_import *imp,
2077                                             const struct req_format *format);
2078 struct ptlrpc_request *ptlrpc_request_alloc_pool(struct obd_import *imp,
2079                                             struct ptlrpc_request_pool *,
2080                                             const struct req_format *format);
2081 void ptlrpc_request_free(struct ptlrpc_request *request);
2082 int ptlrpc_request_pack(struct ptlrpc_request *request,
2083                         __u32 version, int opcode);
2084 struct ptlrpc_request *ptlrpc_request_alloc_pack(struct obd_import *imp,
2085                                                 const struct req_format *format,
2086                                                 __u32 version, int opcode);
2087 int ptlrpc_request_bufs_pack(struct ptlrpc_request *request,
2088                              __u32 version, int opcode, char **bufs,
2089                              struct ptlrpc_cli_ctx *ctx);
2090 void ptlrpc_req_finished(struct ptlrpc_request *request);
2091 void ptlrpc_req_finished_with_imp_lock(struct ptlrpc_request *request);
2092 struct ptlrpc_request *ptlrpc_request_addref(struct ptlrpc_request *req);
2093 struct ptlrpc_bulk_desc *ptlrpc_prep_bulk_imp(struct ptlrpc_request *req,
2094                                               unsigned nfrags, unsigned max_brw,
2095                                               unsigned int type,
2096                                               unsigned portal,
2097                                               const struct ptlrpc_bulk_frag_ops
2098                                                 *ops);
2099
2100 void __ptlrpc_prep_bulk_page(struct ptlrpc_bulk_desc *desc,
2101                              struct page *page, int pageoffset, int len,
2102                              int pin);
2103
2104 void ptlrpc_free_bulk(struct ptlrpc_bulk_desc *bulk);
2105
2106 static inline void ptlrpc_release_bulk_noop(struct ptlrpc_bulk_desc *desc)
2107 {
2108 }
2109
2110 void ptlrpc_retain_replayable_request(struct ptlrpc_request *req,
2111                                       struct obd_import *imp);
2112 __u64 ptlrpc_next_xid(void);
2113 __u64 ptlrpc_sample_next_xid(void);
2114 __u64 ptlrpc_req_xid(struct ptlrpc_request *request);
2115 void ptlrpc_get_mod_rpc_slot(struct ptlrpc_request *req);
2116 void ptlrpc_put_mod_rpc_slot(struct ptlrpc_request *req);
2117
2118 /* Set of routines to run a function in ptlrpcd context */
2119 void *ptlrpcd_alloc_work(struct obd_import *imp,
2120                          int (*cb)(const struct lu_env *, void *), void *data);
2121 void ptlrpcd_destroy_work(void *handler);
2122 int ptlrpcd_queue_work(void *handler);
2123
2124 /** @} */
2125 struct ptlrpc_service_buf_conf {
2126         /* nbufs is buffers # to allocate when growing the pool */
2127         unsigned int                    bc_nbufs;
2128         /* buffer size to post */
2129         unsigned int                    bc_buf_size;
2130         /* portal to listed for requests on */
2131         unsigned int                    bc_req_portal;
2132         /* portal of where to send replies to */
2133         unsigned int                    bc_rep_portal;
2134         /* maximum request size to be accepted for this service */
2135         unsigned int                    bc_req_max_size;
2136         /* maximum reply size this service can ever send */
2137         unsigned int                    bc_rep_max_size;
2138 };
2139
2140 struct ptlrpc_service_thr_conf {
2141         /* threadname should be 8 characters or less - 6 will be added on */
2142         char                            *tc_thr_name;
2143         /* threads increasing factor for each CPU */
2144         unsigned int                    tc_thr_factor;
2145         /* service threads # to start on each partition while initializing */
2146         unsigned int                    tc_nthrs_init;
2147         /*
2148          * low water of threads # upper-limit on each partition while running,
2149          * service availability may be impacted if threads number is lower
2150          * than this value. It can be ZERO if the service doesn't require
2151          * CPU affinity or there is only one partition.
2152          */
2153         unsigned int                    tc_nthrs_base;
2154         /* "soft" limit for total threads number */
2155         unsigned int                    tc_nthrs_max;
2156         /* user specified threads number, it will be validated due to
2157          * other members of this structure. */
2158         unsigned int                    tc_nthrs_user;
2159         /* bind service threads to only CPUs in their associated CPT */
2160         unsigned int                    tc_cpu_bind;
2161         /* Tags for lu_context associated with service thread */
2162         __u32                           tc_ctx_tags;
2163 };
2164
2165 struct ptlrpc_service_cpt_conf {
2166         struct cfs_cpt_table            *cc_cptable;
2167         /* string pattern to describe CPTs for a service */
2168         char                            *cc_pattern;
2169         /* whether or not to have per-CPT service partitions */
2170         bool                            cc_affinity;
2171 };
2172
2173 struct ptlrpc_service_conf {
2174         /* service name */
2175         char                            *psc_name;
2176         /* soft watchdog timeout multiplifier to print stuck service traces */
2177         unsigned int                    psc_watchdog_factor;
2178         /* buffer information */
2179         struct ptlrpc_service_buf_conf  psc_buf;
2180         /* thread information */
2181         struct ptlrpc_service_thr_conf  psc_thr;
2182         /* CPU partition information */
2183         struct ptlrpc_service_cpt_conf  psc_cpt;
2184         /* function table */
2185         struct ptlrpc_service_ops       psc_ops;
2186 };
2187
2188 /* ptlrpc/service.c */
2189 /**
2190  * Server-side services API. Register/unregister service, request state
2191  * management, service thread management
2192  *
2193  * @{
2194  */
2195 void ptlrpc_save_lock(struct ptlrpc_request *req, struct lustre_handle *lock,
2196                       int mode, bool no_ack, bool convert_lock);
2197 void ptlrpc_commit_replies(struct obd_export *exp);
2198 void ptlrpc_dispatch_difficult_reply(struct ptlrpc_reply_state *rs);
2199 void ptlrpc_schedule_difficult_reply(struct ptlrpc_reply_state *rs);
2200 int ptlrpc_hpreq_handler(struct ptlrpc_request *req);
2201 struct ptlrpc_service *ptlrpc_register_service(
2202                                 struct ptlrpc_service_conf *conf,
2203                                 struct kset *parent,
2204                                 struct dentry *debugfs_entry);
2205
2206 int ptlrpc_unregister_service(struct ptlrpc_service *service);
2207 int ptlrpc_service_health_check(struct ptlrpc_service *);
2208 void ptlrpc_server_drop_request(struct ptlrpc_request *req);
2209 void ptlrpc_request_change_export(struct ptlrpc_request *req,
2210                                   struct obd_export *export);
2211 void ptlrpc_update_export_timer(struct obd_export *exp,
2212                                 time64_t extra_delay);
2213
2214 int ptlrpc_hr_init(void);
2215 void ptlrpc_hr_fini(void);
2216
2217 void ptlrpc_watchdog_init(struct delayed_work *work, timeout_t timeout);
2218 void ptlrpc_watchdog_disable(struct delayed_work *work);
2219 void ptlrpc_watchdog_touch(struct delayed_work *work, timeout_t timeout);
2220
2221 /** @} */
2222
2223 /* ptlrpc/import.c */
2224 /**
2225  * Import API
2226  * @{
2227  */
2228 int ptlrpc_connect_import(struct obd_import *imp);
2229 int ptlrpc_connect_import_locked(struct obd_import *imp);
2230 int ptlrpc_init_import(struct obd_import *imp);
2231 int ptlrpc_disconnect_import(struct obd_import *imp, int noclose);
2232 int ptlrpc_disconnect_and_idle_import(struct obd_import *imp);
2233 int ptlrpc_import_recovery_state_machine(struct obd_import *imp);
2234 void deuuidify(char *uuid, const char *prefix, char **uuid_start,
2235                int *uuid_len);
2236 void ptlrpc_import_enter_resend(struct obd_import *imp);
2237 /* ptlrpc/pack_generic.c */
2238 int ptlrpc_reconnect_import(struct obd_import *imp);
2239 /** @} */
2240
2241 /**
2242  * ptlrpc msg buffer and swab interface
2243  *
2244  * @{
2245  */
2246 #define PTLRPC_MAX_BUFCOUNT \
2247         (sizeof(((struct ptlrpc_request *)0)->rq_req_swab_mask) * 8)
2248 #define MD_MAX_BUFLEN           (MDS_REG_MAXREQSIZE > OUT_MAXREQSIZE ? \
2249                                  MDS_REG_MAXREQSIZE : OUT_MAXREQSIZE)
2250 #define PTLRPC_MAX_BUFLEN       (OST_IO_MAXREQSIZE > MD_MAX_BUFLEN ? \
2251                                  OST_IO_MAXREQSIZE : MD_MAX_BUFLEN)
2252 int ptlrpc_unpack_rep_msg(struct ptlrpc_request *req, int len);
2253 int ptlrpc_unpack_req_msg(struct ptlrpc_request *req, int len);
2254
2255 int lustre_msg_check_version(struct lustre_msg *msg, __u32 version);
2256 void lustre_init_msg_v2(struct lustre_msg_v2 *msg, int count, __u32 *lens,
2257                         char **bufs);
2258 int lustre_pack_request(struct ptlrpc_request *, __u32 magic, int count,
2259                         __u32 *lens, char **bufs);
2260 int lustre_pack_reply(struct ptlrpc_request *, int count, __u32 *lens,
2261                       char **bufs);
2262 int lustre_pack_reply_v2(struct ptlrpc_request *req, int count,
2263                          __u32 *lens, char **bufs, int flags);
2264 #define LPRFL_EARLY_REPLY 1
2265 int lustre_pack_reply_flags(struct ptlrpc_request *, int count, __u32 *lens,
2266                             char **bufs, int flags);
2267 int lustre_shrink_msg(struct lustre_msg *msg, int segment,
2268                       unsigned int newlen, int move_data);
2269 int lustre_grow_msg(struct lustre_msg *msg, int segment, unsigned int newlen);
2270 void lustre_free_reply_state(struct ptlrpc_reply_state *rs);
2271 int __lustre_unpack_msg(struct lustre_msg *m, int len);
2272 __u32 lustre_msg_hdr_size(__u32 magic, __u32 count);
2273 __u32 lustre_msg_size(__u32 magic, int count, __u32 *lengths);
2274 __u32 lustre_msg_size_v2(int count, __u32 *lengths);
2275 __u32 lustre_packed_msg_size(struct lustre_msg *msg);
2276 __u32 lustre_msg_early_size(void);
2277 void *lustre_msg_buf_v2(struct lustre_msg_v2 *m, __u32 n, __u32 min_size);
2278 void *lustre_msg_buf(struct lustre_msg *m, __u32 n, __u32 minlen);
2279 __u32 lustre_msg_buflen(struct lustre_msg *m, __u32 n);
2280 void lustre_msg_set_buflen(struct lustre_msg *m, __u32 n, __u32 len);
2281 __u32 lustre_msg_bufcount(struct lustre_msg *m);
2282 char *lustre_msg_string(struct lustre_msg *m, __u32 n, __u32 max_len);
2283 __u32 lustre_msghdr_get_flags(struct lustre_msg *msg);
2284 void lustre_msghdr_set_flags(struct lustre_msg *msg, __u32 flags);
2285 __u32 lustre_msg_get_flags(struct lustre_msg *msg);
2286 void lustre_msg_add_flags(struct lustre_msg *msg, __u32 flags);
2287 void lustre_msg_set_flags(struct lustre_msg *msg, __u32 flags);
2288 void lustre_msg_clear_flags(struct lustre_msg *msg, __u32 flags);
2289 __u32 lustre_msg_get_op_flags(struct lustre_msg *msg);
2290 void lustre_msg_add_op_flags(struct lustre_msg *msg, __u32 flags);
2291 struct lustre_handle *lustre_msg_get_handle(struct lustre_msg *msg);
2292 __u32 lustre_msg_get_type(struct lustre_msg *msg);
2293 enum lustre_msg_version lustre_msg_get_version(struct lustre_msg *msg);
2294 void lustre_msg_add_version(struct lustre_msg *msg, __u32 version);
2295 __u32 lustre_msg_get_opc(struct lustre_msg *msg);
2296 __u64 lustre_msg_get_last_xid(struct lustre_msg *msg);
2297 __u16 lustre_msg_get_tag(struct lustre_msg *msg);
2298 __u64 lustre_msg_get_last_committed(struct lustre_msg *msg);
2299 __u64 *lustre_msg_get_versions(struct lustre_msg *msg);
2300 __u64 lustre_msg_get_transno(struct lustre_msg *msg);
2301 __u64 lustre_msg_get_slv(struct lustre_msg *msg);
2302 __u32 lustre_msg_get_limit(struct lustre_msg *msg);
2303 void lustre_msg_set_slv(struct lustre_msg *msg, __u64 slv);
2304 void lustre_msg_set_limit(struct lustre_msg *msg, __u64 limit);
2305 int lustre_msg_get_status(struct lustre_msg *msg);
2306 __u32 lustre_msg_get_conn_cnt(struct lustre_msg *msg);
2307 __u32 lustre_msg_get_magic(struct lustre_msg *msg);
2308 timeout_t lustre_msg_get_timeout(struct lustre_msg *msg);
2309 timeout_t lustre_msg_get_service_timeout(struct lustre_msg *msg);
2310 char *lustre_msg_get_jobid(struct lustre_msg *msg);
2311 __u32 lustre_msg_get_cksum(struct lustre_msg *msg);
2312 __u64 lustre_msg_get_mbits(struct lustre_msg *msg);
2313 __u32 lustre_msg_calc_cksum(struct lustre_msg *msg, __u32 buf);
2314 void lustre_msg_set_handle(struct lustre_msg *msg,struct lustre_handle *handle);
2315 void lustre_msg_set_type(struct lustre_msg *msg, __u32 type);
2316 void lustre_msg_set_opc(struct lustre_msg *msg, __u32 opc);
2317 void lustre_msg_set_last_xid(struct lustre_msg *msg, __u64 last_xid);
2318 void lustre_msg_set_tag(struct lustre_msg *msg, __u16 tag);
2319 void lustre_msg_set_last_committed(struct lustre_msg *msg,__u64 last_committed);
2320 void lustre_msg_set_versions(struct lustre_msg *msg, __u64 *versions);
2321 void lustre_msg_set_transno(struct lustre_msg *msg, __u64 transno);
2322 void lustre_msg_set_status(struct lustre_msg *msg, __u32 status);
2323 void lustre_msg_set_conn_cnt(struct lustre_msg *msg, __u32 conn_cnt);
2324 void ptlrpc_req_set_repsize(struct ptlrpc_request *req, int count, __u32 *sizes);
2325 void ptlrpc_request_set_replen(struct ptlrpc_request *req);
2326 void lustre_msg_set_timeout(struct lustre_msg *msg, timeout_t timeout);
2327 void lustre_msg_set_service_timeout(struct lustre_msg *msg,
2328                                     timeout_t service_timeout);
2329 void lustre_msg_set_jobid(struct lustre_msg *msg, char *jobid);
2330 void lustre_msg_set_cksum(struct lustre_msg *msg, __u32 cksum);
2331 void lustre_msg_set_mbits(struct lustre_msg *msg, __u64 mbits);
2332
2333 static inline void
2334 lustre_shrink_reply(struct ptlrpc_request *req, int segment,
2335                     unsigned int newlen, int move_data)
2336 {
2337         LASSERT(req->rq_reply_state);
2338         LASSERT(req->rq_repmsg);
2339         req->rq_replen = lustre_shrink_msg(req->rq_repmsg, segment,
2340                                            newlen, move_data);
2341 }
2342
2343 #ifdef LUSTRE_TRANSLATE_ERRNOS
2344
2345 static inline int ptlrpc_status_hton(int h)
2346 {
2347         /*
2348          * Positive errnos must be network errnos, such as LUSTRE_EDEADLK,
2349          * ELDLM_LOCK_ABORTED, etc.
2350          */
2351         if (h < 0)
2352                 return -lustre_errno_hton(-h);
2353         else
2354                 return h;
2355 }
2356
2357 static inline int ptlrpc_status_ntoh(int n)
2358 {
2359         /*
2360          * See the comment in ptlrpc_status_hton().
2361          */
2362         if (n < 0)
2363                 return -lustre_errno_ntoh(-n);
2364         else
2365                 return n;
2366 }
2367
2368 #else
2369
2370 #define ptlrpc_status_hton(h) (h)
2371 #define ptlrpc_status_ntoh(n) (n)
2372
2373 #endif
2374 /** @} */
2375
2376 /** Change request phase of \a req to \a new_phase */
2377 static inline void
2378 ptlrpc_rqphase_move(struct ptlrpc_request *req, enum rq_phase new_phase)
2379 {
2380         if (req->rq_phase == new_phase)
2381                 return;
2382
2383         if (new_phase == RQ_PHASE_UNREG_RPC ||
2384             new_phase == RQ_PHASE_UNREG_BULK) {
2385                 /* No embedded unregistering phases */
2386                 if (req->rq_phase == RQ_PHASE_UNREG_RPC ||
2387                     req->rq_phase == RQ_PHASE_UNREG_BULK)
2388                         return;
2389
2390                 req->rq_next_phase = req->rq_phase;
2391                 if (req->rq_import)
2392                         atomic_inc(&req->rq_import->imp_unregistering);
2393         }
2394
2395         if (req->rq_phase == RQ_PHASE_UNREG_RPC ||
2396             req->rq_phase == RQ_PHASE_UNREG_BULK) {
2397                 if (req->rq_import)
2398                         atomic_dec(&req->rq_import->imp_unregistering);
2399         }
2400
2401         DEBUG_REQ(D_INFO, req, "move request phase from %s to %s",
2402                   ptlrpc_rqphase2str(req), ptlrpc_phase2str(new_phase));
2403
2404         req->rq_phase = new_phase;
2405 }
2406
2407 /**
2408  * Returns true if request \a req got early reply and hard deadline is not met
2409  */
2410 static inline int
2411 ptlrpc_client_early(struct ptlrpc_request *req)
2412 {
2413         return req->rq_early;
2414 }
2415
2416 /**
2417  * Returns true if we got real reply from server for this request
2418  */
2419 static inline int
2420 ptlrpc_client_replied(struct ptlrpc_request *req)
2421 {
2422         if (req->rq_reply_deadline > ktime_get_real_seconds())
2423                 return 0;
2424         return req->rq_replied;
2425 }
2426
2427 /** Returns true if request \a req is in process of receiving server reply */
2428 static inline int
2429 ptlrpc_client_recv(struct ptlrpc_request *req)
2430 {
2431         if (req->rq_reply_deadline > ktime_get_real_seconds())
2432                 return 1;
2433         return req->rq_receiving_reply;
2434 }
2435
2436 #define ptlrpc_cli_wait_unlink(req) __ptlrpc_cli_wait_unlink(req, NULL)
2437
2438 static inline int
2439 __ptlrpc_cli_wait_unlink(struct ptlrpc_request *req, bool *discard)
2440 {
2441         int rc;
2442
2443         spin_lock(&req->rq_lock);
2444         if (req->rq_reply_deadline > ktime_get_real_seconds()) {
2445                 spin_unlock(&req->rq_lock);
2446                 return 1;
2447         }
2448         if (req->rq_req_deadline > ktime_get_real_seconds()) {
2449                 spin_unlock(&req->rq_lock);
2450                 return 1;
2451         }
2452
2453         if (discard) {
2454                 *discard = false;
2455                 if (req->rq_reply_unlinked && req->rq_req_unlinked == 0) {
2456                         *discard = true;
2457                         spin_unlock(&req->rq_lock);
2458                         return 1; /* Should call again after LNetMDUnlink */
2459                 }
2460         }
2461
2462         rc = !req->rq_req_unlinked || !req->rq_reply_unlinked ||
2463              req->rq_receiving_reply;
2464         spin_unlock(&req->rq_lock);
2465         return rc;
2466 }
2467
2468 static inline void
2469 ptlrpc_client_wake_req(struct ptlrpc_request *req)
2470 {
2471         smp_mb();
2472         if (req->rq_set == NULL)
2473                 wake_up(&req->rq_reply_waitq);
2474         else
2475                 wake_up(&req->rq_set->set_waitq);
2476 }
2477
2478 static inline void
2479 ptlrpc_rs_addref(struct ptlrpc_reply_state *rs)
2480 {
2481         LASSERT(atomic_read(&rs->rs_refcount) > 0);
2482         atomic_inc(&rs->rs_refcount);
2483 }
2484
2485 static inline void
2486 ptlrpc_rs_decref(struct ptlrpc_reply_state *rs)
2487 {
2488         LASSERT(atomic_read(&rs->rs_refcount) > 0);
2489         if (atomic_dec_and_test(&rs->rs_refcount))
2490                 lustre_free_reply_state(rs);
2491 }
2492
2493 /* Should only be called once per req */
2494 static inline void ptlrpc_req_drop_rs(struct ptlrpc_request *req)
2495 {
2496         if (req->rq_reply_state == NULL)
2497                 return; /* shouldn't occur */
2498         ptlrpc_rs_decref(req->rq_reply_state);
2499         req->rq_reply_state = NULL;
2500         req->rq_repmsg = NULL;
2501 }
2502
2503 static inline __u32 lustre_request_magic(struct ptlrpc_request *req)
2504 {
2505         return lustre_msg_get_magic(req->rq_reqmsg);
2506 }
2507
2508 static inline int ptlrpc_req_get_repsize(struct ptlrpc_request *req)
2509 {
2510         switch (req->rq_reqmsg->lm_magic) {
2511         case LUSTRE_MSG_MAGIC_V2:
2512                 return req->rq_reqmsg->lm_repsize;
2513         default:
2514                 LASSERTF(0, "incorrect message magic: %08x\n",
2515                          req->rq_reqmsg->lm_magic);
2516                 return -EFAULT;
2517         }
2518 }
2519
2520 static inline int ptlrpc_send_limit_expired(struct ptlrpc_request *req)
2521 {
2522         if (req->rq_delay_limit != 0 &&
2523             req->rq_queued_time + req->rq_delay_limit < ktime_get_seconds())
2524                 return 1;
2525         return 0;
2526 }
2527
2528 static inline int ptlrpc_no_resend(struct ptlrpc_request *req)
2529 {
2530         if (!req->rq_no_resend && ptlrpc_send_limit_expired(req)) {
2531                 spin_lock(&req->rq_lock);
2532                 req->rq_no_resend = 1;
2533                 spin_unlock(&req->rq_lock);
2534         }
2535         return req->rq_no_resend;
2536 }
2537
2538 static inline int
2539 ptlrpc_server_get_timeout(struct ptlrpc_service_part *svcpt)
2540 {
2541         int at = AT_OFF ? 0 : at_get(&svcpt->scp_at_estimate);
2542
2543         return svcpt->scp_service->srv_watchdog_factor *
2544                max_t(int, at, obd_timeout);
2545 }
2546
2547 /**
2548  * Calculate the amount of time for lock prolongation.
2549  *
2550  * This is helper function to get the timeout extra time.
2551  *
2552  * @req         current request
2553  *
2554  * Return:      amount of time to extend the timeout with
2555  */
2556 static inline timeout_t prolong_timeout(struct ptlrpc_request *req)
2557 {
2558         struct ptlrpc_service_part *svcpt = req->rq_rqbd->rqbd_svcpt;
2559         timeout_t req_timeout = 0;
2560
2561         if (AT_OFF)
2562                 return obd_timeout / 2;
2563
2564         if (req->rq_deadline > req->rq_arrival_time.tv_sec)
2565                 req_timeout = req->rq_deadline - req->rq_arrival_time.tv_sec;
2566
2567         return max(req_timeout,
2568                    at_est2timeout(at_get(&svcpt->scp_at_estimate)));
2569 }
2570
2571 static inline struct ptlrpc_service *
2572 ptlrpc_req2svc(struct ptlrpc_request *req)
2573 {
2574         LASSERT(req->rq_rqbd != NULL);
2575         return req->rq_rqbd->rqbd_svcpt->scp_service;
2576 }
2577
2578 /* ldlm/ldlm_lib.c */
2579 /**
2580  * Target client logic
2581  * @{
2582  */
2583 int client_obd_setup(struct obd_device *obd, struct lustre_cfg *lcfg);
2584 int client_obd_cleanup(struct obd_device *obd);
2585 int client_connect_import(const struct lu_env *env,
2586                           struct obd_export **exp, struct obd_device *obd,
2587                           struct obd_uuid *cluuid, struct obd_connect_data *,
2588                           void *localdata);
2589 int client_disconnect_export(struct obd_export *exp);
2590 int client_import_add_conn(struct obd_import *imp, struct obd_uuid *uuid,
2591                            int priority);
2592 int client_import_dyn_add_conn(struct obd_import *imp, struct obd_uuid *uuid,
2593                                lnet_nid_t prim_nid, int priority);
2594 int client_import_add_nids_to_conn(struct obd_import *imp, lnet_nid_t *nids,
2595                                    int nid_count, struct obd_uuid *uuid);
2596 int client_import_del_conn(struct obd_import *imp, struct obd_uuid *uuid);
2597 int client_import_find_conn(struct obd_import *imp, lnet_nid_t peer,
2598                             struct obd_uuid *uuid);
2599 int import_set_conn_priority(struct obd_import *imp, struct obd_uuid *uuid);
2600 void client_destroy_import(struct obd_import *imp);
2601 /** @} */
2602
2603 #ifdef HAVE_SERVER_SUPPORT
2604 int server_disconnect_export(struct obd_export *exp);
2605 #endif
2606
2607 /* ptlrpc/pinger.c */
2608 /**
2609  * Pinger API (client side only)
2610  * @{
2611  */
2612 enum timeout_event {
2613         TIMEOUT_GRANT = 1
2614 };
2615 struct timeout_item;
2616 typedef int (*timeout_cb_t)(struct timeout_item *, void *);
2617 int ptlrpc_pinger_add_import(struct obd_import *imp);
2618 int ptlrpc_pinger_del_import(struct obd_import *imp);
2619 struct ptlrpc_request * ptlrpc_prep_ping(struct obd_import *imp);
2620 int ptlrpc_obd_ping(struct obd_device *obd);
2621 void ping_evictor_start(void);
2622 void ping_evictor_stop(void);
2623 void ptlrpc_pinger_ir_up(void);
2624 void ptlrpc_pinger_ir_down(void);
2625 /** @} */
2626 int ptlrpc_pinger_suppress_pings(void);
2627
2628 /* ptlrpc/ptlrpcd.c */
2629 void ptlrpcd_stop(struct ptlrpcd_ctl *pc, int force);
2630 void ptlrpcd_free(struct ptlrpcd_ctl *pc);
2631 void ptlrpcd_wake(struct ptlrpc_request *req);
2632 void ptlrpcd_add_req(struct ptlrpc_request *req);
2633 void ptlrpcd_add_rqset(struct ptlrpc_request_set *set);
2634 int ptlrpcd_addref(void);
2635 void ptlrpcd_decref(void);
2636
2637 /* ptlrpc/lproc_ptlrpc.c */
2638 /**
2639  * procfs output related functions
2640  * @{
2641  */
2642 const char* ll_opcode2str(__u32 opcode);
2643 const int ll_str2opcode(const char *ops);
2644 #ifdef CONFIG_PROC_FS
2645 void ptlrpc_lprocfs_register_obd(struct obd_device *obd);
2646 void ptlrpc_lprocfs_unregister_obd(struct obd_device *obd);
2647 void ptlrpc_lprocfs_brw(struct ptlrpc_request *req, int bytes);
2648 #else
2649 static inline void ptlrpc_lprocfs_register_obd(struct obd_device *obd) {}
2650 static inline void ptlrpc_lprocfs_unregister_obd(struct obd_device *obd) {}
2651 static inline void ptlrpc_lprocfs_brw(struct ptlrpc_request *req, int bytes) {}
2652 #endif
2653 /** @} */
2654
2655 /* ptlrpc/llog_server.c */
2656 int llog_origin_handle_open(struct ptlrpc_request *req);
2657 int llog_origin_handle_prev_block(struct ptlrpc_request *req);
2658 int llog_origin_handle_next_block(struct ptlrpc_request *req);
2659 int llog_origin_handle_read_header(struct ptlrpc_request *req);
2660
2661 /* ptlrpc/llog_client.c */
2662 extern const struct llog_operations llog_client_ops;
2663 /** @} net */
2664
2665 #endif
2666 /** @} PtlRPC */