Whamcloud - gitweb
- make HEAD from b_post_cmd3
[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 int mgc_logname2resid(char *logname, struct ldlm_res_id *res_id)
49 {
50         char *name_end;
51         int len;
52         __u64 resname = 0;
53
54         /* fsname is at most 8 chars long at the beginning of the logname
55            e.g. "lustre-MDT0001" or "lustre" */
56         name_end = strrchr(logname, '-');
57         if (name_end)
58                 len = name_end - logname;
59         else
60                 len = strlen(logname);
61         if (len > 8) {
62                 CERROR("fsname too long: %s\n", logname);
63                 return -EINVAL;
64         }
65         if (len <= 0) {
66                 CERROR("missing fsname: %s\n", logname);
67                 return -EINVAL;
68         }
69         memcpy(&resname, logname, len);
70
71         memset(res_id, 0, sizeof(*res_id));
72
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         CDEBUG(D_CONFIG, "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                         if (cld->cld_lostlock) {
273                                 CDEBUG(D_MGC, "updating log %s\n", 
274                                        cld->cld_logname);
275                                 cld->cld_lostlock = 0;
276                                 rc = mgc_process_log(cld->cld_mgcexp->exp_obd,
277                                                      cld);
278                                 /* Whether we enqueued again or not in 
279                                    mgc_process_log, we're done with the ref 
280                                    from the old enqueue */      
281                                 config_log_put(cld);
282                         }
283                         spin_lock(&config_list_lock);
284                 }
285                 spin_unlock(&config_list_lock);
286                 
287                 /* Wait a bit to see if anyone else needs a requeue */
288                 l_wait_event(rq_waitq, rq_state & (RQ_NOW | RQ_STOP),
289                              &lwi_later);
290                 spin_lock(&config_list_lock);
291         }
292         /* spinlock and while guarantee RQ_NOW and RQ_LATER are not set */
293         rq_state &= ~RQ_RUNNING;
294         spin_unlock(&config_list_lock);
295         
296         CDEBUG(D_MGC, "Ending requeue thread\n");
297         RETURN(rc);
298 }
299
300 /* Add a cld to the list to requeue.  Start the requeue thread if needed.
301    We are responsible for dropping the config log reference from here on out. */
302 static int mgc_requeue_add(struct config_llog_data *cld, int later)
303 {
304         int rc = 0;
305
306         CDEBUG(D_INFO, "log %s: requeue (l=%d r=%d sp=%d st=%x)\n", 
307                cld->cld_logname, later, atomic_read(&cld->cld_refcount),
308                cld->cld_stopping, rq_state);
309         
310         /* Hold lock for rq_state */
311         spin_lock(&config_list_lock);
312         cld->cld_lostlock = 1;
313
314         if (cld->cld_stopping || (rq_state & RQ_STOP)) {
315                 spin_unlock(&config_list_lock);
316                 config_log_put(cld);
317                 RETURN(0);
318         }
319
320         if (!(rq_state & RQ_RUNNING)) {
321                 LASSERT(rq_state == 0);
322                 rq_state = RQ_RUNNING | (later ? RQ_LATER : RQ_NOW);
323                 spin_unlock(&config_list_lock);
324                 rc = cfs_kernel_thread(mgc_requeue_thread, 0,
325                                        CLONE_VM | CLONE_FILES);
326                 if (rc < 0) {
327                         CERROR("log %s: cannot start requeue thread (%d),"
328                                "no more log updates!\n", cld->cld_logname, rc);
329                         /* Drop the ref, since the rq thread won't */
330                         cld->cld_lostlock = 0;
331                         config_log_put(cld);
332                         rq_state = 0;
333                         RETURN(rc);
334                 }
335         } else {
336                 rq_state |= later ? RQ_LATER : RQ_NOW;
337                 spin_unlock(&config_list_lock);
338                 cfs_waitq_signal(&rq_waitq);
339         }
340
341         RETURN(0);
342 }
343
344 /********************** class fns **********************/
345
346 static int mgc_fs_setup(struct obd_device *obd, struct super_block *sb,
347                         struct vfsmount *mnt)
348 {
349         struct lvfs_run_ctxt saved;
350         struct lustre_sb_info *lsi = s2lsi(sb);
351         struct client_obd *cli = &obd->u.cli;
352         struct dentry *dentry;
353         char *label;
354         int err = 0;
355         ENTRY;
356
357         LASSERT(lsi);
358         LASSERT(lsi->lsi_srv_mnt == mnt);
359
360         /* The mgc fs exclusion sem. Only one fs can be setup at a time. */
361         down(&cli->cl_mgc_sem);
362
363         cleanup_group_info();
364
365         obd->obd_fsops = fsfilt_get_ops(MT_STR(lsi->lsi_ldd));
366         if (IS_ERR(obd->obd_fsops)) {
367                 up(&cli->cl_mgc_sem);
368                 CERROR("No fstype %s rc=%ld\n", MT_STR(lsi->lsi_ldd),
369                        PTR_ERR(obd->obd_fsops));
370                 RETURN(PTR_ERR(obd->obd_fsops));
371         }
372
373         cli->cl_mgc_vfsmnt = mnt;
374         fsfilt_setup(obd, mnt->mnt_sb);
375
376         OBD_SET_CTXT_MAGIC(&obd->obd_lvfs_ctxt);
377         obd->obd_lvfs_ctxt.pwdmnt = mnt;
378         obd->obd_lvfs_ctxt.pwd = mnt->mnt_root;
379         obd->obd_lvfs_ctxt.fs = get_ds();
380
381         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
382         dentry = lookup_one_len(MOUNT_CONFIGS_DIR, current->fs->pwd,
383                                 strlen(MOUNT_CONFIGS_DIR));
384         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
385         if (IS_ERR(dentry)) {
386                 err = PTR_ERR(dentry);
387                 CERROR("cannot lookup %s directory: rc = %d\n",
388                        MOUNT_CONFIGS_DIR, err);
389                 GOTO(err_ops, err);
390         }
391         cli->cl_mgc_configs_dir = dentry;
392
393         /* We take an obd ref to insure that we can't get to mgc_cleanup
394            without calling mgc_fs_cleanup first. */
395         class_incref(obd);
396
397         label = fsfilt_get_label(obd, mnt->mnt_sb);
398         if (label)
399                 CDEBUG(D_MGC, "MGC using disk labelled=%s\n", label);
400
401         /* We keep the cl_mgc_sem until mgc_fs_cleanup */
402         RETURN(0);
403
404 err_ops:
405         fsfilt_put_ops(obd->obd_fsops);
406         obd->obd_fsops = NULL;
407         cli->cl_mgc_vfsmnt = NULL;
408         up(&cli->cl_mgc_sem);
409         RETURN(err);
410 }
411
412 static int mgc_fs_cleanup(struct obd_device *obd)
413 {
414         struct client_obd *cli = &obd->u.cli;
415         int rc = 0;
416         ENTRY;
417
418         LASSERT(cli->cl_mgc_vfsmnt != NULL);
419
420         if (cli->cl_mgc_configs_dir != NULL) {
421                 struct lvfs_run_ctxt saved;
422                 push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
423                 l_dput(cli->cl_mgc_configs_dir);
424                 cli->cl_mgc_configs_dir = NULL;
425                 pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
426                 class_decref(obd);
427         }
428
429         cli->cl_mgc_vfsmnt = NULL;
430         if (obd->obd_fsops)
431                 fsfilt_put_ops(obd->obd_fsops);
432
433         up(&cli->cl_mgc_sem);
434
435         RETURN(rc);
436 }
437
438 static atomic_t mgc_count = ATOMIC_INIT(0);
439 static int mgc_precleanup(struct obd_device *obd, enum obd_cleanup_stage stage)
440 {
441         int rc = 0;
442         ENTRY;
443
444         switch (stage) {
445         case OBD_CLEANUP_EARLY:
446                 break;
447         case OBD_CLEANUP_EXPORTS:
448                 if (atomic_dec_and_test(&mgc_count)) {
449                         /* Kick the requeue waitq - cld's should all be 
450                            stopping */
451                         spin_lock(&config_list_lock);
452                         rq_state |= RQ_STOP;
453                         spin_unlock(&config_list_lock);
454                         cfs_waitq_signal(&rq_waitq);
455                 }
456                 break;
457         case OBD_CLEANUP_SELF_EXP:
458                 rc = obd_llog_finish(obd, 0);
459                 if (rc != 0)
460                         CERROR("failed to cleanup llogging subsystems\n");
461                 break;
462         case OBD_CLEANUP_OBD:
463                 break;
464         }
465         RETURN(rc);
466 }
467
468 static int mgc_cleanup(struct obd_device *obd)
469 {
470         struct client_obd *cli = &obd->u.cli;
471         int rc;
472         ENTRY;
473
474         LASSERT(cli->cl_mgc_vfsmnt == NULL);
475
476         /* COMPAT_146 - old config logs may have added profiles we don't
477            know about */
478         if (obd->obd_type->typ_refcnt <= 1)
479                 /* Only for the last mgc */
480                 class_del_profiles();
481
482         ptlrpcd_decref();
483
484         rc = client_obd_cleanup(obd);
485         RETURN(rc);
486 }
487
488 static int mgc_setup(struct obd_device *obd, struct lustre_cfg *lcfg)
489 {
490         int rc;
491         ENTRY;
492
493         ptlrpcd_addref();
494
495         rc = client_obd_setup(obd, lcfg);
496         if (rc)
497                 GOTO(err_decref, rc);
498
499         rc = obd_llog_init(obd, NULL, obd, 0, NULL, NULL);
500         if (rc) {
501                 CERROR("failed to setup llogging subsystems\n");
502                 GOTO(err_cleanup, rc);
503         }
504
505         spin_lock(&config_list_lock);
506         atomic_inc(&mgc_count);
507         if (atomic_read(&mgc_count) == 1) {
508                 rq_state &= ~RQ_STOP;
509                 cfs_waitq_init(&rq_waitq);
510         }
511         spin_unlock(&config_list_lock);
512         
513         RETURN(rc);
514
515 err_cleanup:
516         client_obd_cleanup(obd);
517 err_decref:
518         ptlrpcd_decref();
519         RETURN(rc);
520 }
521
522 /* based on ll_mdc_blocking_ast */
523 static int mgc_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
524                             void *data, int flag)
525 {
526         struct lustre_handle lockh;
527         struct config_llog_data *cld = (struct config_llog_data *)data;
528         int rc = 0;
529         ENTRY;
530
531         switch (flag) {
532         case LDLM_CB_BLOCKING:
533                 /* mgs wants the lock, give it up... */
534                 LDLM_DEBUG(lock, "MGC blocking CB");
535                 ldlm_lock2handle(lock, &lockh);
536                 rc = ldlm_cli_cancel(&lockh);
537                 break;
538         case LDLM_CB_CANCELING: {
539                 /* We've given up the lock, prepare ourselves to update. */
540                 LDLM_DEBUG(lock, "MGC cancel CB");
541
542                 CDEBUG(D_MGC, "Lock res "LPX64" (%.8s)\n",
543                        lock->l_resource->lr_name.name[0],
544                        (char *)&lock->l_resource->lr_name.name[0]);
545
546                 if (!cld) {
547                         CERROR("missing data, won't requeue\n");
548                         break;
549                 }
550                 /* Are we done with this log? */
551                 if (cld->cld_stopping) {
552                         CDEBUG(D_MGC, "log %s: stopping, won't requeue\n", 
553                                cld->cld_logname);
554                         config_log_put(cld);    
555                         break;
556                 }
557                 /* Make sure not to re-enqueue when the mgc is stopping
558                    (we get called from client_disconnect_export) */
559                 if (!lock->l_conn_export ||
560                     !lock->l_conn_export->exp_obd->u.cli.cl_conn_count) {
561                         CDEBUG(D_MGC, "log %s: disconnecting, won't requeue\n",
562                                cld->cld_logname);
563                         config_log_put(cld);    
564                         break;
565                 }
566                 /* Did we fail to get the lock? */
567                 if (lock->l_req_mode != lock->l_granted_mode) {
568                         CDEBUG(D_MGC, "log %s: original grant failed, will "
569                                "requeue later\n", cld->cld_logname);
570                         /* Try to re-enqueue later */
571                         rc = mgc_requeue_add(cld, 1);
572                         break;
573                 }
574                 /* Re-enqueue now */
575                 rc = mgc_requeue_add(cld, 0);
576                 break;
577         }
578         default:
579                 LBUG();
580         }
581
582
583         if (rc) {
584                 CERROR("%s CB failed %d:\n", flag == LDLM_CB_BLOCKING ?
585                        "blocking" : "cancel", rc);
586                 LDLM_ERROR(lock, "MGC ast");
587         }
588         RETURN(rc);
589 }
590
591 /* Take a config lock so we can get cancel notifications */
592 static int mgc_enqueue(struct obd_export *exp, struct lov_stripe_md *lsm,
593                        __u32 type, ldlm_policy_data_t *policy, __u32 mode,
594                        int *flags, void *bl_cb, void *cp_cb, void *gl_cb,
595                        void *data, __u32 lvb_len, void *lvb_swabber,
596                        struct lustre_handle *lockh)
597 {
598         struct config_llog_data *cld = (struct config_llog_data *)data;
599         int rc;
600         ENTRY;
601
602         CDEBUG(D_MGC, "Enqueue for %s (res "LPX64")\n", cld->cld_logname,
603                cld->cld_resid.name[0]);
604
605         /* We can only drop this config log ref when we drop the lock */
606         if (config_log_get(cld))
607                 RETURN(ELDLM_LOCK_ABORTED);
608
609         /* We need a callback for every lockholder, so don't try to
610            ldlm_lock_match (see rev 1.1.2.11.2.47) */
611
612         rc = ldlm_cli_enqueue(exp, NULL, &cld->cld_resid,
613                               type, NULL, mode, flags,
614                               mgc_blocking_ast, ldlm_completion_ast, NULL,
615                               data, NULL, 0, NULL, lockh, 0);
616         /* A failed enqueue should still call the mgc_blocking_ast, 
617            where it will be requeued if needed ("grant failed"). */ 
618
619         RETURN(rc);
620 }
621
622 static int mgc_cancel(struct obd_export *exp, struct lov_stripe_md *md,
623                       __u32 mode, struct lustre_handle *lockh)
624 {
625         ENTRY;
626
627         ldlm_lock_decref(lockh, mode);
628
629         RETURN(0);
630 }
631
632 #if 0
633 static int mgc_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
634                          void *karg, void *uarg)
635 {
636         struct obd_device *obd = exp->exp_obd;
637         struct obd_ioctl_data *data = karg;
638         struct llog_ctxt *ctxt;
639         struct lvfs_run_ctxt saved;
640         int rc;
641         ENTRY;
642
643 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
644         MOD_INC_USE_COUNT;
645 #else
646         if (!try_module_get(THIS_MODULE)) {
647                 CERROR("Can't get module. Is it alive?");
648                 return -EINVAL;
649         }
650 #endif
651         switch (cmd) {
652         /* REPLicator context */
653         case OBD_IOC_PARSE: {
654                 CERROR("MGC parsing llog %s\n", data->ioc_inlbuf1);
655                 ctxt = llog_get_context(exp->exp_obd, LLOG_CONFIG_REPL_CTXT);
656                 rc = class_config_parse_llog(ctxt, data->ioc_inlbuf1, NULL);
657                 GOTO(out, rc);
658         }
659 #ifdef __KERNEL__
660         case OBD_IOC_LLOG_INFO:
661         case OBD_IOC_LLOG_PRINT: {
662                 ctxt = llog_get_context(obd, LLOG_CONFIG_REPL_CTXT);
663                 rc = llog_ioctl(ctxt, cmd, data);
664
665                 GOTO(out, rc);
666         }
667 #endif
668         /* ORIGinator context */
669         case OBD_IOC_DUMP_LOG: {
670                 ctxt = llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT);
671                 push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
672                 rc = class_config_dump_llog(ctxt, data->ioc_inlbuf1, NULL);
673                 pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
674                 if (rc)
675                         RETURN(rc);
676
677                 GOTO(out, rc);
678         }
679         default:
680                 CERROR("mgc_ioctl(): unrecognised ioctl %#x\n", cmd);
681                 GOTO(out, rc = -ENOTTY);
682         }
683 out:
684 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
685         MOD_DEC_USE_COUNT;
686 #else
687         module_put(THIS_MODULE);
688 #endif
689
690         return rc;
691 }
692 #endif
693
694 /* Send target_reg message to MGS */
695 static int mgc_target_register(struct obd_export *exp,
696                                struct mgs_target_info *mti)
697 {
698         struct ptlrpc_request *req;
699         struct mgs_target_info *req_mti, *rep_mti;
700         int size[] = { sizeof(struct ptlrpc_body), sizeof(*req_mti) };
701         int rep_size[] = { sizeof(struct ptlrpc_body), sizeof(*mti) };
702         int rc;
703         ENTRY;
704
705         req = ptlrpc_prep_req(class_exp2cliimp(exp), LUSTRE_MGS_VERSION,
706                               MGS_TARGET_REG, 2, size, NULL);
707         if (!req)
708                 RETURN(-ENOMEM);
709
710         req_mti = lustre_msg_buf(req->rq_reqmsg, REQ_REC_OFF, sizeof(*req_mti));
711         if (!req_mti)
712                 RETURN(-ENOMEM);
713         memcpy(req_mti, mti, sizeof(*req_mti));
714
715         ptlrpc_req_set_repsize(req, 2, rep_size);
716
717         CDEBUG(D_MGC, "register %s\n", mti->mti_svname);
718
719         rc = ptlrpc_queue_wait(req);
720         if (!rc) {
721                 rep_mti = lustre_swab_repbuf(req, REPLY_REC_OFF,
722                                              sizeof(*rep_mti),
723                                              lustre_swab_mgs_target_info);
724                 memcpy(mti, rep_mti, sizeof(*rep_mti));
725                 CDEBUG(D_MGC, "register %s got index = %d\n",
726                        mti->mti_svname, mti->mti_stripe_index);
727         }
728         ptlrpc_req_finished(req);
729
730         RETURN(rc);
731 }
732
733 int mgc_set_info_async(struct obd_export *exp, obd_count keylen,
734                        void *key, obd_count vallen, void *val,
735                        struct ptlrpc_request_set *set)
736 {
737         struct obd_import *imp = class_exp2cliimp(exp);
738         int rc = -EINVAL;
739         ENTRY;
740
741         /* Try to "recover" the initial connection; i.e. retry */
742         if (KEY_IS(KEY_INIT_RECOV)) {
743                 if (vallen != sizeof(int))
744                         RETURN(-EINVAL);
745                 spin_lock(&imp->imp_lock);
746                 imp->imp_initial_recov = *(int *)val;
747                 spin_unlock(&imp->imp_lock);
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                 spin_lock(&imp->imp_lock);
759                 imp->imp_initial_recov_bk = value > 0;
760                 /* Even after the initial connection, give up all comms if
761                    nobody answers the first time. */
762                 imp->imp_recon_bk = 1;
763                 spin_unlock(&imp->imp_lock);
764                 CDEBUG(D_MGC, "InitRecov %s %d/%d:d%d:i%d:r%d:or%d:%s\n",
765                        imp->imp_obd->obd_name, value, imp->imp_initial_recov,
766                        imp->imp_deactive, imp->imp_invalid,
767                        imp->imp_replayable, imp->imp_obd->obd_replayable,
768                        ptlrpc_import_state_name(imp->imp_state));
769                 /* Resurrect if we previously died */
770                 if (imp->imp_invalid || value > 1) {
771                         /* Force a new connect attempt */
772                         /* (can't put these in obdclass, module loop) */
773                         ptlrpc_invalidate_import(imp);
774                         /* Do a fresh connect next time by zeroing the handle */
775                         ptlrpc_disconnect_import(imp, 1);
776                         /* See client_disconnect_export */
777                         /* Allow reconnect attempts */
778                         imp->imp_obd->obd_no_recov = 0;
779                         /* Remove 'invalid' flag */
780                         ptlrpc_activate_import(imp);
781                         /* Attempt a new connect */
782                         ptlrpc_recover_import(imp, NULL);
783                 }
784                 RETURN(0);
785         }
786         /* FIXME move this to mgc_process_config */
787         if (KEY_IS("register_target")) {
788                 struct mgs_target_info *mti;
789                 if (vallen != sizeof(struct mgs_target_info))
790                         RETURN(-EINVAL);
791                 mti = (struct mgs_target_info *)val;
792                 CDEBUG(D_MGC, "register_target %s %#x\n",
793                        mti->mti_svname, mti->mti_flags);
794                 rc =  mgc_target_register(exp, mti);
795                 RETURN(rc);
796         }
797         if (KEY_IS("set_fs")) {
798                 struct super_block *sb = (struct super_block *)val;
799                 struct lustre_sb_info *lsi;
800                 if (vallen != sizeof(struct super_block))
801                         RETURN(-EINVAL);
802                 lsi = s2lsi(sb);
803                 rc = mgc_fs_setup(exp->exp_obd, sb, lsi->lsi_srv_mnt);
804                 if (rc) {
805                         CERROR("set_fs got %d\n", rc);
806                 }
807                 RETURN(rc);
808         }
809         if (KEY_IS("clear_fs")) {
810                 if (vallen != 0)
811                         RETURN(-EINVAL);
812                 rc = mgc_fs_cleanup(exp->exp_obd);
813                 if (rc) {
814                         CERROR("clear_fs got %d\n", rc);
815                 }
816                 RETURN(rc);
817         }
818
819         RETURN(rc);
820 }
821
822 static int mgc_import_event(struct obd_device *obd,
823                             struct obd_import *imp,
824                             enum obd_import_event event)
825 {
826         int rc = 0;
827
828         LASSERT(imp->imp_obd == obd);
829         CDEBUG(D_MGC, "import event %#x\n", event);
830
831         switch (event) {
832         case IMP_EVENT_DISCON:
833                 /* MGC imports should not wait for recovery */
834                 ptlrpc_invalidate_import(imp);
835                 break;
836         case IMP_EVENT_INACTIVE:
837                 break;
838         case IMP_EVENT_INVALIDATE: {
839                 struct ldlm_namespace *ns = obd->obd_namespace;
840                 ldlm_namespace_cleanup(ns, LDLM_FL_LOCAL_ONLY);
841                 break;
842         }
843         case IMP_EVENT_ACTIVE:
844                 LCONSOLE_WARN("%s: Reactivating import\n", obd->obd_name);
845                 break;
846         case IMP_EVENT_OCD:
847                 break;
848         default:
849                 CERROR("Unknown import event %#x\n", event);
850                 LBUG();
851         }
852         RETURN(rc);
853 }
854
855 static int mgc_llog_init(struct obd_device *obd, struct obd_llogs *llogs,
856                          struct obd_device *tgt, int count,
857                          struct llog_catid *logid, struct obd_uuid *uuid)
858 {
859         struct llog_ctxt *ctxt;
860         int rc;
861         ENTRY;
862
863         rc = llog_setup(obd, llogs, LLOG_CONFIG_ORIG_CTXT, tgt, 0, NULL,
864                         &llog_lvfs_ops);
865         if (rc)
866                 RETURN(rc);
867
868         rc = llog_setup(obd, llogs, LLOG_CONFIG_REPL_CTXT, tgt, 0, NULL,
869                         &llog_client_ops);
870         if (rc == 0) {
871                 ctxt = llog_get_context(obd, LLOG_CONFIG_REPL_CTXT);
872                 ctxt->loc_imp = obd->u.cli.cl_import;
873         }
874
875         RETURN(rc);
876 }
877
878 static int mgc_llog_finish(struct obd_device *obd, int count)
879 {
880         int rc;
881         ENTRY;
882
883         rc = llog_cleanup(llog_get_context(obd, LLOG_CONFIG_REPL_CTXT));
884         rc = llog_cleanup(llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT));
885
886         RETURN(rc);
887 }
888
889 /* identical to mgs_log_is_empty */
890 static int mgc_llog_is_empty(struct obd_device *obd, struct llog_ctxt *ctxt,
891                             char *name)
892 {
893         struct lvfs_run_ctxt saved;
894         struct llog_handle *llh;
895         int rc = 0;
896
897         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
898         rc = llog_create(ctxt, &llh, NULL, name);
899         if (rc == 0) {
900                 llog_init_handle(llh, LLOG_F_IS_PLAIN, NULL);
901                 rc = llog_get_size(llh);
902                 llog_close(llh);
903         }
904         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
905         /* header is record 1 */
906         return(rc <= 1);
907 }
908
909 static int mgc_copy_handler(struct llog_handle *llh, struct llog_rec_hdr *rec,
910                             void *data)
911 {
912         struct llog_rec_hdr local_rec = *rec;
913         struct llog_handle *local_llh = (struct llog_handle *)data;
914         char *cfg_buf = (char*) (rec + 1);
915         struct lustre_cfg *lcfg;
916         int rc = 0;
917         ENTRY;
918
919         /* Append all records */
920         local_rec.lrh_len -= sizeof(*rec) + sizeof(struct llog_rec_tail);
921         rc = llog_write_rec(local_llh, &local_rec, NULL, 0,
922                             (void *)cfg_buf, -1);
923
924         lcfg = (struct lustre_cfg *)cfg_buf;
925         CDEBUG(D_INFO, "idx=%d, rc=%d, len=%d, cmd %x %s %s\n",
926                rec->lrh_index, rc, rec->lrh_len, lcfg->lcfg_command,
927                lustre_cfg_string(lcfg, 0), lustre_cfg_string(lcfg, 1));
928
929         RETURN(rc);
930 }
931
932 /* Copy a remote log locally */
933 static int mgc_copy_llog(struct obd_device *obd, struct llog_ctxt *rctxt,
934                          struct llog_ctxt *lctxt, char *logname)
935 {
936         struct llog_handle *local_llh, *remote_llh;
937         struct obd_uuid *uuid;
938         char *temp_log;
939         int rc, rc2;
940         ENTRY;
941
942         /* Write new log to a temp name, then vfs_rename over logname
943            upon successful completion. */
944
945         OBD_ALLOC(temp_log, strlen(logname) + 1);
946         if (!temp_log) 
947                 RETURN(-ENOMEM);
948         sprintf(temp_log, "%sT", logname);
949
950         /* Make sure there's no old temp log */
951         rc = llog_create(lctxt, &local_llh, NULL, temp_log);
952         if (rc)
953                 GOTO(out, rc);
954         rc = llog_init_handle(local_llh, LLOG_F_IS_PLAIN, NULL);
955         if (rc) 
956                 GOTO(out, rc);
957         rc = llog_destroy(local_llh);
958         llog_free_handle(local_llh);
959         if (rc)
960                 GOTO(out, rc);
961
962         /* open local log */
963         rc = llog_create(lctxt, &local_llh, NULL, temp_log);
964         if (rc)
965                 GOTO(out, rc);
966
967         /* set the log header uuid for fun */
968         OBD_ALLOC_PTR(uuid);
969         obd_str2uuid(uuid, logname);
970         rc = llog_init_handle(local_llh, LLOG_F_IS_PLAIN, uuid);
971         OBD_FREE_PTR(uuid);
972         if (rc)
973                 GOTO(out_closel, rc);
974
975         /* open remote log */
976         rc = llog_create(rctxt, &remote_llh, NULL, logname);
977         if (rc)
978                 GOTO(out_closel, rc);
979         rc = llog_init_handle(remote_llh, LLOG_F_IS_PLAIN, NULL);
980         if (rc)
981                 GOTO(out_closer, rc);
982
983         /* Copy remote log */
984         rc = llog_process(remote_llh, mgc_copy_handler,(void *)local_llh, NULL);
985
986 out_closer:
987         rc2 = llog_close(remote_llh);
988         if (!rc)
989                 rc = rc2;
990 out_closel:
991         rc2 = llog_close(local_llh);
992         if (!rc)
993                 rc = rc2;
994
995         /* We've copied the remote log to the local temp log, now
996            replace the old local log with the temp log. */
997         if (!rc) {
998                 struct client_obd *cli = &obd->u.cli;
999                 LASSERT(cli);
1000                 LASSERT(cli->cl_mgc_configs_dir);
1001                 rc = lustre_rename(cli->cl_mgc_configs_dir, temp_log, logname);
1002         }
1003         CDEBUG(D_MGC, "Copied remote log %s (%d)\n", logname, rc);
1004 out:
1005         if (rc)
1006                 CERROR("Failed to copy remote log %s (%d)\n", logname, rc);
1007         OBD_FREE(temp_log, strlen(logname) + 1);
1008         RETURN(rc);
1009 }
1010
1011 DECLARE_MUTEX(llog_process_lock);
1012
1013 /* Get a config log from the MGS and process it.
1014    This func is called for both clients and servers. */
1015 static int mgc_process_log(struct obd_device *mgc,
1016                            struct config_llog_data *cld)
1017 {
1018         struct llog_ctxt *ctxt, *lctxt;
1019         struct lustre_handle lockh;
1020         struct client_obd *cli = &mgc->u.cli;
1021         struct lvfs_run_ctxt saved;
1022         struct lustre_sb_info *lsi;
1023         int rc = 0, rcl, flags = 0, must_pop = 0;
1024         ENTRY;
1025
1026         if (!cld || !cld->cld_cfg.cfg_sb) {
1027                 /* This should never happen */
1028                 CERROR("Missing cld, aborting log update\n");
1029                 RETURN(-EINVAL);
1030         }
1031         if (cld->cld_stopping)
1032                 RETURN(0);
1033
1034         OBD_FAIL_TIMEOUT(OBD_FAIL_MGC_PROCESS_LOG, 20);
1035
1036         lsi = s2lsi(cld->cld_cfg.cfg_sb);
1037
1038         CDEBUG(D_MGC, "Process log %s:%s from %d\n", cld->cld_logname,
1039                cld->cld_cfg.cfg_instance, cld->cld_cfg.cfg_last_idx + 1);
1040
1041         ctxt = llog_get_context(mgc, LLOG_CONFIG_REPL_CTXT);
1042         if (!ctxt) {
1043                 CERROR("missing llog context\n");
1044                 RETURN(-EINVAL);
1045         }
1046
1047         /* I don't want mutliple processes running process_log at once --
1048            sounds like badness.  It actually might be fine, as long as
1049            we're not trying to update from the same log
1050            simultaneously (in which case we should use a per-log sem.) */
1051         down(&llog_process_lock);
1052
1053         /* Get the cfg lock on the llog */
1054         rcl = mgc_enqueue(mgc->u.cli.cl_mgc_mgsexp, NULL, LDLM_PLAIN, NULL,
1055                           LCK_CR, &flags, NULL, NULL, NULL,
1056                           cld, 0, NULL, &lockh);
1057         if (rcl)
1058                 CDEBUG(D_MGC, "Can't get cfg lock: %d\n", rcl);
1059
1060         lctxt = llog_get_context(mgc, LLOG_CONFIG_ORIG_CTXT);
1061
1062         /* Copy the setup log locally if we can. Don't mess around if we're
1063            running an MGS though (logs are already local). */
1064         if (lctxt && lsi && (lsi->lsi_flags & LSI_SERVER) &&
1065             (lsi->lsi_srv_mnt == cli->cl_mgc_vfsmnt) &&
1066             !IS_MGS(lsi->lsi_ldd)) {
1067                 push_ctxt(&saved, &mgc->obd_lvfs_ctxt, NULL);
1068                 must_pop++;
1069                 if (rcl == 0)
1070                         /* Only try to copy log if we have the lock. */
1071                         rc = mgc_copy_llog(mgc, ctxt, lctxt, cld->cld_logname);
1072                 if (rcl || rc) {
1073                         if (mgc_llog_is_empty(mgc, lctxt, cld->cld_logname)) {
1074                                 LCONSOLE_ERROR_MSG(0x13a, "Failed to get MGS "
1075                                                    "log %s and no local copy."
1076                                                    "\n", cld->cld_logname);
1077                                 GOTO(out_pop, rc = -ENOTCONN);
1078                         }
1079                         LCONSOLE_WARN("Failed to get MGS log %s, using "
1080                                       "local copy.\n", cld->cld_logname);
1081                 }
1082                 /* Now, whether we copied or not, start using the local llog.
1083                    If we failed to copy, we'll start using whatever the old
1084                    log has. */
1085                 ctxt = lctxt;
1086         }
1087
1088         /* logname and instance info should be the same, so use our
1089            copy of the instance for the update.  The cfg_last_idx will
1090            be updated here. */
1091         rc = class_config_parse_llog(ctxt, cld->cld_logname, &cld->cld_cfg);
1092
1093  out_pop:
1094         if (must_pop)
1095                 pop_ctxt(&saved, &mgc->obd_lvfs_ctxt, NULL);
1096
1097         /* Now drop the lock so MGS can revoke it */
1098         if (!rcl) {
1099                 rcl = mgc_cancel(mgc->u.cli.cl_mgc_mgsexp, NULL,
1100                                  LCK_CR, &lockh);
1101                 if (rcl)
1102                         CERROR("Can't drop cfg lock: %d\n", rcl);
1103         }
1104
1105         CDEBUG(D_MGC, "%s: configuration from log '%s' %sed (%d).\n",
1106                mgc->obd_name, cld->cld_logname, rc ? "fail" : "succeed", rc);
1107
1108         up(&llog_process_lock);
1109
1110         RETURN(rc);
1111 }
1112
1113 static int mgc_process_config(struct obd_device *obd, obd_count len, void *buf)
1114 {
1115         struct lustre_cfg *lcfg = buf;
1116         int cmd;
1117         int rc = 0;
1118         ENTRY;
1119
1120         switch(cmd = lcfg->lcfg_command) {
1121         case LCFG_LOV_ADD_OBD: {
1122                 /* Add any new target, not just osts */
1123                 struct mgs_target_info *mti;
1124
1125                 if (LUSTRE_CFG_BUFLEN(lcfg, 1) !=
1126                     sizeof(struct mgs_target_info))
1127                         GOTO(out, rc = -EINVAL);
1128
1129                 mti = (struct mgs_target_info *)lustre_cfg_buf(lcfg, 1);
1130                 CDEBUG(D_MGC, "add_target %s %#x\n",
1131                        mti->mti_svname, mti->mti_flags);
1132                 rc = mgc_target_register(obd->u.cli.cl_mgc_mgsexp, mti);
1133                 break;
1134         }
1135         case LCFG_LOV_DEL_OBD:
1136                 /* Remove target from the fs? */
1137                 /* FIXME */
1138                 CERROR("lov_del_obd unimplemented\n");
1139                 rc = -ENOSYS;
1140                 break;
1141         case LCFG_LOG_START: {
1142                 struct config_llog_data *cld;
1143                 struct config_llog_instance *cfg;
1144                 struct super_block *sb;
1145                 char *logname = lustre_cfg_string(lcfg, 1);
1146                 cfg = (struct config_llog_instance *)lustre_cfg_buf(lcfg, 2);
1147                 sb = *(struct super_block **)lustre_cfg_buf(lcfg, 3);
1148
1149                 CDEBUG(D_MGC, "parse_log %s from %d\n", logname,
1150                        cfg->cfg_last_idx);
1151
1152                 /* We're only called through here on the initial mount */
1153                 rc = config_log_add(logname, cfg, sb);
1154                 if (rc)
1155                         break;
1156                 cld = config_log_find(logname, cfg);
1157                 if (IS_ERR(cld)) {
1158                         rc = PTR_ERR(cld);
1159                         break;
1160                 }
1161
1162                 /* COMPAT_146 */
1163                 /* FIXME only set this for old logs!  Right now this forces
1164                    us to always skip the "inside markers" check */
1165                 cld->cld_cfg.cfg_flags |= CFG_F_COMPAT146;
1166
1167                 rc = mgc_process_log(obd, cld);
1168                 config_log_put(cld);
1169
1170                 break;
1171         }
1172         case LCFG_LOG_END: {
1173                 struct config_llog_instance *cfg = NULL;
1174                 char *logname = lustre_cfg_string(lcfg, 1);
1175                 if (lcfg->lcfg_bufcount >= 2)
1176                         cfg = (struct config_llog_instance *)lustre_cfg_buf(
1177                                 lcfg, 2);
1178                 rc = config_log_end(logname, cfg);
1179                 break;
1180         }
1181         default: {
1182                 CERROR("Unknown command: %d\n", lcfg->lcfg_command);
1183                 GOTO(out, rc = -EINVAL);
1184
1185         }
1186         }
1187 out:
1188         RETURN(rc);
1189 }
1190
1191 struct obd_ops mgc_obd_ops = {
1192         .o_owner        = THIS_MODULE,
1193         .o_setup        = mgc_setup,
1194         .o_precleanup   = mgc_precleanup,
1195         .o_cleanup      = mgc_cleanup,
1196         .o_add_conn     = client_import_add_conn,
1197         .o_del_conn     = client_import_del_conn,
1198         .o_connect      = client_connect_import,
1199         .o_disconnect   = client_disconnect_export,
1200         //.o_enqueue      = mgc_enqueue,
1201         .o_cancel       = mgc_cancel,
1202         //.o_iocontrol    = mgc_iocontrol,
1203         .o_set_info_async = mgc_set_info_async,
1204         .o_import_event = mgc_import_event,
1205         .o_llog_init    = mgc_llog_init,
1206         .o_llog_finish  = mgc_llog_finish,
1207         .o_process_config = mgc_process_config,
1208 };
1209
1210 int __init mgc_init(void)
1211 {
1212         return class_register_type(&mgc_obd_ops, NULL, NULL,
1213                                    LUSTRE_MGC_NAME, NULL);
1214 }
1215
1216 #ifdef __KERNEL__
1217 static void /*__exit*/ mgc_exit(void)
1218 {
1219         class_unregister_type(LUSTRE_MGC_NAME);
1220 }
1221
1222 MODULE_AUTHOR("Cluster File Systems, Inc. <info@clusterfs.com>");
1223 MODULE_DESCRIPTION("Lustre Management Client");
1224 MODULE_LICENSE("GPL");
1225
1226 module_init(mgc_init);
1227 module_exit(mgc_exit);
1228 #endif