Whamcloud - gitweb
Branch b1_6
[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         LASSERT(list_empty(&req->rq_timed_list));
382         if (req != &rqbd->rqbd_req) {
383                 /* NB request buffers use an embedded
384                  * req if the incoming req unlinked the
385                  * MD; this isn't one of them! */
386                 OBD_FREE(req, sizeof(*req));
387         } else {
388                 struct ptlrpc_service *svc = rqbd->rqbd_service;
389                 /* schedule request buffer for re-use.
390                  * NB I can only do this after I've disposed of their
391                  * reqs; particularly the embedded req */
392                 spin_lock(&svc->srv_lock);
393                 list_add_tail(&rqbd->rqbd_list, &svc->srv_idle_rqbds);
394                 spin_unlock(&svc->srv_lock);
395         }
396 }
397
398 static void __ptlrpc_server_free_request(struct ptlrpc_request *req)
399 {
400         list_del(&req->rq_list);
401         ptlrpc_req_drop_rs(req);
402         ptlrpc_server_req_decref(req);
403 }
404
405 static void ptlrpc_server_free_request(struct ptlrpc_request *req)
406 {
407         struct ptlrpc_request_buffer_desc *rqbd = req->rq_rqbd;
408         struct ptlrpc_service             *svc = rqbd->rqbd_service;
409         int                                refcount;
410         struct list_head                  *tmp;
411         struct list_head                  *nxt;
412
413         if (req->rq_phase != RQ_PHASE_NEW) /* incorrect message magic */
414                 DEBUG_REQ(D_INFO, req, "free req");
415         spin_lock(&svc->srv_at_lock);
416         req->rq_sent_final = 1;
417         list_del_init(&req->rq_timed_list);
418         spin_unlock(&svc->srv_at_lock);
419
420         spin_lock(&svc->srv_lock);
421
422         svc->srv_n_active_reqs--;
423         list_add(&req->rq_list, &rqbd->rqbd_reqs);
424
425         refcount = --(rqbd->rqbd_refcount);
426         if (refcount == 0) {
427                 /* request buffer is now idle: add to history */
428                 list_del(&rqbd->rqbd_list);
429                 list_add_tail(&rqbd->rqbd_list, &svc->srv_history_rqbds);
430                 svc->srv_n_history_rqbds++;
431
432                 /* cull some history?
433                  * I expect only about 1 or 2 rqbds need to be recycled here */
434                 while (svc->srv_n_history_rqbds > svc->srv_max_history_rqbds) {
435                         rqbd = list_entry(svc->srv_history_rqbds.next,
436                                           struct ptlrpc_request_buffer_desc,
437                                           rqbd_list);
438
439                         list_del(&rqbd->rqbd_list);
440                         svc->srv_n_history_rqbds--;
441
442                         /* remove rqbd's reqs from svc's req history while
443                          * I've got the service lock */
444                         list_for_each(tmp, &rqbd->rqbd_reqs) {
445                                 req = list_entry(tmp, struct ptlrpc_request,
446                                                  rq_list);
447                                 /* Track the highest culled req seq */
448                                 if (req->rq_history_seq >
449                                     svc->srv_request_max_cull_seq)
450                                         svc->srv_request_max_cull_seq =
451                                                 req->rq_history_seq;
452                                 list_del(&req->rq_history_list);
453                         }
454
455                         spin_unlock(&svc->srv_lock);
456
457                         list_for_each_safe(tmp, nxt, &rqbd->rqbd_reqs) {
458                                 req = list_entry(rqbd->rqbd_reqs.next,
459                                                  struct ptlrpc_request,
460                                                  rq_list);
461                                 __ptlrpc_server_free_request(req);
462                         }
463
464                         spin_lock(&svc->srv_lock);
465                 }
466         } else if (req->rq_reply_state && req->rq_reply_state->rs_prealloc) {
467                  /* If we are low on memory, we are not interested in
468                     history */
469                 list_del(&req->rq_history_list);
470                 __ptlrpc_server_free_request(req);
471         }
472
473         spin_unlock(&svc->srv_lock);
474 }
475
476 /* This function makes sure dead exports are evicted in a timely manner.
477    This function is only called when some export receives a message (i.e.,
478    the network is up.) */
479 static void ptlrpc_update_export_timer(struct obd_export *exp, long extra_delay)
480 {
481         struct obd_export *oldest_exp;
482         time_t oldest_time;
483
484         ENTRY;
485
486         LASSERT(exp);
487
488         /* Compensate for slow machines, etc, by faking our request time
489            into the future.  Although this can break the strict time-ordering
490            of the list, we can be really lazy here - we don't have to evict
491            at the exact right moment.  Eventually, all silent exports
492            will make it to the top of the list. */
493         exp->exp_last_request_time = max(exp->exp_last_request_time,
494                                          cfs_time_current_sec() + extra_delay);
495
496         CDEBUG(D_INFO, "updating export %s at %ld\n",
497                exp->exp_client_uuid.uuid,
498                exp->exp_last_request_time);
499
500         /* exports may get disconnected from the chain even though the
501            export has references, so we must keep the spin lock while
502            manipulating the lists */
503         spin_lock(&exp->exp_obd->obd_dev_lock);
504
505         if (list_empty(&exp->exp_obd_chain_timed)) {
506                 /* this one is not timed */
507                 spin_unlock(&exp->exp_obd->obd_dev_lock);
508                 EXIT;
509                 return;
510         }
511
512         list_move_tail(&exp->exp_obd_chain_timed,
513                        &exp->exp_obd->obd_exports_timed);
514
515         oldest_exp = list_entry(exp->exp_obd->obd_exports_timed.next,
516                                 struct obd_export, exp_obd_chain_timed);
517         oldest_time = oldest_exp->exp_last_request_time;
518         spin_unlock(&exp->exp_obd->obd_dev_lock);
519
520         if (exp->exp_obd->obd_recovering) {
521                 /* be nice to everyone during recovery */
522                 EXIT;
523                 return;
524         }
525
526         /* Note - racing to start/reset the obd_eviction timer is safe */
527         if (exp->exp_obd->obd_eviction_timer == 0) {
528                 /* Check if the oldest entry is expired. */
529                 if (cfs_time_current_sec() > (oldest_time + PING_EVICT_TIMEOUT +
530                                               extra_delay)) {
531                         /* We need a second timer, in case the net was down and
532                          * it just came back. Since the pinger may skip every
533                          * other PING_INTERVAL (see note in ptlrpc_pinger_main),
534                          * we better wait for 3. */
535                         exp->exp_obd->obd_eviction_timer =
536                                 cfs_time_current_sec() + 3 * PING_INTERVAL;
537                         CDEBUG(D_HA, "%s: Think about evicting %s from %ld\n",
538                                exp->exp_obd->obd_name, obd_export_nid2str(exp),
539                                oldest_time);
540                 }
541         } else {
542                 if (cfs_time_current_sec() > 
543                     (exp->exp_obd->obd_eviction_timer + extra_delay)) {
544                         /* The evictor won't evict anyone who we've heard from
545                          * recently, so we don't have to check before we start
546                          * it. */
547                         if (!ping_evictor_wake(exp))
548                                 exp->exp_obd->obd_eviction_timer = 0;
549                 }
550         }
551
552         EXIT;
553 }
554
555 static int ptlrpc_check_req(struct ptlrpc_request *req)
556 {
557         if (lustre_msg_get_conn_cnt(req->rq_reqmsg) < 
558             req->rq_export->exp_conn_cnt) {
559                 DEBUG_REQ(D_ERROR, req,
560                           "DROPPING req from old connection %d < %d",
561                           lustre_msg_get_conn_cnt(req->rq_reqmsg),
562                           req->rq_export->exp_conn_cnt);
563                 return -EEXIST;
564         }
565         if (req->rq_export->exp_obd && req->rq_export->exp_obd->obd_fail) {
566              /* Failing over, don't handle any more reqs, send
567                 error response instead. */
568                 CDEBUG(D_RPCTRACE, "Dropping req %p for failed obd %s\n",
569                        req, req->rq_export->exp_obd->obd_name);
570                 req->rq_status = -ENODEV;
571                 ptlrpc_error(req);
572                 return -ENODEV;
573         }
574         return 0;
575 }
576
577 static void ptlrpc_at_set_timer(struct ptlrpc_service *svc)
578 {
579         struct ptlrpc_request *rq;
580         time_t next;
581
582         spin_lock(&svc->srv_at_lock);
583         if (list_empty(&svc->srv_at_list)) {
584                 cfs_timer_disarm(&svc->srv_at_timer);
585                 spin_unlock(&svc->srv_at_lock);
586                 return;
587         }
588
589         /* Set timer for closest deadline */
590         rq = list_entry(svc->srv_at_list.next, struct ptlrpc_request, 
591                         rq_timed_list);
592         next = rq->rq_deadline - cfs_time_current_sec() - at_early_margin;
593         if (next <= 0) 
594                 ptlrpc_at_timer((unsigned long)svc);
595         else
596                 cfs_timer_arm(&svc->srv_at_timer, cfs_time_shift(next));
597         spin_unlock(&svc->srv_at_lock);
598         CDEBUG(D_INFO, "armed %s at %+lds\n", svc->srv_name, next);
599 }
600
601 /* Add rpc to early reply check list */
602 static int ptlrpc_at_add_timed(struct ptlrpc_request *req)
603 {
604         struct ptlrpc_service *svc = req->rq_rqbd->rqbd_service;
605         struct ptlrpc_request *rq;
606         int found = 0;
607
608         if (AT_OFF) 
609                 return(0);
610
611         if ((lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT) == 0)
612                 return(-ENOSYS);
613         
614         DEBUG_REQ(D_ADAPTTO, req, "add timed %lds", 
615                   req->rq_deadline - cfs_time_current_sec());
616         
617         spin_lock(&svc->srv_at_lock);
618
619         if (unlikely(req->rq_sent_final)) {
620                 spin_unlock(&svc->srv_at_lock);
621                 return 0;
622         }
623
624         LASSERT(list_empty(&req->rq_timed_list));
625         /* Add to sorted list.  Presumably latest rpcs will have the latest
626            deadlines, so search backward. */
627         list_for_each_entry_reverse(rq, &svc->srv_at_list, rq_timed_list) {
628                 if (req->rq_deadline > rq->rq_deadline) {
629                         list_add(&req->rq_timed_list, &rq->rq_timed_list);
630                         found++;
631                         break;
632                 }
633         }
634         if (!found)
635                 /* Add to front if shortest deadline or list empty */
636                 list_add(&req->rq_timed_list, &svc->srv_at_list);
637
638         /* Check if we're the head of the list */
639         found = (svc->srv_at_list.next == &req->rq_timed_list);
640
641         spin_unlock(&svc->srv_at_lock);
642
643         if (found)
644                 ptlrpc_at_set_timer(svc);
645
646         return 0;
647 }            
648
649 static int ptlrpc_at_send_early_reply(struct ptlrpc_request *req, 
650                                       int extra_time)
651 {
652         struct ptlrpc_service *svc = req->rq_rqbd->rqbd_service;
653         struct ptlrpc_request *reqcopy;
654         struct lustre_msg *reqmsg;
655         long olddl = req->rq_deadline - cfs_time_current_sec();
656         time_t newdl;
657         int rc;
658         ENTRY;
659                             
660         /* deadline is when the client expects us to reply, margin is the 
661            difference between clients' and servers' expectations */
662         DEBUG_REQ(D_ADAPTTO, req, 
663                   "%ssending early reply (deadline %+lds, margin %+lds) for "
664                   "%d+%d", AT_OFF ? "AT off - not " : "",
665                   olddl, olddl - at_get(&svc->srv_at_estimate),
666                   at_get(&svc->srv_at_estimate), extra_time);
667
668         if (AT_OFF) 
669                 RETURN(0);
670         
671         if (olddl < 0) {
672                 CDEBUG(D_WARNING, "x"LPU64": Already past deadline (%+lds), not"
673                        " sending early reply. Increase at_early_margin (%d)?\n",
674                        req->rq_xid, olddl, at_early_margin);
675                 /* Return an error so we're not re-added to the timed list. */
676                 RETURN(-ETIMEDOUT);
677         }
678
679         if ((lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT) == 0){
680                 CDEBUG(D_INFO, "Wanted to ask client for more time, but no AT "
681                       "support\n");
682                 RETURN(-ENOSYS);
683         }
684
685         if (extra_time) {
686                 /* Fake our processing time into the future to ask the
687                    clients for some extra amount of time */
688                 extra_time += cfs_time_current_sec() -
689                         req->rq_arrival_time.tv_sec;
690                 at_add(&svc->srv_at_estimate, extra_time);
691         }
692
693         newdl = req->rq_arrival_time.tv_sec + at_get(&svc->srv_at_estimate);
694         if (req->rq_deadline >= newdl) {
695                 /* We're not adding any time, no need to send an early reply
696                    (e.g. maybe at adaptive_max) */
697                 CDEBUG(D_ADAPTTO, "x"LPU64": Couldn't add any time (%ld/%ld), "
698                        "not sending early reply\n", req->rq_xid, olddl,
699                        newdl - cfs_time_current_sec());
700                 RETURN(-ETIMEDOUT);
701         }
702
703         OBD_ALLOC(reqcopy, sizeof *reqcopy);
704         if (reqcopy == NULL)
705                 RETURN(-ENOMEM);
706         OBD_ALLOC(reqmsg, req->rq_reqlen);
707         if (!reqmsg) {
708                 OBD_FREE(reqcopy, sizeof *reqcopy);
709                 RETURN(-ENOMEM);
710         }
711         
712         *reqcopy = *req;
713         reqcopy->rq_reply_state = NULL;
714         reqcopy->rq_rep_swab_mask = 0;
715         /* We only need the reqmsg for the magic */
716         reqcopy->rq_reqmsg = reqmsg;
717         memcpy(reqmsg, req->rq_reqmsg, req->rq_reqlen);
718
719         if (req->rq_sent_final) {
720                 CDEBUG(D_ADAPTTO, "x"LPU64": normal reply already sent out, "
721                        "abort sending early reply\n", req->rq_xid);
722                 GOTO(out, rc = 0);
723         }
724
725         /* Connection ref */
726         reqcopy->rq_export = class_conn2export(
727                                      lustre_msg_get_handle(reqcopy->rq_reqmsg));
728         if (reqcopy->rq_export == NULL)
729                 GOTO(out, rc = -ENODEV);
730
731         /* RPC ref */
732         class_export_rpc_get(reqcopy->rq_export);
733         if (reqcopy->rq_export->exp_obd && 
734             reqcopy->rq_export->exp_obd->obd_fail)
735                 GOTO(out_put, rc = -ENODEV);
736
737         rc = lustre_pack_reply_flags(reqcopy, 1, NULL, NULL, LPRFL_EARLY_REPLY);
738         if (rc) 
739                 GOTO(out_put, rc);
740
741         rc = ptlrpc_send_reply(reqcopy, PTLRPC_REPLY_EARLY);
742
743         if (!rc) {
744                 /* Adjust our own deadline to what we told the client */
745                 req->rq_deadline = newdl;
746                 req->rq_early_count++; /* number sent, server side */
747         } else {
748                 DEBUG_REQ(D_ERROR, req, "Early reply send failed %d", rc);
749         }
750
751         /* Free the (early) reply state from lustre_pack_reply. 
752            (ptlrpc_send_reply takes it's own rs ref, so this is safe here) */
753         ptlrpc_req_drop_rs(reqcopy);
754
755 out_put:
756         class_export_rpc_put(reqcopy->rq_export);
757         class_export_put(reqcopy->rq_export);
758 out:
759         OBD_FREE(reqmsg, req->rq_reqlen);
760         OBD_FREE(reqcopy, sizeof *reqcopy);
761         RETURN(rc);
762 }
763
764 /* Send early replies to everybody expiring within at_early_margin
765    asking for at_extra time */
766 static int ptlrpc_at_check_timed(struct ptlrpc_service *svc)
767 {
768         struct ptlrpc_request *rq, *n;
769         struct list_head work_list;
770         time_t now = cfs_time_current_sec();
771         int first, counter = 0;
772         ENTRY;
773
774         if (AT_OFF) 
775                 RETURN(0);
776
777         spin_lock(&svc->srv_at_lock);
778         if (svc->srv_at_check == 0) {
779                 spin_unlock(&svc->srv_at_lock);
780                 RETURN(0);
781         }
782         svc->srv_at_check = 0;
783         
784         if (list_empty(&svc->srv_at_list)) {
785                 spin_unlock(&svc->srv_at_lock);
786                 RETURN(0);      
787         }
788
789         /* The timer went off, but maybe the nearest rpc already completed. */
790         rq = list_entry(svc->srv_at_list.next, struct ptlrpc_request,
791                         rq_timed_list);
792         first = (int)(rq->rq_deadline - now);
793         if (first > at_early_margin) {
794                 /* We've still got plenty of time.  Reset the timer. */
795                 spin_unlock(&svc->srv_at_lock);
796                 ptlrpc_at_set_timer(svc);
797                 RETURN(0);      
798         }
799
800         /* We're close to a timeout, and we don't know how much longer the 
801            server will take. Send early replies to everyone expiring soon. */
802         CFS_INIT_LIST_HEAD(&work_list);
803         list_for_each_entry_safe(rq, n, &svc->srv_at_list, rq_timed_list) {
804                 if (rq->rq_deadline <= now + at_early_margin) {
805                         list_move(&rq->rq_timed_list, &work_list);
806                         counter++;
807                 } else {
808                         break;
809                 }
810         }
811
812         spin_unlock(&svc->srv_at_lock);
813
814         /* we have a new earliest deadline, restart the timer */
815         ptlrpc_at_set_timer(svc);
816
817         CDEBUG(D_ADAPTTO, "timeout in %+ds, asking for %d secs on %d early "
818                "replies\n", first, at_extra, counter);
819         if (first < 0)
820                 /* We're already past request deadlines before we even get a 
821                    chance to send early replies */
822                 LCONSOLE_WARN("%s: This server is not able to keep up with "
823                               "request traffic (cpu-bound).\n", svc->srv_name);
824
825         /* ptlrpc_server_free_request may delete an entry out of the work
826            list */
827         spin_lock(&svc->srv_at_lock);
828         while (!list_empty(&work_list)) {
829                 rq = list_entry(work_list.next, struct ptlrpc_request,
830                                 rq_timed_list);
831                 list_del_init(&rq->rq_timed_list);
832                 /* if the entry is still in the worklist, it hasn't been
833                    deleted, and is safe to take a ref to keep the req around */
834                 atomic_inc(&rq->rq_refcount);
835                 spin_unlock(&svc->srv_at_lock);
836
837                 if (ptlrpc_at_send_early_reply(rq, at_extra) == 0)
838                         ptlrpc_at_add_timed(rq);
839
840                 ptlrpc_server_req_decref(rq);
841                 spin_lock(&svc->srv_at_lock);
842         }
843         spin_unlock(&svc->srv_at_lock);
844
845         RETURN(0);      
846 }
847
848 /* Handle freshly incoming reqs, add to timed early reply list,
849    pass on to regular request queue */
850 static int
851 ptlrpc_server_handle_req_in(struct ptlrpc_service *svc)
852 {
853         struct ptlrpc_request *req;
854         __u32                  deadline;
855         int                    rc;
856         ENTRY;
857
858         LASSERT(svc);
859
860         spin_lock(&svc->srv_lock);
861         if (list_empty(&svc->srv_req_in_queue)) {
862                 spin_unlock(&svc->srv_lock);
863                 RETURN(0);
864         }
865
866         req = list_entry(svc->srv_req_in_queue.next,
867                          struct ptlrpc_request, rq_list);
868         list_del_init (&req->rq_list);
869         /* Consider this still a "queued" request as far as stats are
870            concerned */
871         spin_unlock(&svc->srv_lock);
872         
873         /* Clear request swab mask; this is a new request */
874         req->rq_req_swab_mask = 0;
875
876         rc = lustre_unpack_msg(req->rq_reqmsg, req->rq_reqlen);
877         if (rc != 0) {
878                 CERROR ("error unpacking request: ptl %d from %s"
879                         " xid "LPU64"\n", svc->srv_req_portal,
880                         libcfs_id2str(req->rq_peer), req->rq_xid);
881                 goto err_req;
882         }
883
884         rc = lustre_unpack_req_ptlrpc_body(req, MSG_PTLRPC_BODY_OFF);
885         if (rc) {
886                 CERROR ("error unpacking ptlrpc body: ptl %d from %s"
887                         " xid "LPU64"\n", svc->srv_req_portal,
888                         libcfs_id2str(req->rq_peer), req->rq_xid);
889                 goto err_req;
890         }
891
892         rc = -EINVAL;
893         if (lustre_msg_get_type(req->rq_reqmsg) != PTL_RPC_MSG_REQUEST) {
894                 CERROR("wrong packet type received (type=%u) from %s\n",
895                        lustre_msg_get_type(req->rq_reqmsg),
896                        libcfs_id2str(req->rq_peer));
897                 goto err_req;
898         }
899
900         CDEBUG(D_NET, "got req "LPD64"\n", req->rq_xid);
901         
902         req->rq_export = class_conn2export(
903                 lustre_msg_get_handle(req->rq_reqmsg));
904         if (req->rq_export) {
905                 rc = ptlrpc_check_req(req);
906                 class_export_put(req->rq_export);
907                 req->rq_export = NULL;
908                 if (rc) 
909                         goto err_req;
910         }
911
912         /* req_in handling should/must be fast */
913         if (cfs_time_current_sec() - req->rq_arrival_time.tv_sec > 5) 
914                 DEBUG_REQ(D_WARNING, req, "Slow req_in handling %lus",
915                           cfs_time_current_sec() - req->rq_arrival_time.tv_sec);
916
917         /* Set rpc server deadline and add it to the timed list */
918         deadline = (lustre_msghdr_get_flags(req->rq_reqmsg) &
919                     MSGHDR_AT_SUPPORT) ? 
920                    /* The max time the client expects us to take */
921                    lustre_msg_get_timeout(req->rq_reqmsg) : obd_timeout;
922         LASSERT(deadline > 0);
923         req->rq_deadline = req->rq_arrival_time.tv_sec + deadline;
924         
925         ptlrpc_at_add_timed(req);
926
927         /* Move it over to the request processing queue */
928         spin_lock(&svc->srv_lock);
929         list_add_tail(&req->rq_list, &svc->srv_request_queue);
930         cfs_waitq_signal(&svc->srv_waitq);
931         spin_unlock(&svc->srv_lock);
932         RETURN(1);
933
934 err_req:
935         spin_lock(&svc->srv_lock);
936         svc->srv_n_queued_reqs--;
937         svc->srv_n_active_reqs++;
938         spin_unlock(&svc->srv_lock);
939         ptlrpc_server_free_request(req);
940
941         RETURN(1);
942 }
943
944 static int
945 ptlrpc_server_handle_request(struct ptlrpc_service *svc,
946                              struct ptlrpc_thread *thread)
947 {
948         struct obd_export     *export = NULL;
949         struct ptlrpc_request *request;
950         struct timeval         work_start;
951         struct timeval         work_end;
952         long                   timediff;
953         int                    rc;
954         ENTRY;
955
956         LASSERT(svc);
957
958         spin_lock(&svc->srv_lock);
959         if (list_empty (&svc->srv_request_queue) ||
960             (
961 #ifndef __KERNEL__
962              /* !@%$# liblustre only has 1 thread */
963              svc->srv_n_difficult_replies != 0 &&
964 #endif
965              svc->srv_n_active_reqs >= (svc->srv_threads_running - 1))) {
966                 /* Don't handle regular requests in the last thread, in order               * remain free to handle any 'difficult' replies (that might
967                  * to handle difficult replies (which might block other threads)
968                  * as well as handle any incoming reqs, early replies, etc. 
969                  * That means we always need at least 2 service threads. */
970                 spin_unlock(&svc->srv_lock);
971                 RETURN(0);
972         }
973
974         request = list_entry (svc->srv_request_queue.next,
975                               struct ptlrpc_request, rq_list);
976         list_del_init (&request->rq_list);
977         svc->srv_n_queued_reqs--;
978         svc->srv_n_active_reqs++;
979
980         spin_unlock(&svc->srv_lock);
981
982         do_gettimeofday(&work_start);
983         timediff = cfs_timeval_sub(&work_start, &request->rq_arrival_time,NULL);
984         if (svc->srv_stats != NULL) {
985                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQWAIT_CNTR,
986                                     timediff);
987                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQQDEPTH_CNTR,
988                                     svc->srv_n_queued_reqs);
989                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQACTIVE_CNTR,
990                                     svc->srv_n_active_reqs);
991                 lprocfs_counter_add(svc->srv_stats, PTLRPC_TIMEOUT,
992                                     at_get(&svc->srv_at_estimate));
993         }
994         
995         CDEBUG(D_NET, "got req "LPD64"\n", request->rq_xid);
996         
997         request->rq_svc_thread = thread;
998         request->rq_export = class_conn2export(
999                                      lustre_msg_get_handle(request->rq_reqmsg));
1000
1001         if (request->rq_export) {
1002                 if (ptlrpc_check_req(request))
1003                         goto put_conn;
1004                 ptlrpc_update_export_timer(request->rq_export, timediff >> 19);
1005                 export = class_export_rpc_get(request->rq_export);
1006         }
1007
1008         /* Discard requests queued for longer than the deadline.  
1009            The deadline is increased if we send an early reply. */
1010         if (cfs_time_current_sec() > request->rq_deadline) {
1011                 DEBUG_REQ(D_ERROR, request, "Dropping timed-out request from %s"
1012                           ": deadline %ld%+lds ago\n",
1013                           libcfs_id2str(request->rq_peer),
1014                           request->rq_deadline -
1015                           request->rq_arrival_time.tv_sec,
1016                           cfs_time_current_sec() - request->rq_deadline);
1017                 goto put_rpc_export;
1018         }
1019
1020         request->rq_phase = RQ_PHASE_INTERPRET;
1021
1022         CDEBUG(D_RPCTRACE, "Handling RPC pname:cluuid+ref:pid:xid:nid:opc "
1023                "%s:%s+%d:%d:x"LPU64":%s:%d\n", cfs_curproc_comm(),
1024                (request->rq_export ?
1025                 (char *)request->rq_export->exp_client_uuid.uuid : "0"),
1026                (request->rq_export ?
1027                 atomic_read(&request->rq_export->exp_refcount) : -99),
1028                lustre_msg_get_status(request->rq_reqmsg), request->rq_xid,
1029                libcfs_id2str(request->rq_peer),
1030                lustre_msg_get_opc(request->rq_reqmsg));
1031
1032         OBD_FAIL_TIMEOUT_MS(OBD_FAIL_PTLRPC_PAUSE_REQ, obd_fail_val);
1033
1034         rc = svc->srv_handler(request);
1035         
1036         request->rq_phase = RQ_PHASE_COMPLETE;
1037
1038         CDEBUG(D_RPCTRACE, "Handled RPC pname:cluuid+ref:pid:xid:nid:opc "
1039                "%s:%s+%d:%d:x"LPU64":%s:%d\n", cfs_curproc_comm(),
1040                (request->rq_export ?
1041                 (char *)request->rq_export->exp_client_uuid.uuid : "0"),
1042                (request->rq_export ?
1043                 atomic_read(&request->rq_export->exp_refcount) : -99),
1044                lustre_msg_get_status(request->rq_reqmsg), request->rq_xid,
1045                libcfs_id2str(request->rq_peer),
1046                lustre_msg_get_opc(request->rq_reqmsg));
1047
1048 put_rpc_export:
1049         if (export != NULL)
1050                 class_export_rpc_put(export);
1051
1052 put_conn:
1053         if (request->rq_export != NULL)
1054                 class_export_put(request->rq_export);
1055
1056         if (cfs_time_current_sec() > request->rq_deadline) {
1057                 DEBUG_REQ(D_WARNING, request, "Request x"LPU64" took longer "
1058                           "than estimated (%ld%+lds); client may timeout.",
1059                           request->rq_xid, request->rq_deadline -
1060                           request->rq_arrival_time.tv_sec,
1061                           cfs_time_current_sec() - request->rq_deadline);
1062         }
1063
1064         do_gettimeofday(&work_end);
1065         timediff = cfs_timeval_sub(&work_end, &work_start, NULL);
1066         CDEBUG(D_RPCTRACE, "request x"LPU64" opc %u from %s processed in "
1067                "%ldus (%ldus total) trans "LPU64" rc %d/%d\n",
1068                request->rq_xid, lustre_msg_get_opc(request->rq_reqmsg),
1069                libcfs_id2str(request->rq_peer), timediff,
1070                cfs_timeval_sub(&work_end, &request->rq_arrival_time, NULL),
1071                request->rq_repmsg ? lustre_msg_get_transno(request->rq_repmsg) :
1072                request->rq_transno, request->rq_status,
1073                request->rq_repmsg ? lustre_msg_get_status(request->rq_repmsg): 
1074                -999);
1075         if (svc->srv_stats != NULL) {
1076                 int opc = opcode_offset(lustre_msg_get_opc(request->rq_reqmsg));
1077                 if (opc > 0) {
1078                         LASSERT(opc < LUSTRE_MAX_OPCODES);
1079                         lprocfs_counter_add(svc->srv_stats,
1080                                             opc + PTLRPC_LAST_CNTR,
1081                                             timediff);
1082                 }
1083         }
1084         if (request->rq_early_count) {
1085                 DEBUG_REQ(D_ADAPTTO, request, 
1086                           "sent %d early replies before finishing in %lds",
1087                           request->rq_early_count,
1088                           work_end.tv_sec - request->rq_arrival_time.tv_sec);
1089         }
1090
1091         ptlrpc_server_free_request(request);
1092
1093         RETURN(1);
1094 }
1095
1096 static int
1097 ptlrpc_server_handle_reply (struct ptlrpc_service *svc)
1098 {
1099         struct ptlrpc_reply_state *rs;
1100         struct obd_export         *exp;
1101         struct obd_device         *obd;
1102         int                        nlocks;
1103         int                        been_handled;
1104         ENTRY;
1105
1106         spin_lock(&svc->srv_lock);
1107         if (list_empty (&svc->srv_reply_queue)) {
1108                 spin_unlock(&svc->srv_lock);
1109                 RETURN(0);
1110         }
1111
1112         rs = list_entry (svc->srv_reply_queue.next,
1113                          struct ptlrpc_reply_state, rs_list);
1114
1115         exp = rs->rs_export;
1116         obd = exp->exp_obd;
1117
1118         LASSERT (rs->rs_difficult);
1119         LASSERT (rs->rs_scheduled);
1120
1121         list_del_init (&rs->rs_list);
1122
1123         /* Disengage from notifiers carefully (lock order - irqrestore below!)*/
1124         spin_unlock(&svc->srv_lock);
1125
1126         spin_lock (&obd->obd_uncommitted_replies_lock);
1127         /* Noop if removed already */
1128         list_del_init (&rs->rs_obd_list);
1129         spin_unlock (&obd->obd_uncommitted_replies_lock);
1130
1131         spin_lock (&exp->exp_lock);
1132         /* Noop if removed already */
1133         list_del_init (&rs->rs_exp_list);
1134         spin_unlock (&exp->exp_lock);
1135
1136         spin_lock(&svc->srv_lock);
1137
1138         been_handled = rs->rs_handled;
1139         rs->rs_handled = 1;
1140
1141         nlocks = rs->rs_nlocks;                 /* atomic "steal", but */
1142         rs->rs_nlocks = 0;                      /* locks still on rs_locks! */
1143
1144         if (nlocks == 0 && !been_handled) {
1145                 /* If we see this, we should already have seen the warning
1146                  * in mds_steal_ack_locks()  */
1147                 CWARN("All locks stolen from rs %p x"LPD64".t"LPD64
1148                       " o%d NID %s\n",
1149                       rs,
1150                       rs->rs_xid, rs->rs_transno,
1151                       lustre_msg_get_opc(rs->rs_msg),
1152                       libcfs_nid2str(exp->exp_connection->c_peer.nid));
1153         }
1154
1155         if ((!been_handled && rs->rs_on_net) || nlocks > 0) {
1156                 spin_unlock(&svc->srv_lock);
1157
1158                 if (!been_handled && rs->rs_on_net) {
1159                         LNetMDUnlink(rs->rs_md_h);
1160                         /* Ignore return code; we're racing with
1161                          * completion... */
1162                 }
1163
1164                 while (nlocks-- > 0)
1165                         ldlm_lock_decref(&rs->rs_locks[nlocks],
1166                                          rs->rs_modes[nlocks]);
1167
1168                 spin_lock(&svc->srv_lock);
1169         }
1170
1171         rs->rs_scheduled = 0;
1172
1173         if (!rs->rs_on_net) {
1174                 /* Off the net */
1175                 svc->srv_n_difficult_replies--;
1176                 spin_unlock(&svc->srv_lock);
1177
1178                 class_export_put (exp);
1179                 rs->rs_export = NULL;
1180                 ptlrpc_rs_decref (rs);
1181                 atomic_dec (&svc->srv_outstanding_replies);
1182                 RETURN(1);
1183         }
1184
1185         /* still on the net; callback will schedule */
1186         spin_unlock(&svc->srv_lock);
1187         RETURN(1);
1188 }
1189
1190 #ifndef __KERNEL__
1191 /* FIXME make use of timeout later */
1192 int
1193 liblustre_check_services (void *arg)
1194 {
1195         int  did_something = 0;
1196         int  rc;
1197         struct list_head *tmp, *nxt;
1198         ENTRY;
1199
1200         /* I'm relying on being single threaded, not to have to lock
1201          * ptlrpc_all_services etc */
1202         list_for_each_safe (tmp, nxt, &ptlrpc_all_services) {
1203                 struct ptlrpc_service *svc =
1204                         list_entry (tmp, struct ptlrpc_service, srv_list);
1205
1206                 if (svc->srv_threads_running != 0)     /* I've recursed */
1207                         continue;
1208
1209                 /* service threads can block for bulk, so this limits us
1210                  * (arbitrarily) to recursing 1 stack frame per service.
1211                  * Note that the problem with recursion is that we have to
1212                  * unwind completely before our caller can resume. */
1213
1214                 svc->srv_threads_running++;
1215
1216                 do {
1217                         rc = ptlrpc_server_handle_req_in(svc);
1218                         rc |= ptlrpc_server_handle_reply(svc);
1219                         rc |= ptlrpc_at_check_timed(svc);
1220                         rc |= ptlrpc_server_handle_request(svc, NULL);
1221                         rc |= (ptlrpc_server_post_idle_rqbds(svc) > 0);
1222                         did_something |= rc;
1223                 } while (rc);
1224
1225                 svc->srv_threads_running--;
1226         }
1227
1228         RETURN(did_something);
1229 }
1230 #define ptlrpc_stop_all_threads(s) do {} while (0)
1231
1232 #else /* __KERNEL__ */
1233
1234 /* Don't use daemonize, it removes fs struct from new thread (bug 418) */
1235 void ptlrpc_daemonize(char *name)
1236 {
1237         struct fs_struct *fs = current->fs;
1238
1239         atomic_inc(&fs->count);
1240         cfs_daemonize(name);
1241         exit_fs(cfs_current());
1242         current->fs = fs;
1243         ll_set_fs_pwd(current->fs, init_task.fs->pwdmnt, init_task.fs->pwd);
1244 }
1245
1246 static void
1247 ptlrpc_check_rqbd_pool(struct ptlrpc_service *svc)
1248 {
1249         int avail = svc->srv_nrqbd_receiving;
1250         int low_water = test_req_buffer_pressure ? 0 :
1251                         svc->srv_nbuf_per_group/2;
1252
1253         /* NB I'm not locking; just looking. */
1254
1255         /* CAVEAT EMPTOR: We might be allocating buffers here because we've
1256          * allowed the request history to grow out of control.  We could put a
1257          * sanity check on that here and cull some history if we need the
1258          * space. */
1259
1260         if (avail <= low_water)
1261                 ptlrpc_grow_req_bufs(svc);
1262
1263         if (svc->srv_stats)
1264                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQBUF_AVAIL_CNTR,
1265                                     avail);
1266 }
1267
1268 static int
1269 ptlrpc_retry_rqbds(void *arg)
1270 {
1271         struct ptlrpc_service *svc = (struct ptlrpc_service *)arg;
1272
1273         svc->srv_rqbd_timeout = 0;
1274         return (-ETIMEDOUT);
1275 }
1276
1277 static int ptlrpc_main(void *arg)
1278 {
1279         struct ptlrpc_svc_data *data = (struct ptlrpc_svc_data *)arg;
1280         struct ptlrpc_service  *svc = data->svc;
1281         struct ptlrpc_thread   *thread = data->thread;
1282         struct obd_device      *dev = data->dev;
1283         struct ptlrpc_reply_state *rs;
1284         struct lc_watchdog     *watchdog;
1285 #ifdef WITH_GROUP_INFO
1286         struct group_info *ginfo = NULL;
1287 #endif
1288         int counter = 0, rc = 0;
1289         ENTRY;
1290
1291         ptlrpc_daemonize(data->name);
1292
1293 #if defined(HAVE_NODE_TO_CPUMASK) && defined(CONFIG_NUMA)
1294         /* we need to do this before any per-thread allocation is done so that
1295          * we get the per-thread allocations on local node.  bug 7342 */
1296         if (svc->srv_cpu_affinity) {
1297                 int cpu, num_cpu;
1298
1299                 for (cpu = 0, num_cpu = 0; cpu < num_possible_cpus(); cpu++) {
1300                         if (!cpu_online(cpu))
1301                                 continue;
1302                         if (num_cpu == thread->t_id % num_online_cpus())
1303                                 break;
1304                         num_cpu++;
1305                 }
1306                 set_cpus_allowed(cfs_current(), node_to_cpumask(cpu_to_node(cpu)));
1307         }
1308 #endif
1309
1310 #ifdef WITH_GROUP_INFO
1311         ginfo = groups_alloc(0);
1312         if (!ginfo) {
1313                 rc = -ENOMEM;
1314                 goto out;
1315         }
1316
1317         set_current_groups(ginfo);
1318         put_group_info(ginfo);
1319 #endif
1320
1321         if (svc->srv_init != NULL) {
1322                 rc = svc->srv_init(thread);
1323                 if (rc)
1324                         goto out;
1325         }
1326
1327         /* Alloc reply state structure for this one */
1328         OBD_ALLOC_GFP(rs, svc->srv_max_reply_size, CFS_ALLOC_STD);
1329         if (!rs) {
1330                 rc = -ENOMEM;
1331                 goto out_srv_init;
1332         }
1333
1334         /* Record that the thread is running */
1335         thread->t_flags = SVC_RUNNING;
1336         /*
1337          * wake up our creator. Note: @data is invalid after this point,
1338          * because it's allocated on ptlrpc_start_thread() stack.
1339          */
1340         cfs_waitq_signal(&thread->t_ctl_waitq);
1341
1342         watchdog = lc_watchdog_add(max_t(int, obd_timeout, AT_OFF ? 0 : 
1343                                    at_get(&svc->srv_at_estimate)) * 
1344                                    svc->srv_watchdog_factor, NULL, NULL);
1345
1346         spin_lock(&svc->srv_lock);
1347         svc->srv_threads_running++;
1348         list_add(&rs->rs_list, &svc->srv_free_rs_list);
1349         spin_unlock(&svc->srv_lock);
1350         cfs_waitq_signal(&svc->srv_free_rs_waitq);
1351
1352         CDEBUG(D_NET, "service thread %d (#%d) started\n", thread->t_id,
1353                svc->srv_threads_running);
1354
1355         /* XXX maintain a list of all managed devices: insert here */
1356
1357         while ((thread->t_flags & SVC_STOPPING) == 0 ||
1358                svc->srv_n_difficult_replies != 0) {
1359                 /* Don't exit while there are replies to be handled */
1360                 struct l_wait_info lwi = LWI_TIMEOUT(svc->srv_rqbd_timeout,
1361                                                      ptlrpc_retry_rqbds, svc);
1362
1363                 lc_watchdog_disable(watchdog);
1364
1365                 cond_resched();
1366
1367                 l_wait_event_exclusive (svc->srv_waitq,
1368                               ((thread->t_flags & SVC_STOPPING) != 0 &&
1369                                svc->srv_n_difficult_replies == 0) ||
1370                               (!list_empty(&svc->srv_idle_rqbds) &&
1371                                svc->srv_rqbd_timeout == 0) ||
1372                               !list_empty(&svc->srv_req_in_queue) ||
1373                               !list_empty(&svc->srv_reply_queue) ||
1374                               (!list_empty(&svc->srv_request_queue) &&
1375                                (svc->srv_n_active_reqs <
1376                                 (svc->srv_threads_running - 1))) ||
1377                               svc->srv_at_check,
1378                               &lwi);
1379
1380                 lc_watchdog_touch_ms(watchdog, max_t(int, obd_timeout,
1381                                      AT_OFF ? 0 : 
1382                                      at_get(&svc->srv_at_estimate)) * 
1383                                      svc->srv_watchdog_factor);
1384
1385                 ptlrpc_check_rqbd_pool(svc);
1386
1387                 if ((svc->srv_threads_started < svc->srv_threads_max) &&
1388                     (svc->srv_n_active_reqs >= (svc->srv_threads_started - 1))){
1389                         /* Ignore return code - we tried... */
1390                         ptlrpc_start_thread(dev, svc);
1391                 }
1392
1393                 if (!list_empty(&svc->srv_reply_queue))
1394                         ptlrpc_server_handle_reply (svc);
1395
1396                 if (!list_empty(&svc->srv_req_in_queue)) {
1397                         /* Process all incoming reqs before handling any */
1398                         ptlrpc_server_handle_req_in(svc);
1399                         /* but limit ourselves in case of flood */ 
1400                         if (counter++ < 1000)
1401                                 continue;
1402                         counter = 0;
1403                 }
1404
1405                 if (svc->srv_at_check) 
1406                         ptlrpc_at_check_timed(svc);
1407
1408                 /* don't handle requests in the last thread */
1409                 if (!list_empty (&svc->srv_request_queue) &&
1410                     (svc->srv_n_active_reqs < (svc->srv_threads_running - 1)))
1411                         ptlrpc_server_handle_request(svc, thread);
1412
1413                 if (!list_empty(&svc->srv_idle_rqbds) &&
1414                     ptlrpc_server_post_idle_rqbds(svc) < 0) {
1415                         /* I just failed to repost request buffers.  Wait
1416                          * for a timeout (unless something else happens)
1417                          * before I try again */
1418                         svc->srv_rqbd_timeout = cfs_time_seconds(1)/10;
1419                         CDEBUG(D_RPCTRACE,"Posted buffers: %d\n",
1420                                svc->srv_nrqbd_receiving);
1421                 }
1422         }
1423
1424         lc_watchdog_delete(watchdog);
1425
1426 out_srv_init:
1427         /*
1428          * deconstruct service specific state created by ptlrpc_start_thread()
1429          */
1430         if (svc->srv_done != NULL)
1431                 svc->srv_done(thread);
1432
1433 out:
1434         CDEBUG(D_NET, "service thread %d exiting: rc %d\n", thread->t_id, rc);
1435
1436         spin_lock(&svc->srv_lock);
1437         svc->srv_threads_running--;              /* must know immediately */
1438         thread->t_id = rc;
1439         thread->t_flags = SVC_STOPPED;
1440
1441         cfs_waitq_signal(&thread->t_ctl_waitq);
1442         spin_unlock(&svc->srv_lock);
1443
1444         return rc;
1445 }
1446
1447 static void ptlrpc_stop_thread(struct ptlrpc_service *svc,
1448                                struct ptlrpc_thread *thread)
1449 {
1450         struct l_wait_info lwi = { 0 };
1451
1452         spin_lock(&svc->srv_lock);
1453         thread->t_flags = SVC_STOPPING;
1454         spin_unlock(&svc->srv_lock);
1455
1456         cfs_waitq_broadcast(&svc->srv_waitq);
1457         l_wait_event(thread->t_ctl_waitq, (thread->t_flags & SVC_STOPPED),
1458                      &lwi);
1459
1460         spin_lock(&svc->srv_lock);
1461         list_del(&thread->t_link);
1462         spin_unlock(&svc->srv_lock);
1463
1464         OBD_FREE(thread, sizeof(*thread));
1465 }
1466
1467 void ptlrpc_stop_all_threads(struct ptlrpc_service *svc)
1468 {
1469         struct ptlrpc_thread *thread;
1470
1471         spin_lock(&svc->srv_lock);
1472         while (!list_empty(&svc->srv_threads)) {
1473                 thread = list_entry(svc->srv_threads.next,
1474                                     struct ptlrpc_thread, t_link);
1475
1476                 spin_unlock(&svc->srv_lock);
1477                 ptlrpc_stop_thread(svc, thread);
1478                 spin_lock(&svc->srv_lock);
1479         }
1480
1481         spin_unlock(&svc->srv_lock);
1482 }
1483
1484 int ptlrpc_start_threads(struct obd_device *dev, struct ptlrpc_service *svc)
1485 {
1486         int i, rc = 0;
1487         ENTRY;
1488
1489         /* We require 2 threads min - see note in 
1490            ptlrpc_server_handle_request */
1491         LASSERT(svc->srv_threads_min >= 2);
1492         for (i = 0; i < svc->srv_threads_min; i++) {
1493                 rc = ptlrpc_start_thread(dev, svc);
1494                 if (rc) {
1495                         CERROR("cannot start %s thread #%d: rc %d\n",
1496                                svc->srv_thread_name, i, rc);
1497                         ptlrpc_stop_all_threads(svc);
1498                 }
1499         }
1500         RETURN(rc);
1501 }
1502
1503 int ptlrpc_start_thread(struct obd_device *dev, struct ptlrpc_service *svc)
1504 {
1505         struct l_wait_info lwi = { 0 };
1506         struct ptlrpc_svc_data d;
1507         struct ptlrpc_thread *thread;
1508         char name[32];
1509         int id, rc;
1510         ENTRY;
1511
1512         CDEBUG(D_RPCTRACE, "%s started %d min %d max %d running %d\n",
1513                svc->srv_name, svc->srv_threads_started, svc->srv_threads_min,
1514                svc->srv_threads_max, svc->srv_threads_running);
1515         if (svc->srv_threads_started >= svc->srv_threads_max)
1516                 RETURN(-EMFILE);
1517
1518         OBD_ALLOC(thread, sizeof(*thread));
1519         if (thread == NULL)
1520                 RETURN(-ENOMEM);
1521         cfs_waitq_init(&thread->t_ctl_waitq);
1522
1523         spin_lock(&svc->srv_lock);
1524         if (svc->srv_threads_started >= svc->srv_threads_max) {
1525                 spin_unlock(&svc->srv_lock);
1526                 OBD_FREE(thread, sizeof(*thread));
1527                 RETURN(-EMFILE);
1528         }
1529         list_add(&thread->t_link, &svc->srv_threads);
1530         id = svc->srv_threads_started++;
1531         spin_unlock(&svc->srv_lock);
1532
1533         thread->t_id = id;
1534         sprintf(name, "%s_%02d", svc->srv_thread_name, id);
1535         d.dev = dev;
1536         d.svc = svc;
1537         d.name = name;
1538         d.thread = thread;
1539
1540         CDEBUG(D_RPCTRACE, "starting thread '%s'\n", name);
1541         
1542         /* CLONE_VM and CLONE_FILES just avoid a needless copy, because we
1543          * just drop the VM and FILES in ptlrpc_daemonize() right away.
1544          */
1545         rc = cfs_kernel_thread(ptlrpc_main, &d, CLONE_VM | CLONE_FILES);
1546         if (rc < 0) {
1547                 CERROR("cannot start thread '%s': rc %d\n", name, rc);
1548
1549                 spin_lock(&svc->srv_lock);
1550                 list_del(&thread->t_link);
1551                 --svc->srv_threads_started;
1552                 spin_unlock(&svc->srv_lock);
1553
1554                 OBD_FREE(thread, sizeof(*thread));
1555                 RETURN(rc);
1556         }
1557         l_wait_event(thread->t_ctl_waitq,
1558                      thread->t_flags & (SVC_RUNNING | SVC_STOPPED), &lwi);
1559
1560         rc = (thread->t_flags & SVC_STOPPED) ? thread->t_id : 0;
1561         RETURN(rc);
1562 }
1563 #endif
1564
1565 int ptlrpc_unregister_service(struct ptlrpc_service *service)
1566 {
1567         int                   rc;
1568         struct l_wait_info    lwi;
1569         struct list_head     *tmp;
1570         struct ptlrpc_reply_state *rs, *t;
1571
1572         cfs_timer_disarm(&service->srv_at_timer);
1573
1574         ptlrpc_stop_all_threads(service);
1575         LASSERT(list_empty(&service->srv_threads));
1576
1577         spin_lock (&ptlrpc_all_services_lock);
1578         list_del_init (&service->srv_list);
1579         spin_unlock (&ptlrpc_all_services_lock);
1580
1581         ptlrpc_lprocfs_unregister_service(service);
1582
1583         /* All history will be culled when the next request buffer is
1584          * freed */
1585         service->srv_max_history_rqbds = 0;
1586
1587         CDEBUG(D_NET, "%s: tearing down\n", service->srv_name);
1588
1589         rc = LNetClearLazyPortal(service->srv_req_portal);
1590         LASSERT (rc == 0);
1591
1592         /* Unlink all the request buffers.  This forces a 'final' event with
1593          * its 'unlink' flag set for each posted rqbd */
1594         list_for_each(tmp, &service->srv_active_rqbds) {
1595                 struct ptlrpc_request_buffer_desc *rqbd =
1596                         list_entry(tmp, struct ptlrpc_request_buffer_desc, 
1597                                    rqbd_list);
1598
1599                 rc = LNetMDUnlink(rqbd->rqbd_md_h);
1600                 LASSERT (rc == 0 || rc == -ENOENT);
1601         }
1602
1603         /* Wait for the network to release any buffers it's currently
1604          * filling */
1605         for (;;) {
1606                 spin_lock(&service->srv_lock);
1607                 rc = service->srv_nrqbd_receiving;
1608                 spin_unlock(&service->srv_lock);
1609
1610                 if (rc == 0)
1611                         break;
1612
1613                 /* Network access will complete in finite time but the HUGE
1614                  * timeout lets us CWARN for visibility of sluggish NALs */
1615                 lwi = LWI_TIMEOUT(cfs_time_seconds(LONG_UNLINK), NULL, NULL);
1616                 rc = l_wait_event(service->srv_waitq,
1617                                   service->srv_nrqbd_receiving == 0,
1618                                   &lwi);
1619                 if (rc == -ETIMEDOUT)
1620                         CWARN("Service %s waiting for request buffers\n",
1621                               service->srv_name);
1622         }
1623
1624         /* schedule all outstanding replies to terminate them */
1625         spin_lock(&service->srv_lock);
1626         while (!list_empty(&service->srv_active_replies)) {
1627                 struct ptlrpc_reply_state *rs =
1628                         list_entry(service->srv_active_replies.next,
1629                                    struct ptlrpc_reply_state, rs_list);
1630                 ptlrpc_schedule_difficult_reply(rs);
1631         }
1632         spin_unlock(&service->srv_lock);
1633
1634         /* purge the request queue.  NB No new replies (rqbds all unlinked)
1635          * and no service threads, so I'm the only thread noodling the
1636          * request queue now */
1637         while (!list_empty(&service->srv_req_in_queue)) {
1638                 struct ptlrpc_request *req =
1639                         list_entry(service->srv_req_in_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         while (!list_empty(&service->srv_request_queue)) {
1649                 struct ptlrpc_request *req =
1650                         list_entry(service->srv_request_queue.next,
1651                                    struct ptlrpc_request,
1652                                    rq_list);
1653
1654                 list_del(&req->rq_list);
1655                 service->srv_n_queued_reqs--;
1656                 service->srv_n_active_reqs++;
1657                 ptlrpc_server_free_request(req);
1658         }
1659         LASSERT(service->srv_n_queued_reqs == 0);
1660         LASSERT(service->srv_n_active_reqs == 0);
1661         LASSERT(service->srv_n_history_rqbds == 0);
1662         LASSERT(list_empty(&service->srv_active_rqbds));
1663
1664         /* Now free all the request buffers since nothing references them
1665          * any more... */
1666         while (!list_empty(&service->srv_idle_rqbds)) {
1667                 struct ptlrpc_request_buffer_desc *rqbd =
1668                         list_entry(service->srv_idle_rqbds.next,
1669                                    struct ptlrpc_request_buffer_desc,
1670                                    rqbd_list);
1671
1672                 ptlrpc_free_rqbd(rqbd);
1673         }
1674
1675         /* wait for all outstanding replies to complete (they were
1676          * scheduled having been flagged to abort above) */
1677         while (atomic_read(&service->srv_outstanding_replies) != 0) {
1678                 struct l_wait_info lwi = LWI_TIMEOUT(cfs_time_seconds(10), NULL, NULL);
1679
1680                 rc = l_wait_event(service->srv_waitq,
1681                                   !list_empty(&service->srv_reply_queue), &lwi);
1682                 LASSERT(rc == 0 || rc == -ETIMEDOUT);
1683
1684                 if (rc == 0) {
1685                         ptlrpc_server_handle_reply(service);
1686                         continue;
1687                 }
1688                 CWARN("Unexpectedly long timeout %p\n", service);
1689         }
1690
1691         list_for_each_entry_safe(rs, t, &service->srv_free_rs_list, rs_list) {
1692                 list_del(&rs->rs_list);
1693                 OBD_FREE(rs, service->srv_max_reply_size);
1694         }
1695
1696         /* In case somebody rearmed this in the meantime */
1697         cfs_timer_disarm(&service->srv_at_timer);
1698
1699         OBD_FREE(service, sizeof(*service));
1700         return 0;
1701 }
1702
1703 /* Returns 0 if the service is healthy.
1704  *
1705  * Right now, it just checks to make sure that requests aren't languishing
1706  * in the queue.  We'll use this health check to govern whether a node needs
1707  * to be shot, so it's intentionally non-aggressive. */
1708 int ptlrpc_service_health_check(struct ptlrpc_service *svc)
1709 {
1710         struct ptlrpc_request *request;
1711         struct timeval         right_now;
1712         long                   timediff;
1713
1714         if (svc == NULL)
1715                 return 0;
1716
1717         do_gettimeofday(&right_now);
1718
1719         spin_lock(&svc->srv_lock);
1720         if (list_empty(&svc->srv_request_queue)) {
1721                 spin_unlock(&svc->srv_lock);
1722                 return 0;
1723         }
1724         
1725         /* How long has the next entry been waiting? */
1726         request = list_entry(svc->srv_request_queue.next,
1727                              struct ptlrpc_request, rq_list);
1728         timediff = cfs_timeval_sub(&right_now, &request->rq_arrival_time, NULL);
1729         spin_unlock(&svc->srv_lock);
1730
1731         if ((timediff / ONE_MILLION) > (AT_OFF ? obd_timeout * 3/2 : 
1732                                         at_max)) {
1733                 CERROR("%s: unhealthy - request has been waiting %lds\n",
1734                        svc->srv_name, timediff / ONE_MILLION);
1735                 return (-1);
1736         }
1737
1738         return 0;
1739 }