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