Whamcloud - gitweb
b=11973
[fs/lustre-release.git] / lustre / mgc / mgc_request.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  *  lustre/mgc/mgc_request.c
5  *  Lustre Management Client
6  *
7  *  Copyright (C) 2006 Cluster File Systems, Inc.
8  *   Author: Nathan Rutman <nathan@clusterfs.com>
9  *
10  *   This file is part of Lustre, http://www.lustre.org
11  *
12  *   Lustre is free software; you can redistribute it and/or
13  *   modify it under the terms of version 2 of the GNU General Public
14  *   License as published by the Free Software Foundation.
15  *
16  *   Lustre is distributed in the hope that it will be useful,
17  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
18  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  *   GNU General Public License for more details.
20  *
21  *   You should have received a copy of the GNU General Public License
22  *   along with Lustre; if not, write to the Free Software
23  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24  *
25  */
26  
27 #ifndef EXPORT_SYMTAB
28 # define EXPORT_SYMTAB
29 #endif
30 #define DEBUG_SUBSYSTEM S_MGC
31 #define D_MGC D_CONFIG /*|D_WARNING*/
32
33 #ifdef __KERNEL__
34 # include <linux/module.h>
35 # include <linux/pagemap.h>
36 # include <linux/miscdevice.h>
37 # include <linux/init.h>
38 #else
39 # include <liblustre.h>
40 #endif
41
42 #include <obd_class.h>
43 #include <lustre_dlm.h>
44 #include <lustre_log.h>
45 #include <lustre_fsfilt.h>
46 #include <lustre_disk.h>
47
48
49 int mgc_logname2resid(char *logname, struct ldlm_res_id *res_id)
50 {
51         char *name_end;
52         int len;
53         __u64 resname = 0;
54         
55         /* fsname is at most 8 chars long at the beginning of the logname
56            e.g. "lustre-MDT0001" or "lustre" */
57         name_end = strrchr(logname, '-');
58         if (name_end)
59                 len = name_end - logname;
60         else
61                 len = strlen(logname);
62         if (len > 8) {
63                 CERROR("fsname too long: %s\n", logname);
64                 return -EINVAL;
65         }
66         if (len <= 0) {
67                 CERROR("missing fsname: %s\n", logname);
68                 return -EINVAL;
69         }
70         memcpy(&resname, logname, len);
71
72         memset(res_id, 0, sizeof(*res_id));
73         /* Always use the same endianness for the resid */
74         res_id->name[0] = cpu_to_le64(resname);
75         CDEBUG(D_MGC, "log %s to resid "LPX64"/"LPX64" (%.8s)\n", logname,
76                res_id->name[0], res_id->name[1], (char *)&res_id->name[0]);
77         return 0;
78 }
79 EXPORT_SYMBOL(mgc_logname2resid);
80
81 /********************** config llog list **********************/
82 static struct list_head config_llog_list = LIST_HEAD_INIT(config_llog_list);
83 static spinlock_t       config_list_lock = SPIN_LOCK_UNLOCKED;
84
85 /* Take a reference to a config log */
86 static int config_log_get(struct config_llog_data *cld)
87 {
88         ENTRY;
89         if (cld->cld_stopping)
90                 RETURN(1);
91         atomic_inc(&cld->cld_refcount);
92         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
93                atomic_read(&cld->cld_refcount));
94         RETURN(0);
95 }
96
97 /* Drop a reference to a config log.  When no longer referenced, 
98    we can free the config log data */
99 static void config_log_put(struct config_llog_data *cld)
100 {
101         ENTRY;
102         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
103                atomic_read(&cld->cld_refcount));
104         if (atomic_dec_and_test(&cld->cld_refcount)) {
105                 CDEBUG(D_MGC, "dropping config log %s\n", cld->cld_logname);
106                 class_export_put(cld->cld_mgcexp);
107                 spin_lock(&config_list_lock);
108                 list_del(&cld->cld_list_chain);
109                 spin_unlock(&config_list_lock);
110                 OBD_FREE(cld->cld_logname, strlen(cld->cld_logname) + 1);
111                 if (cld->cld_cfg.cfg_instance != NULL)
112                         OBD_FREE(cld->cld_cfg.cfg_instance, 
113                                  strlen(cld->cld_cfg.cfg_instance) + 1);
114                 OBD_FREE(cld, sizeof(*cld));
115         }
116         EXIT;
117 }
118
119 /* Find a config log by name */
120 static struct config_llog_data *config_log_find(char *logname, 
121                                                struct config_llog_instance *cfg)
122 {
123         struct list_head *tmp;
124         struct config_llog_data *cld;
125         char *logid = logname;
126         int match_instance = 0;
127         ENTRY;
128
129         if (cfg && cfg->cfg_instance) {
130                 match_instance++;
131                 logid = cfg->cfg_instance;
132         }
133         if (!logid) {
134                 CERROR("No log specified\n");
135                 RETURN(ERR_PTR(-EINVAL));
136         }
137
138         spin_lock(&config_list_lock);
139         list_for_each(tmp, &config_llog_list) {
140                 cld = list_entry(tmp, struct config_llog_data, cld_list_chain);
141                 if (match_instance && cld->cld_cfg.cfg_instance && 
142                     strcmp(logid, cld->cld_cfg.cfg_instance) == 0)
143                         goto out_found;
144                 if (!match_instance &&  
145                     strcmp(logid, cld->cld_logname) == 0)
146                         goto out_found;
147         }
148         spin_unlock(&config_list_lock);
149
150         CERROR("can't get log %s\n", logid);
151         RETURN(ERR_PTR(-ENOENT));
152 out_found:
153         atomic_inc(&cld->cld_refcount);
154         spin_unlock(&config_list_lock);
155         RETURN(cld);
156 }
157
158 /* Add this log to our list of active logs. 
159    We have one active log per "mount" - client instance or servername.
160    Each instance may be at a different point in the log. */
161 static int config_log_add(char *logname, struct config_llog_instance *cfg,
162                           struct super_block *sb)
163 {
164         struct config_llog_data *cld;
165         struct lustre_sb_info *lsi = s2lsi(sb);
166         int rc;
167         ENTRY;
168
169         CDEBUG(D_MGC, "adding config log %s:%s\n", logname, cfg->cfg_instance);
170         
171         OBD_ALLOC(cld, sizeof(*cld));
172         if (!cld) 
173                 RETURN(-ENOMEM);
174         OBD_ALLOC(cld->cld_logname, strlen(logname) + 1);
175         if (!cld->cld_logname) { 
176                 OBD_FREE(cld, sizeof(*cld));
177                 RETURN(-ENOMEM);
178         }
179         strcpy(cld->cld_logname, logname);
180         cld->cld_cfg = *cfg;
181         cld->cld_cfg.cfg_last_idx = 0;
182         cld->cld_cfg.cfg_flags = 0;
183         cld->cld_cfg.cfg_sb = sb;
184         atomic_set(&cld->cld_refcount, 1);
185         
186         /* Keep the mgc around until we are done */
187         cld->cld_mgcexp = class_export_get(lsi->lsi_mgc->obd_self_export);
188         
189         if (cfg->cfg_instance != NULL) {
190                 OBD_ALLOC(cld->cld_cfg.cfg_instance, 
191                           strlen(cfg->cfg_instance) + 1);
192                 strcpy(cld->cld_cfg.cfg_instance, cfg->cfg_instance);
193         }
194         rc = mgc_logname2resid(logname, &cld->cld_resid);
195         spin_lock(&config_list_lock);
196         list_add(&cld->cld_list_chain, &config_llog_list);
197         spin_unlock(&config_list_lock);
198         
199         if (rc) {
200                 config_log_put(cld);
201                 RETURN(rc);
202         }
203         
204         RETURN(rc);
205 }
206
207 /* Stop watching for updates on this log. */
208 static int config_log_end(char *logname, struct config_llog_instance *cfg)
209 {       
210         struct config_llog_data *cld;
211         int rc = 0;
212         ENTRY;
213                                        
214         cld = config_log_find(logname, cfg);
215         if (IS_ERR(cld)) 
216                 RETURN(PTR_ERR(cld));
217         /* drop the ref from the find */
218         config_log_put(cld);
219
220         cld->cld_stopping = 1;
221         /* drop the start ref */
222         config_log_put(cld);
223         CDEBUG(D_MGC, "end config log %s (%d)\n", logname ? logname : "client",
224                rc);
225         RETURN(rc);
226 }
227
228 /* reenqueue any lost locks */
229 #define RQ_RUNNING 0x1
230 #define RQ_NOW     0x2
231 #define RQ_LATER   0x4
232 #define RQ_STOP    0x8
233 static int rq_state = 0;
234 static cfs_waitq_t rq_waitq;
235
236 static int mgc_process_log(struct obd_device *mgc, 
237                            struct config_llog_data *cld);
238
239 static int mgc_requeue_thread(void *data)
240 {
241         struct l_wait_info lwi_now, lwi_later;
242         struct config_llog_data *cld, *n;
243         char name[] = "ll_cfg_requeue";
244         int rc = 0;
245         ENTRY;
246         
247         ptlrpc_daemonize(name);
248         
249         CDEBUG(D_MGC, "Starting requeue thread\n");
250
251         lwi_later = LWI_TIMEOUT(60 * HZ, NULL, NULL);
252         l_wait_event(rq_waitq, rq_state & (RQ_NOW | RQ_STOP), &lwi_later);
253
254         /* Keep trying failed locks periodically */
255         spin_lock(&config_list_lock);
256         while (rq_state & (RQ_NOW | RQ_LATER)) {
257                 /* Any new or requeued lostlocks will change the state */
258                 rq_state &= ~(RQ_NOW | RQ_LATER); 
259                 spin_unlock(&config_list_lock);
260
261                 /* Always wait a few seconds to allow the server who 
262                    caused the lock revocation to finish its setup, plus some
263                    random so everyone doesn't try to reconnect at once. */
264                 lwi_now = LWI_TIMEOUT(3 * HZ + (ll_rand() & 0xff) * (HZ / 100),
265                                       NULL, NULL);
266                 l_wait_event(rq_waitq, rq_state & RQ_STOP, &lwi_now);
267                 
268                 spin_lock(&config_list_lock);
269                 list_for_each_entry_safe(cld, n, &config_llog_list,
270                                          cld_list_chain) {
271                         spin_unlock(&config_list_lock);
272                         
273                         if (cld->cld_lostlock) {
274                                 CDEBUG(D_MGC, "updating log %s\n", 
275                                        cld->cld_logname);
276                                 cld->cld_lostlock = 0;
277                                 rc = mgc_process_log(cld->cld_mgcexp->exp_obd,
278                                                      cld);
279                                 /* Whether we enqueued again or not in 
280                                    mgc_process_log, we're done with the ref 
281                                    from the old enqueue */        
282                                 config_log_put(cld);
283                         }
284
285                         spin_lock(&config_list_lock);
286                 }
287                 spin_unlock(&config_list_lock);
288                 
289                 /* Wait a bit to see if anyone else needs a requeue */
290                 l_wait_event(rq_waitq, rq_state & (RQ_NOW | RQ_STOP),
291                              &lwi_later);
292                 spin_lock(&config_list_lock);
293         }
294         /* spinlock and while guarantee RQ_NOW and RQ_LATER are not set */
295         rq_state &= ~RQ_RUNNING;
296         spin_unlock(&config_list_lock);
297         
298         CDEBUG(D_MGC, "Ending requeue thread\n");
299         RETURN(rc);
300 }
301
302 /* Add a cld to the list to requeue.  Start the requeue thread if needed.
303    We are responsible for dropping the config log reference from here on out. */
304 static int mgc_requeue_add(struct config_llog_data *cld, int later)
305 {
306         int rc = 0;
307
308         CDEBUG(D_INFO, "log %s: requeue (l=%d r=%d sp=%d st=%x)\n", 
309                cld->cld_logname, later, atomic_read(&cld->cld_refcount),
310                cld->cld_stopping, rq_state);
311         
312         /* Hold lock for rq_state */
313         spin_lock(&config_list_lock);
314         cld->cld_lostlock = 1;
315
316         if (cld->cld_stopping || (rq_state & RQ_STOP)) {
317                 spin_unlock(&config_list_lock);
318                 config_log_put(cld);
319                 RETURN(0);
320         }
321
322         if (!(rq_state & RQ_RUNNING)) {
323                 LASSERT(rq_state == 0);
324                 rq_state = RQ_RUNNING | (later ? RQ_LATER : RQ_NOW);
325                 spin_unlock(&config_list_lock);
326                 rc = cfs_kernel_thread(mgc_requeue_thread, 0,
327                                        CLONE_VM | CLONE_FILES);
328                 if (rc < 0) {
329                         CERROR("log %s: cannot start requeue thread (%d),"
330                                "no more log updates!\n", cld->cld_logname, rc);
331                         /* Drop the ref, since the rq thread won't */
332                         cld->cld_lostlock = 0;
333                         config_log_put(cld);
334                         rq_state = 0;
335                         RETURN(rc);
336                 }
337         } else {
338                 rq_state |= later ? RQ_LATER : RQ_NOW;
339                 spin_unlock(&config_list_lock);
340                 cfs_waitq_signal(&rq_waitq);
341         }
342
343         RETURN(0);
344 }
345
346 /********************** class fns **********************/
347
348 static int mgc_fs_setup(struct obd_device *obd, struct super_block *sb, 
349                         struct vfsmount *mnt)
350 {
351         struct lvfs_run_ctxt saved;
352         struct lustre_sb_info *lsi = s2lsi(sb);
353         struct client_obd *cli = &obd->u.cli;
354         struct dentry *dentry;
355         char *label;
356         int err = 0;
357         ENTRY;
358
359         LASSERT(lsi);
360         LASSERT(lsi->lsi_srv_mnt == mnt);
361
362         /* The mgc fs exclusion sem. Only one fs can be setup at a time. */
363         down(&cli->cl_mgc_sem);
364
365         cleanup_group_info();
366
367         obd->obd_fsops = fsfilt_get_ops(MT_STR(lsi->lsi_ldd));
368         if (IS_ERR(obd->obd_fsops)) {
369                 up(&cli->cl_mgc_sem);
370                 CERROR("No fstype %s rc=%ld\n", MT_STR(lsi->lsi_ldd), 
371                        PTR_ERR(obd->obd_fsops));
372                 RETURN(PTR_ERR(obd->obd_fsops));
373         }
374
375         cli->cl_mgc_vfsmnt = mnt;
376         fsfilt_setup(obd, mnt->mnt_sb);
377
378         OBD_SET_CTXT_MAGIC(&obd->obd_lvfs_ctxt);
379         obd->obd_lvfs_ctxt.pwdmnt = mnt;
380         obd->obd_lvfs_ctxt.pwd = mnt->mnt_root;
381         obd->obd_lvfs_ctxt.fs = get_ds();
382
383         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
384         dentry = lookup_one_len(MOUNT_CONFIGS_DIR, current->fs->pwd,
385                                 strlen(MOUNT_CONFIGS_DIR));
386         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
387         if (IS_ERR(dentry)) {
388                 err = PTR_ERR(dentry);
389                 CERROR("cannot lookup %s directory: rc = %d\n", 
390                        MOUNT_CONFIGS_DIR, err);
391                 GOTO(err_ops, err);
392         }
393         cli->cl_mgc_configs_dir = dentry;
394
395         /* We take an obd ref to insure that we can't get to mgc_cleanup
396            without calling mgc_fs_cleanup first. */
397         class_incref(obd);
398
399         label = fsfilt_get_label(obd, mnt->mnt_sb);
400         if (label)
401                 CDEBUG(D_MGC, "MGC using disk labelled=%s\n", label);
402
403         /* We keep the cl_mgc_sem until mgc_fs_cleanup */
404         RETURN(0);
405
406 err_ops:        
407         fsfilt_put_ops(obd->obd_fsops);
408         obd->obd_fsops = NULL;
409         cli->cl_mgc_vfsmnt = NULL;
410         up(&cli->cl_mgc_sem);
411         RETURN(err);
412 }
413
414 static int mgc_fs_cleanup(struct obd_device *obd)
415 {
416         struct client_obd *cli = &obd->u.cli;
417         int rc = 0;
418         ENTRY;
419
420         LASSERT(cli->cl_mgc_vfsmnt != NULL);
421
422         if (cli->cl_mgc_configs_dir != NULL) {
423                 struct lvfs_run_ctxt saved;
424                 push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
425                 l_dput(cli->cl_mgc_configs_dir);
426                 cli->cl_mgc_configs_dir = NULL; 
427                 pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
428                 class_decref(obd);
429         }
430
431         cli->cl_mgc_vfsmnt = NULL;
432         if (obd->obd_fsops) 
433                 fsfilt_put_ops(obd->obd_fsops);
434         
435         up(&cli->cl_mgc_sem);
436
437         RETURN(rc);
438 }
439
440 static atomic_t mgc_count = ATOMIC_INIT(0);
441 static int mgc_precleanup(struct obd_device *obd, enum obd_cleanup_stage stage)
442 {
443         int rc = 0;
444         ENTRY;
445
446         switch (stage) {
447         case OBD_CLEANUP_EARLY: 
448                 break;
449         case OBD_CLEANUP_EXPORTS:
450                 if (atomic_dec_and_test(&mgc_count)) {
451                         /* Kick the requeue waitq - cld's should all be 
452                            stopping */
453                         spin_lock(&config_list_lock);
454                         rq_state |= RQ_STOP;
455                         spin_unlock(&config_list_lock);
456                         cfs_waitq_signal(&rq_waitq);
457                 }
458                 break;
459         case OBD_CLEANUP_SELF_EXP:
460                 rc = obd_llog_finish(obd, 0);
461                 if (rc != 0)
462                         CERROR("failed to cleanup llogging subsystems\n");
463                 break;
464         case OBD_CLEANUP_OBD:
465                 break;
466         }
467         RETURN(rc);
468 }
469
470 static int mgc_cleanup(struct obd_device *obd)
471 {
472         struct client_obd *cli = &obd->u.cli;
473         int rc;
474         ENTRY;
475
476         LASSERT(cli->cl_mgc_vfsmnt == NULL);
477         
478         /* COMPAT_146 - old config logs may have added profiles we don't 
479            know about */
480         if (obd->obd_type->typ_refcnt <= 1) 
481                 /* Only for the last mgc */
482                 class_del_profiles();
483
484         ptlrpcd_decref();
485
486         rc = client_obd_cleanup(obd);
487         RETURN(rc);
488 }
489
490 static int mgc_setup(struct obd_device *obd, obd_count len, void *buf)
491 {
492         int rc;
493         ENTRY;
494
495         ptlrpcd_addref();
496
497         rc = client_obd_setup(obd, len, buf);
498         if (rc)
499                 GOTO(err_decref, rc);
500
501         rc = obd_llog_init(obd, obd, 0, NULL, NULL);
502         if (rc) {
503                 CERROR("failed to setup llogging subsystems\n");
504                 GOTO(err_cleanup, rc);
505         }
506
507         spin_lock(&config_list_lock);
508         atomic_inc(&mgc_count);
509         if (atomic_read(&mgc_count) == 1) {
510                 rq_state &= ~RQ_STOP;
511                 cfs_waitq_init(&rq_waitq);
512         }
513         spin_unlock(&config_list_lock);
514         
515         RETURN(rc);
516
517 err_cleanup:
518         client_obd_cleanup(obd);
519 err_decref:
520         ptlrpcd_decref();
521         RETURN(rc);
522 }
523
524 /* based on ll_mdc_blocking_ast */
525 static int mgc_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
526                             void *data, int flag)
527 {
528         struct lustre_handle lockh;
529         struct config_llog_data *cld = (struct config_llog_data *)data;
530         int rc = 0;
531         ENTRY;
532
533         switch (flag) {
534         case LDLM_CB_BLOCKING:
535                 /* mgs wants the lock, give it up... */
536                 LDLM_DEBUG(lock, "MGC blocking CB");
537                 ldlm_lock2handle(lock, &lockh);
538                 rc = ldlm_cli_cancel(&lockh);
539                 break;
540         case LDLM_CB_CANCELING: {
541                 /* We've given up the lock, prepare ourselves to update. */
542                 LDLM_DEBUG(lock, "MGC cancel CB");
543                 
544                 CDEBUG(D_MGC, "Lock res "LPX64" (%.8s)\n",
545                        lock->l_resource->lr_name.name[0], 
546                        (char *)&lock->l_resource->lr_name.name[0]);
547                 
548                 if (!cld) {
549                         CERROR("missing data, won't requeue\n");
550                         break;
551                 }
552                 /* Are we done with this log? */
553                 if (cld->cld_stopping) {
554                         CDEBUG(D_MGC, "log %s: stopping, won't requeue\n", 
555                                cld->cld_logname);
556                         config_log_put(cld);    
557                         break;
558                 }
559                 /* Make sure not to re-enqueue when the mgc is stopping
560                    (we get called from client_disconnect_export) */
561                 if (!lock->l_conn_export ||
562                     !lock->l_conn_export->exp_obd->u.cli.cl_conn_count) {
563                         CDEBUG(D_MGC, "log %s: disconnecting, won't requeue\n",
564                                cld->cld_logname);
565                         config_log_put(cld);    
566                         break;
567                 }
568                 /* Did we fail to get the lock? */
569                 if (lock->l_req_mode != lock->l_granted_mode) {
570                         CDEBUG(D_MGC, "log %s: original grant failed, will "
571                                "requeue later\n", cld->cld_logname);
572                         /* Try to re-enqueue later */
573                         rc = mgc_requeue_add(cld, 1);
574                         break;
575                 }
576                 /* Re-enqueue now */
577                 rc = mgc_requeue_add(cld, 0);
578                 break;
579         }
580         default:
581                 LBUG();
582         }
583
584
585         if (rc) {
586                 CERROR("%s CB failed %d:\n", flag == LDLM_CB_BLOCKING ? 
587                        "blocking" : "cancel", rc);
588                 LDLM_ERROR(lock, "MGC ast");
589         }
590         RETURN(rc);
591 }
592
593 /* Take a config lock so we can get cancel notifications */
594 static int mgc_enqueue(struct obd_export *exp, struct lov_stripe_md *lsm,
595                        __u32 type, ldlm_policy_data_t *policy, __u32 mode,
596                        int *flags, void *bl_cb, void *cp_cb, void *gl_cb,
597                        void *data, __u32 lvb_len, void *lvb_swabber,
598                        struct lustre_handle *lockh)
599 {                       
600         struct config_llog_data *cld = (struct config_llog_data *)data;
601         int rc;
602         ENTRY;
603
604         CDEBUG(D_MGC, "Enqueue for %s (res "LPX64")\n", cld->cld_logname,
605                cld->cld_resid.name[0]);
606                 
607         /* We can only drop this config log ref when we drop the lock */
608         if (config_log_get(cld))
609                 RETURN(ELDLM_LOCK_ABORTED);
610
611         /* We need a callback for every lockholder, so don't try to
612            ldlm_lock_match (see rev 1.1.2.11.2.47) */
613
614         rc = ldlm_cli_enqueue(exp, NULL, cld->cld_resid,
615                               type, NULL, mode, flags, 
616                               mgc_blocking_ast, ldlm_completion_ast, NULL,
617                               data, NULL, 0, NULL, lockh, 0);
618         /* A failed enqueue should still call the mgc_blocking_ast, 
619            where it will be requeued if needed ("grant failed"). */ 
620
621         RETURN(rc);
622 }
623
624 static int mgc_cancel(struct obd_export *exp, struct lov_stripe_md *md,
625                       __u32 mode, struct lustre_handle *lockh)
626 {
627         ENTRY;
628
629         ldlm_lock_decref(lockh, mode);
630
631         RETURN(0);
632 }
633
634 #if 0
635 static int mgc_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
636                          void *karg, void *uarg)
637 {
638         struct obd_device *obd = exp->exp_obd;
639         struct obd_ioctl_data *data = karg;
640         struct llog_ctxt *ctxt;
641         struct lvfs_run_ctxt saved;
642         int rc;
643         ENTRY;
644
645 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
646         MOD_INC_USE_COUNT;
647 #else
648         if (!try_module_get(THIS_MODULE)) {
649                 CERROR("Can't get module. Is it alive?");
650                 return -EINVAL;
651         }
652 #endif
653         switch (cmd) {
654         /* REPLicator context */
655         case OBD_IOC_PARSE: {
656                 CERROR("MGC parsing llog %s\n", data->ioc_inlbuf1);
657                 ctxt = llog_get_context(exp->exp_obd, LLOG_CONFIG_REPL_CTXT);
658                 rc = class_config_parse_llog(ctxt, data->ioc_inlbuf1, NULL);
659                 GOTO(out, rc);
660         }
661 #ifdef __KERNEL__
662         case OBD_IOC_LLOG_INFO:
663         case OBD_IOC_LLOG_PRINT: {
664                 ctxt = llog_get_context(obd, LLOG_CONFIG_REPL_CTXT);
665                 rc = llog_ioctl(ctxt, cmd, data);
666
667                 GOTO(out, rc);
668         }
669 #endif
670         /* ORIGinator context */
671         case OBD_IOC_DUMP_LOG: {
672                 ctxt = llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT);
673                 push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
674                 rc = class_config_dump_llog(ctxt, data->ioc_inlbuf1, NULL);
675                 pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
676                 if (rc)
677                         RETURN(rc);
678
679                 GOTO(out, rc);
680         }
681         default:
682                 CERROR("mgc_ioctl(): unrecognised ioctl %#x\n", cmd);
683                 GOTO(out, rc = -ENOTTY);
684         }
685 out:
686 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
687         MOD_DEC_USE_COUNT;
688 #else
689         module_put(THIS_MODULE);
690 #endif
691
692         return rc;
693 }
694 #endif
695
696 /* Send target_reg message to MGS */
697 static int mgc_target_register(struct obd_export *exp,
698                                struct mgs_target_info *mti)
699 {
700         struct ptlrpc_request *req;
701         struct mgs_target_info *req_mti, *rep_mti;
702         int size[] = { sizeof(struct ptlrpc_body), sizeof(*req_mti) };
703         int rep_size[] = { sizeof(struct ptlrpc_body), sizeof(*mti) };
704         int rc;
705         ENTRY;
706
707         req = ptlrpc_prep_req(class_exp2cliimp(exp), LUSTRE_MGS_VERSION,
708                               MGS_TARGET_REG, 2, size, NULL);
709         if (!req)
710                 RETURN(-ENOMEM);
711
712         req_mti = lustre_msg_buf(req->rq_reqmsg, REQ_REC_OFF, sizeof(*req_mti));
713         if (!req_mti) 
714                 RETURN(-ENOMEM);
715         memcpy(req_mti, mti, sizeof(*req_mti));
716
717         ptlrpc_req_set_repsize(req, 2, rep_size);
718
719         CDEBUG(D_MGC, "register %s\n", mti->mti_svname);
720         
721         rc = ptlrpc_queue_wait(req);
722         if (!rc) {
723                 rep_mti = lustre_swab_repbuf(req, REPLY_REC_OFF,
724                                              sizeof(*rep_mti),
725                                              lustre_swab_mgs_target_info);
726                 memcpy(mti, rep_mti, sizeof(*rep_mti));
727                 CDEBUG(D_MGC, "register %s got index = %d\n",
728                        mti->mti_svname, mti->mti_stripe_index);
729         }
730         ptlrpc_req_finished(req);
731
732         RETURN(rc);
733 }
734
735 int mgc_set_info_async(struct obd_export *exp, obd_count keylen,
736                        void *key, obd_count vallen, void *val, 
737                        struct ptlrpc_request_set *set)
738 {
739         struct obd_import *imp = class_exp2cliimp(exp);
740         int rc = -EINVAL;
741         ENTRY;
742
743         /* Try to "recover" the initial connection; i.e. retry */
744         if (KEY_IS(KEY_INIT_RECOV)) {
745                 if (vallen != sizeof(int))
746                         RETURN(-EINVAL);
747                 imp->imp_initial_recov = *(int *)val;
748                 CDEBUG(D_HA, "%s: set imp_initial_recov = %d\n",
749                        exp->exp_obd->obd_name, imp->imp_initial_recov);
750                 RETURN(0);
751         }
752         /* Turn off initial_recov after we try all backup servers once */
753         if (KEY_IS(KEY_INIT_RECOV_BACKUP)) {
754                 int value;
755                 if (vallen != sizeof(int))
756                         RETURN(-EINVAL);
757                 value = *(int *)val;
758                 imp->imp_initial_recov_bk = value > 0;
759                 /* Even after the initial connection, give up all comms if 
760                    nobody answers the first time. */
761                 imp->imp_recon_bk = 1;
762                 CDEBUG(D_MGC, "InitRecov %s %d/%d:d%d:i%d:r%d:or%d:%s\n", 
763                        imp->imp_obd->obd_name, value, imp->imp_initial_recov,
764                        imp->imp_deactive, imp->imp_invalid, 
765                        imp->imp_replayable, imp->imp_obd->obd_replayable,
766                        ptlrpc_import_state_name(imp->imp_state));
767                 /* Resurrect if we previously died */
768                 if (imp->imp_invalid || value > 1) {
769                         /* See client_disconnect_export */
770                         /* Allow reconnect attempts */
771                         imp->imp_obd->obd_no_recov = 0;
772                         /* Force a new connect attempt */
773                         /* (can't put these in obdclass, module loop) */
774                         ptlrpc_invalidate_import(imp);
775                         /* Do a fresh connect next time by zeroing the handle */
776                         ptlrpc_disconnect_import(imp, 1);
777                         /* Remove 'invalid' flag */
778                         ptlrpc_activate_import(imp);
779                         /* Attempt a new connect */
780                         ptlrpc_recover_import(imp, NULL);
781                 }
782                 RETURN(0);
783         }
784         /* FIXME move this to mgc_process_config */
785         if (KEY_IS("register_target")) {
786                 struct mgs_target_info *mti;
787                 if (vallen != sizeof(struct mgs_target_info))
788                         RETURN(-EINVAL);
789                 mti = (struct mgs_target_info *)val;
790                 CDEBUG(D_MGC, "register_target %s %#x\n",
791                        mti->mti_svname, mti->mti_flags);
792                 rc =  mgc_target_register(exp, mti);
793                 RETURN(rc);
794         }
795         if (KEY_IS("set_fs")) {
796                 struct super_block *sb = (struct super_block *)val;
797                 struct lustre_sb_info *lsi;
798                 if (vallen != sizeof(struct super_block))
799                         RETURN(-EINVAL);
800                 lsi = s2lsi(sb);
801                 rc = mgc_fs_setup(exp->exp_obd, sb, lsi->lsi_srv_mnt);
802                 if (rc) {
803                         CERROR("set_fs got %d\n", rc);
804                 }
805                 RETURN(rc);
806         }
807         if (KEY_IS("clear_fs")) {
808                 if (vallen != 0)
809                         RETURN(-EINVAL);
810                 rc = mgc_fs_cleanup(exp->exp_obd);
811                 if (rc) {
812                         CERROR("clear_fs got %d\n", rc);
813                 }
814                 RETURN(rc);
815         }
816
817         RETURN(rc);
818 }               
819
820 static int mgc_import_event(struct obd_device *obd,
821                             struct obd_import *imp,
822                             enum obd_import_event event)
823 {
824         int rc = 0;
825
826         LASSERT(imp->imp_obd == obd);
827         CDEBUG(D_MGC, "import event %#x\n", event);
828
829         switch (event) {
830         case IMP_EVENT_DISCON: 
831                 /* MGC imports should not wait for recovery */
832                 ptlrpc_invalidate_import(imp);
833                 break;
834         case IMP_EVENT_INACTIVE: 
835                 break;
836         case IMP_EVENT_INVALIDATE: {
837                 struct ldlm_namespace *ns = obd->obd_namespace;
838                 ldlm_namespace_cleanup(ns, LDLM_FL_LOCAL_ONLY);
839                 break;
840         }
841         case IMP_EVENT_ACTIVE: 
842                 LCONSOLE_WARN("%s: Reactivating import\n", obd->obd_name);
843                 break;
844         case IMP_EVENT_OCD:
845                 break;
846         default:
847                 CERROR("Unknown import event %#x\n", event);
848                 LBUG();
849         }
850         RETURN(rc);
851 }
852
853 static int mgc_llog_init(struct obd_device *obd, struct obd_device *tgt,
854                          int count, struct llog_catid *logid,
855                          struct obd_uuid *uuid)
856 {
857         struct llog_ctxt *ctxt;
858         int rc;
859         ENTRY;
860
861         rc = llog_setup(obd, LLOG_CONFIG_ORIG_CTXT, tgt, 0, NULL,
862                         &llog_lvfs_ops);
863         if (rc)
864                 RETURN(rc);
865
866         rc = llog_setup(obd, LLOG_CONFIG_REPL_CTXT, tgt, 0, NULL,
867                         &llog_client_ops);
868         if (rc == 0) {
869                 ctxt = llog_get_context(obd, LLOG_CONFIG_REPL_CTXT);
870                 ctxt->loc_imp = obd->u.cli.cl_import;
871         }
872
873         RETURN(rc);
874 }
875
876 static int mgc_llog_finish(struct obd_device *obd, int count)
877 {
878         int rc;
879         ENTRY;
880
881         rc = llog_cleanup(llog_get_context(obd, LLOG_CONFIG_REPL_CTXT));
882         rc = llog_cleanup(llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT));
883
884         RETURN(rc);
885 }
886
887 /* identical to mgs_log_is_empty */
888 static int mgc_llog_is_empty(struct obd_device *obd, struct llog_ctxt *ctxt,
889                             char *name)
890 {
891         struct lvfs_run_ctxt saved;
892         struct llog_handle *llh;
893         int rc = 0;
894
895         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
896         rc = llog_create(ctxt, &llh, NULL, name);
897         if (rc == 0) {
898                 llog_init_handle(llh, LLOG_F_IS_PLAIN, NULL);
899                 rc = llog_get_size(llh);
900                 llog_close(llh);
901         }
902         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
903         /* header is record 1 */
904         return(rc <= 1);
905 }
906
907 static int mgc_copy_handler(struct llog_handle *llh, struct llog_rec_hdr *rec, 
908                             void *data)
909 {
910         struct llog_rec_hdr local_rec = *rec;
911         struct llog_handle *local_llh = (struct llog_handle *)data;
912         char *cfg_buf = (char*) (rec + 1);
913         struct lustre_cfg *lcfg;
914         int rc = 0;
915         ENTRY;
916
917         /* Append all records */
918         local_rec.lrh_len -= sizeof(*rec) + sizeof(struct llog_rec_tail);
919         rc = llog_write_rec(local_llh, &local_rec, NULL, 0, 
920                             (void *)cfg_buf, -1);
921
922         lcfg = (struct lustre_cfg *)cfg_buf;
923         CDEBUG(D_INFO, "idx=%d, rc=%d, len=%d, cmd %x %s %s\n", 
924                rec->lrh_index, rc, rec->lrh_len, lcfg->lcfg_command, 
925                lustre_cfg_string(lcfg, 0), lustre_cfg_string(lcfg, 1));
926
927         RETURN(rc);
928 }
929
930 /* Copy a remote log locally */
931 static int mgc_copy_llog(struct obd_device *obd, struct llog_ctxt *rctxt,
932                          struct llog_ctxt *lctxt, char *logname)
933 {
934         struct llog_handle *local_llh, *remote_llh;
935         struct obd_uuid *uuid;
936         char *temp_log;
937         int rc, rc2;
938         ENTRY;
939
940         /* Write new log to a temp name, then vfs_rename over logname
941            upon successful completion. */
942
943         OBD_ALLOC(temp_log, strlen(logname) + 1);
944         if (!temp_log) 
945                 RETURN(-ENOMEM);
946         sprintf(temp_log, "%sT", logname);
947
948         /* Make sure there's no old temp log */
949         rc = llog_create(lctxt, &local_llh, NULL, temp_log);
950         if (rc)
951                 GOTO(out, rc);
952         rc = llog_init_handle(local_llh, LLOG_F_IS_PLAIN, NULL);
953         if (rc) 
954                 GOTO(out, rc);
955         rc = llog_destroy(local_llh);
956         llog_free_handle(local_llh);
957         if (rc)
958                 GOTO(out, rc);
959
960         /* open local log */
961         rc = llog_create(lctxt, &local_llh, NULL, temp_log);
962         if (rc)
963                 GOTO(out, rc);
964
965         /* set the log header uuid for fun */
966         OBD_ALLOC_PTR(uuid);
967         obd_str2uuid(uuid, logname);
968         rc = llog_init_handle(local_llh, LLOG_F_IS_PLAIN, uuid);
969         OBD_FREE_PTR(uuid);
970         if (rc)
971                 GOTO(out_closel, rc);
972
973         /* open remote log */
974         rc = llog_create(rctxt, &remote_llh, NULL, logname);
975         if (rc)
976                 GOTO(out_closel, rc);
977         rc = llog_init_handle(remote_llh, LLOG_F_IS_PLAIN, NULL);
978         if (rc)
979                 GOTO(out_closer, rc);
980
981         /* Copy remote log */
982         rc = llog_process(remote_llh, mgc_copy_handler,(void *)local_llh, NULL);
983
984 out_closer:
985         rc2 = llog_close(remote_llh);
986         if (!rc)
987                 rc = rc2;
988 out_closel:
989         rc2 = llog_close(local_llh);
990         if (!rc)
991                 rc = rc2;
992
993         /* We've copied the remote log to the local temp log, now
994            replace the old local log with the temp log. */
995         if (!rc) {
996                 struct client_obd *cli = &obd->u.cli;
997                 LASSERT(cli);
998                 LASSERT(cli->cl_mgc_configs_dir);
999                 rc = lustre_rename(cli->cl_mgc_configs_dir, temp_log, logname);
1000         }
1001         CDEBUG(D_MGC, "Copied remote log %s (%d)\n", logname, rc);
1002 out:
1003         if (rc)
1004                 CERROR("Failed to copy remote log %s (%d)\n", logname, rc);
1005         OBD_FREE(temp_log, strlen(logname) + 1);
1006         RETURN(rc);
1007 }
1008
1009 DECLARE_MUTEX(llog_process_lock);
1010
1011 /* Get a config log from the MGS and process it.
1012    This func is called for both clients and servers. */
1013 static int mgc_process_log(struct obd_device *mgc, 
1014                            struct config_llog_data *cld)
1015 {
1016         struct llog_ctxt *ctxt, *lctxt;
1017         struct lustre_handle lockh;
1018         struct client_obd *cli = &mgc->u.cli;
1019         struct lvfs_run_ctxt saved;
1020         struct lustre_sb_info *lsi;
1021         int rc = 0, rcl, flags = 0, must_pop = 0;
1022         ENTRY;
1023
1024         if (!cld || !cld->cld_cfg.cfg_sb) {
1025                 /* This should never happen */
1026                 CERROR("Missing cld, aborting log update\n");
1027                 RETURN(-EINVAL);
1028         }
1029         if (cld->cld_stopping) 
1030                 RETURN(0);
1031
1032         if (cld->cld_cfg.cfg_flags & CFG_F_SERVER146)
1033                 /* If we started from an old MDT, don't bother trying to
1034                    get log updates from the MGS */
1035                 RETURN(0);
1036
1037         OBD_FAIL_TIMEOUT(OBD_FAIL_MGC_PROCESS_LOG, 20);
1038
1039         lsi = s2lsi(cld->cld_cfg.cfg_sb);
1040
1041         CDEBUG(D_MGC, "Process log %s:%s from %d\n", cld->cld_logname, 
1042                cld->cld_cfg.cfg_instance, cld->cld_cfg.cfg_last_idx + 1);
1043
1044         ctxt = llog_get_context(mgc, LLOG_CONFIG_REPL_CTXT);
1045         if (!ctxt) {
1046                 CERROR("missing llog context\n");
1047                 RETURN(-EINVAL);
1048         }
1049
1050         /* I don't want mutliple processes running process_log at once -- 
1051            sounds like badness.  It actually might be fine, as long as 
1052            we're not trying to update from the same log
1053            simultaneously (in which case we should use a per-log sem.) */
1054         down(&llog_process_lock);
1055
1056         /* Get the cfg lock on the llog */
1057         rcl = mgc_enqueue(mgc->u.cli.cl_mgc_mgsexp, NULL, LDLM_PLAIN, NULL, 
1058                           LCK_CR, &flags, NULL, NULL, NULL, 
1059                           cld, 0, NULL, &lockh);
1060         if (rcl) 
1061                 CDEBUG(D_MGC, "Can't get cfg lock: %d\n", rcl);
1062         
1063         lctxt = llog_get_context(mgc, LLOG_CONFIG_ORIG_CTXT);
1064
1065         /* Copy the setup log locally if we can. Don't mess around if we're 
1066            running an MGS though (logs are already local). */
1067         if (lctxt && lsi && (lsi->lsi_flags & LSI_SERVER) && 
1068             (lsi->lsi_srv_mnt == cli->cl_mgc_vfsmnt) &&
1069             !IS_MGS(lsi->lsi_ldd)) {
1070                 push_ctxt(&saved, &mgc->obd_lvfs_ctxt, NULL);
1071                 must_pop++;
1072                 if (rcl == 0) 
1073                         /* Only try to copy log if we have the lock. */
1074                         rc = mgc_copy_llog(mgc, ctxt, lctxt, cld->cld_logname);
1075                 if (rcl || rc) {
1076                         if (mgc_llog_is_empty(mgc, lctxt, cld->cld_logname)) {
1077                                 LCONSOLE_ERROR("Failed to get MGS log %s "
1078                                                "and no local copy.\n",
1079                                                cld->cld_logname);
1080                                 GOTO(out_pop, rc = -ENOTCONN);
1081                         }
1082                         LCONSOLE_WARN("Failed to get MGS log %s, using "
1083                                       "local copy.\n", cld->cld_logname);
1084                 }
1085                 /* Now, whether we copied or not, start using the local llog.
1086                    If we failed to copy, we'll start using whatever the old 
1087                    log has. */
1088                 ctxt = lctxt;
1089         }
1090
1091         /* logname and instance info should be the same, so use our 
1092            copy of the instance for the update.  The cfg_last_idx will
1093            be updated here. */
1094         rc = class_config_parse_llog(ctxt, cld->cld_logname, &cld->cld_cfg);
1095         
1096  out_pop:
1097         if (must_pop) 
1098                 pop_ctxt(&saved, &mgc->obd_lvfs_ctxt, NULL);
1099
1100         /* Now drop the lock so MGS can revoke it */ 
1101         if (!rcl) {
1102                 rcl = mgc_cancel(mgc->u.cli.cl_mgc_mgsexp, NULL, 
1103                                  LCK_CR, &lockh);
1104                 if (rcl) 
1105                         CERROR("Can't drop cfg lock: %d\n", rcl);
1106         }
1107         
1108         CDEBUG(D_MGC, "%s: configuration from log '%s' %sed (%d).\n",
1109                mgc->obd_name, cld->cld_logname, rc ? "fail" : "succeed", rc);
1110
1111         up(&llog_process_lock);
1112         
1113         RETURN(rc);
1114 }
1115
1116 static int mgc_process_config(struct obd_device *obd, obd_count len, void *buf)
1117 {
1118         struct lustre_cfg *lcfg = buf;
1119         int cmd;
1120         int rc = 0;
1121         ENTRY;
1122
1123         switch(cmd = lcfg->lcfg_command) {
1124         case LCFG_LOV_ADD_OBD: {
1125                 /* Add any new target, not just osts */
1126                 struct mgs_target_info *mti;
1127
1128                 if (LUSTRE_CFG_BUFLEN(lcfg, 1) != 
1129                     sizeof(struct mgs_target_info))
1130                         GOTO(out, rc = -EINVAL);
1131
1132                 mti = (struct mgs_target_info *)lustre_cfg_buf(lcfg, 1);
1133                 CDEBUG(D_MGC, "add_target %s %#x\n",    
1134                        mti->mti_svname, mti->mti_flags);
1135                 rc = mgc_target_register(obd->u.cli.cl_mgc_mgsexp, mti);
1136                 break;
1137         }
1138         case LCFG_LOV_DEL_OBD:
1139                 /* Remove target from the fs? */  
1140                 /* FIXME */
1141                 CERROR("lov_del_obd unimplemented\n");
1142                 rc = -ENOSYS;
1143                 break;
1144         case LCFG_LOG_START: {
1145                 struct config_llog_data *cld;
1146                 struct config_llog_instance *cfg;
1147                 struct super_block *sb;
1148                 char *logname = lustre_cfg_string(lcfg, 1);
1149                 cfg = (struct config_llog_instance *)lustre_cfg_buf(lcfg, 2);
1150                 sb = *(struct super_block **)lustre_cfg_buf(lcfg, 3);
1151                 
1152                 CDEBUG(D_MGC, "parse_log %s from %d\n", logname, 
1153                        cfg->cfg_last_idx);
1154
1155                 /* We're only called through here on the initial mount */
1156                 rc = config_log_add(logname, cfg, sb);
1157                 if (rc) 
1158                         break;
1159                 cld = config_log_find(logname, cfg);
1160                 if (IS_ERR(cld)) {
1161                         rc = PTR_ERR(cld);
1162                         break;
1163                 }
1164                 
1165                 /* COMPAT_146 */
1166                 /* FIXME only set this for old logs!  Right now this forces
1167                    us to always skip the "inside markers" check */
1168                 cld->cld_cfg.cfg_flags |= CFG_F_COMPAT146;
1169                 
1170                 rc = mgc_process_log(obd, cld);
1171                 config_log_put(cld);
1172                 
1173                 break;       
1174         }
1175         case LCFG_LOG_END: {
1176                 struct config_llog_instance *cfg = NULL;
1177                 char *logname = lustre_cfg_string(lcfg, 1);
1178                 if (lcfg->lcfg_bufcount >= 2)
1179                         cfg = (struct config_llog_instance *)lustre_cfg_buf(
1180                                 lcfg, 2);
1181                 rc = config_log_end(logname, cfg);
1182                 break;
1183         }
1184         default: {
1185                 CERROR("Unknown command: %d\n", lcfg->lcfg_command);
1186                 GOTO(out, rc = -EINVAL);
1187
1188         }
1189         }
1190 out:
1191         RETURN(rc);
1192 }
1193
1194 struct obd_ops mgc_obd_ops = {
1195         .o_owner        = THIS_MODULE,
1196         .o_setup        = mgc_setup,
1197         .o_precleanup   = mgc_precleanup,
1198         .o_cleanup      = mgc_cleanup,
1199         .o_add_conn     = client_import_add_conn,
1200         .o_del_conn     = client_import_del_conn,
1201         .o_connect      = client_connect_import,
1202         .o_disconnect   = client_disconnect_export,
1203         //.o_enqueue      = mgc_enqueue,
1204         .o_cancel       = mgc_cancel,
1205         //.o_iocontrol    = mgc_iocontrol,
1206         .o_set_info_async = mgc_set_info_async,
1207         .o_import_event = mgc_import_event,
1208         .o_llog_init    = mgc_llog_init,
1209         .o_llog_finish  = mgc_llog_finish,
1210         .o_process_config = mgc_process_config,
1211 };
1212
1213 int __init mgc_init(void)
1214 {
1215         return class_register_type(&mgc_obd_ops, NULL, LUSTRE_MGC_NAME);
1216 }
1217
1218 #ifdef __KERNEL__
1219 static void /*__exit*/ mgc_exit(void)
1220 {
1221         class_unregister_type(LUSTRE_MGC_NAME);
1222 }
1223
1224 MODULE_AUTHOR("Cluster File Systems, Inc. <info@clusterfs.com>");
1225 MODULE_DESCRIPTION("Lustre Management Client");
1226 MODULE_LICENSE("GPL");
1227
1228 module_init(mgc_init);
1229 module_exit(mgc_exit);
1230 #endif