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