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