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