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