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