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