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