Whamcloud - gitweb
add ability to resend request if it isn't fit in reply buffer.
[fs/lustre-release.git] / lustre / ptlrpc / service.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  */
36
37 #define DEBUG_SUBSYSTEM S_RPC
38 #ifndef __KERNEL__
39 #include <liblustre.h>
40 #include <libcfs/kp30.h>
41 #endif
42 #include <obd_support.h>
43 #include <obd_class.h>
44 #include <lustre_net.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
53 CFS_MODULE_PARM(at_min, "i", int, 0644,
54                 "Adaptive timeout minimum (sec)");
55 CFS_MODULE_PARM(at_max, "i", int, 0644,
56                 "Adaptive timeout maximum (sec)");
57 CFS_MODULE_PARM(at_history, "i", int, 0644,
58                 "Adaptive timeouts remember the slowest event that took place "
59                 "within this period (sec)");
60 CFS_MODULE_PARM(at_early_margin, "i", int, 0644,
61                 "How soon before an RPC deadline to send an early reply");
62 CFS_MODULE_PARM(at_extra, "i", int, 0644,
63                 "How much extra time to give with each early reply");
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 spinlock_t ptlrpc_all_services_lock;
70
71 static char *
72 ptlrpc_alloc_request_buffer (int size)
73 {
74         char *ptr;
75
76         if (size > SVC_BUF_VMALLOC_THRESHOLD)
77                 OBD_VMALLOC(ptr, size);
78         else
79                 OBD_ALLOC(ptr, size);
80
81         return (ptr);
82 }
83
84 static void
85 ptlrpc_free_request_buffer (char *ptr, int size)
86 {
87         if (size > SVC_BUF_VMALLOC_THRESHOLD)
88                 OBD_VFREE(ptr, size);
89         else
90                 OBD_FREE(ptr, size);
91 }
92
93 struct ptlrpc_request_buffer_desc *
94 ptlrpc_alloc_rqbd (struct ptlrpc_service *svc)
95 {
96         struct ptlrpc_request_buffer_desc *rqbd;
97
98         OBD_ALLOC(rqbd, sizeof (*rqbd));
99         if (rqbd == NULL)
100                 return (NULL);
101
102         rqbd->rqbd_service = svc;
103         rqbd->rqbd_refcount = 0;
104         rqbd->rqbd_cbid.cbid_fn = request_in_callback;
105         rqbd->rqbd_cbid.cbid_arg = rqbd;
106         CFS_INIT_LIST_HEAD(&rqbd->rqbd_reqs);
107         rqbd->rqbd_buffer = ptlrpc_alloc_request_buffer(svc->srv_buf_size);
108
109         if (rqbd->rqbd_buffer == NULL) {
110                 OBD_FREE(rqbd, sizeof (*rqbd));
111                 return (NULL);
112         }
113
114         spin_lock(&svc->srv_lock);
115         list_add(&rqbd->rqbd_list, &svc->srv_idle_rqbds);
116         svc->srv_nbufs++;
117         spin_unlock(&svc->srv_lock);
118
119         return (rqbd);
120 }
121
122 void
123 ptlrpc_free_rqbd (struct ptlrpc_request_buffer_desc *rqbd)
124 {
125         struct ptlrpc_service *svc = rqbd->rqbd_service;
126
127         LASSERT (rqbd->rqbd_refcount == 0);
128         LASSERT (list_empty(&rqbd->rqbd_reqs));
129
130         spin_lock(&svc->srv_lock);
131         list_del(&rqbd->rqbd_list);
132         svc->srv_nbufs--;
133         spin_unlock(&svc->srv_lock);
134
135         ptlrpc_free_request_buffer (rqbd->rqbd_buffer, svc->srv_buf_size);
136         OBD_FREE (rqbd, sizeof (*rqbd));
137 }
138
139 int
140 ptlrpc_grow_req_bufs(struct ptlrpc_service *svc)
141 {
142         struct ptlrpc_request_buffer_desc *rqbd;
143         int                                i;
144
145         CDEBUG(D_RPCTRACE, "%s: allocate %d new %d-byte reqbufs (%d/%d left)\n",
146                svc->srv_name, svc->srv_nbuf_per_group, svc->srv_buf_size,
147                svc->srv_nrqbd_receiving, svc->srv_nbufs);
148         for (i = 0; i < svc->srv_nbuf_per_group; i++) {
149                 rqbd = ptlrpc_alloc_rqbd(svc);
150
151                 if (rqbd == NULL) {
152                         CERROR ("%s: Can't allocate request buffer\n",
153                                 svc->srv_name);
154                         return (-ENOMEM);
155                 }
156
157                 if (ptlrpc_server_post_idle_rqbds(svc) < 0)
158                         return (-EAGAIN);
159         }
160
161         return (0);
162 }
163
164 void
165 ptlrpc_save_lock(struct ptlrpc_request *req,
166                  struct lustre_handle *lock, int mode)
167 {
168         struct ptlrpc_reply_state *rs = req->rq_reply_state;
169         int                        idx;
170
171         LASSERT(rs != NULL);
172         LASSERT(rs->rs_nlocks < RS_MAX_LOCKS);
173
174         if (req->rq_export->exp_disconnected) {
175                 ldlm_lock_decref(lock, mode);
176         } else {
177                 idx = rs->rs_nlocks++;
178                 rs->rs_locks[idx] = *lock;
179                 rs->rs_modes[idx] = mode;
180                 rs->rs_difficult = 1;
181         }
182 }
183
184 void
185 ptlrpc_schedule_difficult_reply (struct ptlrpc_reply_state *rs)
186 {
187         struct ptlrpc_service *svc = rs->rs_service;
188
189 #ifdef CONFIG_SMP
190         LASSERT (spin_is_locked (&svc->srv_lock));
191 #endif
192         LASSERT (rs->rs_difficult);
193         rs->rs_scheduled_ever = 1;              /* flag any notification attempt */
194
195         if (rs->rs_scheduled)                   /* being set up or already notified */
196                 return;
197
198         rs->rs_scheduled = 1;
199         list_del (&rs->rs_list);
200         list_add (&rs->rs_list, &svc->srv_reply_queue);
201         cfs_waitq_signal (&svc->srv_waitq);
202 }
203
204 void
205 ptlrpc_commit_replies (struct obd_export *exp)
206 {
207         struct list_head   *tmp;
208         struct list_head   *nxt;
209
210         /* Find any replies that have been committed and get their service
211          * to attend to complete them. */
212
213         /* CAVEAT EMPTOR: spinlock ordering!!! */
214         spin_lock(&exp->exp_uncommitted_replies_lock);
215
216         list_for_each_safe(tmp, nxt, &exp->exp_uncommitted_replies) {
217                 struct ptlrpc_reply_state *rs =
218                         list_entry(tmp, struct ptlrpc_reply_state, rs_obd_list);
219
220                 LASSERT(rs->rs_difficult);
221                 /* VBR: per-export last_committed */
222                 LASSERT(rs->rs_export);
223                 if (rs->rs_transno <= rs->rs_export->exp_last_committed) {
224                         struct ptlrpc_service *svc = rs->rs_service;
225
226                         spin_lock (&svc->srv_lock);
227                         list_del_init (&rs->rs_obd_list);
228                         ptlrpc_schedule_difficult_reply (rs);
229                         spin_unlock (&svc->srv_lock);
230                 }
231         }
232
233         spin_unlock(&exp->exp_uncommitted_replies_lock);
234 }
235
236 static int
237 ptlrpc_server_post_idle_rqbds (struct ptlrpc_service *svc)
238 {
239         struct ptlrpc_request_buffer_desc *rqbd;
240         int                                rc;
241         int                                posted = 0;
242
243         for (;;) {
244                 spin_lock(&svc->srv_lock);
245
246                 if (list_empty (&svc->srv_idle_rqbds)) {
247                         spin_unlock(&svc->srv_lock);
248                         return (posted);
249                 }
250
251                 rqbd = list_entry(svc->srv_idle_rqbds.next,
252                                   struct ptlrpc_request_buffer_desc,
253                                   rqbd_list);
254                 list_del (&rqbd->rqbd_list);
255
256                 /* assume we will post successfully */
257                 svc->srv_nrqbd_receiving++;
258                 list_add (&rqbd->rqbd_list, &svc->srv_active_rqbds);
259
260                 spin_unlock(&svc->srv_lock);
261
262                 rc = ptlrpc_register_rqbd(rqbd);
263                 if (rc != 0)
264                         break;
265
266                 posted = 1;
267         }
268
269         spin_lock(&svc->srv_lock);
270
271         svc->srv_nrqbd_receiving--;
272         list_del(&rqbd->rqbd_list);
273         list_add_tail(&rqbd->rqbd_list, &svc->srv_idle_rqbds);
274
275         /* Don't complain if no request buffers are posted right now; LNET
276          * won't drop requests because we set the portal lazy! */
277
278         spin_unlock(&svc->srv_lock);
279
280         return (-1);
281 }
282
283 static void ptlrpc_at_timer(unsigned long castmeharder)
284 {
285         struct ptlrpc_service *svc = (struct ptlrpc_service *)castmeharder;
286         svc->srv_at_check = 1;
287         svc->srv_at_checktime = cfs_time_current();
288         cfs_waitq_signal(&svc->srv_waitq);
289 }
290
291 /* @threadname should be 11 characters or less - 3 will be added on */
292 struct ptlrpc_service *
293 ptlrpc_init_svc(int nbufs, int bufsize, int max_req_size, int max_reply_size,
294                 int req_portal, int rep_portal, int watchdog_factor,
295                 svc_handler_t handler, char *name,
296                 cfs_proc_dir_entry_t *proc_entry,
297                 svcreq_printfn_t svcreq_printfn,
298                 int min_threads, int max_threads, char *threadname,
299                 svc_hpreq_handler_t hp_handler)
300 {
301         int                     rc;
302         struct ptlrpc_at_array *array;
303         struct ptlrpc_service  *service;
304         unsigned int            size, index;
305         ENTRY;
306
307         LASSERT (nbufs > 0);
308         LASSERT (bufsize >= max_req_size);
309
310         OBD_ALLOC(service, sizeof(*service));
311         if (service == NULL)
312                 RETURN(NULL);
313
314         /* First initialise enough for early teardown */
315
316         service->srv_name = name;
317         spin_lock_init(&service->srv_lock);
318         CFS_INIT_LIST_HEAD(&service->srv_threads);
319         cfs_waitq_init(&service->srv_waitq);
320
321         service->srv_nbuf_per_group = test_req_buffer_pressure ? 1 : nbufs;
322         service->srv_max_req_size = max_req_size;
323         service->srv_buf_size = bufsize;
324         service->srv_rep_portal = rep_portal;
325         service->srv_req_portal = req_portal;
326         service->srv_watchdog_factor = watchdog_factor;
327         service->srv_handler = handler;
328         service->srv_request_history_print_fn = svcreq_printfn;
329         service->srv_request_seq = 1;           /* valid seq #s start at 1 */
330         service->srv_request_max_cull_seq = 0;
331         service->srv_threads_min = min_threads;
332         service->srv_threads_max = max_threads;
333         service->srv_thread_name = threadname;
334         service->srv_hpreq_handler = hp_handler;
335         service->srv_hpreq_ratio = PTLRPC_SVC_HP_RATIO;
336         service->srv_hpreq_count = 0;
337         service->srv_n_hpreq = 0;
338
339         rc = LNetSetLazyPortal(service->srv_req_portal);
340         LASSERT (rc == 0);
341
342         CFS_INIT_LIST_HEAD(&service->srv_request_queue);
343         CFS_INIT_LIST_HEAD(&service->srv_request_hpq);
344         CFS_INIT_LIST_HEAD(&service->srv_idle_rqbds);
345         CFS_INIT_LIST_HEAD(&service->srv_active_rqbds);
346         CFS_INIT_LIST_HEAD(&service->srv_history_rqbds);
347         CFS_INIT_LIST_HEAD(&service->srv_request_history);
348         CFS_INIT_LIST_HEAD(&service->srv_active_replies);
349         CFS_INIT_LIST_HEAD(&service->srv_reply_queue);
350         CFS_INIT_LIST_HEAD(&service->srv_free_rs_list);
351         cfs_waitq_init(&service->srv_free_rs_waitq);
352
353         spin_lock_init(&service->srv_at_lock);
354         CFS_INIT_LIST_HEAD(&service->srv_req_in_queue);
355
356         array = &service->srv_at_array;
357         size = at_est2timeout(at_max);
358         array->paa_size = size;
359         array->paa_count = 0;
360         array->paa_deadline = -1;
361
362         /* allocate memory for srv_at_array (ptlrpc_at_array) */
363         OBD_ALLOC(array->paa_reqs_array, sizeof(struct list_head) * size);
364         if (array->paa_reqs_array == NULL)
365                 GOTO(failed, NULL);
366
367         for (index = 0; index < size; index++)
368                 CFS_INIT_LIST_HEAD(&array->paa_reqs_array[index]);
369
370         OBD_ALLOC(array->paa_reqs_count, sizeof(__u32) * size);
371         if (array->paa_reqs_count == NULL)
372                 GOTO(failed, NULL);
373
374         cfs_timer_init(&service->srv_at_timer, ptlrpc_at_timer, service);
375         /* At SOW, service time should be quick; 10s seems generous. If client
376            timeout is less than this, we'll be sending an early reply. */
377         at_init(&service->srv_at_estimate, 10, 0);
378
379         spin_lock (&ptlrpc_all_services_lock);
380         list_add (&service->srv_list, &ptlrpc_all_services);
381         spin_unlock (&ptlrpc_all_services_lock);
382
383         /* Now allocate the request buffers */
384         rc = ptlrpc_grow_req_bufs(service);
385         /* We shouldn't be under memory pressure at startup, so
386          * fail if we can't post all our buffers at this time. */
387         if (rc != 0)
388                 GOTO(failed, NULL);
389
390         /* Now allocate pool of reply buffers */
391         /* Increase max reply size to next power of two */
392         service->srv_max_reply_size = 1;
393         while (service->srv_max_reply_size < max_reply_size)
394                 service->srv_max_reply_size <<= 1;
395
396         if (proc_entry != NULL)
397                 ptlrpc_lprocfs_register_service(proc_entry, service);
398
399         CDEBUG(D_NET, "%s: Started, listening on portal %d\n",
400                service->srv_name, service->srv_req_portal);
401
402         RETURN(service);
403 failed:
404         ptlrpc_unregister_service(service);
405         return NULL;
406 }
407
408 /**
409  * to actually free the request, must be called without holding svc_lock.
410  * note it's caller's responsibility to unlink req->rq_list.
411  */
412 static void ptlrpc_server_free_request(struct ptlrpc_request *req)
413 {
414         LASSERT(atomic_read(&req->rq_refcount) == 0);
415         LASSERT(list_empty(&req->rq_timed_list));
416
417         /* DEBUG_REQ() assumes the reply state of a request with a valid
418          * ref will not be destroyed until that reference is dropped. */
419         ptlrpc_req_drop_rs(req);
420
421         if (req != &req->rq_rqbd->rqbd_req) {
422                 /* NB request buffers use an embedded
423                  * req if the incoming req unlinked the
424                  * MD; this isn't one of them! */
425                 OBD_FREE(req, sizeof(*req));
426         }
427 }
428
429 /**
430  * drop a reference count of the request. if it reaches 0, we either
431  * put it into history list, or free it immediately.
432  */
433 static void ptlrpc_server_drop_request(struct ptlrpc_request *req)
434 {
435         struct ptlrpc_request_buffer_desc *rqbd = req->rq_rqbd;
436         struct ptlrpc_service             *svc = rqbd->rqbd_service;
437         int                                refcount;
438         struct list_head                  *tmp;
439         struct list_head                  *nxt;
440
441         if (!atomic_dec_and_test(&req->rq_refcount))
442                 return;
443
444         spin_lock(&svc->srv_lock);
445
446         svc->srv_n_active_reqs--;
447         list_add(&req->rq_list, &rqbd->rqbd_reqs);
448
449         refcount = --(rqbd->rqbd_refcount);
450         if (refcount == 0) {
451                 /* request buffer is now idle: add to history */
452                 list_del(&rqbd->rqbd_list);
453                 list_add_tail(&rqbd->rqbd_list, &svc->srv_history_rqbds);
454                 svc->srv_n_history_rqbds++;
455
456                 /* cull some history?
457                  * I expect only about 1 or 2 rqbds need to be recycled here */
458                 while (svc->srv_n_history_rqbds > svc->srv_max_history_rqbds) {
459                         rqbd = list_entry(svc->srv_history_rqbds.next,
460                                           struct ptlrpc_request_buffer_desc,
461                                           rqbd_list);
462
463                         list_del(&rqbd->rqbd_list);
464                         svc->srv_n_history_rqbds--;
465
466                         /* remove rqbd's reqs from svc's req history while
467                          * I've got the service lock */
468                         list_for_each(tmp, &rqbd->rqbd_reqs) {
469                                 req = list_entry(tmp, struct ptlrpc_request,
470                                                  rq_list);
471                                 /* Track the highest culled req seq */
472                                 if (req->rq_history_seq >
473                                     svc->srv_request_max_cull_seq)
474                                         svc->srv_request_max_cull_seq =
475                                                 req->rq_history_seq;
476                                 list_del(&req->rq_history_list);
477                         }
478
479                         spin_unlock(&svc->srv_lock);
480
481                         list_for_each_safe(tmp, nxt, &rqbd->rqbd_reqs) {
482                                 req = list_entry(rqbd->rqbd_reqs.next,
483                                                  struct ptlrpc_request,
484                                                  rq_list);
485                                 list_del(&req->rq_list);
486                                 ptlrpc_server_free_request(req);
487                         }
488
489                         spin_lock(&svc->srv_lock);
490                         /*
491                          * now all reqs including the embedded req has been
492                          * disposed, schedule request buffer for re-use.
493                          */
494                         LASSERT(atomic_read(&rqbd->rqbd_req.rq_refcount) == 0);
495                         list_add_tail(&rqbd->rqbd_list, &svc->srv_idle_rqbds);
496                 }
497
498                 spin_unlock(&svc->srv_lock);
499         } else if (req->rq_reply_state && req->rq_reply_state->rs_prealloc) {
500                  /* If we are low on memory, we are not interested in history */
501                 list_del(&req->rq_list);
502                 list_del_init(&req->rq_history_list);
503                 spin_unlock(&svc->srv_lock);
504
505                 ptlrpc_server_free_request(req);
506         } else {
507                 spin_unlock(&svc->srv_lock);
508         }
509 }
510
511 /**
512  * to finish a request: stop sending more early replies, and release
513  * the request. should be called after we finished handling the request.
514  */
515 static void ptlrpc_server_finish_request(struct ptlrpc_request *req)
516 {
517         struct ptlrpc_service  *svc = req->rq_rqbd->rqbd_service;
518
519         if (req->rq_export) {
520                 class_export_put(req->rq_export);
521                 req->rq_export = NULL;
522         }
523
524         if (req->rq_phase != RQ_PHASE_NEW) /* incorrect message magic */
525                 DEBUG_REQ(D_INFO, req, "free req");
526
527         spin_lock(&svc->srv_at_lock);
528         req->rq_sent_final = 1;
529         list_del_init(&req->rq_timed_list);
530         if (req->rq_at_linked) {
531                 struct ptlrpc_at_array *array = &svc->srv_at_array;
532                 __u32 index = req->rq_at_index;
533
534                 req->rq_at_linked = 0;
535                 array->paa_reqs_count[index]--;
536                 array->paa_count--;
537         }
538         spin_unlock(&svc->srv_at_lock);
539
540         ptlrpc_server_drop_request(req);
541 }
542
543 /* This function makes sure dead exports are evicted in a timely manner.
544    This function is only called when some export receives a message (i.e.,
545    the network is up.) */
546 static void ptlrpc_update_export_timer(struct obd_export *exp, long extra_delay)
547 {
548         struct obd_export *oldest_exp;
549         time_t oldest_time, new_time;
550
551         ENTRY;
552
553         LASSERT(exp);
554
555         /* Compensate for slow machines, etc, by faking our request time
556            into the future.  Although this can break the strict time-ordering
557            of the list, we can be really lazy here - we don't have to evict
558            at the exact right moment.  Eventually, all silent exports
559            will make it to the top of the list. */
560
561         /* Do not pay attention on 1sec or smaller renewals. */
562         new_time = cfs_time_current_sec() + extra_delay;
563         if (exp->exp_last_request_time + 1 /*second */ >= new_time)
564                 RETURN_EXIT;
565
566         exp->exp_last_request_time = new_time;
567         CDEBUG(D_INFO, "updating export %s at %ld\n",
568                exp->exp_client_uuid.uuid,
569                exp->exp_last_request_time);
570
571         /* exports may get disconnected from the chain even though the
572            export has references, so we must keep the spin lock while
573            manipulating the lists */
574         spin_lock(&exp->exp_obd->obd_dev_lock);
575
576         if (list_empty(&exp->exp_obd_chain_timed)) {
577                 /* this one is not timed */
578                 spin_unlock(&exp->exp_obd->obd_dev_lock);
579                 RETURN_EXIT;
580         }
581
582         list_move_tail(&exp->exp_obd_chain_timed,
583                        &exp->exp_obd->obd_exports_timed);
584
585         oldest_exp = list_entry(exp->exp_obd->obd_exports_timed.next,
586                                 struct obd_export, exp_obd_chain_timed);
587         oldest_time = oldest_exp->exp_last_request_time;
588         spin_unlock(&exp->exp_obd->obd_dev_lock);
589
590         if (exp->exp_obd->obd_recovering) {
591                 /* be nice to everyone during recovery */
592                 EXIT;
593                 return;
594         }
595
596         /* Note - racing to start/reset the obd_eviction timer is safe */
597         if (exp->exp_obd->obd_eviction_timer == 0) {
598                 /* Check if the oldest entry is expired. */
599                 if (cfs_time_current_sec() > (oldest_time + PING_EVICT_TIMEOUT +
600                                               extra_delay)) {
601                         /* We need a second timer, in case the net was down and
602                          * it just came back. Since the pinger may skip every
603                          * other PING_INTERVAL (see note in ptlrpc_pinger_main),
604                          * we better wait for 3. */
605                         exp->exp_obd->obd_eviction_timer =
606                                 cfs_time_current_sec() + 3 * PING_INTERVAL;
607                         CDEBUG(D_HA, "%s: Think about evicting %s from %ld\n",
608                                exp->exp_obd->obd_name, obd_export_nid2str(exp),
609                                oldest_time);
610                 }
611         } else {
612                 if (cfs_time_current_sec() >
613                     (exp->exp_obd->obd_eviction_timer + extra_delay)) {
614                         /* The evictor won't evict anyone who we've heard from
615                          * recently, so we don't have to check before we start
616                          * it. */
617                         if (!ping_evictor_wake(exp))
618                                 exp->exp_obd->obd_eviction_timer = 0;
619                 }
620         }
621
622         EXIT;
623 }
624
625 static int ptlrpc_check_req(struct ptlrpc_request *req)
626 {
627         if (lustre_msg_get_conn_cnt(req->rq_reqmsg) <
628             req->rq_export->exp_conn_cnt) {
629                 DEBUG_REQ(D_ERROR, req,
630                           "DROPPING req from old connection %d < %d",
631                           lustre_msg_get_conn_cnt(req->rq_reqmsg),
632                           req->rq_export->exp_conn_cnt);
633                 return -EEXIST;
634         }
635         if (req->rq_export->exp_obd && req->rq_export->exp_obd->obd_fail) {
636              /* Failing over, don't handle any more reqs, send
637                 error response instead. */
638                 CDEBUG(D_RPCTRACE, "Dropping req %p for failed obd %s\n",
639                        req, req->rq_export->exp_obd->obd_name);
640                 req->rq_status = -ENODEV;
641                 ptlrpc_error(req);
642                 return -ENODEV;
643         }
644         return 0;
645 }
646
647 static void ptlrpc_at_set_timer(struct ptlrpc_service *svc)
648 {
649         struct ptlrpc_at_array *array = &svc->srv_at_array;
650         __s32 next;
651
652         spin_lock(&svc->srv_at_lock);
653         if (array->paa_count == 0) {
654                 cfs_timer_disarm(&svc->srv_at_timer);
655                 spin_unlock(&svc->srv_at_lock);
656                 return;
657         }
658
659         /* Set timer for closest deadline */
660         next = (__s32)(array->paa_deadline - cfs_time_current_sec() -
661                        at_early_margin);
662         if (next <= 0)
663                 ptlrpc_at_timer((unsigned long)svc);
664         else
665                 cfs_timer_arm(&svc->srv_at_timer, cfs_time_shift(next));
666         spin_unlock(&svc->srv_at_lock);
667         CDEBUG(D_INFO, "armed %s at %+ds\n", svc->srv_name, next);
668 }
669
670 /* Add rpc to early reply check list */
671 static int ptlrpc_at_add_timed(struct ptlrpc_request *req)
672 {
673         struct ptlrpc_service *svc = req->rq_rqbd->rqbd_service;
674         struct ptlrpc_request *rq = NULL;
675         struct ptlrpc_at_array *array = &svc->srv_at_array;
676         __u32 index;
677         int found = 0;
678
679         if (AT_OFF)
680                 return(0);
681
682         if ((lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT) == 0)
683                 return(-ENOSYS);
684
685         spin_lock(&svc->srv_at_lock);
686
687         if (unlikely(req->rq_sent_final)) {
688                 spin_unlock(&svc->srv_at_lock);
689                 return 0;
690         }
691
692         LASSERT(list_empty(&req->rq_timed_list));
693
694         index = (unsigned long)req->rq_deadline % array->paa_size;
695         if (array->paa_reqs_count[index] > 0) {
696                 /* latest rpcs will have the latest deadlines in the list,
697                  * so search backward. */
698                 list_for_each_entry_reverse(rq, &array->paa_reqs_array[index],
699                                             rq_timed_list) {
700                         if (req->rq_deadline >= rq->rq_deadline) {
701                                 list_add(&req->rq_timed_list,
702                                          &rq->rq_timed_list);
703                                 break;
704                         }
705                 }
706         }
707         
708         /* Add the request at the head of the list */
709         if (list_empty(&req->rq_timed_list))
710                 list_add(&req->rq_timed_list, &array->paa_reqs_array[index]);
711
712         req->rq_at_linked = 1;
713         req->rq_at_index = index;
714         array->paa_reqs_count[index]++;
715         array->paa_count++;
716         if (array->paa_count == 1 || array->paa_deadline > req->rq_deadline) {
717                 array->paa_deadline = req->rq_deadline;
718                 found = 1;
719         }
720         spin_unlock(&svc->srv_at_lock);
721
722         if (found)
723                 ptlrpc_at_set_timer(svc);
724
725         return 0;
726 }
727
728 static int ptlrpc_at_send_early_reply(struct ptlrpc_request *req,
729                                       int extra_time)
730 {
731         struct ptlrpc_service *svc = req->rq_rqbd->rqbd_service;
732         struct ptlrpc_request *reqcopy;
733         struct lustre_msg *reqmsg;
734         long olddl = req->rq_deadline - cfs_time_current_sec();
735         time_t newdl;
736         int rc;
737         ENTRY;
738
739         /* deadline is when the client expects us to reply, margin is the
740            difference between clients' and servers' expectations */
741         DEBUG_REQ(D_ADAPTTO, req,
742                   "%ssending early reply (deadline %+lds, margin %+lds) for "
743                   "%d+%d", AT_OFF ? "AT off - not " : "",
744                   olddl, olddl - at_get(&svc->srv_at_estimate),
745                   at_get(&svc->srv_at_estimate), extra_time);
746
747         if (AT_OFF)
748                 RETURN(0);
749
750         if (olddl < 0) {
751                 DEBUG_REQ(D_WARNING, req, "Already past deadline (%+lds), "
752                           "not sending early reply. Consider increasing "
753                           "at_early_margin (%d)?", olddl, at_early_margin);
754
755                 /* Return an error so we're not re-added to the timed list. */
756                 RETURN(-ETIMEDOUT);
757         }
758
759         if ((lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT) == 0){
760                 DEBUG_REQ(D_INFO, req, "Wanted to ask client for more time, "
761                           "but no AT support");
762                 RETURN(-ENOSYS);
763         }
764
765         if (req->rq_export && req->rq_export->exp_in_recovery) {
766                 /* don't increase server estimates during recovery, and give
767                    clients the full recovery time. */
768                 newdl = cfs_time_current_sec() +
769                         req->rq_export->exp_obd->obd_recovery_timeout;
770         } else {
771                 if (extra_time) {
772                         /* Fake our processing time into the future to ask the
773                            clients for some extra amount of time */
774                         extra_time += cfs_time_current_sec() -
775                                       req->rq_arrival_time.tv_sec;
776                         at_add(&svc->srv_at_estimate, extra_time);
777                 }
778                 newdl = req->rq_arrival_time.tv_sec +
779                         at_get(&svc->srv_at_estimate);
780         }
781         if (req->rq_deadline >= newdl) {
782                 /* We're not adding any time, no need to send an early reply
783                    (e.g. maybe at adaptive_max) */
784                 DEBUG_REQ(D_WARNING, req, "Couldn't add any time "
785                           "(%ld/%ld), not sending early reply\n",
786                           olddl, newdl - cfs_time_current_sec());
787                 RETURN(-ETIMEDOUT);
788         }
789
790         OBD_ALLOC(reqcopy, sizeof *reqcopy);
791         if (reqcopy == NULL)
792                 RETURN(-ENOMEM);
793         OBD_ALLOC(reqmsg, req->rq_reqlen);
794         if (!reqmsg) {
795                 OBD_FREE(reqcopy, sizeof *reqcopy);
796                 RETURN(-ENOMEM);
797         }
798
799         *reqcopy = *req;
800         reqcopy->rq_reply_state = NULL;
801         reqcopy->rq_rep_swab_mask = 0;
802         /* We only need the reqmsg for the magic */
803         reqcopy->rq_reqmsg = reqmsg;
804         memcpy(reqmsg, req->rq_reqmsg, req->rq_reqlen);
805
806         if (req->rq_sent_final) {
807                 DEBUG_REQ(D_ADAPTTO, reqcopy, "Normal reply already sent out, "
808                           "abort sending early reply\n");
809                 GOTO(out, rc = 0);
810         }
811
812         /* Connection ref */
813         reqcopy->rq_export = class_conn2export(
814                                      lustre_msg_get_handle(reqcopy->rq_reqmsg));
815         if (reqcopy->rq_export == NULL)
816                 GOTO(out, rc = -ENODEV);
817
818         /* RPC ref */
819         class_export_rpc_get(reqcopy->rq_export);
820         if (reqcopy->rq_export->exp_obd &&
821             reqcopy->rq_export->exp_obd->obd_fail)
822                 GOTO(out_put, rc = -ENODEV);
823
824         rc = lustre_pack_reply_flags(reqcopy, 1, NULL, NULL, LPRFL_EARLY_REPLY);
825         if (rc)
826                 GOTO(out_put, rc);
827
828         rc = ptlrpc_send_reply(reqcopy, PTLRPC_REPLY_EARLY);
829
830         if (!rc) {
831                 /* Adjust our own deadline to what we told the client */
832                 req->rq_deadline = newdl;
833                 req->rq_early_count++; /* number sent, server side */
834         } else {
835                 DEBUG_REQ(D_ERROR, req, "Early reply send failed %d", rc);
836         }
837
838         /* Free the (early) reply state from lustre_pack_reply.
839            (ptlrpc_send_reply takes it's own rs ref, so this is safe here) */
840         ptlrpc_req_drop_rs(reqcopy);
841
842 out_put:
843         class_export_rpc_put(reqcopy->rq_export);
844         class_export_put(reqcopy->rq_export);
845 out:
846         OBD_FREE(reqmsg, req->rq_reqlen);
847         OBD_FREE(reqcopy, sizeof *reqcopy);
848         RETURN(rc);
849 }
850
851 /* Send early replies to everybody expiring within at_early_margin
852    asking for at_extra time */
853 static int ptlrpc_at_check_timed(struct ptlrpc_service *svc)
854 {
855         struct ptlrpc_request *rq, *n;
856         struct list_head work_list;
857         struct ptlrpc_at_array *array = &svc->srv_at_array;
858         __u32  index, count;
859         time_t deadline;
860         time_t now = cfs_time_current_sec();
861         cfs_duration_t delay;
862         int first, counter = 0;
863         ENTRY;
864
865         spin_lock(&svc->srv_at_lock);
866         if (svc->srv_at_check == 0) {
867                 spin_unlock(&svc->srv_at_lock);
868                 RETURN(0);
869         }
870         delay = cfs_time_sub(cfs_time_current(), svc->srv_at_checktime);
871         svc->srv_at_check = 0;
872
873         if (array->paa_count == 0) {
874                 spin_unlock(&svc->srv_at_lock);
875                 RETURN(0);
876         }
877
878         /* The timer went off, but maybe the nearest rpc already completed. */
879         first = array->paa_deadline - now;
880         if (first > at_early_margin) {
881                 /* We've still got plenty of time.  Reset the timer. */
882                 spin_unlock(&svc->srv_at_lock);
883                 ptlrpc_at_set_timer(svc);
884                 RETURN(0);
885         }
886
887         /* We're close to a timeout, and we don't know how much longer the
888            server will take. Send early replies to everyone expiring soon. */
889         CFS_INIT_LIST_HEAD(&work_list);
890         deadline = -1;
891         index = (unsigned long)array->paa_deadline % array->paa_size;
892         count = array->paa_count;
893         while (count > 0) {
894                 count -= array->paa_reqs_count[index];
895                 list_for_each_entry_safe(rq, n, &array->paa_reqs_array[index],
896                                          rq_timed_list) {
897                         if (rq->rq_deadline <= now + at_early_margin) {
898                                 list_move(&rq->rq_timed_list, &work_list);
899                                 counter++;
900                                 array->paa_reqs_count[index]--;
901                                 array->paa_count--;
902                                 rq->rq_at_linked = 0;
903                                 continue;
904                         }
905
906                         /* update the earliest deadline */
907                         if (deadline == -1 || rq->rq_deadline < deadline)
908                                 deadline = rq->rq_deadline;
909
910                         break;
911                 }
912
913                 if (++index >= array->paa_size)
914                         index = 0;
915         }
916         array->paa_deadline = deadline;
917         spin_unlock(&svc->srv_at_lock);
918
919         /* we have a new earliest deadline, restart the timer */
920         ptlrpc_at_set_timer(svc);
921
922         CDEBUG(D_ADAPTTO, "timeout in %+ds, asking for %d secs on %d early "
923                "replies\n", first, at_extra, counter);
924
925         if (first < 0) {
926                 /* We're already past request deadlines before we even get a
927                    chance to send early replies */
928                 LCONSOLE_WARN("%s: This server is not able to keep up with "
929                               "request traffic (cpu-bound).\n",  svc->srv_name);
930                 CWARN("earlyQ=%d reqQ=%d recA=%d, svcEst=%d, "
931                       "delay="CFS_DURATION_T"(jiff)\n",
932                       counter, svc->srv_n_queued_reqs, svc->srv_n_active_reqs,
933                       at_get(&svc->srv_at_estimate), delay);
934         }
935
936         /* ptlrpc_server_finish_request may delete an entry out of
937          * the work list */
938         spin_lock(&svc->srv_at_lock);
939         while (!list_empty(&work_list)) {
940                 rq = list_entry(work_list.next, struct ptlrpc_request,
941                                 rq_timed_list);
942                 list_del_init(&rq->rq_timed_list);
943                 /* if the entry is still in the worklist, it hasn't been
944                    deleted, and is safe to take a ref to keep the req around */
945                 atomic_inc(&rq->rq_refcount);
946                 spin_unlock(&svc->srv_at_lock);
947
948                 if (ptlrpc_at_send_early_reply(rq, at_extra) == 0)
949                         ptlrpc_at_add_timed(rq);
950
951                 ptlrpc_server_drop_request(rq);
952                 spin_lock(&svc->srv_at_lock);
953         }
954         spin_unlock(&svc->srv_at_lock);
955
956         RETURN(0);
957 }
958
959 /**
960  * Put the request to the export list if the request may become
961  * a high priority one.
962  */
963 static int ptlrpc_hpreq_init(struct ptlrpc_service *svc,
964                              struct ptlrpc_request *req)
965 {
966         int rc;
967         ENTRY;
968
969         if (svc->srv_hpreq_handler) {
970                 rc = svc->srv_hpreq_handler(req);
971                 if (rc)
972                         RETURN(rc);
973         }
974         if (req->rq_export && req->rq_ops) {
975                 spin_lock(&req->rq_export->exp_lock);
976                 list_add(&req->rq_exp_list, &req->rq_export->exp_queued_rpc);
977                 spin_unlock(&req->rq_export->exp_lock);
978         }
979
980         RETURN(0);
981 }
982
983 /** Remove the request from the export list. */
984 static void ptlrpc_hpreq_fini(struct ptlrpc_request *req)
985 {
986         ENTRY;
987         if (req->rq_export && req->rq_ops) {
988                 spin_lock(&req->rq_export->exp_lock);
989                 list_del_init(&req->rq_exp_list);
990                 spin_unlock(&req->rq_export->exp_lock);
991         }
992         EXIT;
993 }
994
995 /**
996  * Make the request a high priority one.
997  *
998  * All the high priority requests are queued in a separate FIFO
999  * ptlrpc_service::srv_request_hpq list which is parallel to
1000  * ptlrpc_service::srv_request_queue list but has a higher priority
1001  * for handling.
1002  *
1003  * \see ptlrpc_server_handle_request().
1004  */
1005 static void ptlrpc_hpreq_reorder_nolock(struct ptlrpc_service *svc,
1006                                         struct ptlrpc_request *req)
1007 {
1008         ENTRY;
1009         LASSERT(svc != NULL);
1010         spin_lock(&req->rq_lock);
1011         if (req->rq_hp == 0) {
1012                 int opc = lustre_msg_get_opc(req->rq_reqmsg);
1013
1014                 /* Add to the high priority queue. */
1015                 list_move_tail(&req->rq_list, &svc->srv_request_hpq);
1016                 req->rq_hp = 1;
1017                 if (opc != OBD_PING)
1018                         DEBUG_REQ(D_NET, req, "high priority req");
1019         }
1020         spin_unlock(&req->rq_lock);
1021         EXIT;
1022 }
1023
1024 void ptlrpc_hpreq_reorder(struct ptlrpc_request *req)
1025 {
1026         struct ptlrpc_service *svc = req->rq_rqbd->rqbd_service;
1027         ENTRY;
1028
1029         spin_lock(&svc->srv_lock);
1030         /* It may happen that the request is already taken for the processing
1031          * but still in the export list, do not re-add it into the HP list. */
1032         if (req->rq_phase == RQ_PHASE_NEW)
1033                 ptlrpc_hpreq_reorder_nolock(svc, req);
1034         spin_unlock(&svc->srv_lock);
1035         EXIT;
1036 }
1037
1038 /** Check if the request if a high priority one. */
1039 static int ptlrpc_server_hpreq_check(struct ptlrpc_request *req)
1040 {
1041         int opc, rc = 0;
1042         ENTRY;
1043
1044         /* Check by request opc. */
1045         opc = lustre_msg_get_opc(req->rq_reqmsg);
1046         if (opc == OBD_PING)
1047                 RETURN(1);
1048
1049         /* Perform request specific check. */
1050         if (req->rq_ops && req->rq_ops->hpreq_check)
1051                 rc = req->rq_ops->hpreq_check(req);
1052         RETURN(rc);
1053 }
1054
1055 /** Check if a request is a high priority one. */
1056 static int ptlrpc_server_request_add(struct ptlrpc_service *svc,
1057                                      struct ptlrpc_request *req)
1058 {
1059         int rc;
1060         ENTRY;
1061
1062         rc = ptlrpc_server_hpreq_check(req);
1063         if (rc < 0)
1064                 RETURN(rc);
1065
1066         spin_lock(&svc->srv_lock);
1067         /* Before inserting the request into the queue, check if it is not
1068          * inserted yet, or even already handled -- it may happen due to
1069          * a racing ldlm_server_blocking_ast(). */
1070         if (req->rq_phase == RQ_PHASE_NEW && list_empty(&req->rq_list)) {
1071                 if (rc)
1072                         ptlrpc_hpreq_reorder_nolock(svc, req);
1073                 else
1074                         list_add_tail(&req->rq_list, &svc->srv_request_queue);
1075         }
1076         spin_unlock(&svc->srv_lock);
1077
1078         RETURN(0);
1079 }
1080
1081 /* Only allow normal priority requests on a service that has a high-priority
1082  * queue if forced (i.e. cleanup), if there are other high priority requests
1083  * already being processed (i.e. those threads can service more high-priority
1084  * requests), or if there are enough idle threads that a later thread can do
1085  * a high priority request. */
1086 static int ptlrpc_server_allow_normal(struct ptlrpc_service *svc, int force)
1087 {
1088         return force || !svc->srv_hpreq_handler || svc->srv_n_hpreq > 0 ||
1089                svc->srv_n_active_reqs < svc->srv_threads_running - 2;
1090 }
1091
1092 static struct ptlrpc_request *
1093 ptlrpc_server_request_get(struct ptlrpc_service *svc, int force)
1094 {
1095         struct ptlrpc_request *req = NULL;
1096         ENTRY;
1097
1098         if (ptlrpc_server_allow_normal(svc, force) &&
1099             !list_empty(&svc->srv_request_queue) &&
1100             (list_empty(&svc->srv_request_hpq) ||
1101              svc->srv_hpreq_count >= svc->srv_hpreq_ratio)) {
1102                 req = list_entry(svc->srv_request_queue.next,
1103                                  struct ptlrpc_request, rq_list);
1104                 svc->srv_hpreq_count = 0;
1105         } else if (!list_empty(&svc->srv_request_hpq)) {
1106                 req = list_entry(svc->srv_request_hpq.next,
1107                                  struct ptlrpc_request, rq_list);
1108                 svc->srv_hpreq_count++;
1109         }
1110         RETURN(req);
1111 }
1112
1113 static int ptlrpc_server_request_pending(struct ptlrpc_service *svc, int force)
1114 {
1115         return ((ptlrpc_server_allow_normal(svc, force) &&
1116                  !list_empty(&svc->srv_request_queue)) ||
1117                 !list_empty(&svc->srv_request_hpq));
1118 }
1119
1120 /* Handle freshly incoming reqs, add to timed early reply list,
1121    pass on to regular request queue */
1122 static int
1123 ptlrpc_server_handle_req_in(struct ptlrpc_service *svc)
1124 {
1125         struct ptlrpc_request *req;
1126         __u32                  deadline;
1127         int                    rc;
1128         ENTRY;
1129
1130         LASSERT(svc);
1131
1132         spin_lock(&svc->srv_lock);
1133         if (list_empty(&svc->srv_req_in_queue)) {
1134                 spin_unlock(&svc->srv_lock);
1135                 RETURN(0);
1136         }
1137
1138         req = list_entry(svc->srv_req_in_queue.next,
1139                          struct ptlrpc_request, rq_list);
1140         list_del_init (&req->rq_list);
1141         /* Consider this still a "queued" request as far as stats are
1142            concerned */
1143         spin_unlock(&svc->srv_lock);
1144
1145         /* Clear request swab mask; this is a new request */
1146         req->rq_req_swab_mask = 0;
1147
1148         rc = lustre_unpack_msg(req->rq_reqmsg, req->rq_reqlen);
1149         if (rc < 0) {
1150                 CERROR ("error unpacking request: ptl %d from %s"
1151                         " xid "LPU64"\n", svc->srv_req_portal,
1152                         libcfs_id2str(req->rq_peer), req->rq_xid);
1153                 goto err_req;
1154         }
1155
1156         if (rc > 0)
1157                 lustre_set_req_swabbed(req, MSG_PTLRPC_HEADER_OFF);
1158
1159         rc = lustre_unpack_req_ptlrpc_body(req, MSG_PTLRPC_BODY_OFF);
1160         if (rc) {
1161                 CERROR ("error unpacking ptlrpc body: ptl %d from %s"
1162                         " xid "LPU64"\n", svc->srv_req_portal,
1163                         libcfs_id2str(req->rq_peer), req->rq_xid);
1164                 goto err_req;
1165         }
1166
1167         rc = -EINVAL;
1168         if (lustre_msg_get_type(req->rq_reqmsg) != PTL_RPC_MSG_REQUEST) {
1169                 CERROR("wrong packet type received (type=%u) from %s\n",
1170                        lustre_msg_get_type(req->rq_reqmsg),
1171                        libcfs_id2str(req->rq_peer));
1172                 goto err_req;
1173         }
1174
1175         CDEBUG(D_NET, "got req "LPU64"\n", req->rq_xid);
1176
1177         req->rq_export = class_conn2export(
1178                 lustre_msg_get_handle(req->rq_reqmsg));
1179         if (req->rq_export) {
1180                 rc = ptlrpc_check_req(req);
1181                 if (rc)
1182                         goto err_req;
1183                 ptlrpc_update_export_timer(req->rq_export, 0);
1184         }
1185
1186         /* req_in handling should/must be fast */
1187         if (cfs_time_current_sec() - req->rq_arrival_time.tv_sec > 5)
1188                 DEBUG_REQ(D_WARNING, req, "Slow req_in handling %lus",
1189                           cfs_time_current_sec() - req->rq_arrival_time.tv_sec);
1190
1191         /* Set rpc server deadline and add it to the timed list */
1192         deadline = (lustre_msghdr_get_flags(req->rq_reqmsg) &
1193                     MSGHDR_AT_SUPPORT) ?
1194                    /* The max time the client expects us to take */
1195                    lustre_msg_get_timeout(req->rq_reqmsg) : obd_timeout;
1196         req->rq_deadline = req->rq_arrival_time.tv_sec + deadline;
1197         if (unlikely(deadline == 0)) {
1198                 DEBUG_REQ(D_ERROR, req, "Dropping request with 0 timeout");
1199                 goto err_req;
1200         }
1201
1202         ptlrpc_at_add_timed(req);
1203         rc = ptlrpc_hpreq_init(svc, req);
1204         if (rc)
1205                 GOTO(err_req, rc);
1206
1207         /* Move it over to the request processing queue */
1208         rc = ptlrpc_server_request_add(svc, req);
1209         if (rc)
1210                 GOTO(err_req, rc);
1211         cfs_waitq_signal(&svc->srv_waitq);
1212         RETURN(1);
1213
1214 err_req:
1215         spin_lock(&svc->srv_lock);
1216         svc->srv_n_queued_reqs--;
1217         svc->srv_n_active_reqs++;
1218         spin_unlock(&svc->srv_lock);
1219         ptlrpc_server_finish_request(req);
1220
1221         RETURN(1);
1222 }
1223
1224 static int
1225 ptlrpc_server_handle_request(struct ptlrpc_service *svc,
1226                              struct ptlrpc_thread *thread)
1227 {
1228         struct obd_export     *export = NULL;
1229         struct ptlrpc_request *request;
1230         struct timeval         work_start;
1231         struct timeval         work_end;
1232         long                   timediff;
1233         int                    opc, rc;
1234         int                    fail_opc = 0;
1235         ENTRY;
1236
1237         LASSERT(svc);
1238
1239         spin_lock(&svc->srv_lock);
1240         if (!ptlrpc_server_request_pending(svc, 0) ||
1241             (
1242 #ifndef __KERNEL__
1243              /* !@%$# liblustre only has 1 thread */
1244              svc->srv_n_difficult_replies != 0 &&
1245 #endif
1246              svc->srv_n_active_reqs >= (svc->srv_threads_running - 1))) {
1247                 /* Don't handle regular requests in the last thread, in order
1248                  * to handle difficult replies (which might block other threads)
1249                  * as well as handle any incoming reqs, early replies, etc.
1250                  * That means we always need at least 2 service threads. */
1251                 spin_unlock(&svc->srv_lock);
1252                 RETURN(0);
1253         }
1254
1255         request = ptlrpc_server_request_get(svc, 0);
1256         if  (request == NULL) {
1257                 spin_unlock(&svc->srv_lock);
1258                 RETURN(0);
1259         }
1260
1261         opc = lustre_msg_get_opc(request->rq_reqmsg);
1262         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT))
1263                 fail_opc = OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT;
1264         else if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT))
1265                 fail_opc = OBD_FAIL_PTLRPC_HPREQ_TIMEOUT;
1266
1267         if (unlikely(fail_opc)) {
1268                 if (request->rq_export && request->rq_ops) {
1269                         spin_unlock(&svc->srv_lock);
1270                         OBD_FAIL_TIMEOUT(fail_opc, 4);
1271                         spin_lock(&svc->srv_lock);
1272                         request = ptlrpc_server_request_get(svc, 0);
1273                         if  (request == NULL) {
1274                                 spin_unlock(&svc->srv_lock);
1275                                 RETURN(0);
1276                         }
1277                         LASSERT(ptlrpc_server_request_pending(svc, 0));
1278                 }
1279         }
1280
1281         list_del_init(&request->rq_list);
1282         svc->srv_n_queued_reqs--;
1283         svc->srv_n_active_reqs++;
1284
1285         if (request->rq_hp)
1286                 svc->srv_n_hpreq++;
1287
1288         /* The phase is changed under the lock here because we need to know
1289          * the request is under processing (see ptlrpc_hpreq_reorder()). */
1290         ptlrpc_rqphase_move(request, RQ_PHASE_INTERPRET);
1291         spin_unlock(&svc->srv_lock);
1292
1293         ptlrpc_hpreq_fini(request);
1294
1295         if(OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_DUMP_LOG))
1296                 libcfs_debug_dumplog();
1297
1298         do_gettimeofday(&work_start);
1299         timediff = cfs_timeval_sub(&work_start, &request->rq_arrival_time,NULL);
1300         if (svc->srv_stats != NULL) {
1301                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQWAIT_CNTR,
1302                                     timediff);
1303                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQQDEPTH_CNTR,
1304                                     svc->srv_n_queued_reqs);
1305                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQACTIVE_CNTR,
1306                                     svc->srv_n_active_reqs);
1307                 lprocfs_counter_add(svc->srv_stats, PTLRPC_TIMEOUT,
1308                                     at_get(&svc->srv_at_estimate));
1309         }
1310
1311         CDEBUG(D_NET, "got req "LPU64"\n", request->rq_xid);
1312
1313         request->rq_svc_thread = thread;
1314         if (request->rq_export) {
1315                 if (ptlrpc_check_req(request))
1316                         goto put_conn;
1317                 ptlrpc_update_export_timer(request->rq_export, timediff >> 19);
1318                 export = class_export_rpc_get(request->rq_export);
1319         }
1320
1321         /* Discard requests queued for longer than the deadline.
1322            The deadline is increased if we send an early reply. */
1323         if (cfs_time_current_sec() > request->rq_deadline) {
1324                 DEBUG_REQ(D_ERROR, request, "Dropping timed-out request from %s"
1325                           ": deadline %ld%+lds ago\n",
1326                           libcfs_id2str(request->rq_peer),
1327                           request->rq_deadline -
1328                           request->rq_arrival_time.tv_sec,
1329                           cfs_time_current_sec() - request->rq_deadline);
1330                 goto put_rpc_export;
1331         }
1332
1333         CDEBUG(D_RPCTRACE, "Handling RPC pname:cluuid+ref:pid:xid:nid:opc "
1334                "%s:%s+%d:%d:x"LPU64":%s:%d\n", cfs_curproc_comm(),
1335                (request->rq_export ?
1336                 (char *)request->rq_export->exp_client_uuid.uuid : "0"),
1337                (request->rq_export ?
1338                 atomic_read(&request->rq_export->exp_refcount) : -99),
1339                lustre_msg_get_status(request->rq_reqmsg), request->rq_xid,
1340                libcfs_id2str(request->rq_peer),
1341                lustre_msg_get_opc(request->rq_reqmsg));
1342
1343         if (lustre_msg_get_opc(request->rq_reqmsg) != OBD_PING)
1344                 OBD_FAIL_TIMEOUT_MS(OBD_FAIL_PTLRPC_PAUSE_REQ, obd_fail_val);
1345
1346         rc = svc->srv_handler(request);
1347
1348         ptlrpc_rqphase_move(request, RQ_PHASE_COMPLETE);
1349
1350         CDEBUG(D_RPCTRACE, "Handled RPC pname:cluuid+ref:pid:xid:nid:opc "
1351                "%s:%s+%d:%d:x"LPU64":%s:%d\n", cfs_curproc_comm(),
1352                (request->rq_export ?
1353                 (char *)request->rq_export->exp_client_uuid.uuid : "0"),
1354                (request->rq_export ?
1355                 atomic_read(&request->rq_export->exp_refcount) : -99),
1356                lustre_msg_get_status(request->rq_reqmsg), request->rq_xid,
1357                libcfs_id2str(request->rq_peer),
1358                lustre_msg_get_opc(request->rq_reqmsg));
1359
1360 put_rpc_export:
1361         if (export != NULL && !request->rq_copy_queued)
1362                 class_export_rpc_put(export);
1363
1364 put_conn:
1365         if (cfs_time_current_sec() > request->rq_deadline) {
1366                 DEBUG_REQ(D_WARNING, request, "Request x"LPU64" took longer "
1367                           "than estimated (%ld%+lds); client may timeout.",
1368                           request->rq_xid, request->rq_deadline -
1369                           request->rq_arrival_time.tv_sec,
1370                           cfs_time_current_sec() - request->rq_deadline);
1371         }
1372
1373         do_gettimeofday(&work_end);
1374         timediff = cfs_timeval_sub(&work_end, &work_start, NULL);
1375         CDEBUG(D_RPCTRACE, "request x"LPU64" opc %u from %s processed in "
1376                "%ldus (%ldus total) trans "LPU64" rc %d/%d\n",
1377                request->rq_xid, lustre_msg_get_opc(request->rq_reqmsg),
1378                libcfs_id2str(request->rq_peer), timediff,
1379                cfs_timeval_sub(&work_end, &request->rq_arrival_time, NULL),
1380                request->rq_repmsg ? lustre_msg_get_transno(request->rq_repmsg) :
1381                request->rq_transno, request->rq_status,
1382                request->rq_repmsg ? lustre_msg_get_status(request->rq_repmsg):
1383                -999);
1384         if (svc->srv_stats != NULL) {
1385                 __u32 op = lustre_msg_get_opc(request->rq_reqmsg);
1386                 int opc = opcode_offset(op);
1387                 if (opc > 0 && !(op == LDLM_ENQUEUE || op == MDS_REINT)) {
1388                         LASSERT(opc < LUSTRE_MAX_OPCODES);
1389                         lprocfs_counter_add(svc->srv_stats,
1390                                             opc + EXTRA_MAX_OPCODES,
1391                                             timediff);
1392                 }
1393         }
1394         if (request->rq_early_count) {
1395                 DEBUG_REQ(D_ADAPTTO, request,
1396                           "sent %d early replies before finishing in %lds",
1397                           request->rq_early_count,
1398                           work_end.tv_sec - request->rq_arrival_time.tv_sec);
1399         }
1400
1401         spin_lock(&svc->srv_lock);
1402         if (request->rq_hp)
1403                 svc->srv_n_hpreq--;
1404         spin_unlock(&svc->srv_lock);
1405         ptlrpc_server_finish_request(request);
1406
1407         RETURN(1);
1408 }
1409
1410 static int
1411 ptlrpc_server_handle_reply (struct ptlrpc_service *svc)
1412 {
1413         struct ptlrpc_reply_state *rs;
1414         struct obd_export         *exp;
1415         struct obd_device         *obd;
1416         int                        nlocks;
1417         int                        been_handled;
1418         ENTRY;
1419
1420         spin_lock(&svc->srv_lock);
1421         if (list_empty (&svc->srv_reply_queue)) {
1422                 spin_unlock(&svc->srv_lock);
1423                 RETURN(0);
1424         }
1425
1426         rs = list_entry (svc->srv_reply_queue.next,
1427                          struct ptlrpc_reply_state, rs_list);
1428
1429         exp = rs->rs_export;
1430         obd = exp->exp_obd;
1431
1432         LASSERT (rs->rs_difficult);
1433         LASSERT (rs->rs_scheduled);
1434
1435         list_del_init (&rs->rs_list);
1436
1437         /* Disengage from notifiers carefully (lock order - irqrestore below!)*/
1438         spin_unlock(&svc->srv_lock);
1439
1440         spin_lock (&exp->exp_uncommitted_replies_lock);
1441         /* Noop if removed already */
1442         list_del_init (&rs->rs_obd_list);
1443         spin_unlock (&exp->exp_uncommitted_replies_lock);
1444
1445         spin_lock (&exp->exp_lock);
1446         /* Noop if removed already */
1447         list_del_init (&rs->rs_exp_list);
1448         spin_unlock (&exp->exp_lock);
1449
1450         spin_lock(&svc->srv_lock);
1451
1452         been_handled = rs->rs_handled;
1453         rs->rs_handled = 1;
1454
1455         nlocks = rs->rs_nlocks;                 /* atomic "steal", but */
1456         rs->rs_nlocks = 0;                      /* locks still on rs_locks! */
1457
1458         if (nlocks == 0 && !been_handled) {
1459                 /* If we see this, we should already have seen the warning
1460                  * in mds_steal_ack_locks()  */
1461                 CWARN("All locks stolen from rs %p x"LPD64".t"LPD64
1462                       " o%d NID %s\n", rs, rs->rs_xid, rs->rs_transno,
1463                       lustre_msg_get_opc(rs->rs_msg),
1464                       libcfs_nid2str(exp->exp_connection->c_peer.nid));
1465         }
1466
1467         if ((!been_handled && rs->rs_on_net) || nlocks > 0) {
1468                 spin_unlock(&svc->srv_lock);
1469
1470                 if (!been_handled && rs->rs_on_net) {
1471                         LNetMDUnlink(rs->rs_md_h);
1472                         /* Ignore return code; we're racing with
1473                          * completion... */
1474                 }
1475
1476                 while (nlocks-- > 0)
1477                         ldlm_lock_decref(&rs->rs_locks[nlocks],
1478                                          rs->rs_modes[nlocks]);
1479
1480                 spin_lock(&svc->srv_lock);
1481         }
1482
1483         rs->rs_scheduled = 0;
1484
1485         if (!rs->rs_on_net) {
1486                 /* Off the net */
1487                 svc->srv_n_difficult_replies--;
1488                 spin_unlock(&svc->srv_lock);
1489
1490                 class_export_put (exp);
1491                 rs->rs_export = NULL;
1492                 ptlrpc_rs_decref (rs);
1493                 atomic_dec (&svc->srv_outstanding_replies);
1494                 RETURN(1);
1495         }
1496
1497         /* still on the net; callback will schedule */
1498         spin_unlock(&svc->srv_lock);
1499         RETURN(1);
1500 }
1501
1502 #ifndef __KERNEL__
1503 /* FIXME make use of timeout later */
1504 int
1505 liblustre_check_services (void *arg)
1506 {
1507         int  did_something = 0;
1508         int  rc;
1509         struct list_head *tmp, *nxt;
1510         ENTRY;
1511
1512         /* I'm relying on being single threaded, not to have to lock
1513          * ptlrpc_all_services etc */
1514         list_for_each_safe (tmp, nxt, &ptlrpc_all_services) {
1515                 struct ptlrpc_service *svc =
1516                         list_entry (tmp, struct ptlrpc_service, srv_list);
1517
1518                 if (svc->srv_threads_running != 0)     /* I've recursed */
1519                         continue;
1520
1521                 /* service threads can block for bulk, so this limits us
1522                  * (arbitrarily) to recursing 1 stack frame per service.
1523                  * Note that the problem with recursion is that we have to
1524                  * unwind completely before our caller can resume. */
1525
1526                 svc->srv_threads_running++;
1527
1528                 do {
1529                         rc = ptlrpc_server_handle_req_in(svc);
1530                         rc |= ptlrpc_server_handle_reply(svc);
1531                         rc |= ptlrpc_at_check_timed(svc);
1532                         rc |= ptlrpc_server_handle_request(svc, NULL);
1533                         rc |= (ptlrpc_server_post_idle_rqbds(svc) > 0);
1534                         did_something |= rc;
1535                 } while (rc);
1536
1537                 svc->srv_threads_running--;
1538         }
1539
1540         RETURN(did_something);
1541 }
1542 #define ptlrpc_stop_all_threads(s) do {} while (0)
1543
1544 #else /* __KERNEL__ */
1545
1546 static void
1547 ptlrpc_check_rqbd_pool(struct ptlrpc_service *svc)
1548 {
1549         int avail = svc->srv_nrqbd_receiving;
1550         int low_water = test_req_buffer_pressure ? 0 :
1551                         svc->srv_nbuf_per_group/2;
1552
1553         /* NB I'm not locking; just looking. */
1554
1555         /* CAVEAT EMPTOR: We might be allocating buffers here because we've
1556          * allowed the request history to grow out of control.  We could put a
1557          * sanity check on that here and cull some history if we need the
1558          * space. */
1559
1560         if (avail <= low_water)
1561                 ptlrpc_grow_req_bufs(svc);
1562
1563         if (svc->srv_stats)
1564                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQBUF_AVAIL_CNTR,
1565                                     avail);
1566 }
1567
1568 static int
1569 ptlrpc_retry_rqbds(void *arg)
1570 {
1571         struct ptlrpc_service *svc = (struct ptlrpc_service *)arg;
1572
1573         svc->srv_rqbd_timeout = 0;
1574         return (-ETIMEDOUT);
1575 }
1576
1577 static int ptlrpc_main(void *arg)
1578 {
1579         struct ptlrpc_svc_data *data = (struct ptlrpc_svc_data *)arg;
1580         struct ptlrpc_service  *svc = data->svc;
1581         struct ptlrpc_thread   *thread = data->thread;
1582         struct obd_device      *dev = data->dev;
1583         struct ptlrpc_reply_state *rs;
1584 #ifdef WITH_GROUP_INFO
1585         struct group_info *ginfo = NULL;
1586 #endif
1587         int counter = 0, rc = 0;
1588         ENTRY;
1589
1590         cfs_daemonize_ctxt(data->name);
1591
1592 #if defined(HAVE_NODE_TO_CPUMASK) && defined(CONFIG_NUMA)
1593         /* we need to do this before any per-thread allocation is done so that
1594          * we get the per-thread allocations on local node.  bug 7342 */
1595         if (svc->srv_cpu_affinity) {
1596                 int cpu, num_cpu;
1597
1598                 for (cpu = 0, num_cpu = 0; cpu < num_possible_cpus(); cpu++) {
1599                         if (!cpu_online(cpu))
1600                                 continue;
1601                         if (num_cpu == thread->t_id % num_online_cpus())
1602                                 break;
1603                         num_cpu++;
1604                 }
1605                 set_cpus_allowed(cfs_current(), node_to_cpumask(cpu_to_node(cpu)));
1606         }
1607 #endif
1608
1609 #ifdef WITH_GROUP_INFO
1610         ginfo = groups_alloc(0);
1611         if (!ginfo) {
1612                 rc = -ENOMEM;
1613                 goto out;
1614         }
1615
1616         set_current_groups(ginfo);
1617         put_group_info(ginfo);
1618 #endif
1619
1620         if (svc->srv_init != NULL) {
1621                 rc = svc->srv_init(thread);
1622                 if (rc)
1623                         goto out;
1624         }
1625
1626         /* Alloc reply state structure for this one */
1627         OBD_ALLOC_GFP(rs, svc->srv_max_reply_size, CFS_ALLOC_STD);
1628         if (!rs) {
1629                 rc = -ENOMEM;
1630                 goto out_srv_init;
1631         }
1632
1633         /* Record that the thread is running */
1634         thread->t_flags = SVC_RUNNING;
1635         /*
1636          * wake up our creator. Note: @data is invalid after this point,
1637          * because it's allocated on ptlrpc_start_thread() stack.
1638          */
1639         cfs_waitq_signal(&thread->t_ctl_waitq);
1640
1641         thread->t_watchdog = lc_watchdog_add(GET_TIMEOUT(svc), NULL, NULL);
1642
1643         spin_lock(&svc->srv_lock);
1644         svc->srv_threads_running++;
1645         list_add(&rs->rs_list, &svc->srv_free_rs_list);
1646         spin_unlock(&svc->srv_lock);
1647         cfs_waitq_signal(&svc->srv_free_rs_waitq);
1648
1649         CDEBUG(D_NET, "service thread %d (#%d) started\n", thread->t_id,
1650                svc->srv_threads_running);
1651
1652         /* XXX maintain a list of all managed devices: insert here */
1653
1654         while ((thread->t_flags & SVC_STOPPING) == 0 ||
1655                svc->srv_n_difficult_replies != 0) {
1656                 /* Don't exit while there are replies to be handled */
1657                 struct l_wait_info lwi = LWI_TIMEOUT(svc->srv_rqbd_timeout,
1658                                                      ptlrpc_retry_rqbds, svc);
1659
1660                 lc_watchdog_disable(thread->t_watchdog);
1661
1662                 cond_resched();
1663
1664                 l_wait_event_exclusive (svc->srv_waitq,
1665                               ((thread->t_flags & SVC_STOPPING) != 0 &&
1666                                svc->srv_n_difficult_replies == 0) ||
1667                               (!list_empty(&svc->srv_idle_rqbds) &&
1668                                svc->srv_rqbd_timeout == 0) ||
1669                               !list_empty(&svc->srv_req_in_queue) ||
1670                               !list_empty(&svc->srv_reply_queue) ||
1671                               (ptlrpc_server_request_pending(svc, 0) &&
1672                                (svc->srv_n_active_reqs <
1673                                 (svc->srv_threads_running - 1))) ||
1674                               svc->srv_at_check,
1675                               &lwi);
1676
1677                 lc_watchdog_touch(thread->t_watchdog, GET_TIMEOUT(svc));
1678
1679                 ptlrpc_check_rqbd_pool(svc);
1680
1681                 if ((svc->srv_threads_started < svc->srv_threads_max) &&
1682                     (svc->srv_n_active_reqs >= (svc->srv_threads_started - 1))){
1683                         /* Ignore return code - we tried... */
1684                         ptlrpc_start_thread(dev, svc);
1685                 }
1686
1687                 if (!list_empty(&svc->srv_reply_queue))
1688                         ptlrpc_server_handle_reply (svc);
1689
1690                 if (!list_empty(&svc->srv_req_in_queue)) {
1691                         /* Process all incoming reqs before handling any */
1692                         ptlrpc_server_handle_req_in(svc);
1693                         /* but limit ourselves in case of flood */
1694                         if (counter++ < 1000)
1695                                 continue;
1696                         counter = 0;
1697                 }
1698
1699                 if (svc->srv_at_check)
1700                         ptlrpc_at_check_timed(svc);
1701
1702                 /* don't handle requests in the last thread */
1703                 if (ptlrpc_server_request_pending(svc, 0) &&
1704                     (svc->srv_n_active_reqs < (svc->srv_threads_running - 1)))
1705                         ptlrpc_server_handle_request(svc, thread);
1706
1707                 if (!list_empty(&svc->srv_idle_rqbds) &&
1708                     ptlrpc_server_post_idle_rqbds(svc) < 0) {
1709                         /* I just failed to repost request buffers.  Wait
1710                          * for a timeout (unless something else happens)
1711                          * before I try again */
1712                         svc->srv_rqbd_timeout = cfs_time_seconds(1)/10;
1713                         CDEBUG(D_RPCTRACE,"Posted buffers: %d\n",
1714                                svc->srv_nrqbd_receiving);
1715                 }
1716         }
1717
1718         lc_watchdog_delete(thread->t_watchdog);
1719         thread->t_watchdog = NULL;
1720
1721 out_srv_init:
1722         /*
1723          * deconstruct service specific state created by ptlrpc_start_thread()
1724          */
1725         if (svc->srv_done != NULL)
1726                 svc->srv_done(thread);
1727
1728 out:
1729         CDEBUG(D_NET, "service thread %d exiting: rc %d\n", thread->t_id, rc);
1730
1731         spin_lock(&svc->srv_lock);
1732         svc->srv_threads_running--;              /* must know immediately */
1733         thread->t_id = rc;
1734         thread->t_flags = SVC_STOPPED;
1735
1736         cfs_waitq_signal(&thread->t_ctl_waitq);
1737         spin_unlock(&svc->srv_lock);
1738
1739         return rc;
1740 }
1741
1742 static void ptlrpc_stop_thread(struct ptlrpc_service *svc,
1743                                struct ptlrpc_thread *thread)
1744 {
1745         struct l_wait_info lwi = { 0 };
1746
1747         spin_lock(&svc->srv_lock);
1748         thread->t_flags = SVC_STOPPING;
1749         spin_unlock(&svc->srv_lock);
1750
1751         cfs_waitq_broadcast(&svc->srv_waitq);
1752         l_wait_event(thread->t_ctl_waitq, (thread->t_flags & SVC_STOPPED),
1753                      &lwi);
1754
1755         spin_lock(&svc->srv_lock);
1756         list_del(&thread->t_link);
1757         spin_unlock(&svc->srv_lock);
1758
1759         OBD_FREE(thread, sizeof(*thread));
1760 }
1761
1762 void ptlrpc_stop_all_threads(struct ptlrpc_service *svc)
1763 {
1764         struct ptlrpc_thread *thread;
1765
1766         spin_lock(&svc->srv_lock);
1767         while (!list_empty(&svc->srv_threads)) {
1768                 thread = list_entry(svc->srv_threads.next,
1769                                     struct ptlrpc_thread, t_link);
1770
1771                 spin_unlock(&svc->srv_lock);
1772                 ptlrpc_stop_thread(svc, thread);
1773                 spin_lock(&svc->srv_lock);
1774         }
1775
1776         spin_unlock(&svc->srv_lock);
1777 }
1778
1779 int ptlrpc_start_threads(struct obd_device *dev, struct ptlrpc_service *svc)
1780 {
1781         int i, rc = 0;
1782         ENTRY;
1783
1784         /* We require 2 threads min - see note in
1785          * ptlrpc_server_handle_request() */
1786
1787         LASSERT(svc->srv_threads_min >= 2);
1788         for (i = 0; i < svc->srv_threads_min; i++) {
1789                 rc = ptlrpc_start_thread(dev, svc);
1790                 /* We have enough threads, don't start more.  b=15759 */
1791                 if (rc == -EMFILE)
1792                         break;
1793                 if (rc) {
1794                         CERROR("cannot start %s thread #%d: rc %d\n",
1795                                svc->srv_thread_name, i, rc);
1796                         ptlrpc_stop_all_threads(svc);
1797                 }
1798         }
1799         RETURN(rc);
1800 }
1801
1802 int ptlrpc_start_thread(struct obd_device *dev, struct ptlrpc_service *svc)
1803 {
1804         struct l_wait_info lwi = { 0 };
1805         struct ptlrpc_svc_data d;
1806         struct ptlrpc_thread *thread;
1807         char name[32];
1808         int id, rc;
1809         ENTRY;
1810
1811         CDEBUG(D_RPCTRACE, "%s started %d min %d max %d running %d\n",
1812                svc->srv_name, svc->srv_threads_started, svc->srv_threads_min,
1813                svc->srv_threads_max, svc->srv_threads_running);
1814         if (unlikely(svc->srv_threads_started >= svc->srv_threads_max) ||
1815             (OBD_FAIL_CHECK(OBD_FAIL_TGT_TOOMANY_THREADS) &&
1816              svc->srv_threads_started == svc->srv_threads_min - 1))
1817                 RETURN(-EMFILE);
1818
1819         OBD_ALLOC(thread, sizeof(*thread));
1820         if (thread == NULL)
1821                 RETURN(-ENOMEM);
1822         cfs_waitq_init(&thread->t_ctl_waitq);
1823
1824         spin_lock(&svc->srv_lock);
1825         if (svc->srv_threads_started >= svc->srv_threads_max) {
1826                 spin_unlock(&svc->srv_lock);
1827                 OBD_FREE(thread, sizeof(*thread));
1828                 RETURN(-EMFILE);
1829         }
1830         list_add(&thread->t_link, &svc->srv_threads);
1831         id = svc->srv_threads_started++;
1832         spin_unlock(&svc->srv_lock);
1833
1834         thread->t_svc = svc;
1835         thread->t_id = id;
1836         sprintf(name, "%s_%02d", svc->srv_thread_name, id);
1837         d.dev = dev;
1838         d.svc = svc;
1839         d.name = name;
1840         d.thread = thread;
1841
1842         CDEBUG(D_RPCTRACE, "starting thread '%s'\n", name);
1843
1844         /* CLONE_VM and CLONE_FILES just avoid a needless copy, because we
1845          * just drop the VM and FILES in cfs_daemonize_ctxt() right away.
1846          */
1847         rc = cfs_kernel_thread(ptlrpc_main, &d, CLONE_VM | CLONE_FILES);
1848         if (rc < 0) {
1849                 CERROR("cannot start thread '%s': rc %d\n", name, rc);
1850
1851                 spin_lock(&svc->srv_lock);
1852                 list_del(&thread->t_link);
1853                 --svc->srv_threads_started;
1854                 spin_unlock(&svc->srv_lock);
1855
1856                 OBD_FREE(thread, sizeof(*thread));
1857                 RETURN(rc);
1858         }
1859         l_wait_event(thread->t_ctl_waitq,
1860                      thread->t_flags & (SVC_RUNNING | SVC_STOPPED), &lwi);
1861
1862         rc = (thread->t_flags & SVC_STOPPED) ? thread->t_id : 0;
1863         RETURN(rc);
1864 }
1865 #endif
1866
1867 int ptlrpc_unregister_service(struct ptlrpc_service *service)
1868 {
1869         int                   rc;
1870         struct l_wait_info    lwi;
1871         struct list_head     *tmp;
1872         struct ptlrpc_reply_state *rs, *t;
1873         struct ptlrpc_at_array *array = &service->srv_at_array;
1874
1875         cfs_timer_disarm(&service->srv_at_timer);
1876
1877         ptlrpc_stop_all_threads(service);
1878         LASSERT(list_empty(&service->srv_threads));
1879
1880         spin_lock (&ptlrpc_all_services_lock);
1881         list_del_init (&service->srv_list);
1882         spin_unlock (&ptlrpc_all_services_lock);
1883
1884         ptlrpc_lprocfs_unregister_service(service);
1885
1886         /* All history will be culled when the next request buffer is
1887          * freed */
1888         service->srv_max_history_rqbds = 0;
1889
1890         CDEBUG(D_NET, "%s: tearing down\n", service->srv_name);
1891
1892         rc = LNetClearLazyPortal(service->srv_req_portal);
1893         LASSERT (rc == 0);
1894
1895         /* Unlink all the request buffers.  This forces a 'final' event with
1896          * its 'unlink' flag set for each posted rqbd */
1897         list_for_each(tmp, &service->srv_active_rqbds) {
1898                 struct ptlrpc_request_buffer_desc *rqbd =
1899                         list_entry(tmp, struct ptlrpc_request_buffer_desc,
1900                                    rqbd_list);
1901
1902                 rc = LNetMDUnlink(rqbd->rqbd_md_h);
1903                 LASSERT (rc == 0 || rc == -ENOENT);
1904         }
1905
1906         /* Wait for the network to release any buffers it's currently
1907          * filling */
1908         for (;;) {
1909                 spin_lock(&service->srv_lock);
1910                 rc = service->srv_nrqbd_receiving;
1911                 spin_unlock(&service->srv_lock);
1912
1913                 if (rc == 0)
1914                         break;
1915
1916                 /* Network access will complete in finite time but the HUGE
1917                  * timeout lets us CWARN for visibility of sluggish NALs */
1918                 lwi = LWI_TIMEOUT_INTERVAL(cfs_time_seconds(LONG_UNLINK),
1919                                            cfs_time_seconds(1), NULL, NULL);
1920                 rc = l_wait_event(service->srv_waitq,
1921                                   service->srv_nrqbd_receiving == 0,
1922                                   &lwi);
1923                 if (rc == -ETIMEDOUT)
1924                         CWARN("Service %s waiting for request buffers\n",
1925                               service->srv_name);
1926         }
1927
1928         /* schedule all outstanding replies to terminate them */
1929         spin_lock(&service->srv_lock);
1930         while (!list_empty(&service->srv_active_replies)) {
1931                 struct ptlrpc_reply_state *rs =
1932                         list_entry(service->srv_active_replies.next,
1933                                    struct ptlrpc_reply_state, rs_list);
1934                 ptlrpc_schedule_difficult_reply(rs);
1935         }
1936         spin_unlock(&service->srv_lock);
1937
1938         /* purge the request queue.  NB No new replies (rqbds all unlinked)
1939          * and no service threads, so I'm the only thread noodling the
1940          * request queue now */
1941         while (!list_empty(&service->srv_req_in_queue)) {
1942                 struct ptlrpc_request *req =
1943                         list_entry(service->srv_req_in_queue.next,
1944                                    struct ptlrpc_request,
1945                                    rq_list);
1946
1947                 list_del(&req->rq_list);
1948                 service->srv_n_queued_reqs--;
1949                 service->srv_n_active_reqs++;
1950                 ptlrpc_server_finish_request(req);
1951         }
1952         while (ptlrpc_server_request_pending(service, 1)) {
1953                 struct ptlrpc_request *req;
1954
1955                 req = ptlrpc_server_request_get(service, 1);
1956                 list_del(&req->rq_list);
1957                 service->srv_n_queued_reqs--;
1958                 service->srv_n_active_reqs++;
1959                 ptlrpc_hpreq_fini(req);
1960                 ptlrpc_server_finish_request(req);
1961         }
1962         LASSERT(service->srv_n_queued_reqs == 0);
1963         LASSERT(service->srv_n_active_reqs == 0);
1964         LASSERT(service->srv_n_history_rqbds == 0);
1965         LASSERT(list_empty(&service->srv_active_rqbds));
1966
1967         /* Now free all the request buffers since nothing references them
1968          * any more... */
1969         while (!list_empty(&service->srv_idle_rqbds)) {
1970                 struct ptlrpc_request_buffer_desc *rqbd =
1971                         list_entry(service->srv_idle_rqbds.next,
1972                                    struct ptlrpc_request_buffer_desc,
1973                                    rqbd_list);
1974
1975                 ptlrpc_free_rqbd(rqbd);
1976         }
1977
1978         /* wait for all outstanding replies to complete (they were
1979          * scheduled having been flagged to abort above) */
1980         while (atomic_read(&service->srv_outstanding_replies) != 0) {
1981                 struct l_wait_info lwi = LWI_TIMEOUT(cfs_time_seconds(10), NULL, NULL);
1982
1983                 rc = l_wait_event(service->srv_waitq,
1984                                   !list_empty(&service->srv_reply_queue), &lwi);
1985                 LASSERT(rc == 0 || rc == -ETIMEDOUT);
1986
1987                 if (rc == 0) {
1988                         ptlrpc_server_handle_reply(service);
1989                         continue;
1990                 }
1991                 CWARN("Unexpectedly long timeout %p\n", service);
1992         }
1993
1994         list_for_each_entry_safe(rs, t, &service->srv_free_rs_list, rs_list) {
1995                 list_del(&rs->rs_list);
1996                 OBD_FREE(rs, service->srv_max_reply_size);
1997         }
1998
1999         /* In case somebody rearmed this in the meantime */
2000         cfs_timer_disarm(&service->srv_at_timer);
2001
2002         if (array->paa_reqs_array != NULL) {
2003                 OBD_FREE(array->paa_reqs_array,
2004                          sizeof(struct list_head) * array->paa_size);
2005                 array->paa_reqs_array = NULL;
2006         }
2007
2008         if (array->paa_reqs_count != NULL) {
2009                 OBD_FREE(array->paa_reqs_count,
2010                          sizeof(__u32) * array->paa_size);
2011                 array->paa_reqs_count= NULL;
2012         }
2013
2014         OBD_FREE(service, sizeof(*service));
2015         return 0;
2016 }
2017
2018 /* Returns 0 if the service is healthy.
2019  *
2020  * Right now, it just checks to make sure that requests aren't languishing
2021  * in the queue.  We'll use this health check to govern whether a node needs
2022  * to be shot, so it's intentionally non-aggressive. */
2023 int ptlrpc_service_health_check(struct ptlrpc_service *svc)
2024 {
2025         struct ptlrpc_request *request;
2026         struct timeval         right_now;
2027         long                   timediff;
2028
2029         if (svc == NULL)
2030                 return 0;
2031
2032         do_gettimeofday(&right_now);
2033
2034         spin_lock(&svc->srv_lock);
2035         if (!ptlrpc_server_request_pending(svc, 1)) {
2036                 spin_unlock(&svc->srv_lock);
2037                 return 0;
2038         }
2039
2040         /* How long has the next entry been waiting? */
2041         if (list_empty(&svc->srv_request_queue))
2042                 request = list_entry(svc->srv_request_hpq.next,
2043                                      struct ptlrpc_request, rq_list);
2044         else
2045                 request = list_entry(svc->srv_request_queue.next,
2046                                      struct ptlrpc_request, rq_list);
2047         timediff = cfs_timeval_sub(&right_now, &request->rq_arrival_time, NULL);
2048         spin_unlock(&svc->srv_lock);
2049
2050         if ((timediff / ONE_MILLION) > (AT_OFF ? obd_timeout * 3/2 :
2051                                         at_max)) {
2052                 CERROR("%s: unhealthy - request has been waiting %lds\n",
2053                        svc->srv_name, timediff / ONE_MILLION);
2054                 return (-1);
2055         }
2056
2057         return 0;
2058 }