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