Whamcloud - gitweb
Drop slow OSCs if we can, but not for requested start idx.
[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  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  */
36
37 #define DEBUG_SUBSYSTEM S_RPC
38 #ifndef __KERNEL__
39 #include <liblustre.h>
40 #endif
41 #include <obd_support.h>
42 #include <obd_class.h>
43 #include <lustre_net.h>
44 #include <lu_object.h>
45 #include <lnet/types.h>
46 #include "ptlrpc_internal.h"
47
48 /* The following are visible and mutable through /sys/module/ptlrpc */
49 int test_req_buffer_pressure = 0;
50 CFS_MODULE_PARM(test_req_buffer_pressure, "i", int, 0444,
51                 "set non-zero to put pressure on request buffer pools");
52 unsigned int at_min = 0;
53 CFS_MODULE_PARM(at_min, "i", int, 0644,
54                 "Adaptive timeout minimum (sec)");
55 unsigned int at_max = 600;
56 EXPORT_SYMBOL(at_max);
57 CFS_MODULE_PARM(at_max, "i", int, 0644,
58                 "Adaptive timeout maximum (sec)");
59 unsigned int at_history = 600;
60 CFS_MODULE_PARM(at_history, "i", int, 0644,
61                 "Adaptive timeouts remember the slowest event that took place "
62                 "within this period (sec)");
63 static int at_early_margin = 5;
64 CFS_MODULE_PARM(at_early_margin, "i", int, 0644,
65                 "How soon before an RPC deadline to send an early reply");
66 static int at_extra = 30;
67 CFS_MODULE_PARM(at_extra, "i", int, 0644,
68                 "How much extra time to give with each early reply");
69
70
71 /* forward ref */
72 static int ptlrpc_server_post_idle_rqbds (struct ptlrpc_service *svc);
73
74 static CFS_LIST_HEAD(ptlrpc_all_services);
75 spinlock_t ptlrpc_all_services_lock;
76
77 static char *
78 ptlrpc_alloc_request_buffer (int size)
79 {
80         char *ptr;
81
82         if (size > SVC_BUF_VMALLOC_THRESHOLD)
83                 OBD_VMALLOC(ptr, size);
84         else
85                 OBD_ALLOC(ptr, size);
86
87         return (ptr);
88 }
89
90 static void
91 ptlrpc_free_request_buffer (char *ptr, int size)
92 {
93         if (size > SVC_BUF_VMALLOC_THRESHOLD)
94                 OBD_VFREE(ptr, size);
95         else
96                 OBD_FREE(ptr, size);
97 }
98
99 struct ptlrpc_request_buffer_desc *
100 ptlrpc_alloc_rqbd (struct ptlrpc_service *svc)
101 {
102         struct ptlrpc_request_buffer_desc *rqbd;
103
104         OBD_ALLOC_PTR(rqbd);
105         if (rqbd == NULL)
106                 return (NULL);
107
108         rqbd->rqbd_service = svc;
109         rqbd->rqbd_refcount = 0;
110         rqbd->rqbd_cbid.cbid_fn = request_in_callback;
111         rqbd->rqbd_cbid.cbid_arg = rqbd;
112         CFS_INIT_LIST_HEAD(&rqbd->rqbd_reqs);
113         rqbd->rqbd_buffer = ptlrpc_alloc_request_buffer(svc->srv_buf_size);
114
115         if (rqbd->rqbd_buffer == NULL) {
116                 OBD_FREE_PTR(rqbd);
117                 return (NULL);
118         }
119
120         spin_lock(&svc->srv_lock);
121         list_add(&rqbd->rqbd_list, &svc->srv_idle_rqbds);
122         svc->srv_nbufs++;
123         spin_unlock(&svc->srv_lock);
124
125         return (rqbd);
126 }
127
128 void
129 ptlrpc_free_rqbd (struct ptlrpc_request_buffer_desc *rqbd)
130 {
131         struct ptlrpc_service *svc = rqbd->rqbd_service;
132
133         LASSERT (rqbd->rqbd_refcount == 0);
134         LASSERT (list_empty(&rqbd->rqbd_reqs));
135
136         spin_lock(&svc->srv_lock);
137         list_del(&rqbd->rqbd_list);
138         svc->srv_nbufs--;
139         spin_unlock(&svc->srv_lock);
140
141         ptlrpc_free_request_buffer (rqbd->rqbd_buffer, svc->srv_buf_size);
142         OBD_FREE_PTR(rqbd);
143 }
144
145 int
146 ptlrpc_grow_req_bufs(struct ptlrpc_service *svc)
147 {
148         struct ptlrpc_request_buffer_desc *rqbd;
149         int                                i;
150
151         CDEBUG(D_RPCTRACE, "%s: allocate %d new %d-byte reqbufs (%d/%d left)\n",
152                svc->srv_name, svc->srv_nbuf_per_group, svc->srv_buf_size,
153                svc->srv_nrqbd_receiving, svc->srv_nbufs);
154         for (i = 0; i < svc->srv_nbuf_per_group; i++) {
155                 rqbd = ptlrpc_alloc_rqbd(svc);
156
157                 if (rqbd == NULL) {
158                         CERROR ("%s: Can't allocate request buffer\n",
159                                 svc->srv_name);
160                         return (-ENOMEM);
161                 }
162
163                 if (ptlrpc_server_post_idle_rqbds(svc) < 0)
164                         return (-EAGAIN);
165         }
166
167         return (0);
168 }
169
170 void
171 ptlrpc_save_lock (struct ptlrpc_request *req,
172                   struct lustre_handle *lock, int mode, int no_ack)
173 {
174         struct ptlrpc_reply_state *rs = req->rq_reply_state;
175         int                        idx;
176
177         LASSERT(rs != NULL);
178         LASSERT(rs->rs_nlocks < RS_MAX_LOCKS);
179
180         idx = rs->rs_nlocks++;
181         rs->rs_locks[idx] = *lock;
182         rs->rs_modes[idx] = mode;
183         rs->rs_difficult = 1;
184         rs->rs_no_ack = !!no_ack;
185 }
186
187 void
188 ptlrpc_schedule_difficult_reply (struct ptlrpc_reply_state *rs)
189 {
190         struct ptlrpc_service *svc = rs->rs_service;
191         ENTRY;
192
193         LASSERT_SPIN_LOCKED(&svc->srv_lock);
194         LASSERT (rs->rs_difficult);
195         rs->rs_scheduled_ever = 1;              /* flag any notification attempt */
196
197         if (rs->rs_scheduled) {                  /* being set up or already notified */
198                 EXIT;
199                 return;
200         }
201
202         rs->rs_scheduled = 1;
203         list_del (&rs->rs_list);
204         list_add (&rs->rs_list, &svc->srv_reply_queue);
205         cfs_waitq_signal (&svc->srv_waitq);
206         EXIT;
207 }
208
209 void
210 ptlrpc_commit_replies (struct obd_device *obd)
211 {
212         struct list_head   *tmp;
213         struct list_head   *nxt;
214         ENTRY;
215
216         /* Find any replies that have been committed and get their service
217          * to attend to complete them. */
218
219         /* CAVEAT EMPTOR: spinlock ordering!!! */
220         spin_lock(&obd->obd_uncommitted_replies_lock);
221
222         list_for_each_safe (tmp, nxt, &obd->obd_uncommitted_replies) {
223                 struct ptlrpc_reply_state *rs =
224                         list_entry(tmp, struct ptlrpc_reply_state, rs_obd_list);
225
226                 LASSERT (rs->rs_difficult);
227
228                 if (rs->rs_transno <= obd->obd_last_committed) {
229                         struct ptlrpc_service *svc = rs->rs_service;
230
231                         spin_lock (&svc->srv_lock);
232                         list_del_init (&rs->rs_obd_list);
233                         ptlrpc_schedule_difficult_reply (rs);
234                         spin_unlock (&svc->srv_lock);
235                 }
236         }
237
238         spin_unlock(&obd->obd_uncommitted_replies_lock);
239         EXIT;
240 }
241
242 static int
243 ptlrpc_server_post_idle_rqbds (struct ptlrpc_service *svc)
244 {
245         struct ptlrpc_request_buffer_desc *rqbd;
246         int                                rc;
247         int                                posted = 0;
248
249         for (;;) {
250                 spin_lock(&svc->srv_lock);
251
252                 if (list_empty (&svc->srv_idle_rqbds)) {
253                         spin_unlock(&svc->srv_lock);
254                         return (posted);
255                 }
256
257                 rqbd = list_entry(svc->srv_idle_rqbds.next,
258                                   struct ptlrpc_request_buffer_desc,
259                                   rqbd_list);
260                 list_del (&rqbd->rqbd_list);
261
262                 /* assume we will post successfully */
263                 svc->srv_nrqbd_receiving++;
264                 list_add (&rqbd->rqbd_list, &svc->srv_active_rqbds);
265
266                 spin_unlock(&svc->srv_lock);
267
268                 rc = ptlrpc_register_rqbd(rqbd);
269                 if (rc != 0)
270                         break;
271
272                 posted = 1;
273         }
274
275         spin_lock(&svc->srv_lock);
276
277         svc->srv_nrqbd_receiving--;
278         list_del(&rqbd->rqbd_list);
279         list_add_tail(&rqbd->rqbd_list, &svc->srv_idle_rqbds);
280
281         /* Don't complain if no request buffers are posted right now; LNET
282          * won't drop requests because we set the portal lazy! */
283
284         spin_unlock(&svc->srv_lock);
285
286         return (-1);
287 }
288
289 struct ptlrpc_service *ptlrpc_init_svc_conf(struct ptlrpc_service_conf *c,
290                                             svc_handler_t h, char *name,
291                                             struct proc_dir_entry *proc_entry,
292                                             svcreq_printfn_t prntfn,
293                                             char *threadname)
294 {
295         return ptlrpc_init_svc(c->psc_nbufs, c->psc_bufsize,
296                                c->psc_max_req_size, c->psc_max_reply_size,
297                                c->psc_req_portal, c->psc_rep_portal,
298                                c->psc_watchdog_factor,
299                                h, name, proc_entry,
300                                prntfn, c->psc_min_threads, c->psc_max_threads,
301                                threadname, c->psc_ctx_tags, NULL);
302 }
303 EXPORT_SYMBOL(ptlrpc_init_svc_conf);
304
305 static void ptlrpc_at_timer(unsigned long castmeharder)
306 {
307         struct ptlrpc_service *svc = (struct ptlrpc_service *)castmeharder;
308         svc->srv_at_check = 1;
309         svc->srv_at_checktime = cfs_time_current();
310         cfs_waitq_signal(&svc->srv_waitq);
311 }
312
313 /* @threadname should be 11 characters or less - 3 will be added on */
314 struct ptlrpc_service *
315 ptlrpc_init_svc(int nbufs, int bufsize, int max_req_size, int max_reply_size,
316                 int req_portal, int rep_portal, int watchdog_factor,
317                 svc_handler_t handler, char *name,
318                 cfs_proc_dir_entry_t *proc_entry,
319                 svcreq_printfn_t svcreq_printfn,
320                 int min_threads, int max_threads,
321                 char *threadname, __u32 ctx_tags,
322                 svc_hpreq_handler_t hp_handler)
323 {
324         int                    rc;
325         struct ptlrpc_service *service;
326         ENTRY;
327
328         LASSERT (nbufs > 0);
329         LASSERT (bufsize >= max_req_size + SPTLRPC_MAX_PAYLOAD);
330         LASSERT (ctx_tags != 0);
331
332         OBD_ALLOC_PTR(service);
333         if (service == NULL)
334                 RETURN(NULL);
335
336         /* First initialise enough for early teardown */
337
338         service->srv_name = name;
339         spin_lock_init(&service->srv_lock);
340         CFS_INIT_LIST_HEAD(&service->srv_threads);
341         cfs_waitq_init(&service->srv_waitq);
342
343         service->srv_nbuf_per_group = test_req_buffer_pressure ? 1 : nbufs;
344         service->srv_max_req_size = max_req_size + SPTLRPC_MAX_PAYLOAD;
345         service->srv_buf_size = bufsize;
346         service->srv_rep_portal = rep_portal;
347         service->srv_req_portal = req_portal;
348         service->srv_watchdog_factor = watchdog_factor;
349         service->srv_handler = handler;
350         service->srv_request_history_print_fn = svcreq_printfn;
351         service->srv_request_seq = 1;           /* valid seq #s start at 1 */
352         service->srv_request_max_cull_seq = 0;
353         service->srv_threads_min = min_threads;
354         service->srv_threads_max = max_threads;
355         service->srv_thread_name = threadname;
356         service->srv_ctx_tags = ctx_tags;
357         service->srv_hpreq_handler = hp_handler;
358         service->srv_hpreq_ratio = PTLRPC_SVC_HP_RATIO;
359         service->srv_hpreq_count = 0;
360         service->srv_n_hpreq = 0;
361
362         rc = LNetSetLazyPortal(service->srv_req_portal);
363         LASSERT (rc == 0);
364
365         CFS_INIT_LIST_HEAD(&service->srv_request_queue);
366         CFS_INIT_LIST_HEAD(&service->srv_request_hpq);
367         CFS_INIT_LIST_HEAD(&service->srv_idle_rqbds);
368         CFS_INIT_LIST_HEAD(&service->srv_active_rqbds);
369         CFS_INIT_LIST_HEAD(&service->srv_history_rqbds);
370         CFS_INIT_LIST_HEAD(&service->srv_request_history);
371         CFS_INIT_LIST_HEAD(&service->srv_active_replies);
372         CFS_INIT_LIST_HEAD(&service->srv_reply_queue);
373         CFS_INIT_LIST_HEAD(&service->srv_free_rs_list);
374         cfs_waitq_init(&service->srv_free_rs_waitq);
375
376         spin_lock_init(&service->srv_at_lock);
377         CFS_INIT_LIST_HEAD(&service->srv_req_in_queue);
378         CFS_INIT_LIST_HEAD(&service->srv_at_list);
379         cfs_timer_init(&service->srv_at_timer, ptlrpc_at_timer, service);
380         /* At SOW, service time should be quick; 10s seems generous. If client
381            timeout is less than this, we'll be sending an early reply. */
382         at_init(&service->srv_at_estimate, 10, 0);
383
384         spin_lock (&ptlrpc_all_services_lock);
385         list_add (&service->srv_list, &ptlrpc_all_services);
386         spin_unlock (&ptlrpc_all_services_lock);
387
388         /* Now allocate the request buffers */
389         rc = ptlrpc_grow_req_bufs(service);
390         /* We shouldn't be under memory pressure at startup, so
391          * fail if we can't post all our buffers at this time. */
392         if (rc != 0)
393                 GOTO(failed, NULL);
394
395         /* Now allocate pool of reply buffers */
396         /* Increase max reply size to next power of two */
397         service->srv_max_reply_size = 1;
398         while (service->srv_max_reply_size <
399                max_reply_size + SPTLRPC_MAX_PAYLOAD)
400                 service->srv_max_reply_size <<= 1;
401
402         if (proc_entry != NULL)
403                 ptlrpc_lprocfs_register_service(proc_entry, service);
404
405         CDEBUG(D_NET, "%s: Started, listening on portal %d\n",
406                service->srv_name, service->srv_req_portal);
407
408         RETURN(service);
409 failed:
410         ptlrpc_unregister_service(service);
411         return NULL;
412 }
413
414 /**
415  * to actually free the request, must be called without holding svc_lock.
416  * note it's caller's responsibility to unlink req->rq_list.
417  */
418 static void ptlrpc_server_free_request(struct ptlrpc_request *req)
419 {
420         LASSERT(atomic_read(&req->rq_refcount) == 0);
421         LASSERT(list_empty(&req->rq_timed_list));
422
423          /* DEBUG_REQ() assumes the reply state of a request with a valid
424           * ref will not be destroyed until that reference is dropped. */
425         ptlrpc_req_drop_rs(req);
426
427         sptlrpc_svc_ctx_decref(req);
428
429         if (req != &req->rq_rqbd->rqbd_req) {
430                 /* NB request buffers use an embedded
431                  * req if the incoming req unlinked the
432                  * MD; this isn't one of them! */
433                 OBD_FREE(req, sizeof(*req));
434         }
435 }
436
437 /**
438  * drop a reference count of the request. if it reaches 0, we either
439  * put it into history list, or free it immediately.
440  */
441 static void ptlrpc_server_drop_request(struct ptlrpc_request *req)
442 {
443         struct ptlrpc_request_buffer_desc *rqbd = req->rq_rqbd;
444         struct ptlrpc_service             *svc = rqbd->rqbd_service;
445         int                                refcount;
446         struct list_head                  *tmp;
447         struct list_head                  *nxt;
448
449         if (!atomic_dec_and_test(&req->rq_refcount))
450                 return;
451
452         spin_lock(&svc->srv_lock);
453
454         svc->srv_n_active_reqs--;
455         list_add(&req->rq_list, &rqbd->rqbd_reqs);
456
457         refcount = --(rqbd->rqbd_refcount);
458         if (refcount == 0) {
459                 /* request buffer is now idle: add to history */
460                 list_del(&rqbd->rqbd_list);
461                 list_add_tail(&rqbd->rqbd_list, &svc->srv_history_rqbds);
462                 svc->srv_n_history_rqbds++;
463
464                 /* cull some history?
465                  * I expect only about 1 or 2 rqbds need to be recycled here */
466                 while (svc->srv_n_history_rqbds > svc->srv_max_history_rqbds) {
467                         rqbd = list_entry(svc->srv_history_rqbds.next,
468                                           struct ptlrpc_request_buffer_desc,
469                                           rqbd_list);
470
471                         list_del(&rqbd->rqbd_list);
472                         svc->srv_n_history_rqbds--;
473
474                         /* remove rqbd's reqs from svc's req history while
475                          * I've got the service lock */
476                         list_for_each(tmp, &rqbd->rqbd_reqs) {
477                                 req = list_entry(tmp, struct ptlrpc_request,
478                                                  rq_list);
479                                 /* Track the highest culled req seq */
480                                 if (req->rq_history_seq >
481                                     svc->srv_request_max_cull_seq)
482                                         svc->srv_request_max_cull_seq =
483                                                 req->rq_history_seq;
484                                 list_del(&req->rq_history_list);
485                         }
486
487                         spin_unlock(&svc->srv_lock);
488
489                         list_for_each_safe(tmp, nxt, &rqbd->rqbd_reqs) {
490                                 req = list_entry(rqbd->rqbd_reqs.next,
491                                                  struct ptlrpc_request,
492                                                  rq_list);
493                                 list_del(&req->rq_list);
494                                 ptlrpc_server_free_request(req);
495                         }
496
497                         spin_lock(&svc->srv_lock);
498                         /*
499                          * now all reqs including the embedded req has been
500                          * disposed, schedule request buffer for re-use.
501                          */
502                         LASSERT(atomic_read(&rqbd->rqbd_req.rq_refcount) == 0);
503                         list_add_tail(&rqbd->rqbd_list, &svc->srv_idle_rqbds);
504                 }
505
506                 spin_unlock(&svc->srv_lock);
507         } else if (req->rq_reply_state && req->rq_reply_state->rs_prealloc) {
508                 /* If we are low on memory, we are not interested in history */
509                 list_del(&req->rq_list);
510                 list_del_init(&req->rq_history_list);
511                 spin_unlock(&svc->srv_lock);
512
513                 ptlrpc_server_free_request(req);
514         } else {
515                 spin_unlock(&svc->srv_lock);
516         }
517 }
518
519 /**
520  * to finish a request: stop sending more early replies, and release
521  * the request. should be called after we finished handling the request.
522  */
523 static void ptlrpc_server_finish_request(struct ptlrpc_request *req)
524 {
525         struct ptlrpc_service  *svc = req->rq_rqbd->rqbd_service;
526
527         if (req->rq_export) {
528                 class_export_put(req->rq_export);
529                 req->rq_export = NULL;
530         }
531
532         if (req->rq_phase != RQ_PHASE_NEW) /* incorrect message magic */
533                 DEBUG_REQ(D_INFO, req, "free req");
534
535         spin_lock(&svc->srv_at_lock);
536         req->rq_sent_final = 1;
537         list_del_init(&req->rq_timed_list);
538         spin_unlock(&svc->srv_at_lock);
539
540         ptlrpc_server_drop_request(req);
541 }
542
543 /* This function makes sure dead exports are evicted in a timely manner.
544    This function is only called when some export receives a message (i.e.,
545    the network is up.) */
546 static void ptlrpc_update_export_timer(struct obd_export *exp, long extra_delay)
547 {
548         struct obd_export *oldest_exp;
549         time_t oldest_time, new_time;
550
551         ENTRY;
552
553         LASSERT(exp);
554
555         /* Compensate for slow machines, etc, by faking our request time
556            into the future.  Although this can break the strict time-ordering
557            of the list, we can be really lazy here - we don't have to evict
558            at the exact right moment.  Eventually, all silent exports
559            will make it to the top of the list. */
560
561         /* Do not pay attention on 1sec or smaller renewals. */
562         new_time = cfs_time_current_sec() + extra_delay;
563         if (exp->exp_last_request_time + 1 /*second */ >= new_time)
564                 RETURN_EXIT;
565
566         exp->exp_last_request_time = new_time;
567         CDEBUG(D_HA, "updating export %s at "CFS_TIME_T" exp %p\n",
568                exp->exp_client_uuid.uuid,
569                exp->exp_last_request_time, exp);
570
571         /* exports may get disconnected from the chain even though the
572            export has references, so we must keep the spin lock while
573            manipulating the lists */
574         spin_lock(&exp->exp_obd->obd_dev_lock);
575
576         if (list_empty(&exp->exp_obd_chain_timed)) {
577                 /* this one is not timed */
578                 spin_unlock(&exp->exp_obd->obd_dev_lock);
579                 RETURN_EXIT;
580         }
581
582         list_move_tail(&exp->exp_obd_chain_timed,
583                        &exp->exp_obd->obd_exports_timed);
584
585         oldest_exp = list_entry(exp->exp_obd->obd_exports_timed.next,
586                                 struct obd_export, exp_obd_chain_timed);
587         oldest_time = oldest_exp->exp_last_request_time;
588         spin_unlock(&exp->exp_obd->obd_dev_lock);
589
590         if (exp->exp_obd->obd_recovering) {
591                 /* be nice to everyone during recovery */
592                 EXIT;
593                 return;
594         }
595
596         /* Note - racing to start/reset the obd_eviction timer is safe */
597         if (exp->exp_obd->obd_eviction_timer == 0) {
598                 /* Check if the oldest entry is expired. */
599                 if (cfs_time_current_sec() > (oldest_time + PING_EVICT_TIMEOUT +
600                                               extra_delay)) {
601                         /* We need a second timer, in case the net was down and
602                          * it just came back. Since the pinger may skip every
603                          * other PING_INTERVAL (see note in ptlrpc_pinger_main),
604                          * we better wait for 3. */
605                         exp->exp_obd->obd_eviction_timer =
606                                 cfs_time_current_sec() + 3 * PING_INTERVAL;
607                         CDEBUG(D_HA, "%s: Think about evicting %s from "CFS_TIME_T"\n",
608                                exp->exp_obd->obd_name, obd_export_nid2str(exp),
609                                oldest_time);
610                 }
611         } else {
612                 if (cfs_time_current_sec() >
613                     (exp->exp_obd->obd_eviction_timer + extra_delay)) {
614                         /* The evictor won't evict anyone who we've heard from
615                          * recently, so we don't have to check before we start
616                          * it. */
617                         if (!ping_evictor_wake(exp))
618                                 exp->exp_obd->obd_eviction_timer = 0;
619                 }
620         }
621
622         EXIT;
623 }
624
625 static int ptlrpc_check_req(struct ptlrpc_request *req)
626 {
627         if (unlikely(lustre_msg_get_conn_cnt(req->rq_reqmsg) <
628                      req->rq_export->exp_conn_cnt)) {
629                 DEBUG_REQ(D_ERROR, req,
630                           "DROPPING req from old connection %d < %d",
631                           lustre_msg_get_conn_cnt(req->rq_reqmsg),
632                           req->rq_export->exp_conn_cnt);
633                 return -EEXIST;
634         }
635         if (unlikely(req->rq_export->exp_obd &&
636                      req->rq_export->exp_obd->obd_fail)) {
637              /* Failing over, don't handle any more reqs, send
638                 error response instead. */
639                 CDEBUG(D_RPCTRACE, "Dropping req %p for failed obd %s\n",
640                        req, req->rq_export->exp_obd->obd_name);
641                 req->rq_status = -ENODEV;
642                 ptlrpc_error(req);
643                 return -ENODEV;
644         }
645
646         return 0;
647 }
648
649 static void ptlrpc_at_set_timer(struct ptlrpc_service *svc)
650 {
651         struct ptlrpc_request *rq;
652         __s32 next;
653
654         spin_lock(&svc->srv_at_lock);
655         if (list_empty(&svc->srv_at_list)) {
656                 cfs_timer_disarm(&svc->srv_at_timer);
657                 spin_unlock(&svc->srv_at_lock);
658                 return;
659         }
660
661         /* Set timer for closest deadline */
662         rq = list_entry(svc->srv_at_list.next, struct ptlrpc_request,
663                         rq_timed_list);
664         next = (__s32)(rq->rq_deadline - cfs_time_current_sec() -
665                        at_early_margin);
666         if (next <= 0)
667                 ptlrpc_at_timer((unsigned long)svc);
668         else
669                 cfs_timer_arm(&svc->srv_at_timer, cfs_time_shift(next));
670         spin_unlock(&svc->srv_at_lock);
671         CDEBUG(D_INFO, "armed %s at %+ds\n", svc->srv_name, next);
672 }
673
674 /* Add rpc to early reply check list */
675 static int ptlrpc_at_add_timed(struct ptlrpc_request *req)
676 {
677         struct ptlrpc_service *svc = req->rq_rqbd->rqbd_service;
678         struct ptlrpc_request *rq;
679         int found = 0;
680
681         if (AT_OFF)
682                 return(0);
683
684         if (req->rq_no_reply)
685                 return 0;
686
687         if ((lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT) == 0)
688                 return(-ENOSYS);
689
690         spin_lock(&svc->srv_at_lock);
691
692         if (unlikely(req->rq_sent_final)) {
693                 spin_unlock(&svc->srv_at_lock);
694                 return 0;
695         }
696
697         LASSERT(list_empty(&req->rq_timed_list));
698         /* Add to sorted list.  Presumably latest rpcs will have the latest
699            deadlines, so search backward. */
700         list_for_each_entry_reverse(rq, &svc->srv_at_list, rq_timed_list) {
701                 if (req->rq_deadline >= rq->rq_deadline) {
702                         list_add(&req->rq_timed_list, &rq->rq_timed_list);
703                         found++;
704                         break;
705                 }
706         }
707         if (!found)
708                 /* Add to front if shortest deadline or list empty */
709                 list_add(&req->rq_timed_list, &svc->srv_at_list);
710
711         /* Check if we're the head of the list */
712         found = (svc->srv_at_list.next == &req->rq_timed_list);
713
714         spin_unlock(&svc->srv_at_lock);
715
716         if (found)
717                 ptlrpc_at_set_timer(svc);
718
719         return 0;
720 }
721
722 static int ptlrpc_at_send_early_reply(struct ptlrpc_request *req,
723                                       int extra_time)
724 {
725         struct ptlrpc_service *svc = req->rq_rqbd->rqbd_service;
726         struct ptlrpc_request *reqcopy;
727         struct lustre_msg *reqmsg;
728         cfs_duration_t olddl = req->rq_deadline - cfs_time_current_sec();
729         time_t newdl;
730         int rc;
731         ENTRY;
732
733         /* deadline is when the client expects us to reply, margin is the
734            difference between clients' and servers' expectations */
735         DEBUG_REQ(D_ADAPTTO, req,
736                   "%ssending early reply (deadline %+lds, margin %+lds) for "
737                   "%d+%d", AT_OFF ? "AT off - not " : "",
738                   olddl, olddl - at_get(&svc->srv_at_estimate),
739                   at_get(&svc->srv_at_estimate), extra_time);
740
741         if (AT_OFF)
742                 RETURN(0);
743
744         if (olddl < 0) {
745                 DEBUG_REQ(D_WARNING, req, "Already past deadline (%+lds), "
746                           "not sending early reply. Consider increasing "
747                           "at_early_margin (%d)?", olddl, at_early_margin);
748
749                 /* Return an error so we're not re-added to the timed list. */
750                 RETURN(-ETIMEDOUT);
751         }
752
753         if ((lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT) == 0){
754                 DEBUG_REQ(D_INFO, req, "Wanted to ask client for more time, "
755                           "but no AT support");
756                 RETURN(-ENOSYS);
757         }
758
759         if (req->rq_export && req->rq_export->exp_in_recovery) {
760                 /* don't increase server estimates during recovery, and give
761                    clients the full recovery time. */
762                 newdl = cfs_time_current_sec() +
763                         req->rq_export->exp_obd->obd_recovery_timeout;
764         } else {
765                 if (extra_time) {
766                         /* Fake our processing time into the future to ask the
767                            clients for some extra amount of time */
768                         extra_time += cfs_time_current_sec() -
769                                 req->rq_arrival_time.tv_sec;
770                         at_add(&svc->srv_at_estimate, extra_time);
771                 }
772                 newdl = req->rq_arrival_time.tv_sec +
773                         at_get(&svc->srv_at_estimate);
774         }
775         if (req->rq_deadline >= newdl) {
776                 /* We're not adding any time, no need to send an early reply
777                    (e.g. maybe at adaptive_max) */
778                 DEBUG_REQ(D_WARNING, req, "Couldn't add any time ("
779                           CFS_DURATION_T"/"CFS_DURATION_T"), "
780                           "not sending early reply\n", olddl,
781                           cfs_time_sub(newdl, cfs_time_current_sec()));
782                 RETURN(-ETIMEDOUT);
783         }
784
785         OBD_ALLOC(reqcopy, sizeof *reqcopy);
786         if (reqcopy == NULL)
787                 RETURN(-ENOMEM);
788         OBD_ALLOC(reqmsg, req->rq_reqlen);
789         if (!reqmsg) {
790                 OBD_FREE(reqcopy, sizeof *reqcopy);
791                 RETURN(-ENOMEM);
792         }
793
794         *reqcopy = *req;
795         reqcopy->rq_reply_state = NULL;
796         reqcopy->rq_rep_swab_mask = 0;
797         reqcopy->rq_pack_bulk = 0;
798         reqcopy->rq_pack_udesc = 0;
799         reqcopy->rq_packed_final = 0;
800         sptlrpc_svc_ctx_addref(reqcopy);
801         /* We only need the reqmsg for the magic */
802         reqcopy->rq_reqmsg = reqmsg;
803         memcpy(reqmsg, req->rq_reqmsg, req->rq_reqlen);
804
805         if (req->rq_sent_final) {
806                 DEBUG_REQ(D_ADAPTTO, reqcopy, "Normal reply already sent out, "
807                           "abort sending early reply\n");
808                 GOTO(out, rc = 0);
809         }
810
811         /* Connection ref */
812         reqcopy->rq_export = class_conn2export(
813                                      lustre_msg_get_handle(reqcopy->rq_reqmsg));
814         if (reqcopy->rq_export == NULL)
815                 GOTO(out, rc = -ENODEV);
816
817         /* RPC ref */
818         class_export_rpc_get(reqcopy->rq_export);
819         if (reqcopy->rq_export->exp_obd &&
820             reqcopy->rq_export->exp_obd->obd_fail)
821                 GOTO(out_put, rc = -ENODEV);
822
823         rc = lustre_pack_reply_flags(reqcopy, 1, NULL, NULL, LPRFL_EARLY_REPLY);
824         if (rc)
825                 GOTO(out_put, rc);
826
827         rc = ptlrpc_send_reply(reqcopy, PTLRPC_REPLY_EARLY);
828
829         if (!rc) {
830                 /* Adjust our own deadline to what we told the client */
831                 req->rq_deadline = newdl;
832                 req->rq_early_count++; /* number sent, server side */
833         } else {
834                 DEBUG_REQ(D_ERROR, req, "Early reply send failed %d", rc);
835         }
836
837         /* Free the (early) reply state from lustre_pack_reply.
838            (ptlrpc_send_reply takes it's own rs ref, so this is safe here) */
839         ptlrpc_req_drop_rs(reqcopy);
840
841 out_put:
842         class_export_rpc_put(reqcopy->rq_export);
843         class_export_put(reqcopy->rq_export);
844 out:
845         sptlrpc_svc_ctx_decref(reqcopy);
846         OBD_FREE(reqmsg, req->rq_reqlen);
847         OBD_FREE(reqcopy, sizeof *reqcopy);
848         RETURN(rc);
849 }
850
851 /* Send early replies to everybody expiring within at_early_margin
852    asking for at_extra time */
853 static int ptlrpc_at_check_timed(struct ptlrpc_service *svc)
854 {
855         struct ptlrpc_request *rq, *n;
856         struct list_head work_list;
857         time_t now = cfs_time_current_sec();
858         cfs_duration_t delay;
859         int first, counter = 0;
860         ENTRY;
861
862         spin_lock(&svc->srv_at_lock);
863         if (svc->srv_at_check == 0) {
864                 spin_unlock(&svc->srv_at_lock);
865                 RETURN(0);
866         }
867         delay = cfs_time_sub(cfs_time_current(), svc->srv_at_checktime);
868         svc->srv_at_check = 0;
869
870         if (list_empty(&svc->srv_at_list)) {
871                 spin_unlock(&svc->srv_at_lock);
872                 RETURN(0);
873         }
874
875         /* The timer went off, but maybe the nearest rpc already completed. */
876         rq = list_entry(svc->srv_at_list.next, struct ptlrpc_request,
877                         rq_timed_list);
878         first = (int)(rq->rq_deadline - now);
879         if (first > at_early_margin) {
880                 /* We've still got plenty of time.  Reset the timer. */
881                 spin_unlock(&svc->srv_at_lock);
882                 ptlrpc_at_set_timer(svc);
883                 RETURN(0);
884         }
885
886         /* We're close to a timeout, and we don't know how much longer the
887            server will take. Send early replies to everyone expiring soon. */
888         CFS_INIT_LIST_HEAD(&work_list);
889         list_for_each_entry_safe(rq, n, &svc->srv_at_list, rq_timed_list) {
890                 if (rq->rq_deadline <= now + at_early_margin) {
891                         list_move_tail(&rq->rq_timed_list, &work_list);
892                         counter++;
893                 } else {
894                         break;
895                 }
896         }
897
898         spin_unlock(&svc->srv_at_lock);
899
900         /* we have a new earliest deadline, restart the timer */
901         ptlrpc_at_set_timer(svc);
902
903         CDEBUG(D_ADAPTTO, "timeout in %+ds, asking for %d secs on %d early "
904                "replies\n", first, at_extra, counter);
905         if (first < 0) {
906                 /* We're already past request deadlines before we even get a
907                    chance to send early replies */
908                 LCONSOLE_WARN("%s: This server is not able to keep up with "
909                               "request traffic (cpu-bound).\n", svc->srv_name);
910                 CWARN("earlyQ=%d reqQ=%d recA=%d, svcEst=%d, "
911                       "delay="CFS_DURATION_T"(jiff)\n",
912                       counter, svc->srv_n_queued_reqs, svc->srv_n_active_reqs,
913                       at_get(&svc->srv_at_estimate), delay);
914         }
915
916         /* ptlrpc_server_finish_request may delete an entry out of
917          * the work list */
918         spin_lock(&svc->srv_at_lock);
919         while (!list_empty(&work_list)) {
920                 rq = list_entry(work_list.next, struct ptlrpc_request,
921                                 rq_timed_list);
922                 list_del_init(&rq->rq_timed_list);
923                 /* if the entry is still in the worklist, it hasn't been
924                    deleted, and is safe to take a ref to keep the req around */
925                 atomic_inc(&rq->rq_refcount);
926                 spin_unlock(&svc->srv_at_lock);
927
928                 if (ptlrpc_at_send_early_reply(rq, at_extra) == 0)
929                         ptlrpc_at_add_timed(rq);
930
931                 ptlrpc_server_drop_request(rq);
932                 spin_lock(&svc->srv_at_lock);
933         }
934         spin_unlock(&svc->srv_at_lock);
935
936         RETURN(0);
937 }
938
939 /**
940  * Put the request to the export list if the request may become
941  * a high priority one.
942  */
943 static int ptlrpc_hpreq_init(struct ptlrpc_service *svc,
944                              struct ptlrpc_request *req)
945 {
946         int rc;
947         ENTRY;
948
949         if (svc->srv_hpreq_handler) {
950                 rc = svc->srv_hpreq_handler(req);
951                 if (rc)
952                         RETURN(rc);
953         }
954         if (req->rq_export && req->rq_ops) {
955                 spin_lock(&req->rq_export->exp_lock);
956                 list_add(&req->rq_exp_list, &req->rq_export->exp_queued_rpc);
957                 spin_unlock(&req->rq_export->exp_lock);
958         }
959
960         RETURN(0);
961 }
962
963 /** Remove the request from the export list. */
964 static void ptlrpc_hpreq_fini(struct ptlrpc_request *req)
965 {
966         ENTRY;
967         if (req->rq_export && req->rq_ops) {
968                 spin_lock(&req->rq_export->exp_lock);
969                 list_del_init(&req->rq_exp_list);
970                 spin_unlock(&req->rq_export->exp_lock);
971         }
972         EXIT;
973 }
974
975 /**
976  * Make the request a high priority one.
977  *
978  * All the high priority requests are queued in a separate FIFO
979  * ptlrpc_service::srv_request_hpq list which is parallel to
980  * ptlrpc_service::srv_request_queue list but has a higher priority
981  * for handling.
982  *
983  * \see ptlrpc_server_handle_request().
984  */
985 static void ptlrpc_hpreq_reorder_nolock(struct ptlrpc_service *svc,
986                                         struct ptlrpc_request *req)
987 {
988         ENTRY;
989         LASSERT(svc != NULL);
990         spin_lock(&req->rq_lock);
991         if (req->rq_hp == 0) {
992                 int opc = lustre_msg_get_opc(req->rq_reqmsg);
993
994                 /* Add to the high priority queue. */
995                 list_move_tail(&req->rq_list, &svc->srv_request_hpq);
996                 req->rq_hp = 1;
997                 if (opc != OBD_PING)
998                         DEBUG_REQ(D_NET, req, "high priority req");
999         }
1000         spin_unlock(&req->rq_lock);
1001         EXIT;
1002 }
1003
1004 void ptlrpc_hpreq_reorder(struct ptlrpc_request *req)
1005 {
1006         struct ptlrpc_service *svc = req->rq_rqbd->rqbd_service;
1007         ENTRY;
1008
1009         spin_lock(&svc->srv_lock);
1010         /* It may happen that the request is already taken for the processing
1011          * but still in the export list, do not re-add it into the HP list. */
1012         if (req->rq_phase == RQ_PHASE_NEW)
1013                 ptlrpc_hpreq_reorder_nolock(svc, req);
1014         spin_unlock(&svc->srv_lock);
1015         EXIT;
1016 }
1017
1018 /** Check if the request if a high priority one. */
1019 static int ptlrpc_server_hpreq_check(struct ptlrpc_request *req)
1020 {
1021         int opc, rc = 0;
1022         ENTRY;
1023
1024         /* Check by request opc. */
1025         opc = lustre_msg_get_opc(req->rq_reqmsg);
1026         if (opc == OBD_PING)
1027                 RETURN(1);
1028
1029         /* Perform request specific check. */
1030         if (req->rq_ops && req->rq_ops->hpreq_check)
1031                 rc = req->rq_ops->hpreq_check(req);
1032         RETURN(rc);
1033 }
1034
1035 /** Check if a request is a high priority one. */
1036 static int ptlrpc_server_request_add(struct ptlrpc_service *svc,
1037                                      struct ptlrpc_request *req)
1038 {
1039         int rc;
1040         ENTRY;
1041
1042         rc = ptlrpc_server_hpreq_check(req);
1043         if (rc < 0)
1044                 RETURN(rc);
1045
1046         spin_lock(&svc->srv_lock);
1047         /* Before inserting the request into the queue, check if it is not
1048          * inserted yet, or even already handled -- it may happen due to
1049          * a racing ldlm_server_blocking_ast(). */
1050         if (req->rq_phase == RQ_PHASE_NEW && list_empty(&req->rq_list)) {
1051                 if (rc)
1052                         ptlrpc_hpreq_reorder_nolock(svc, req);
1053                 else
1054                         list_add_tail(&req->rq_list, &svc->srv_request_queue);
1055         }
1056         spin_unlock(&svc->srv_lock);
1057
1058         RETURN(0);
1059 }
1060
1061 /* Only allow normal priority requests on a service that has a high-priority
1062  * queue if forced (i.e. cleanup), if there are other high priority requests
1063  * already being processed (i.e. those threads can service more high-priority
1064  * requests), or if there are enough idle threads that a later thread can do
1065  * a high priority request. */
1066 static int ptlrpc_server_allow_normal(struct ptlrpc_service *svc, int force)
1067 {
1068         return force || !svc->srv_hpreq_handler || svc->srv_n_hpreq > 0 ||
1069                svc->srv_n_active_reqs < svc->srv_threads_running - 2;
1070 }
1071
1072 static struct ptlrpc_request *
1073 ptlrpc_server_request_get(struct ptlrpc_service *svc, int force)
1074 {
1075         struct ptlrpc_request *req = NULL;
1076         ENTRY;
1077
1078         if (ptlrpc_server_allow_normal(svc, force) &&
1079             !list_empty(&svc->srv_request_queue) &&
1080             (list_empty(&svc->srv_request_hpq) ||
1081              svc->srv_hpreq_count >= svc->srv_hpreq_ratio)) {
1082                 req = list_entry(svc->srv_request_queue.next,
1083                                  struct ptlrpc_request, rq_list);
1084                 svc->srv_hpreq_count = 0;
1085         } else if (!list_empty(&svc->srv_request_hpq)) {
1086                 req = list_entry(svc->srv_request_hpq.next,
1087                                  struct ptlrpc_request, rq_list);
1088                 svc->srv_hpreq_count++;
1089         }
1090         RETURN(req);
1091 }
1092
1093 static int ptlrpc_server_request_pending(struct ptlrpc_service *svc, int force)
1094 {
1095         return ((ptlrpc_server_allow_normal(svc, force) &&
1096                  !list_empty(&svc->srv_request_queue)) ||
1097                 !list_empty(&svc->srv_request_hpq));
1098 }
1099
1100 /* Handle freshly incoming reqs, add to timed early reply list,
1101    pass on to regular request queue */
1102 static int
1103 ptlrpc_server_handle_req_in(struct ptlrpc_service *svc)
1104 {
1105         struct ptlrpc_request *req;
1106         __u32                  deadline;
1107         int                    rc;
1108         ENTRY;
1109
1110         LASSERT(svc);
1111
1112         spin_lock(&svc->srv_lock);
1113         if (list_empty(&svc->srv_req_in_queue)) {
1114                 spin_unlock(&svc->srv_lock);
1115                 RETURN(0);
1116         }
1117
1118         req = list_entry(svc->srv_req_in_queue.next,
1119                          struct ptlrpc_request, rq_list);
1120         list_del_init (&req->rq_list);
1121         /* Consider this still a "queued" request as far as stats are
1122            concerned */
1123         spin_unlock(&svc->srv_lock);
1124
1125         /* go through security check/transform */
1126         rc = sptlrpc_svc_unwrap_request(req);
1127         switch (rc) {
1128         case SECSVC_OK:
1129                 break;
1130         case SECSVC_COMPLETE:
1131                 target_send_reply(req, 0, OBD_FAIL_MDS_ALL_REPLY_NET);
1132                 goto err_req;
1133         case SECSVC_DROP:
1134                 goto err_req;
1135         default:
1136                 LBUG();
1137         }
1138
1139         /* Clear request swab mask; this is a new request */
1140         req->rq_req_swab_mask = 0;
1141
1142         rc = lustre_unpack_msg(req->rq_reqmsg, req->rq_reqlen);
1143         if (rc != 0) {
1144                 CERROR("error unpacking request: ptl %d from %s x"LPU64"\n",
1145                        svc->srv_req_portal, libcfs_id2str(req->rq_peer),
1146                        req->rq_xid);
1147                 goto err_req;
1148         }
1149
1150         rc = lustre_unpack_req_ptlrpc_body(req, MSG_PTLRPC_BODY_OFF);
1151         if (rc) {
1152                 CERROR ("error unpacking ptlrpc body: ptl %d from %s x"
1153                         LPU64"\n", svc->srv_req_portal,
1154                         libcfs_id2str(req->rq_peer), req->rq_xid);
1155                 goto err_req;
1156         }
1157
1158         rc = -EINVAL;
1159         if (lustre_msg_get_type(req->rq_reqmsg) != PTL_RPC_MSG_REQUEST) {
1160                 CERROR("wrong packet type received (type=%u) from %s\n",
1161                        lustre_msg_get_type(req->rq_reqmsg),
1162                        libcfs_id2str(req->rq_peer));
1163                 goto err_req;
1164         }
1165
1166         CDEBUG(D_NET, "got req "LPD64"\n", req->rq_xid);
1167
1168         req->rq_export = class_conn2export(
1169                 lustre_msg_get_handle(req->rq_reqmsg));
1170         if (req->rq_export) {
1171                 rc = ptlrpc_check_req(req);
1172                 if (rc == 0) {
1173                         rc = sptlrpc_target_export_check(req->rq_export, req);
1174                         if (rc)
1175                                 DEBUG_REQ(D_ERROR, req, "DROPPING req with "
1176                                           "illegal security flavor,");
1177                 }
1178
1179                 if (rc)
1180                         goto err_req;
1181                 ptlrpc_update_export_timer(req->rq_export, 0);
1182         }
1183
1184         /* req_in handling should/must be fast */
1185         if (cfs_time_current_sec() - req->rq_arrival_time.tv_sec > 5)
1186                 DEBUG_REQ(D_WARNING, req, "Slow req_in handling "CFS_DURATION_T"s",
1187                           cfs_time_sub(cfs_time_current_sec(),
1188                                        req->rq_arrival_time.tv_sec));
1189
1190         /* Set rpc server deadline and add it to the timed list */
1191         deadline = (lustre_msghdr_get_flags(req->rq_reqmsg) &
1192                     MSGHDR_AT_SUPPORT) ?
1193                    /* The max time the client expects us to take */
1194                    lustre_msg_get_timeout(req->rq_reqmsg) : obd_timeout;
1195         req->rq_deadline = req->rq_arrival_time.tv_sec + deadline;
1196         if (unlikely(deadline == 0)) {
1197                 DEBUG_REQ(D_ERROR, req, "Dropping request with 0 timeout");
1198                 goto err_req;
1199         }
1200
1201         ptlrpc_at_add_timed(req);
1202         rc = ptlrpc_hpreq_init(svc, req);
1203         if (rc)
1204                 GOTO(err_req, rc);
1205
1206         /* Move it over to the request processing queue */
1207         rc = ptlrpc_server_request_add(svc, req);
1208         if (rc)
1209                 GOTO(err_req, rc);
1210         cfs_waitq_signal(&svc->srv_waitq);
1211         RETURN(1);
1212
1213 err_req:
1214         spin_lock(&svc->srv_lock);
1215         svc->srv_n_queued_reqs--;
1216         svc->srv_n_active_reqs++;
1217         spin_unlock(&svc->srv_lock);
1218         ptlrpc_server_finish_request(req);
1219
1220         RETURN(1);
1221 }
1222
1223 static int
1224 ptlrpc_server_handle_request(struct ptlrpc_service *svc,
1225                              struct ptlrpc_thread *thread)
1226 {
1227         struct obd_export     *export = NULL;
1228         struct ptlrpc_request *request;
1229         struct timeval         work_start;
1230         struct timeval         work_end;
1231         long                   timediff;
1232         int                    opc, rc;
1233         int                    fail_opc = 0;
1234         ENTRY;
1235
1236         LASSERT(svc);
1237
1238         spin_lock(&svc->srv_lock);
1239         if (unlikely(!ptlrpc_server_request_pending(svc, 0) ||
1240             (
1241 #ifndef __KERNEL__
1242              /* !@%$# liblustre only has 1 thread */
1243              svc->srv_n_difficult_replies != 0 &&
1244 #endif
1245              svc->srv_n_active_reqs >= (svc->srv_threads_running - 1)))) {
1246                  /* Don't handle regular requests in the last thread, in order               * re
1247                   * to handle difficult replies (which might block other threads)
1248                   * as well as handle any incoming reqs, early replies, etc.
1249                   * That means we always need at least 2 service threads. */
1250                 spin_unlock(&svc->srv_lock);
1251                 RETURN(0);
1252              }
1253
1254         request = ptlrpc_server_request_get(svc, 0);
1255         if  (request == NULL) {
1256                 spin_unlock(&svc->srv_lock);
1257                 RETURN(0);
1258         }
1259
1260         opc = lustre_msg_get_opc(request->rq_reqmsg);
1261         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT))
1262                 fail_opc = OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT;
1263         else if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT))
1264                 fail_opc = OBD_FAIL_PTLRPC_HPREQ_TIMEOUT;
1265
1266         if (unlikely(fail_opc)) {
1267                 if (request->rq_export && request->rq_ops) {
1268                         spin_unlock(&svc->srv_lock);
1269                         OBD_FAIL_TIMEOUT(fail_opc, 4);
1270                         spin_lock(&svc->srv_lock);
1271                         request = ptlrpc_server_request_get(svc, 0);
1272                         if  (request == NULL) {
1273                                 spin_unlock(&svc->srv_lock);
1274                                 RETURN(0);
1275                         }
1276                         LASSERT(ptlrpc_server_request_pending(svc, 0));
1277                 }
1278         }
1279
1280         list_del_init(&request->rq_list);
1281         svc->srv_n_queued_reqs--;
1282         svc->srv_n_active_reqs++;
1283         if (request->rq_hp)
1284                 svc->srv_n_hpreq++;
1285
1286         /* The phase is changed under the lock here because we need to know
1287          * the request is under processing (see ptlrpc_hpreq_reorder()). */
1288         ptlrpc_rqphase_move(request, RQ_PHASE_INTERPRET);
1289         spin_unlock(&svc->srv_lock);
1290
1291         ptlrpc_hpreq_fini(request);
1292
1293         if(OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_DUMP_LOG))
1294                 libcfs_debug_dumplog();
1295
1296         do_gettimeofday(&work_start);
1297         timediff = cfs_timeval_sub(&work_start, &request->rq_arrival_time,NULL);
1298         if (likely(svc->srv_stats != NULL)) {
1299                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQWAIT_CNTR,
1300                                     timediff);
1301                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQQDEPTH_CNTR,
1302                                     svc->srv_n_queued_reqs);
1303                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQACTIVE_CNTR,
1304                                     svc->srv_n_active_reqs);
1305                 lprocfs_counter_add(svc->srv_stats, PTLRPC_TIMEOUT,
1306                                     at_get(&svc->srv_at_estimate));
1307         }
1308
1309         rc = lu_context_init(&request->rq_session,
1310                              LCT_SESSION|LCT_REMEMBER|LCT_NOREF);
1311         if (rc) {
1312                 CERROR("Failure to initialize session: %d\n", rc);
1313                 goto out_req;
1314         }
1315         request->rq_session.lc_thread = thread;
1316         request->rq_session.lc_cookie = 0x5;
1317         lu_context_enter(&request->rq_session);
1318
1319         CDEBUG(D_NET, "got req "LPU64"\n", request->rq_xid);
1320
1321         request->rq_svc_thread = thread;
1322         if (thread)
1323                 request->rq_svc_thread->t_env->le_ses = &request->rq_session;
1324
1325         if (likely(request->rq_export)) {
1326                 if (unlikely(ptlrpc_check_req(request)))
1327                         goto put_conn;
1328                 ptlrpc_update_export_timer(request->rq_export, timediff >> 19);
1329                 export = class_export_rpc_get(request->rq_export);
1330         }
1331
1332         /* Discard requests queued for longer than the deadline.
1333            The deadline is increased if we send an early reply. */
1334         if (cfs_time_current_sec() > request->rq_deadline) {
1335                 DEBUG_REQ(D_ERROR, request, "Dropping timed-out request from %s"
1336                           ": deadline "CFS_DURATION_T":"CFS_DURATION_T"s ago\n",
1337                           libcfs_id2str(request->rq_peer),
1338                           cfs_time_sub(request->rq_deadline,
1339                           request->rq_arrival_time.tv_sec),
1340                           cfs_time_sub(cfs_time_current_sec(),
1341                           request->rq_deadline));
1342                 goto put_rpc_export;
1343         }
1344
1345         CDEBUG(D_RPCTRACE, "Handling RPC pname:cluuid+ref:pid:xid:nid:opc "
1346                "%s:%s+%d:%d:x"LPU64":%s:%d\n", cfs_curproc_comm(),
1347                (request->rq_export ?
1348                 (char *)request->rq_export->exp_client_uuid.uuid : "0"),
1349                (request->rq_export ?
1350                 atomic_read(&request->rq_export->exp_refcount) : -99),
1351                lustre_msg_get_status(request->rq_reqmsg), request->rq_xid,
1352                libcfs_id2str(request->rq_peer),
1353                lustre_msg_get_opc(request->rq_reqmsg));
1354
1355         OBD_FAIL_TIMEOUT_MS(OBD_FAIL_PTLRPC_PAUSE_REQ, obd_fail_val);
1356
1357         rc = svc->srv_handler(request);
1358
1359         ptlrpc_rqphase_move(request, RQ_PHASE_COMPLETE);
1360
1361         CDEBUG(D_RPCTRACE, "Handled RPC pname:cluuid+ref:pid:xid:nid:opc "
1362                "%s:%s+%d:%d:x"LPU64":%s:%d\n", cfs_curproc_comm(),
1363                (request->rq_export ?
1364                 (char *)request->rq_export->exp_client_uuid.uuid : "0"),
1365                (request->rq_export ?
1366                 atomic_read(&request->rq_export->exp_refcount) : -99),
1367                lustre_msg_get_status(request->rq_reqmsg), request->rq_xid,
1368                libcfs_id2str(request->rq_peer),
1369                lustre_msg_get_opc(request->rq_reqmsg));
1370
1371 put_rpc_export:
1372         if (export != NULL)
1373                 class_export_rpc_put(export);
1374 put_conn:
1375         lu_context_exit(&request->rq_session);
1376         lu_context_fini(&request->rq_session);
1377
1378         if (unlikely(cfs_time_current_sec() > request->rq_deadline)) {
1379                 DEBUG_REQ(D_WARNING, request, "Request x"LPU64" took longer "
1380                           "than estimated ("CFS_DURATION_T":"CFS_DURATION_T"s);"
1381                           " client may timeout.",
1382                           request->rq_xid, cfs_time_sub(request->rq_deadline,
1383                           request->rq_arrival_time.tv_sec),
1384                           cfs_time_sub(cfs_time_current_sec(),
1385                           request->rq_deadline));
1386         }
1387
1388         do_gettimeofday(&work_end);
1389         timediff = cfs_timeval_sub(&work_end, &work_start, NULL);
1390         CDEBUG(D_RPCTRACE, "request x"LPU64" opc %u from %s processed in "
1391                "%ldus (%ldus total) trans "LPU64" rc %d/%d\n",
1392                request->rq_xid, lustre_msg_get_opc(request->rq_reqmsg),
1393                libcfs_id2str(request->rq_peer), timediff,
1394                cfs_timeval_sub(&work_end, &request->rq_arrival_time, NULL),
1395                request->rq_repmsg ? lustre_msg_get_transno(request->rq_repmsg) :
1396                request->rq_transno, request->rq_status,
1397                request->rq_repmsg ? lustre_msg_get_status(request->rq_repmsg):
1398                -999);
1399         if (likely(svc->srv_stats != NULL && request->rq_reqmsg != NULL)) {
1400                 __u32 op = lustre_msg_get_opc(request->rq_reqmsg);
1401                 int opc = opcode_offset(op);
1402                 if (opc > 0 && !(op == LDLM_ENQUEUE || op == MDS_REINT)) {
1403                         LASSERT(opc < LUSTRE_MAX_OPCODES);
1404                         lprocfs_counter_add(svc->srv_stats,
1405                                             opc + EXTRA_MAX_OPCODES,
1406                                             timediff);
1407                 }
1408         }
1409         if (unlikely(request->rq_early_count)) {
1410                 DEBUG_REQ(D_ADAPTTO, request,
1411                           "sent %d early replies before finishing in "
1412                           CFS_DURATION_T"s",
1413                           request->rq_early_count,
1414                           cfs_time_sub(work_end.tv_sec,
1415                           request->rq_arrival_time.tv_sec));
1416         }
1417
1418 out_req:
1419         spin_lock(&svc->srv_lock);
1420         if (request->rq_hp)
1421                 svc->srv_n_hpreq--;
1422         spin_unlock(&svc->srv_lock);
1423         ptlrpc_server_finish_request(request);
1424
1425         RETURN(1);
1426 }
1427
1428 static int
1429 ptlrpc_server_handle_reply (struct ptlrpc_service *svc)
1430 {
1431         struct ptlrpc_reply_state *rs;
1432         struct obd_export         *exp;
1433         struct obd_device         *obd;
1434         int                        nlocks;
1435         int                        been_handled;
1436         ENTRY;
1437
1438         spin_lock(&svc->srv_lock);
1439         if (list_empty (&svc->srv_reply_queue)) {
1440                 spin_unlock(&svc->srv_lock);
1441                 RETURN(0);
1442         }
1443
1444         rs = list_entry (svc->srv_reply_queue.next,
1445                          struct ptlrpc_reply_state, rs_list);
1446
1447         exp = rs->rs_export;
1448         obd = exp->exp_obd;
1449
1450         LASSERT (rs->rs_difficult);
1451         LASSERT (rs->rs_scheduled);
1452
1453         list_del_init (&rs->rs_list);
1454
1455         /* Disengage from notifiers carefully (lock order - irqrestore below!)*/
1456         spin_unlock(&svc->srv_lock);
1457
1458         spin_lock (&obd->obd_uncommitted_replies_lock);
1459         /* Noop if removed already */
1460         list_del_init (&rs->rs_obd_list);
1461         spin_unlock (&obd->obd_uncommitted_replies_lock);
1462
1463         spin_lock (&exp->exp_lock);
1464         /* Noop if removed already */
1465         list_del_init (&rs->rs_exp_list);
1466         spin_unlock (&exp->exp_lock);
1467
1468         spin_lock(&svc->srv_lock);
1469
1470         been_handled = rs->rs_handled;
1471         rs->rs_handled = 1;
1472
1473         nlocks = rs->rs_nlocks;                 /* atomic "steal", but */
1474         rs->rs_nlocks = 0;                      /* locks still on rs_locks! */
1475
1476         if (nlocks == 0 && !been_handled) {
1477                 /* If we see this, we should already have seen the warning
1478                  * in mds_steal_ack_locks()  */
1479                 CWARN("All locks stolen from rs %p x"LPD64".t"LPD64
1480                       " o%d NID %s\n",
1481                       rs,
1482                       rs->rs_xid, rs->rs_transno,
1483                       lustre_msg_get_opc(rs->rs_msg),
1484                       libcfs_nid2str(exp->exp_connection->c_peer.nid));
1485         }
1486
1487         if ((!been_handled && rs->rs_on_net) || nlocks > 0) {
1488                 spin_unlock(&svc->srv_lock);
1489
1490                 if (!been_handled && rs->rs_on_net) {
1491                         LNetMDUnlink(rs->rs_md_h);
1492                         /* Ignore return code; we're racing with
1493                          * completion... */
1494                 }
1495
1496                 while (nlocks-- > 0)
1497                         ldlm_lock_decref(&rs->rs_locks[nlocks],
1498                                          rs->rs_modes[nlocks]);
1499
1500                 spin_lock(&svc->srv_lock);
1501         }
1502
1503         rs->rs_scheduled = 0;
1504
1505         if (!rs->rs_on_net) {
1506                 /* Off the net */
1507                 svc->srv_n_difficult_replies--;
1508                 if (svc->srv_n_difficult_replies == 0 && svc->srv_is_stopping)
1509                         /* wake up threads that are being stopped by
1510                            ptlrpc_unregister_service/ptlrpc_stop_threads
1511                            and sleep waiting svr_n_difficult_replies == 0 */
1512                         cfs_waitq_broadcast(&svc->srv_waitq);
1513                 spin_unlock(&svc->srv_lock);
1514
1515                 class_export_put (exp);
1516                 rs->rs_export = NULL;
1517                 ptlrpc_rs_decref (rs);
1518                 atomic_dec (&svc->srv_outstanding_replies);
1519                 RETURN(1);
1520         }
1521
1522         /* still on the net; callback will schedule */
1523         spin_unlock(&svc->srv_lock);
1524         RETURN(1);
1525 }
1526
1527 #ifndef __KERNEL__
1528 /* FIXME make use of timeout later */
1529 int
1530 liblustre_check_services (void *arg)
1531 {
1532         int  did_something = 0;
1533         int  rc;
1534         struct list_head *tmp, *nxt;
1535         ENTRY;
1536
1537         /* I'm relying on being single threaded, not to have to lock
1538          * ptlrpc_all_services etc */
1539         list_for_each_safe (tmp, nxt, &ptlrpc_all_services) {
1540                 struct ptlrpc_service *svc =
1541                         list_entry (tmp, struct ptlrpc_service, srv_list);
1542
1543                 if (svc->srv_threads_running != 0)     /* I've recursed */
1544                         continue;
1545
1546                 /* service threads can block for bulk, so this limits us
1547                  * (arbitrarily) to recursing 1 stack frame per service.
1548                  * Note that the problem with recursion is that we have to
1549                  * unwind completely before our caller can resume. */
1550
1551                 svc->srv_threads_running++;
1552
1553                 do {
1554                         rc = ptlrpc_server_handle_req_in(svc);
1555                         rc |= ptlrpc_server_handle_reply(svc);
1556                         rc |= ptlrpc_at_check_timed(svc);
1557                         rc |= ptlrpc_server_handle_request(svc, NULL);
1558                         rc |= (ptlrpc_server_post_idle_rqbds(svc) > 0);
1559                         did_something |= rc;
1560                 } while (rc);
1561
1562                 svc->srv_threads_running--;
1563         }
1564
1565         RETURN(did_something);
1566 }
1567 #define ptlrpc_stop_all_threads(s) do {} while (0)
1568
1569 #else /* __KERNEL__ */
1570
1571 /* Don't use daemonize, it removes fs struct from new thread (bug 418) */
1572 void ptlrpc_daemonize(char *name)
1573 {
1574         struct fs_struct *fs = current->fs;
1575
1576         atomic_inc(&fs->count);
1577         cfs_daemonize(name);
1578         exit_fs(cfs_current());
1579         current->fs = fs;
1580         ll_set_fs_pwd(current->fs, init_task.fs->pwdmnt, init_task.fs->pwd);
1581 }
1582
1583 static void
1584 ptlrpc_check_rqbd_pool(struct ptlrpc_service *svc)
1585 {
1586         int avail = svc->srv_nrqbd_receiving;
1587         int low_water = test_req_buffer_pressure ? 0 :
1588                         svc->srv_nbuf_per_group/2;
1589
1590         /* NB I'm not locking; just looking. */
1591
1592         /* CAVEAT EMPTOR: We might be allocating buffers here because we've
1593          * allowed the request history to grow out of control.  We could put a
1594          * sanity check on that here and cull some history if we need the
1595          * space. */
1596
1597         if (avail <= low_water)
1598                 ptlrpc_grow_req_bufs(svc);
1599
1600         if (svc->srv_stats)
1601                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQBUF_AVAIL_CNTR,
1602                                     avail);
1603 }
1604
1605 static int
1606 ptlrpc_retry_rqbds(void *arg)
1607 {
1608         struct ptlrpc_service *svc = (struct ptlrpc_service *)arg;
1609
1610         svc->srv_rqbd_timeout = 0;
1611         return (-ETIMEDOUT);
1612 }
1613
1614 static int ptlrpc_main(void *arg)
1615 {
1616         struct ptlrpc_svc_data *data = (struct ptlrpc_svc_data *)arg;
1617         struct ptlrpc_service  *svc = data->svc;
1618         struct ptlrpc_thread   *thread = data->thread;
1619         struct obd_device      *dev = data->dev;
1620         struct ptlrpc_reply_state *rs;
1621 #ifdef WITH_GROUP_INFO
1622         struct group_info *ginfo = NULL;
1623 #endif
1624         struct lu_env env;
1625         int counter = 0, rc = 0;
1626         ENTRY;
1627
1628         ptlrpc_daemonize(data->name);
1629
1630 #if defined(HAVE_NODE_TO_CPUMASK) && defined(CONFIG_NUMA)
1631         /* we need to do this before any per-thread allocation is done so that
1632          * we get the per-thread allocations on local node.  bug 7342 */
1633         if (svc->srv_cpu_affinity) {
1634                 int cpu, num_cpu;
1635
1636                 for (cpu = 0, num_cpu = 0; cpu < num_possible_cpus(); cpu++) {
1637                         if (!cpu_online(cpu))
1638                                 continue;
1639                         if (num_cpu == thread->t_id % num_online_cpus())
1640                                 break;
1641                         num_cpu++;
1642                 }
1643                 set_cpus_allowed(cfs_current(), node_to_cpumask(cpu_to_node(cpu)));
1644         }
1645 #endif
1646
1647 #ifdef WITH_GROUP_INFO
1648         ginfo = groups_alloc(0);
1649         if (!ginfo) {
1650                 rc = -ENOMEM;
1651                 goto out;
1652         }
1653
1654         set_current_groups(ginfo);
1655         put_group_info(ginfo);
1656 #endif
1657
1658         if (svc->srv_init != NULL) {
1659                 rc = svc->srv_init(thread);
1660                 if (rc)
1661                         goto out;
1662         }
1663
1664         rc = lu_context_init(&env.le_ctx,
1665                              svc->srv_ctx_tags|LCT_REMEMBER|LCT_NOREF);
1666         if (rc)
1667                 goto out_srv_fini;
1668
1669         thread->t_env = &env;
1670         env.le_ctx.lc_thread = thread;
1671         env.le_ctx.lc_cookie = 0x6;
1672
1673         /* Alloc reply state structure for this one */
1674         OBD_ALLOC_GFP(rs, svc->srv_max_reply_size, CFS_ALLOC_STD);
1675         if (!rs) {
1676                 rc = -ENOMEM;
1677                 goto out_srv_fini;
1678         }
1679
1680         /* Record that the thread is running */
1681         thread->t_flags = SVC_RUNNING;
1682         /*
1683          * wake up our creator. Note: @data is invalid after this point,
1684          * because it's allocated on ptlrpc_start_thread() stack.
1685          */
1686         cfs_waitq_signal(&thread->t_ctl_waitq);
1687
1688         thread->t_watchdog = lc_watchdog_add(max_t(int, obd_timeout, AT_OFF ? 0 :
1689                                                    at_get(&svc->srv_at_estimate))
1690                                              *  svc->srv_watchdog_factor,
1691                                              NULL, NULL);
1692
1693         spin_lock(&svc->srv_lock);
1694         svc->srv_threads_running++;
1695         list_add(&rs->rs_list, &svc->srv_free_rs_list);
1696         spin_unlock(&svc->srv_lock);
1697         cfs_waitq_signal(&svc->srv_free_rs_waitq);
1698
1699         CDEBUG(D_NET, "service thread %d (#%d) started\n", thread->t_id,
1700                svc->srv_threads_running);
1701
1702         /* XXX maintain a list of all managed devices: insert here */
1703
1704         while ((thread->t_flags & SVC_STOPPING) == 0 ||
1705                svc->srv_n_difficult_replies != 0) {
1706                 /* Don't exit while there are replies to be handled */
1707                 struct l_wait_info lwi = LWI_TIMEOUT(svc->srv_rqbd_timeout,
1708                                                      ptlrpc_retry_rqbds, svc);
1709
1710                 lc_watchdog_disable(thread->t_watchdog);
1711
1712                 cond_resched();
1713
1714                 l_wait_event_exclusive (svc->srv_waitq,
1715                               ((thread->t_flags & SVC_STOPPING) != 0 &&
1716                                svc->srv_n_difficult_replies == 0) ||
1717                               (!list_empty(&svc->srv_idle_rqbds) &&
1718                                svc->srv_rqbd_timeout == 0) ||
1719                               !list_empty(&svc->srv_req_in_queue) ||
1720                               !list_empty(&svc->srv_reply_queue) ||
1721                               (ptlrpc_server_request_pending(svc, 0) &&
1722                                (svc->srv_n_active_reqs <
1723                                 (svc->srv_threads_running - 1))) ||
1724                               svc->srv_at_check,
1725                               &lwi);
1726
1727                 lc_watchdog_touch_ms(thread->t_watchdog, max_t(int, obd_timeout,
1728                                      AT_OFF ? 0 :
1729                                      at_get(&svc->srv_at_estimate)) *
1730                                      svc->srv_watchdog_factor);
1731
1732                 ptlrpc_check_rqbd_pool(svc);
1733
1734                 if ((svc->srv_threads_started < svc->srv_threads_max) &&
1735                     (svc->srv_n_active_reqs >= (svc->srv_threads_started - 1))){
1736                         /* Ignore return code - we tried... */
1737                         ptlrpc_start_thread(dev, svc);
1738                 }
1739
1740                 if (!list_empty(&svc->srv_reply_queue))
1741                         ptlrpc_server_handle_reply(svc);
1742
1743                 if (!list_empty(&svc->srv_req_in_queue)) {
1744                         /* Process all incoming reqs before handling any */
1745                         ptlrpc_server_handle_req_in(svc);
1746                         /* but limit ourselves in case of flood */
1747                         if (counter++ < 1000)
1748                                 continue;
1749                         counter = 0;
1750                 }
1751
1752                 if (svc->srv_at_check)
1753                         ptlrpc_at_check_timed(svc);
1754
1755                 /* don't handle requests in the last thread */
1756                 if (ptlrpc_server_request_pending(svc, 0) &&
1757                     (svc->srv_n_active_reqs < (svc->srv_threads_running - 1))) {
1758                         lu_context_enter(&env.le_ctx);
1759                         ptlrpc_server_handle_request(svc, thread);
1760                         lu_context_exit(&env.le_ctx);
1761                 }
1762
1763                 if (!list_empty(&svc->srv_idle_rqbds) &&
1764                     ptlrpc_server_post_idle_rqbds(svc) < 0) {
1765                         /* I just failed to repost request buffers.  Wait
1766                          * for a timeout (unless something else happens)
1767                          * before I try again */
1768                         svc->srv_rqbd_timeout = cfs_time_seconds(1)/10;
1769                         CDEBUG(D_RPCTRACE,"Posted buffers: %d\n",
1770                                svc->srv_nrqbd_receiving);
1771                 }
1772         }
1773
1774         lc_watchdog_delete(thread->t_watchdog);
1775         thread->t_watchdog = NULL;
1776
1777 out_srv_fini:
1778         /*
1779          * deconstruct service specific state created by ptlrpc_start_thread()
1780          */
1781         if (svc->srv_done != NULL)
1782                 svc->srv_done(thread);
1783
1784         lu_context_fini(&env.le_ctx);
1785 out:
1786         CDEBUG(D_NET, "service thread %d exiting: rc %d\n", thread->t_id, rc);
1787
1788         spin_lock(&svc->srv_lock);
1789         svc->srv_threads_running--; /* must know immediately */
1790         thread->t_id = rc;
1791         thread->t_flags = SVC_STOPPED;
1792
1793         cfs_waitq_signal(&thread->t_ctl_waitq);
1794         spin_unlock(&svc->srv_lock);
1795
1796         return rc;
1797 }
1798
1799 static void ptlrpc_stop_thread(struct ptlrpc_service *svc,
1800                                struct ptlrpc_thread *thread)
1801 {
1802         struct l_wait_info lwi = { 0 };
1803         ENTRY;
1804
1805         CDEBUG(D_RPCTRACE, "Stopping thread %p\n", thread);
1806         spin_lock(&svc->srv_lock);
1807         thread->t_flags = SVC_STOPPING;
1808         spin_unlock(&svc->srv_lock);
1809
1810         cfs_waitq_broadcast(&svc->srv_waitq);
1811         l_wait_event(thread->t_ctl_waitq, (thread->t_flags & SVC_STOPPED),
1812                      &lwi);
1813
1814         spin_lock(&svc->srv_lock);
1815         list_del(&thread->t_link);
1816         spin_unlock(&svc->srv_lock);
1817
1818         OBD_FREE_PTR(thread);
1819         EXIT;
1820 }
1821
1822 void ptlrpc_stop_all_threads(struct ptlrpc_service *svc)
1823 {
1824         struct ptlrpc_thread *thread;
1825         ENTRY;
1826
1827         spin_lock(&svc->srv_lock);
1828         while (!list_empty(&svc->srv_threads)) {
1829                 thread = list_entry(svc->srv_threads.next,
1830                                     struct ptlrpc_thread, t_link);
1831
1832                 spin_unlock(&svc->srv_lock);
1833                 ptlrpc_stop_thread(svc, thread);
1834                 spin_lock(&svc->srv_lock);
1835         }
1836
1837         spin_unlock(&svc->srv_lock);
1838         EXIT;
1839 }
1840
1841 int ptlrpc_start_threads(struct obd_device *dev, struct ptlrpc_service *svc)
1842 {
1843         int i, rc = 0;
1844         ENTRY;
1845
1846         /* We require 2 threads min - see note in
1847            ptlrpc_server_handle_request */
1848         LASSERT(svc->srv_threads_min >= 2);
1849         for (i = 0; i < svc->srv_threads_min; i++) {
1850                 rc = ptlrpc_start_thread(dev, svc);
1851                 /* We have enough threads, don't start more.  b=15759 */
1852                 if (rc == -EMFILE)
1853                         break;
1854                 if (rc) {
1855                         CERROR("cannot start %s thread #%d: rc %d\n",
1856                                svc->srv_thread_name, i, rc);
1857                         ptlrpc_stop_all_threads(svc);
1858                 }
1859         }
1860         RETURN(rc);
1861 }
1862
1863 int ptlrpc_start_thread(struct obd_device *dev, struct ptlrpc_service *svc)
1864 {
1865         struct l_wait_info lwi = { 0 };
1866         struct ptlrpc_svc_data d;
1867         struct ptlrpc_thread *thread;
1868         char name[32];
1869         int id, rc;
1870         ENTRY;
1871
1872         CDEBUG(D_RPCTRACE, "%s started %d min %d max %d running %d\n",
1873                svc->srv_name, svc->srv_threads_started, svc->srv_threads_min,
1874                svc->srv_threads_max, svc->srv_threads_running);
1875         if (unlikely(svc->srv_threads_started >= svc->srv_threads_max) ||
1876             (OBD_FAIL_CHECK(OBD_FAIL_TGT_TOOMANY_THREADS) &&
1877              svc->srv_threads_started == svc->srv_threads_min - 1))
1878                 RETURN(-EMFILE);
1879
1880         OBD_ALLOC_PTR(thread);
1881         if (thread == NULL)
1882                 RETURN(-ENOMEM);
1883         cfs_waitq_init(&thread->t_ctl_waitq);
1884
1885         spin_lock(&svc->srv_lock);
1886         if (svc->srv_threads_started >= svc->srv_threads_max) {
1887                 spin_unlock(&svc->srv_lock);
1888                 OBD_FREE_PTR(thread);
1889                 RETURN(-EMFILE);
1890         }
1891         list_add(&thread->t_link, &svc->srv_threads);
1892         id = svc->srv_threads_started++;
1893         spin_unlock(&svc->srv_lock);
1894
1895         thread->t_id = id;
1896         sprintf(name, "%s_%02d", svc->srv_thread_name, id);
1897         d.dev = dev;
1898         d.svc = svc;
1899         d.name = name;
1900         d.thread = thread;
1901
1902         CDEBUG(D_RPCTRACE, "starting thread '%s'\n", name);
1903
1904           /* CLONE_VM and CLONE_FILES just avoid a needless copy, because we
1905          * just drop the VM and FILES in ptlrpc_daemonize() right away.
1906          */
1907         rc = cfs_kernel_thread(ptlrpc_main, &d, CLONE_VM | CLONE_FILES);
1908         if (rc < 0) {
1909                 CERROR("cannot start thread '%s': rc %d\n", name, rc);
1910
1911                 spin_lock(&svc->srv_lock);
1912                 list_del(&thread->t_link);
1913                 --svc->srv_threads_started;
1914                 spin_unlock(&svc->srv_lock);
1915
1916                 OBD_FREE(thread, sizeof(*thread));
1917                 RETURN(rc);
1918         }
1919         l_wait_event(thread->t_ctl_waitq,
1920                      thread->t_flags & (SVC_RUNNING | SVC_STOPPED), &lwi);
1921
1922         rc = (thread->t_flags & SVC_STOPPED) ? thread->t_id : 0;
1923         RETURN(rc);
1924 }
1925 #endif
1926
1927 int ptlrpc_unregister_service(struct ptlrpc_service *service)
1928 {
1929         int                   rc;
1930         struct l_wait_info    lwi;
1931         struct list_head     *tmp;
1932         struct ptlrpc_reply_state *rs, *t;
1933         ENTRY;
1934
1935         service->srv_is_stopping = 1;
1936         cfs_timer_disarm(&service->srv_at_timer);
1937
1938         ptlrpc_stop_all_threads(service);
1939         LASSERT(list_empty(&service->srv_threads));
1940
1941         spin_lock (&ptlrpc_all_services_lock);
1942         list_del_init (&service->srv_list);
1943         spin_unlock (&ptlrpc_all_services_lock);
1944
1945         ptlrpc_lprocfs_unregister_service(service);
1946
1947         /* All history will be culled when the next request buffer is
1948          * freed */
1949         service->srv_max_history_rqbds = 0;
1950
1951         CDEBUG(D_NET, "%s: tearing down\n", service->srv_name);
1952
1953         rc = LNetClearLazyPortal(service->srv_req_portal);
1954         LASSERT (rc == 0);
1955
1956         /* Unlink all the request buffers.  This forces a 'final' event with
1957          * its 'unlink' flag set for each posted rqbd */
1958         list_for_each(tmp, &service->srv_active_rqbds) {
1959                 struct ptlrpc_request_buffer_desc *rqbd =
1960                         list_entry(tmp, struct ptlrpc_request_buffer_desc,
1961                                    rqbd_list);
1962
1963                 rc = LNetMDUnlink(rqbd->rqbd_md_h);
1964                 LASSERT (rc == 0 || rc == -ENOENT);
1965         }
1966
1967         /* Wait for the network to release any buffers it's currently
1968          * filling */
1969         for (;;) {
1970                 spin_lock(&service->srv_lock);
1971                 rc = service->srv_nrqbd_receiving;
1972                 spin_unlock(&service->srv_lock);
1973
1974                 if (rc == 0)
1975                         break;
1976
1977                 /* Network access will complete in finite time but the HUGE
1978                  * timeout lets us CWARN for visibility of sluggish NALs */
1979                 lwi = LWI_TIMEOUT(cfs_time_seconds(LONG_UNLINK), NULL, NULL);
1980                 rc = l_wait_event(service->srv_waitq,
1981                                   service->srv_nrqbd_receiving == 0,
1982                                   &lwi);
1983                 if (rc == -ETIMEDOUT)
1984                         CWARN("Service %s waiting for request buffers\n",
1985                               service->srv_name);
1986         }
1987
1988         /* schedule all outstanding replies to terminate them */
1989         spin_lock(&service->srv_lock);
1990         while (!list_empty(&service->srv_active_replies)) {
1991                 struct ptlrpc_reply_state *rs =
1992                         list_entry(service->srv_active_replies.next,
1993                                    struct ptlrpc_reply_state, rs_list);
1994                 ptlrpc_schedule_difficult_reply(rs);
1995         }
1996         spin_unlock(&service->srv_lock);
1997
1998         /* purge the request queue.  NB No new replies (rqbds all unlinked)
1999          * and no service threads, so I'm the only thread noodling the
2000          * request queue now */
2001         while (!list_empty(&service->srv_req_in_queue)) {
2002                 struct ptlrpc_request *req =
2003                         list_entry(service->srv_req_in_queue.next,
2004                                    struct ptlrpc_request,
2005                                    rq_list);
2006
2007                 list_del(&req->rq_list);
2008                 service->srv_n_queued_reqs--;
2009                 service->srv_n_active_reqs++;
2010                 ptlrpc_server_finish_request(req);
2011         }
2012         while (ptlrpc_server_request_pending(service, 1)) {
2013                 struct ptlrpc_request *req;
2014
2015                 req = ptlrpc_server_request_get(service, 1);
2016                 list_del(&req->rq_list);
2017                 service->srv_n_queued_reqs--;
2018                 service->srv_n_active_reqs++;
2019                 ptlrpc_hpreq_fini(req);
2020                 ptlrpc_server_finish_request(req);
2021         }
2022         LASSERT(service->srv_n_queued_reqs == 0);
2023         LASSERT(service->srv_n_active_reqs == 0);
2024         LASSERT(service->srv_n_history_rqbds == 0);
2025         LASSERT(list_empty(&service->srv_active_rqbds));
2026
2027         /* Now free all the request buffers since nothing references them
2028          * any more... */
2029         while (!list_empty(&service->srv_idle_rqbds)) {
2030                 struct ptlrpc_request_buffer_desc *rqbd =
2031                         list_entry(service->srv_idle_rqbds.next,
2032                                    struct ptlrpc_request_buffer_desc,
2033                                    rqbd_list);
2034
2035                 ptlrpc_free_rqbd(rqbd);
2036         }
2037
2038         /* wait for all outstanding replies to complete (they were
2039          * scheduled having been flagged to abort above) */
2040         while (atomic_read(&service->srv_outstanding_replies) != 0) {
2041                 struct l_wait_info lwi = LWI_TIMEOUT(cfs_time_seconds(10), NULL, NULL);
2042
2043                 rc = l_wait_event(service->srv_waitq,
2044                                   !list_empty(&service->srv_reply_queue), &lwi);
2045                 LASSERT(rc == 0 || rc == -ETIMEDOUT);
2046
2047                 if (rc == 0) {
2048                         ptlrpc_server_handle_reply(service);
2049                         continue;
2050                 }
2051                 CWARN("Unexpectedly long timeout %p\n", service);
2052         }
2053
2054         list_for_each_entry_safe(rs, t, &service->srv_free_rs_list, rs_list) {
2055                 list_del(&rs->rs_list);
2056                 OBD_FREE(rs, service->srv_max_reply_size);
2057         }
2058
2059         /* In case somebody rearmed this in the meantime */
2060         cfs_timer_disarm(&service->srv_at_timer);
2061
2062         OBD_FREE_PTR(service);
2063         RETURN(0);
2064 }
2065
2066 /* Returns 0 if the service is healthy.
2067  *
2068  * Right now, it just checks to make sure that requests aren't languishing
2069  * in the queue.  We'll use this health check to govern whether a node needs
2070  * to be shot, so it's intentionally non-aggressive. */
2071 int ptlrpc_service_health_check(struct ptlrpc_service *svc)
2072 {
2073         struct ptlrpc_request *request;
2074         struct timeval         right_now;
2075         long                   timediff;
2076
2077         if (svc == NULL)
2078                 return 0;
2079
2080         do_gettimeofday(&right_now);
2081
2082         spin_lock(&svc->srv_lock);
2083         if (!ptlrpc_server_request_pending(svc, 1)) {
2084                 spin_unlock(&svc->srv_lock);
2085                 return 0;
2086         }
2087
2088         /* How long has the next entry been waiting? */
2089         if (list_empty(&svc->srv_request_queue))
2090                 request = list_entry(svc->srv_request_hpq.next,
2091                                      struct ptlrpc_request, rq_list);
2092         else
2093                 request = list_entry(svc->srv_request_queue.next,
2094                                      struct ptlrpc_request, rq_list);
2095         timediff = cfs_timeval_sub(&right_now, &request->rq_arrival_time, NULL);
2096         spin_unlock(&svc->srv_lock);
2097
2098         if ((timediff / ONE_MILLION) > (AT_OFF ? obd_timeout * 3/2 :
2099                                         at_max)) {
2100                 CERROR("%s: unhealthy - request has been waiting %lds\n",
2101                        svc->srv_name, timediff / ONE_MILLION);
2102                 return (-1);
2103         }
2104
2105         return 0;
2106 }