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