Whamcloud - gitweb
LU-56 ptlrpc: clean up ptlrpc svc initializing APIs
[fs/lustre-release.git] / lustre / ptlrpc / service.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2012, Whamcloud, Inc.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  */
36
37 #define DEBUG_SUBSYSTEM S_RPC
38 #ifndef __KERNEL__
39 #include <liblustre.h>
40 #endif
41 #include <obd_support.h>
42 #include <obd_class.h>
43 #include <lustre_net.h>
44 #include <lu_object.h>
45 #include <lnet/types.h>
46 #include "ptlrpc_internal.h"
47
48 /* The following are visible and mutable through /sys/module/ptlrpc */
49 int test_req_buffer_pressure = 0;
50 CFS_MODULE_PARM(test_req_buffer_pressure, "i", int, 0444,
51                 "set non-zero to put pressure on request buffer pools");
52 CFS_MODULE_PARM(at_min, "i", int, 0644,
53                 "Adaptive timeout minimum (sec)");
54 CFS_MODULE_PARM(at_max, "i", int, 0644,
55                 "Adaptive timeout maximum (sec)");
56 CFS_MODULE_PARM(at_history, "i", int, 0644,
57                 "Adaptive timeouts remember the slowest event that took place "
58                 "within this period (sec)");
59 CFS_MODULE_PARM(at_early_margin, "i", int, 0644,
60                 "How soon before an RPC deadline to send an early reply");
61 CFS_MODULE_PARM(at_extra, "i", int, 0644,
62                 "How much extra time to give with each early reply");
63
64
65 /* forward ref */
66 static int ptlrpc_server_post_idle_rqbds (struct ptlrpc_service *svc);
67 static void ptlrpc_hpreq_fini(struct ptlrpc_request *req);
68
69 static CFS_LIST_HEAD(ptlrpc_all_services);
70 cfs_spinlock_t ptlrpc_all_services_lock;
71
72 struct ptlrpc_request_buffer_desc *
73 ptlrpc_alloc_rqbd (struct ptlrpc_service *svc)
74 {
75         struct ptlrpc_request_buffer_desc *rqbd;
76
77         OBD_ALLOC_PTR(rqbd);
78         if (rqbd == NULL)
79                 return (NULL);
80
81         rqbd->rqbd_service = svc;
82         rqbd->rqbd_refcount = 0;
83         rqbd->rqbd_cbid.cbid_fn = request_in_callback;
84         rqbd->rqbd_cbid.cbid_arg = rqbd;
85         CFS_INIT_LIST_HEAD(&rqbd->rqbd_reqs);
86         OBD_ALLOC_LARGE(rqbd->rqbd_buffer, svc->srv_buf_size);
87
88         if (rqbd->rqbd_buffer == NULL) {
89                 OBD_FREE_PTR(rqbd);
90                 return (NULL);
91         }
92
93         cfs_spin_lock(&svc->srv_lock);
94         cfs_list_add(&rqbd->rqbd_list, &svc->srv_idle_rqbds);
95         svc->srv_nbufs++;
96         cfs_spin_unlock(&svc->srv_lock);
97
98         return (rqbd);
99 }
100
101 void
102 ptlrpc_free_rqbd (struct ptlrpc_request_buffer_desc *rqbd)
103 {
104         struct ptlrpc_service *svc = rqbd->rqbd_service;
105
106         LASSERT (rqbd->rqbd_refcount == 0);
107         LASSERT (cfs_list_empty(&rqbd->rqbd_reqs));
108
109         cfs_spin_lock(&svc->srv_lock);
110         cfs_list_del(&rqbd->rqbd_list);
111         svc->srv_nbufs--;
112         cfs_spin_unlock(&svc->srv_lock);
113
114         OBD_FREE_LARGE(rqbd->rqbd_buffer, svc->srv_buf_size);
115         OBD_FREE_PTR(rqbd);
116 }
117
118 int
119 ptlrpc_grow_req_bufs(struct ptlrpc_service *svc)
120 {
121         struct ptlrpc_request_buffer_desc *rqbd;
122         int                                rc = 0;
123         int                                i;
124
125         for (i = 0; i < svc->srv_nbuf_per_group; i++) {
126                 /* NB: another thread might be doing this as well, we need to
127                  * make sure that it wouldn't over-allocate, see LU-1212. */
128                 if (svc->srv_nrqbd_receiving >= svc->srv_nbuf_per_group)
129                         break;
130
131                 rqbd = ptlrpc_alloc_rqbd(svc);
132
133                 if (rqbd == NULL) {
134                         CERROR("%s: Can't allocate request buffer\n",
135                                svc->srv_name);
136                         rc = -ENOMEM;
137                         break;
138                 }
139
140                 if (ptlrpc_server_post_idle_rqbds(svc) < 0) {
141                         rc = -EAGAIN;
142                         break;
143                 }
144         }
145
146         CDEBUG(D_RPCTRACE,
147                "%s: allocate %d new %d-byte reqbufs (%d/%d left), rc = %d\n",
148                svc->srv_name, i, svc->srv_buf_size,
149                svc->srv_nrqbd_receiving, svc->srv_nbufs, rc);
150
151         return rc;
152 }
153
154 /**
155  * Part of Rep-Ack logic.
156  * Puts a lock and its mode into reply state assotiated to request reply.
157  */
158 void
159 ptlrpc_save_lock(struct ptlrpc_request *req,
160                  struct lustre_handle *lock, int mode, int no_ack)
161 {
162         struct ptlrpc_reply_state *rs = req->rq_reply_state;
163         int                        idx;
164
165         LASSERT(rs != NULL);
166         LASSERT(rs->rs_nlocks < RS_MAX_LOCKS);
167
168         if (req->rq_export->exp_disconnected) {
169                 ldlm_lock_decref(lock, mode);
170         } else {
171                 idx = rs->rs_nlocks++;
172                 rs->rs_locks[idx] = *lock;
173                 rs->rs_modes[idx] = mode;
174                 rs->rs_difficult = 1;
175                 rs->rs_no_ack = !!no_ack;
176         }
177 }
178
179 #ifdef __KERNEL__
180
181 #define HRT_RUNNING 0
182 #define HRT_STOPPING 1
183
184 struct ptlrpc_hr_thread {
185         cfs_spinlock_t        hrt_lock;
186         unsigned long         hrt_flags;
187         cfs_waitq_t           hrt_wait;
188         cfs_list_t            hrt_queue;
189         cfs_completion_t      hrt_completion;
190 };
191
192 struct ptlrpc_hr_service {
193         int                     hr_index;
194         int                     hr_n_threads;
195         int                     hr_size;
196         struct ptlrpc_hr_thread hr_threads[0];
197 };
198
199 struct rs_batch {
200         cfs_list_t              rsb_replies;
201         struct ptlrpc_service  *rsb_svc;
202         unsigned int            rsb_n_replies;
203 };
204
205 /**
206  *  A pointer to per-node reply handling service.
207  */
208 static struct ptlrpc_hr_service *ptlrpc_hr = NULL;
209
210 /**
211  * maximum mumber of replies scheduled in one batch
212  */
213 #define MAX_SCHEDULED 256
214
215 /**
216  * Initialize a reply batch.
217  *
218  * \param b batch
219  */
220 static void rs_batch_init(struct rs_batch *b)
221 {
222         memset(b, 0, sizeof *b);
223         CFS_INIT_LIST_HEAD(&b->rsb_replies);
224 }
225
226 /**
227  * Choose an hr thread to dispatch requests to.
228  */
229 static unsigned int get_hr_thread_index(struct ptlrpc_hr_service *hr)
230 {
231         unsigned int idx;
232
233         /* Concurrent modification of hr_index w/o any spinlock
234            protection is harmless as long as the result fits
235            [0..(hr_n_threads-1)] range and each thread gets near equal
236            load. */
237         idx = hr->hr_index;
238         hr->hr_index = (idx >= hr->hr_n_threads - 1) ? 0 : idx + 1;
239         return idx;
240 }
241
242 /**
243  * Dispatch all replies accumulated in the batch to one from
244  * dedicated reply handling threads.
245  *
246  * \param b batch
247  */
248 static void rs_batch_dispatch(struct rs_batch *b)
249 {
250         if (b->rsb_n_replies != 0) {
251                 struct ptlrpc_hr_service *hr = ptlrpc_hr;
252                 int idx;
253
254                 idx = get_hr_thread_index(hr);
255
256                 cfs_spin_lock(&hr->hr_threads[idx].hrt_lock);
257                 cfs_list_splice_init(&b->rsb_replies,
258                                      &hr->hr_threads[idx].hrt_queue);
259                 cfs_spin_unlock(&hr->hr_threads[idx].hrt_lock);
260                 cfs_waitq_signal(&hr->hr_threads[idx].hrt_wait);
261                 b->rsb_n_replies = 0;
262         }
263 }
264
265 /**
266  * Add a reply to a batch.
267  * Add one reply object to a batch, schedule batched replies if overload.
268  *
269  * \param b batch
270  * \param rs reply
271  */
272 static void rs_batch_add(struct rs_batch *b, struct ptlrpc_reply_state *rs)
273 {
274         struct ptlrpc_service *svc = rs->rs_service;
275
276         if (svc != b->rsb_svc || b->rsb_n_replies >= MAX_SCHEDULED) {
277                 if (b->rsb_svc != NULL) {
278                         rs_batch_dispatch(b);
279                         cfs_spin_unlock(&b->rsb_svc->srv_rs_lock);
280                 }
281                 cfs_spin_lock(&svc->srv_rs_lock);
282                 b->rsb_svc = svc;
283         }
284         cfs_spin_lock(&rs->rs_lock);
285         rs->rs_scheduled_ever = 1;
286         if (rs->rs_scheduled == 0) {
287                 cfs_list_move(&rs->rs_list, &b->rsb_replies);
288                 rs->rs_scheduled = 1;
289                 b->rsb_n_replies++;
290         }
291         rs->rs_committed = 1;
292         cfs_spin_unlock(&rs->rs_lock);
293 }
294
295 /**
296  * Reply batch finalization.
297  * Dispatch remaining replies from the batch
298  * and release remaining spinlock.
299  *
300  * \param b batch
301  */
302 static void rs_batch_fini(struct rs_batch *b)
303 {
304         if (b->rsb_svc != 0) {
305                 rs_batch_dispatch(b);
306                 cfs_spin_unlock(&b->rsb_svc->srv_rs_lock);
307         }
308 }
309
310 #define DECLARE_RS_BATCH(b)     struct rs_batch b
311
312 #else /* __KERNEL__ */
313
314 #define rs_batch_init(b)        do{}while(0)
315 #define rs_batch_fini(b)        do{}while(0)
316 #define rs_batch_add(b, r)      ptlrpc_schedule_difficult_reply(r)
317 #define DECLARE_RS_BATCH(b)
318
319 #endif /* __KERNEL__ */
320
321 /**
322  * Put reply state into a queue for processing because we received
323  * ACK from the client
324  */
325 void ptlrpc_dispatch_difficult_reply(struct ptlrpc_reply_state *rs)
326 {
327 #ifdef __KERNEL__
328         struct ptlrpc_hr_service *hr = ptlrpc_hr;
329         int idx;
330         ENTRY;
331
332         LASSERT(cfs_list_empty(&rs->rs_list));
333
334         idx = get_hr_thread_index(hr);
335         cfs_spin_lock(&hr->hr_threads[idx].hrt_lock);
336         cfs_list_add_tail(&rs->rs_list, &hr->hr_threads[idx].hrt_queue);
337         cfs_spin_unlock(&hr->hr_threads[idx].hrt_lock);
338         cfs_waitq_signal(&hr->hr_threads[idx].hrt_wait);
339         EXIT;
340 #else
341         cfs_list_add_tail(&rs->rs_list, &rs->rs_service->srv_reply_queue);
342 #endif
343 }
344
345 void
346 ptlrpc_schedule_difficult_reply (struct ptlrpc_reply_state *rs)
347 {
348         ENTRY;
349
350         LASSERT_SPIN_LOCKED(&rs->rs_service->srv_rs_lock);
351         LASSERT_SPIN_LOCKED(&rs->rs_lock);
352         LASSERT (rs->rs_difficult);
353         rs->rs_scheduled_ever = 1;  /* flag any notification attempt */
354
355         if (rs->rs_scheduled) {     /* being set up or already notified */
356                 EXIT;
357                 return;
358         }
359
360         rs->rs_scheduled = 1;
361         cfs_list_del_init(&rs->rs_list);
362         ptlrpc_dispatch_difficult_reply(rs);
363         EXIT;
364 }
365
366 void ptlrpc_commit_replies(struct obd_export *exp)
367 {
368         struct ptlrpc_reply_state *rs, *nxt;
369         DECLARE_RS_BATCH(batch);
370         ENTRY;
371
372         rs_batch_init(&batch);
373         /* Find any replies that have been committed and get their service
374          * to attend to complete them. */
375
376         /* CAVEAT EMPTOR: spinlock ordering!!! */
377         cfs_spin_lock(&exp->exp_uncommitted_replies_lock);
378         cfs_list_for_each_entry_safe(rs, nxt, &exp->exp_uncommitted_replies,
379                                      rs_obd_list) {
380                 LASSERT (rs->rs_difficult);
381                 /* VBR: per-export last_committed */
382                 LASSERT(rs->rs_export);
383                 if (rs->rs_transno <= exp->exp_last_committed) {
384                         cfs_list_del_init(&rs->rs_obd_list);
385                         rs_batch_add(&batch, rs);
386                 }
387         }
388         cfs_spin_unlock(&exp->exp_uncommitted_replies_lock);
389         rs_batch_fini(&batch);
390         EXIT;
391 }
392
393 static int
394 ptlrpc_server_post_idle_rqbds (struct ptlrpc_service *svc)
395 {
396         struct ptlrpc_request_buffer_desc *rqbd;
397         int                                rc;
398         int                                posted = 0;
399
400         for (;;) {
401                 cfs_spin_lock(&svc->srv_lock);
402
403                 if (cfs_list_empty (&svc->srv_idle_rqbds)) {
404                         cfs_spin_unlock(&svc->srv_lock);
405                         return (posted);
406                 }
407
408                 rqbd = cfs_list_entry(svc->srv_idle_rqbds.next,
409                                       struct ptlrpc_request_buffer_desc,
410                                       rqbd_list);
411                 cfs_list_del (&rqbd->rqbd_list);
412
413                 /* assume we will post successfully */
414                 svc->srv_nrqbd_receiving++;
415                 cfs_list_add (&rqbd->rqbd_list, &svc->srv_active_rqbds);
416
417                 cfs_spin_unlock(&svc->srv_lock);
418
419                 rc = ptlrpc_register_rqbd(rqbd);
420                 if (rc != 0)
421                         break;
422
423                 posted = 1;
424         }
425
426         cfs_spin_lock(&svc->srv_lock);
427
428         svc->srv_nrqbd_receiving--;
429         cfs_list_del(&rqbd->rqbd_list);
430         cfs_list_add_tail(&rqbd->rqbd_list, &svc->srv_idle_rqbds);
431
432         /* Don't complain if no request buffers are posted right now; LNET
433          * won't drop requests because we set the portal lazy! */
434
435         cfs_spin_unlock(&svc->srv_lock);
436
437         return (-1);
438 }
439
440 static void ptlrpc_at_timer(unsigned long castmeharder)
441 {
442         struct ptlrpc_service *svc = (struct ptlrpc_service *)castmeharder;
443         svc->srv_at_check = 1;
444         svc->srv_at_checktime = cfs_time_current();
445         cfs_waitq_signal(&svc->srv_waitq);
446 }
447
448 /**
449  * Initialize service on a given portal.
450  * This includes starting serving threads , allocating and posting rqbds and
451  * so on.
452  */
453 struct ptlrpc_service *
454 ptlrpc_register_service(struct ptlrpc_service_conf *conf,
455                         cfs_proc_dir_entry_t *proc_entry)
456 {
457         struct ptlrpc_service   *service;
458         struct ptlrpc_at_array  *array;
459         unsigned int            index;
460         unsigned int            size;
461         int                     rc;
462         ENTRY;
463
464         LASSERT(conf->psc_buf.bc_nbufs > 0);
465         LASSERT(conf->psc_buf.bc_buf_size >=
466                 conf->psc_buf.bc_req_max_size + SPTLRPC_MAX_PAYLOAD);
467         LASSERT(conf->psc_thr.tc_ctx_tags != 0);
468
469         OBD_ALLOC_PTR(service);
470         if (service == NULL)
471                 RETURN(ERR_PTR(-ENOMEM));
472
473         /* First initialise enough for early teardown */
474
475         cfs_spin_lock_init(&service->srv_lock);
476         cfs_spin_lock_init(&service->srv_rq_lock);
477         cfs_spin_lock_init(&service->srv_rs_lock);
478         CFS_INIT_LIST_HEAD(&service->srv_threads);
479         cfs_waitq_init(&service->srv_waitq);
480
481         service->srv_name               = conf->psc_name;
482         service->srv_watchdog_factor    = conf->psc_watchdog_factor;
483         service->srv_nbuf_per_group     = test_req_buffer_pressure ?
484                                           1 : conf->psc_buf.bc_nbufs;
485         service->srv_max_req_size       = conf->psc_buf.bc_req_max_size +
486                                           SPTLRPC_MAX_PAYLOAD;
487         service->srv_buf_size           = conf->psc_buf.bc_buf_size;
488         service->srv_rep_portal         = conf->psc_buf.bc_rep_portal;
489         service->srv_req_portal         = conf->psc_buf.bc_req_portal;
490         service->srv_request_seq        = 1; /* valid seq #s start at 1 */
491         service->srv_request_max_cull_seq = 0;
492         service->srv_threads_min        = conf->psc_thr.tc_nthrs_min;
493         service->srv_threads_max        = conf->psc_thr.tc_nthrs_max;
494         service->srv_thread_name        = conf->psc_thr.tc_thr_name;
495         service->srv_ctx_tags           = conf->psc_thr.tc_ctx_tags;
496         service->srv_cpu_affinity       = !!conf->psc_thr.tc_cpu_affinity;
497         service->srv_hpreq_ratio        = PTLRPC_SVC_HP_RATIO;
498         service->srv_hpreq_count        = 0;
499         service->srv_n_active_hpreq     = 0;
500         service->srv_ops                = conf->psc_ops;
501
502         rc = LNetSetLazyPortal(service->srv_req_portal);
503         LASSERT (rc == 0);
504
505         CFS_INIT_LIST_HEAD(&service->srv_request_queue);
506         CFS_INIT_LIST_HEAD(&service->srv_request_hpq);
507         CFS_INIT_LIST_HEAD(&service->srv_idle_rqbds);
508         CFS_INIT_LIST_HEAD(&service->srv_active_rqbds);
509         CFS_INIT_LIST_HEAD(&service->srv_history_rqbds);
510         CFS_INIT_LIST_HEAD(&service->srv_request_history);
511         CFS_INIT_LIST_HEAD(&service->srv_active_replies);
512 #ifndef __KERNEL__
513         CFS_INIT_LIST_HEAD(&service->srv_reply_queue);
514 #endif
515         CFS_INIT_LIST_HEAD(&service->srv_free_rs_list);
516         cfs_waitq_init(&service->srv_free_rs_waitq);
517         cfs_atomic_set(&service->srv_n_difficult_replies, 0);
518
519         cfs_spin_lock_init(&service->srv_at_lock);
520         CFS_INIT_LIST_HEAD(&service->srv_req_in_queue);
521
522         array = &service->srv_at_array;
523         size = at_est2timeout(at_max);
524         array->paa_size = size;
525         array->paa_count = 0;
526         array->paa_deadline = -1;
527
528         /* allocate memory for srv_at_array (ptlrpc_at_array) */
529         OBD_ALLOC(array->paa_reqs_array, sizeof(cfs_list_t) * size);
530         if (array->paa_reqs_array == NULL)
531                 GOTO(failed, rc = -ENOMEM);
532
533         for (index = 0; index < size; index++)
534                 CFS_INIT_LIST_HEAD(&array->paa_reqs_array[index]);
535
536         OBD_ALLOC(array->paa_reqs_count, sizeof(__u32) * size);
537         if (array->paa_reqs_count == NULL)
538                 GOTO(failed, rc = -ENOMEM);
539
540         cfs_timer_init(&service->srv_at_timer, ptlrpc_at_timer, service);
541         /* At SOW, service time should be quick; 10s seems generous. If client
542            timeout is less than this, we'll be sending an early reply. */
543         at_init(&service->srv_at_estimate, 10, 0);
544
545         cfs_spin_lock (&ptlrpc_all_services_lock);
546         cfs_list_add (&service->srv_list, &ptlrpc_all_services);
547         cfs_spin_unlock (&ptlrpc_all_services_lock);
548
549         /* Now allocate the request buffers */
550         rc = ptlrpc_grow_req_bufs(service);
551         /* We shouldn't be under memory pressure at startup, so
552          * fail if we can't post all our buffers at this time. */
553         if (rc != 0)
554                 GOTO(failed, rc = -ENOMEM);
555
556         /* Now allocate pool of reply buffers */
557         /* Increase max reply size to next power of two */
558         service->srv_max_reply_size = 1;
559         while (service->srv_max_reply_size <
560                conf->psc_buf.bc_rep_max_size + SPTLRPC_MAX_PAYLOAD)
561                 service->srv_max_reply_size <<= 1;
562
563         if (proc_entry != NULL)
564                 ptlrpc_lprocfs_register_service(proc_entry, service);
565
566         CDEBUG(D_NET, "%s: Started, listening on portal %d\n",
567                service->srv_name, service->srv_req_portal);
568
569 #ifdef __KERNEL__
570         rc = ptlrpc_start_threads(service);
571         if (rc != 0) {
572                 CERROR("Failed to start threads for service %s: %d\n",
573                        service->srv_name, rc);
574                 GOTO(failed, rc);
575         }
576 #endif
577
578         RETURN(service);
579 failed:
580         ptlrpc_unregister_service(service);
581         RETURN(ERR_PTR(rc));
582 }
583
584 /**
585  * to actually free the request, must be called without holding svc_lock.
586  * note it's caller's responsibility to unlink req->rq_list.
587  */
588 static void ptlrpc_server_free_request(struct ptlrpc_request *req)
589 {
590         LASSERT(cfs_atomic_read(&req->rq_refcount) == 0);
591         LASSERT(cfs_list_empty(&req->rq_timed_list));
592
593          /* DEBUG_REQ() assumes the reply state of a request with a valid
594           * ref will not be destroyed until that reference is dropped. */
595         ptlrpc_req_drop_rs(req);
596
597         sptlrpc_svc_ctx_decref(req);
598
599         if (req != &req->rq_rqbd->rqbd_req) {
600                 /* NB request buffers use an embedded
601                  * req if the incoming req unlinked the
602                  * MD; this isn't one of them! */
603                 OBD_FREE(req, sizeof(*req));
604         }
605 }
606
607 /**
608  * drop a reference count of the request. if it reaches 0, we either
609  * put it into history list, or free it immediately.
610  */
611 void ptlrpc_server_drop_request(struct ptlrpc_request *req)
612 {
613         struct ptlrpc_request_buffer_desc *rqbd = req->rq_rqbd;
614         struct ptlrpc_service             *svc = rqbd->rqbd_service;
615         int                                refcount;
616         cfs_list_t                        *tmp;
617         cfs_list_t                        *nxt;
618
619         if (!cfs_atomic_dec_and_test(&req->rq_refcount))
620                 return;
621
622         cfs_spin_lock(&svc->srv_at_lock);
623         if (req->rq_at_linked) {
624                 struct ptlrpc_at_array *array = &svc->srv_at_array;
625                 __u32 index = req->rq_at_index;
626
627                 LASSERT(!cfs_list_empty(&req->rq_timed_list));
628                 cfs_list_del_init(&req->rq_timed_list);
629                 cfs_spin_lock(&req->rq_lock);
630                 req->rq_at_linked = 0;
631                 cfs_spin_unlock(&req->rq_lock);
632                 array->paa_reqs_count[index]--;
633                 array->paa_count--;
634         } else
635                 LASSERT(cfs_list_empty(&req->rq_timed_list));
636         cfs_spin_unlock(&svc->srv_at_lock);
637
638         /* finalize request */
639         if (req->rq_export) {
640                 class_export_put(req->rq_export);
641                 req->rq_export = NULL;
642         }
643
644         cfs_spin_lock(&svc->srv_lock);
645
646         cfs_list_add(&req->rq_list, &rqbd->rqbd_reqs);
647
648         refcount = --(rqbd->rqbd_refcount);
649         if (refcount == 0) {
650                 /* request buffer is now idle: add to history */
651                 cfs_list_del(&rqbd->rqbd_list);
652                 cfs_list_add_tail(&rqbd->rqbd_list, &svc->srv_history_rqbds);
653                 svc->srv_n_history_rqbds++;
654
655                 /* cull some history?
656                  * I expect only about 1 or 2 rqbds need to be recycled here */
657                 while (svc->srv_n_history_rqbds > svc->srv_max_history_rqbds) {
658                         rqbd = cfs_list_entry(svc->srv_history_rqbds.next,
659                                               struct ptlrpc_request_buffer_desc,
660                                               rqbd_list);
661
662                         cfs_list_del(&rqbd->rqbd_list);
663                         svc->srv_n_history_rqbds--;
664
665                         /* remove rqbd's reqs from svc's req history while
666                          * I've got the service lock */
667                         cfs_list_for_each(tmp, &rqbd->rqbd_reqs) {
668                                 req = cfs_list_entry(tmp, struct ptlrpc_request,
669                                                      rq_list);
670                                 /* Track the highest culled req seq */
671                                 if (req->rq_history_seq >
672                                     svc->srv_request_max_cull_seq)
673                                         svc->srv_request_max_cull_seq =
674                                                 req->rq_history_seq;
675                                 cfs_list_del(&req->rq_history_list);
676                         }
677
678                         cfs_spin_unlock(&svc->srv_lock);
679
680                         cfs_list_for_each_safe(tmp, nxt, &rqbd->rqbd_reqs) {
681                                 req = cfs_list_entry(rqbd->rqbd_reqs.next,
682                                                      struct ptlrpc_request,
683                                                      rq_list);
684                                 cfs_list_del(&req->rq_list);
685                                 ptlrpc_server_free_request(req);
686                         }
687
688                         cfs_spin_lock(&svc->srv_lock);
689                         /*
690                          * now all reqs including the embedded req has been
691                          * disposed, schedule request buffer for re-use.
692                          */
693                         LASSERT(cfs_atomic_read(&rqbd->rqbd_req.rq_refcount) ==
694                                 0);
695                         cfs_list_add_tail(&rqbd->rqbd_list,
696                                           &svc->srv_idle_rqbds);
697                 }
698
699                 cfs_spin_unlock(&svc->srv_lock);
700         } else if (req->rq_reply_state && req->rq_reply_state->rs_prealloc) {
701                 /* If we are low on memory, we are not interested in history */
702                 cfs_list_del(&req->rq_list);
703                 cfs_list_del_init(&req->rq_history_list);
704                 cfs_spin_unlock(&svc->srv_lock);
705
706                 ptlrpc_server_free_request(req);
707         } else {
708                 cfs_spin_unlock(&svc->srv_lock);
709         }
710 }
711
712 /**
713  * to finish a request: stop sending more early replies, and release
714  * the request. should be called after we finished handling the request.
715  */
716 static void ptlrpc_server_finish_request(struct ptlrpc_service *svc,
717                                          struct ptlrpc_request *req)
718 {
719         ptlrpc_hpreq_fini(req);
720
721         cfs_spin_lock(&svc->srv_rq_lock);
722         svc->srv_n_active_reqs--;
723         if (req->rq_hp)
724                 svc->srv_n_active_hpreq--;
725         cfs_spin_unlock(&svc->srv_rq_lock);
726
727         ptlrpc_server_drop_request(req);
728 }
729
730 /**
731  * This function makes sure dead exports are evicted in a timely manner.
732  * This function is only called when some export receives a message (i.e.,
733  * the network is up.)
734  */
735 static void ptlrpc_update_export_timer(struct obd_export *exp, long extra_delay)
736 {
737         struct obd_export *oldest_exp;
738         time_t oldest_time, new_time;
739
740         ENTRY;
741
742         LASSERT(exp);
743
744         /* Compensate for slow machines, etc, by faking our request time
745            into the future.  Although this can break the strict time-ordering
746            of the list, we can be really lazy here - we don't have to evict
747            at the exact right moment.  Eventually, all silent exports
748            will make it to the top of the list. */
749
750         /* Do not pay attention on 1sec or smaller renewals. */
751         new_time = cfs_time_current_sec() + extra_delay;
752         if (exp->exp_last_request_time + 1 /*second */ >= new_time)
753                 RETURN_EXIT;
754
755         exp->exp_last_request_time = new_time;
756         CDEBUG(D_HA, "updating export %s at "CFS_TIME_T" exp %p\n",
757                exp->exp_client_uuid.uuid,
758                exp->exp_last_request_time, exp);
759
760         /* exports may get disconnected from the chain even though the
761            export has references, so we must keep the spin lock while
762            manipulating the lists */
763         cfs_spin_lock(&exp->exp_obd->obd_dev_lock);
764
765         if (cfs_list_empty(&exp->exp_obd_chain_timed)) {
766                 /* this one is not timed */
767                 cfs_spin_unlock(&exp->exp_obd->obd_dev_lock);
768                 RETURN_EXIT;
769         }
770
771         cfs_list_move_tail(&exp->exp_obd_chain_timed,
772                            &exp->exp_obd->obd_exports_timed);
773
774         oldest_exp = cfs_list_entry(exp->exp_obd->obd_exports_timed.next,
775                                     struct obd_export, exp_obd_chain_timed);
776         oldest_time = oldest_exp->exp_last_request_time;
777         cfs_spin_unlock(&exp->exp_obd->obd_dev_lock);
778
779         if (exp->exp_obd->obd_recovering) {
780                 /* be nice to everyone during recovery */
781                 EXIT;
782                 return;
783         }
784
785         /* Note - racing to start/reset the obd_eviction timer is safe */
786         if (exp->exp_obd->obd_eviction_timer == 0) {
787                 /* Check if the oldest entry is expired. */
788                 if (cfs_time_current_sec() > (oldest_time + PING_EVICT_TIMEOUT +
789                                               extra_delay)) {
790                         /* We need a second timer, in case the net was down and
791                          * it just came back. Since the pinger may skip every
792                          * other PING_INTERVAL (see note in ptlrpc_pinger_main),
793                          * we better wait for 3. */
794                         exp->exp_obd->obd_eviction_timer =
795                                 cfs_time_current_sec() + 3 * PING_INTERVAL;
796                         CDEBUG(D_HA, "%s: Think about evicting %s from "CFS_TIME_T"\n",
797                                exp->exp_obd->obd_name, 
798                                obd_export_nid2str(oldest_exp), oldest_time);
799                 }
800         } else {
801                 if (cfs_time_current_sec() >
802                     (exp->exp_obd->obd_eviction_timer + extra_delay)) {
803                         /* The evictor won't evict anyone who we've heard from
804                          * recently, so we don't have to check before we start
805                          * it. */
806                         if (!ping_evictor_wake(exp))
807                                 exp->exp_obd->obd_eviction_timer = 0;
808                 }
809         }
810
811         EXIT;
812 }
813
814 /**
815  * Sanity check request \a req.
816  * Return 0 if all is ok, error code otherwise.
817  */
818 static int ptlrpc_check_req(struct ptlrpc_request *req)
819 {
820         int rc = 0;
821
822         if (unlikely(lustre_msg_get_conn_cnt(req->rq_reqmsg) <
823                      req->rq_export->exp_conn_cnt)) {
824                 DEBUG_REQ(D_ERROR, req,
825                           "DROPPING req from old connection %d < %d",
826                           lustre_msg_get_conn_cnt(req->rq_reqmsg),
827                           req->rq_export->exp_conn_cnt);
828                 return -EEXIST;
829         }
830         if (unlikely(req->rq_export->exp_obd &&
831                      req->rq_export->exp_obd->obd_fail)) {
832              /* Failing over, don't handle any more reqs, send
833                 error response instead. */
834                 CDEBUG(D_RPCTRACE, "Dropping req %p for failed obd %s\n",
835                        req, req->rq_export->exp_obd->obd_name);
836                 rc = -ENODEV;
837         } else if (lustre_msg_get_flags(req->rq_reqmsg) &
838                    (MSG_REPLAY | MSG_REQ_REPLAY_DONE) &&
839                    !(req->rq_export->exp_obd->obd_recovering)) {
840                         DEBUG_REQ(D_ERROR, req,
841                                   "Invalid replay without recovery");
842                         class_fail_export(req->rq_export);
843                         rc = -ENODEV;
844         } else if (lustre_msg_get_transno(req->rq_reqmsg) != 0 &&
845                    !(req->rq_export->exp_obd->obd_recovering)) {
846                         DEBUG_REQ(D_ERROR, req, "Invalid req with transno "
847                                   LPU64" without recovery",
848                                   lustre_msg_get_transno(req->rq_reqmsg));
849                         class_fail_export(req->rq_export);
850                         rc = -ENODEV;
851         }
852
853         if (unlikely(rc < 0)) {
854                 req->rq_status = rc;
855                 ptlrpc_error(req);
856         }
857         return rc;
858 }
859
860 static void ptlrpc_at_set_timer(struct ptlrpc_service *svc)
861 {
862         struct ptlrpc_at_array *array = &svc->srv_at_array;
863         __s32 next;
864
865         cfs_spin_lock(&svc->srv_at_lock);
866         if (array->paa_count == 0) {
867                 cfs_timer_disarm(&svc->srv_at_timer);
868                 cfs_spin_unlock(&svc->srv_at_lock);
869                 return;
870         }
871
872         /* Set timer for closest deadline */
873         next = (__s32)(array->paa_deadline - cfs_time_current_sec() -
874                        at_early_margin);
875         if (next <= 0)
876                 ptlrpc_at_timer((unsigned long)svc);
877         else
878                 cfs_timer_arm(&svc->srv_at_timer, cfs_time_shift(next));
879         cfs_spin_unlock(&svc->srv_at_lock);
880         CDEBUG(D_INFO, "armed %s at %+ds\n", svc->srv_name, next);
881 }
882
883 /* Add rpc to early reply check list */
884 static int ptlrpc_at_add_timed(struct ptlrpc_request *req)
885 {
886         struct ptlrpc_service *svc = req->rq_rqbd->rqbd_service;
887         struct ptlrpc_request *rq = NULL;
888         struct ptlrpc_at_array *array = &svc->srv_at_array;
889         __u32 index;
890         int found = 0;
891
892         if (AT_OFF)
893                 return(0);
894
895         if (req->rq_no_reply)
896                 return 0;
897
898         if ((lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT) == 0)
899                 return(-ENOSYS);
900
901         cfs_spin_lock(&svc->srv_at_lock);
902         LASSERT(cfs_list_empty(&req->rq_timed_list));
903
904         index = (unsigned long)req->rq_deadline % array->paa_size;
905         if (array->paa_reqs_count[index] > 0) {
906                 /* latest rpcs will have the latest deadlines in the list,
907                  * so search backward. */
908                 cfs_list_for_each_entry_reverse(rq,
909                                                 &array->paa_reqs_array[index],
910                                                 rq_timed_list) {
911                         if (req->rq_deadline >= rq->rq_deadline) {
912                                 cfs_list_add(&req->rq_timed_list,
913                                              &rq->rq_timed_list);
914                                 break;
915                         }
916                 }
917         }
918
919         /* Add the request at the head of the list */
920         if (cfs_list_empty(&req->rq_timed_list))
921                 cfs_list_add(&req->rq_timed_list,
922                              &array->paa_reqs_array[index]);
923
924         cfs_spin_lock(&req->rq_lock);
925         req->rq_at_linked = 1;
926         cfs_spin_unlock(&req->rq_lock);
927         req->rq_at_index = index;
928         array->paa_reqs_count[index]++;
929         array->paa_count++;
930         if (array->paa_count == 1 || array->paa_deadline > req->rq_deadline) {
931                 array->paa_deadline = req->rq_deadline;
932                 found = 1;
933         }
934         cfs_spin_unlock(&svc->srv_at_lock);
935
936         if (found)
937                 ptlrpc_at_set_timer(svc);
938
939         return 0;
940 }
941
942 static int ptlrpc_at_send_early_reply(struct ptlrpc_request *req)
943 {
944         struct ptlrpc_service *svc = req->rq_rqbd->rqbd_service;
945         struct ptlrpc_request *reqcopy;
946         struct lustre_msg *reqmsg;
947         cfs_duration_t olddl = req->rq_deadline - cfs_time_current_sec();
948         time_t newdl;
949         int rc;
950         ENTRY;
951
952         /* deadline is when the client expects us to reply, margin is the
953            difference between clients' and servers' expectations */
954         DEBUG_REQ(D_ADAPTTO, req,
955                   "%ssending early reply (deadline %+lds, margin %+lds) for "
956                   "%d+%d", AT_OFF ? "AT off - not " : "",
957                   olddl, olddl - at_get(&svc->srv_at_estimate),
958                   at_get(&svc->srv_at_estimate), at_extra);
959
960         if (AT_OFF)
961                 RETURN(0);
962
963         if (olddl < 0) {
964                 DEBUG_REQ(D_WARNING, req, "Already past deadline (%+lds), "
965                           "not sending early reply. Consider increasing "
966                           "at_early_margin (%d)?", olddl, at_early_margin);
967
968                 /* Return an error so we're not re-added to the timed list. */
969                 RETURN(-ETIMEDOUT);
970         }
971
972         if ((lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT) == 0){
973                 DEBUG_REQ(D_INFO, req, "Wanted to ask client for more time, "
974                           "but no AT support");
975                 RETURN(-ENOSYS);
976         }
977
978         if (req->rq_export &&
979             lustre_msg_get_flags(req->rq_reqmsg) &
980             (MSG_REPLAY | MSG_REQ_REPLAY_DONE | MSG_LOCK_REPLAY_DONE)) {
981                 /* During recovery, we don't want to send too many early
982                  * replies, but on the other hand we want to make sure the
983                  * client has enough time to resend if the rpc is lost. So
984                  * during the recovery period send at least 4 early replies,
985                  * spacing them every at_extra if we can. at_estimate should
986                  * always equal this fixed value during recovery. */
987                 at_measured(&svc->srv_at_estimate, min(at_extra,
988                             req->rq_export->exp_obd->obd_recovery_timeout / 4));
989         } else {
990                 /* Fake our processing time into the future to ask the clients
991                  * for some extra amount of time */
992                 at_measured(&svc->srv_at_estimate, at_extra +
993                             cfs_time_current_sec() -
994                             req->rq_arrival_time.tv_sec);
995
996                 /* Check to see if we've actually increased the deadline -
997                  * we may be past adaptive_max */
998                 if (req->rq_deadline >= req->rq_arrival_time.tv_sec +
999                     at_get(&svc->srv_at_estimate)) {
1000                         DEBUG_REQ(D_WARNING, req, "Couldn't add any time "
1001                                   "(%ld/%ld), not sending early reply\n",
1002                                   olddl, req->rq_arrival_time.tv_sec +
1003                                   at_get(&svc->srv_at_estimate) -
1004                                   cfs_time_current_sec());
1005                         RETURN(-ETIMEDOUT);
1006                 }
1007         }
1008         newdl = cfs_time_current_sec() + at_get(&svc->srv_at_estimate);
1009
1010         OBD_ALLOC(reqcopy, sizeof *reqcopy);
1011         if (reqcopy == NULL)
1012                 RETURN(-ENOMEM);
1013         OBD_ALLOC_LARGE(reqmsg, req->rq_reqlen);
1014         if (!reqmsg) {
1015                 OBD_FREE(reqcopy, sizeof *reqcopy);
1016                 RETURN(-ENOMEM);
1017         }
1018
1019         *reqcopy = *req;
1020         reqcopy->rq_reply_state = NULL;
1021         reqcopy->rq_rep_swab_mask = 0;
1022         reqcopy->rq_pack_bulk = 0;
1023         reqcopy->rq_pack_udesc = 0;
1024         reqcopy->rq_packed_final = 0;
1025         sptlrpc_svc_ctx_addref(reqcopy);
1026         /* We only need the reqmsg for the magic */
1027         reqcopy->rq_reqmsg = reqmsg;
1028         memcpy(reqmsg, req->rq_reqmsg, req->rq_reqlen);
1029
1030         LASSERT(cfs_atomic_read(&req->rq_refcount));
1031         /** if it is last refcount then early reply isn't needed */
1032         if (cfs_atomic_read(&req->rq_refcount) == 1) {
1033                 DEBUG_REQ(D_ADAPTTO, reqcopy, "Normal reply already sent out, "
1034                           "abort sending early reply\n");
1035                 GOTO(out, rc = -EINVAL);
1036         }
1037
1038         /* Connection ref */
1039         reqcopy->rq_export = class_conn2export(
1040                                      lustre_msg_get_handle(reqcopy->rq_reqmsg));
1041         if (reqcopy->rq_export == NULL)
1042                 GOTO(out, rc = -ENODEV);
1043
1044         /* RPC ref */
1045         class_export_rpc_get(reqcopy->rq_export);
1046         if (reqcopy->rq_export->exp_obd &&
1047             reqcopy->rq_export->exp_obd->obd_fail)
1048                 GOTO(out_put, rc = -ENODEV);
1049
1050         rc = lustre_pack_reply_flags(reqcopy, 1, NULL, NULL, LPRFL_EARLY_REPLY);
1051         if (rc)
1052                 GOTO(out_put, rc);
1053
1054         rc = ptlrpc_send_reply(reqcopy, PTLRPC_REPLY_EARLY);
1055
1056         if (!rc) {
1057                 /* Adjust our own deadline to what we told the client */
1058                 req->rq_deadline = newdl;
1059                 req->rq_early_count++; /* number sent, server side */
1060         } else {
1061                 DEBUG_REQ(D_ERROR, req, "Early reply send failed %d", rc);
1062         }
1063
1064         /* Free the (early) reply state from lustre_pack_reply.
1065            (ptlrpc_send_reply takes it's own rs ref, so this is safe here) */
1066         ptlrpc_req_drop_rs(reqcopy);
1067
1068 out_put:
1069         class_export_rpc_put(reqcopy->rq_export);
1070         class_export_put(reqcopy->rq_export);
1071 out:
1072         sptlrpc_svc_ctx_decref(reqcopy);
1073         OBD_FREE_LARGE(reqmsg, req->rq_reqlen);
1074         OBD_FREE(reqcopy, sizeof *reqcopy);
1075         RETURN(rc);
1076 }
1077
1078 /* Send early replies to everybody expiring within at_early_margin
1079    asking for at_extra time */
1080 static int ptlrpc_at_check_timed(struct ptlrpc_service *svc)
1081 {
1082         struct ptlrpc_request *rq, *n;
1083         cfs_list_t work_list;
1084         struct ptlrpc_at_array *array = &svc->srv_at_array;
1085         __u32  index, count;
1086         time_t deadline;
1087         time_t now = cfs_time_current_sec();
1088         cfs_duration_t delay;
1089         int first, counter = 0;
1090         ENTRY;
1091
1092         cfs_spin_lock(&svc->srv_at_lock);
1093         if (svc->srv_at_check == 0) {
1094                 cfs_spin_unlock(&svc->srv_at_lock);
1095                 RETURN(0);
1096         }
1097         delay = cfs_time_sub(cfs_time_current(), svc->srv_at_checktime);
1098         svc->srv_at_check = 0;
1099
1100         if (array->paa_count == 0) {
1101                 cfs_spin_unlock(&svc->srv_at_lock);
1102                 RETURN(0);
1103         }
1104
1105         /* The timer went off, but maybe the nearest rpc already completed. */
1106         first = array->paa_deadline - now;
1107         if (first > at_early_margin) {
1108                 /* We've still got plenty of time.  Reset the timer. */
1109                 cfs_spin_unlock(&svc->srv_at_lock);
1110                 ptlrpc_at_set_timer(svc);
1111                 RETURN(0);
1112         }
1113
1114         /* We're close to a timeout, and we don't know how much longer the
1115            server will take. Send early replies to everyone expiring soon. */
1116         CFS_INIT_LIST_HEAD(&work_list);
1117         deadline = -1;
1118         index = (unsigned long)array->paa_deadline % array->paa_size;
1119         count = array->paa_count;
1120         while (count > 0) {
1121                 count -= array->paa_reqs_count[index];
1122                 cfs_list_for_each_entry_safe(rq, n,
1123                                              &array->paa_reqs_array[index],
1124                                              rq_timed_list) {
1125                         if (rq->rq_deadline <= now + at_early_margin) {
1126                                 cfs_list_del_init(&rq->rq_timed_list);
1127                                 /**
1128                                  * ptlrpc_server_drop_request() may drop
1129                                  * refcount to 0 already. Let's check this and
1130                                  * don't add entry to work_list
1131                                  */
1132                                 if (likely(cfs_atomic_inc_not_zero(&rq->rq_refcount)))
1133                                         cfs_list_add(&rq->rq_timed_list, &work_list);
1134                                 counter++;
1135                                 array->paa_reqs_count[index]--;
1136                                 array->paa_count--;
1137                                 cfs_spin_lock(&rq->rq_lock);
1138                                 rq->rq_at_linked = 0;
1139                                 cfs_spin_unlock(&rq->rq_lock);
1140                                 continue;
1141                         }
1142
1143                         /* update the earliest deadline */
1144                         if (deadline == -1 || rq->rq_deadline < deadline)
1145                                 deadline = rq->rq_deadline;
1146
1147                         break;
1148                 }
1149
1150                 if (++index >= array->paa_size)
1151                         index = 0;
1152         }
1153         array->paa_deadline = deadline;
1154         cfs_spin_unlock(&svc->srv_at_lock);
1155
1156         /* we have a new earliest deadline, restart the timer */
1157         ptlrpc_at_set_timer(svc);
1158
1159         CDEBUG(D_ADAPTTO, "timeout in %+ds, asking for %d secs on %d early "
1160                "replies\n", first, at_extra, counter);
1161         if (first < 0) {
1162                 /* We're already past request deadlines before we even get a
1163                    chance to send early replies */
1164                 LCONSOLE_WARN("%s: This server is not able to keep up with "
1165                               "request traffic (cpu-bound).\n", svc->srv_name);
1166                 CWARN("earlyQ=%d reqQ=%d recA=%d, svcEst=%d, "
1167                       "delay="CFS_DURATION_T"(jiff)\n",
1168                       counter, svc->srv_n_queued_reqs, svc->srv_n_active_reqs,
1169                       at_get(&svc->srv_at_estimate), delay);
1170         }
1171
1172         /* we took additional refcount so entries can't be deleted from list, no
1173          * locking is needed */
1174         while (!cfs_list_empty(&work_list)) {
1175                 rq = cfs_list_entry(work_list.next, struct ptlrpc_request,
1176                                     rq_timed_list);
1177                 cfs_list_del_init(&rq->rq_timed_list);
1178
1179                 if (ptlrpc_at_send_early_reply(rq) == 0)
1180                         ptlrpc_at_add_timed(rq);
1181
1182                 ptlrpc_server_drop_request(rq);
1183         }
1184
1185         RETURN(0);
1186 }
1187
1188 /**
1189  * Put the request to the export list if the request may become
1190  * a high priority one.
1191  */
1192 static int ptlrpc_hpreq_init(struct ptlrpc_service *svc,
1193                              struct ptlrpc_request *req)
1194 {
1195         int rc = 0;
1196         ENTRY;
1197
1198         if (svc->srv_ops.so_hpreq_handler) {
1199                 rc = svc->srv_ops.so_hpreq_handler(req);
1200                 if (rc)
1201                         RETURN(rc);
1202         }
1203         if (req->rq_export && req->rq_ops) {
1204                 /* Perform request specific check. We should do this check
1205                  * before the request is added into exp_hp_rpcs list otherwise
1206                  * it may hit swab race at LU-1044. */
1207                 if (req->rq_ops->hpreq_check)
1208                         rc = req->rq_ops->hpreq_check(req);
1209
1210                 cfs_spin_lock_bh(&req->rq_export->exp_rpc_lock);
1211                 cfs_list_add(&req->rq_exp_list,
1212                              &req->rq_export->exp_hp_rpcs);
1213                 cfs_spin_unlock_bh(&req->rq_export->exp_rpc_lock);
1214         }
1215
1216         RETURN(rc);
1217 }
1218
1219 /** Remove the request from the export list. */
1220 static void ptlrpc_hpreq_fini(struct ptlrpc_request *req)
1221 {
1222         ENTRY;
1223         if (req->rq_export && req->rq_ops) {
1224                 /* refresh lock timeout again so that client has more
1225                  * room to send lock cancel RPC. */
1226                 if (req->rq_ops->hpreq_fini)
1227                         req->rq_ops->hpreq_fini(req);
1228
1229                 cfs_spin_lock_bh(&req->rq_export->exp_rpc_lock);
1230                 cfs_list_del_init(&req->rq_exp_list);
1231                 cfs_spin_unlock_bh(&req->rq_export->exp_rpc_lock);
1232         }
1233         EXIT;
1234 }
1235
1236 /**
1237  * Make the request a high priority one.
1238  *
1239  * All the high priority requests are queued in a separate FIFO
1240  * ptlrpc_service::srv_request_hpq list which is parallel to
1241  * ptlrpc_service::srv_request_queue list but has a higher priority
1242  * for handling.
1243  *
1244  * \see ptlrpc_server_handle_request().
1245  */
1246 static void ptlrpc_hpreq_reorder_nolock(struct ptlrpc_service *svc,
1247                                         struct ptlrpc_request *req)
1248 {
1249         ENTRY;
1250         LASSERT(svc != NULL);
1251         cfs_spin_lock(&req->rq_lock);
1252         if (req->rq_hp == 0) {
1253                 int opc = lustre_msg_get_opc(req->rq_reqmsg);
1254
1255                 /* Add to the high priority queue. */
1256                 cfs_list_move_tail(&req->rq_list, &svc->srv_request_hpq);
1257                 req->rq_hp = 1;
1258                 if (opc != OBD_PING)
1259                         DEBUG_REQ(D_RPCTRACE, req, "high priority req");
1260         }
1261         cfs_spin_unlock(&req->rq_lock);
1262         EXIT;
1263 }
1264
1265 /**
1266  * \see ptlrpc_hpreq_reorder_nolock
1267  */
1268 void ptlrpc_hpreq_reorder(struct ptlrpc_request *req)
1269 {
1270         struct ptlrpc_service *svc = req->rq_rqbd->rqbd_service;
1271         ENTRY;
1272
1273         cfs_spin_lock(&svc->srv_rq_lock);
1274         /* It may happen that the request is already taken for the processing
1275          * but still in the export list, or the request is not in the request
1276          * queue but in the export list already, do not add it into the
1277          * HP list. */
1278         if (!cfs_list_empty(&req->rq_list))
1279                 ptlrpc_hpreq_reorder_nolock(svc, req);
1280         cfs_spin_unlock(&svc->srv_rq_lock);
1281         EXIT;
1282 }
1283
1284 /** Check if the request is a high priority one. */
1285 static int ptlrpc_server_hpreq_check(struct ptlrpc_service *svc,
1286                                      struct ptlrpc_request *req)
1287 {
1288         ENTRY;
1289
1290         /* Check by request opc. */
1291         if (OBD_PING == lustre_msg_get_opc(req->rq_reqmsg))
1292                 RETURN(1);
1293
1294         RETURN(ptlrpc_hpreq_init(svc, req));
1295 }
1296
1297 /** Check if a request is a high priority one. */
1298 static int ptlrpc_server_request_add(struct ptlrpc_service *svc,
1299                                      struct ptlrpc_request *req)
1300 {
1301         int rc;
1302         ENTRY;
1303
1304         rc = ptlrpc_server_hpreq_check(svc, req);
1305         if (rc < 0)
1306                 RETURN(rc);
1307
1308         cfs_spin_lock(&svc->srv_rq_lock);
1309
1310         if (rc)
1311                 ptlrpc_hpreq_reorder_nolock(svc, req);
1312         else
1313                 cfs_list_add_tail(&req->rq_list,
1314                                   &svc->srv_request_queue);
1315
1316         cfs_spin_unlock(&svc->srv_rq_lock);
1317
1318         RETURN(0);
1319 }
1320
1321 /**
1322  * Allow to handle high priority request
1323  * User can call it w/o any lock but need to hold ptlrpc_service::srv_rq_lock
1324  * to get reliable result
1325  */
1326 static int ptlrpc_server_allow_high(struct ptlrpc_service *svc, int force)
1327 {
1328         if (force)
1329                 return 1;
1330
1331         if (svc->srv_n_active_reqs >= svc->srv_threads_running - 1)
1332                 return 0;
1333
1334         return cfs_list_empty(&svc->srv_request_queue) ||
1335                svc->srv_hpreq_count < svc->srv_hpreq_ratio;
1336 }
1337
1338 static int ptlrpc_server_high_pending(struct ptlrpc_service *svc, int force)
1339 {
1340         return ptlrpc_server_allow_high(svc, force) &&
1341                !cfs_list_empty(&svc->srv_request_hpq);
1342 }
1343
1344 /**
1345  * Only allow normal priority requests on a service that has a high-priority
1346  * queue if forced (i.e. cleanup), if there are other high priority requests
1347  * already being processed (i.e. those threads can service more high-priority
1348  * requests), or if there are enough idle threads that a later thread can do
1349  * a high priority request.
1350  * User can call it w/o any lock but need to hold ptlrpc_service::srv_rq_lock
1351  * to get reliable result
1352  */
1353 static int ptlrpc_server_allow_normal(struct ptlrpc_service *svc, int force)
1354 {
1355 #ifndef __KERNEL__
1356         if (1) /* always allow to handle normal request for liblustre */
1357                 return 1;
1358 #endif
1359         if (force ||
1360             svc->srv_n_active_reqs < svc->srv_threads_running - 2)
1361                 return 1;
1362
1363         if (svc->srv_n_active_reqs >= svc->srv_threads_running - 1)
1364                 return 0;
1365
1366         return svc->srv_n_active_hpreq > 0 ||
1367                svc->srv_ops.so_hpreq_handler == NULL;
1368 }
1369
1370 static int ptlrpc_server_normal_pending(struct ptlrpc_service *svc, int force)
1371 {
1372         return ptlrpc_server_allow_normal(svc, force) &&
1373                !cfs_list_empty(&svc->srv_request_queue);
1374 }
1375
1376 /**
1377  * Returns true if there are requests available in incoming
1378  * request queue for processing and it is allowed to fetch them.
1379  * User can call it w/o any lock but need to hold ptlrpc_service::srv_rq_lock
1380  * to get reliable result
1381  * \see ptlrpc_server_allow_normal
1382  * \see ptlrpc_server_allow high
1383  */
1384 static inline int
1385 ptlrpc_server_request_pending(struct ptlrpc_service *svc, int force)
1386 {
1387         return ptlrpc_server_high_pending(svc, force) ||
1388                ptlrpc_server_normal_pending(svc, force);
1389 }
1390
1391 /**
1392  * Fetch a request for processing from queue of unprocessed requests.
1393  * Favors high-priority requests.
1394  * Returns a pointer to fetched request.
1395  */
1396 static struct ptlrpc_request *
1397 ptlrpc_server_request_get(struct ptlrpc_service *svc, int force)
1398 {
1399         struct ptlrpc_request *req;
1400         ENTRY;
1401
1402         if (ptlrpc_server_high_pending(svc, force)) {
1403                 req = cfs_list_entry(svc->srv_request_hpq.next,
1404                                      struct ptlrpc_request, rq_list);
1405                 svc->srv_hpreq_count++;
1406                 RETURN(req);
1407
1408         }
1409
1410         if (ptlrpc_server_normal_pending(svc, force)) {
1411                 req = cfs_list_entry(svc->srv_request_queue.next,
1412                                      struct ptlrpc_request, rq_list);
1413                 svc->srv_hpreq_count = 0;
1414                 RETURN(req);
1415         }
1416         RETURN(NULL);
1417 }
1418
1419 /**
1420  * Handle freshly incoming reqs, add to timed early reply list,
1421  * pass on to regular request queue.
1422  * All incoming requests pass through here before getting into
1423  * ptlrpc_server_handle_req later on.
1424  */
1425 static int
1426 ptlrpc_server_handle_req_in(struct ptlrpc_service *svc)
1427 {
1428         struct ptlrpc_request *req;
1429         __u32                  deadline;
1430         int                    rc;
1431         ENTRY;
1432
1433         LASSERT(svc);
1434
1435         cfs_spin_lock(&svc->srv_lock);
1436         if (cfs_list_empty(&svc->srv_req_in_queue)) {
1437                 cfs_spin_unlock(&svc->srv_lock);
1438                 RETURN(0);
1439         }
1440
1441         req = cfs_list_entry(svc->srv_req_in_queue.next,
1442                              struct ptlrpc_request, rq_list);
1443         cfs_list_del_init (&req->rq_list);
1444         svc->srv_n_queued_reqs--;
1445         /* Consider this still a "queued" request as far as stats are
1446            concerned */
1447         cfs_spin_unlock(&svc->srv_lock);
1448
1449         /* go through security check/transform */
1450         rc = sptlrpc_svc_unwrap_request(req);
1451         switch (rc) {
1452         case SECSVC_OK:
1453                 break;
1454         case SECSVC_COMPLETE:
1455                 target_send_reply(req, 0, OBD_FAIL_MDS_ALL_REPLY_NET);
1456                 goto err_req;
1457         case SECSVC_DROP:
1458                 goto err_req;
1459         default:
1460                 LBUG();
1461         }
1462
1463         /*
1464          * for null-flavored rpc, msg has been unpacked by sptlrpc, although
1465          * redo it wouldn't be harmful.
1466          */
1467         if (SPTLRPC_FLVR_POLICY(req->rq_flvr.sf_rpc) != SPTLRPC_POLICY_NULL) {
1468                 rc = ptlrpc_unpack_req_msg(req, req->rq_reqlen);
1469                 if (rc != 0) {
1470                         CERROR("error unpacking request: ptl %d from %s "
1471                                "x"LPU64"\n", svc->srv_req_portal,
1472                                libcfs_id2str(req->rq_peer), req->rq_xid);
1473                         goto err_req;
1474                 }
1475         }
1476
1477         rc = lustre_unpack_req_ptlrpc_body(req, MSG_PTLRPC_BODY_OFF);
1478         if (rc) {
1479                 CERROR ("error unpacking ptlrpc body: ptl %d from %s x"
1480                         LPU64"\n", svc->srv_req_portal,
1481                         libcfs_id2str(req->rq_peer), req->rq_xid);
1482                 goto err_req;
1483         }
1484
1485         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_DROP_REQ_OPC) &&
1486             lustre_msg_get_opc(req->rq_reqmsg) == cfs_fail_val) {
1487                 CERROR("drop incoming rpc opc %u, x"LPU64"\n",
1488                        cfs_fail_val, req->rq_xid);
1489                 goto err_req;
1490         }
1491
1492         rc = -EINVAL;
1493         if (lustre_msg_get_type(req->rq_reqmsg) != PTL_RPC_MSG_REQUEST) {
1494                 CERROR("wrong packet type received (type=%u) from %s\n",
1495                        lustre_msg_get_type(req->rq_reqmsg),
1496                        libcfs_id2str(req->rq_peer));
1497                 goto err_req;
1498         }
1499
1500         switch(lustre_msg_get_opc(req->rq_reqmsg)) {
1501         case MDS_WRITEPAGE:
1502         case OST_WRITE:
1503                 req->rq_bulk_write = 1;
1504                 break;
1505         case MDS_READPAGE:
1506         case OST_READ:
1507         case MGS_CONFIG_READ:
1508                 req->rq_bulk_read = 1;
1509                 break;
1510         }
1511
1512         CDEBUG(D_RPCTRACE, "got req x"LPU64"\n", req->rq_xid);
1513
1514         req->rq_export = class_conn2export(
1515                 lustre_msg_get_handle(req->rq_reqmsg));
1516         if (req->rq_export) {
1517                 rc = ptlrpc_check_req(req);
1518                 if (rc == 0) {
1519                         rc = sptlrpc_target_export_check(req->rq_export, req);
1520                         if (rc)
1521                                 DEBUG_REQ(D_ERROR, req, "DROPPING req with "
1522                                           "illegal security flavor,");
1523                 }
1524
1525                 if (rc)
1526                         goto err_req;
1527                 ptlrpc_update_export_timer(req->rq_export, 0);
1528         }
1529
1530         /* req_in handling should/must be fast */
1531         if (cfs_time_current_sec() - req->rq_arrival_time.tv_sec > 5)
1532                 DEBUG_REQ(D_WARNING, req, "Slow req_in handling "CFS_DURATION_T"s",
1533                           cfs_time_sub(cfs_time_current_sec(),
1534                                        req->rq_arrival_time.tv_sec));
1535
1536         /* Set rpc server deadline and add it to the timed list */
1537         deadline = (lustre_msghdr_get_flags(req->rq_reqmsg) &
1538                     MSGHDR_AT_SUPPORT) ?
1539                    /* The max time the client expects us to take */
1540                    lustre_msg_get_timeout(req->rq_reqmsg) : obd_timeout;
1541         req->rq_deadline = req->rq_arrival_time.tv_sec + deadline;
1542         if (unlikely(deadline == 0)) {
1543                 DEBUG_REQ(D_ERROR, req, "Dropping request with 0 timeout");
1544                 goto err_req;
1545         }
1546
1547         ptlrpc_at_add_timed(req);
1548
1549         /* Move it over to the request processing queue */
1550         rc = ptlrpc_server_request_add(svc, req);
1551         if (rc) {
1552                 ptlrpc_hpreq_fini(req);
1553                 GOTO(err_req, rc);
1554         }
1555         cfs_waitq_signal(&svc->srv_waitq);
1556         RETURN(1);
1557
1558 err_req:
1559         cfs_spin_lock(&svc->srv_rq_lock);
1560         svc->srv_n_active_reqs++;
1561         cfs_spin_unlock(&svc->srv_rq_lock);
1562         ptlrpc_server_finish_request(svc, req);
1563
1564         RETURN(1);
1565 }
1566
1567 /**
1568  * Main incoming request handling logic.
1569  * Calls handler function from service to do actual processing.
1570  */
1571 static int
1572 ptlrpc_server_handle_request(struct ptlrpc_service *svc,
1573                              struct ptlrpc_thread *thread)
1574 {
1575         struct obd_export     *export = NULL;
1576         struct ptlrpc_request *request;
1577         struct timeval         work_start;
1578         struct timeval         work_end;
1579         long                   timediff;
1580         int                    rc;
1581         int                    fail_opc = 0;
1582         ENTRY;
1583
1584         LASSERT(svc);
1585
1586         cfs_spin_lock(&svc->srv_rq_lock);
1587 #ifndef __KERNEL__
1588         /* !@%$# liblustre only has 1 thread */
1589         if (cfs_atomic_read(&svc->srv_n_difficult_replies) != 0) {
1590                 cfs_spin_unlock(&svc->srv_rq_lock);
1591                 RETURN(0);
1592         }
1593 #endif
1594         request = ptlrpc_server_request_get(svc, 0);
1595         if  (request == NULL) {
1596                 cfs_spin_unlock(&svc->srv_rq_lock);
1597                 RETURN(0);
1598         }
1599
1600         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT))
1601                 fail_opc = OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT;
1602         else if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT))
1603                 fail_opc = OBD_FAIL_PTLRPC_HPREQ_TIMEOUT;
1604
1605         if (unlikely(fail_opc)) {
1606                 if (request->rq_export && request->rq_ops) {
1607                         cfs_spin_unlock(&svc->srv_rq_lock);
1608                         OBD_FAIL_TIMEOUT(fail_opc, 4);
1609                         cfs_spin_lock(&svc->srv_rq_lock);
1610                         request = ptlrpc_server_request_get(svc, 0);
1611                         if  (request == NULL) {
1612                                 cfs_spin_unlock(&svc->srv_rq_lock);
1613                                 RETURN(0);
1614                         }
1615                 }
1616         }
1617
1618         cfs_list_del_init(&request->rq_list);
1619         svc->srv_n_active_reqs++;
1620         if (request->rq_hp)
1621                 svc->srv_n_active_hpreq++;
1622
1623         cfs_spin_unlock(&svc->srv_rq_lock);
1624
1625         ptlrpc_rqphase_move(request, RQ_PHASE_INTERPRET);
1626
1627         if(OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_DUMP_LOG))
1628                 libcfs_debug_dumplog();
1629
1630         cfs_gettimeofday(&work_start);
1631         timediff = cfs_timeval_sub(&work_start, &request->rq_arrival_time,NULL);
1632         if (likely(svc->srv_stats != NULL)) {
1633                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQWAIT_CNTR,
1634                                     timediff);
1635                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQQDEPTH_CNTR,
1636                                     svc->srv_n_queued_reqs);
1637                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQACTIVE_CNTR,
1638                                     svc->srv_n_active_reqs);
1639                 lprocfs_counter_add(svc->srv_stats, PTLRPC_TIMEOUT,
1640                                     at_get(&svc->srv_at_estimate));
1641         }
1642
1643         rc = lu_context_init(&request->rq_session,
1644                              LCT_SESSION|LCT_REMEMBER|LCT_NOREF);
1645         if (rc) {
1646                 CERROR("Failure to initialize session: %d\n", rc);
1647                 goto out_req;
1648         }
1649         request->rq_session.lc_thread = thread;
1650         request->rq_session.lc_cookie = 0x5;
1651         lu_context_enter(&request->rq_session);
1652
1653         CDEBUG(D_NET, "got req "LPU64"\n", request->rq_xid);
1654
1655         request->rq_svc_thread = thread;
1656         if (thread)
1657                 request->rq_svc_thread->t_env->le_ses = &request->rq_session;
1658
1659         if (likely(request->rq_export)) {
1660                 if (unlikely(ptlrpc_check_req(request)))
1661                         goto put_conn;
1662                 ptlrpc_update_export_timer(request->rq_export, timediff >> 19);
1663                 export = class_export_rpc_get(request->rq_export);
1664         }
1665
1666         /* Discard requests queued for longer than the deadline.
1667            The deadline is increased if we send an early reply. */
1668         if (cfs_time_current_sec() > request->rq_deadline) {
1669                 DEBUG_REQ(D_ERROR, request, "Dropping timed-out request from %s"
1670                           ": deadline "CFS_DURATION_T":"CFS_DURATION_T"s ago\n",
1671                           libcfs_id2str(request->rq_peer),
1672                           cfs_time_sub(request->rq_deadline,
1673                           request->rq_arrival_time.tv_sec),
1674                           cfs_time_sub(cfs_time_current_sec(),
1675                           request->rq_deadline));
1676                 goto put_rpc_export;
1677         }
1678
1679         CDEBUG(D_RPCTRACE, "Handling RPC pname:cluuid+ref:pid:xid:nid:opc "
1680                "%s:%s+%d:%d:x"LPU64":%s:%d\n", cfs_curproc_comm(),
1681                (request->rq_export ?
1682                 (char *)request->rq_export->exp_client_uuid.uuid : "0"),
1683                (request->rq_export ?
1684                 cfs_atomic_read(&request->rq_export->exp_refcount) : -99),
1685                lustre_msg_get_status(request->rq_reqmsg), request->rq_xid,
1686                libcfs_id2str(request->rq_peer),
1687                lustre_msg_get_opc(request->rq_reqmsg));
1688
1689         if (lustre_msg_get_opc(request->rq_reqmsg) != OBD_PING)
1690                 CFS_FAIL_TIMEOUT_MS(OBD_FAIL_PTLRPC_PAUSE_REQ, cfs_fail_val);
1691
1692         rc = svc->srv_ops.so_req_handler(request);
1693
1694         ptlrpc_rqphase_move(request, RQ_PHASE_COMPLETE);
1695
1696 put_rpc_export:
1697         if (export != NULL)
1698                 class_export_rpc_put(export);
1699 put_conn:
1700         lu_context_exit(&request->rq_session);
1701         lu_context_fini(&request->rq_session);
1702
1703         if (unlikely(cfs_time_current_sec() > request->rq_deadline)) {
1704                 DEBUG_REQ(D_WARNING, request, "Request x"LPU64" took longer "
1705                           "than estimated ("CFS_DURATION_T":"CFS_DURATION_T"s);"
1706                           " client may timeout.",
1707                           request->rq_xid, cfs_time_sub(request->rq_deadline,
1708                           request->rq_arrival_time.tv_sec),
1709                           cfs_time_sub(cfs_time_current_sec(),
1710                           request->rq_deadline));
1711         }
1712
1713         cfs_gettimeofday(&work_end);
1714         timediff = cfs_timeval_sub(&work_end, &work_start, NULL);
1715         CDEBUG(D_RPCTRACE, "Handled RPC pname:cluuid+ref:pid:xid:nid:opc "
1716                "%s:%s+%d:%d:x"LPU64":%s:%d Request procesed in "
1717                "%ldus (%ldus total) trans "LPU64" rc %d/%d\n",
1718                 cfs_curproc_comm(),
1719                 (request->rq_export ?
1720                  (char *)request->rq_export->exp_client_uuid.uuid : "0"),
1721                 (request->rq_export ?
1722                  cfs_atomic_read(&request->rq_export->exp_refcount) : -99),
1723                 lustre_msg_get_status(request->rq_reqmsg),
1724                 request->rq_xid,
1725                 libcfs_id2str(request->rq_peer),
1726                 lustre_msg_get_opc(request->rq_reqmsg),
1727                 timediff,
1728                 cfs_timeval_sub(&work_end, &request->rq_arrival_time, NULL),
1729                 (request->rq_repmsg ?
1730                  lustre_msg_get_transno(request->rq_repmsg) :
1731                  request->rq_transno),
1732                 request->rq_status,
1733                 (request->rq_repmsg ?
1734                  lustre_msg_get_status(request->rq_repmsg) : -999));
1735         if (likely(svc->srv_stats != NULL && request->rq_reqmsg != NULL)) {
1736                 __u32 op = lustre_msg_get_opc(request->rq_reqmsg);
1737                 int opc = opcode_offset(op);
1738                 if (opc > 0 && !(op == LDLM_ENQUEUE || op == MDS_REINT)) {
1739                         LASSERT(opc < LUSTRE_MAX_OPCODES);
1740                         lprocfs_counter_add(svc->srv_stats,
1741                                             opc + EXTRA_MAX_OPCODES,
1742                                             timediff);
1743                 }
1744         }
1745         if (unlikely(request->rq_early_count)) {
1746                 DEBUG_REQ(D_ADAPTTO, request,
1747                           "sent %d early replies before finishing in "
1748                           CFS_DURATION_T"s",
1749                           request->rq_early_count,
1750                           cfs_time_sub(work_end.tv_sec,
1751                           request->rq_arrival_time.tv_sec));
1752         }
1753
1754 out_req:
1755         ptlrpc_server_finish_request(svc, request);
1756
1757         RETURN(1);
1758 }
1759
1760 /**
1761  * An internal function to process a single reply state object.
1762  */
1763 static int
1764 ptlrpc_handle_rs (struct ptlrpc_reply_state *rs)
1765 {
1766         struct ptlrpc_service     *svc = rs->rs_service;
1767         struct obd_export         *exp;
1768         int                        nlocks;
1769         int                        been_handled;
1770         ENTRY;
1771
1772         exp = rs->rs_export;
1773
1774         LASSERT (rs->rs_difficult);
1775         LASSERT (rs->rs_scheduled);
1776         LASSERT (cfs_list_empty(&rs->rs_list));
1777
1778         cfs_spin_lock (&exp->exp_lock);
1779         /* Noop if removed already */
1780         cfs_list_del_init (&rs->rs_exp_list);
1781         cfs_spin_unlock (&exp->exp_lock);
1782
1783         /* The disk commit callback holds exp_uncommitted_replies_lock while it
1784          * iterates over newly committed replies, removing them from
1785          * exp_uncommitted_replies.  It then drops this lock and schedules the
1786          * replies it found for handling here.
1787          *
1788          * We can avoid contention for exp_uncommitted_replies_lock between the
1789          * HRT threads and further commit callbacks by checking rs_committed
1790          * which is set in the commit callback while it holds both
1791          * rs_lock and exp_uncommitted_reples.
1792          *
1793          * If we see rs_committed clear, the commit callback _may_ not have
1794          * handled this reply yet and we race with it to grab
1795          * exp_uncommitted_replies_lock before removing the reply from
1796          * exp_uncommitted_replies.  Note that if we lose the race and the
1797          * reply has already been removed, list_del_init() is a noop.
1798          *
1799          * If we see rs_committed set, we know the commit callback is handling,
1800          * or has handled this reply since store reordering might allow us to
1801          * see rs_committed set out of sequence.  But since this is done
1802          * holding rs_lock, we can be sure it has all completed once we hold
1803          * rs_lock, which we do right next.
1804          */
1805         if (!rs->rs_committed) {
1806                 cfs_spin_lock(&exp->exp_uncommitted_replies_lock);
1807                 cfs_list_del_init(&rs->rs_obd_list);
1808                 cfs_spin_unlock(&exp->exp_uncommitted_replies_lock);
1809         }
1810
1811         cfs_spin_lock(&rs->rs_lock);
1812
1813         been_handled = rs->rs_handled;
1814         rs->rs_handled = 1;
1815
1816         nlocks = rs->rs_nlocks;                 /* atomic "steal", but */
1817         rs->rs_nlocks = 0;                      /* locks still on rs_locks! */
1818
1819         if (nlocks == 0 && !been_handled) {
1820                 /* If we see this, we should already have seen the warning
1821                  * in mds_steal_ack_locks()  */
1822                 CWARN("All locks stolen from rs %p x"LPD64".t"LPD64
1823                       " o%d NID %s\n",
1824                       rs,
1825                       rs->rs_xid, rs->rs_transno, rs->rs_opc,
1826                       libcfs_nid2str(exp->exp_connection->c_peer.nid));
1827         }
1828
1829         if ((!been_handled && rs->rs_on_net) || nlocks > 0) {
1830                 cfs_spin_unlock(&rs->rs_lock);
1831
1832                 if (!been_handled && rs->rs_on_net) {
1833                         LNetMDUnlink(rs->rs_md_h);
1834                         /* Ignore return code; we're racing with
1835                          * completion... */
1836                 }
1837
1838                 while (nlocks-- > 0)
1839                         ldlm_lock_decref(&rs->rs_locks[nlocks],
1840                                          rs->rs_modes[nlocks]);
1841
1842                 cfs_spin_lock(&rs->rs_lock);
1843         }
1844
1845         rs->rs_scheduled = 0;
1846
1847         if (!rs->rs_on_net) {
1848                 /* Off the net */
1849                 cfs_spin_unlock(&rs->rs_lock);
1850
1851                 class_export_put (exp);
1852                 rs->rs_export = NULL;
1853                 ptlrpc_rs_decref (rs);
1854                 if (cfs_atomic_dec_and_test(&svc->srv_n_difficult_replies) &&
1855                     svc->srv_is_stopping)
1856                         cfs_waitq_broadcast(&svc->srv_waitq);
1857                 RETURN(1);
1858         }
1859
1860         /* still on the net; callback will schedule */
1861         cfs_spin_unlock(&rs->rs_lock);
1862         RETURN(1);
1863 }
1864
1865 #ifndef __KERNEL__
1866
1867 /**
1868  * Check whether given service has a reply available for processing
1869  * and process it.
1870  *
1871  * \param svc a ptlrpc service
1872  * \retval 0 no replies processed
1873  * \retval 1 one reply processed
1874  */
1875 static int
1876 ptlrpc_server_handle_reply(struct ptlrpc_service *svc)
1877 {
1878         struct ptlrpc_reply_state *rs = NULL;
1879         ENTRY;
1880
1881         cfs_spin_lock(&svc->srv_rs_lock);
1882         if (!cfs_list_empty(&svc->srv_reply_queue)) {
1883                 rs = cfs_list_entry(svc->srv_reply_queue.prev,
1884                                     struct ptlrpc_reply_state,
1885                                     rs_list);
1886                 cfs_list_del_init(&rs->rs_list);
1887         }
1888         cfs_spin_unlock(&svc->srv_rs_lock);
1889         if (rs != NULL)
1890                 ptlrpc_handle_rs(rs);
1891         RETURN(rs != NULL);
1892 }
1893
1894 /* FIXME make use of timeout later */
1895 int
1896 liblustre_check_services (void *arg)
1897 {
1898         int  did_something = 0;
1899         int  rc;
1900         cfs_list_t *tmp, *nxt;
1901         ENTRY;
1902
1903         /* I'm relying on being single threaded, not to have to lock
1904          * ptlrpc_all_services etc */
1905         cfs_list_for_each_safe (tmp, nxt, &ptlrpc_all_services) {
1906                 struct ptlrpc_service *svc =
1907                         cfs_list_entry (tmp, struct ptlrpc_service, srv_list);
1908
1909                 if (svc->srv_threads_running != 0)     /* I've recursed */
1910                         continue;
1911
1912                 /* service threads can block for bulk, so this limits us
1913                  * (arbitrarily) to recursing 1 stack frame per service.
1914                  * Note that the problem with recursion is that we have to
1915                  * unwind completely before our caller can resume. */
1916
1917                 svc->srv_threads_running++;
1918
1919                 do {
1920                         rc = ptlrpc_server_handle_req_in(svc);
1921                         rc |= ptlrpc_server_handle_reply(svc);
1922                         rc |= ptlrpc_at_check_timed(svc);
1923                         rc |= ptlrpc_server_handle_request(svc, NULL);
1924                         rc |= (ptlrpc_server_post_idle_rqbds(svc) > 0);
1925                         did_something |= rc;
1926                 } while (rc);
1927
1928                 svc->srv_threads_running--;
1929         }
1930
1931         RETURN(did_something);
1932 }
1933 #define ptlrpc_stop_all_threads(s) do {} while (0)
1934
1935 #else /* __KERNEL__ */
1936
1937 static void
1938 ptlrpc_check_rqbd_pool(struct ptlrpc_service *svc)
1939 {
1940         int avail = svc->srv_nrqbd_receiving;
1941         int low_water = test_req_buffer_pressure ? 0 :
1942                         svc->srv_nbuf_per_group / 2;
1943
1944         /* NB I'm not locking; just looking. */
1945
1946         /* CAVEAT EMPTOR: We might be allocating buffers here because we've
1947          * allowed the request history to grow out of control.  We could put a
1948          * sanity check on that here and cull some history if we need the
1949          * space. */
1950
1951         if (avail <= low_water)
1952                 ptlrpc_grow_req_bufs(svc);
1953
1954         if (svc->srv_stats)
1955                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQBUF_AVAIL_CNTR,
1956                                     avail);
1957 }
1958
1959 static int
1960 ptlrpc_retry_rqbds(void *arg)
1961 {
1962         struct ptlrpc_service *svc = (struct ptlrpc_service *)arg;
1963
1964         svc->srv_rqbd_timeout = 0;
1965         return (-ETIMEDOUT);
1966 }
1967
1968 static inline int
1969 ptlrpc_threads_enough(struct ptlrpc_service *svc)
1970 {
1971         return svc->srv_n_active_reqs <
1972                svc->srv_threads_running - 1 -
1973                (svc->srv_ops.so_hpreq_handler != NULL);
1974 }
1975
1976 /**
1977  * allowed to create more threads
1978  * user can call it w/o any lock but need to hold ptlrpc_service::srv_lock to
1979  * get reliable result
1980  */
1981 static inline int
1982 ptlrpc_threads_increasable(struct ptlrpc_service *svc)
1983 {
1984         return svc->srv_threads_running +
1985                svc->srv_threads_starting < svc->srv_threads_max;
1986 }
1987
1988 /**
1989  * too many requests and allowed to create more threads
1990  */
1991 static inline int
1992 ptlrpc_threads_need_create(struct ptlrpc_service *svc)
1993 {
1994         return !ptlrpc_threads_enough(svc) && ptlrpc_threads_increasable(svc);
1995 }
1996
1997 static inline int
1998 ptlrpc_thread_stopping(struct ptlrpc_thread *thread)
1999 {
2000         return thread_is_stopping(thread) ||
2001                thread->t_svc->srv_is_stopping;
2002 }
2003
2004 static inline int
2005 ptlrpc_rqbd_pending(struct ptlrpc_service *svc)
2006 {
2007         return !cfs_list_empty(&svc->srv_idle_rqbds) &&
2008                svc->srv_rqbd_timeout == 0;
2009 }
2010
2011 static inline int
2012 ptlrpc_at_check(struct ptlrpc_service *svc)
2013 {
2014         return svc->srv_at_check;
2015 }
2016
2017 /**
2018  * requests wait on preprocessing
2019  * user can call it w/o any lock but need to hold ptlrpc_service::srv_lock to
2020  * get reliable result
2021  */
2022 static inline int
2023 ptlrpc_server_request_waiting(struct ptlrpc_service *svc)
2024 {
2025         return !cfs_list_empty(&svc->srv_req_in_queue);
2026 }
2027
2028 static __attribute__((__noinline__)) int
2029 ptlrpc_wait_event(struct ptlrpc_service *svc,
2030                   struct ptlrpc_thread *thread)
2031 {
2032         /* Don't exit while there are replies to be handled */
2033         struct l_wait_info lwi = LWI_TIMEOUT(svc->srv_rqbd_timeout,
2034                                              ptlrpc_retry_rqbds, svc);
2035
2036         lc_watchdog_disable(thread->t_watchdog);
2037
2038         cfs_cond_resched();
2039
2040         l_wait_event_exclusive_head(svc->srv_waitq,
2041                                ptlrpc_thread_stopping(thread) ||
2042                                ptlrpc_server_request_waiting(svc) ||
2043                                ptlrpc_server_request_pending(svc, 0) ||
2044                                ptlrpc_rqbd_pending(svc) ||
2045                                ptlrpc_at_check(svc), &lwi);
2046
2047         if (ptlrpc_thread_stopping(thread))
2048                 return -EINTR;
2049
2050         lc_watchdog_touch(thread->t_watchdog, CFS_GET_TIMEOUT(svc));
2051
2052         return 0;
2053 }
2054
2055 /**
2056  * Main thread body for service threads.
2057  * Waits in a loop waiting for new requests to process to appear.
2058  * Every time an incoming requests is added to its queue, a waitq
2059  * is woken up and one of the threads will handle it.
2060  */
2061 static int ptlrpc_main(void *arg)
2062 {
2063         struct ptlrpc_svc_data *data = (struct ptlrpc_svc_data *)arg;
2064         struct ptlrpc_service  *svc = data->svc;
2065         struct ptlrpc_thread   *thread = data->thread;
2066         struct ptlrpc_reply_state *rs;
2067 #ifdef WITH_GROUP_INFO
2068         cfs_group_info_t *ginfo = NULL;
2069 #endif
2070         struct lu_env *env;
2071         int counter = 0, rc = 0;
2072         ENTRY;
2073
2074         thread->t_pid = cfs_curproc_pid();
2075         cfs_daemonize_ctxt(data->name);
2076
2077 #if defined(HAVE_NODE_TO_CPUMASK) && defined(CONFIG_NUMA)
2078         /* we need to do this before any per-thread allocation is done so that
2079          * we get the per-thread allocations on local node.  bug 7342 */
2080         if (svc->srv_cpu_affinity) {
2081                 int cpu, num_cpu;
2082
2083                 for (cpu = 0, num_cpu = 0; cpu < cfs_num_possible_cpus();
2084                      cpu++) {
2085                         if (!cpu_online(cpu))
2086                                 continue;
2087                         if (num_cpu == thread->t_id % cfs_num_online_cpus())
2088                                 break;
2089                         num_cpu++;
2090                 }
2091                 cfs_set_cpus_allowed(cfs_current(),
2092                                      node_to_cpumask(cpu_to_node(cpu)));
2093         }
2094 #endif
2095
2096 #ifdef WITH_GROUP_INFO
2097         ginfo = cfs_groups_alloc(0);
2098         if (!ginfo) {
2099                 rc = -ENOMEM;
2100                 goto out;
2101         }
2102
2103         cfs_set_current_groups(ginfo);
2104         cfs_put_group_info(ginfo);
2105 #endif
2106
2107         if (svc->srv_ops.so_thr_init != NULL) {
2108                 rc = svc->srv_ops.so_thr_init(thread);
2109                 if (rc)
2110                         goto out;
2111         }
2112
2113         OBD_ALLOC_PTR(env);
2114         if (env == NULL) {
2115                 rc = -ENOMEM;
2116                 goto out_srv_fini;
2117         }
2118
2119         rc = lu_context_init(&env->le_ctx,
2120                              svc->srv_ctx_tags|LCT_REMEMBER|LCT_NOREF);
2121         if (rc)
2122                 goto out_srv_fini;
2123
2124         thread->t_env = env;
2125         env->le_ctx.lc_thread = thread;
2126         env->le_ctx.lc_cookie = 0x6;
2127
2128         /* Alloc reply state structure for this one */
2129         OBD_ALLOC_LARGE(rs, svc->srv_max_reply_size);
2130         if (!rs) {
2131                 rc = -ENOMEM;
2132                 goto out_srv_fini;
2133         }
2134
2135         cfs_spin_lock(&svc->srv_lock);
2136
2137         LASSERT(thread_is_starting(thread));
2138         thread_clear_flags(thread, SVC_STARTING);
2139         svc->srv_threads_starting--;
2140
2141         /* SVC_STOPPING may already be set here if someone else is trying
2142          * to stop the service while this new thread has been dynamically
2143          * forked. We still set SVC_RUNNING to let our creator know that
2144          * we are now running, however we will exit as soon as possible */
2145         thread_add_flags(thread, SVC_RUNNING);
2146         svc->srv_threads_running++;
2147         cfs_spin_unlock(&svc->srv_lock);
2148
2149         /*
2150          * wake up our creator. Note: @data is invalid after this point,
2151          * because it's allocated on ptlrpc_start_thread() stack.
2152          */
2153         cfs_waitq_signal(&thread->t_ctl_waitq);
2154
2155         thread->t_watchdog = lc_watchdog_add(CFS_GET_TIMEOUT(svc), NULL, NULL);
2156
2157         cfs_spin_lock(&svc->srv_rs_lock);
2158         cfs_list_add(&rs->rs_list, &svc->srv_free_rs_list);
2159         cfs_waitq_signal(&svc->srv_free_rs_waitq);
2160         cfs_spin_unlock(&svc->srv_rs_lock);
2161
2162         CDEBUG(D_NET, "service thread %d (#%d) started\n", thread->t_id,
2163                svc->srv_threads_running);
2164
2165         /* XXX maintain a list of all managed devices: insert here */
2166         while (!ptlrpc_thread_stopping(thread)) {
2167                 if (ptlrpc_wait_event(svc, thread))
2168                         break;
2169
2170                 ptlrpc_check_rqbd_pool(svc);
2171
2172                 if (ptlrpc_threads_need_create(svc)) {
2173                         /* Ignore return code - we tried... */
2174                         ptlrpc_start_thread(svc);
2175                 }
2176
2177                 /* Process all incoming reqs before handling any */
2178                 if (ptlrpc_server_request_waiting(svc)) {
2179                         ptlrpc_server_handle_req_in(svc);
2180                         /* but limit ourselves in case of flood */
2181                         if (counter++ < 100)
2182                                 continue;
2183                         counter = 0;
2184                 }
2185
2186                 if (ptlrpc_at_check(svc))
2187                         ptlrpc_at_check_timed(svc);
2188
2189                 if (ptlrpc_server_request_pending(svc, 0)) {
2190                         lu_context_enter(&env->le_ctx);
2191                         ptlrpc_server_handle_request(svc, thread);
2192                         lu_context_exit(&env->le_ctx);
2193                 }
2194
2195                 if (ptlrpc_rqbd_pending(svc) &&
2196                     ptlrpc_server_post_idle_rqbds(svc) < 0) {
2197                         /* I just failed to repost request buffers.
2198                          * Wait for a timeout (unless something else
2199                          * happens) before I try again */
2200                         svc->srv_rqbd_timeout = cfs_time_seconds(1)/10;
2201                         CDEBUG(D_RPCTRACE,"Posted buffers: %d\n",
2202                                svc->srv_nrqbd_receiving);
2203                 }
2204         }
2205
2206         lc_watchdog_delete(thread->t_watchdog);
2207         thread->t_watchdog = NULL;
2208
2209 out_srv_fini:
2210         /*
2211          * deconstruct service specific state created by ptlrpc_start_thread()
2212          */
2213         if (svc->srv_ops.so_thr_done != NULL)
2214                 svc->srv_ops.so_thr_done(thread);
2215
2216         if (env != NULL) {
2217                 lu_context_fini(&env->le_ctx);
2218                 OBD_FREE_PTR(env);
2219         }
2220 out:
2221         CDEBUG(D_RPCTRACE, "service thread [ %p : %u ] %d exiting: rc %d\n",
2222                thread, thread->t_pid, thread->t_id, rc);
2223
2224         cfs_spin_lock(&svc->srv_lock);
2225         if (thread_test_and_clear_flags(thread, SVC_STARTING))
2226                 svc->srv_threads_starting--;
2227
2228         if (thread_test_and_clear_flags(thread, SVC_RUNNING))
2229                 /* must know immediately */
2230                 svc->srv_threads_running--;
2231
2232         thread->t_id    = rc;
2233         thread_add_flags(thread, SVC_STOPPED);
2234
2235         cfs_waitq_signal(&thread->t_ctl_waitq);
2236         cfs_spin_unlock(&svc->srv_lock);
2237
2238         return rc;
2239 }
2240
2241 struct ptlrpc_hr_args {
2242         int                       thread_index;
2243         int                       cpu_index;
2244         struct ptlrpc_hr_service *hrs;
2245 };
2246
2247 static int hrt_dont_sleep(struct ptlrpc_hr_thread *t,
2248                           cfs_list_t *replies)
2249 {
2250         int result;
2251
2252         cfs_spin_lock(&t->hrt_lock);
2253         cfs_list_splice_init(&t->hrt_queue, replies);
2254         result = cfs_test_bit(HRT_STOPPING, &t->hrt_flags) ||
2255                 !cfs_list_empty(replies);
2256         cfs_spin_unlock(&t->hrt_lock);
2257         return result;
2258 }
2259
2260 /**
2261  * Main body of "handle reply" function.
2262  * It processes acked reply states
2263  */
2264 static int ptlrpc_hr_main(void *arg)
2265 {
2266         struct ptlrpc_hr_args * hr_args = arg;
2267         struct ptlrpc_hr_service *hr = hr_args->hrs;
2268         struct ptlrpc_hr_thread *t = &hr->hr_threads[hr_args->thread_index];
2269         char threadname[20];
2270         CFS_LIST_HEAD(replies);
2271
2272         snprintf(threadname, sizeof(threadname),
2273                  "ptlrpc_hr_%d", hr_args->thread_index);
2274
2275         cfs_daemonize_ctxt(threadname);
2276 #if defined(CONFIG_NUMA) && defined(HAVE_NODE_TO_CPUMASK)
2277         cfs_set_cpus_allowed(cfs_current(),
2278                              node_to_cpumask(cpu_to_node(hr_args->cpu_index)));
2279 #endif
2280         cfs_set_bit(HRT_RUNNING, &t->hrt_flags);
2281         cfs_waitq_signal(&t->hrt_wait);
2282
2283         while (!cfs_test_bit(HRT_STOPPING, &t->hrt_flags)) {
2284
2285                 l_wait_condition(t->hrt_wait, hrt_dont_sleep(t, &replies));
2286                 while (!cfs_list_empty(&replies)) {
2287                         struct ptlrpc_reply_state *rs;
2288
2289                         rs = cfs_list_entry(replies.prev,
2290                                             struct ptlrpc_reply_state,
2291                                             rs_list);
2292                         cfs_list_del_init(&rs->rs_list);
2293                         ptlrpc_handle_rs(rs);
2294                 }
2295         }
2296
2297         cfs_clear_bit(HRT_RUNNING, &t->hrt_flags);
2298         cfs_complete(&t->hrt_completion);
2299
2300         return 0;
2301 }
2302
2303 static int ptlrpc_start_hr_thread(struct ptlrpc_hr_service *hr, int n, int cpu)
2304 {
2305         struct ptlrpc_hr_thread *t = &hr->hr_threads[n];
2306         struct ptlrpc_hr_args args;
2307         int rc;
2308         ENTRY;
2309
2310         args.thread_index = n;
2311         args.cpu_index = cpu;
2312         args.hrs = hr;
2313
2314         rc = cfs_create_thread(ptlrpc_hr_main, (void*)&args, CFS_DAEMON_FLAGS);
2315         if (rc < 0) {
2316                 cfs_complete(&t->hrt_completion);
2317                 GOTO(out, rc);
2318         }
2319         l_wait_condition(t->hrt_wait, cfs_test_bit(HRT_RUNNING, &t->hrt_flags));
2320         RETURN(0);
2321  out:
2322         return rc;
2323 }
2324
2325 static void ptlrpc_stop_hr_thread(struct ptlrpc_hr_thread *t)
2326 {
2327         ENTRY;
2328
2329         cfs_set_bit(HRT_STOPPING, &t->hrt_flags);
2330         cfs_waitq_signal(&t->hrt_wait);
2331         cfs_wait_for_completion(&t->hrt_completion);
2332
2333         EXIT;
2334 }
2335
2336 static void ptlrpc_stop_hr_threads(struct ptlrpc_hr_service *hrs)
2337 {
2338         int n;
2339         ENTRY;
2340
2341         for (n = 0; n < hrs->hr_n_threads; n++)
2342                 ptlrpc_stop_hr_thread(&hrs->hr_threads[n]);
2343
2344         EXIT;
2345 }
2346
2347 static int ptlrpc_start_hr_threads(struct ptlrpc_hr_service *hr)
2348 {
2349         int rc = -ENOMEM;
2350         int n, cpu, threads_started = 0;
2351         ENTRY;
2352
2353         LASSERT(hr != NULL);
2354         LASSERT(hr->hr_n_threads > 0);
2355
2356         for (n = 0, cpu = 0; n < hr->hr_n_threads; n++) {
2357 #if defined(CONFIG_SMP) && defined(HAVE_NODE_TO_CPUMASK)
2358                 while (!cpu_online(cpu)) {
2359                         cpu++;
2360                         if (cpu >= cfs_num_possible_cpus())
2361                                 cpu = 0;
2362                 }
2363 #endif
2364                 rc = ptlrpc_start_hr_thread(hr, n, cpu);
2365                 if (rc != 0)
2366                         break;
2367                 threads_started++;
2368                 cpu++;
2369         }
2370         if (threads_started == 0) {
2371                 CERROR("No reply handling threads started\n");
2372                 RETURN(-ESRCH);
2373         }
2374         if (threads_started < hr->hr_n_threads) {
2375                 CWARN("Started only %d reply handling threads from %d\n",
2376                       threads_started, hr->hr_n_threads);
2377                 hr->hr_n_threads = threads_started;
2378         }
2379         RETURN(0);
2380 }
2381
2382 static void ptlrpc_stop_thread(struct ptlrpc_service *svc,
2383                                struct ptlrpc_thread *thread)
2384 {
2385         struct l_wait_info lwi = { 0 };
2386         ENTRY;
2387
2388         CDEBUG(D_RPCTRACE, "Stopping thread [ %p : %u ]\n",
2389                thread, thread->t_pid);
2390
2391         cfs_spin_lock(&svc->srv_lock);
2392         /* let the thread know that we would like it to stop asap */
2393         thread_add_flags(thread, SVC_STOPPING);
2394         cfs_spin_unlock(&svc->srv_lock);
2395
2396         cfs_waitq_broadcast(&svc->srv_waitq);
2397         l_wait_event(thread->t_ctl_waitq,
2398                      thread_is_stopped(thread), &lwi);
2399
2400         cfs_spin_lock(&svc->srv_lock);
2401         cfs_list_del(&thread->t_link);
2402         cfs_spin_unlock(&svc->srv_lock);
2403
2404         OBD_FREE_PTR(thread);
2405         EXIT;
2406 }
2407
2408 /**
2409  * Stops all threads of a particular service \a svc
2410  */
2411 void ptlrpc_stop_all_threads(struct ptlrpc_service *svc)
2412 {
2413         struct ptlrpc_thread *thread;
2414         ENTRY;
2415
2416         cfs_spin_lock(&svc->srv_lock);
2417         while (!cfs_list_empty(&svc->srv_threads)) {
2418                 thread = cfs_list_entry(svc->srv_threads.next,
2419                                         struct ptlrpc_thread, t_link);
2420
2421                 cfs_spin_unlock(&svc->srv_lock);
2422                 ptlrpc_stop_thread(svc, thread);
2423                 cfs_spin_lock(&svc->srv_lock);
2424         }
2425
2426         cfs_spin_unlock(&svc->srv_lock);
2427         EXIT;
2428 }
2429
2430 int ptlrpc_start_threads(struct ptlrpc_service *svc)
2431 {
2432         int i, rc = 0;
2433         ENTRY;
2434
2435         /* We require 2 threads min - see note in
2436            ptlrpc_server_handle_request */
2437         LASSERT(svc->srv_threads_min >= 2);
2438         for (i = 0; i < svc->srv_threads_min; i++) {
2439                 rc = ptlrpc_start_thread(svc);
2440                 /* We have enough threads, don't start more.  b=15759 */
2441                 if (rc == -EMFILE) {
2442                         rc = 0;
2443                         break;
2444                 }
2445                 if (rc) {
2446                         CERROR("cannot start %s thread #%d: rc %d\n",
2447                                svc->srv_thread_name, i, rc);
2448                         ptlrpc_stop_all_threads(svc);
2449                         break;
2450                 }
2451         }
2452         RETURN(rc);
2453 }
2454
2455 int ptlrpc_start_thread(struct ptlrpc_service *svc)
2456 {
2457         struct l_wait_info lwi = { 0 };
2458         struct ptlrpc_svc_data d;
2459         struct ptlrpc_thread *thread;
2460         char name[32];
2461         int rc;
2462         ENTRY;
2463
2464         CDEBUG(D_RPCTRACE, "%s started %d min %d max %d running %d\n",
2465                svc->srv_name, svc->srv_threads_running, svc->srv_threads_min,
2466                svc->srv_threads_max, svc->srv_threads_running);
2467
2468         if (unlikely(svc->srv_is_stopping))
2469                 RETURN(-ESRCH);
2470
2471         if (!ptlrpc_threads_increasable(svc) ||
2472             (OBD_FAIL_CHECK(OBD_FAIL_TGT_TOOMANY_THREADS) &&
2473              svc->srv_threads_running == svc->srv_threads_min - 1))
2474                 RETURN(-EMFILE);
2475
2476         OBD_ALLOC_PTR(thread);
2477         if (thread == NULL)
2478                 RETURN(-ENOMEM);
2479         cfs_waitq_init(&thread->t_ctl_waitq);
2480
2481         cfs_spin_lock(&svc->srv_lock);
2482         if (!ptlrpc_threads_increasable(svc)) {
2483                 cfs_spin_unlock(&svc->srv_lock);
2484                 OBD_FREE_PTR(thread);
2485                 RETURN(-EMFILE);
2486         }
2487
2488         svc->srv_threads_starting++;
2489         thread->t_id    = svc->srv_threads_next_id++;
2490         thread_add_flags(thread, SVC_STARTING);
2491         thread->t_svc   = svc;
2492
2493         cfs_list_add(&thread->t_link, &svc->srv_threads);
2494         cfs_spin_unlock(&svc->srv_lock);
2495
2496         sprintf(name, "%s_%02d", svc->srv_thread_name, thread->t_id);
2497         d.svc = svc;
2498         d.name = name;
2499         d.thread = thread;
2500
2501         CDEBUG(D_RPCTRACE, "starting thread '%s'\n", name);
2502
2503         /* CLONE_VM and CLONE_FILES just avoid a needless copy, because we
2504          * just drop the VM and FILES in cfs_daemonize_ctxt() right away.
2505          */
2506         rc = cfs_create_thread(ptlrpc_main, &d, CFS_DAEMON_FLAGS);
2507         if (rc < 0) {
2508                 CERROR("cannot start thread '%s': rc %d\n", name, rc);
2509
2510                 cfs_spin_lock(&svc->srv_lock);
2511                 cfs_list_del(&thread->t_link);
2512                 --svc->srv_threads_starting;
2513                 cfs_spin_unlock(&svc->srv_lock);
2514
2515                 OBD_FREE(thread, sizeof(*thread));
2516                 RETURN(rc);
2517         }
2518         l_wait_event(thread->t_ctl_waitq,
2519                      thread_is_running(thread) || thread_is_stopped(thread),
2520                      &lwi);
2521
2522         rc = thread_is_stopped(thread) ? thread->t_id : 0;
2523         RETURN(rc);
2524 }
2525
2526
2527 int ptlrpc_hr_init(void)
2528 {
2529         int i;
2530         int n_cpus = cfs_num_online_cpus();
2531         struct ptlrpc_hr_service *hr;
2532         int size;
2533         int rc;
2534         ENTRY;
2535
2536         LASSERT(ptlrpc_hr == NULL);
2537
2538         size = offsetof(struct ptlrpc_hr_service, hr_threads[n_cpus]);
2539         OBD_ALLOC(hr, size);
2540         if (hr == NULL)
2541                 RETURN(-ENOMEM);
2542         for (i = 0; i < n_cpus; i++) {
2543                 struct ptlrpc_hr_thread *t = &hr->hr_threads[i];
2544
2545                 cfs_spin_lock_init(&t->hrt_lock);
2546                 cfs_waitq_init(&t->hrt_wait);
2547                 CFS_INIT_LIST_HEAD(&t->hrt_queue);
2548                 cfs_init_completion(&t->hrt_completion);
2549         }
2550         hr->hr_n_threads = n_cpus;
2551         hr->hr_size = size;
2552         ptlrpc_hr = hr;
2553
2554         rc = ptlrpc_start_hr_threads(hr);
2555         if (rc) {
2556                 OBD_FREE(hr, hr->hr_size);
2557                 ptlrpc_hr = NULL;
2558         }
2559         RETURN(rc);
2560 }
2561
2562 void ptlrpc_hr_fini(void)
2563 {
2564         if (ptlrpc_hr != NULL) {
2565                 ptlrpc_stop_hr_threads(ptlrpc_hr);
2566                 OBD_FREE(ptlrpc_hr, ptlrpc_hr->hr_size);
2567                 ptlrpc_hr = NULL;
2568         }
2569 }
2570
2571 #endif /* __KERNEL__ */
2572
2573 /**
2574  * Wait until all already scheduled replies are processed.
2575  */
2576 static void ptlrpc_wait_replies(struct ptlrpc_service *svc)
2577 {
2578         while (1) {
2579                 int rc;
2580                 struct l_wait_info lwi = LWI_TIMEOUT(cfs_time_seconds(10),
2581                                                      NULL, NULL);
2582                 rc = l_wait_event(svc->srv_waitq, cfs_atomic_read(&svc-> \
2583                                   srv_n_difficult_replies) == 0,
2584                                   &lwi);
2585                 if (rc == 0)
2586                         break;
2587                 CWARN("Unexpectedly long timeout %p\n", svc);
2588         }
2589 }
2590
2591 int ptlrpc_unregister_service(struct ptlrpc_service *service)
2592 {
2593         int                   rc;
2594         struct l_wait_info    lwi;
2595         cfs_list_t           *tmp;
2596         struct ptlrpc_reply_state *rs, *t;
2597         struct ptlrpc_at_array *array = &service->srv_at_array;
2598         ENTRY;
2599
2600         service->srv_is_stopping = 1;
2601         cfs_timer_disarm(&service->srv_at_timer);
2602
2603         ptlrpc_stop_all_threads(service);
2604         LASSERT(cfs_list_empty(&service->srv_threads));
2605
2606         cfs_spin_lock (&ptlrpc_all_services_lock);
2607         cfs_list_del_init (&service->srv_list);
2608         cfs_spin_unlock (&ptlrpc_all_services_lock);
2609
2610         ptlrpc_lprocfs_unregister_service(service);
2611
2612         /* All history will be culled when the next request buffer is
2613          * freed */
2614         service->srv_max_history_rqbds = 0;
2615
2616         CDEBUG(D_NET, "%s: tearing down\n", service->srv_name);
2617
2618         rc = LNetClearLazyPortal(service->srv_req_portal);
2619         LASSERT (rc == 0);
2620
2621         /* Unlink all the request buffers.  This forces a 'final' event with
2622          * its 'unlink' flag set for each posted rqbd */
2623         cfs_list_for_each(tmp, &service->srv_active_rqbds) {
2624                 struct ptlrpc_request_buffer_desc *rqbd =
2625                         cfs_list_entry(tmp, struct ptlrpc_request_buffer_desc,
2626                                        rqbd_list);
2627
2628                 rc = LNetMDUnlink(rqbd->rqbd_md_h);
2629                 LASSERT (rc == 0 || rc == -ENOENT);
2630         }
2631
2632         /* Wait for the network to release any buffers it's currently
2633          * filling */
2634         for (;;) {
2635                 cfs_spin_lock(&service->srv_lock);
2636                 rc = service->srv_nrqbd_receiving;
2637                 cfs_spin_unlock(&service->srv_lock);
2638
2639                 if (rc == 0)
2640                         break;
2641
2642                 /* Network access will complete in finite time but the HUGE
2643                  * timeout lets us CWARN for visibility of sluggish NALs */
2644                 lwi = LWI_TIMEOUT_INTERVAL(cfs_time_seconds(LONG_UNLINK),
2645                                            cfs_time_seconds(1), NULL, NULL);
2646                 rc = l_wait_event(service->srv_waitq,
2647                                   service->srv_nrqbd_receiving == 0,
2648                                   &lwi);
2649                 if (rc == -ETIMEDOUT)
2650                         CWARN("Service %s waiting for request buffers\n",
2651                               service->srv_name);
2652         }
2653
2654         /* schedule all outstanding replies to terminate them */
2655         cfs_spin_lock(&service->srv_rs_lock);
2656         while (!cfs_list_empty(&service->srv_active_replies)) {
2657                 struct ptlrpc_reply_state *rs =
2658                         cfs_list_entry(service->srv_active_replies.next,
2659                                        struct ptlrpc_reply_state, rs_list);
2660                 cfs_spin_lock(&rs->rs_lock);
2661                 ptlrpc_schedule_difficult_reply(rs);
2662                 cfs_spin_unlock(&rs->rs_lock);
2663         }
2664         cfs_spin_unlock(&service->srv_rs_lock);
2665
2666         /* purge the request queue.  NB No new replies (rqbds all unlinked)
2667          * and no service threads, so I'm the only thread noodling the
2668          * request queue now */
2669         while (!cfs_list_empty(&service->srv_req_in_queue)) {
2670                 struct ptlrpc_request *req =
2671                         cfs_list_entry(service->srv_req_in_queue.next,
2672                                        struct ptlrpc_request,
2673                                        rq_list);
2674
2675                 cfs_list_del(&req->rq_list);
2676                 service->srv_n_queued_reqs--;
2677                 service->srv_n_active_reqs++;
2678                 ptlrpc_server_finish_request(service, req);
2679         }
2680         while (ptlrpc_server_request_pending(service, 1)) {
2681                 struct ptlrpc_request *req;
2682
2683                 req = ptlrpc_server_request_get(service, 1);
2684                 cfs_list_del(&req->rq_list);
2685                 service->srv_n_active_reqs++;
2686                 ptlrpc_server_finish_request(service, req);
2687         }
2688         LASSERT(service->srv_n_queued_reqs == 0);
2689         LASSERT(service->srv_n_active_reqs == 0);
2690         LASSERT(service->srv_n_history_rqbds == 0);
2691         LASSERT(cfs_list_empty(&service->srv_active_rqbds));
2692
2693         /* Now free all the request buffers since nothing references them
2694          * any more... */
2695         while (!cfs_list_empty(&service->srv_idle_rqbds)) {
2696                 struct ptlrpc_request_buffer_desc *rqbd =
2697                         cfs_list_entry(service->srv_idle_rqbds.next,
2698                                        struct ptlrpc_request_buffer_desc,
2699                                        rqbd_list);
2700
2701                 ptlrpc_free_rqbd(rqbd);
2702         }
2703
2704         ptlrpc_wait_replies(service);
2705
2706         cfs_list_for_each_entry_safe(rs, t, &service->srv_free_rs_list,
2707                                      rs_list) {
2708                 cfs_list_del(&rs->rs_list);
2709                 OBD_FREE_LARGE(rs, service->srv_max_reply_size);
2710         }
2711
2712         /* In case somebody rearmed this in the meantime */
2713         cfs_timer_disarm(&service->srv_at_timer);
2714
2715         if (array->paa_reqs_array != NULL) {
2716                 OBD_FREE(array->paa_reqs_array,
2717                          sizeof(cfs_list_t) * array->paa_size);
2718                 array->paa_reqs_array = NULL;
2719         }
2720
2721         if (array->paa_reqs_count != NULL) {
2722                 OBD_FREE(array->paa_reqs_count,
2723                          sizeof(__u32) * array->paa_size);
2724                 array->paa_reqs_count= NULL;
2725         }
2726
2727         OBD_FREE_PTR(service);
2728         RETURN(0);
2729 }
2730
2731 /**
2732  * Returns 0 if the service is healthy.
2733  *
2734  * Right now, it just checks to make sure that requests aren't languishing
2735  * in the queue.  We'll use this health check to govern whether a node needs
2736  * to be shot, so it's intentionally non-aggressive. */
2737 int ptlrpc_service_health_check(struct ptlrpc_service *svc)
2738 {
2739         struct ptlrpc_request *request;
2740         struct timeval         right_now;
2741         long                   timediff;
2742
2743         if (svc == NULL)
2744                 return 0;
2745
2746         cfs_gettimeofday(&right_now);
2747
2748         cfs_spin_lock(&svc->srv_rq_lock);
2749         if (!ptlrpc_server_request_pending(svc, 1)) {
2750                 cfs_spin_unlock(&svc->srv_rq_lock);
2751                 return 0;
2752         }
2753
2754         /* How long has the next entry been waiting? */
2755         if (cfs_list_empty(&svc->srv_request_queue))
2756                 request = cfs_list_entry(svc->srv_request_hpq.next,
2757                                          struct ptlrpc_request, rq_list);
2758         else
2759                 request = cfs_list_entry(svc->srv_request_queue.next,
2760                                          struct ptlrpc_request, rq_list);
2761         timediff = cfs_timeval_sub(&right_now, &request->rq_arrival_time, NULL);
2762         cfs_spin_unlock(&svc->srv_rq_lock);
2763
2764         if ((timediff / ONE_MILLION) > (AT_OFF ? obd_timeout * 3/2 :
2765                                         at_max)) {
2766                 CERROR("%s: unhealthy - request has been waiting %lds\n",
2767                        svc->srv_name, timediff / ONE_MILLION);
2768                 return (-1);
2769         }
2770
2771         return 0;
2772 }