Whamcloud - gitweb
LU-10467 lustre: convert most users of LWI_TIMEOUT_INTERVAL()
[fs/lustre-release.git] / lustre / ptlrpc / service.c
index 267685c..8962690 100644 (file)
  *
  * You should have received a copy of the GNU General Public License
  * version 2 along with this program; If not, see
- * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
- *
- * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
+ * http://www.gnu.org/licenses/gpl-2.0.html
  *
  * GPL HEADER END
  */
@@ -27,7 +23,7 @@
  * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
  * Use is subject to license terms.
  *
- * Copyright (c) 2010, 2014, Intel Corporation.
+ * Copyright (c) 2010, 2017, Intel Corporation.
  */
 /*
  * This file is part of Lustre, http://www.lustre.org/
  */
 
 #define DEBUG_SUBSYSTEM S_RPC
+
+#include <linux/kthread.h>
+#include <linux/ratelimit.h>
+
 #include <obd_support.h>
 #include <obd_class.h>
 #include <lustre_net.h>
 #include <lu_object.h>
-#include <lnet/types.h>
+#include <uapi/linux/lnet/lnet-types.h>
 #include "ptlrpc_internal.h"
+#include <linux/delay.h>
 
 /* The following are visible and mutable through /sys/module/ptlrpc */
 int test_req_buffer_pressure = 0;
-CFS_MODULE_PARM(test_req_buffer_pressure, "i", int, 0444,
-                "set non-zero to put pressure on request buffer pools");
-CFS_MODULE_PARM(at_min, "i", int, 0644,
-                "Adaptive timeout minimum (sec)");
-CFS_MODULE_PARM(at_max, "i", int, 0644,
-                "Adaptive timeout maximum (sec)");
-CFS_MODULE_PARM(at_history, "i", int, 0644,
-                "Adaptive timeouts remember the slowest event that took place "
-                "within this period (sec)");
-CFS_MODULE_PARM(at_early_margin, "i", int, 0644,
-                "How soon before an RPC deadline to send an early reply");
-CFS_MODULE_PARM(at_extra, "i", int, 0644,
-                "How much extra time to give with each early reply");
-
+module_param(test_req_buffer_pressure, int, 0444);
+MODULE_PARM_DESC(test_req_buffer_pressure, "set non-zero to put pressure on request buffer pools");
+module_param(at_min, int, 0644);
+MODULE_PARM_DESC(at_min, "Adaptive timeout minimum (sec)");
+module_param(at_max, int, 0644);
+MODULE_PARM_DESC(at_max, "Adaptive timeout maximum (sec)");
+module_param(at_history, int, 0644);
+MODULE_PARM_DESC(at_history,
+                "Adaptive timeouts remember the slowest event that took place within this period (sec)");
+module_param(at_early_margin, int, 0644);
+MODULE_PARM_DESC(at_early_margin, "How soon before an RPC deadline to send an early reply");
+module_param(at_extra, int, 0644);
+MODULE_PARM_DESC(at_extra, "How much extra time to give with each early reply");
 
 /* forward ref */
 static int ptlrpc_server_post_idle_rqbds(struct ptlrpc_service_part *svcpt);
@@ -99,8 +99,7 @@ ptlrpc_alloc_rqbd(struct ptlrpc_service_part *svcpt)
        return rqbd;
 }
 
-static void
-ptlrpc_free_rqbd(struct ptlrpc_request_buffer_desc *rqbd)
+static void ptlrpc_free_rqbd(struct ptlrpc_request_buffer_desc *rqbd)
 {
        struct ptlrpc_service_part *svcpt = rqbd->rqbd_svcpt;
 
@@ -116,13 +115,12 @@ ptlrpc_free_rqbd(struct ptlrpc_request_buffer_desc *rqbd)
        OBD_FREE_PTR(rqbd);
 }
 
