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