Whamcloud - gitweb
73aff1b730c346df7938b48136db415ae4344cd4
[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 cfs_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         cfs_spin_lock(&svc->srv_lock);
115         cfs_list_add(&rqbd->rqbd_list, &svc->srv_idle_rqbds);
116         svc->srv_nbufs++;
117         cfs_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 (cfs_list_empty(&rqbd->rqbd_reqs));
129
130         cfs_spin_lock(&svc->srv_lock);
131         cfs_list_del(&rqbd->rqbd_list);
132         svc->srv_nbufs--;
133         cfs_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         cfs_spinlock_t        hrt_lock;
192         unsigned long         hrt_flags;
193         cfs_waitq_t           hrt_wait;
194         cfs_list_t            hrt_queue;
195         cfs_completion_t      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         cfs_list_t              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                 cfs_spin_lock(&hr->hr_threads[idx].hrt_lock);
249                 cfs_list_splice_init(&b->rsb_replies,
250                                      &hr->hr_threads[idx].hrt_queue);
251                 cfs_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                         cfs_spin_unlock(&b->rsb_svc->srv_lock);
272                 }
273                 cfs_spin_lock(&svc->srv_lock);
274                 b->rsb_svc = svc;
275         }
276         cfs_spin_lock(&rs->rs_lock);
277         rs->rs_scheduled_ever = 1;
278         if (rs->rs_scheduled == 0) {
279                 cfs_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         cfs_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                 cfs_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(cfs_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         cfs_spin_lock(&hr->hr_threads[idx].hrt_lock);
326         cfs_list_add_tail(&rs->rs_list, &hr->hr_threads[idx].hrt_queue);
327         cfs_spin_unlock(&hr->hr_threads[idx].hrt_lock);
328         cfs_waitq_signal(&hr->hr_threads[idx].hrt_wait);
329         EXIT;
330 #else
331         cfs_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         cfs_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         cfs_spin_lock(&exp->exp_uncommitted_replies_lock);
368         cfs_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                         cfs_list_del_init(&rs->rs_obd_list);
375                         rs_batch_add(&batch, rs);
376                 }
377         }
378         cfs_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                 cfs_spin_lock(&svc->srv_lock);
392
393                 if (cfs_list_empty (&svc->srv_idle_rqbds)) {
394                         cfs_spin_unlock(&svc->srv_lock);
395                         return (posted);
396                 }
397
398                 rqbd = cfs_list_entry(svc->srv_idle_rqbds.next,
399                                       struct ptlrpc_request_buffer_desc,
400                                       rqbd_list);
401                 cfs_list_del (&rqbd->rqbd_list);
402
403                 /* assume we will post successfully */
404                 svc->srv_nrqbd_receiving++;
405                 cfs_list_add (&rqbd->rqbd_list, &svc->srv_active_rqbds);
406
407                 cfs_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         cfs_spin_lock(&svc->srv_lock);
417
418         svc->srv_nrqbd_receiving--;
419         cfs_list_del(&rqbd->rqbd_list);
420         cfs_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         cfs_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         cfs_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         cfs_atomic_set(&service->srv_n_difficult_replies, 0);
521
522         cfs_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(cfs_list_t) * 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         cfs_spin_lock (&ptlrpc_all_services_lock);
549         cfs_list_add (&service->srv_list, &ptlrpc_all_services);
550         cfs_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(cfs_atomic_read(&req->rq_refcount) == 0);
585         LASSERT(cfs_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  * increment the number of active requests consuming service threads.
603  */
604 void ptlrpc_server_active_request_inc(struct ptlrpc_request *req)
605 {
606         struct ptlrpc_request_buffer_desc *rqbd = req->rq_rqbd;
607         struct ptlrpc_service *svc = rqbd->rqbd_service;
608
609         cfs_spin_lock(&svc->srv_lock);
610         svc->srv_n_active_reqs++;
611         cfs_spin_unlock(&svc->srv_lock);
612 }
613
614 /**
615  * decrement the number of active requests consuming service threads.
616  */
617 void ptlrpc_server_active_request_dec(struct ptlrpc_request *req)
618 {
619         struct ptlrpc_request_buffer_desc *rqbd = req->rq_rqbd;
620         struct ptlrpc_service *svc = rqbd->rqbd_service;
621
622         cfs_spin_lock(&svc->srv_lock);
623         svc->srv_n_active_reqs--;
624         cfs_spin_unlock(&svc->srv_lock);
625 }
626
627 /**
628  * drop a reference count of the request. if it reaches 0, we either
629  * put it into history list, or free it immediately.
630  */
631 void ptlrpc_server_drop_request(struct ptlrpc_request *req)
632 {
633         struct ptlrpc_request_buffer_desc *rqbd = req->rq_rqbd;
634         struct ptlrpc_service             *svc = rqbd->rqbd_service;
635         int                                refcount;
636         cfs_list_t                        *tmp;
637         cfs_list_t                        *nxt;
638
639         if (!cfs_atomic_dec_and_test(&req->rq_refcount))
640                 return;
641
642         cfs_spin_lock(&svc->srv_at_lock);
643         if (req->rq_at_linked) {
644                 struct ptlrpc_at_array *array = &svc->srv_at_array;
645                 __u32 index = req->rq_at_index;
646
647                 LASSERT(!cfs_list_empty(&req->rq_timed_list));
648                 cfs_list_del_init(&req->rq_timed_list);
649                 req->rq_at_linked = 0;
650                 array->paa_reqs_count[index]--;
651                 array->paa_count--;
652         } else
653                 LASSERT(cfs_list_empty(&req->rq_timed_list));
654         cfs_spin_unlock(&svc->srv_at_lock);
655
656         /* finalize request */
657         if (req->rq_export) {
658                 class_export_put(req->rq_export);
659                 req->rq_export = NULL;
660         }
661
662         cfs_spin_lock(&svc->srv_lock);
663
664         svc->srv_n_active_reqs--;
665         cfs_list_add(&req->rq_list, &rqbd->rqbd_reqs);
666
667         refcount = --(rqbd->rqbd_refcount);
668         if (refcount == 0) {
669                 /* request buffer is now idle: add to history */
670                 cfs_list_del(&rqbd->rqbd_list);
671                 cfs_list_add_tail(&rqbd->rqbd_list, &svc->srv_history_rqbds);
672                 svc->srv_n_history_rqbds++;
673
674                 /* cull some history?
675                  * I expect only about 1 or 2 rqbds need to be recycled here */
676                 while (svc->srv_n_history_rqbds > svc->srv_max_history_rqbds) {
677                         rqbd = cfs_list_entry(svc->srv_history_rqbds.next,
678                                               struct ptlrpc_request_buffer_desc,
679                                               rqbd_list);
680
681                         cfs_list_del(&rqbd->rqbd_list);
682                         svc->srv_n_history_rqbds--;
683
684                         /* remove rqbd's reqs from svc's req history while
685                          * I've got the service lock */
686                         cfs_list_for_each(tmp, &rqbd->rqbd_reqs) {
687                                 req = cfs_list_entry(tmp, struct ptlrpc_request,
688                                                      rq_list);
689                                 /* Track the highest culled req seq */
690                                 if (req->rq_history_seq >
691                                     svc->srv_request_max_cull_seq)
692                                         svc->srv_request_max_cull_seq =
693                                                 req->rq_history_seq;
694                                 cfs_list_del(&req->rq_history_list);
695                         }
696
697                         cfs_spin_unlock(&svc->srv_lock);
698
699                         cfs_list_for_each_safe(tmp, nxt, &rqbd->rqbd_reqs) {
700                                 req = cfs_list_entry(rqbd->rqbd_reqs.next,
701                                                      struct ptlrpc_request,
702                                                      rq_list);
703                                 cfs_list_del(&req->rq_list);
704                                 ptlrpc_server_free_request(req);
705                         }
706
707                         cfs_spin_lock(&svc->srv_lock);
708                         /*
709                          * now all reqs including the embedded req has been
710                          * disposed, schedule request buffer for re-use.
711                          */
712                         LASSERT(cfs_atomic_read(&rqbd->rqbd_req.rq_refcount) ==
713                                 0);
714                         cfs_list_add_tail(&rqbd->rqbd_list,
715                                           &svc->srv_idle_rqbds);
716                 }
717
718                 cfs_spin_unlock(&svc->srv_lock);
719         } else if (req->rq_reply_state && req->rq_reply_state->rs_prealloc) {
720                 /* If we are low on memory, we are not interested in history */
721                 cfs_list_del(&req->rq_list);
722                 cfs_list_del_init(&req->rq_history_list);
723                 cfs_spin_unlock(&svc->srv_lock);
724
725                 ptlrpc_server_free_request(req);
726         } else {
727                 cfs_spin_unlock(&svc->srv_lock);
728         }
729 }
730
731 /**
732  * to finish a request: stop sending more early replies, and release
733  * the request. should be called after we finished handling the request.
734  */
735 static void ptlrpc_server_finish_request(struct ptlrpc_request *req)
736 {
737         ptlrpc_server_drop_request(req);
738 }
739
740 /* This function makes sure dead exports are evicted in a timely manner.
741    This function is only called when some export receives a message (i.e.,
742    the network is up.) */
743 static void ptlrpc_update_export_timer(struct obd_export *exp, long extra_delay)
744 {
745         struct obd_export *oldest_exp;
746         time_t oldest_time, new_time;
747
748         ENTRY;
749
750         LASSERT(exp);
751
752         /* Compensate for slow machines, etc, by faking our request time
753            into the future.  Although this can break the strict time-ordering
754            of the list, we can be really lazy here - we don't have to evict
755            at the exact right moment.  Eventually, all silent exports
756            will make it to the top of the list. */
757
758         /* Do not pay attention on 1sec or smaller renewals. */
759         new_time = cfs_time_current_sec() + extra_delay;
760         if (exp->exp_last_request_time + 1 /*second */ >= new_time)
761                 RETURN_EXIT;
762
763         exp->exp_last_request_time = new_time;
764         CDEBUG(D_HA, "updating export %s at "CFS_TIME_T" exp %p\n",
765                exp->exp_client_uuid.uuid,
766                exp->exp_last_request_time, exp);
767
768         /* exports may get disconnected from the chain even though the
769            export has references, so we must keep the spin lock while
770            manipulating the lists */
771         cfs_spin_lock(&exp->exp_obd->obd_dev_lock);
772
773         if (cfs_list_empty(&exp->exp_obd_chain_timed)) {
774                 /* this one is not timed */
775                 cfs_spin_unlock(&exp->exp_obd->obd_dev_lock);
776                 RETURN_EXIT;
777         }
778
779         cfs_list_move_tail(&exp->exp_obd_chain_timed,
780                            &exp->exp_obd->obd_exports_timed);
781
782         oldest_exp = cfs_list_entry(exp->exp_obd->obd_exports_timed.next,
783                                     struct obd_export, exp_obd_chain_timed);
784         oldest_time = oldest_exp->exp_last_request_time;
785         cfs_spin_unlock(&exp->exp_obd->obd_dev_lock);
786
787         if (exp->exp_obd->obd_recovering) {
788                 /* be nice to everyone during recovery */
789                 EXIT;
790                 return;
791         }
792
793         /* Note - racing to start/reset the obd_eviction timer is safe */
794         if (exp->exp_obd->obd_eviction_timer == 0) {
795                 /* Check if the oldest entry is expired. */
796                 if (cfs_time_current_sec() > (oldest_time + PING_EVICT_TIMEOUT +
797                                               extra_delay)) {
798                         /* We need a second timer, in case the net was down and
799                          * it just came back. Since the pinger may skip every
800                          * other PING_INTERVAL (see note in ptlrpc_pinger_main),
801                          * we better wait for 3. */
802                         exp->exp_obd->obd_eviction_timer =
803                                 cfs_time_current_sec() + 3 * PING_INTERVAL;
804                         CDEBUG(D_HA, "%s: Think about evicting %s from "CFS_TIME_T"\n",
805                                exp->exp_obd->obd_name, 
806                                obd_export_nid2str(oldest_exp), oldest_time);
807                 }
808         } else {
809                 if (cfs_time_current_sec() >
810                     (exp->exp_obd->obd_eviction_timer + extra_delay)) {
811                         /* The evictor won't evict anyone who we've heard from
812                          * recently, so we don't have to check before we start
813                          * it. */
814                         if (!ping_evictor_wake(exp))
815                                 exp->exp_obd->obd_eviction_timer = 0;
816                 }
817         }
818
819         EXIT;
820 }
821
822 static int ptlrpc_check_req(struct ptlrpc_request *req)
823 {
824         if (unlikely(lustre_msg_get_conn_cnt(req->rq_reqmsg) <
825                      req->rq_export->exp_conn_cnt)) {
826                 DEBUG_REQ(D_ERROR, req,
827                           "DROPPING req from old connection %d < %d",
828                           lustre_msg_get_conn_cnt(req->rq_reqmsg),
829                           req->rq_export->exp_conn_cnt);
830                 return -EEXIST;
831         }
832         if (unlikely(req->rq_export->exp_obd &&
833                      req->rq_export->exp_obd->obd_fail)) {
834              /* Failing over, don't handle any more reqs, send
835                 error response instead. */
836                 CDEBUG(D_RPCTRACE, "Dropping req %p for failed obd %s\n",
837                        req, req->rq_export->exp_obd->obd_name);
838                 req->rq_status = -ENODEV;
839                 ptlrpc_error(req);
840                 return -ENODEV;
841         }
842
843         return 0;
844 }
845
846 static void ptlrpc_at_set_timer(struct ptlrpc_service *svc)
847 {
848         struct ptlrpc_at_array *array = &svc->srv_at_array;
849         __s32 next;
850
851         cfs_spin_lock(&svc->srv_at_lock);
852         if (array->paa_count == 0) {
853                 cfs_timer_disarm(&svc->srv_at_timer);
854                 cfs_spin_unlock(&svc->srv_at_lock);
855                 return;
856         }
857
858         /* Set timer for closest deadline */
859         next = (__s32)(array->paa_deadline - cfs_time_current_sec() -
860                        at_early_margin);
861         if (next <= 0)
862                 ptlrpc_at_timer((unsigned long)svc);
863         else
864                 cfs_timer_arm(&svc->srv_at_timer, cfs_time_shift(next));
865         cfs_spin_unlock(&svc->srv_at_lock);
866         CDEBUG(D_INFO, "armed %s at %+ds\n", svc->srv_name, next);
867 }
868
869 /* Add rpc to early reply check list */
870 static int ptlrpc_at_add_timed(struct ptlrpc_request *req)
871 {
872         struct ptlrpc_service *svc = req->rq_rqbd->rqbd_service;
873         struct ptlrpc_request *rq = NULL;
874         struct ptlrpc_at_array *array = &svc->srv_at_array;
875         __u32 index;
876         int found = 0;
877
878         if (AT_OFF)
879                 return(0);
880
881         if (req->rq_no_reply)
882                 return 0;
883
884         if ((lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT) == 0)
885                 return(-ENOSYS);
886
887         cfs_spin_lock(&svc->srv_at_lock);
888         LASSERT(cfs_list_empty(&req->rq_timed_list));
889
890         index = (unsigned long)req->rq_deadline % array->paa_size;
891         if (array->paa_reqs_count[index] > 0) {
892                 /* latest rpcs will have the latest deadlines in the list,
893                  * so search backward. */
894                 cfs_list_for_each_entry_reverse(rq,
895                                                 &array->paa_reqs_array[index],
896                                                 rq_timed_list) {
897                         if (req->rq_deadline >= rq->rq_deadline) {
898                                 cfs_list_add(&req->rq_timed_list,
899                                              &rq->rq_timed_list);
900                                 break;
901                         }
902                 }
903         }
904
905         /* Add the request at the head of the list */
906         if (cfs_list_empty(&req->rq_timed_list))
907                 cfs_list_add(&req->rq_timed_list,
908                              &array->paa_reqs_array[index]);
909
910         req->rq_at_linked = 1;
911         req->rq_at_index = index;
912         array->paa_reqs_count[index]++;
913         array->paa_count++;
914         if (array->paa_count == 1 || array->paa_deadline > req->rq_deadline) {
915                 array->paa_deadline = req->rq_deadline;
916                 found = 1;
917         }
918         cfs_spin_unlock(&svc->srv_at_lock);
919
920         if (found)
921                 ptlrpc_at_set_timer(svc);
922
923         return 0;
924 }
925
926 static int ptlrpc_at_send_early_reply(struct ptlrpc_request *req)
927 {
928         struct ptlrpc_service *svc = req->rq_rqbd->rqbd_service;
929         struct ptlrpc_request *reqcopy;
930         struct lustre_msg *reqmsg;
931         cfs_duration_t olddl = req->rq_deadline - cfs_time_current_sec();
932         time_t newdl;
933         int rc;
934         ENTRY;
935
936         /* deadline is when the client expects us to reply, margin is the
937            difference between clients' and servers' expectations */
938         DEBUG_REQ(D_ADAPTTO, req,
939                   "%ssending early reply (deadline %+lds, margin %+lds) for "
940                   "%d+%d", AT_OFF ? "AT off - not " : "",
941                   olddl, olddl - at_get(&svc->srv_at_estimate),
942                   at_get(&svc->srv_at_estimate), at_extra);
943
944         if (AT_OFF)
945                 RETURN(0);
946
947         if (olddl < 0) {
948                 DEBUG_REQ(D_WARNING, req, "Already past deadline (%+lds), "
949                           "not sending early reply. Consider increasing "
950                           "at_early_margin (%d)?", olddl, at_early_margin);
951
952                 /* Return an error so we're not re-added to the timed list. */
953                 RETURN(-ETIMEDOUT);
954         }
955
956         if ((lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT) == 0){
957                 DEBUG_REQ(D_INFO, req, "Wanted to ask client for more time, "
958                           "but no AT support");
959                 RETURN(-ENOSYS);
960         }
961
962         if (req->rq_export &&
963             lustre_msg_get_flags(req->rq_reqmsg) &
964             (MSG_REPLAY | MSG_REQ_REPLAY_DONE | MSG_LOCK_REPLAY_DONE)) {
965                 /**
966                  * Use at_extra as early reply period for recovery requests but
967                  * make sure it is not bigger than recovery time / 4
968                  */
969                 at_add(&svc->srv_at_estimate,
970                        min(at_extra,
971                            req->rq_export->exp_obd->obd_recovery_timeout / 4));
972         } else {
973                 /* Fake our processing time into the future to ask the clients
974                  * for some extra amount of time */
975                 at_add(&svc->srv_at_estimate, at_extra);
976         }
977
978         newdl = cfs_time_current_sec() + at_get(&svc->srv_at_estimate);
979         if (req->rq_deadline >= newdl) {
980                 /* We're not adding any time, no need to send an early reply
981                    (e.g. maybe at adaptive_max) */
982                 DEBUG_REQ(D_WARNING, req, "Couldn't add any time ("
983                           CFS_DURATION_T"/"CFS_DURATION_T"), "
984                           "not sending early reply\n", olddl,
985                           cfs_time_sub(newdl, cfs_time_current_sec()));
986                 RETURN(-ETIMEDOUT);
987         }
988
989         OBD_ALLOC(reqcopy, sizeof *reqcopy);
990         if (reqcopy == NULL)
991                 RETURN(-ENOMEM);
992         OBD_ALLOC(reqmsg, req->rq_reqlen);
993         if (!reqmsg) {
994                 OBD_FREE(reqcopy, sizeof *reqcopy);
995                 RETURN(-ENOMEM);
996         }
997
998         *reqcopy = *req;
999         reqcopy->rq_reply_state = NULL;
1000         reqcopy->rq_rep_swab_mask = 0;
1001         reqcopy->rq_pack_bulk = 0;
1002         reqcopy->rq_pack_udesc = 0;
1003         reqcopy->rq_packed_final = 0;
1004         sptlrpc_svc_ctx_addref(reqcopy);
1005         /* We only need the reqmsg for the magic */
1006         reqcopy->rq_reqmsg = reqmsg;
1007         memcpy(reqmsg, req->rq_reqmsg, req->rq_reqlen);
1008
1009         LASSERT(cfs_atomic_read(&req->rq_refcount));
1010         /** if it is last refcount then early reply isn't needed */
1011         if (cfs_atomic_read(&req->rq_refcount) == 1) {
1012                 DEBUG_REQ(D_ADAPTTO, reqcopy, "Normal reply already sent out, "
1013                           "abort sending early reply\n");
1014                 GOTO(out, rc = -EINVAL);
1015         }
1016
1017         /* Connection ref */
1018         reqcopy->rq_export = class_conn2export(
1019                                      lustre_msg_get_handle(reqcopy->rq_reqmsg));
1020         if (reqcopy->rq_export == NULL)
1021                 GOTO(out, rc = -ENODEV);
1022
1023         /* RPC ref */
1024         class_export_rpc_get(reqcopy->rq_export);
1025         if (reqcopy->rq_export->exp_obd &&
1026             reqcopy->rq_export->exp_obd->obd_fail)
1027                 GOTO(out_put, rc = -ENODEV);
1028
1029         rc = lustre_pack_reply_flags(reqcopy, 1, NULL, NULL, LPRFL_EARLY_REPLY);
1030         if (rc)
1031                 GOTO(out_put, rc);
1032
1033         rc = ptlrpc_send_reply(reqcopy, PTLRPC_REPLY_EARLY);
1034
1035         if (!rc) {
1036                 /* Adjust our own deadline to what we told the client */
1037                 req->rq_deadline = newdl;
1038                 req->rq_early_count++; /* number sent, server side */
1039         } else {
1040                 DEBUG_REQ(D_ERROR, req, "Early reply send failed %d", rc);
1041         }
1042
1043         /* Free the (early) reply state from lustre_pack_reply.
1044            (ptlrpc_send_reply takes it's own rs ref, so this is safe here) */
1045         ptlrpc_req_drop_rs(reqcopy);
1046
1047 out_put:
1048         class_export_rpc_put(reqcopy->rq_export);
1049         class_export_put(reqcopy->rq_export);
1050 out:
1051         sptlrpc_svc_ctx_decref(reqcopy);
1052         OBD_FREE(reqmsg, req->rq_reqlen);
1053         OBD_FREE(reqcopy, sizeof *reqcopy);
1054         RETURN(rc);
1055 }
1056
1057 /* Send early replies to everybody expiring within at_early_margin
1058    asking for at_extra time */
1059 static int ptlrpc_at_check_timed(struct ptlrpc_service *svc)
1060 {
1061         struct ptlrpc_request *rq, *n;
1062         cfs_list_t work_list;
1063         struct ptlrpc_at_array *array = &svc->srv_at_array;
1064         __u32  index, count;
1065         time_t deadline;
1066         time_t now = cfs_time_current_sec();
1067         cfs_duration_t delay;
1068         int first, counter = 0;
1069         ENTRY;
1070
1071         cfs_spin_lock(&svc->srv_at_lock);
1072         if (svc->srv_at_check == 0) {
1073                 cfs_spin_unlock(&svc->srv_at_lock);
1074                 RETURN(0);
1075         }
1076         delay = cfs_time_sub(cfs_time_current(), svc->srv_at_checktime);
1077         svc->srv_at_check = 0;
1078
1079         if (array->paa_count == 0) {
1080                 cfs_spin_unlock(&svc->srv_at_lock);
1081                 RETURN(0);
1082         }
1083
1084         /* The timer went off, but maybe the nearest rpc already completed. */
1085         first = array->paa_deadline - now;
1086         if (first > at_early_margin) {
1087                 /* We've still got plenty of time.  Reset the timer. */
1088                 cfs_spin_unlock(&svc->srv_at_lock);
1089                 ptlrpc_at_set_timer(svc);
1090                 RETURN(0);
1091         }
1092
1093         /* We're close to a timeout, and we don't know how much longer the
1094            server will take. Send early replies to everyone expiring soon. */
1095         CFS_INIT_LIST_HEAD(&work_list);
1096         deadline = -1;
1097         index = (unsigned long)array->paa_deadline % array->paa_size;
1098         count = array->paa_count;
1099         while (count > 0) {
1100                 count -= array->paa_reqs_count[index];
1101                 cfs_list_for_each_entry_safe(rq, n,
1102                                              &array->paa_reqs_array[index],
1103                                              rq_timed_list) {
1104                         if (rq->rq_deadline <= now + at_early_margin) {
1105                                 cfs_list_del_init(&rq->rq_timed_list);
1106                                 /**
1107                                  * ptlrpc_server_drop_request() may drop
1108                                  * refcount to 0 already. Let's check this and
1109                                  * don't add entry to work_list
1110                                  */
1111                                 if (likely(cfs_atomic_inc_not_zero(&rq->rq_refcount)))
1112                                         cfs_list_add(&rq->rq_timed_list, &work_list);
1113                                 counter++;
1114                                 array->paa_reqs_count[index]--;
1115                                 array->paa_count--;
1116                                 rq->rq_at_linked = 0;
1117                                 continue;
1118                         }
1119
1120                         /* update the earliest deadline */
1121                         if (deadline == -1 || rq->rq_deadline < deadline)
1122                                 deadline = rq->rq_deadline;
1123
1124                         break;
1125                 }
1126
1127                 if (++index >= array->paa_size)
1128                         index = 0;
1129         }
1130         array->paa_deadline = deadline;
1131         cfs_spin_unlock(&svc->srv_at_lock);
1132
1133         /* we have a new earliest deadline, restart the timer */
1134         ptlrpc_at_set_timer(svc);
1135
1136         CDEBUG(D_ADAPTTO, "timeout in %+ds, asking for %d secs on %d early "
1137                "replies\n", first, at_extra, counter);
1138         if (first < 0) {
1139                 /* We're already past request deadlines before we even get a
1140                    chance to send early replies */
1141                 LCONSOLE_WARN("%s: This server is not able to keep up with "
1142                               "request traffic (cpu-bound).\n", svc->srv_name);
1143                 CWARN("earlyQ=%d reqQ=%d recA=%d, svcEst=%d, "
1144                       "delay="CFS_DURATION_T"(jiff)\n",
1145                       counter, svc->srv_n_queued_reqs, svc->srv_n_active_reqs,
1146                       at_get(&svc->srv_at_estimate), delay);
1147         }
1148
1149         /* we took additional refcount so entries can't be deleted from list, no
1150          * locking is needed */
1151         while (!cfs_list_empty(&work_list)) {
1152                 rq = cfs_list_entry(work_list.next, struct ptlrpc_request,
1153                                     rq_timed_list);
1154                 cfs_list_del_init(&rq->rq_timed_list);
1155
1156                 if (ptlrpc_at_send_early_reply(rq) == 0)
1157                         ptlrpc_at_add_timed(rq);
1158
1159                 ptlrpc_server_drop_request(rq);
1160         }
1161
1162         RETURN(0);
1163 }
1164
1165 /**
1166  * Put the request to the export list if the request may become
1167  * a high priority one.
1168  */
1169 static int ptlrpc_hpreq_init(struct ptlrpc_service *svc,
1170                              struct ptlrpc_request *req)
1171 {
1172         int rc;
1173         ENTRY;
1174
1175         if (svc->srv_hpreq_handler) {
1176                 rc = svc->srv_hpreq_handler(req);
1177                 if (rc)
1178                         RETURN(rc);
1179         }
1180         if (req->rq_export && req->rq_ops) {
1181                 cfs_spin_lock(&req->rq_export->exp_lock);
1182                 cfs_list_add(&req->rq_exp_list,
1183                              &req->rq_export->exp_queued_rpc);
1184                 cfs_spin_unlock(&req->rq_export->exp_lock);
1185         }
1186
1187         RETURN(0);
1188 }
1189
1190 /** Remove the request from the export list. */
1191 static void ptlrpc_hpreq_fini(struct ptlrpc_request *req)
1192 {
1193         ENTRY;
1194         if (req->rq_export && req->rq_ops) {
1195                 cfs_spin_lock(&req->rq_export->exp_lock);
1196                 cfs_list_del_init(&req->rq_exp_list);
1197                 cfs_spin_unlock(&req->rq_export->exp_lock);
1198         }
1199         EXIT;
1200 }
1201
1202 /**
1203  * Make the request a high priority one.
1204  *
1205  * All the high priority requests are queued in a separate FIFO
1206  * ptlrpc_service::srv_request_hpq list which is parallel to
1207  * ptlrpc_service::srv_request_queue list but has a higher priority
1208  * for handling.
1209  *
1210  * \see ptlrpc_server_handle_request().
1211  */
1212 static void ptlrpc_hpreq_reorder_nolock(struct ptlrpc_service *svc,
1213                                         struct ptlrpc_request *req)
1214 {
1215         ENTRY;
1216         LASSERT(svc != NULL);
1217         cfs_spin_lock(&req->rq_lock);
1218         if (req->rq_hp == 0) {
1219                 int opc = lustre_msg_get_opc(req->rq_reqmsg);
1220
1221                 /* Add to the high priority queue. */
1222                 cfs_list_move_tail(&req->rq_list, &svc->srv_request_hpq);
1223                 req->rq_hp = 1;
1224                 if (opc != OBD_PING)
1225                         DEBUG_REQ(D_NET, req, "high priority req");
1226         }
1227         cfs_spin_unlock(&req->rq_lock);
1228         EXIT;
1229 }
1230
1231 void ptlrpc_hpreq_reorder(struct ptlrpc_request *req)
1232 {
1233         struct ptlrpc_service *svc = req->rq_rqbd->rqbd_service;
1234         ENTRY;
1235
1236         cfs_spin_lock(&svc->srv_lock);
1237         /* It may happen that the request is already taken for the processing
1238          * but still in the export list, do not re-add it into the HP list. */
1239         if (req->rq_phase == RQ_PHASE_NEW)
1240                 ptlrpc_hpreq_reorder_nolock(svc, req);
1241         cfs_spin_unlock(&svc->srv_lock);
1242         EXIT;
1243 }
1244
1245 /** Check if the request is a high priority one. */
1246 static int ptlrpc_server_hpreq_check(struct ptlrpc_request *req)
1247 {
1248         int opc, rc = 0;
1249         ENTRY;
1250
1251         /* Check by request opc. */
1252         opc = lustre_msg_get_opc(req->rq_reqmsg);
1253         if (opc == OBD_PING)
1254                 RETURN(1);
1255
1256         /* Perform request specific check. */
1257         if (req->rq_ops && req->rq_ops->hpreq_check)
1258                 rc = req->rq_ops->hpreq_check(req);
1259         RETURN(rc);
1260 }
1261
1262 /** Check if a request is a high priority one. */
1263 static int ptlrpc_server_request_add(struct ptlrpc_service *svc,
1264                                      struct ptlrpc_request *req)
1265 {
1266         int rc;
1267         ENTRY;
1268
1269         rc = ptlrpc_server_hpreq_check(req);
1270         if (rc < 0)
1271                 RETURN(rc);
1272
1273         cfs_spin_lock(&svc->srv_lock);
1274         /* Before inserting the request into the queue, check if it is not
1275          * inserted yet, or even already handled -- it may happen due to
1276          * a racing ldlm_server_blocking_ast(). */
1277         if (req->rq_phase == RQ_PHASE_NEW && cfs_list_empty(&req->rq_list)) {
1278                 if (rc)
1279                         ptlrpc_hpreq_reorder_nolock(svc, req);
1280                 else
1281                         cfs_list_add_tail(&req->rq_list,
1282                                           &svc->srv_request_queue);
1283         }
1284         cfs_spin_unlock(&svc->srv_lock);
1285
1286         RETURN(0);
1287 }
1288
1289 /* Only allow normal priority requests on a service that has a high-priority
1290  * queue if forced (i.e. cleanup), if there are other high priority requests
1291  * already being processed (i.e. those threads can service more high-priority
1292  * requests), or if there are enough idle threads that a later thread can do
1293  * a high priority request. */
1294 static int ptlrpc_server_allow_normal(struct ptlrpc_service *svc, int force)
1295 {
1296         return force || !svc->srv_hpreq_handler || svc->srv_n_hpreq > 0 ||
1297                svc->srv_n_active_reqs < svc->srv_threads_running - 2;
1298 }
1299
1300 static struct ptlrpc_request *
1301 ptlrpc_server_request_get(struct ptlrpc_service *svc, int force)
1302 {
1303         struct ptlrpc_request *req = NULL;
1304         ENTRY;
1305
1306         if (ptlrpc_server_allow_normal(svc, force) &&
1307             !cfs_list_empty(&svc->srv_request_queue) &&
1308             (cfs_list_empty(&svc->srv_request_hpq) ||
1309              svc->srv_hpreq_count >= svc->srv_hpreq_ratio)) {
1310                 req = cfs_list_entry(svc->srv_request_queue.next,
1311                                      struct ptlrpc_request, rq_list);
1312                 svc->srv_hpreq_count = 0;
1313         } else if (!cfs_list_empty(&svc->srv_request_hpq)) {
1314                 req = cfs_list_entry(svc->srv_request_hpq.next,
1315                                      struct ptlrpc_request, rq_list);
1316                 svc->srv_hpreq_count++;
1317         }
1318         RETURN(req);
1319 }
1320
1321 static int ptlrpc_server_request_pending(struct ptlrpc_service *svc, int force)
1322 {
1323         return ((ptlrpc_server_allow_normal(svc, force) &&
1324                  !cfs_list_empty(&svc->srv_request_queue)) ||
1325                 !cfs_list_empty(&svc->srv_request_hpq));
1326 }
1327
1328 /* Handle freshly incoming reqs, add to timed early reply list,
1329    pass on to regular request queue */
1330 static int
1331 ptlrpc_server_handle_req_in(struct ptlrpc_service *svc)
1332 {
1333         struct ptlrpc_request *req;
1334         __u32                  deadline;
1335         int                    rc;
1336         ENTRY;
1337
1338         LASSERT(svc);
1339
1340         cfs_spin_lock(&svc->srv_lock);
1341         if (cfs_list_empty(&svc->srv_req_in_queue)) {
1342                 cfs_spin_unlock(&svc->srv_lock);
1343                 RETURN(0);
1344         }
1345
1346         req = cfs_list_entry(svc->srv_req_in_queue.next,
1347                              struct ptlrpc_request, rq_list);
1348         cfs_list_del_init (&req->rq_list);
1349         /* Consider this still a "queued" request as far as stats are
1350            concerned */
1351         cfs_spin_unlock(&svc->srv_lock);
1352
1353         /* go through security check/transform */
1354         rc = sptlrpc_svc_unwrap_request(req);
1355         switch (rc) {
1356         case SECSVC_OK:
1357                 break;
1358         case SECSVC_COMPLETE:
1359                 target_send_reply(req, 0, OBD_FAIL_MDS_ALL_REPLY_NET);
1360                 goto err_req;
1361         case SECSVC_DROP:
1362                 goto err_req;
1363         default:
1364                 LBUG();
1365         }
1366
1367         /*
1368          * for null-flavored rpc, msg has been unpacked by sptlrpc, although
1369          * redo it wouldn't be harmful.
1370          */
1371         if (SPTLRPC_FLVR_POLICY(req->rq_flvr.sf_rpc) != SPTLRPC_POLICY_NULL) {
1372                 rc = ptlrpc_unpack_req_msg(req, req->rq_reqlen);
1373                 if (rc != 0) {
1374                         CERROR("error unpacking request: ptl %d from %s "
1375                                "x"LPU64"\n", svc->srv_req_portal,
1376                                libcfs_id2str(req->rq_peer), req->rq_xid);
1377                         goto err_req;
1378                 }
1379         }
1380
1381         rc = lustre_unpack_req_ptlrpc_body(req, MSG_PTLRPC_BODY_OFF);
1382         if (rc) {
1383                 CERROR ("error unpacking ptlrpc body: ptl %d from %s x"
1384                         LPU64"\n", svc->srv_req_portal,
1385                         libcfs_id2str(req->rq_peer), req->rq_xid);
1386                 goto err_req;
1387         }
1388
1389         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_DROP_REQ_OPC) &&
1390             lustre_msg_get_opc(req->rq_reqmsg) == obd_fail_val) {
1391                 CERROR("drop incoming rpc opc %u, x"LPU64"\n",
1392                        obd_fail_val, req->rq_xid);
1393                 goto err_req;
1394         }
1395
1396         rc = -EINVAL;
1397         if (lustre_msg_get_type(req->rq_reqmsg) != PTL_RPC_MSG_REQUEST) {
1398                 CERROR("wrong packet type received (type=%u) from %s\n",
1399                        lustre_msg_get_type(req->rq_reqmsg),
1400                        libcfs_id2str(req->rq_peer));
1401                 goto err_req;
1402         }
1403
1404         switch(lustre_msg_get_opc(req->rq_reqmsg)) {
1405         case MDS_WRITEPAGE:
1406         case OST_WRITE:
1407                 req->rq_bulk_write = 1;
1408                 break;
1409         case MDS_READPAGE:
1410         case OST_READ:
1411                 req->rq_bulk_read = 1;
1412                 break;
1413         }
1414
1415         CDEBUG(D_NET, "got req "LPU64"\n", req->rq_xid);
1416
1417         req->rq_export = class_conn2export(
1418                 lustre_msg_get_handle(req->rq_reqmsg));
1419         if (req->rq_export) {
1420                 rc = ptlrpc_check_req(req);
1421                 if (rc == 0) {
1422                         rc = sptlrpc_target_export_check(req->rq_export, req);
1423                         if (rc)
1424                                 DEBUG_REQ(D_ERROR, req, "DROPPING req with "
1425                                           "illegal security flavor,");
1426                 }
1427
1428                 if (rc)
1429                         goto err_req;
1430                 ptlrpc_update_export_timer(req->rq_export, 0);
1431         }
1432
1433         /* req_in handling should/must be fast */
1434         if (cfs_time_current_sec() - req->rq_arrival_time.tv_sec > 5)
1435                 DEBUG_REQ(D_WARNING, req, "Slow req_in handling "CFS_DURATION_T"s",
1436                           cfs_time_sub(cfs_time_current_sec(),
1437                                        req->rq_arrival_time.tv_sec));
1438
1439         /* Set rpc server deadline and add it to the timed list */
1440         deadline = (lustre_msghdr_get_flags(req->rq_reqmsg) &
1441                     MSGHDR_AT_SUPPORT) ?
1442                    /* The max time the client expects us to take */
1443                    lustre_msg_get_timeout(req->rq_reqmsg) : obd_timeout;
1444         req->rq_deadline = req->rq_arrival_time.tv_sec + deadline;
1445         if (unlikely(deadline == 0)) {
1446                 DEBUG_REQ(D_ERROR, req, "Dropping request with 0 timeout");
1447                 goto err_req;
1448         }
1449
1450         ptlrpc_at_add_timed(req);
1451         rc = ptlrpc_hpreq_init(svc, req);
1452         if (rc)
1453                 GOTO(err_req, rc);
1454
1455         /* Move it over to the request processing queue */
1456         rc = ptlrpc_server_request_add(svc, req);
1457         if (rc)
1458                 GOTO(err_req, rc);
1459         cfs_waitq_signal(&svc->srv_waitq);
1460         RETURN(1);
1461
1462 err_req:
1463         cfs_spin_lock(&svc->srv_lock);
1464         svc->srv_n_queued_reqs--;
1465         svc->srv_n_active_reqs++;
1466         cfs_spin_unlock(&svc->srv_lock);
1467         ptlrpc_server_finish_request(req);
1468
1469         RETURN(1);
1470 }
1471
1472 static int
1473 ptlrpc_server_handle_request(struct ptlrpc_service *svc,
1474                              struct ptlrpc_thread *thread)
1475 {
1476         struct obd_export     *export = NULL;
1477         struct ptlrpc_request *request;
1478         struct timeval         work_start;
1479         struct timeval         work_end;
1480         long                   timediff;
1481         int                    opc, rc;
1482         int                    fail_opc = 0;
1483         ENTRY;
1484
1485         LASSERT(svc);
1486
1487         cfs_spin_lock(&svc->srv_lock);
1488         if (unlikely(!ptlrpc_server_request_pending(svc, 0) ||
1489             (
1490 #ifndef __KERNEL__
1491              /* !@%$# liblustre only has 1 thread */
1492              cfs_atomic_read(&svc->srv_n_difficult_replies) != 0 &&
1493 #endif
1494              svc->srv_n_active_reqs >= (svc->srv_threads_running - 1)))) {
1495                  /* Don't handle regular requests in the last thread, in order               * re
1496                   * to handle difficult replies (which might block other threads)
1497                   * as well as handle any incoming reqs, early replies, etc.
1498                   * That means we always need at least 2 service threads. */
1499                 cfs_spin_unlock(&svc->srv_lock);
1500                 RETURN(0);
1501              }
1502
1503         request = ptlrpc_server_request_get(svc, 0);
1504         if  (request == NULL) {
1505                 cfs_spin_unlock(&svc->srv_lock);
1506                 RETURN(0);
1507         }
1508
1509         opc = lustre_msg_get_opc(request->rq_reqmsg);
1510         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT))
1511                 fail_opc = OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT;
1512         else if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT))
1513                 fail_opc = OBD_FAIL_PTLRPC_HPREQ_TIMEOUT;
1514
1515         if (unlikely(fail_opc)) {
1516                 if (request->rq_export && request->rq_ops) {
1517                         cfs_spin_unlock(&svc->srv_lock);
1518                         OBD_FAIL_TIMEOUT(fail_opc, 4);
1519                         cfs_spin_lock(&svc->srv_lock);
1520                         request = ptlrpc_server_request_get(svc, 0);
1521                         if  (request == NULL) {
1522                                 cfs_spin_unlock(&svc->srv_lock);
1523                                 RETURN(0);
1524                         }
1525                         LASSERT(ptlrpc_server_request_pending(svc, 0));
1526                 }
1527         }
1528
1529         cfs_list_del_init(&request->rq_list);
1530         svc->srv_n_queued_reqs--;
1531         svc->srv_n_active_reqs++;
1532         if (request->rq_hp)
1533                 svc->srv_n_hpreq++;
1534
1535         /* The phase is changed under the lock here because we need to know
1536          * the request is under processing (see ptlrpc_hpreq_reorder()). */
1537         ptlrpc_rqphase_move(request, RQ_PHASE_INTERPRET);
1538         cfs_spin_unlock(&svc->srv_lock);
1539
1540         ptlrpc_hpreq_fini(request);
1541
1542         if(OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_DUMP_LOG))
1543                 libcfs_debug_dumplog();
1544
1545         cfs_gettimeofday(&work_start);
1546         timediff = cfs_timeval_sub(&work_start, &request->rq_arrival_time,NULL);
1547         if (likely(svc->srv_stats != NULL)) {
1548                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQWAIT_CNTR,
1549                                     timediff);
1550                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQQDEPTH_CNTR,
1551                                     svc->srv_n_queued_reqs);
1552                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQACTIVE_CNTR,
1553                                     svc->srv_n_active_reqs);
1554                 lprocfs_counter_add(svc->srv_stats, PTLRPC_TIMEOUT,
1555                                     at_get(&svc->srv_at_estimate));
1556         }
1557
1558         rc = lu_context_init(&request->rq_session,
1559                              LCT_SESSION|LCT_REMEMBER|LCT_NOREF);
1560         if (rc) {
1561                 CERROR("Failure to initialize session: %d\n", rc);
1562                 goto out_req;
1563         }
1564         request->rq_session.lc_thread = thread;
1565         request->rq_session.lc_cookie = 0x5;
1566         lu_context_enter(&request->rq_session);
1567
1568         CDEBUG(D_NET, "got req "LPU64"\n", request->rq_xid);
1569
1570         request->rq_svc_thread = thread;
1571         if (thread)
1572                 request->rq_svc_thread->t_env->le_ses = &request->rq_session;
1573
1574         if (likely(request->rq_export)) {
1575                 if (unlikely(ptlrpc_check_req(request)))
1576                         goto put_conn;
1577                 ptlrpc_update_export_timer(request->rq_export, timediff >> 19);
1578                 export = class_export_rpc_get(request->rq_export);
1579         }
1580
1581         /* Discard requests queued for longer than the deadline.
1582            The deadline is increased if we send an early reply. */
1583         if (cfs_time_current_sec() > request->rq_deadline) {
1584                 DEBUG_REQ(D_ERROR, request, "Dropping timed-out request from %s"
1585                           ": deadline "CFS_DURATION_T":"CFS_DURATION_T"s ago\n",
1586                           libcfs_id2str(request->rq_peer),
1587                           cfs_time_sub(request->rq_deadline,
1588                           request->rq_arrival_time.tv_sec),
1589                           cfs_time_sub(cfs_time_current_sec(),
1590                           request->rq_deadline));
1591                 goto put_rpc_export;
1592         }
1593
1594         CDEBUG(D_RPCTRACE, "Handling RPC pname:cluuid+ref:pid:xid:nid:opc "
1595                "%s:%s+%d:%d:x"LPU64":%s:%d\n", cfs_curproc_comm(),
1596                (request->rq_export ?
1597                 (char *)request->rq_export->exp_client_uuid.uuid : "0"),
1598                (request->rq_export ?
1599                 cfs_atomic_read(&request->rq_export->exp_refcount) : -99),
1600                lustre_msg_get_status(request->rq_reqmsg), request->rq_xid,
1601                libcfs_id2str(request->rq_peer),
1602                lustre_msg_get_opc(request->rq_reqmsg));
1603
1604         if (lustre_msg_get_opc(request->rq_reqmsg) != OBD_PING)
1605                 OBD_FAIL_TIMEOUT_MS(OBD_FAIL_PTLRPC_PAUSE_REQ, obd_fail_val);
1606
1607         rc = svc->srv_handler(request);
1608
1609         ptlrpc_rqphase_move(request, RQ_PHASE_COMPLETE);
1610
1611 put_rpc_export:
1612         if (export != NULL)
1613                 class_export_rpc_put(export);
1614 put_conn:
1615         lu_context_exit(&request->rq_session);
1616         lu_context_fini(&request->rq_session);
1617
1618         if (unlikely(cfs_time_current_sec() > request->rq_deadline)) {
1619                 DEBUG_REQ(D_WARNING, request, "Request x"LPU64" took longer "
1620                           "than estimated ("CFS_DURATION_T":"CFS_DURATION_T"s);"
1621                           " client may timeout.",
1622                           request->rq_xid, cfs_time_sub(request->rq_deadline,
1623                           request->rq_arrival_time.tv_sec),
1624                           cfs_time_sub(cfs_time_current_sec(),
1625                           request->rq_deadline));
1626         }
1627
1628         cfs_gettimeofday(&work_end);
1629         timediff = cfs_timeval_sub(&work_end, &work_start, NULL);
1630         CDEBUG(D_RPCTRACE, "Handled RPC pname:cluuid+ref:pid:xid:nid:opc "
1631                "%s:%s+%d:%d:x"LPU64":%s:%d Request procesed in "
1632                "%ldus (%ldus total) trans "LPU64" rc %d/%d\n",
1633                 cfs_curproc_comm(),
1634                 (request->rq_export ?
1635                  (char *)request->rq_export->exp_client_uuid.uuid : "0"),
1636                 (request->rq_export ?
1637                  cfs_atomic_read(&request->rq_export->exp_refcount) : -99),
1638                 lustre_msg_get_status(request->rq_reqmsg),
1639                 request->rq_xid,
1640                 libcfs_id2str(request->rq_peer),
1641                 lustre_msg_get_opc(request->rq_reqmsg),
1642                 timediff,
1643                 cfs_timeval_sub(&work_end, &request->rq_arrival_time, NULL),
1644                 (request->rq_repmsg ?
1645                  lustre_msg_get_transno(request->rq_repmsg) :
1646                  request->rq_transno),
1647                 request->rq_status,
1648                 (request->rq_repmsg ?
1649                  lustre_msg_get_status(request->rq_repmsg) : -999));
1650         if (likely(svc->srv_stats != NULL && request->rq_reqmsg != NULL)) {
1651                 __u32 op = lustre_msg_get_opc(request->rq_reqmsg);
1652                 int opc = opcode_offset(op);
1653                 if (opc > 0 && !(op == LDLM_ENQUEUE || op == MDS_REINT)) {
1654                         LASSERT(opc < LUSTRE_MAX_OPCODES);
1655                         lprocfs_counter_add(svc->srv_stats,
1656                                             opc + EXTRA_MAX_OPCODES,
1657                                             timediff);
1658                 }
1659         }
1660         if (unlikely(request->rq_early_count)) {
1661                 DEBUG_REQ(D_ADAPTTO, request,
1662                           "sent %d early replies before finishing in "
1663                           CFS_DURATION_T"s",
1664                           request->rq_early_count,
1665                           cfs_time_sub(work_end.tv_sec,
1666                           request->rq_arrival_time.tv_sec));
1667         }
1668
1669 out_req:
1670         cfs_spin_lock(&svc->srv_lock);
1671         if (request->rq_hp)
1672                 svc->srv_n_hpreq--;
1673         cfs_spin_unlock(&svc->srv_lock);
1674         ptlrpc_server_finish_request(request);
1675
1676         RETURN(1);
1677 }
1678
1679 /**
1680  * An internal function to process a single reply state object.
1681  */
1682 static int
1683 ptlrpc_handle_rs (struct ptlrpc_reply_state *rs)
1684 {
1685         struct ptlrpc_service     *svc = rs->rs_service;
1686         struct obd_export         *exp;
1687         struct obd_device         *obd;
1688         int                        nlocks;
1689         int                        been_handled;
1690         ENTRY;
1691
1692         exp = rs->rs_export;
1693         obd = exp->exp_obd;
1694
1695         LASSERT (rs->rs_difficult);
1696         LASSERT (rs->rs_scheduled);
1697         LASSERT (cfs_list_empty(&rs->rs_list));
1698
1699         cfs_spin_lock (&exp->exp_lock);
1700         /* Noop if removed already */
1701         cfs_list_del_init (&rs->rs_exp_list);
1702         cfs_spin_unlock (&exp->exp_lock);
1703
1704         /* The disk commit callback holds exp_uncommitted_replies_lock while it
1705          * iterates over newly committed replies, removing them from
1706          * exp_uncommitted_replies.  It then drops this lock and schedules the
1707          * replies it found for handling here.
1708          *
1709          * We can avoid contention for exp_uncommitted_replies_lock between the
1710          * HRT threads and further commit callbacks by checking rs_committed
1711          * which is set in the commit callback while it holds both
1712          * rs_lock and exp_uncommitted_reples.
1713          *
1714          * If we see rs_committed clear, the commit callback _may_ not have
1715          * handled this reply yet and we race with it to grab
1716          * exp_uncommitted_replies_lock before removing the reply from
1717          * exp_uncommitted_replies.  Note that if we lose the race and the
1718          * reply has already been removed, list_del_init() is a noop.
1719          *
1720          * If we see rs_committed set, we know the commit callback is handling,
1721          * or has handled this reply since store reordering might allow us to
1722          * see rs_committed set out of sequence.  But since this is done
1723          * holding rs_lock, we can be sure it has all completed once we hold
1724          * rs_lock, which we do right next.
1725          */
1726         if (!rs->rs_committed) {
1727                 cfs_spin_lock(&exp->exp_uncommitted_replies_lock);
1728                 cfs_list_del_init(&rs->rs_obd_list);
1729                 cfs_spin_unlock(&exp->exp_uncommitted_replies_lock);
1730         }
1731
1732         cfs_spin_lock(&rs->rs_lock);
1733
1734         been_handled = rs->rs_handled;
1735         rs->rs_handled = 1;
1736
1737         nlocks = rs->rs_nlocks;                 /* atomic "steal", but */
1738         rs->rs_nlocks = 0;                      /* locks still on rs_locks! */
1739
1740         if (nlocks == 0 && !been_handled) {
1741                 /* If we see this, we should already have seen the warning
1742                  * in mds_steal_ack_locks()  */
1743                 CWARN("All locks stolen from rs %p x"LPD64".t"LPD64
1744                       " o%d NID %s\n",
1745                       rs,
1746                       rs->rs_xid, rs->rs_transno, rs->rs_opc,
1747                       libcfs_nid2str(exp->exp_connection->c_peer.nid));
1748         }
1749
1750         if ((!been_handled && rs->rs_on_net) || nlocks > 0) {
1751                 cfs_spin_unlock(&rs->rs_lock);
1752
1753                 if (!been_handled && rs->rs_on_net) {
1754                         LNetMDUnlink(rs->rs_md_h);
1755                         /* Ignore return code; we're racing with
1756                          * completion... */
1757                 }
1758
1759                 while (nlocks-- > 0)
1760                         ldlm_lock_decref(&rs->rs_locks[nlocks],
1761                                          rs->rs_modes[nlocks]);
1762
1763                 cfs_spin_lock(&rs->rs_lock);
1764         }
1765
1766         rs->rs_scheduled = 0;
1767
1768         if (!rs->rs_on_net) {
1769                 /* Off the net */
1770                 cfs_spin_unlock(&rs->rs_lock);
1771
1772                 class_export_put (exp);
1773                 rs->rs_export = NULL;
1774                 ptlrpc_rs_decref (rs);
1775                 cfs_atomic_dec (&svc->srv_outstanding_replies);
1776                 if (cfs_atomic_dec_and_test(&svc->srv_n_difficult_replies) &&
1777                     svc->srv_is_stopping)
1778                         cfs_waitq_broadcast(&svc->srv_waitq);
1779                 RETURN(1);
1780         }
1781
1782         /* still on the net; callback will schedule */
1783         cfs_spin_unlock(&rs->rs_lock);
1784         RETURN(1);
1785 }
1786
1787 #ifndef __KERNEL__
1788
1789 /**
1790  * Check whether given service has a reply available for processing
1791  * and process it.
1792  *
1793  * \param svc a ptlrpc service
1794  * \retval 0 no replies processed
1795  * \retval 1 one reply processed
1796  */
1797 static int
1798 ptlrpc_server_handle_reply(struct ptlrpc_service *svc)
1799 {
1800         struct ptlrpc_reply_state *rs = NULL;
1801         ENTRY;
1802
1803         cfs_spin_lock(&svc->srv_lock);
1804         if (!cfs_list_empty(&svc->srv_reply_queue)) {
1805                 rs = cfs_list_entry(svc->srv_reply_queue.prev,
1806                                     struct ptlrpc_reply_state,
1807                                     rs_list);
1808                 cfs_list_del_init(&rs->rs_list);
1809         }
1810         cfs_spin_unlock(&svc->srv_lock);
1811         if (rs != NULL)
1812                 ptlrpc_handle_rs(rs);
1813         RETURN(rs != NULL);
1814 }
1815
1816 /* FIXME make use of timeout later */
1817 int
1818 liblustre_check_services (void *arg)
1819 {
1820         int  did_something = 0;
1821         int  rc;
1822         cfs_list_t *tmp, *nxt;
1823         ENTRY;
1824
1825         /* I'm relying on being single threaded, not to have to lock
1826          * ptlrpc_all_services etc */
1827         cfs_list_for_each_safe (tmp, nxt, &ptlrpc_all_services) {
1828                 struct ptlrpc_service *svc =
1829                         cfs_list_entry (tmp, struct ptlrpc_service, srv_list);
1830
1831                 if (svc->srv_threads_running != 0)     /* I've recursed */
1832                         continue;
1833
1834                 /* service threads can block for bulk, so this limits us
1835                  * (arbitrarily) to recursing 1 stack frame per service.
1836                  * Note that the problem with recursion is that we have to
1837                  * unwind completely before our caller can resume. */
1838
1839                 svc->srv_threads_running++;
1840
1841                 do {
1842                         rc = ptlrpc_server_handle_req_in(svc);
1843                         rc |= ptlrpc_server_handle_reply(svc);
1844                         rc |= ptlrpc_at_check_timed(svc);
1845                         rc |= ptlrpc_server_handle_request(svc, NULL);
1846                         rc |= (ptlrpc_server_post_idle_rqbds(svc) > 0);
1847                         did_something |= rc;
1848                 } while (rc);
1849
1850                 svc->srv_threads_running--;
1851         }
1852
1853         RETURN(did_something);
1854 }
1855 #define ptlrpc_stop_all_threads(s) do {} while (0)
1856
1857 #else /* __KERNEL__ */
1858
1859 static void
1860 ptlrpc_check_rqbd_pool(struct ptlrpc_service *svc)
1861 {
1862         int avail = svc->srv_nrqbd_receiving;
1863         int low_water = test_req_buffer_pressure ? 0 :
1864                         svc->srv_nbuf_per_group/2;
1865
1866         /* NB I'm not locking; just looking. */
1867
1868         /* CAVEAT EMPTOR: We might be allocating buffers here because we've
1869          * allowed the request history to grow out of control.  We could put a
1870          * sanity check on that here and cull some history if we need the
1871          * space. */
1872
1873         if (avail <= low_water)
1874                 ptlrpc_grow_req_bufs(svc);
1875
1876         if (svc->srv_stats)
1877                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQBUF_AVAIL_CNTR,
1878                                     avail);
1879 }
1880
1881 static int
1882 ptlrpc_retry_rqbds(void *arg)
1883 {
1884         struct ptlrpc_service *svc = (struct ptlrpc_service *)arg;
1885
1886         svc->srv_rqbd_timeout = 0;
1887         return (-ETIMEDOUT);
1888 }
1889
1890 static int ptlrpc_main(void *arg)
1891 {
1892         struct ptlrpc_svc_data *data = (struct ptlrpc_svc_data *)arg;
1893         struct ptlrpc_service  *svc = data->svc;
1894         struct ptlrpc_thread   *thread = data->thread;
1895         struct obd_device      *dev = data->dev;
1896         struct ptlrpc_reply_state *rs;
1897 #ifdef WITH_GROUP_INFO
1898         cfs_group_info_t *ginfo = NULL;
1899 #endif
1900         struct lu_env env;
1901         int counter = 0, rc = 0;
1902         ENTRY;
1903
1904         thread->t_pid = cfs_curproc_pid();
1905         cfs_daemonize_ctxt(data->name);
1906
1907 #if defined(HAVE_NODE_TO_CPUMASK) && defined(CONFIG_NUMA)
1908         /* we need to do this before any per-thread allocation is done so that
1909          * we get the per-thread allocations on local node.  bug 7342 */
1910         if (svc->srv_cpu_affinity) {
1911                 int cpu, num_cpu;
1912
1913                 for (cpu = 0, num_cpu = 0; cpu < cfs_num_possible_cpus();
1914                      cpu++) {
1915                         if (!cfs_cpu_online(cpu))
1916                                 continue;
1917                         if (num_cpu == thread->t_id % cfs_num_online_cpus())
1918                                 break;
1919                         num_cpu++;
1920                 }
1921                 cfs_set_cpus_allowed(cfs_current(),
1922                                      node_to_cpumask(cpu_to_node(cpu)));
1923         }
1924 #endif
1925
1926 #ifdef WITH_GROUP_INFO
1927         ginfo = cfs_groups_alloc(0);
1928         if (!ginfo) {
1929                 rc = -ENOMEM;
1930                 goto out;
1931         }
1932
1933         cfs_set_current_groups(ginfo);
1934         cfs_put_group_info(ginfo);
1935 #endif
1936
1937         if (svc->srv_init != NULL) {
1938                 rc = svc->srv_init(thread);
1939                 if (rc)
1940                         goto out;
1941         }
1942
1943         rc = lu_context_init(&env.le_ctx,
1944                              svc->srv_ctx_tags|LCT_REMEMBER|LCT_NOREF);
1945         if (rc)
1946                 goto out_srv_fini;
1947
1948         thread->t_env = &env;
1949         env.le_ctx.lc_thread = thread;
1950         env.le_ctx.lc_cookie = 0x6;
1951
1952         /* Alloc reply state structure for this one */
1953         OBD_ALLOC_GFP(rs, svc->srv_max_reply_size, CFS_ALLOC_STD);
1954         if (!rs) {
1955                 rc = -ENOMEM;
1956                 goto out_srv_fini;
1957         }
1958
1959         cfs_spin_lock(&svc->srv_lock);
1960         /* SVC_STOPPING may already be set here if someone else is trying
1961          * to stop the service while this new thread has been dynamically
1962          * forked. We still set SVC_RUNNING to let our creator know that
1963          * we are now running, however we will exit as soon as possible */
1964         thread->t_flags |= SVC_RUNNING;
1965         cfs_spin_unlock(&svc->srv_lock);
1966
1967         /*
1968          * wake up our creator. Note: @data is invalid after this point,
1969          * because it's allocated on ptlrpc_start_thread() stack.
1970          */
1971         cfs_waitq_signal(&thread->t_ctl_waitq);
1972
1973         thread->t_watchdog = lc_watchdog_add(CFS_GET_TIMEOUT(svc), NULL, NULL);
1974
1975         cfs_spin_lock(&svc->srv_lock);
1976         svc->srv_threads_running++;
1977         cfs_list_add(&rs->rs_list, &svc->srv_free_rs_list);
1978         cfs_spin_unlock(&svc->srv_lock);
1979         cfs_waitq_signal(&svc->srv_free_rs_waitq);
1980
1981         CDEBUG(D_NET, "service thread %d (#%d) started\n", thread->t_id,
1982                svc->srv_threads_running);
1983
1984         /* XXX maintain a list of all managed devices: insert here */
1985
1986         while (!(thread->t_flags & SVC_STOPPING) && !svc->srv_is_stopping) {
1987                 /* Don't exit while there are replies to be handled */
1988                 struct l_wait_info lwi = LWI_TIMEOUT(svc->srv_rqbd_timeout,
1989                                                      ptlrpc_retry_rqbds, svc);
1990
1991                 lc_watchdog_disable(thread->t_watchdog);
1992
1993                 cfs_cond_resched();
1994
1995                 l_wait_event_exclusive (svc->srv_waitq,
1996                               thread->t_flags & SVC_STOPPING ||
1997                               svc->srv_is_stopping ||
1998                               (!cfs_list_empty(&svc->srv_idle_rqbds) &&
1999                                svc->srv_rqbd_timeout == 0) ||
2000                               !cfs_list_empty(&svc->srv_req_in_queue) ||
2001                               (ptlrpc_server_request_pending(svc, 0) &&
2002                                (svc->srv_n_active_reqs <
2003                                 (svc->srv_threads_running - 1))) ||
2004                               svc->srv_at_check,
2005                               &lwi);
2006
2007                 if (thread->t_flags & SVC_STOPPING || svc->srv_is_stopping)
2008                         break;
2009
2010                 lc_watchdog_touch(thread->t_watchdog, CFS_GET_TIMEOUT(svc));
2011
2012                 ptlrpc_check_rqbd_pool(svc);
2013
2014                 if (svc->srv_threads_started < svc->srv_threads_max &&
2015                     svc->srv_n_active_reqs >= (svc->srv_threads_started - 1)) 
2016                         /* Ignore return code - we tried... */
2017                         ptlrpc_start_thread(dev, svc);
2018
2019                 if (!cfs_list_empty(&svc->srv_req_in_queue)) {
2020                         /* Process all incoming reqs before handling any */
2021                         ptlrpc_server_handle_req_in(svc);
2022                         /* but limit ourselves in case of flood */
2023                         if (counter++ < 1000)
2024                                 continue;
2025                         counter = 0;
2026                 }
2027
2028                 if (svc->srv_at_check)
2029                         ptlrpc_at_check_timed(svc);
2030
2031                 /* don't handle requests in the last thread */
2032                 if (ptlrpc_server_request_pending(svc, 0) &&
2033                     (svc->srv_n_active_reqs < (svc->srv_threads_running - 1))) {
2034                         lu_context_enter(&env.le_ctx);
2035                         ptlrpc_server_handle_request(svc, thread);
2036                         lu_context_exit(&env.le_ctx);
2037                 }
2038
2039                 if (!cfs_list_empty(&svc->srv_idle_rqbds) &&
2040                     ptlrpc_server_post_idle_rqbds(svc) < 0) {
2041                         /* I just failed to repost request buffers.  Wait
2042                          * for a timeout (unless something else happens)
2043                          * before I try again */
2044                         svc->srv_rqbd_timeout = cfs_time_seconds(1)/10;
2045                         CDEBUG(D_RPCTRACE,"Posted buffers: %d\n",
2046                                svc->srv_nrqbd_receiving);
2047                 }
2048         }
2049
2050         lc_watchdog_delete(thread->t_watchdog);
2051         thread->t_watchdog = NULL;
2052
2053 out_srv_fini:
2054         /*
2055          * deconstruct service specific state created by ptlrpc_start_thread()
2056          */
2057         if (svc->srv_done != NULL)
2058                 svc->srv_done(thread);
2059
2060         lu_context_fini(&env.le_ctx);
2061 out:
2062         CDEBUG(D_RPCTRACE, "service thread [ %p : %u ] %d exiting: rc %d\n",
2063                thread, thread->t_pid, thread->t_id, rc);
2064
2065         cfs_spin_lock(&svc->srv_lock);
2066         svc->srv_threads_running--; /* must know immediately */
2067         thread->t_id = rc;
2068         thread->t_flags = SVC_STOPPED;
2069
2070         cfs_waitq_signal(&thread->t_ctl_waitq);
2071         cfs_spin_unlock(&svc->srv_lock);
2072
2073         return rc;
2074 }
2075
2076 struct ptlrpc_hr_args {
2077         int                       thread_index;
2078         int                       cpu_index;
2079         struct ptlrpc_hr_service *hrs;
2080 };
2081
2082 static int hrt_dont_sleep(struct ptlrpc_hr_thread *t,
2083                           cfs_list_t *replies)
2084 {
2085         int result;
2086
2087         cfs_spin_lock(&t->hrt_lock);
2088         cfs_list_splice_init(&t->hrt_queue, replies);
2089         result = cfs_test_bit(HRT_STOPPING, &t->hrt_flags) ||
2090                 !cfs_list_empty(replies);
2091         cfs_spin_unlock(&t->hrt_lock);
2092         return result;
2093 }
2094
2095 static int ptlrpc_hr_main(void *arg)
2096 {
2097         struct ptlrpc_hr_args * hr_args = arg;
2098         struct ptlrpc_hr_service *hr = hr_args->hrs;
2099         struct ptlrpc_hr_thread *t = &hr->hr_threads[hr_args->thread_index];
2100         char threadname[20];
2101         CFS_LIST_HEAD(replies);
2102
2103         snprintf(threadname, sizeof(threadname),
2104                  "ptlrpc_hr_%d", hr_args->thread_index);
2105
2106         cfs_daemonize_ctxt(threadname);
2107 #if defined(CONFIG_SMP) && defined(HAVE_NODE_TO_CPUMASK)
2108         cfs_set_cpus_allowed(cfs_current(),
2109                              node_to_cpumask(cpu_to_node(hr_args->cpu_index)));
2110 #endif
2111         cfs_set_bit(HRT_RUNNING, &t->hrt_flags);
2112         cfs_waitq_signal(&t->hrt_wait);
2113
2114         while (!cfs_test_bit(HRT_STOPPING, &t->hrt_flags)) {
2115
2116                 l_cfs_wait_event(t->hrt_wait, hrt_dont_sleep(t, &replies));
2117                 while (!cfs_list_empty(&replies)) {
2118                         struct ptlrpc_reply_state *rs;
2119
2120                         rs = cfs_list_entry(replies.prev,
2121                                             struct ptlrpc_reply_state,
2122                                             rs_list);
2123                         cfs_list_del_init(&rs->rs_list);
2124                         ptlrpc_handle_rs(rs);
2125                 }
2126         }
2127
2128         cfs_clear_bit(HRT_RUNNING, &t->hrt_flags);
2129         cfs_complete(&t->hrt_completion);
2130
2131         return 0;
2132 }
2133
2134 static int ptlrpc_start_hr_thread(struct ptlrpc_hr_service *hr, int n, int cpu)
2135 {
2136         struct ptlrpc_hr_thread *t = &hr->hr_threads[n];
2137         struct ptlrpc_hr_args args;
2138         int rc;
2139         ENTRY;
2140
2141         args.thread_index = n;
2142         args.cpu_index = cpu;
2143         args.hrs = hr;
2144
2145         rc = cfs_kernel_thread(ptlrpc_hr_main, (void*)&args,
2146                                CLONE_VM|CLONE_FILES);
2147         if (rc < 0) {
2148                 cfs_complete(&t->hrt_completion);
2149                 GOTO(out, rc);
2150         }
2151         l_cfs_wait_event(t->hrt_wait, cfs_test_bit(HRT_RUNNING, &t->hrt_flags));
2152         RETURN(0);
2153  out:
2154         return rc;
2155 }
2156
2157 static void ptlrpc_stop_hr_thread(struct ptlrpc_hr_thread *t)
2158 {
2159         ENTRY;
2160
2161         cfs_set_bit(HRT_STOPPING, &t->hrt_flags);
2162         cfs_waitq_signal(&t->hrt_wait);
2163         cfs_wait_for_completion(&t->hrt_completion);
2164
2165         EXIT;
2166 }
2167
2168 static void ptlrpc_stop_hr_threads(struct ptlrpc_hr_service *hrs)
2169 {
2170         int n;
2171         ENTRY;
2172
2173         for (n = 0; n < hrs->hr_n_threads; n++)
2174                 ptlrpc_stop_hr_thread(&hrs->hr_threads[n]);
2175
2176         EXIT;
2177 }
2178
2179 static int ptlrpc_start_hr_threads(struct ptlrpc_hr_service *hr)
2180 {
2181         int rc = -ENOMEM;
2182         int n, cpu, threads_started = 0;
2183         ENTRY;
2184
2185         LASSERT(hr != NULL);
2186         LASSERT(hr->hr_n_threads > 0);
2187
2188         for (n = 0, cpu = 0; n < hr->hr_n_threads; n++) {
2189 #if defined(CONFIG_SMP) && defined(HAVE_NODE_TO_CPUMASK)
2190                 while(!cfs_cpu_online(cpu)) {
2191                         cpu++;
2192                         if (cpu >= cfs_num_possible_cpus())
2193                                 cpu = 0;
2194                 }
2195 #endif
2196                 rc = ptlrpc_start_hr_thread(hr, n, cpu);
2197                 if (rc != 0)
2198                         break;
2199                 threads_started++;
2200                 cpu++;
2201         }
2202         if (threads_started == 0) {
2203                 CERROR("No reply handling threads started\n");
2204                 RETURN(-ESRCH);
2205         }
2206         if (threads_started < hr->hr_n_threads) {
2207                 CWARN("Started only %d reply handling threads from %d\n",
2208                       threads_started, hr->hr_n_threads);
2209                 hr->hr_n_threads = threads_started;
2210         }
2211         RETURN(0);
2212 }
2213
2214 static void ptlrpc_stop_thread(struct ptlrpc_service *svc,
2215                                struct ptlrpc_thread *thread)
2216 {
2217         struct l_wait_info lwi = { 0 };
2218         ENTRY;
2219
2220         CDEBUG(D_RPCTRACE, "Stopping thread [ %p : %u ]\n",
2221                thread, thread->t_pid);
2222
2223         cfs_spin_lock(&svc->srv_lock);
2224         /* let the thread know that we would like it to stop asap */
2225         thread->t_flags |= SVC_STOPPING;
2226         cfs_spin_unlock(&svc->srv_lock);
2227
2228         cfs_waitq_broadcast(&svc->srv_waitq);
2229         l_wait_event(thread->t_ctl_waitq,
2230                      (thread->t_flags & SVC_STOPPED), &lwi);
2231
2232         cfs_spin_lock(&svc->srv_lock);
2233         cfs_list_del(&thread->t_link);
2234         cfs_spin_unlock(&svc->srv_lock);
2235
2236         OBD_FREE_PTR(thread);
2237         EXIT;
2238 }
2239
2240 void ptlrpc_stop_all_threads(struct ptlrpc_service *svc)
2241 {
2242         struct ptlrpc_thread *thread;
2243         ENTRY;
2244
2245         cfs_spin_lock(&svc->srv_lock);
2246         while (!cfs_list_empty(&svc->srv_threads)) {
2247                 thread = cfs_list_entry(svc->srv_threads.next,
2248                                         struct ptlrpc_thread, t_link);
2249
2250                 cfs_spin_unlock(&svc->srv_lock);
2251                 ptlrpc_stop_thread(svc, thread);
2252                 cfs_spin_lock(&svc->srv_lock);
2253         }
2254
2255         cfs_spin_unlock(&svc->srv_lock);
2256         EXIT;
2257 }
2258
2259 int ptlrpc_start_threads(struct obd_device *dev, struct ptlrpc_service *svc)
2260 {
2261         int i, rc = 0;
2262         ENTRY;
2263
2264         /* We require 2 threads min - see note in
2265            ptlrpc_server_handle_request */
2266         LASSERT(svc->srv_threads_min >= 2);
2267         for (i = 0; i < svc->srv_threads_min; i++) {
2268                 rc = ptlrpc_start_thread(dev, svc);
2269                 /* We have enough threads, don't start more.  b=15759 */
2270                 if (rc == -EMFILE)
2271                         break;
2272                 if (rc) {
2273                         CERROR("cannot start %s thread #%d: rc %d\n",
2274                                svc->srv_thread_name, i, rc);
2275                         ptlrpc_stop_all_threads(svc);
2276                         break;
2277                 }
2278         }
2279         RETURN(rc);
2280 }
2281
2282 int ptlrpc_start_thread(struct obd_device *dev, struct ptlrpc_service *svc)
2283 {
2284         struct l_wait_info lwi = { 0 };
2285         struct ptlrpc_svc_data d;
2286         struct ptlrpc_thread *thread;
2287         char name[32];
2288         int id, rc;
2289         ENTRY;
2290
2291         CDEBUG(D_RPCTRACE, "%s started %d min %d max %d running %d\n",
2292                svc->srv_name, svc->srv_threads_started, svc->srv_threads_min,
2293                svc->srv_threads_max, svc->srv_threads_running);
2294
2295         if (unlikely(svc->srv_is_stopping))
2296                 RETURN(-ESRCH);
2297
2298         if (unlikely(svc->srv_threads_started >= svc->srv_threads_max) ||
2299             (OBD_FAIL_CHECK(OBD_FAIL_TGT_TOOMANY_THREADS) &&
2300              svc->srv_threads_started == svc->srv_threads_min - 1))
2301                 RETURN(-EMFILE);
2302
2303         OBD_ALLOC_PTR(thread);
2304         if (thread == NULL)
2305                 RETURN(-ENOMEM);
2306         cfs_waitq_init(&thread->t_ctl_waitq);
2307
2308         cfs_spin_lock(&svc->srv_lock);
2309         if (svc->srv_threads_started >= svc->srv_threads_max) {
2310                 cfs_spin_unlock(&svc->srv_lock);
2311                 OBD_FREE_PTR(thread);
2312                 RETURN(-EMFILE);
2313         }
2314         cfs_list_add(&thread->t_link, &svc->srv_threads);
2315         id = svc->srv_threads_started++;
2316         cfs_spin_unlock(&svc->srv_lock);
2317
2318         thread->t_svc = svc;
2319         thread->t_id = id;
2320         sprintf(name, "%s_%02d", svc->srv_thread_name, id);
2321         d.dev = dev;
2322         d.svc = svc;
2323         d.name = name;
2324         d.thread = thread;
2325
2326         CDEBUG(D_RPCTRACE, "starting thread '%s'\n", name);
2327
2328         /* CLONE_VM and CLONE_FILES just avoid a needless copy, because we
2329          * just drop the VM and FILES in cfs_daemonize_ctxt() right away.
2330          */
2331         rc = cfs_kernel_thread(ptlrpc_main, &d, CLONE_VM | CLONE_FILES);
2332         if (rc < 0) {
2333                 CERROR("cannot start thread '%s': rc %d\n", name, rc);
2334
2335                 cfs_spin_lock(&svc->srv_lock);
2336                 cfs_list_del(&thread->t_link);
2337                 --svc->srv_threads_started;
2338                 cfs_spin_unlock(&svc->srv_lock);
2339
2340                 OBD_FREE(thread, sizeof(*thread));
2341                 RETURN(rc);
2342         }
2343         l_wait_event(thread->t_ctl_waitq,
2344                      thread->t_flags & (SVC_RUNNING | SVC_STOPPED), &lwi);
2345
2346         rc = (thread->t_flags & SVC_STOPPED) ? thread->t_id : 0;
2347         RETURN(rc);
2348 }
2349
2350
2351 int ptlrpc_hr_init(void)
2352 {
2353         int i;
2354         int n_cpus = cfs_num_online_cpus();
2355         struct ptlrpc_hr_service *hr;
2356         int size;
2357         int rc;
2358         ENTRY;
2359
2360         LASSERT(ptlrpc_hr == NULL);
2361
2362         size = offsetof(struct ptlrpc_hr_service, hr_threads[n_cpus]);
2363         OBD_ALLOC(hr, size);
2364         if (hr == NULL)
2365                 RETURN(-ENOMEM);
2366         for (i = 0; i < n_cpus; i++) {
2367                 struct ptlrpc_hr_thread *t = &hr->hr_threads[i];
2368
2369                 cfs_spin_lock_init(&t->hrt_lock);
2370                 cfs_waitq_init(&t->hrt_wait);
2371                 CFS_INIT_LIST_HEAD(&t->hrt_queue);
2372                 cfs_init_completion(&t->hrt_completion);
2373         }
2374         hr->hr_n_threads = n_cpus;
2375         hr->hr_size = size;
2376         ptlrpc_hr = hr;
2377
2378         rc = ptlrpc_start_hr_threads(hr);
2379         if (rc) {
2380                 OBD_FREE(hr, hr->hr_size);
2381                 ptlrpc_hr = NULL;
2382         }
2383         RETURN(rc);
2384 }
2385
2386 void ptlrpc_hr_fini(void)
2387 {
2388         if (ptlrpc_hr != NULL) {
2389                 ptlrpc_stop_hr_threads(ptlrpc_hr);
2390                 OBD_FREE(ptlrpc_hr, ptlrpc_hr->hr_size);
2391                 ptlrpc_hr = NULL;
2392         }
2393 }
2394
2395 #endif /* __KERNEL__ */
2396
2397 /**
2398  * Wait until all already scheduled replies are processed.
2399  */
2400 static void ptlrpc_wait_replies(struct ptlrpc_service *svc)
2401 {
2402         while (1) {
2403                 int rc;
2404                 struct l_wait_info lwi = LWI_TIMEOUT(cfs_time_seconds(10),
2405                                                      NULL, NULL);
2406                 rc = l_wait_event(svc->srv_waitq, cfs_atomic_read(&svc-> \
2407                                   srv_n_difficult_replies) == 0,
2408                                   &lwi);
2409                 if (rc == 0)
2410                         break;
2411                 CWARN("Unexpectedly long timeout %p\n", svc);
2412         }
2413 }
2414
2415 int ptlrpc_unregister_service(struct ptlrpc_service *service)
2416 {
2417         int                   rc;
2418         struct l_wait_info    lwi;
2419         cfs_list_t           *tmp;
2420         struct ptlrpc_reply_state *rs, *t;
2421         struct ptlrpc_at_array *array = &service->srv_at_array;
2422         ENTRY;
2423
2424         service->srv_is_stopping = 1;
2425         cfs_timer_disarm(&service->srv_at_timer);
2426
2427         ptlrpc_stop_all_threads(service);
2428         LASSERT(cfs_list_empty(&service->srv_threads));
2429
2430         cfs_spin_lock (&ptlrpc_all_services_lock);
2431         cfs_list_del_init (&service->srv_list);
2432         cfs_spin_unlock (&ptlrpc_all_services_lock);
2433
2434         ptlrpc_lprocfs_unregister_service(service);
2435
2436         /* All history will be culled when the next request buffer is
2437          * freed */
2438         service->srv_max_history_rqbds = 0;
2439
2440         CDEBUG(D_NET, "%s: tearing down\n", service->srv_name);
2441
2442         rc = LNetClearLazyPortal(service->srv_req_portal);
2443         LASSERT (rc == 0);
2444
2445         /* Unlink all the request buffers.  This forces a 'final' event with
2446          * its 'unlink' flag set for each posted rqbd */
2447         cfs_list_for_each(tmp, &service->srv_active_rqbds) {
2448                 struct ptlrpc_request_buffer_desc *rqbd =
2449                         cfs_list_entry(tmp, struct ptlrpc_request_buffer_desc,
2450                                        rqbd_list);
2451
2452                 rc = LNetMDUnlink(rqbd->rqbd_md_h);
2453                 LASSERT (rc == 0 || rc == -ENOENT);
2454         }
2455
2456         /* Wait for the network to release any buffers it's currently
2457          * filling */
2458         for (;;) {
2459                 cfs_spin_lock(&service->srv_lock);
2460                 rc = service->srv_nrqbd_receiving;
2461                 cfs_spin_unlock(&service->srv_lock);
2462
2463                 if (rc == 0)
2464                         break;
2465
2466                 /* Network access will complete in finite time but the HUGE
2467                  * timeout lets us CWARN for visibility of sluggish NALs */
2468                 lwi = LWI_TIMEOUT_INTERVAL(cfs_time_seconds(LONG_UNLINK),
2469                                            cfs_time_seconds(1), NULL, NULL);
2470                 rc = l_wait_event(service->srv_waitq,
2471                                   service->srv_nrqbd_receiving == 0,
2472                                   &lwi);
2473                 if (rc == -ETIMEDOUT)
2474                         CWARN("Service %s waiting for request buffers\n",
2475                               service->srv_name);
2476         }
2477
2478         /* schedule all outstanding replies to terminate them */
2479         cfs_spin_lock(&service->srv_lock);
2480         while (!cfs_list_empty(&service->srv_active_replies)) {
2481                 struct ptlrpc_reply_state *rs =
2482                         cfs_list_entry(service->srv_active_replies.next,
2483                                        struct ptlrpc_reply_state, rs_list);
2484                 cfs_spin_lock(&rs->rs_lock);
2485                 ptlrpc_schedule_difficult_reply(rs);
2486                 cfs_spin_unlock(&rs->rs_lock);
2487         }
2488         cfs_spin_unlock(&service->srv_lock);
2489
2490         /* purge the request queue.  NB No new replies (rqbds all unlinked)
2491          * and no service threads, so I'm the only thread noodling the
2492          * request queue now */
2493         while (!cfs_list_empty(&service->srv_req_in_queue)) {
2494                 struct ptlrpc_request *req =
2495                         cfs_list_entry(service->srv_req_in_queue.next,
2496                                        struct ptlrpc_request,
2497                                        rq_list);
2498
2499                 cfs_list_del(&req->rq_list);
2500                 service->srv_n_queued_reqs--;
2501                 service->srv_n_active_reqs++;
2502                 ptlrpc_server_finish_request(req);
2503         }
2504         while (ptlrpc_server_request_pending(service, 1)) {
2505                 struct ptlrpc_request *req;
2506
2507                 req = ptlrpc_server_request_get(service, 1);
2508                 cfs_list_del(&req->rq_list);
2509                 service->srv_n_queued_reqs--;
2510                 service->srv_n_active_reqs++;
2511                 ptlrpc_hpreq_fini(req);
2512                 ptlrpc_server_finish_request(req);
2513         }
2514         LASSERT(service->srv_n_queued_reqs == 0);
2515         LASSERT(service->srv_n_active_reqs == 0);
2516         LASSERT(service->srv_n_history_rqbds == 0);
2517         LASSERT(cfs_list_empty(&service->srv_active_rqbds));
2518
2519         /* Now free all the request buffers since nothing references them
2520          * any more... */
2521         while (!cfs_list_empty(&service->srv_idle_rqbds)) {
2522                 struct ptlrpc_request_buffer_desc *rqbd =
2523                         cfs_list_entry(service->srv_idle_rqbds.next,
2524                                        struct ptlrpc_request_buffer_desc,
2525                                        rqbd_list);
2526
2527                 ptlrpc_free_rqbd(rqbd);
2528         }
2529
2530         ptlrpc_wait_replies(service);
2531
2532         cfs_list_for_each_entry_safe(rs, t, &service->srv_free_rs_list,
2533                                      rs_list) {
2534                 cfs_list_del(&rs->rs_list);
2535                 OBD_FREE(rs, service->srv_max_reply_size);
2536         }
2537
2538         /* In case somebody rearmed this in the meantime */
2539         cfs_timer_disarm(&service->srv_at_timer);
2540
2541         if (array->paa_reqs_array != NULL) {
2542                 OBD_FREE(array->paa_reqs_array,
2543                          sizeof(cfs_list_t) * array->paa_size);
2544                 array->paa_reqs_array = NULL;
2545         }
2546
2547         if (array->paa_reqs_count != NULL) {
2548                 OBD_FREE(array->paa_reqs_count,
2549                          sizeof(__u32) * array->paa_size);
2550                 array->paa_reqs_count= NULL;
2551         }
2552
2553         OBD_FREE_PTR(service);
2554         RETURN(0);
2555 }
2556
2557 /* Returns 0 if the service is healthy.
2558  *
2559  * Right now, it just checks to make sure that requests aren't languishing
2560  * in the queue.  We'll use this health check to govern whether a node needs
2561  * to be shot, so it's intentionally non-aggressive. */
2562 int ptlrpc_service_health_check(struct ptlrpc_service *svc)
2563 {
2564         struct ptlrpc_request *request;
2565         struct timeval         right_now;
2566         long                   timediff;
2567
2568         if (svc == NULL)
2569                 return 0;
2570
2571         cfs_gettimeofday(&right_now);
2572
2573         cfs_spin_lock(&svc->srv_lock);
2574         if (!ptlrpc_server_request_pending(svc, 1)) {
2575                 cfs_spin_unlock(&svc->srv_lock);
2576                 return 0;
2577         }
2578
2579         /* How long has the next entry been waiting? */
2580         if (cfs_list_empty(&svc->srv_request_queue))
2581                 request = cfs_list_entry(svc->srv_request_hpq.next,
2582                                          struct ptlrpc_request, rq_list);
2583         else
2584                 request = cfs_list_entry(svc->srv_request_queue.next,
2585                                          struct ptlrpc_request, rq_list);
2586         timediff = cfs_timeval_sub(&right_now, &request->rq_arrival_time, NULL);
2587         cfs_spin_unlock(&svc->srv_lock);
2588
2589         if ((timediff / ONE_MILLION) > (AT_OFF ? obd_timeout * 3/2 :
2590                                         at_max)) {
2591                 CERROR("%s: unhealthy - request has been waiting %lds\n",
2592                        svc->srv_name, timediff / ONE_MILLION);
2593                 return (-1);
2594         }
2595
2596         return 0;
2597 }