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