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