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