-static int
-ptlrpc_grow_req_bufs(struct ptlrpc_service_part *svcpt, int post)
+static int ptlrpc_grow_req_bufs(struct ptlrpc_service_part *svcpt, int post)
 {
-       struct ptlrpc_service             *svc = svcpt->scp_service;
-        struct ptlrpc_request_buffer_desc *rqbd;
-        int                                rc = 0;
-        int                                i;
+       struct ptlrpc_service *svc = svcpt->scp_service;
+       struct ptlrpc_request_buffer_desc *rqbd;
+       int rc = 0;
+       int i;
 
        if (svcpt->scp_rqbd_allocating)
                goto try_post;
@@ -140,20 +138,24 @@ ptlrpc_grow_req_bufs(struct ptlrpc_service_part *svcpt, int post)
        spin_unlock(&svcpt->scp_lock);
 
 
-        for (i = 0; i < svc->srv_nbuf_per_group; i++) {
-                /* NB: another thread might have recycled enough rqbds, we
-                * need to make sure it wouldn't over-allocate, see LU-1212. */
-               if (svcpt->scp_nrqbds_posted >= svc->srv_nbuf_per_group)
+       for (i = 0; i < svc->srv_nbuf_per_group; i++) {
+               /*
+                * NB: another thread might have recycled enough rqbds, we
+                * need to make sure it wouldn't over-allocate, see LU-1212.
+                */
+               if (svcpt->scp_nrqbds_posted >= svc->srv_nbuf_per_group ||
+                   (svc->srv_nrqbds_max != 0 &&
+                    svcpt->scp_nrqbds_total > svc->srv_nrqbds_max))
                        break;
 
                rqbd = ptlrpc_alloc_rqbd(svcpt);
 
-                if (rqbd == NULL) {
-                        CERROR("%s: Can't allocate request buffer\n",
-                               svc->srv_name);
-                        rc = -ENOMEM;
-                        break;
-                }
+               if (rqbd == NULL) {
+                       CERROR("%s: Can't allocate request buffer\n",
+                              svc->srv_name);
+                       rc = -ENOMEM;
+                       break;
+               }
        }
 
        spin_lock(&svcpt->scp_lock);
@@ -179,25 +181,21 @@ ptlrpc_grow_req_bufs(struct ptlrpc_service_part *svcpt, int post)
  * Part of Rep-Ack logic.
  * Puts a lock and its mode into reply state assotiated to request reply.
  */
-void
-ptlrpc_save_lock(struct ptlrpc_request *req,
-                 struct lustre_handle *lock, int mode, int no_ack)
-{
-        struct ptlrpc_reply_state *rs = req->rq_reply_state;
-        int                        idx;
-
-        LASSERT(rs != NULL);
-        LASSERT(rs->rs_nlocks < RS_MAX_LOCKS);
-
-        if (req->rq_export->exp_disconnected) {
-                ldlm_lock_decref(lock, mode);
-        } else {
-                idx = rs->rs_nlocks++;
-                rs->rs_locks[idx] = *lock;
-                rs->rs_modes[idx] = mode;
-                rs->rs_difficult = 1;
-                rs->rs_no_ack = !!no_ack;
-        }
+void ptlrpc_save_lock(struct ptlrpc_request *req, struct lustre_handle *lock,
+                     int mode, bool no_ack, bool convert_lock)
+{
+       struct ptlrpc_reply_state *rs = req->rq_reply_state;
+       int idx;
+
+       LASSERT(rs != NULL);
+       LASSERT(rs->rs_nlocks < RS_MAX_LOCKS);
+
+       idx = rs->rs_nlocks++;
+       rs->rs_locks[idx] = *lock;
+       rs->rs_modes[idx] = mode;
+       rs->rs_difficult = 1;
+       rs->rs_no_ack = no_ack;
+       rs->rs_convert_lock = convert_lock;
 }
 EXPORT_SYMBOL(ptlrpc_save_lock);
 
@@ -208,7 +206,7 @@ struct ptlrpc_hr_thread {
        int                             hrt_id;         /* thread ID */
        spinlock_t                      hrt_lock;
        wait_queue_head_t               hrt_waitq;
-       struct list_head                        hrt_queue;      /* RS queue */
+       struct list_head                hrt_queue;
        struct ptlrpc_hr_partition      *hrt_partition;
 };
 
@@ -235,7 +233,7 @@ struct ptlrpc_hr_service {
        struct cfs_cpt_table            *hr_cpt_table;
        /** controller sleep waitq */
        wait_queue_head_t               hr_waitq;
-        unsigned int                   hr_stopping;
+       unsigned int                    hr_stopping;
        /** roundrobin rotor for non-affinity service */
        unsigned int                    hr_rotor;
        /* partition data */
@@ -263,15 +261,15 @@ static struct ptlrpc_hr_service           ptlrpc_hr;
  */
 static void rs_batch_init(struct rs_batch *b)
 {
-       memset(b, 0, sizeof *b);
+       memset(b, 0, sizeof(*b));
        INIT_LIST_HEAD(&b->rsb_replies);
 }
 
 /**
  * Choose an hr thread to dispatch requests to.
  */
-static struct ptlrpc_hr_thread *
-ptlrpc_hr_select(struct ptlrpc_service_part *svcpt)
+static
+struct ptlrpc_hr_thread *ptlrpc_hr_select(struct ptlrpc_service_part *svcpt)
 {
        struct ptlrpc_hr_partition      *hrp;
        unsigned int                    rotor;
@@ -369,6 +367,7 @@ static void rs_batch_fini(struct rs_batch *b)
 void ptlrpc_dispatch_difficult_reply(struct ptlrpc_reply_state *rs)
 {
        struct ptlrpc_hr_thread *hrt;
+
        ENTRY;
 
        LASSERT(list_empty(&rs->rs_list));
@@ -383,14 +382,13 @@ void ptlrpc_dispatch_difficult_reply(struct ptlrpc_reply_state *rs)
        EXIT;
 }
 
-void
-ptlrpc_schedule_difficult_reply(struct ptlrpc_reply_state *rs)
+void ptlrpc_schedule_difficult_reply(struct ptlrpc_reply_state *rs)
 {
        ENTRY;
 
        assert_spin_locked(&rs->rs_svcpt->scp_rep_lock);
        assert_spin_locked(&rs->rs_lock);
-       LASSERT (rs->rs_difficult);
+       LASSERT(rs->rs_difficult);
        rs->rs_scheduled_ever = 1;  /* flag any notification attempt */
 
        if (rs->rs_scheduled) {     /* being set up or already notified */
@@ -407,37 +405,39 @@ EXPORT_SYMBOL(ptlrpc_schedule_difficult_reply);
 
 void ptlrpc_commit_replies(struct obd_export *exp)
 {
-        struct ptlrpc_reply_state *rs, *nxt;
-        DECLARE_RS_BATCH(batch);
-        ENTRY;
+       struct ptlrpc_reply_state *rs, *nxt;
+       DECLARE_RS_BATCH(batch);
 
-        rs_batch_init(&batch);
-        /* Find any replies that have been committed and get their service
-         * to attend to complete them. */
+       ENTRY;
+
+       rs_batch_init(&batch);
+       /*
+        * Find any replies that have been committed and get their service
+        * to attend to complete them.
+        */
 
-        /* CAVEAT EMPTOR: spinlock ordering!!! */
+       /* CAVEAT EMPTOR: spinlock ordering!!! */
        spin_lock(&exp->exp_uncommitted_replies_lock);
        list_for_each_entry_safe(rs, nxt, &exp->exp_uncommitted_replies,
-                                     rs_obd_list) {
-                LASSERT (rs->rs_difficult);
-                /* VBR: per-export last_committed */
-                LASSERT(rs->rs_export);
-                if (rs->rs_transno <= exp->exp_last_committed) {
+                                rs_obd_list) {
+               LASSERT(rs->rs_difficult);
+               /* VBR: per-export last_committed */
+               LASSERT(rs->rs_export);
+               if (rs->rs_transno <= exp->exp_last_committed) {
                        list_del_init(&rs->rs_obd_list);
-                        rs_batch_add(&batch, rs);
-                }
-        }
+                       rs_batch_add(&batch, rs);
+               }
+       }
        spin_unlock(&exp->exp_uncommitted_replies_lock);
        rs_batch_fini(&batch);
        EXIT;
 }
 
-static int
-ptlrpc_server_post_idle_rqbds(struct ptlrpc_service_part *svcpt)
+static int ptlrpc_server_post_idle_rqbds(struct ptlrpc_service_part *svcpt)
 {
        struct ptlrpc_request_buffer_desc *rqbd;
-       int                               rc;
-       int                               posted = 0;
+       int rc;
+       int posted = 0;
 
        for (;;) {
                spin_lock(&svcpt->scp_lock);
@@ -450,11 +450,10 @@ ptlrpc_server_post_idle_rqbds(struct ptlrpc_service_part *svcpt)
                rqbd = list_entry(svcpt->scp_rqbd_idle.next,
                                      struct ptlrpc_request_buffer_desc,
                                      rqbd_list);
-               list_del(&rqbd->rqbd_list);
 
                /* assume we will post successfully */
                svcpt->scp_nrqbds_posted++;
-               list_add(&rqbd->rqbd_list, &svcpt->scp_rqbd_posted);
+               list_move(&rqbd->rqbd_list, &svcpt->scp_rqbd_posted);
 
                spin_unlock(&svcpt->scp_lock);
 
@@ -468,37 +467,37 @@ ptlrpc_server_post_idle_rqbds(struct ptlrpc_service_part *svcpt)
        spin_lock(&svcpt->scp_lock);
 
        svcpt->scp_nrqbds_posted--;
-       list_del(&rqbd->rqbd_list);
-       list_add_tail(&rqbd->rqbd_list, &svcpt->scp_rqbd_idle);
+       list_move_tail(&rqbd->rqbd_list, &svcpt->scp_rqbd_idle);
 
-       /* Don't complain if no request buffers are posted right now; LNET
-        * won't drop requests because we set the portal lazy! */
+       /*
+        * Don't complain if no request buffers are posted right now; LNET
+        * won't drop requests because we set the portal lazy!
+        */
 
        spin_unlock(&svcpt->scp_lock);
 
        return -1;
 }
 
-static void ptlrpc_at_timer(unsigned long castmeharder)
+static void ptlrpc_at_timer(cfs_timer_cb_arg_t data)
 {
        struct ptlrpc_service_part *svcpt;
 
-       svcpt = (struct ptlrpc_service_part *)castmeharder;
+       svcpt = cfs_from_timer(svcpt, data, scp_at_timer);
 
        svcpt->scp_at_check = 1;
-       svcpt->scp_at_checktime = cfs_time_current();
+       svcpt->scp_at_checktime = ktime_get();
        wake_up(&svcpt->scp_waitq);
 }
 
-static void
-ptlrpc_server_nthreads_check(struct ptlrpc_service *svc,
-                            struct ptlrpc_service_conf *conf)
+static void ptlrpc_server_nthreads_check(struct ptlrpc_service *svc,
+                                        struct ptlrpc_service_conf *conf)
 {
-       struct ptlrpc_service_thr_conf  *tc = &conf->psc_thr;
-       unsigned                        init;
-       unsigned                        total;
-       unsigned                        nthrs;
-       int                             weight;
+       struct ptlrpc_service_thr_conf *tc = &conf->psc_thr;
+       unsigned int init;
+       unsigned int total;
+       unsigned int nthrs;
+       int weight;
 
        /*
         * Common code for estimating & validating threads number.
@@ -512,14 +511,18 @@ ptlrpc_server_nthreads_check(struct ptlrpc_service *svc,
        init = PTLRPC_NTHRS_INIT + (svc->srv_ops.so_hpreq_handler != NULL);
        init = max_t(int, init, tc->tc_nthrs_init);
 
-       /* NB: please see comments in lustre_lnet.h for definition
-        * details of these members */
+       /*
+        * NB: please see comments in lustre_lnet.h for definition
+        * details of these members
+        */
        LASSERT(tc->tc_nthrs_max != 0);
 
        if (tc->tc_nthrs_user != 0) {
-               /* In case there is a reason to test a service with many
+               /*
+                * In case there is a reason to test a service with many
                 * threads, we give a less strict check here, it can
-                * be up to 8 * nthrs_max */
+                * be up to 8 * nthrs_max
+                */
                total = min(tc->tc_nthrs_max * 8, tc->tc_nthrs_user);
                nthrs = total / svc->srv_ncpts;
                init  = max(init, nthrs);
@@ -528,8 +531,10 @@ ptlrpc_server_nthreads_check(struct ptlrpc_service *svc,
 
        total = tc->tc_nthrs_max;
        if (tc->tc_nthrs_base == 0) {
-               /* don't care about base threads number per partition,
-                * this is most for non-affinity service */
+               /*
+                * don't care about base threads number per partition,
+                * this is most for non-affinity service
+                */
                nthrs = total / svc->srv_ncpts;
                goto out;
        }
@@ -538,9 +543,11 @@ ptlrpc_server_nthreads_check(struct ptlrpc_service *svc,
        if (svc->srv_ncpts == 1) {
                int     i;
 
-               /* NB: Increase the base number if it's single partition
+               /*
+                * NB: Increase the base number if it's single partition
                 * and total number of cores/HTs is larger or equal to 4.
-                * result will always < 2 * nthrs_base */
+                * result will always < 2 * nthrs_base
+                */
                weight = cfs_cpt_weight(svc->srv_cptable, CFS_CPT_ANY);
                for (i = 1; (weight >> (i + 1)) != 0 && /* >= 4 cores/HTs */
                            (tc->tc_nthrs_base >> i) != 0; i++)
@@ -553,7 +560,7 @@ ptlrpc_server_nthreads_check(struct ptlrpc_service *svc,
 
                /*
                 * User wants to increase number of threads with for
-                * each CPU core/HT, most likely the factor is larger then
+                * each CPU core/HT, most likely the factor is larger than
                 * one thread/core because service threads are supposed to
                 * be blocked by lock or wait for IO.
                 */
@@ -563,13 +570,16 @@ ptlrpc_server_nthreads_check(struct ptlrpc_service *svc,
                 * have too many threads no matter how many cores/HTs
                 * there are.
                 */
-               if (cfs_cpu_ht_nsiblings(0) > 1) { /* weight is # of HTs */
+               preempt_disable();
+               if (cpumask_weight
+                   (topology_sibling_cpumask(smp_processor_id())) > 1) {
+                       /* weight is # of HTs */
                        /* depress thread factor for hyper-thread */
                        factor = factor - (factor >> 1) + (factor >> 3);
                }
+               preempt_enable();
 
                weight = cfs_cpt_weight(svc->srv_cptable, 0);
-               LASSERT(weight > 0);
 
                for (; factor > 0 && weight > 0; factor--, weight -= fade)
                        nthrs += min(weight, fade) * factor;
@@ -585,8 +595,8 @@ ptlrpc_server_nthreads_check(struct ptlrpc_service *svc,
        svc->srv_nthrs_cpt_init = init;
 
        if (nthrs * svc->srv_ncpts > tc->tc_nthrs_max) {
-               CDEBUG(D_OTHER, "%s: This service may have more threads (%d) "
-                      "than the given soft limit (%d)\n",
+               CDEBUG(D_OTHER,
+                      "%s: This service may have more threads (%d) than the given soft limit (%d)\n",
                       svc->srv_name, nthrs * svc->srv_ncpts,
                       tc->tc_nthrs_max);
        }
@@ -595,20 +605,20 @@ ptlrpc_server_nthreads_check(struct ptlrpc_service *svc,
 /**
  * Initialize percpt data for a service
  */
-static int
-ptlrpc_service_part_init(struct ptlrpc_service *svc,
-                        struct ptlrpc_service_part *svcpt, int cpt)
+static int ptlrpc_service_part_init(struct ptlrpc_service *svc,
+                                   struct ptlrpc_service_part *svcpt, int cpt)
 {
-       struct ptlrpc_at_array  *array;
-       int                     size;
-       int                     index;
-       int                     rc;
+       struct ptlrpc_at_array *array;
+       int size;
+       int index;
+       int rc;
 
        svcpt->scp_cpt = cpt;
        INIT_LIST_HEAD(&svcpt->scp_threads);
 
        /* rqbd and incoming request queue */
        spin_lock_init(&svcpt->scp_lock);
+       mutex_init(&svcpt->scp_mutex);
        INIT_LIST_HEAD(&svcpt->scp_rqbd_idle);
        INIT_LIST_HEAD(&svcpt->scp_rqbd_posted);
        INIT_LIST_HEAD(&svcpt->scp_req_incoming);
@@ -650,17 +660,23 @@ ptlrpc_service_part_init(struct ptlrpc_service *svc,
        if (array->paa_reqs_count == NULL)
                goto failed;
 
-       cfs_timer_init(&svcpt->scp_at_timer, ptlrpc_at_timer, svcpt);
-       /* At SOW, service time should be quick; 10s seems generous. If client
-        * timeout is less than this, we'll be sending an early reply. */
+       cfs_timer_setup(&svcpt->scp_at_timer, ptlrpc_at_timer,
+                       (unsigned long)svcpt, 0);
+
+       /*
+        * At SOW, service time should be quick; 10s seems generous. If client
+        * timeout is less than this, we'll be sending an early reply.
+        */
        at_init(&svcpt->scp_at_estimate, 10, 0);
 
        /* assign this before call ptlrpc_grow_req_bufs */
        svcpt->scp_service = svc;
        /* Now allocate the request buffers, but don't post them now */
        rc = ptlrpc_grow_req_bufs(svcpt, 0);
-       /* We shouldn't be under memory pressure at startup, so
-        * fail if we can't allocate all our buffers at this time. */
+       /*
+        * We shouldn't be under memory pressure at startup, so
+        * fail if we can't allocate all our buffers at this time.
+        */
        if (rc != 0)
                goto failed;
 
@@ -686,19 +702,20 @@ ptlrpc_service_part_init(struct ptlrpc_service *svc,
  * This includes starting serving threads , allocating and posting rqbds and
  * so on.
  */
-struct ptlrpc_service *
-ptlrpc_register_service(struct ptlrpc_service_conf *conf,
-                       struct proc_dir_entry *proc_entry)
+struct ptlrpc_service *ptlrpc_register_service(struct ptlrpc_service_conf *conf,
+                                              struct kset *parent,
+                                              struct dentry *debugfs_entry)
 {
-       struct ptlrpc_service_cpt_conf  *cconf = &conf->psc_cpt;
-       struct ptlrpc_service           *service;
-       struct ptlrpc_service_part      *svcpt;
-       struct cfs_cpt_table            *cptable;
-       __u32                           *cpts = NULL;
-       int                             ncpts;
-       int                             cpt;
-       int                             rc;
-       int                             i;
+       struct ptlrpc_service_cpt_conf *cconf = &conf->psc_cpt;
+       struct ptlrpc_service *service;
+       struct ptlrpc_service_part *svcpt;
+       struct cfs_cpt_table *cptable;
+       __u32 *cpts = NULL;
+       int ncpts;
+       int cpt;
+       int rc;
+       int i;
+
        ENTRY;
 
        LASSERT(conf->psc_buf.bc_nbufs > 0);
@@ -710,7 +727,13 @@ ptlrpc_register_service(struct ptlrpc_service_conf *conf,
        if (cptable == NULL)
                cptable = cfs_cpt_table;
 
-       if (!conf->psc_thr.tc_cpu_affinity) {
+       if (conf->psc_thr.tc_cpu_bind > 1) {
+               CERROR("%s: Invalid cpu bind value %d, only 1 or 0 allowed\n",
+                      conf->psc_name, conf->psc_thr.tc_cpu_bind);
+               RETURN(ERR_PTR(-EINVAL));
+       }
+
+       if (!cconf->cc_affinity) {
                ncpts = 1;
        } else {
                ncpts = cfs_cpt_number(cptable);
@@ -749,6 +772,7 @@ ptlrpc_register_service(struct ptlrpc_service_conf *conf,
        service->srv_cptable            = cptable;
        service->srv_cpts               = cpts;
        service->srv_ncpts              = ncpts;
+       service->srv_cpt_bind           = conf->psc_thr.tc_cpu_bind;
 
        service->srv_cpt_bits = 0; /* it's zero already, easy to read... */
        while ((1 << service->srv_cpt_bits) < cfs_cpt_number(cptable))
@@ -763,12 +787,22 @@ ptlrpc_register_service(struct ptlrpc_service_conf *conf,
        /* buffer configuration */
        service->srv_nbuf_per_group     = test_req_buffer_pressure ?
                                          1 : conf->psc_buf.bc_nbufs;
+       /* do not limit max number of rqbds by default */
+       service->srv_nrqbds_max         = 0;
+
        service->srv_max_req_size       = conf->psc_buf.bc_req_max_size +
                                          SPTLRPC_MAX_PAYLOAD;
        service->srv_buf_size           = conf->psc_buf.bc_buf_size;
        service->srv_rep_portal         = conf->psc_buf.bc_rep_portal;
        service->srv_req_portal         = conf->psc_buf.bc_req_portal;
 
+       /* With slab/alloc_pages buffer size will be rounded up to 2^n */
+       if (service->srv_buf_size & (service->srv_buf_size - 1)) {
+               int round = size_roundup_power2(service->srv_buf_size);
+
+               service->srv_buf_size = round;
+       }
+
        /* Increase max reply size to next power of two */
        service->srv_max_reply_size = 1;
        while (service->srv_max_reply_size <
@@ -781,7 +815,7 @@ ptlrpc_register_service(struct ptlrpc_service_conf *conf,
        service->srv_ops                = conf->psc_ops;
 
        for (i = 0; i < ncpts; i++) {
-               if (!conf->psc_thr.tc_cpu_affinity)
+               if (!cconf->cc_affinity)
                        cpt = CFS_CPT_ANY;
                else
                        cpt = cpts != NULL ? cpts[i] : i;
@@ -805,8 +839,14 @@ ptlrpc_register_service(struct ptlrpc_service_conf *conf,
        list_add(&service->srv_list, &ptlrpc_all_services);
        mutex_unlock(&ptlrpc_all_services_mutex);
 
-       if (proc_entry != NULL)
-               ptlrpc_lprocfs_register_service(proc_entry, service);
+       if (parent) {
+               rc = ptlrpc_sysfs_register_service(parent, service);
+               if (rc)
+                       GOTO(failed, rc);
+       }
+
+       if (debugfs_entry != NULL)
+               ptlrpc_ldebugfs_register_service(debugfs_entry, service);
 
        rc = ptlrpc_service_nrs_setup(service);
        if (rc != 0)
@@ -838,16 +878,20 @@ static void ptlrpc_server_free_request(struct ptlrpc_request *req)
        LASSERT(atomic_read(&req->rq_refcount) == 0);
        LASSERT(list_empty(&req->rq_timed_list));
 
-       /* DEBUG_REQ() assumes the reply state of a request with a valid
-        * ref will not be destroyed until that reference is dropped. */
+       /*
+        * DEBUG_REQ() assumes the reply state of a request with a valid
+        * ref will not be destroyed until that reference is dropped.
+        */
        ptlrpc_req_drop_rs(req);
 
        sptlrpc_svc_ctx_decref(req);
 
        if (req != &req->rq_rqbd->rqbd_req) {
-               /* NB request buffers use an embedded
+               /*
+                * NB request buffers use an embedded
                 * req if the incoming req unlinked the
-                * MD; this isn't one of them! */
+                * MD; this isn't one of them!
+                */
                ptlrpc_request_cache_free(req);
        }
 }
@@ -875,8 +919,10 @@ void ptlrpc_server_drop_request(struct ptlrpc_request *req)
 
        if (req->rq_at_linked) {
                spin_lock(&svcpt->scp_at_lock);
-               /* recheck with lock, in case it's unlinked by
-                * ptlrpc_at_check_timed() */
+               /*
+                * recheck with lock, in case it's unlinked by
+                * ptlrpc_at_check_timed()
+                */
                if (likely(req->rq_at_linked))
                        ptlrpc_at_remove_timed(req);
                spin_unlock(&svcpt->scp_at_lock);
@@ -897,13 +943,13 @@ void ptlrpc_server_drop_request(struct ptlrpc_request *req)
        refcount = --(rqbd->rqbd_refcount);
        if (refcount == 0) {
                /* request buffer is now idle: add to history */
-               list_del(&rqbd->rqbd_list);
-
-               list_add_tail(&rqbd->rqbd_list, &svcpt->scp_hist_rqbds);
+               list_move_tail(&rqbd->rqbd_list, &svcpt->scp_hist_rqbds);
                svcpt->scp_hist_nrqbds++;
 
-               /* cull some history?
-                * I expect only about 1 or 2 rqbds need to be recycled here */
+               /*
+                * cull some history?
+                * I expect only about 1 or 2 rqbds need to be recycled here
+                */
                while (svcpt->scp_hist_nrqbds > svc->srv_hist_nrqbds_cpt_max) {
                        rqbd = list_entry(svcpt->scp_hist_rqbds.next,
                                          struct ptlrpc_request_buffer_desc,
@@ -912,8 +958,10 @@ void ptlrpc_server_drop_request(struct ptlrpc_request *req)
                        list_del(&rqbd->rqbd_list);
                        svcpt->scp_hist_nrqbds--;
 
-                       /* remove rqbd's reqs from svc's req history while
-                        * I've got the service lock */
+                       /*
+                        * remove rqbd's reqs from svc's req history while
+                        * I've got the service lock
+                        */
                        list_for_each(tmp, &rqbd->rqbd_reqs) {
                                req = list_entry(tmp, struct ptlrpc_request,
                                                 rq_list);
@@ -939,10 +987,24 @@ void ptlrpc_server_drop_request(struct ptlrpc_request *req)
                        spin_lock(&svcpt->scp_lock);
                        /*
                         * now all reqs including the embedded req has been
-                        * disposed, schedule request buffer for re-use.
+                        * disposed, schedule request buffer for re-use
+                        * or free it to drain some in excess.
                         */
                        LASSERT(atomic_read(&rqbd->rqbd_req.rq_refcount) == 0);
-                       list_add_tail(&rqbd->rqbd_list, &svcpt->scp_rqbd_idle);
+                       if (svcpt->scp_nrqbds_posted >=
+                           svc->srv_nbuf_per_group ||
+                           (svc->srv_nrqbds_max != 0 &&
+                            svcpt->scp_nrqbds_total > svc->srv_nrqbds_max) ||
+                           test_req_buffer_pressure) {
+                               /* like in ptlrpc_free_rqbd() */
+                               svcpt->scp_nrqbds_total--;
+                               OBD_FREE_LARGE(rqbd->rqbd_buffer,
+                                              svc->srv_buf_size);
+                               OBD_FREE_PTR(rqbd);
+                       } else {
+                               list_add_tail(&rqbd->rqbd_list,
+                                             &svcpt->scp_rqbd_idle);
+                       }
                }
 
                spin_unlock(&svcpt->scp_lock);
@@ -963,6 +1025,30 @@ void ptlrpc_server_drop_request(struct ptlrpc_request *req)
        }
 }
 
+static void ptlrpc_add_exp_list_nolock(struct ptlrpc_request *req,
+                                      struct obd_export *export, bool hp)
+{
+       __u16 tag = lustre_msg_get_tag(req->rq_reqmsg);
+
+       if (hp)
+               list_add(&req->rq_exp_list, &export->exp_hp_rpcs);
+       else
+               list_add(&req->rq_exp_list, &export->exp_reg_rpcs);
+       if (tag && export->exp_used_slots)
+               set_bit(tag - 1, export->exp_used_slots);
+}
+
+static void ptlrpc_del_exp_list(struct ptlrpc_request *req)
+{
+       __u16 tag = lustre_msg_get_tag(req->rq_reqmsg);
+
+       spin_lock(&req->rq_export->exp_rpc_lock);
+       list_del_init(&req->rq_exp_list);
+       if (tag && !req->rq_obsolete && req->rq_export->exp_used_slots)
+               clear_bit(tag - 1, req->rq_export->exp_used_slots);
+       spin_unlock(&req->rq_export->exp_rpc_lock);
+}
+
 /** Change request export and move hp request from old export to new */
 void ptlrpc_request_change_export(struct ptlrpc_request *req,
                                  struct obd_export *export)
@@ -970,18 +1056,14 @@ void ptlrpc_request_change_export(struct ptlrpc_request *req,
        if (req->rq_export != NULL) {
                LASSERT(!list_empty(&req->rq_exp_list));
                /* remove rq_exp_list from last export */
-               spin_lock_bh(&req->rq_export->exp_rpc_lock);
-               list_del_init(&req->rq_exp_list);
-               spin_unlock_bh(&req->rq_export->exp_rpc_lock);
-               /* export has one reference already, so it`s safe to
+               ptlrpc_del_exp_list(req);
+               /* export has one reference already, so it's safe to
                 * add req to export queue here and get another
-                * reference for request later */
-               spin_lock_bh(&export->exp_rpc_lock);
-               if (req->rq_ops != NULL) /* hp request */
-                       list_add(&req->rq_exp_list, &export->exp_hp_rpcs);
-               else
-                       list_add(&req->rq_exp_list, &export->exp_reg_rpcs);
-               spin_unlock_bh(&export->exp_rpc_lock);
+                * reference for request later
+                */
+               spin_lock(&export->exp_rpc_lock);
+               ptlrpc_add_exp_list_nolock(req, export, req->rq_ops != NULL);
+               spin_unlock(&export->exp_rpc_lock);
 
                class_export_rpc_dec(req->rq_export);
                class_export_put(req->rq_export);
@@ -990,8 +1072,6 @@ void ptlrpc_request_change_export(struct ptlrpc_request *req,
        /* request takes one export refcount */
        req->rq_export = class_export_get(export);
        class_export_rpc_inc(export);
-
-       return;
 }
 
 /**
@@ -1007,7 +1087,7 @@ static void ptlrpc_server_finish_request(struct ptlrpc_service_part *svcpt,
 }
 
 /**
- * to finish a active request: stop sending more early replies, and release
+ * to finish an active request: stop sending more early replies, and release
  * the request. should be called after we finished handling the request.
  */
 static void ptlrpc_server_finish_active_request(
@@ -1034,31 +1114,35 @@ static void ptlrpc_server_finish_active_request(
  * This function is only called when some export receives a message (i.e.,
  * the network is up.)
  */
-void ptlrpc_update_export_timer(struct obd_export *exp, long extra_delay)
+void ptlrpc_update_export_timer(struct obd_export *exp, time64_t extra_delay)
 {
-        struct obd_export *oldest_exp;
-        time_t oldest_time, new_time;
+       struct obd_export *oldest_exp;
+       time64_t oldest_time, new_time;
 
-        ENTRY;
+       ENTRY;
 
-        LASSERT(exp);
+       LASSERT(exp);
 
-        /* Compensate for slow machines, etc, by faking our request time
-           into the future.  Although this can break the strict time-ordering
-           of the list, we can be really lazy here - we don't have to evict
-           at the exact right moment.  Eventually, all silent exports
-           will make it to the top of the list. */
+       /*
+        * Compensate for slow machines, etc, by faking our request time
+        * into the future.  Although this can break the strict time-ordering
+        * of the list, we can be really lazy here - we don't have to evict
+        * at the exact right moment.  Eventually, all silent exports
+        * will make it to the top of the list.
+        */
 
-        /* Do not pay attention on 1sec or smaller renewals. */
-        new_time = cfs_time_current_sec() + extra_delay;
-        if (exp->exp_last_request_time + 1 /*second */ >= new_time)
-                RETURN_EXIT;
+       /* Do not pay attention on 1sec or smaller renewals. */
+       new_time = ktime_get_real_seconds() + extra_delay;
+       if (exp->exp_last_request_time + 1 /*second */ >= new_time)
+               RETURN_EXIT;
 
-        exp->exp_last_request_time = new_time;
+       exp->exp_last_request_time = new_time;
 
-       /* exports may get disconnected from the chain even though the
-          export has references, so we must keep the spin lock while
-          manipulating the lists */
+       /*
+        * exports may get disconnected from the chain even though the
+        * export has references, so we must keep the spin lock while
+        * manipulating the lists
+        */
        spin_lock(&exp->exp_obd->obd_dev_lock);
 
        if (list_empty(&exp->exp_obd_chain_timed)) {
@@ -1075,39 +1159,43 @@ void ptlrpc_update_export_timer(struct obd_export *exp, long extra_delay)
        oldest_time = oldest_exp->exp_last_request_time;
        spin_unlock(&exp->exp_obd->obd_dev_lock);
 
-        if (exp->exp_obd->obd_recovering) {
-                /* be nice to everyone during recovery */
-                EXIT;
-                return;
-        }
-
-        /* Note - racing to start/reset the obd_eviction timer is safe */
-        if (exp->exp_obd->obd_eviction_timer == 0) {
-                /* Check if the oldest entry is expired. */
-                if (cfs_time_current_sec() > (oldest_time + PING_EVICT_TIMEOUT +
-                                              extra_delay)) {
-                        /* We need a second timer, in case the net was down and
-                         * it just came back. Since the pinger may skip every
-                         * other PING_INTERVAL (see note in ptlrpc_pinger_main),
-                         * we better wait for 3. */
-                        exp->exp_obd->obd_eviction_timer =
-                                cfs_time_current_sec() + 3 * PING_INTERVAL;
-                        CDEBUG(D_HA, "%s: Think about evicting %s from "CFS_TIME_T"\n",
-                               exp->exp_obd->obd_name,
-                               obd_export_nid2str(oldest_exp), oldest_time);
-                }
-        } else {
-                if (cfs_time_current_sec() >
-                    (exp->exp_obd->obd_eviction_timer + extra_delay)) {
-                        /* The evictor won't evict anyone who we've heard from
-                         * recently, so we don't have to check before we start
-                         * it. */
-                        if (!ping_evictor_wake(exp))
-                                exp->exp_obd->obd_eviction_timer = 0;
-                }
-        }
-
-        EXIT;
+       if (exp->exp_obd->obd_recovering) {
+               /* be nice to everyone during recovery */
+               EXIT;
+               return;
+       }
+
+       /* Note - racing to start/reset the obd_eviction timer is safe */
+       if (exp->exp_obd->obd_eviction_timer == 0) {
+               /* Check if the oldest entry is expired. */
+               if (ktime_get_real_seconds() >
+                   oldest_time + PING_EVICT_TIMEOUT + extra_delay) {
+                       /*
+                        * We need a second timer, in case the net was down and
+                        * it just came back. Since the pinger may skip every
+                        * other PING_INTERVAL (see note in ptlrpc_pinger_main),
+                        * we better wait for 3.
+                        */
+                       exp->exp_obd->obd_eviction_timer =
+                               ktime_get_real_seconds() + 3 * PING_INTERVAL;
+                       CDEBUG(D_HA, "%s: Think about evicting %s from %lld\n",
+                              exp->exp_obd->obd_name,
+                              obd_export_nid2str(oldest_exp), oldest_time);
+               }
+       } else {
+               if (ktime_get_real_seconds() >
+                   (exp->exp_obd->obd_eviction_timer + extra_delay)) {
+                       /*
+                        * The evictor won't evict anyone who we've heard from
+                        * recently, so we don't have to check before we start
+                        * it.
+                        */
+                       if (!ping_evictor_wake(exp))
+                               exp->exp_obd->obd_eviction_timer = 0;
+               }
+       }
+
+       EXIT;
 }
 
 /**
@@ -1128,52 +1216,55 @@ static int ptlrpc_check_req(struct ptlrpc_request *req)
                return -EEXIST;
        }
        if (unlikely(obd == NULL || obd->obd_fail)) {
-               /* Failing over, don't handle any more reqs,
-                * send error response instead. */
+               /*
+                * Failing over, don't handle any more reqs,
+                * send error response instead.
+                */
                CDEBUG(D_RPCTRACE, "Dropping req %p for failed obd %s\n",
                        req, (obd != NULL) ? obd->obd_name : "unknown");
-                rc = -ENODEV;
-        } else if (lustre_msg_get_flags(req->rq_reqmsg) &
-                   (MSG_REPLAY | MSG_REQ_REPLAY_DONE) &&
+               rc = -ENODEV;
+       } else if (lustre_msg_get_flags(req->rq_reqmsg) &
+                  (MSG_REPLAY | MSG_REQ_REPLAY_DONE) &&
                   !obd->obd_recovering) {
-                        DEBUG_REQ(D_ERROR, req,
-                                  "Invalid replay without recovery");
-                        class_fail_export(req->rq_export);
-                        rc = -ENODEV;
-        } else if (lustre_msg_get_transno(req->rq_reqmsg) != 0 &&
+               DEBUG_REQ(D_ERROR, req,
+                         "Invalid replay without recovery");
+               class_fail_export(req->rq_export);
+               rc = -ENODEV;
+       } else if (lustre_msg_get_transno(req->rq_reqmsg) != 0 &&
                   !obd->obd_recovering) {
-                        DEBUG_REQ(D_ERROR, req, "Invalid req with transno "
-                                  LPU64" without recovery",
-                                  lustre_msg_get_transno(req->rq_reqmsg));
-                        class_fail_export(req->rq_export);
-                        rc = -ENODEV;
-        }
+               DEBUG_REQ(D_ERROR, req,
+                         "Invalid req with transno %llu without recovery",
+                         lustre_msg_get_transno(req->rq_reqmsg));
+               class_fail_export(req->rq_export);
+               rc = -ENODEV;
+       }
 
-        if (unlikely(rc < 0)) {
-                req->rq_status = rc;
-                ptlrpc_error(req);
-        }
-        return rc;
+       if (unlikely(rc < 0)) {
+               req->rq_status = rc;
+               ptlrpc_error(req);
+       }
+       return rc;
 }
 
 static void ptlrpc_at_set_timer(struct ptlrpc_service_part *svcpt)
 {
        struct ptlrpc_at_array *array = &svcpt->scp_at_array;
-       __s32 next;
+       time64_t next;
 
        if (array->paa_count == 0) {
-               cfs_timer_disarm(&svcpt->scp_at_timer);
+               del_timer(&svcpt->scp_at_timer);
                return;
        }
 
        /* Set timer for closest deadline */
-       next = (__s32)(array->paa_deadline - cfs_time_current_sec() -
-                      at_early_margin);
+       next = array->paa_deadline - ktime_get_real_seconds() -
+              at_early_margin;
        if (next <= 0) {
-               ptlrpc_at_timer((unsigned long)svcpt);
+               ptlrpc_at_timer(cfs_timer_cb_arg(svcpt, scp_at_timer));
        } else {
-               cfs_timer_arm(&svcpt->scp_at_timer, cfs_time_shift(next));
-               CDEBUG(D_INFO, "armed %s at %+ds\n",
+               mod_timer(&svcpt->scp_at_timer,
+                         jiffies + nsecs_to_jiffies(next * NSEC_PER_SEC));
+               CDEBUG(D_INFO, "armed %s at %+llds\n",
                       svcpt->scp_service->srv_name, next);
        }
 }
@@ -1183,40 +1274,40 @@ static int ptlrpc_at_add_timed(struct ptlrpc_request *req)
 {
        struct ptlrpc_service_part *svcpt = req->rq_rqbd->rqbd_svcpt;
        struct ptlrpc_at_array *array = &svcpt->scp_at_array;
-        struct ptlrpc_request *rq = NULL;
-        __u32 index;
+       struct ptlrpc_request *rq = NULL;
+       __u32 index;
 
-        if (AT_OFF)
-                return(0);
+       if (AT_OFF)
+               return(0);
 
-        if (req->rq_no_reply)
-                return 0;
+       if (req->rq_no_reply)
+               return 0;
 
-        if ((lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT) == 0)
-                return(-ENOSYS);
+       if ((lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT) == 0)
+               return(-ENOSYS);
 
        spin_lock(&svcpt->scp_at_lock);
        LASSERT(list_empty(&req->rq_timed_list));
 
-        index = (unsigned long)req->rq_deadline % array->paa_size;
-        if (array->paa_reqs_count[index] > 0) {
-                /* latest rpcs will have the latest deadlines in the list,
-                 * so search backward. */
-               list_for_each_entry_reverse(rq,
-                                                &array->paa_reqs_array[index],
-                                                rq_timed_list) {
-                        if (req->rq_deadline >= rq->rq_deadline) {
+       div_u64_rem(req->rq_deadline, array->paa_size, &index);
+       if (array->paa_reqs_count[index] > 0) {
+               /*
+                * latest rpcs will have the latest deadlines in the list,
+                * so search backward.
+                */
+               list_for_each_entry_reverse(rq, &array->paa_reqs_array[index],
+                                           rq_timed_list) {
+                       if (req->rq_deadline >= rq->rq_deadline) {
                                list_add(&req->rq_timed_list,
-                                             &rq->rq_timed_list);
-                                break;
-                        }
-                }
-        }
+                                        &rq->rq_timed_list);
+                               break;
+                       }
+               }
+       }
 
-        /* Add the request at the head of the list */
+       /* Add the request at the head of the list */
        if (list_empty(&req->rq_timed_list))
-               list_add(&req->rq_timed_list,
-                             &array->paa_reqs_array[index]);
+               list_add(&req->rq_timed_list, &array->paa_reqs_array[index]);
 
        spin_lock(&req->rq_lock);
        req->rq_at_linked = 1;
@@ -1233,8 +1324,7 @@ static int ptlrpc_at_add_timed(struct ptlrpc_request *req)
        return 0;
 }
 
-static void
-ptlrpc_at_remove_timed(struct ptlrpc_request *req)
+static void ptlrpc_at_remove_timed(struct ptlrpc_request *req)
 {
        struct ptlrpc_at_array *array;
 
@@ -1261,8 +1351,8 @@ static int ptlrpc_at_send_early_reply(struct ptlrpc_request *req)
        struct ptlrpc_service_part *svcpt = req->rq_rqbd->rqbd_svcpt;
        struct ptlrpc_request *reqcopy;
        struct lustre_msg *reqmsg;
-       cfs_duration_t olddl = req->rq_deadline - cfs_time_current_sec();
-       time_t  newdl;
+       time64_t olddl = req->rq_deadline - ktime_get_real_seconds();
+       time64_t newdl;
        int rc;
 
        ENTRY;
@@ -1272,48 +1362,61 @@ static int ptlrpc_at_send_early_reply(struct ptlrpc_request *req)
                RETURN(1);
        }
 
-        /* deadline is when the client expects us to reply, margin is the
-           difference between clients' and servers' expectations */
-        DEBUG_REQ(D_ADAPTTO, req,
-                  "%ssending early reply (deadline %+lds, margin %+lds) for "
-                  "%d+%d", AT_OFF ? "AT off - not " : "",
-                 olddl, olddl - at_get(&svcpt->scp_at_estimate),
+       /*
+        * deadline is when the client expects us to reply, margin is the
+        * difference between clients' and servers' expectations
+        */
+       DEBUG_REQ(D_ADAPTTO, req,
+                 "%ssending early reply (deadline %+llds, margin %+llds) for %d+%d",
+                 AT_OFF ? "AT off - not " : "",
+                 (s64)olddl, (s64)(olddl - at_get(&svcpt->scp_at_estimate)),
                  at_get(&svcpt->scp_at_estimate), at_extra);
 
-        if (AT_OFF)
-                RETURN(0);
+       if (AT_OFF)
+               RETURN(0);
 
-        if (olddl < 0) {
-                DEBUG_REQ(D_WARNING, req, "Already past deadline (%+lds), "
-                          "not sending early reply. Consider increasing "
-                          "at_early_margin (%d)?", olddl, at_early_margin);
+       if (olddl < 0) {
+               /* below message is checked in replay-ost-single.sh test_9 */
+               DEBUG_REQ(D_WARNING, req,
+                         "Already past deadline (%+llds), not sending early reply. Consider increasing at_early_margin (%d)?",
+                         (s64)olddl, at_early_margin);
 
-                /* Return an error so we're not re-added to the timed list. */
-                RETURN(-ETIMEDOUT);
-        }
+               /* Return an error so we're not re-added to the timed list. */
+               RETURN(-ETIMEDOUT);
+       }
 
-        if ((lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT) == 0){
-                DEBUG_REQ(D_INFO, req, "Wanted to ask client for more time, "
-                          "but no AT support");
-                RETURN(-ENOSYS);
-        }
+       if ((lustre_msghdr_get_flags(req->rq_reqmsg) &
+            MSGHDR_AT_SUPPORT) == 0) {
+               DEBUG_REQ(D_INFO, req,
+                         "Wanted to ask client for more time, but no AT support");
+               RETURN(-ENOSYS);
+       }
 
        if (req->rq_export &&
            lustre_msg_get_flags(req->rq_reqmsg) &
            (MSG_REPLAY | MSG_REQ_REPLAY_DONE | MSG_LOCK_REPLAY_DONE)) {
-               /* During recovery, we don't want to send too many early
+               struct obd_device *obd_exp = req->rq_export->exp_obd;
+
+               /*
+                * During recovery, we don't want to send too many early
                 * replies, but on the other hand we want to make sure the
                 * client has enough time to resend if the rpc is lost. So
                 * during the recovery period send at least 4 early replies,
                 * spacing them every at_extra if we can. at_estimate should
-                * always equal this fixed value during recovery. */
-               /* Don't account request processing time into AT history
+                * always equal this fixed value during recovery.
+                */
+
+               /*
+                * Don't account request processing time into AT history
                 * during recovery, it is not service time we need but
-                * includes also waiting time for recovering clients */
-               newdl = cfs_time_current_sec() + min(at_extra,
-                       req->rq_export->exp_obd->obd_recovery_timeout / 4);
+                * includes also waiting time for recovering clients
+                */
+               newdl = min_t(time64_t, at_extra,
+                             obd_exp->obd_recovery_timeout / 4) +
+                       ktime_get_real_seconds();
        } else {
-               /* We want to extend the request deadline by at_extra seconds,
+               /*
+                * We want to extend the request deadline by at_extra seconds,
                 * so we set our service estimate to reflect how much time has
                 * passed since this request arrived plus an additional
                 * at_extra seconds. The client will calculate the new deadline
@@ -1321,18 +1424,20 @@ static int ptlrpc_at_send_early_reply(struct ptlrpc_request *req)
                 * account for network latency). See ptlrpc_at_recv_early_reply
                 */
                at_measured(&svcpt->scp_at_estimate, at_extra +
-                           cfs_time_current_sec() -
+                           ktime_get_real_seconds() -
                            req->rq_arrival_time.tv_sec);
                newdl = req->rq_arrival_time.tv_sec +
                        at_get(&svcpt->scp_at_estimate);
        }
 
-       /* Check to see if we've actually increased the deadline -
-        * we may be past adaptive_max */
+       /*
+        * Check to see if we've actually increased the deadline -
+        * we may be past adaptive_max
+        */
        if (req->rq_deadline >= newdl) {
-               DEBUG_REQ(D_WARNING, req, "Couldn't add any time "
-                         "(%ld/%ld), not sending early reply\n",
-                         olddl, newdl - cfs_time_current_sec());
+               DEBUG_REQ(D_WARNING, req,
+                         "Could not add any time (%lld/%lld), not sending early reply",
+                         (s64)olddl, (s64)(newdl - ktime_get_real_seconds()));
                RETURN(-ETIMEDOUT);
        }
 
@@ -1343,16 +1448,16 @@ static int ptlrpc_at_send_early_reply(struct ptlrpc_request *req)
        if (!reqmsg)
                GOTO(out_free, rc = -ENOMEM);
 
-        *reqcopy = *req;
-        reqcopy->rq_reply_state = NULL;
-        reqcopy->rq_rep_swab_mask = 0;
-        reqcopy->rq_pack_bulk = 0;
-        reqcopy->rq_pack_udesc = 0;
-        reqcopy->rq_packed_final = 0;
-        sptlrpc_svc_ctx_addref(reqcopy);
-        /* We only need the reqmsg for the magic */
-        reqcopy->rq_reqmsg = reqmsg;
-        memcpy(reqmsg, req->rq_reqmsg, req->rq_reqlen);
+       *reqcopy = *req;
+       reqcopy->rq_reply_state = NULL;
+       reqcopy->rq_rep_swab_mask = 0;
+       reqcopy->rq_pack_bulk = 0;
+       reqcopy->rq_pack_udesc = 0;
+       reqcopy->rq_packed_final = 0;
+       sptlrpc_svc_ctx_addref(reqcopy);
+       /* We only need the reqmsg for the magic */
+       reqcopy->rq_reqmsg = reqmsg;
+       memcpy(reqmsg, req->rq_reqmsg, req->rq_reqlen);
 
        /*
         * tgt_brw_read() and tgt_brw_write() may have decided not to reply.
@@ -1363,42 +1468,44 @@ static int ptlrpc_at_send_early_reply(struct ptlrpc_request *req)
                GOTO(out, rc = -ETIMEDOUT);
 
        LASSERT(atomic_read(&req->rq_refcount));
-       /** if it is last refcount then early reply isn't needed */
+       /* if it is last refcount then early reply isn't needed */
        if (atomic_read(&req->rq_refcount) == 1) {
-               DEBUG_REQ(D_ADAPTTO, reqcopy, "Normal reply already sent out, "
-                         "abort sending early reply\n");
+               DEBUG_REQ(D_ADAPTTO, reqcopy,
+                         "Normal reply already sent, abort early reply");
                GOTO(out, rc = -EINVAL);
        }
 
-        /* Connection ref */
-        reqcopy->rq_export = class_conn2export(
-                                     lustre_msg_get_handle(reqcopy->rq_reqmsg));
-        if (reqcopy->rq_export == NULL)
-                GOTO(out, rc = -ENODEV);
+       /* Connection ref */
+       reqcopy->rq_export = class_conn2export(
+                       lustre_msg_get_handle(reqcopy->rq_reqmsg));
+       if (reqcopy->rq_export == NULL)
+               GOTO(out, rc = -ENODEV);
 
-        /* RPC ref */
+       /* RPC ref */
        class_export_rpc_inc(reqcopy->rq_export);
-        if (reqcopy->rq_export->exp_obd &&
-            reqcopy->rq_export->exp_obd->obd_fail)
-                GOTO(out_put, rc = -ENODEV);
+       if (reqcopy->rq_export->exp_obd &&
+           reqcopy->rq_export->exp_obd->obd_fail)
+               GOTO(out_put, rc = -ENODEV);
 
-        rc = lustre_pack_reply_flags(reqcopy, 1, NULL, NULL, LPRFL_EARLY_REPLY);
-        if (rc)
-                GOTO(out_put, rc);
+       rc = lustre_pack_reply_flags(reqcopy, 1, NULL, NULL, LPRFL_EARLY_REPLY);
+       if (rc)
+               GOTO(out_put, rc);
 
-        rc = ptlrpc_send_reply(reqcopy, PTLRPC_REPLY_EARLY);
+       rc = ptlrpc_send_reply(reqcopy, PTLRPC_REPLY_EARLY);
 
        if (!rc) {
                /* Adjust our own deadline to what we told the client */
                req->rq_deadline = newdl;
                req->rq_early_count++; /* number sent, server side */
        } else {
-               DEBUG_REQ(D_ERROR, req, "Early reply send failed %d", rc);
+               DEBUG_REQ(D_ERROR, req, "Early reply send failed: rc = %d", rc);
        }
 
-        /* Free the (early) reply state from lustre_pack_reply.
-           (ptlrpc_send_reply takes it's own rs ref, so this is safe here) */
-        ptlrpc_req_drop_rs(reqcopy);
+       /*
+        * Free the (early) reply state from lustre_pack_reply.
+        * (ptlrpc_send_reply takes it's own rs ref, so this is safe here)
+        */
+       ptlrpc_req_drop_rs(reqcopy);
 
 out_put:
        class_export_rpc_dec(reqcopy->rq_export);
@@ -1411,26 +1518,28 @@ out_free:
        RETURN(rc);
 }
 
-/* Send early replies to everybody expiring within at_early_margin
-   asking for at_extra time */
+/*
+ * Send early replies to everybody expiring within at_early_margin
+ * asking for at_extra time
+ */
 static int ptlrpc_at_check_timed(struct ptlrpc_service_part *svcpt)
 {
        struct ptlrpc_at_array *array = &svcpt->scp_at_array;
-        struct ptlrpc_request *rq, *n;
+       struct ptlrpc_request *rq, *n;
        struct list_head work_list;
-        __u32  index, count;
-        time_t deadline;
-        time_t now = cfs_time_current_sec();
-        cfs_duration_t delay;
-        int first, counter = 0;
-        ENTRY;
+       __u32 index, count;
+       time64_t deadline;
+       time64_t now = ktime_get_real_seconds();
+       s64 delay;
+       int first, counter = 0;
 
+       ENTRY;
        spin_lock(&svcpt->scp_at_lock);
        if (svcpt->scp_at_check == 0) {
                spin_unlock(&svcpt->scp_at_lock);
                RETURN(0);
        }
-       delay = cfs_time_sub(cfs_time_current(), svcpt->scp_at_checktime);
+       delay = ktime_ms_delta(ktime_get(), svcpt->scp_at_checktime);
        svcpt->scp_at_check = 0;
 
        if (array->paa_count == 0) {
@@ -1447,11 +1556,13 @@ static int ptlrpc_at_check_timed(struct ptlrpc_service_part *svcpt)
                RETURN(0);
        }
 
-       /* We're close to a timeout, and we don't know how much longer the
-          server will take. Send early replies to everyone expiring soon. */
+       /*
+        * We're close to a timeout, and we don't know how much longer the
+        * server will take. Send early replies to everyone expiring soon.
+        */
        INIT_LIST_HEAD(&work_list);
        deadline = -1;
-       index = (unsigned long)array->paa_deadline % array->paa_size;
+       div_u64_rem(array->paa_deadline, array->paa_size, &index);
        count = array->paa_count;
        while (count > 0) {
                count -= array->paa_reqs_count[index];
@@ -1466,14 +1577,18 @@ static int ptlrpc_at_check_timed(struct ptlrpc_service_part *svcpt)
                                break;
                        }
 
-                       ptlrpc_at_remove_timed(rq);
                        /**
                         * ptlrpc_server_drop_request() may drop
                         * refcount to 0 already. Let's check this and
                         * don't add entry to work_list
                         */
-                       if (likely(atomic_inc_not_zero(&rq->rq_refcount)))
+                       if (likely(atomic_inc_not_zero(&rq->rq_refcount))) {
+                               ptlrpc_at_remove_timed(rq);
                                list_add(&rq->rq_timed_list, &work_list);
+                       } else {
+                               ptlrpc_at_remove_timed(rq);
+                       }
+
                        counter++;
                }
 
@@ -1486,56 +1601,66 @@ static int ptlrpc_at_check_timed(struct ptlrpc_service_part *svcpt)
 
        spin_unlock(&svcpt->scp_at_lock);
 
-        CDEBUG(D_ADAPTTO, "timeout in %+ds, asking for %d secs on %d early "
-               "replies\n", first, at_extra, counter);
-        if (first < 0) {
-                /* We're already past request deadlines before we even get a
-                   chance to send early replies */
-                LCONSOLE_WARN("%s: This server is not able to keep up with "
-                             "request traffic (cpu-bound).\n",
+       CDEBUG(D_ADAPTTO,
+              "timeout in %+ds, asking for %d secs on %d early replies\n",
+              first, at_extra, counter);
+       if (first < 0) {
+               /*
+                * We're already past request deadlines before we even get a
+                * chance to send early replies
+                */
+               LCONSOLE_WARN("%s: This server is not able to keep up with request traffic (cpu-bound).\n",
                              svcpt->scp_service->srv_name);
-               CWARN("earlyQ=%d reqQ=%d recA=%d, svcEst=%d, "
-                     "delay="CFS_DURATION_T"(jiff)\n",
+               CWARN("earlyQ=%d reqQ=%d recA=%d, svcEst=%d, delay=%lld\n",
                      counter, svcpt->scp_nreqs_incoming,
                      svcpt->scp_nreqs_active,
                      at_get(&svcpt->scp_at_estimate), delay);
-        }
+       }
 
-        /* we took additional refcount so entries can't be deleted from list, no
-         * locking is needed */
+       /*
+        * we took additional refcount so entries can't be deleted from list, no
+        * locking is needed
+        */
        while (!list_empty(&work_list)) {
                rq = list_entry(work_list.next, struct ptlrpc_request,
-                                    rq_timed_list);
+                               rq_timed_list);
                list_del_init(&rq->rq_timed_list);
 
-                if (ptlrpc_at_send_early_reply(rq) == 0)
-                        ptlrpc_at_add_timed(rq);
+               if (ptlrpc_at_send_early_reply(rq) == 0)
+                       ptlrpc_at_add_timed(rq);
 
-                ptlrpc_server_drop_request(rq);
-        }
+               ptlrpc_server_drop_request(rq);
+       }
 
        RETURN(1); /* return "did_something" for liblustre */
 }
 
-/* Check if we are already handling earlier incarnation of this request.
- * Called under &req->rq_export->exp_rpc_lock locked */
-static int ptlrpc_server_check_resend_in_progress(struct ptlrpc_request *req)
+/*
+ * Check if we are already handling earlier incarnation of this request.
+ * Called under &req->rq_export->exp_rpc_lock locked
+ */
+static struct ptlrpc_request*
+ptlrpc_server_check_resend_in_progress(struct ptlrpc_request *req)
 {
-       struct ptlrpc_request   *tmp = NULL;
+       struct ptlrpc_request *tmp = NULL;
 
        if (!(lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT) ||
            (atomic_read(&req->rq_export->exp_rpc_count) == 0))
-               return 0;
+               return NULL;
 
-       /* bulk request are aborted upon reconnect, don't try to
-        * find a match */
+       /*
+        * bulk request are aborted upon reconnect, don't try to
+        * find a match
+        */
        if (req->rq_bulk_write || req->rq_bulk_read)
-               return 0;
+               return NULL;
 
-       /* This list should not be longer than max_requests in
+       /*
+        * This list should not be longer than max_requests in
         * flights on the client, so it is not all that long.
         * Also we only hit this codepath in case of a resent
-        * request which makes it even more rarely hit */
+        * request which makes it even more rarely hit
+        */
        list_for_each_entry(tmp, &req->rq_export->exp_reg_rpcs,
                                rq_exp_list) {
                /* Found duplicate one */
@@ -1548,76 +1673,98 @@ static int ptlrpc_server_check_resend_in_progress(struct ptlrpc_request *req)
                if (tmp->rq_xid == req->rq_xid)
                        goto found;
        }
-       return 0;
+       return NULL;
 
 found:
        DEBUG_REQ(D_HA, req, "Found duplicate req in processing");
        DEBUG_REQ(D_HA, tmp, "Request being processed");
-       return -EBUSY;
+       return tmp;
+}
+
+#ifdef HAVE_SERVER_SUPPORT
+static void ptlrpc_server_mark_obsolete(struct ptlrpc_request *req)
+{
+       req->rq_obsolete = 1;
+}
+
+static void
+ptlrpc_server_mark_in_progress_obsolete(struct ptlrpc_request *req)
+{
+       struct ptlrpc_request   *tmp = NULL;
+       __u16                   tag;
+
+       if (!tgt_is_increasing_xid_client(req->rq_export) ||
+           req->rq_export->exp_used_slots == NULL)
+               return;
+
+       tag = lustre_msg_get_tag(req->rq_reqmsg);
+       if (tag == 0)
+               return;
+
+       if (!test_bit(tag - 1, req->rq_export->exp_used_slots))
+               return;
+
+       /* This list should not be longer than max_requests in
+        * flights on the client, so it is not all that long.
+        * Also we only hit this codepath in case of a resent
+        * request which makes it even more rarely hit */
+       list_for_each_entry(tmp, &req->rq_export->exp_reg_rpcs, rq_exp_list) {
+               if (tag == lustre_msg_get_tag(tmp->rq_reqmsg) &&
+                   req->rq_xid > tmp->rq_xid)
+                       ptlrpc_server_mark_obsolete(tmp);
+
+       }
+       list_for_each_entry(tmp, &req->rq_export->exp_hp_rpcs, rq_exp_list) {
+               if (tag == lustre_msg_get_tag(tmp->rq_reqmsg) &&
+                   req->rq_xid > tmp->rq_xid)
+                       ptlrpc_server_mark_obsolete(tmp);
+       }
 }
+#endif
 
 /**
- * Put the request to the export list if the request may become
- * a high priority one.
+ * Check if a request should be assigned with a high priority.
+ *
+ * \retval     < 0: error occurred
+ *               0: normal RPC request
+ *              +1: high priority request
  */
 static int ptlrpc_server_hpreq_init(struct ptlrpc_service_part *svcpt,
                                    struct ptlrpc_request *req)
 {
-       struct list_head        *list;
-       int              rc, hp = 0;
+       int rc = 0;
 
        ENTRY;
-
-       if (svcpt->scp_service->srv_ops.so_hpreq_handler) {
+       if (svcpt->scp_service->srv_ops.so_hpreq_handler != NULL) {
                rc = svcpt->scp_service->srv_ops.so_hpreq_handler(req);
                if (rc < 0)
                        RETURN(rc);
+
                LASSERT(rc == 0);
        }
-       if (req->rq_export) {
-               if (req->rq_ops) {
-                       /* Perform request specific check. We should do this
-                        * check before the request is added into exp_hp_rpcs
-                        * list otherwise it may hit swab race at LU-1044. */
-                       if (req->rq_ops->hpreq_check) {
-                               rc = req->rq_ops->hpreq_check(req);
-                               /**
-                                * XXX: Out of all current
-                                * ptlrpc_hpreq_ops::hpreq_check(), only
-                                * ldlm_cancel_hpreq_check() can return an
-                                * error code; other functions assert in
-                                * similar places, which seems odd.
-                                * What also does not seem right is that
-                                * handlers for those RPCs do not assert
-                                * on the same checks, but rather handle the
-                                * error cases. e.g. see ost_rw_hpreq_check(),
-                                * and ost_brw_read(), ost_brw_write().
-                                */
-                               if (rc < 0)
-                                       RETURN(rc);
-                               LASSERT(rc == 0 || rc == 1);
-                               hp = rc;
-                       }
-                       list = &req->rq_export->exp_hp_rpcs;
-               } else {
-                       list = &req->rq_export->exp_reg_rpcs;
-               }
 
-               /* do search for duplicated xid and the adding to the list
-                * atomically */
-               spin_lock_bh(&req->rq_export->exp_rpc_lock);
-               rc = ptlrpc_server_check_resend_in_progress(req);
-               if (rc < 0) {
-                       spin_unlock_bh(&req->rq_export->exp_rpc_lock);
-                       RETURN(rc);
+       if (req->rq_export != NULL && req->rq_ops != NULL) {
+               /*
+                * Perform request specific check. We should do this
+                * check before the request is added into exp_hp_rpcs
+                * list otherwise it may hit swab race at LU-1044.
+                */
+               if (req->rq_ops->hpreq_check != NULL) {
+                       rc = req->rq_ops->hpreq_check(req);
+                       if (rc == -ESTALE) {
+                               req->rq_status = rc;
+                               ptlrpc_error(req);
+                       }
+                       /*
+                        * can only return error,
+                        * 0 for normal request,
+                        * or 1 for high priority request
+                        */
+                       LASSERT(rc <= 1);
                }
-               list_add(&req->rq_exp_list, list);
-               spin_unlock_bh(&req->rq_export->exp_rpc_lock);
        }
 
-       ptlrpc_nrs_req_initialize(svcpt, req, !!hp);
-
-       RETURN(hp);
+       RETURN(rc);
 }
 
 /** Remove the request from the export list. */
@@ -1625,14 +1772,14 @@ static void ptlrpc_server_hpreq_fini(struct ptlrpc_request *req)
 {
        ENTRY;
        if (req->rq_export) {
-               /* refresh lock timeout again so that client has more
-                * room to send lock cancel RPC. */
+               /*
+                * refresh lock timeout again so that client has more
+                * room to send lock cancel RPC.
+                */
                if (req->rq_ops && req->rq_ops->hpreq_fini)
                        req->rq_ops->hpreq_fini(req);
 
-               spin_lock_bh(&req->rq_export->exp_rpc_lock);
-               list_del_init(&req->rq_exp_list);
-               spin_unlock_bh(&req->rq_export->exp_rpc_lock);
+               ptlrpc_del_exp_list(req);
        }
        EXIT;
 }
@@ -1651,8 +1798,10 @@ int ptlrpc_hpreq_handler(struct ptlrpc_request *req)
 {
        int opc = lustre_msg_get_opc(req->rq_reqmsg);
 
-       /* Check for export to let only reconnects for not yet evicted
-        * export to become a HP rpc. */
+       /*
+        * Check for export to let only reconnects for not yet evicted
+        * export to become a HP rpc.
+        */
        if ((req->rq_export != NULL) &&
            (opc == OBD_PING || opc == MDS_CONNECT || opc == OST_CONNECT))
                req->rq_ops = &ptlrpc_hpreq_common;
@@ -1664,21 +1813,84 @@ EXPORT_SYMBOL(ptlrpc_hpreq_handler);
 static int ptlrpc_server_request_add(struct ptlrpc_service_part *svcpt,
                                     struct ptlrpc_request *req)
 {
-       int     rc;
+       int rc;
+       bool hp;
+       struct ptlrpc_request *orig;
+
        ENTRY;
 
        rc = ptlrpc_server_hpreq_init(svcpt, req);
        if (rc < 0)
                RETURN(rc);
 
-       /* the current thread is not the processing thread for this request
+       hp = rc > 0;
+       ptlrpc_nrs_req_initialize(svcpt, req, hp);
+
+       while (req->rq_export != NULL) {
+               struct obd_export *exp = req->rq_export;
+
+               /*
+                * do search for duplicated xid and the adding to the list
+                * atomically
+                */
+               spin_lock_bh(&exp->exp_rpc_lock);
+#ifdef HAVE_SERVER_SUPPORT
+               ptlrpc_server_mark_in_progress_obsolete(req);
+#endif
+               orig = ptlrpc_server_check_resend_in_progress(req);
+               if (orig && OBD_FAIL_PRECHECK(OBD_FAIL_PTLRPC_RESEND_RACE)) {
+                       spin_unlock_bh(&exp->exp_rpc_lock);
+
+                       OBD_RACE(OBD_FAIL_PTLRPC_RESEND_RACE);
+                       msleep(4 * MSEC_PER_SEC);
+                       continue;
+               }
+
+               if (orig && likely(atomic_inc_not_zero(&orig->rq_refcount))) {
+                       bool linked;
+
+                       spin_unlock_bh(&exp->exp_rpc_lock);
+
+                       /*
+                        * When the client resend request and the server has
+                        * the previous copy of it, we need to update deadlines,
+                        * to be sure that the client and the server have equal
+                        *  request deadlines.
+                        */
+
+                       spin_lock(&orig->rq_rqbd->rqbd_svcpt->scp_at_lock);
+                       linked = orig->rq_at_linked;
+                       if (likely(linked))
+                               ptlrpc_at_remove_timed(orig);
+                       spin_unlock(&orig->rq_rqbd->rqbd_svcpt->scp_at_lock);
+                       orig->rq_deadline = req->rq_deadline;
+                       if (likely(linked))
+                               ptlrpc_at_add_timed(orig);
+                       ptlrpc_server_drop_request(orig);
+                       ptlrpc_nrs_req_finalize(req);
+
+                       /* don't mark slot unused for resend in progress */
+                       req->rq_obsolete = 1;
+
+                       RETURN(-EBUSY);
+               }
+
+               ptlrpc_add_exp_list_nolock(req, exp, hp || req->rq_ops != NULL);
+
+               spin_unlock_bh(&exp->exp_rpc_lock);
+               break;
+       }
+
+       /*
+        * the current thread is not the processing thread for this request
         * since that, but request is in exp_hp_list and can be find there.
-        * Remove all relations between request and old thread. */
+        * Remove all relations between request and old thread.
+        */
        req->rq_svc_thread->t_env->le_ses = NULL;
        req->rq_svc_thread = NULL;
        req->rq_session.lc_thread = NULL;
 
-       ptlrpc_nrs_req_add(svcpt, req, !!rc);
+       ptlrpc_nrs_req_add(svcpt, req, hp);
 
        RETURN(0);
 }
@@ -1740,6 +1952,7 @@ static bool ptlrpc_server_allow_normal(struct ptlrpc_service_part *svcpt,
                                       bool force)
 {
        int running = svcpt->scp_nthrs_running;
+
        if (unlikely(svcpt->scp_service->srv_req_portal == MDS_REQUEST_PORTAL &&
                     CFS_FAIL_PRECHECK(OBD_FAIL_PTLRPC_CANCEL_RESEND))) {
                /* leave just 1 thread for normal RPCs */
@@ -1778,8 +1991,9 @@ static bool ptlrpc_server_normal_pending(struct ptlrpc_service_part *svcpt,
  * \see ptlrpc_server_allow_normal
  * \see ptlrpc_server_allow high
  */
-static inline bool
-ptlrpc_server_request_pending(struct ptlrpc_service_part *svcpt, bool force)
+static inline
+bool ptlrpc_server_request_pending(struct ptlrpc_service_part *svcpt,
+                                  bool force)
 {
        return ptlrpc_server_high_pending(svcpt, force) ||
               ptlrpc_server_normal_pending(svcpt, force);
@@ -1794,6 +2008,7 @@ static struct ptlrpc_request *
 ptlrpc_server_request_get(struct ptlrpc_service_part *svcpt, bool force)
 {
        struct ptlrpc_request *req = NULL;
+
        ENTRY;
 
        spin_lock(&svcpt->scp_req_lock);
@@ -1836,14 +2051,14 @@ got_request:
  * All incoming requests pass through here before getting into
  * ptlrpc_server_handle_req later on.
  */
-static int
-ptlrpc_server_handle_req_in(struct ptlrpc_service_part *svcpt,
-                           struct ptlrpc_thread *thread)
-{
-       struct ptlrpc_service   *svc = svcpt->scp_service;
-       struct ptlrpc_request   *req;
-       __u32                   deadline;
-       int                     rc;
+static int ptlrpc_server_handle_req_in(struct ptlrpc_service_part *svcpt,
+                                      struct ptlrpc_thread *thread)
+{
+       struct ptlrpc_service *svc = svcpt->scp_service;
+       struct ptlrpc_request *req;
+       __u32 deadline;
+       int rc;
+
        ENTRY;
 
        spin_lock(&svcpt->scp_lock);
@@ -1856,108 +2071,111 @@ ptlrpc_server_handle_req_in(struct ptlrpc_service_part *svcpt,
                             struct ptlrpc_request, rq_list);
        list_del_init(&req->rq_list);
        svcpt->scp_nreqs_incoming--;
-       /* Consider this still a "queued" request as far as stats are
-        * concerned */
+       /*
+        * Consider this still a "queued" request as far as stats are
+        * concerned
+        */
        spin_unlock(&svcpt->scp_lock);
 
-        /* go through security check/transform */
-        rc = sptlrpc_svc_unwrap_request(req);
-        switch (rc) {
-        case SECSVC_OK:
-                break;
-        case SECSVC_COMPLETE:
-                target_send_reply(req, 0, OBD_FAIL_MDS_ALL_REPLY_NET);
-                goto err_req;
-        case SECSVC_DROP:
-                goto err_req;
-        default:
-                LBUG();
-        }
-
-        /*
-         * for null-flavored rpc, msg has been unpacked by sptlrpc, although
-         * redo it wouldn't be harmful.
-         */
-        if (SPTLRPC_FLVR_POLICY(req->rq_flvr.sf_rpc) != SPTLRPC_POLICY_NULL) {
-                rc = ptlrpc_unpack_req_msg(req, req->rq_reqlen);
-                if (rc != 0) {
-                        CERROR("error unpacking request: ptl %d from %s "
-                               "x"LPU64"\n", svc->srv_req_portal,
-                               libcfs_id2str(req->rq_peer), req->rq_xid);
-                        goto err_req;
-                }
-        }
-
-        rc = lustre_unpack_req_ptlrpc_body(req, MSG_PTLRPC_BODY_OFF);
-        if (rc) {
-                CERROR ("error unpacking ptlrpc body: ptl %d from %s x"
-                        LPU64"\n", svc->srv_req_portal,
-                        libcfs_id2str(req->rq_peer), req->rq_xid);
-                goto err_req;
-        }
-
-        if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_DROP_REQ_OPC) &&
-            lustre_msg_get_opc(req->rq_reqmsg) == cfs_fail_val) {
-                CERROR("drop incoming rpc opc %u, x"LPU64"\n",
-                       cfs_fail_val, req->rq_xid);
-                goto err_req;
-        }
-
-        rc = -EINVAL;
-        if (lustre_msg_get_type(req->rq_reqmsg) != PTL_RPC_MSG_REQUEST) {
-                CERROR("wrong packet type received (type=%u) from %s\n",
-                       lustre_msg_get_type(req->rq_reqmsg),
-                       libcfs_id2str(req->rq_peer));
-                goto err_req;
-        }
-
-        switch(lustre_msg_get_opc(req->rq_reqmsg)) {
-        case MDS_WRITEPAGE:
-        case OST_WRITE:
-                req->rq_bulk_write = 1;
-                break;
-        case MDS_READPAGE:
-        case OST_READ:
-        case MGS_CONFIG_READ:
-                req->rq_bulk_read = 1;
-                break;
-        }
-
-        CDEBUG(D_RPCTRACE, "got req x"LPU64"\n", req->rq_xid);
-
-        req->rq_export = class_conn2export(
-                lustre_msg_get_handle(req->rq_reqmsg));
-        if (req->rq_export) {
-                rc = ptlrpc_check_req(req);
-                if (rc == 0) {
-                        rc = sptlrpc_target_export_check(req->rq_export, req);
-                        if (rc)
-                                DEBUG_REQ(D_ERROR, req, "DROPPING req with "
-                                          "illegal security flavor,");
-                }
-
-                if (rc)
-                        goto err_req;
-                ptlrpc_update_export_timer(req->rq_export, 0);
-        }
-
-        /* req_in handling should/must be fast */
-        if (cfs_time_current_sec() - req->rq_arrival_time.tv_sec > 5)
-                DEBUG_REQ(D_WARNING, req, "Slow req_in handling "CFS_DURATION_T"s",
-                          cfs_time_sub(cfs_time_current_sec(),
-                                       req->rq_arrival_time.tv_sec));
-
-        /* Set rpc server deadline and add it to the timed list */
-        deadline = (lustre_msghdr_get_flags(req->rq_reqmsg) &
-                    MSGHDR_AT_SUPPORT) ?
-                   /* The max time the client expects us to take */
-                   lustre_msg_get_timeout(req->rq_reqmsg) : obd_timeout;
-
-        req->rq_deadline = req->rq_arrival_time.tv_sec + deadline;
-        if (unlikely(deadline == 0)) {
-                DEBUG_REQ(D_ERROR, req, "Dropping request with 0 timeout");
-                goto err_req;
-        }
+       /* go through security check/transform */
+       rc = sptlrpc_svc_unwrap_request(req);
+       switch (rc) {
+       case SECSVC_OK:
+               break;
+       case SECSVC_COMPLETE:
+               target_send_reply(req, 0, OBD_FAIL_MDS_ALL_REPLY_NET);
+               goto err_req;
+       case SECSVC_DROP:
+               goto err_req;
+       default:
+               LBUG();
+       }
+
+       /*
+        * for null-flavored rpc, msg has been unpacked by sptlrpc, although
+        * redo it wouldn't be harmful.
+        */
+       if (SPTLRPC_FLVR_POLICY(req->rq_flvr.sf_rpc) != SPTLRPC_POLICY_NULL) {
+               rc = ptlrpc_unpack_req_msg(req, req->rq_reqlen);
+               if (rc != 0) {
+                       CERROR("error unpacking request: ptl %d from %s x%llu\n",
+                              svc->srv_req_portal, libcfs_id2str(req->rq_peer),
+                              req->rq_xid);
+                       goto err_req;
+               }
+       }
+
+       rc = lustre_unpack_req_ptlrpc_body(req, MSG_PTLRPC_BODY_OFF);
+       if (rc) {
+               CERROR("error unpacking ptlrpc body: ptl %d from %s x %llu\n",
+                      svc->srv_req_portal, libcfs_id2str(req->rq_peer),
+                      req->rq_xid);
+               goto err_req;
+       }
+
+       if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_DROP_REQ_OPC) &&
+           lustre_msg_get_opc(req->rq_reqmsg) == cfs_fail_val) {
+               CERROR("drop incoming rpc opc %u, x%llu\n",
+                      cfs_fail_val, req->rq_xid);
+               goto err_req;
+       }
+
+       rc = -EINVAL;
+       if (lustre_msg_get_type(req->rq_reqmsg) != PTL_RPC_MSG_REQUEST) {
+               CERROR("wrong packet type received (type=%u) from %s\n",
+                      lustre_msg_get_type(req->rq_reqmsg),
+                      libcfs_id2str(req->rq_peer));
+               goto err_req;
+       }
+
+       switch (lustre_msg_get_opc(req->rq_reqmsg)) {
+       case MDS_WRITEPAGE:
+       case OST_WRITE:
+       case OUT_UPDATE:
+               req->rq_bulk_write = 1;
+               break;
+       case MDS_READPAGE:
+       case OST_READ:
+       case MGS_CONFIG_READ:
+               req->rq_bulk_read = 1;
+               break;
+       }
+
+       CDEBUG(D_RPCTRACE, "got req x%llu\n", req->rq_xid);
+
+       req->rq_export = class_conn2export(
+               lustre_msg_get_handle(req->rq_reqmsg));
+       if (req->rq_export) {
+               rc = ptlrpc_check_req(req);
+               if (rc == 0) {
+                       rc = sptlrpc_target_export_check(req->rq_export, req);
+                       if (rc)
+                               DEBUG_REQ(D_ERROR, req,
+                                         "DROPPING req with illegal security flavor");
+               }
+
+               if (rc)
+                       goto err_req;
+               ptlrpc_update_export_timer(req->rq_export, 0);
+       }
+
+       /* req_in handling should/must be fast */
+       if (ktime_get_real_seconds() - req->rq_arrival_time.tv_sec > 5)
+               DEBUG_REQ(D_WARNING, req, "Slow req_in handling %llds",
+                         (s64)(ktime_get_real_seconds() -
+                               req->rq_arrival_time.tv_sec));
+
+       /* Set rpc server deadline and add it to the timed list */
+       deadline = (lustre_msghdr_get_flags(req->rq_reqmsg) &
+                   MSGHDR_AT_SUPPORT) ?
+                   /* The max time the client expects us to take */
+                   lustre_msg_get_timeout(req->rq_reqmsg) : obd_timeout;
+
+       req->rq_deadline = req->rq_arrival_time.tv_sec + deadline;
+       if (unlikely(deadline == 0)) {
+               DEBUG_REQ(D_ERROR, req, "Dropping request with 0 timeout");
+               goto err_req;
+       }
 
        /* Skip early reply */
        if (OBD_FAIL_PRECHECK(OBD_FAIL_MDS_RESEND))
@@ -1965,8 +2183,10 @@ ptlrpc_server_handle_req_in(struct ptlrpc_service_part *svcpt,
 
        req->rq_svc_thread = thread;
        if (thread != NULL) {
-               /* initialize request session, it is needed for request
-                * processing by target */
+               /*
+                * initialize request session, it is needed for request
+                * processing by target
+                */
                rc = lu_context_init(&req->rq_session, LCT_SERVER_SESSION |
                                                       LCT_NOREF);
                if (rc) {
@@ -1999,16 +2219,17 @@ err_req:
  * Main incoming request handling logic.
  * Calls handler function from service to do actual processing.
  */
-static int
-ptlrpc_server_handle_request(struct ptlrpc_service_part *svcpt,
-                            struct ptlrpc_thread *thread)
-{
-       struct ptlrpc_service   *svc = svcpt->scp_service;
-       struct ptlrpc_request   *request;
-       struct timeval           work_start;
-       struct timeval           work_end;
-       long                     timediff;
-       int                      fail_opc = 0;
+static int ptlrpc_server_handle_request(struct ptlrpc_service_part *svcpt,
+                                       struct ptlrpc_thread *thread)
+{
+       struct ptlrpc_service *svc = svcpt->scp_service;
+       struct ptlrpc_request *request;
+       ktime_t work_start;
+       ktime_t work_end;
+       ktime_t arrived;
+       s64 timediff_usecs;
+       s64 arrived_usecs;
+       int fail_opc = 0;
 
        ENTRY;
 
@@ -2016,67 +2237,73 @@ ptlrpc_server_handle_request(struct ptlrpc_service_part *svcpt,
        if (request == NULL)
                RETURN(0);
 
-        if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT))
-                fail_opc = OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT;
-        else if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT))
-                fail_opc = OBD_FAIL_PTLRPC_HPREQ_TIMEOUT;
+       if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT))
+               fail_opc = OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT;
+       else if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT))
+               fail_opc = OBD_FAIL_PTLRPC_HPREQ_TIMEOUT;
 
-        if (unlikely(fail_opc)) {
+       if (unlikely(fail_opc)) {
                if (request->rq_export && request->rq_ops)
                        OBD_FAIL_TIMEOUT(fail_opc, 4);
        }
 
-        ptlrpc_rqphase_move(request, RQ_PHASE_INTERPRET);
+       ptlrpc_rqphase_move(request, RQ_PHASE_INTERPRET);
 
-       if(OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_DUMP_LOG))
+       if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_DUMP_LOG))
                libcfs_debug_dumplog();
 
-       do_gettimeofday(&work_start);
-       timediff = cfs_timeval_sub(&work_start, &request->rq_arrival_time,NULL);
+       work_start = ktime_get_real();
+       arrived = timespec64_to_ktime(request->rq_arrival_time);
+       timediff_usecs = ktime_us_delta(work_start, arrived);
        if (likely(svc->srv_stats != NULL)) {
-                lprocfs_counter_add(svc->srv_stats, PTLRPC_REQWAIT_CNTR,
-                                    timediff);
-                lprocfs_counter_add(svc->srv_stats, PTLRPC_REQQDEPTH_CNTR,
+               lprocfs_counter_add(svc->srv_stats, PTLRPC_REQWAIT_CNTR,
+                                   timediff_usecs);
+               lprocfs_counter_add(svc->srv_stats, PTLRPC_REQQDEPTH_CNTR,
                                    svcpt->scp_nreqs_incoming);
                lprocfs_counter_add(svc->srv_stats, PTLRPC_REQACTIVE_CNTR,
                                    svcpt->scp_nreqs_active);
                lprocfs_counter_add(svc->srv_stats, PTLRPC_TIMEOUT,
                                    at_get(&svcpt->scp_at_estimate));
-        }
+       }
 
        if (likely(request->rq_export)) {
                if (unlikely(ptlrpc_check_req(request)))
                        goto put_conn;
-                ptlrpc_update_export_timer(request->rq_export, timediff >> 19);
-        }
-
-        /* Discard requests queued for longer than the deadline.
-           The deadline is increased if we send an early reply. */
-        if (cfs_time_current_sec() > request->rq_deadline) {
-                DEBUG_REQ(D_ERROR, request, "Dropping timed-out request from %s"
-                          ": deadline "CFS_DURATION_T":"CFS_DURATION_T"s ago\n",
-                          libcfs_id2str(request->rq_peer),
-                          cfs_time_sub(request->rq_deadline,
-                          request->rq_arrival_time.tv_sec),
-                          cfs_time_sub(cfs_time_current_sec(),
-                          request->rq_deadline));
-                goto put_conn;
-        }
-
-       CDEBUG(D_RPCTRACE, "Handling RPC pname:cluuid+ref:pid:xid:nid:opc "
-              "%s:%s+%d:%d:x"LPU64":%s:%d\n", current_comm(),
+               ptlrpc_update_export_timer(request->rq_export,
+                                          div_u64(timediff_usecs,
+                                                  USEC_PER_SEC / 2));
+       }
+
+       /*
+        * Discard requests queued for longer than the deadline.
+        * The deadline is increased if we send an early reply.
+        */
+       if (ktime_get_real_seconds() > request->rq_deadline) {
+               DEBUG_REQ(D_ERROR, request,
+                         "Dropping timed-out request from %s: deadline %lld/%llds ago",
+                         libcfs_id2str(request->rq_peer),
+                         request->rq_deadline -
+                         request->rq_arrival_time.tv_sec,
+                         ktime_get_real_seconds() - request->rq_deadline);
+               goto put_conn;
+       }
+
+       CDEBUG(D_RPCTRACE,
+              "Handling RPC req@%p pname:cluuid+ref:pid:xid:nid:opc:job %s:%s+%d:%d:x%llu:%s:%d:%s\n",
+              request, current_comm(),
               (request->rq_export ?
                (char *)request->rq_export->exp_client_uuid.uuid : "0"),
               (request->rq_export ?
-               atomic_read(&request->rq_export->exp_refcount) : -99),
+               refcount_read(&request->rq_export->exp_handle.h_ref) : -99),
               lustre_msg_get_status(request->rq_reqmsg), request->rq_xid,
               libcfs_id2str(request->rq_peer),
-              lustre_msg_get_opc(request->rq_reqmsg));
+              lustre_msg_get_opc(request->rq_reqmsg),
+              lustre_msg_get_jobid(request->rq_reqmsg) ?: "");
 
-        if (lustre_msg_get_opc(request->rq_reqmsg) != OBD_PING)
-                CFS_FAIL_TIMEOUT_MS(OBD_FAIL_PTLRPC_PAUSE_REQ, cfs_fail_val);
+       if (lustre_msg_get_opc(request->rq_reqmsg) != OBD_PING)
+               CFS_FAIL_TIMEOUT_MS(OBD_FAIL_PTLRPC_PAUSE_REQ, cfs_fail_val);
 
-       CDEBUG(D_NET, "got req "LPU64"\n", request->rq_xid);
+       CDEBUG(D_NET, "got req %llu\n", request->rq_xid);
 
        /* re-assign request and sesson thread to the current one */
        request->rq_svc_thread = thread;
@@ -2090,56 +2317,54 @@ ptlrpc_server_handle_request(struct ptlrpc_service_part *svcpt,
        ptlrpc_rqphase_move(request, RQ_PHASE_COMPLETE);
 
 put_conn:
-       if (unlikely(cfs_time_current_sec() > request->rq_deadline)) {
-                    DEBUG_REQ(D_WARNING, request, "Request took longer "
-                              "than estimated ("CFS_DURATION_T":"CFS_DURATION_T"s);"
-                              " client may timeout.",
-                              cfs_time_sub(request->rq_deadline,
-                                           request->rq_arrival_time.tv_sec),
-                              cfs_time_sub(cfs_time_current_sec(),
-                                           request->rq_deadline));
-       }
-
-       do_gettimeofday(&work_end);
-       timediff = cfs_timeval_sub(&work_end, &work_start, NULL);
-       CDEBUG(D_RPCTRACE, "Handled RPC pname:cluuid+ref:pid:xid:nid:opc "
-              "%s:%s+%d:%d:x"LPU64":%s:%d Request procesed in "
-              "%ldus (%ldus total) trans "LPU64" rc %d/%d\n",
-               current_comm(),
-               (request->rq_export ?
-                (char *)request->rq_export->exp_client_uuid.uuid : "0"),
-                (request->rq_export ?
-                atomic_read(&request->rq_export->exp_refcount) : -99),
-                lustre_msg_get_status(request->rq_reqmsg),
-                request->rq_xid,
-                libcfs_id2str(request->rq_peer),
-                lustre_msg_get_opc(request->rq_reqmsg),
-                timediff,
-                cfs_timeval_sub(&work_end, &request->rq_arrival_time, NULL),
-                (request->rq_repmsg ?
-                 lustre_msg_get_transno(request->rq_repmsg) :
-                 request->rq_transno),
-                request->rq_status,
-                (request->rq_repmsg ?
-                 lustre_msg_get_status(request->rq_repmsg) : -999));
-        if (likely(svc->srv_stats != NULL && request->rq_reqmsg != NULL)) {
-                __u32 op = lustre_msg_get_opc(request->rq_reqmsg);
-                int opc = opcode_offset(op);
-                if (opc > 0 && !(op == LDLM_ENQUEUE || op == MDS_REINT)) {
-                        LASSERT(opc < LUSTRE_MAX_OPCODES);
-                        lprocfs_counter_add(svc->srv_stats,
-                                            opc + EXTRA_MAX_OPCODES,
-                                            timediff);
-                }
-        }
-        if (unlikely(request->rq_early_count)) {
-                DEBUG_REQ(D_ADAPTTO, request,
-                          "sent %d early replies before finishing in "
-                          CFS_DURATION_T"s",
-                          request->rq_early_count,
-                          cfs_time_sub(work_end.tv_sec,
-                          request->rq_arrival_time.tv_sec));
-        }
+       if (unlikely(ktime_get_real_seconds() > request->rq_deadline)) {
+               DEBUG_REQ(D_WARNING, request,
+                         "Request took longer than estimated (%lld/%llds); client may timeout",
+                         request->rq_deadline -
+                         request->rq_arrival_time.tv_sec,
+                         ktime_get_real_seconds() - request->rq_deadline);
+       }
+
+       work_end = ktime_get_real();
+       timediff_usecs = ktime_us_delta(work_end, work_start);
+       arrived_usecs = ktime_us_delta(work_end, arrived);
+       CDEBUG(D_RPCTRACE,
+              "Handled RPC req@%p pname:cluuid+ref:pid:xid:nid:opc:job %s:%s+%d:%d:x%llu:%s:%d:%s Request processed in %lldus (%lldus total) trans %llu rc %d/%d\n",
+              request, current_comm(),
+              (request->rq_export ?
+              (char *)request->rq_export->exp_client_uuid.uuid : "0"),
+              (request->rq_export ?
+               refcount_read(&request->rq_export->exp_handle.h_ref) : -99),
+              lustre_msg_get_status(request->rq_reqmsg),
+              request->rq_xid,
+              libcfs_id2str(request->rq_peer),
+              lustre_msg_get_opc(request->rq_reqmsg),
+              lustre_msg_get_jobid(request->rq_reqmsg) ?: "",
+              timediff_usecs,
+              arrived_usecs,
+              (request->rq_repmsg ?
+              lustre_msg_get_transno(request->rq_repmsg) :
+              request->rq_transno),
+              request->rq_status,
+              (request->rq_repmsg ?
+              lustre_msg_get_status(request->rq_repmsg) : -999));
+       if (likely(svc->srv_stats != NULL && request->rq_reqmsg != NULL)) {
+               __u32 op = lustre_msg_get_opc(request->rq_reqmsg);
+               int opc = opcode_offset(op);
+
+               if (opc > 0 && !(op == LDLM_ENQUEUE || op == MDS_REINT)) {
+                       LASSERT(opc < LUSTRE_MAX_OPCODES);
+                       lprocfs_counter_add(svc->srv_stats,
+                                           opc + EXTRA_MAX_OPCODES,
+                                           timediff_usecs);
+               }
+       }
+       if (unlikely(request->rq_early_count)) {
+               DEBUG_REQ(D_ADAPTTO, request,
+                         "sent %d early replies before finishing in %llds",
+                         request->rq_early_count,
+                         div_u64(arrived_usecs, USEC_PER_SEC));
+       }
 
        ptlrpc_server_finish_active_request(svcpt, request);
 
@@ -2149,15 +2374,15 @@ put_conn:
 /**
  * An internal function to process a single reply state object.
  */
-static int
-ptlrpc_handle_rs(struct ptlrpc_reply_state *rs)
+static int ptlrpc_handle_rs(struct ptlrpc_reply_state *rs)
 {
        struct ptlrpc_service_part *svcpt = rs->rs_svcpt;
-       struct ptlrpc_service     *svc = svcpt->scp_service;
-        struct obd_export         *exp;
-        int                        nlocks;
-        int                        been_handled;
-        ENTRY;
+       struct ptlrpc_service *svc = svcpt->scp_service;
+       struct obd_export *exp;
+       int nlocks;
+       int been_handled;
+
+       ENTRY;
 
        exp = rs->rs_export;
 
@@ -2165,58 +2390,110 @@ ptlrpc_handle_rs(struct ptlrpc_reply_state *rs)
        LASSERT(rs->rs_scheduled);
        LASSERT(list_empty(&rs->rs_list));
 
-       spin_lock(&exp->exp_lock);
-       /* Noop if removed already */
-       list_del_init(&rs->rs_exp_list);
-       spin_unlock(&exp->exp_lock);
-
-        /* The disk commit callback holds exp_uncommitted_replies_lock while it
-         * iterates over newly committed replies, removing them from
-         * exp_uncommitted_replies.  It then drops this lock and schedules the
-         * replies it found for handling here.
-         *
-         * We can avoid contention for exp_uncommitted_replies_lock between the
-         * HRT threads and further commit callbacks by checking rs_committed
-         * which is set in the commit callback while it holds both
-         * rs_lock and exp_uncommitted_reples.
-         *
-         * If we see rs_committed clear, the commit callback _may_ not have
-         * handled this reply yet and we race with it to grab
-         * exp_uncommitted_replies_lock before removing the reply from
-         * exp_uncommitted_replies.  Note that if we lose the race and the
-         * reply has already been removed, list_del_init() is a noop.
-         *
-         * If we see rs_committed set, we know the commit callback is handling,
-         * or has handled this reply since store reordering might allow us to
-         * see rs_committed set out of sequence.  But since this is done
-         * holding rs_lock, we can be sure it has all completed once we hold
-         * rs_lock, which we do right next.
-         */
+       /*
+        * The disk commit callback holds exp_uncommitted_replies_lock while it
+        * iterates over newly committed replies, removing them from
+        * exp_uncommitted_replies.  It then drops this lock and schedules the
+        * replies it found for handling here.
+        *
+        * We can avoid contention for exp_uncommitted_replies_lock between the
+        * HRT threads and further commit callbacks by checking rs_committed
+        * which is set in the commit callback while it holds both
+        * rs_lock and exp_uncommitted_reples.
+        *
+        * If we see rs_committed clear, the commit callback _may_ not have
+        * handled this reply yet and we race with it to grab
+        * exp_uncommitted_replies_lock before removing the reply from
+        * exp_uncommitted_replies.  Note that if we lose the race and the
+        * reply has already been removed, list_del_init() is a noop.
+        *
+        * If we see rs_committed set, we know the commit callback is handling,
+        * or has handled this reply since store reordering might allow us to
+        * see rs_committed set out of sequence.  But since this is done
+        * holding rs_lock, we can be sure it has all completed once we hold
+        * rs_lock, which we do right next.
+        */
        if (!rs->rs_committed) {
+               /*
+                * if rs was commited, no need to convert locks, don't check
+                * rs_committed here because rs may never be added into
+                * exp_uncommitted_replies and this flag never be set, see
+                * target_send_reply()
+                */
+               if (rs->rs_convert_lock &&
+                   rs->rs_transno > exp->exp_last_committed) {
+                       struct ldlm_lock *lock;
+                       struct ldlm_lock *ack_locks[RS_MAX_LOCKS] = { NULL };
+
+                       spin_lock(&rs->rs_lock);
+                       if (rs->rs_convert_lock &&
+                           rs->rs_transno > exp->exp_last_committed) {
+                               nlocks = rs->rs_nlocks;
+                               while (nlocks-- > 0) {
+                                       /*
+                                        * NB don't assume rs is always handled
+                                        * by the same service thread (see
+                                        * ptlrpc_hr_select, so REP-ACK hr may
+                                        * race with trans commit, while the
+                                        * latter will release locks, get locks
+                                        * here early to convert to COS mode
+                                        * safely.
+                                        */
+                                       lock = ldlm_handle2lock(
+                                                       &rs->rs_locks[nlocks]);
+                                       LASSERT(lock);
+                                       ack_locks[nlocks] = lock;
+                                       rs->rs_modes[nlocks] = LCK_COS;
+                               }
+                               nlocks = rs->rs_nlocks;
+                               rs->rs_convert_lock = 0;
+                               /*
+                                * clear rs_scheduled so that commit callback
+                                * can schedule again
+                                */
+                               rs->rs_scheduled = 0;
+                               spin_unlock(&rs->rs_lock);
+
+                               while (nlocks-- > 0) {
+                                       lock = ack_locks[nlocks];
+                                       ldlm_lock_mode_downgrade(lock, LCK_COS);
+                                       LDLM_LOCK_PUT(lock);
+                               }
+                               RETURN(0);
+                       }
+                       spin_unlock(&rs->rs_lock);
+               }
+
                spin_lock(&exp->exp_uncommitted_replies_lock);
                list_del_init(&rs->rs_obd_list);
                spin_unlock(&exp->exp_uncommitted_replies_lock);
        }
 
+       spin_lock(&exp->exp_lock);
+       /* Noop if removed already */
+       list_del_init(&rs->rs_exp_list);
+       spin_unlock(&exp->exp_lock);
+
        spin_lock(&rs->rs_lock);
 
-        been_handled = rs->rs_handled;
-        rs->rs_handled = 1;
+       been_handled = rs->rs_handled;
+       rs->rs_handled = 1;
 
-        nlocks = rs->rs_nlocks;                 /* atomic "steal", but */
-        rs->rs_nlocks = 0;                      /* locks still on rs_locks! */
+       nlocks = rs->rs_nlocks; /* atomic "steal", but */
+       rs->rs_nlocks = 0; /* locks still on rs_locks! */
 
-        if (nlocks == 0 && !been_handled) {
-                /* If we see this, we should already have seen the warning
-                 * in mds_steal_ack_locks()  */
-               CDEBUG(D_HA, "All locks stolen from rs %p x"LPD64".t"LPD64
-                      " o%d NID %s\n",
-                      rs,
-                      rs->rs_xid, rs->rs_transno, rs->rs_opc,
+       if (nlocks == 0 && !been_handled) {
+               /*
+                * If we see this, we should already have seen the warning
+                * in mds_steal_ack_locks()
+                */
+               CDEBUG(D_HA,
+                      "All locks stolen from rs %p x%lld.t%lld o%d NID %s\n",
+                      rs, rs->rs_xid, rs->rs_transno, rs->rs_opc,
                       libcfs_nid2str(exp->exp_connection->c_peer.nid));
-        }
+       }
 
-        if ((!been_handled && rs->rs_on_net) || nlocks > 0) {
+       if ((!been_handled && rs->rs_on_net) || nlocks > 0) {
                spin_unlock(&rs->rs_lock);
 
                if (!been_handled && rs->rs_on_net) {
@@ -2232,12 +2509,13 @@ ptlrpc_handle_rs(struct ptlrpc_reply_state *rs)
        }
 
        rs->rs_scheduled = 0;
+       rs->rs_convert_lock = 0;
 
        if (!rs->rs_on_net) {
                /* Off the net */
                spin_unlock(&rs->rs_lock);
 
-               class_export_put (exp);
+               class_export_put(exp);
                rs->rs_export = NULL;
                ptlrpc_rs_decref(rs);
                if (atomic_dec_and_test(&svcpt->scp_nreps_difficult) &&
@@ -2252,21 +2530,22 @@ ptlrpc_handle_rs(struct ptlrpc_reply_state *rs)
 }
 
 
-static void
-ptlrpc_check_rqbd_pool(struct ptlrpc_service_part *svcpt)
+static void ptlrpc_check_rqbd_pool(struct ptlrpc_service_part *svcpt)
 {
        int avail = svcpt->scp_nrqbds_posted;
        int low_water = test_req_buffer_pressure ? 0 :
                        svcpt->scp_service->srv_nbuf_per_group / 2;
 
-        /* NB I'm not locking; just looking. */
+       /* NB I'm not locking; just looking. */
 
-        /* CAVEAT EMPTOR: We might be allocating buffers here because we've
-         * allowed the request history to grow out of control.  We could put a
-         * sanity check on that here and cull some history if we need the
-         * space. */
+       /*
+        * CAVEAT EMPTOR: We might be allocating buffers here because we've
+        * allowed the request history to grow out of control.  We could put a
+        * sanity check on that here and cull some history if we need the
+        * space.
+        */
 
-        if (avail <= low_water)
+       if (avail <= low_water)
                ptlrpc_grow_req_bufs(svcpt, 1);
 
        if (svcpt->scp_service->srv_stats) {
@@ -2275,8 +2554,7 @@ ptlrpc_check_rqbd_pool(struct ptlrpc_service_part *svcpt)
        }
 }
 
-static int
-ptlrpc_retry_rqbds(void *arg)
+static int ptlrpc_retry_rqbds(void *arg)
 {
        struct ptlrpc_service_part *svcpt = (struct ptlrpc_service_part *)arg;
 
@@ -2284,8 +2562,7 @@ ptlrpc_retry_rqbds(void *arg)
        return -ETIMEDOUT;
 }
 
-static inline int
-ptlrpc_threads_enough(struct ptlrpc_service_part *svcpt)
+static inline int ptlrpc_threads_enough(struct ptlrpc_service_part *svcpt)
 {
        return svcpt->scp_nreqs_active <
               svcpt->scp_nthrs_running - 1 -
@@ -2297,8 +2574,7 @@ ptlrpc_threads_enough(struct ptlrpc_service_part *svcpt)
  * user can call it w/o any lock but need to hold
  * ptlrpc_service_part::scp_lock to get reliable result
  */
-static inline int
-ptlrpc_threads_increasable(struct ptlrpc_service_part *svcpt)
+static inline int ptlrpc_threads_increasable(struct ptlrpc_service_part *svcpt)
 {
        return svcpt->scp_nthrs_running +
               svcpt->scp_nthrs_starting <
@@ -2308,22 +2584,47 @@ ptlrpc_threads_increasable(struct ptlrpc_service_part *svcpt)
 /**
  * too many requests and allowed to create more threads
  */
-static inline int
-ptlrpc_threads_need_create(struct ptlrpc_service_part *svcpt)
+static inline int ptlrpc_threads_need_create(struct ptlrpc_service_part *svcpt)
 {
        return !ptlrpc_threads_enough(svcpt) &&
                ptlrpc_threads_increasable(svcpt);
 }
 
-static inline int
-ptlrpc_thread_stopping(struct ptlrpc_thread *thread)
+static inline int ptlrpc_thread_stopping(struct ptlrpc_thread *thread)
 {
        return thread_is_stopping(thread) ||
               thread->t_svcpt->scp_service->srv_is_stopping;
 }
 
-static inline int
-ptlrpc_rqbd_pending(struct ptlrpc_service_part *svcpt)
+/* stop the highest numbered thread if there are too many threads running */
+static inline bool ptlrpc_thread_should_stop(struct ptlrpc_thread *thread)
+{
+       struct ptlrpc_service_part *svcpt = thread->t_svcpt;
+
+       return thread->t_id >= svcpt->scp_service->srv_nthrs_cpt_limit &&
+               thread->t_id == svcpt->scp_thr_nextid - 1;
+}
+
+static void ptlrpc_stop_thread(struct ptlrpc_thread *thread)
+{
+       CDEBUG(D_INFO, "Stopping thread %s #%u\n",
+              thread->t_svcpt->scp_service->srv_thread_name, thread->t_id);
+       thread_add_flags(thread, SVC_STOPPING);
+}
+
+static inline void ptlrpc_thread_stop(struct ptlrpc_thread *thread)
+{
+       struct ptlrpc_service_part *svcpt = thread->t_svcpt;
+
+       spin_lock(&svcpt->scp_lock);
+       if (ptlrpc_thread_should_stop(thread)) {
+               ptlrpc_stop_thread(thread);
+               svcpt->scp_thr_nextid--;
+       }
+       spin_unlock(&svcpt->scp_lock);
+}
+
+static inline int ptlrpc_rqbd_pending(struct ptlrpc_service_part *svcpt)
 {
        return !list_empty(&svcpt->scp_rqbd_idle) &&
               svcpt->scp_rqbd_timeout == 0;
@@ -2335,6 +2636,60 @@ ptlrpc_at_check(struct ptlrpc_service_part *svcpt)
        return svcpt->scp_at_check;
 }
 
+/*
+ * If a thread runs too long or spends to much time on a single request,
+ * we want to know about it, so we set up a delayed work item as a watchdog.
+ * If it fires, we display a stack trace of the delayed thread,
+ * providing we aren't rate-limited
+ *
+ * Watchdog stack traces are limited to 3 per 'libcfs_watchdog_ratelimit'
+ * seconds
+ */
+static struct ratelimit_state watchdog_limit;
+
+static void ptlrpc_watchdog_fire(struct work_struct *w)
+{
+       struct ptlrpc_thread *thread = container_of(w, struct ptlrpc_thread,
+                                                   t_watchdog.work);
+       u64 ms_lapse = ktime_ms_delta(ktime_get(), thread->t_touched);
+       u32 ms_frac = do_div(ms_lapse, MSEC_PER_SEC);
+
+       /* ___ratelimit() returns true if the action is NOT ratelimited */
+       if (__ratelimit(&watchdog_limit)) {
+               /* below message is checked in sanity-quota.sh test_6,18 */
+               LCONSOLE_WARN("%s: service thread pid %u was inactive for %llu.%03u seconds. The thread might be hung, or it might only be slow and will resume later. Dumping the stack trace for debugging purposes:\n",
+                             thread->t_task->comm, thread->t_task->pid,
+                             ms_lapse, ms_frac);
+
+               libcfs_debug_dumpstack(thread->t_task);
+       } else {
+               /* below message is checked in sanity-quota.sh test_6,18 */
+               LCONSOLE_WARN("%s: service thread pid %u was inactive for %llu.%03u seconds. Watchdog stack traces are limited to 3 per %u seconds, skipping this one.\n",
+                             thread->t_task->comm, thread->t_task->pid,
+                             ms_lapse, ms_frac, libcfs_watchdog_ratelimit);
+       }
+}
+
+static void ptlrpc_watchdog_init(struct delayed_work *work, time_t time)
+{
+       INIT_DELAYED_WORK(work, ptlrpc_watchdog_fire);
+       schedule_delayed_work(work, cfs_time_seconds(time));
+}
+
+static void ptlrpc_watchdog_disable(struct delayed_work *work)
+{
+       cancel_delayed_work_sync(work);
+}
+
+static void ptlrpc_watchdog_touch(struct delayed_work *work, time_t time)
+{
+       struct ptlrpc_thread *thread = container_of(&work->work,
+                                                   struct ptlrpc_thread,
+                                                   t_watchdog.work);
+       thread->t_touched = ktime_get();
+       mod_delayed_work(system_wq, work, cfs_time_seconds(time));
+}
+
 /**
  * requests wait on preprocessing
  * user can call it w/o any lock but need to hold
@@ -2354,7 +2709,7 @@ ptlrpc_wait_event(struct ptlrpc_service_part *svcpt,
        struct l_wait_info lwi = LWI_TIMEOUT(svcpt->scp_rqbd_timeout,
                                             ptlrpc_retry_rqbds, svcpt);
 
-       lc_watchdog_disable(thread->t_watchdog);
+       ptlrpc_watchdog_disable(&thread->t_watchdog);
 
        cond_resched();
 
@@ -2368,8 +2723,8 @@ ptlrpc_wait_event(struct ptlrpc_service_part *svcpt,
        if (ptlrpc_thread_stopping(thread))
                return -EINTR;
 
-       lc_watchdog_touch(thread->t_watchdog,
-                         ptlrpc_server_get_timeout(svcpt));
+       ptlrpc_watchdog_touch(&thread->t_watchdog,
+                             ptlrpc_server_get_timeout(svcpt));
        return 0;
 }
 
@@ -2381,56 +2736,56 @@ ptlrpc_wait_event(struct ptlrpc_service_part *svcpt,
  */
 static int ptlrpc_main(void *arg)
 {
-       struct ptlrpc_thread            *thread = (struct ptlrpc_thread *)arg;
-       struct ptlrpc_service_part      *svcpt = thread->t_svcpt;
-       struct ptlrpc_service           *svc = svcpt->scp_service;
-       struct ptlrpc_reply_state       *rs;
+       struct ptlrpc_thread *thread = (struct ptlrpc_thread *)arg;
+       struct ptlrpc_service_part *svcpt = thread->t_svcpt;
+       struct ptlrpc_service *svc = svcpt->scp_service;
+       struct ptlrpc_reply_state *rs;
        struct group_info *ginfo = NULL;
        struct lu_env *env;
        int counter = 0, rc = 0;
+
        ENTRY;
 
+       thread->t_task = current;
        thread->t_pid = current_pid();
        unshare_fs_struct();
 
-       /* NB: we will call cfs_cpt_bind() for all threads, because we
-        * might want to run lustre server only on a subset of system CPUs,
-        * in that case ->scp_cpt is CFS_CPT_ANY */
-       rc = cfs_cpt_bind(svc->srv_cptable, svcpt->scp_cpt);
-       if (rc != 0) {
-               CWARN("%s: failed to bind %s on CPT %d\n",
-                     svc->srv_name, thread->t_name, svcpt->scp_cpt);
+       if (svc->srv_cpt_bind) {
+               rc = cfs_cpt_bind(svc->srv_cptable, svcpt->scp_cpt);
+               if (rc != 0) {
+                       CWARN("%s: failed to bind %s on CPT %d\n",
+                             svc->srv_name, thread->t_name, svcpt->scp_cpt);
+               }
        }
 
        ginfo = groups_alloc(0);
-       if (!ginfo) {
-               rc = -ENOMEM;
-               goto out;
-       }
+       if (!ginfo)
+               GOTO(out, rc = -ENOMEM);
 
        set_current_groups(ginfo);
        put_group_info(ginfo);
 
        if (svc->srv_ops.so_thr_init != NULL) {
                rc = svc->srv_ops.so_thr_init(thread);
-                if (rc)
-                        goto out;
-        }
+               if (rc)
+                       GOTO(out, rc);
+       }
 
-        OBD_ALLOC_PTR(env);
-        if (env == NULL) {
-                rc = -ENOMEM;
-                goto out_srv_fini;
-        }
+       OBD_ALLOC_PTR(env);
+       if (env == NULL)
+               GOTO(out_srv_fini, rc = -ENOMEM);
+       rc = lu_env_add(env);
+       if (rc)
+               GOTO(out_env, rc);
 
-        rc = lu_context_init(&env->le_ctx,
-                             svc->srv_ctx_tags|LCT_REMEMBER|LCT_NOREF);
-        if (rc)
-                goto out_srv_fini;
+       rc = lu_context_init(&env->le_ctx,
+                            svc->srv_ctx_tags|LCT_REMEMBER|LCT_NOREF);
+       if (rc)
+               GOTO(out_env_remove, rc);
 
-        thread->t_env = env;
-        env->le_ctx.lc_thread = thread;
-        env->le_ctx.lc_cookie = 0x6;
+       thread->t_env = env;
+       env->le_ctx.lc_thread = thread;
+       env->le_ctx.lc_cookie = 0x6;
 
        while (!list_empty(&svcpt->scp_rqbd_idle)) {
                rc = ptlrpc_server_post_idle_rqbds(svcpt);
@@ -2439,15 +2794,13 @@ static int ptlrpc_main(void *arg)
 
                CERROR("Failed to post rqbd for %s on CPT %d: %d\n",
                        svc->srv_name, svcpt->scp_cpt, rc);
-               goto out_srv_fini;
+               GOTO(out_ctx_fini, rc);
        }
 
-        /* Alloc reply state structure for this one */
-        OBD_ALLOC_LARGE(rs, svc->srv_max_reply_size);
-        if (!rs) {
-                rc = -ENOMEM;
-                goto out_srv_fini;
-        }
+       /* Alloc reply state structure for this one */
+       OBD_ALLOC_LARGE(rs, svc->srv_max_reply_size);
+       if (!rs)
+               GOTO(out_ctx_fini, rc = -ENOMEM);
 
        spin_lock(&svcpt->scp_lock);
 
@@ -2457,10 +2810,12 @@ static int ptlrpc_main(void *arg)
        LASSERT(svcpt->scp_nthrs_starting == 1);
        svcpt->scp_nthrs_starting--;
 
-       /* SVC_STOPPING may already be set here if someone else is trying
+       /*
+        * SVC_STOPPING may already be set here if someone else is trying
         * to stop the service while this new thread has been dynamically
         * forked. We still set SVC_RUNNING to let our creator know that
-        * we are now running, however we will exit as soon as possible */
+        * we are now running, however we will exit as soon as possible
+        */
        thread_add_flags(thread, SVC_RUNNING);
        svcpt->scp_nthrs_running++;
        spin_unlock(&svcpt->scp_lock);
@@ -2468,8 +2823,9 @@ static int ptlrpc_main(void *arg)
        /* wake up our creator in case he's still waiting. */
        wake_up(&thread->t_ctl_waitq);
 
-       thread->t_watchdog = lc_watchdog_add(ptlrpc_server_get_timeout(svcpt),
-                                            NULL, NULL);
+       thread->t_touched = ktime_get();
+       ptlrpc_watchdog_init(&thread->t_watchdog,
+                        ptlrpc_server_get_timeout(svcpt));
 
        spin_lock(&svcpt->scp_rep_lock);
        list_add(&rs->rs_list, &svcpt->scp_rep_idle);
@@ -2489,10 +2845,13 @@ static int ptlrpc_main(void *arg)
                if (ptlrpc_threads_need_create(svcpt)) {
                        /* Ignore return code - we tried... */
                        ptlrpc_start_thread(svcpt, 0);
-                }
+               }
 
                /* reset le_ses to initial state */
                env->le_ses = NULL;
+               /* Refill the context before execution to make sure
+                * all thread keys are allocated */
+               lu_env_refill(env);
                /* Process all incoming reqs before handling any */
                if (ptlrpc_server_request_incoming(svcpt)) {
                        lu_context_enter(&env->le_ctx);
@@ -2512,37 +2871,43 @@ static int ptlrpc_main(void *arg)
                        lu_context_enter(&env->le_ctx);
                        ptlrpc_server_handle_request(svcpt, thread);
                        lu_context_exit(&env->le_ctx);
-                }
+               }
 
                if (ptlrpc_rqbd_pending(svcpt) &&
                    ptlrpc_server_post_idle_rqbds(svcpt) < 0) {
-                       /* I just failed to repost request buffers.
+                       /*
+                        * I just failed to repost request buffers.
                         * Wait for a timeout (unless something else
-                        * happens) before I try again */
+                        * happens) before I try again
+                        */
                        svcpt->scp_rqbd_timeout = cfs_time_seconds(1) / 10;
                        CDEBUG(D_RPCTRACE, "Posted buffers: %d\n",
                               svcpt->scp_nrqbds_posted);
-                }
-        }
+               }
+               /*
+                * If the number of threads has been tuned downward and this
+                * thread should be stopped, then stop in reverse order so the
+                * the threads always have contiguous thread index values.
+                */
+               if (unlikely(ptlrpc_thread_should_stop(thread)))
+                       ptlrpc_thread_stop(thread);
+       }
 
-        lc_watchdog_delete(thread->t_watchdog);
-        thread->t_watchdog = NULL;
+       ptlrpc_watchdog_disable(&thread->t_watchdog);
 
+out_ctx_fini:
+       lu_context_fini(&env->le_ctx);
+out_env_remove:
+       lu_env_remove(env);
+out_env:
+       OBD_FREE_PTR(env);
 out_srv_fini:
-        /*
-         * deconstruct service specific state created by ptlrpc_start_thread()
-         */
+       /* deconstruct service thread state created by ptlrpc_start_thread() */
        if (svc->srv_ops.so_thr_done != NULL)
                svc->srv_ops.so_thr_done(thread);
-
-        if (env != NULL) {
-                lu_context_fini(&env->le_ctx);
-                OBD_FREE_PTR(env);
-        }
 out:
-        CDEBUG(D_RPCTRACE, "service thread [ %p : %u ] %d exiting: rc %d\n",
-               thread, thread->t_pid, thread->t_id, rc);
-
+       CDEBUG(D_RPCTRACE, "%s: service thread [%p:%u] %d exiting: rc = %d\n",
+              thread->t_name, thread, thread->t_pid, thread->t_id, rc);
        spin_lock(&svcpt->scp_lock);
        if (thread_test_and_clear_flags(thread, SVC_STARTING))
                svcpt->scp_nthrs_starting--;
@@ -2581,23 +2946,38 @@ static int hrt_dont_sleep(struct ptlrpc_hr_thread *hrt,
  */
 static int ptlrpc_hr_main(void *arg)
 {
-       struct ptlrpc_hr_thread         *hrt = (struct ptlrpc_hr_thread *)arg;
-       struct ptlrpc_hr_partition      *hrp = hrt->hrt_partition;
-       struct list_head                replies;
-       char                            threadname[20];
-       int                             rc;
+       struct ptlrpc_hr_thread *hrt = (struct ptlrpc_hr_thread *)arg;
+       struct ptlrpc_hr_partition *hrp = hrt->hrt_partition;
+       struct list_head replies;
+       struct lu_env *env;
+       int rc;
+
+       OBD_ALLOC_PTR(env);
+       if (env == NULL)
+               RETURN(-ENOMEM);
 
        INIT_LIST_HEAD(&replies);
-       snprintf(threadname, sizeof(threadname), "ptlrpc_hr%02d_%03d",
-                hrp->hrp_cpt, hrt->hrt_id);
        unshare_fs_struct();
 
        rc = cfs_cpt_bind(ptlrpc_hr.hr_cpt_table, hrp->hrp_cpt);
        if (rc != 0) {
+               char threadname[20];
+
+               snprintf(threadname, sizeof(threadname), "ptlrpc_hr%02d_%03d",
+                        hrp->hrp_cpt, hrt->hrt_id);
                CWARN("Failed to bind %s on CPT %d of CPT table %p: rc = %d\n",
                      threadname, hrp->hrp_cpt, ptlrpc_hr.hr_cpt_table, rc);
        }
 
+       rc = lu_context_init(&env->le_ctx, LCT_MD_THREAD | LCT_DT_THREAD |
+                            LCT_REMEMBER | LCT_NOREF);
+       if (rc)
+               GOTO(out_env, rc);
+
+       rc = lu_env_add(env);
+       if (rc)
+               GOTO(out_ctx_fini, rc);
+
        atomic_inc(&hrp->hrp_nstarted);
        wake_up(&ptlrpc_hr.hr_waitq);
 
@@ -2611,21 +2991,30 @@ static int ptlrpc_hr_main(void *arg)
                                        struct ptlrpc_reply_state,
                                        rs_list);
                        list_del_init(&rs->rs_list);
+                       /* refill keys if needed */
+                       lu_env_refill(env);
+                       lu_context_enter(&env->le_ctx);
                        ptlrpc_handle_rs(rs);
+                       lu_context_exit(&env->le_ctx);
                }
        }
 
        atomic_inc(&hrp->hrp_nstopped);
        wake_up(&ptlrpc_hr.hr_waitq);
 
+       lu_env_remove(env);
+out_ctx_fini:
+       lu_context_fini(&env->le_ctx);
+out_env:
+       OBD_FREE_PTR(env);
        return 0;
 }
 
 static void ptlrpc_stop_hr_threads(void)
 {
-       struct ptlrpc_hr_partition      *hrp;
-       int                             i;
-       int                             j;
+       struct ptlrpc_hr_partition *hrp;
+       int i;
+       int j;
 
        ptlrpc_hr.hr_stopping = 1;
 
@@ -2647,9 +3036,10 @@ static void ptlrpc_stop_hr_threads(void)
 
 static int ptlrpc_start_hr_threads(void)
 {
-       struct ptlrpc_hr_partition      *hrp;
-       int                             i;
-       int                             j;
+       struct ptlrpc_hr_partition *hrp;
+       int i;
+       int j;
+
        ENTRY;
 
        cfs_percpt_for_each(hrp, i, ptlrpc_hr.hr_partitions) {
@@ -2674,8 +3064,8 @@ static int ptlrpc_start_hr_threads(void)
                           atomic_read(&hrp->hrp_nstarted) == j);
 
                if (rc < 0) {
-                       CERROR("cannot start reply handler thread %d:%d: "
-                              "rc = %d\n", i, j, rc);
+                       CERROR("cannot start reply handler thread %d:%d: rc = %d\n",
+                              i, j, rc);
                        ptlrpc_stop_hr_threads();
                        RETURN(rc);
                }
@@ -2686,9 +3076,8 @@ static int ptlrpc_start_hr_threads(void)
 
 static void ptlrpc_svcpt_stop_threads(struct ptlrpc_service_part *svcpt)
 {
-       struct l_wait_info      lwi = { 0 };
-       struct ptlrpc_thread    *thread;
-       struct list_head        zombie;
+       struct ptlrpc_thread *thread;
+       struct list_head zombie;
 
        ENTRY;
 
@@ -2698,11 +3087,8 @@ static void ptlrpc_svcpt_stop_threads(struct ptlrpc_service_part *svcpt)
        INIT_LIST_HEAD(&zombie);
        spin_lock(&svcpt->scp_lock);
        /* let the thread know that we would like it to stop asap */
-       list_for_each_entry(thread, &svcpt->scp_threads, t_link) {
-               CDEBUG(D_INFO, "Stopping thread %s #%u\n",
-                      svcpt->scp_service->srv_thread_name, thread->t_id);
-               thread_add_flags(thread, SVC_STOPPING);
-       }
+       list_for_each_entry(thread, &svcpt->scp_threads, t_link)
+               ptlrpc_stop_thread(thread);
 
        wake_up_all(&svcpt->scp_waitq);
 
@@ -2710,16 +3096,15 @@ static void ptlrpc_svcpt_stop_threads(struct ptlrpc_service_part *svcpt)
                thread = list_entry(svcpt->scp_threads.next,
                                        struct ptlrpc_thread, t_link);
                if (thread_is_stopped(thread)) {
-                       list_del(&thread->t_link);
-                       list_add(&thread->t_link, &zombie);
+                       list_move(&thread->t_link, &zombie);
                        continue;
                }
                spin_unlock(&svcpt->scp_lock);
 
                CDEBUG(D_INFO, "waiting for stopping-thread %s #%u\n",
                       svcpt->scp_service->srv_thread_name, thread->t_id);
-               l_wait_event(thread->t_ctl_waitq,
-                            thread_is_stopped(thread), &lwi);
+               wait_event_idle(thread->t_ctl_waitq,
+                               thread_is_stopped(thread));
 
                spin_lock(&svcpt->scp_lock);
        }
@@ -2741,7 +3126,8 @@ static void ptlrpc_svcpt_stop_threads(struct ptlrpc_service_part *svcpt)
 void ptlrpc_stop_all_threads(struct ptlrpc_service *svc)
 {
        struct ptlrpc_service_part *svcpt;
-       int                        i;
+       int i;
+
        ENTRY;
 
        ptlrpc_service_for_each_part(svcpt, i, svc) {
@@ -2754,9 +3140,10 @@ void ptlrpc_stop_all_threads(struct ptlrpc_service *svc)
 
 int ptlrpc_start_threads(struct ptlrpc_service *svc)
 {
-       int     rc = 0;
-       int     i;
-       int     j;
+       int rc = 0;
+       int i;
+       int j;
+
        ENTRY;
 
        /* We require 2 threads min, see note in ptlrpc_server_handle_request */
@@ -2785,11 +3172,11 @@ int ptlrpc_start_threads(struct ptlrpc_service *svc)
 
 int ptlrpc_start_thread(struct ptlrpc_service_part *svcpt, int wait)
 {
-       struct l_wait_info      lwi = { 0 };
-       struct ptlrpc_thread    *thread;
-       struct ptlrpc_service   *svc;
-       struct task_struct      *task;
-       int                     rc;
+       struct ptlrpc_thread *thread;
+       struct ptlrpc_service *svc;
+       struct task_struct *task;
+       int rc;
+
        ENTRY;
 
        LASSERT(svcpt != NULL);
@@ -2822,8 +3209,10 @@ int ptlrpc_start_thread(struct ptlrpc_service_part *svcpt, int wait)
        }
 
        if (svcpt->scp_nthrs_starting != 0) {
-               /* serialize starting because some modules (obdfilter)
-                * might require unique and contiguous t_id */
+               /*
+                * serialize starting because some modules (obdfilter)
+                * might require unique and contiguous t_id
+                */
                LASSERT(svcpt->scp_nthrs_starting == 1);
                spin_unlock(&svcpt->scp_lock);
                OBD_FREE_PTR(thread);
@@ -2864,7 +3253,8 @@ int ptlrpc_start_thread(struct ptlrpc_service_part *svcpt, int wait)
                spin_lock(&svcpt->scp_lock);
                --svcpt->scp_nthrs_starting;
                if (thread_is_stopping(thread)) {
-                       /* this ptlrpc_thread is being hanled
+                       /*
+                        * this ptlrpc_thread is being hanled
                         * by ptlrpc_svcpt_stop_threads now
                         */
                        thread_add_flags(thread, SVC_STOPPED);
@@ -2875,27 +3265,28 @@ int ptlrpc_start_thread(struct ptlrpc_service_part *svcpt, int wait)
                        spin_unlock(&svcpt->scp_lock);
                        OBD_FREE_PTR(thread);
                }
-                RETURN(rc);
-        }
+               RETURN(rc);
+       }
 
        if (!wait)
                RETURN(0);
 
-        l_wait_event(thread->t_ctl_waitq,
-                     thread_is_running(thread) || thread_is_stopped(thread),
-                     &lwi);
+       wait_event_idle(thread->t_ctl_waitq,
+                       thread_is_running(thread) || thread_is_stopped(thread));
 
-        rc = thread_is_stopped(thread) ? thread->t_id : 0;
-        RETURN(rc);
+       rc = thread_is_stopped(thread) ? thread->t_id : 0;
+       RETURN(rc);
 }
 
 int ptlrpc_hr_init(void)
 {
-       struct ptlrpc_hr_partition      *hrp;
-       struct ptlrpc_hr_thread         *hrt;
-       int                             rc;
-       int                             i;
-       int                             j;
+       struct ptlrpc_hr_partition *hrp;
+       struct ptlrpc_hr_thread *hrt;
+       int rc;
+       int cpt;
+       int i;
+       int weight;
+
        ENTRY;
 
        memset(&ptlrpc_hr, 0, sizeof(ptlrpc_hr));
@@ -2906,27 +3297,35 @@ int ptlrpc_hr_init(void)
        if (ptlrpc_hr.hr_partitions == NULL)
                RETURN(-ENOMEM);
 
+       ratelimit_state_init(&watchdog_limit,
+                            cfs_time_seconds(libcfs_watchdog_ratelimit), 3);
+
        init_waitqueue_head(&ptlrpc_hr.hr_waitq);
 
-       cfs_percpt_for_each(hrp, i, ptlrpc_hr.hr_partitions) {
-               hrp->hrp_cpt = i;
+       preempt_disable();
+       weight = cpumask_weight(topology_sibling_cpumask(smp_processor_id()));
+       preempt_enable();
+
+       cfs_percpt_for_each(hrp, cpt, ptlrpc_hr.hr_partitions) {
+               hrp->hrp_cpt = cpt;
 
                atomic_set(&hrp->hrp_nstarted, 0);
                atomic_set(&hrp->hrp_nstopped, 0);
 
-               hrp->hrp_nthrs = cfs_cpt_weight(ptlrpc_hr.hr_cpt_table, i);
-               hrp->hrp_nthrs /= cfs_cpu_ht_nsiblings(0);
+               hrp->hrp_nthrs = cfs_cpt_weight(ptlrpc_hr.hr_cpt_table, cpt);
+               hrp->hrp_nthrs /= weight;
+               if (hrp->hrp_nthrs == 0)
+                       hrp->hrp_nthrs = 1;
 
-               LASSERT(hrp->hrp_nthrs > 0);
-               OBD_CPT_ALLOC(hrp->hrp_thrs, ptlrpc_hr.hr_cpt_table, i,
+               OBD_CPT_ALLOC(hrp->hrp_thrs, ptlrpc_hr.hr_cpt_table, cpt,
                              hrp->hrp_nthrs * sizeof(*hrt));
                if (hrp->hrp_thrs == NULL)
                        GOTO(out, rc = -ENOMEM);
 
-               for (j = 0; j < hrp->hrp_nthrs; j++) {
-                       hrt = &hrp->hrp_thrs[j];
+               for (i = 0; i < hrp->hrp_nthrs; i++) {
+                       hrt = &hrp->hrp_thrs[i];
 
-                       hrt->hrt_id = j;
+                       hrt->hrt_id = i;
                        hrt->hrt_partition = hrp;
                        init_waitqueue_head(&hrt->hrt_waitq);
                        spin_lock_init(&hrt->hrt_lock);
@@ -2943,15 +3342,15 @@ out:
 
 void ptlrpc_hr_fini(void)
 {
-       struct ptlrpc_hr_partition      *hrp;
-       int                             i;
+       struct ptlrpc_hr_partition *hrp;
+       int cpt;
 
        if (ptlrpc_hr.hr_partitions == NULL)
                return;
 
        ptlrpc_stop_hr_threads();
 
-       cfs_percpt_for_each(hrp, i, ptlrpc_hr.hr_partitions) {
+       cfs_percpt_for_each(hrp, cpt, ptlrpc_hr.hr_partitions) {
                if (hrp->hrp_thrs != NULL) {
                        OBD_FREE(hrp->hrp_thrs,
                                 hrp->hrp_nthrs * sizeof(hrp->hrp_thrs[0]));
@@ -2969,13 +3368,10 @@ void ptlrpc_hr_fini(void)
 static void ptlrpc_wait_replies(struct ptlrpc_service_part *svcpt)
 {
        while (1) {
-               int rc;
-               struct l_wait_info lwi = LWI_TIMEOUT(cfs_time_seconds(10),
-                                                    NULL, NULL);
-
-               rc = l_wait_event(svcpt->scp_waitq,
-                    atomic_read(&svcpt->scp_nreps_difficult) == 0, &lwi);
-               if (rc == 0)
+               if (wait_event_idle_timeout(
+                       svcpt->scp_waitq,
+                       atomic_read(&svcpt->scp_nreps_difficult) == 0,
+                       cfs_time_seconds(10)) > 0)
                        break;
                CWARN("Unexpectedly long timeout %s %p\n",
                      svcpt->scp_service->srv_name, svcpt->scp_service);
@@ -2985,27 +3381,28 @@ static void ptlrpc_wait_replies(struct ptlrpc_service_part *svcpt)
 static void
 ptlrpc_service_del_atimer(struct ptlrpc_service *svc)
 {
-       struct ptlrpc_service_part      *svcpt;
-       int                             i;
+       struct ptlrpc_service_part *svcpt;
+       int i;
 
        /* early disarm AT timer... */
        ptlrpc_service_for_each_part(svcpt, i, svc) {
                if (svcpt->scp_service != NULL)
-                       cfs_timer_disarm(&svcpt->scp_at_timer);
+                       del_timer(&svcpt->scp_at_timer);
        }
 }
 
 static void
 ptlrpc_service_unlink_rqbd(struct ptlrpc_service *svc)
 {
-       struct ptlrpc_service_part        *svcpt;
+       struct ptlrpc_service_part *svcpt;
        struct ptlrpc_request_buffer_desc *rqbd;
-       struct l_wait_info                lwi;
-       int                               rc;
-       int                               i;
+       int rc;
+       int i;
 
-       /* All history will be culled when the next request buffer is
-        * freed in ptlrpc_service_purge_all() */
+       /*
+        * All history will be culled when the next request buffer is
+        * freed in ptlrpc_service_purge_all()
+        */
        svc->srv_hist_nrqbds_cpt_max = 0;
 
        rc = LNetClearLazyPortal(svc->srv_req_portal);
@@ -3015,8 +3412,10 @@ ptlrpc_service_unlink_rqbd(struct ptlrpc_service *svc)
                if (svcpt->scp_service == NULL)
                        break;
 
-               /* Unlink all the request buffers.  This forces a 'final'
-                * event with its 'unlink' flag set for each posted rqbd */
+               /*
+                * Unlink all the request buffers.  This forces a 'final'
+                * event with its 'unlink' flag set for each posted rqbd
+                */
                list_for_each_entry(rqbd, &svcpt->scp_rqbd_posted,
                                        rqbd_list) {
                        rc = LNetMDUnlink(rqbd->rqbd_md_h);
@@ -3028,22 +3427,28 @@ ptlrpc_service_unlink_rqbd(struct ptlrpc_service *svc)
                if (svcpt->scp_service == NULL)
                        break;
 
-               /* Wait for the network to release any buffers
-                * it's currently filling */
+               /*
+                * Wait for the network to release any buffers
+                * it's currently filling
+                */
                spin_lock(&svcpt->scp_lock);
                while (svcpt->scp_nrqbds_posted != 0) {
+                       int seconds = LONG_UNLINK;
+
                        spin_unlock(&svcpt->scp_lock);
-                       /* Network access will complete in finite time but
+                       /*
+                        * Network access will complete in finite time but
                         * the HUGE timeout lets us CWARN for visibility
-                        * of sluggish NALs */
-                       lwi = LWI_TIMEOUT_INTERVAL(
-                                       cfs_time_seconds(LONG_UNLINK),
-                                       cfs_time_seconds(1), NULL, NULL);
-                       rc = l_wait_event(svcpt->scp_waitq,
-                                         svcpt->scp_nrqbds_posted == 0, &lwi);
-                       if (rc == -ETIMEDOUT) {
-                               CWARN("Service %s waiting for "
-                                     "request buffers\n",
+                        * of sluggish NALs
+                        */
+                       while (seconds > 0 &&
+                              wait_event_idle_timeout(
+                                      svcpt->scp_waitq,
+                                      svcpt->scp_nrqbds_posted == 0,
+                                      cfs_time_seconds(1)) == 0)
+                               seconds -= 1;
+                       if (seconds == 0) {
+                               CWARN("Service %s waiting for request buffers\n",
                                      svcpt->scp_service->srv_name);
                        }
                        spin_lock(&svcpt->scp_lock);
@@ -3055,11 +3460,11 @@ ptlrpc_service_unlink_rqbd(struct ptlrpc_service *svc)
 static void
 ptlrpc_service_purge_all(struct ptlrpc_service *svc)
 {
-       struct ptlrpc_service_part              *svcpt;
-       struct ptlrpc_request_buffer_desc       *rqbd;
-       struct ptlrpc_request                   *req;
-       struct ptlrpc_reply_state               *rs;
-       int                                     i;
+       struct ptlrpc_service_part *svcpt;
+       struct ptlrpc_request_buffer_desc *rqbd;
+       struct ptlrpc_request *req;
+       struct ptlrpc_reply_state *rs;
+       int i;
 
        ptlrpc_service_for_each_part(svcpt, i, svc) {
                if (svcpt->scp_service == NULL)
@@ -3075,9 +3480,11 @@ ptlrpc_service_purge_all(struct ptlrpc_service *svc)
                }
                spin_unlock(&svcpt->scp_rep_lock);
 
-               /* purge the request queue.  NB No new replies (rqbds
+               /*
+                * purge the request queue.  NB No new replies (rqbds
                 * all unlinked) and no service threads, so I'm the only
-                * thread noodling the request queue now */
+                * thread noodling the request queue now
+                */
                while (!list_empty(&svcpt->scp_req_incoming)) {
                        req = list_entry(svcpt->scp_req_incoming.next,
                                             struct ptlrpc_request, rq_list);
@@ -3095,12 +3502,16 @@ ptlrpc_service_purge_all(struct ptlrpc_service *svc)
                LASSERT(list_empty(&svcpt->scp_rqbd_posted));
                LASSERT(svcpt->scp_nreqs_incoming == 0);
                LASSERT(svcpt->scp_nreqs_active == 0);
-               /* history should have been culled by
-                * ptlrpc_server_finish_request */
+               /*
+                * history should have been culled by
+                * ptlrpc_server_finish_request
+                */
                LASSERT(svcpt->scp_hist_nrqbds == 0);
 
-               /* Now free all the request buffers since nothing
-                * references them any more... */
+               /*
+                * Now free all the request buffers since nothing
+                * references them any more...
+                */
 
                while (!list_empty(&svcpt->scp_rqbd_idle)) {
                        rqbd = list_entry(svcpt->scp_rqbd_idle.next,
@@ -3132,7 +3543,7 @@ ptlrpc_service_free(struct ptlrpc_service *svc)
                        break;
 
                /* In case somebody rearmed this in the meantime */
-               cfs_timer_disarm(&svcpt->scp_at_timer);
+               del_timer(&svcpt->scp_at_timer);
                array = &svcpt->scp_at_array;
 
                if (array->paa_reqs_array != NULL) {
@@ -3178,6 +3589,7 @@ int ptlrpc_unregister_service(struct ptlrpc_service *service)
        ptlrpc_service_nrs_cleanup(service);
 
        ptlrpc_lprocfs_unregister_service(service);
+       ptlrpc_sysfs_unregister_service(service);
 
        ptlrpc_service_free(service);
 
@@ -3190,14 +3602,15 @@ EXPORT_SYMBOL(ptlrpc_unregister_service);
  *
  * Right now, it just checks to make sure that requests aren't languishing
  * in the queue.  We'll use this health check to govern whether a node needs
- * to be shot, so it's intentionally non-aggressive. */
+ * to be shot, so it's intentionally non-aggressive.
+ */
 static int ptlrpc_svcpt_health_check(struct ptlrpc_service_part *svcpt)
 {
-       struct ptlrpc_request           *request = NULL;
-       struct timeval                  right_now;
-       long                            timediff;
+       struct ptlrpc_request *request = NULL;
+       struct timespec64 right_now;
+       struct timespec64 timediff;
 
-       do_gettimeofday(&right_now);
+       ktime_get_real_ts64(&right_now);
 
        spin_lock(&svcpt->scp_req_lock);
        /* How long has the next entry been waiting? */
@@ -3211,13 +3624,13 @@ static int ptlrpc_svcpt_health_check(struct ptlrpc_service_part *svcpt)
                return 0;
        }
 
-       timediff = cfs_timeval_sub(&right_now, &request->rq_arrival_time, NULL);
+       timediff = timespec64_sub(right_now, request->rq_arrival_time);
        spin_unlock(&svcpt->scp_req_lock);
 
-       if ((timediff / ONE_MILLION) >
+       if ((timediff.tv_sec) >
            (AT_OFF ? obd_timeout * 3 / 2 : at_max)) {
-               CERROR("%s: unhealthy - request has been waiting %lds\n",
-                      svcpt->scp_service->srv_name, timediff / ONE_MILLION);
+               CERROR("%s: unhealthy - request has been waiting %llds\n",
+                      svcpt->scp_service->srv_name, (s64)timediff.tv_sec);
                return -1;
        }