Whamcloud - gitweb
LU-580: update mgc llog process code
[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  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
30  * Use is subject to license terms.
31  *
32  * Copyright (c) 2011 Whamcloud, Inc.
33  *
34  */
35 /*
36  * This file is part of Lustre, http://www.lustre.org/
37  * Lustre is a trademark of Sun Microsystems, Inc.
38  *
39  * lustre/mgc/mgc_request.c
40  *
41  * Author: Nathan Rutman <nathan@clusterfs.com>
42  */
43
44 #ifndef EXPORT_SYMTAB
45 # define EXPORT_SYMTAB
46 #endif
47 #define DEBUG_SUBSYSTEM S_MGC
48 #define D_MGC D_CONFIG /*|D_WARNING*/
49
50 #ifdef __KERNEL__
51 # include <linux/module.h>
52 # include <linux/pagemap.h>
53 # include <linux/miscdevice.h>
54 # include <linux/init.h>
55 #else
56 # include <liblustre.h>
57 #endif
58
59 #include <obd_class.h>
60 #include <lustre_dlm.h>
61 #include <lprocfs_status.h>
62 #include <lustre_log.h>
63 #include <lustre_fsfilt.h>
64 #include <lustre_disk.h>
65 #include "mgc_internal.h"
66
67 static int mgc_name2resid(char *name, int len, struct ldlm_res_id *res_id,
68                           int type)
69 {
70         __u64 resname = 0;
71
72         if (len > 8) {
73                 CERROR("name too long: %s\n", name);
74                 return -EINVAL;
75         }
76         if (len <= 0) {
77                 CERROR("missing name: %s\n", name);
78                 return -EINVAL;
79         }
80         memcpy(&resname, name, len);
81
82         /* Always use the same endianness for the resid */
83         memset(res_id, 0, sizeof(*res_id));
84         res_id->name[0] = cpu_to_le64(resname);
85         /* XXX: unfortunately, sptlprc and config llog share one lock */
86         switch(type) {
87         case CONFIG_T_CONFIG:
88         case CONFIG_T_SPTLRPC:
89                 resname = 0;
90                 break;
91         default:
92                 LBUG();
93         }
94         res_id->name[1] = cpu_to_le64(resname);
95         CDEBUG(D_MGC, "log %s to resid "LPX64"/"LPX64" (%.8s)\n", name,
96                res_id->name[0], res_id->name[1], (char *)&res_id->name[0]);
97         return 0;
98 }
99
100 int mgc_fsname2resid(char *fsname, struct ldlm_res_id *res_id, int type)
101 {
102         /* fsname is at most 8 chars long, maybe contain "-".
103          * e.g. "lustre", "SUN-000" */
104         return mgc_name2resid(fsname, strlen(fsname), res_id, type);
105 }
106 EXPORT_SYMBOL(mgc_fsname2resid);
107
108 int mgc_logname2resid(char *logname, struct ldlm_res_id *res_id, int type)
109 {
110         char *name_end;
111         int len;
112
113         /* logname consists of "fsname-nodetype".
114          * e.g. "lustre-MDT0001", "SUN-000-client" */
115         name_end = strrchr(logname, '-');
116         LASSERT(name_end);
117         len = name_end - logname;
118         return mgc_name2resid(logname, len, res_id, type);
119 }
120
121 /********************** config llog list **********************/
122 static CFS_LIST_HEAD(config_llog_list);
123 static cfs_spinlock_t config_list_lock = CFS_SPIN_LOCK_UNLOCKED;
124
125 /* Take a reference to a config log */
126 static int config_log_get(struct config_llog_data *cld)
127 {
128         ENTRY;
129         cfs_atomic_inc(&cld->cld_refcount);
130         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
131                cfs_atomic_read(&cld->cld_refcount));
132         RETURN(0);
133 }
134
135 /* Drop a reference to a config log.  When no longer referenced,
136    we can free the config log data */
137 static void config_log_put(struct config_llog_data *cld)
138 {
139         ENTRY;
140
141         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
142                cfs_atomic_read(&cld->cld_refcount));
143         LASSERT(cfs_atomic_read(&cld->cld_refcount) > 0);
144
145         /* spinlock to make sure no item with 0 refcount in the list */
146         if (cfs_atomic_dec_and_lock(&cld->cld_refcount, &config_list_lock)) {
147                 cfs_list_del(&cld->cld_list_chain);
148                 cfs_spin_unlock(&config_list_lock);
149
150                 CDEBUG(D_MGC, "dropping config log %s\n", cld->cld_logname);
151
152                 if (cld->cld_sptlrpc)
153                         config_log_put(cld->cld_sptlrpc);
154                 if (cld_is_sptlrpc(cld))
155                         sptlrpc_conf_log_stop(cld->cld_logname);
156
157                 class_export_put(cld->cld_mgcexp);
158                 OBD_FREE(cld, sizeof(*cld) + strlen(cld->cld_logname) + 1);
159         }
160
161         EXIT;
162 }
163
164 /* Find a config log by name */
165 static
166 struct config_llog_data *config_log_find(char *logname,
167                                          struct config_llog_instance *cfg)
168 {
169         struct config_llog_data *cld;
170         struct config_llog_data *found = NULL;
171         void *                   instance;
172         ENTRY;
173
174         LASSERT(logname != NULL);
175
176         instance = cfg ? cfg->cfg_instance : NULL;
177         cfs_spin_lock(&config_list_lock);
178         cfs_list_for_each_entry(cld, &config_llog_list, cld_list_chain) {
179                 /* check if instance equals */
180                 if (instance != cld->cld_cfg.cfg_instance)
181                         continue;
182
183                 /* instance may be NULL, should check name */
184                 if (strcmp(logname, cld->cld_logname) == 0) {
185                         found = cld;
186                         break;
187                 }
188         }
189         if (found) {
190                 cfs_atomic_inc(&found->cld_refcount);
191                 LASSERT(found->cld_stopping == 0 || cld_is_sptlrpc(found) == 0);
192         }
193         cfs_spin_unlock(&config_list_lock);
194         RETURN(found);
195 }
196
197 static
198 struct config_llog_data *do_config_log_add(struct obd_device *obd,
199                                            char *logname,
200                                            int type,
201                                            struct config_llog_instance *cfg,
202                                            struct super_block *sb)
203 {
204         struct config_llog_data *cld;
205         int                      rc;
206         ENTRY;
207
208         CDEBUG(D_MGC, "do adding config log %s:%p\n", logname,
209                cfg ? cfg->cfg_instance : 0);
210
211         OBD_ALLOC(cld, sizeof(*cld) + strlen(logname) + 1);
212         if (!cld)
213                 RETURN(ERR_PTR(-ENOMEM));
214
215         strcpy(cld->cld_logname, logname);
216         if (cfg)
217                 cld->cld_cfg = *cfg;
218         cfs_mutex_init(&cld->cld_lock);
219         cld->cld_cfg.cfg_last_idx = 0;
220         cld->cld_cfg.cfg_flags = 0;
221         cld->cld_cfg.cfg_sb = sb;
222         cld->cld_type = type;
223         cfs_atomic_set(&cld->cld_refcount, 1);
224
225         /* Keep the mgc around until we are done */
226         cld->cld_mgcexp = class_export_get(obd->obd_self_export);
227
228         if (cld_is_sptlrpc(cld)) {
229                 sptlrpc_conf_log_start(logname);
230                 cld->cld_cfg.cfg_obdname = obd->obd_name;
231         }
232
233         rc = mgc_logname2resid(logname, &cld->cld_resid, type);
234
235         cfs_spin_lock(&config_list_lock);
236         cfs_list_add(&cld->cld_list_chain, &config_llog_list);
237         cfs_spin_unlock(&config_list_lock);
238
239         if (rc) {
240                 config_log_put(cld);
241                 RETURN(ERR_PTR(rc));
242         }
243
244         if (cld_is_sptlrpc(cld)) {
245                 rc = mgc_process_log(obd, cld);
246                 if (rc)
247                         CERROR("failed processing sptlrpc log: %d\n", rc);
248         }
249
250         RETURN(cld);
251 }
252
253 /** Add this log to the list of active logs watched by an MGC.
254  * Active means we're watching for updates.
255  * We have one active log per "mount" - client instance or servername.
256  * Each instance may be at a different point in the log.
257  */
258 static int config_log_add(struct obd_device *obd, char *logname,
259                           struct config_llog_instance *cfg,
260                           struct super_block *sb)
261 {
262         struct config_llog_data *cld;
263         struct config_llog_data *sptlrpc_cld;
264         char                     seclogname[32];
265         char                    *ptr;
266         ENTRY;
267
268         CDEBUG(D_MGC, "adding config log %s:%p\n", logname, cfg->cfg_instance);
269
270         /*
271          * for each regular log, the depended sptlrpc log name is
272          * <fsname>-sptlrpc. multiple regular logs may share one sptlrpc log.
273          */
274         ptr = strrchr(logname, '-');
275         if (ptr == NULL || ptr - logname > 8) {
276                 CERROR("logname %s is too long\n", logname);
277                 RETURN(-EINVAL);
278         }
279
280         memcpy(seclogname, logname, ptr - logname);
281         strcpy(seclogname + (ptr - logname), "-sptlrpc");
282
283         sptlrpc_cld = config_log_find(seclogname, NULL);
284         if (sptlrpc_cld == NULL) {
285                 sptlrpc_cld = do_config_log_add(obd, seclogname,
286                                                 CONFIG_T_SPTLRPC, NULL, NULL);
287                 if (IS_ERR(sptlrpc_cld)) {
288                         CERROR("can't create sptlrpc log: %s\n", seclogname);
289                         RETURN(PTR_ERR(sptlrpc_cld));
290                 }
291         }
292
293         cld = do_config_log_add(obd, logname, CONFIG_T_CONFIG, cfg, sb);
294         if (IS_ERR(cld)) {
295                 CERROR("can't create log: %s\n", logname);
296                 config_log_put(sptlrpc_cld);
297                 RETURN(PTR_ERR(cld));
298         }
299
300         cld->cld_sptlrpc = sptlrpc_cld;
301
302         RETURN(0);
303 }
304
305 CFS_DECLARE_MUTEX(llog_process_lock);
306
307 /** Stop watching for updates on this log.
308  */
309 static int config_log_end(char *logname, struct config_llog_instance *cfg)
310 {
311         struct config_llog_data *cld, *cld_sptlrpc = NULL;
312         int rc = 0;
313         ENTRY;
314
315         cld = config_log_find(logname, cfg);
316         if (cld == NULL)
317                 RETURN(-ENOENT);
318
319         cfs_mutex_lock(&cld->cld_lock);
320         /*
321          * if cld_stopping is set, it means we didn't start the log thus
322          * not owning the start ref. this can happen after previous umount:
323          * the cld still hanging there waiting for lock cancel, and we
324          * remount again but failed in the middle and call log_end without
325          * calling start_log.
326          */
327         if (unlikely(cld->cld_stopping)) {
328                 cfs_mutex_unlock(&cld->cld_lock);
329                 /* drop the ref from the find */
330                 config_log_put(cld);
331                 RETURN(rc);
332         }
333
334         cld->cld_stopping = 1;
335         cfs_mutex_unlock(&cld->cld_lock);
336
337         cfs_spin_lock(&config_list_lock);
338         cld_sptlrpc = cld->cld_sptlrpc;
339         cld->cld_sptlrpc = NULL;
340         cfs_spin_unlock(&config_list_lock);
341
342         if (cld_sptlrpc)
343                 config_log_put(cld_sptlrpc);
344
345         /* drop the ref from the find */
346         config_log_put(cld);
347         /* drop the start ref */
348         config_log_put(cld);
349
350         CDEBUG(D_MGC, "end config log %s (%d)\n", logname ? logname : "client",
351                rc);
352         RETURN(rc);
353 }
354
355 /* reenqueue any lost locks */
356 #define RQ_RUNNING 0x1
357 #define RQ_NOW     0x2
358 #define RQ_LATER   0x4
359 #define RQ_STOP    0x8
360 static int                    rq_state = 0;
361 static cfs_waitq_t            rq_waitq;
362 static CFS_DECLARE_COMPLETION(rq_exit);
363
364 static void do_requeue(struct config_llog_data *cld)
365 {
366         ENTRY;
367         LASSERT(cfs_atomic_read(&cld->cld_refcount) > 0);
368
369         /* Do not run mgc_process_log on a disconnected export or an
370            export which is being disconnected. Take the client
371            semaphore to make the check non-racy. */
372         cfs_down_read(&cld->cld_mgcexp->exp_obd->u.cli.cl_sem);
373         if (cld->cld_mgcexp->exp_obd->u.cli.cl_conn_count != 0) {
374                 CDEBUG(D_MGC, "updating log %s\n", cld->cld_logname);
375                 mgc_process_log(cld->cld_mgcexp->exp_obd, cld);
376         } else {
377                 CDEBUG(D_MGC, "disconnecting, won't update log %s\n",
378                        cld->cld_logname);
379         }
380         cfs_up_read(&cld->cld_mgcexp->exp_obd->u.cli.cl_sem);
381
382         EXIT;
383 }
384
385 /* this timeout represents how many seconds MGC should wait before
386  * requeue config and recover lock to the MGS. We need to randomize this
387  * in order to not flood the MGS.
388  */
389 #define MGC_TIMEOUT_MIN_SECONDS   5
390 #define MGC_TIMEOUT_RAND_CENTISEC 0x1ff /* ~500 */
391
392 static int mgc_requeue_thread(void *data)
393 {
394         char name[] = "ll_cfg_requeue";
395         int rc = 0;
396         ENTRY;
397
398         cfs_daemonize(name);
399
400         CDEBUG(D_MGC, "Starting requeue thread\n");
401
402         /* Keep trying failed locks periodically */
403         cfs_spin_lock(&config_list_lock);
404         rq_state |= RQ_RUNNING;
405         while (1) {
406                 struct l_wait_info lwi;
407                 struct config_llog_data *cld, *cld_prev;
408                 int rand = cfs_rand() & MGC_TIMEOUT_RAND_CENTISEC;
409                 int stopped = !!(rq_state & RQ_STOP);
410                 int to;
411
412                 /* Any new or requeued lostlocks will change the state */
413                 rq_state &= ~(RQ_NOW | RQ_LATER);
414                 cfs_spin_unlock(&config_list_lock);
415
416                 /* Always wait a few seconds to allow the server who
417                    caused the lock revocation to finish its setup, plus some
418                    random so everyone doesn't try to reconnect at once. */
419                 to = MGC_TIMEOUT_MIN_SECONDS * CFS_HZ;
420                 to += rand * CFS_HZ / 100; /* rand is centi-seconds */
421                 lwi = LWI_TIMEOUT(to, NULL, NULL);
422                 l_wait_event(rq_waitq, rq_state & RQ_STOP, &lwi);
423
424                 /*
425                  * iterate & processing through the list. for each cld, process
426                  * its depending sptlrpc cld firstly (if any) and then itself.
427                  *
428                  * it's guaranteed any item in the list must have
429                  * reference > 0; and if cld_lostlock is set, at
430                  * least one reference is taken by the previous enqueue.
431                  */
432                 cld_prev = NULL;
433
434                 cfs_spin_lock(&config_list_lock);
435                 cfs_list_for_each_entry(cld, &config_llog_list,
436                                         cld_list_chain) {
437                         if (!cld->cld_lostlock)
438                                 continue;
439
440                         cfs_spin_unlock(&config_list_lock);
441
442                         LASSERT(cfs_atomic_read(&cld->cld_refcount) > 0);
443
444                         /* Whether we enqueued again or not in mgc_process_log,
445                          * we're done with the ref from the old enqueue */
446                         if (cld_prev)
447                                 config_log_put(cld_prev);
448                         cld_prev = cld;
449
450                         cld->cld_lostlock = 0;
451                         if (likely(!stopped))
452                                 do_requeue(cld);
453
454                         cfs_spin_lock(&config_list_lock);
455                 }
456                 cfs_spin_unlock(&config_list_lock);
457                 if (cld_prev)
458                         config_log_put(cld_prev);
459
460                 /* break after scanning the list so that we can drop
461                  * refcount to losing lock clds */
462                 if (unlikely(stopped)) {
463                         cfs_spin_lock(&config_list_lock);
464                         break;
465                 }
466
467                 /* Wait a bit to see if anyone else needs a requeue */
468                 lwi = (struct l_wait_info) { 0 };
469                 l_wait_event(rq_waitq, rq_state & (RQ_NOW | RQ_STOP),
470                              &lwi);
471                 cfs_spin_lock(&config_list_lock);
472         }
473         /* spinlock and while guarantee RQ_NOW and RQ_LATER are not set */
474         rq_state &= ~RQ_RUNNING;
475         cfs_spin_unlock(&config_list_lock);
476
477         cfs_complete(&rq_exit);
478
479         CDEBUG(D_MGC, "Ending requeue thread\n");
480         RETURN(rc);
481 }
482
483 /* Add a cld to the list to requeue.  Start the requeue thread if needed.
484    We are responsible for dropping the config log reference from here on out. */
485 static void mgc_requeue_add(struct config_llog_data *cld)
486 {
487         ENTRY;
488
489         CDEBUG(D_INFO, "log %s: requeue (r=%d sp=%d st=%x)\n",
490                cld->cld_logname, cfs_atomic_read(&cld->cld_refcount),
491                cld->cld_stopping, rq_state);
492         LASSERT(cfs_atomic_read(&cld->cld_refcount) > 0);
493
494         cfs_mutex_lock(&cld->cld_lock);
495         if (cld->cld_stopping || cld->cld_lostlock) {
496                 cfs_mutex_unlock(&cld->cld_lock);
497                 RETURN_EXIT;
498         }
499         /* this refcount will be released in mgc_requeue_thread. */
500         config_log_get(cld);
501         cld->cld_lostlock = 1;
502         cfs_mutex_unlock(&cld->cld_lock);
503
504         /* Hold lock for rq_state */
505         cfs_spin_lock(&config_list_lock);
506         if (rq_state & RQ_STOP) {
507                 cfs_spin_unlock(&config_list_lock);
508                 cld->cld_lostlock = 0;
509                 config_log_put(cld);
510         } else {
511                 rq_state |= RQ_NOW;
512                 cfs_spin_unlock(&config_list_lock);
513                 cfs_waitq_signal(&rq_waitq);
514         }
515         EXIT;
516 }
517
518 /********************** class fns **********************/
519
520 static int mgc_fs_setup(struct obd_device *obd, struct super_block *sb,
521                         struct vfsmount *mnt)
522 {
523         struct lvfs_run_ctxt saved;
524         struct lustre_sb_info *lsi = s2lsi(sb);
525         struct client_obd *cli = &obd->u.cli;
526         struct dentry *dentry;
527         char *label;
528         int err = 0;
529         ENTRY;
530
531         LASSERT(lsi);
532         LASSERT(lsi->lsi_srv_mnt == mnt);
533
534         /* The mgc fs exclusion sem. Only one fs can be setup at a time. */
535         cfs_down(&cli->cl_mgc_sem);
536
537         cfs_cleanup_group_info();
538
539         obd->obd_fsops = fsfilt_get_ops(MT_STR(lsi->lsi_ldd));
540         if (IS_ERR(obd->obd_fsops)) {
541                 cfs_up(&cli->cl_mgc_sem);
542                 CERROR("No fstype %s rc=%ld\n", MT_STR(lsi->lsi_ldd),
543                        PTR_ERR(obd->obd_fsops));
544                 RETURN(PTR_ERR(obd->obd_fsops));
545         }
546
547         cli->cl_mgc_vfsmnt = mnt;
548         fsfilt_setup(obd, mnt->mnt_sb);
549
550         OBD_SET_CTXT_MAGIC(&obd->obd_lvfs_ctxt);
551         obd->obd_lvfs_ctxt.pwdmnt = mnt;
552         obd->obd_lvfs_ctxt.pwd = mnt->mnt_root;
553         obd->obd_lvfs_ctxt.fs = get_ds();
554
555         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
556         dentry = ll_lookup_one_len(MOUNT_CONFIGS_DIR, cfs_fs_pwd(current->fs),
557                                    strlen(MOUNT_CONFIGS_DIR));
558         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
559         if (IS_ERR(dentry)) {
560                 err = PTR_ERR(dentry);
561                 CERROR("cannot lookup %s directory: rc = %d\n",
562                        MOUNT_CONFIGS_DIR, err);
563                 GOTO(err_ops, err);
564         }
565         cli->cl_mgc_configs_dir = dentry;
566
567         /* We take an obd ref to insure that we can't get to mgc_cleanup
568            without calling mgc_fs_cleanup first. */
569         class_incref(obd, "mgc_fs", obd);
570
571         label = fsfilt_get_label(obd, mnt->mnt_sb);
572         if (label)
573                 CDEBUG(D_MGC, "MGC using disk labelled=%s\n", label);
574
575         /* We keep the cl_mgc_sem until mgc_fs_cleanup */
576         RETURN(0);
577
578 err_ops:
579         fsfilt_put_ops(obd->obd_fsops);
580         obd->obd_fsops = NULL;
581         cli->cl_mgc_vfsmnt = NULL;
582         cfs_up(&cli->cl_mgc_sem);
583         RETURN(err);
584 }
585
586 static int mgc_fs_cleanup(struct obd_device *obd)
587 {
588         struct client_obd *cli = &obd->u.cli;
589         int rc = 0;
590         ENTRY;
591
592         LASSERT(cli->cl_mgc_vfsmnt != NULL);
593
594         if (cli->cl_mgc_configs_dir != NULL) {
595                 struct lvfs_run_ctxt saved;
596                 push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
597                 l_dput(cli->cl_mgc_configs_dir);
598                 cli->cl_mgc_configs_dir = NULL;
599                 pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
600                 class_decref(obd, "mgc_fs", obd);
601         }
602
603         cli->cl_mgc_vfsmnt = NULL;
604         if (obd->obd_fsops)
605                 fsfilt_put_ops(obd->obd_fsops);
606
607         cfs_up(&cli->cl_mgc_sem);
608
609         RETURN(rc);
610 }
611
612 static cfs_atomic_t mgc_count = CFS_ATOMIC_INIT(0);
613 static int mgc_precleanup(struct obd_device *obd, enum obd_cleanup_stage stage)
614 {
615         int rc = 0;
616         ENTRY;
617
618         switch (stage) {
619         case OBD_CLEANUP_EARLY:
620                 break;
621         case OBD_CLEANUP_EXPORTS:
622                 if (cfs_atomic_dec_and_test(&mgc_count)) {
623                         int running;
624                         /* stop requeue thread */
625                         cfs_spin_lock(&config_list_lock);
626                         running = rq_state & RQ_RUNNING;
627                         if (running)
628                                 rq_state |= RQ_STOP;
629                         cfs_spin_unlock(&config_list_lock);
630                         if (running) {
631                                 cfs_waitq_signal(&rq_waitq);
632                                 cfs_wait_for_completion(&rq_exit);
633                         }
634                 }
635                 obd_cleanup_client_import(obd);
636                 rc = obd_llog_finish(obd, 0);
637                 if (rc != 0)
638                         CERROR("failed to cleanup llogging subsystems\n");
639                 break;
640         }
641         RETURN(rc);
642 }
643
644 static int mgc_cleanup(struct obd_device *obd)
645 {
646         struct client_obd *cli = &obd->u.cli;
647         int rc;
648         ENTRY;
649
650         LASSERT(cli->cl_mgc_vfsmnt == NULL);
651
652         /* COMPAT_146 - old config logs may have added profiles we don't
653            know about */
654         if (obd->obd_type->typ_refcnt <= 1)
655                 /* Only for the last mgc */
656                 class_del_profiles();
657
658         lprocfs_obd_cleanup(obd);
659         ptlrpcd_decref();
660
661         rc = client_obd_cleanup(obd);
662         RETURN(rc);
663 }
664
665 static int mgc_setup(struct obd_device *obd, struct lustre_cfg *lcfg)
666 {
667         struct lprocfs_static_vars lvars;
668         int rc;
669         ENTRY;
670
671         ptlrpcd_addref();
672
673         rc = client_obd_setup(obd, lcfg);
674         if (rc)
675                 GOTO(err_decref, rc);
676
677         rc = obd_llog_init(obd, &obd->obd_olg, obd, NULL);
678         if (rc) {
679                 CERROR("failed to setup llogging subsystems\n");
680                 GOTO(err_cleanup, rc);
681         }
682
683         lprocfs_mgc_init_vars(&lvars);
684         lprocfs_obd_setup(obd, lvars.obd_vars);
685         sptlrpc_lprocfs_cliobd_attach(obd);
686
687         if (cfs_atomic_inc_return(&mgc_count) == 1) {
688                 rq_state = 0;
689                 cfs_waitq_init(&rq_waitq);
690
691                 /* start requeue thread */
692                 rc = cfs_create_thread(mgc_requeue_thread, NULL,
693                                        CFS_DAEMON_FLAGS);
694                 if (rc < 0) {
695                         CERROR("%s: Cannot start requeue thread (%d),"
696                                "no more log updates!\n",
697                                obd->obd_name, rc);
698                         GOTO(err_cleanup, rc);
699                 }
700                 /* rc is the pid of mgc_requeue_thread. */
701                 rc = 0;
702         }
703
704         RETURN(rc);
705
706 err_cleanup:
707         client_obd_cleanup(obd);
708 err_decref:
709         ptlrpcd_decref();
710         RETURN(rc);
711 }
712
713 /* based on ll_mdc_blocking_ast */
714 static int mgc_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
715                             void *data, int flag)
716 {
717         struct lustre_handle lockh;
718         struct config_llog_data *cld = (struct config_llog_data *)data;
719         int rc = 0;
720         ENTRY;
721
722         switch (flag) {
723         case LDLM_CB_BLOCKING:
724                 /* mgs wants the lock, give it up... */
725                 LDLM_DEBUG(lock, "MGC blocking CB");
726                 ldlm_lock2handle(lock, &lockh);
727                 rc = ldlm_cli_cancel(&lockh);
728                 break;
729         case LDLM_CB_CANCELING:
730                 /* We've given up the lock, prepare ourselves to update. */
731                 LDLM_DEBUG(lock, "MGC cancel CB");
732
733                 CDEBUG(D_MGC, "Lock res "LPX64" (%.8s)\n",
734                        lock->l_resource->lr_name.name[0],
735                        (char *)&lock->l_resource->lr_name.name[0]);
736
737                 if (!cld) {
738                         CDEBUG(D_INFO, "missing data, won't requeue\n");
739                         break;
740                 }
741
742                 /* held at mgc_process_log(). */
743                 LASSERT(cfs_atomic_read(&cld->cld_refcount) > 0);
744                 /* Are we done with this log? */
745                 if (cld->cld_stopping) {
746                         CDEBUG(D_MGC, "log %s: stopping, won't requeue\n",
747                                cld->cld_logname);
748                         config_log_put(cld);
749                         break;
750                 }
751                 /* Make sure not to re-enqueue when the mgc is stopping
752                    (we get called from client_disconnect_export) */
753                 if (!lock->l_conn_export ||
754                     !lock->l_conn_export->exp_obd->u.cli.cl_conn_count) {
755                         CDEBUG(D_MGC, "log %.8s: disconnecting, won't requeue\n",
756                                cld->cld_logname);
757                         config_log_put(cld);
758                         break;
759                 }
760
761                 /* Re-enqueue now */
762                 mgc_requeue_add(cld);
763                 config_log_put(cld);
764                 break;
765         default:
766                 LBUG();
767         }
768
769         RETURN(rc);
770 }
771
772 /* Not sure where this should go... */
773 #define  MGC_ENQUEUE_LIMIT 50
774 #define  MGC_TARGET_REG_LIMIT 10
775 #define  MGC_SEND_PARAM_LIMIT 10
776
777 /* Send parameter to MGS*/
778 static int mgc_set_mgs_param(struct obd_export *exp,
779                              struct mgs_send_param *msp)
780 {
781         struct ptlrpc_request *req;
782         struct mgs_send_param *req_msp, *rep_msp;
783         int rc;
784         ENTRY;
785
786         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
787                                         &RQF_MGS_SET_INFO, LUSTRE_MGS_VERSION,
788                                         MGS_SET_INFO);
789         if (!req)
790                 RETURN(-ENOMEM);
791
792         req_msp = req_capsule_client_get(&req->rq_pill, &RMF_MGS_SEND_PARAM);
793         if (!req_msp) {
794                 ptlrpc_req_finished(req);
795                 RETURN(-ENOMEM);
796         }
797
798         memcpy(req_msp, msp, sizeof(*req_msp));
799         ptlrpc_request_set_replen(req);
800
801         /* Limit how long we will wait for the enqueue to complete */
802         req->rq_delay_limit = MGC_SEND_PARAM_LIMIT;
803         rc = ptlrpc_queue_wait(req);
804         if (!rc) {
805                 rep_msp = req_capsule_server_get(&req->rq_pill, &RMF_MGS_SEND_PARAM);
806                 memcpy(msp, rep_msp, sizeof(*rep_msp));
807         }
808
809         ptlrpc_req_finished(req);
810
811         RETURN(rc);
812 }
813
814 /* Take a config lock so we can get cancel notifications */
815 static int mgc_enqueue(struct obd_export *exp, struct lov_stripe_md *lsm,
816                        __u32 type, ldlm_policy_data_t *policy, __u32 mode,
817                        int *flags, void *bl_cb, void *cp_cb, void *gl_cb,
818                        void *data, __u32 lvb_len, void *lvb_swabber,
819                        struct lustre_handle *lockh)
820 {
821         struct config_llog_data *cld = (struct config_llog_data *)data;
822         struct ldlm_enqueue_info einfo = { type, mode, mgc_blocking_ast,
823                          ldlm_completion_ast, NULL, NULL, NULL };
824         struct ptlrpc_request *req;
825         int short_limit = cld_is_sptlrpc(cld);
826         int rc;
827         ENTRY;
828
829         CDEBUG(D_MGC, "Enqueue for %s (res "LPX64")\n", cld->cld_logname,
830                cld->cld_resid.name[0]);
831
832         /* We need a callback for every lockholder, so don't try to
833            ldlm_lock_match (see rev 1.1.2.11.2.47) */
834         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
835                                         &RQF_LDLM_ENQUEUE, LUSTRE_DLM_VERSION,
836                                         LDLM_ENQUEUE);
837         if (req == NULL)
838                 RETURN(-ENOMEM);
839         ptlrpc_request_set_replen(req);
840
841         /* check if this is server or client */
842         if (cld->cld_cfg.cfg_sb) {
843                 struct lustre_sb_info *lsi = s2lsi(cld->cld_cfg.cfg_sb);
844                 if (lsi && (lsi->lsi_flags & LSI_SERVER))
845                         short_limit = 1;
846         }
847         /* Limit how long we will wait for the enqueue to complete */
848         req->rq_delay_limit = short_limit ? 5 : MGC_ENQUEUE_LIMIT;
849         rc = ldlm_cli_enqueue(exp, &req, &einfo, &cld->cld_resid, NULL, flags,
850                               NULL, 0, lockh, 0);
851         /* A failed enqueue should still call the mgc_blocking_ast,
852            where it will be requeued if needed ("grant failed"). */
853         ptlrpc_req_finished(req);
854         RETURN(rc);
855 }
856
857 static int mgc_cancel(struct obd_export *exp, struct lov_stripe_md *md,
858                       __u32 mode, struct lustre_handle *lockh)
859 {
860         ENTRY;
861
862         ldlm_lock_decref(lockh, mode);
863
864         RETURN(0);
865 }
866
867 static void mgc_notify_active(struct obd_device *unused)
868 {
869         /* wakeup mgc_requeue_thread to requeue mgc lock */
870         cfs_spin_lock(&config_list_lock);
871         rq_state |= RQ_NOW;
872         cfs_spin_unlock(&config_list_lock);
873         cfs_waitq_signal(&rq_waitq);
874
875         /* TODO: Help the MGS rebuild nidtbl. -jay */
876 }
877
878 /* Send target_reg message to MGS */
879 static int mgc_target_register(struct obd_export *exp,
880                                struct mgs_target_info *mti)
881 {
882         struct ptlrpc_request  *req;
883         struct mgs_target_info *req_mti, *rep_mti;
884         int                     rc;
885         ENTRY;
886
887         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
888                                         &RQF_MGS_TARGET_REG, LUSTRE_MGS_VERSION,
889                                         MGS_TARGET_REG);
890         if (req == NULL)
891                 RETURN(-ENOMEM);
892
893         req_mti = req_capsule_client_get(&req->rq_pill, &RMF_MGS_TARGET_INFO);
894         if (!req_mti) {
895                 ptlrpc_req_finished(req);
896                 RETURN(-ENOMEM);
897         }
898
899         memcpy(req_mti, mti, sizeof(*req_mti));
900         ptlrpc_request_set_replen(req);
901         CDEBUG(D_MGC, "register %s\n", mti->mti_svname);
902         /* Limit how long we will wait for the enqueue to complete */
903         req->rq_delay_limit = MGC_TARGET_REG_LIMIT;
904
905         rc = ptlrpc_queue_wait(req);
906         if (!rc) {
907                 rep_mti = req_capsule_server_get(&req->rq_pill,
908                                                  &RMF_MGS_TARGET_INFO);
909                 memcpy(mti, rep_mti, sizeof(*rep_mti));
910                 CDEBUG(D_MGC, "register %s got index = %d\n",
911                        mti->mti_svname, mti->mti_stripe_index);
912         }
913         ptlrpc_req_finished(req);
914
915         RETURN(rc);
916 }
917
918 int mgc_set_info_async(struct obd_export *exp, obd_count keylen,
919                        void *key, obd_count vallen, void *val,
920                        struct ptlrpc_request_set *set)
921 {
922         int rc = -EINVAL;
923         ENTRY;
924
925         /* Turn off initial_recov after we try all backup servers once */
926         if (KEY_IS(KEY_INIT_RECOV_BACKUP)) {
927                 struct obd_import *imp = class_exp2cliimp(exp);
928                 int value;
929                 if (vallen != sizeof(int))
930                         RETURN(-EINVAL);
931                 value = *(int *)val;
932                 CDEBUG(D_MGC, "InitRecov %s %d/d%d:i%d:r%d:or%d:%s\n",
933                        imp->imp_obd->obd_name, value,
934                        imp->imp_deactive, imp->imp_invalid,
935                        imp->imp_replayable, imp->imp_obd->obd_replayable,
936                        ptlrpc_import_state_name(imp->imp_state));
937                 /* Resurrect if we previously died */
938                 if ((imp->imp_state != LUSTRE_IMP_FULL &&
939                      imp->imp_state != LUSTRE_IMP_NEW) || value > 1)
940                         ptlrpc_reconnect_import(imp);
941                 RETURN(0);
942         }
943         /* FIXME move this to mgc_process_config */
944         if (KEY_IS(KEY_REGISTER_TARGET)) {
945                 struct mgs_target_info *mti;
946                 if (vallen != sizeof(struct mgs_target_info))
947                         RETURN(-EINVAL);
948                 mti = (struct mgs_target_info *)val;
949                 CDEBUG(D_MGC, "register_target %s %#x\n",
950                        mti->mti_svname, mti->mti_flags);
951                 rc =  mgc_target_register(exp, mti);
952                 RETURN(rc);
953         }
954         if (KEY_IS(KEY_SET_FS)) {
955                 struct super_block *sb = (struct super_block *)val;
956                 struct lustre_sb_info *lsi;
957                 if (vallen != sizeof(struct super_block))
958                         RETURN(-EINVAL);
959                 lsi = s2lsi(sb);
960                 rc = mgc_fs_setup(exp->exp_obd, sb, lsi->lsi_srv_mnt);
961                 if (rc) {
962                         CERROR("set_fs got %d\n", rc);
963                 }
964                 RETURN(rc);
965         }
966         if (KEY_IS(KEY_CLEAR_FS)) {
967                 if (vallen != 0)
968                         RETURN(-EINVAL);
969                 rc = mgc_fs_cleanup(exp->exp_obd);
970                 if (rc) {
971                         CERROR("clear_fs got %d\n", rc);
972                 }
973                 RETURN(rc);
974         }
975         if (KEY_IS(KEY_SET_INFO)) {
976                 struct mgs_send_param *msp;
977
978                 msp = (struct mgs_send_param *)val;
979                 rc =  mgc_set_mgs_param(exp, msp);
980                 RETURN(rc);
981         }
982         if (KEY_IS(KEY_MGSSEC)) {
983                 struct client_obd     *cli = &exp->exp_obd->u.cli;
984                 struct sptlrpc_flavor  flvr;
985
986                 /*
987                  * empty string means using current flavor, if which haven't
988                  * been set yet, set it as null.
989                  *
990                  * if flavor has been set previously, check the asking flavor
991                  * must match the existing one.
992                  */
993                 if (vallen == 0) {
994                         if (cli->cl_flvr_mgc.sf_rpc != SPTLRPC_FLVR_INVALID)
995                                 RETURN(0);
996                         val = "null";
997                         vallen = 4;
998                 }
999
1000                 rc = sptlrpc_parse_flavor(val, &flvr);
1001                 if (rc) {
1002                         CERROR("invalid sptlrpc flavor %s to MGS\n",
1003                                (char *) val);
1004                         RETURN(rc);
1005                 }
1006
1007                 /*
1008                  * caller already hold a mutex
1009                  */
1010                 if (cli->cl_flvr_mgc.sf_rpc == SPTLRPC_FLVR_INVALID) {
1011                         cli->cl_flvr_mgc = flvr;
1012                 } else if (memcmp(&cli->cl_flvr_mgc, &flvr,
1013                                   sizeof(flvr)) != 0) {
1014                         char    str[20];
1015
1016                         sptlrpc_flavor2name(&cli->cl_flvr_mgc,
1017                                             str, sizeof(str));
1018                         LCONSOLE_ERROR("asking sptlrpc flavor %s to MGS but "
1019                                        "currently %s is in use\n",
1020                                        (char *) val, str);
1021                         rc = -EPERM;
1022                 }
1023                 RETURN(rc);
1024         }
1025
1026         RETURN(rc);
1027 }
1028
1029 static int mgc_import_event(struct obd_device *obd,
1030                             struct obd_import *imp,
1031                             enum obd_import_event event)
1032 {
1033         int rc = 0;
1034
1035         LASSERT(imp->imp_obd == obd);
1036         CDEBUG(D_MGC, "import event %#x\n", event);
1037
1038         switch (event) {
1039         case IMP_EVENT_DISCON:
1040                 /* MGC imports should not wait for recovery */
1041                 break;
1042         case IMP_EVENT_INACTIVE:
1043                 break;
1044         case IMP_EVENT_INVALIDATE: {
1045                 struct ldlm_namespace *ns = obd->obd_namespace;
1046                 ldlm_namespace_cleanup(ns, LDLM_FL_LOCAL_ONLY);
1047                 break;
1048         }
1049         case IMP_EVENT_ACTIVE:
1050                 LCONSOLE_WARN("%s: Reactivating import\n", obd->obd_name);
1051                 /* Clearing obd_no_recov allows us to continue pinging */
1052                 obd->obd_no_recov = 0;
1053                 mgc_notify_active(obd);
1054                 break;
1055         case IMP_EVENT_OCD:
1056                 break;
1057         case IMP_EVENT_DEACTIVATE:
1058         case IMP_EVENT_ACTIVATE:
1059                 break;
1060         default:
1061                 CERROR("Unknown import event %#x\n", event);
1062                 LBUG();
1063         }
1064         RETURN(rc);
1065 }
1066
1067 static int mgc_llog_init(struct obd_device *obd, struct obd_llog_group *olg,
1068                          struct obd_device *tgt, int *index)
1069 {
1070         struct llog_ctxt *ctxt;
1071         int rc;
1072         ENTRY;
1073
1074         LASSERT(olg == &obd->obd_olg);
1075
1076         rc = llog_setup(obd, olg, LLOG_CONFIG_ORIG_CTXT, tgt, 0, NULL,
1077                         &llog_lvfs_ops);
1078         if (rc)
1079                 RETURN(rc);
1080
1081         rc = llog_setup(obd, olg, LLOG_CONFIG_REPL_CTXT, tgt, 0, NULL,
1082                         &llog_client_ops);
1083         if (rc == 0) {
1084                 ctxt = llog_get_context(obd, LLOG_CONFIG_REPL_CTXT);
1085                 if (!ctxt) {
1086                         ctxt = llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT);
1087                         if (ctxt)
1088                                 llog_cleanup(ctxt);
1089                         RETURN(-ENODEV);
1090                 }
1091                 llog_initiator_connect(ctxt);
1092                 llog_ctxt_put(ctxt);
1093         } else {
1094                 ctxt = llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT);
1095                 if (ctxt)
1096                         llog_cleanup(ctxt);
1097         }
1098
1099         RETURN(rc);
1100 }
1101
1102 static int mgc_llog_finish(struct obd_device *obd, int count)
1103 {
1104         struct llog_ctxt *ctxt;
1105         int rc = 0, rc2 = 0;
1106         ENTRY;
1107
1108         ctxt = llog_get_context(obd, LLOG_CONFIG_REPL_CTXT);
1109         if (ctxt)
1110                 rc = llog_cleanup(ctxt);
1111
1112         ctxt = llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT);
1113         if (ctxt)
1114                 rc2 = llog_cleanup(ctxt);
1115
1116         if (!rc)
1117                 rc = rc2;
1118
1119         RETURN(rc);
1120 }
1121
1122 /* identical to mgs_log_is_empty */
1123 static int mgc_llog_is_empty(struct obd_device *obd, struct llog_ctxt *ctxt,
1124                             char *name)
1125 {
1126         struct lvfs_run_ctxt saved;
1127         struct llog_handle *llh;
1128         int rc = 0;
1129
1130         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
1131         rc = llog_create(ctxt, &llh, NULL, name);
1132         if (rc == 0) {
1133                 llog_init_handle(llh, LLOG_F_IS_PLAIN, NULL);
1134                 rc = llog_get_size(llh);
1135                 llog_close(llh);
1136         }
1137         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
1138         /* header is record 1 */
1139         return(rc <= 1);
1140 }
1141
1142 static int mgc_copy_handler(struct llog_handle *llh, struct llog_rec_hdr *rec,
1143                             void *data)
1144 {
1145         struct llog_rec_hdr local_rec = *rec;
1146         struct llog_handle *local_llh = (struct llog_handle *)data;
1147         char *cfg_buf = (char*) (rec + 1);
1148         struct lustre_cfg *lcfg;
1149         int rc = 0;
1150         ENTRY;
1151
1152         /* Append all records */
1153         local_rec.lrh_len -= sizeof(*rec) + sizeof(struct llog_rec_tail);
1154         rc = llog_write_rec(local_llh, &local_rec, NULL, 0,
1155                             (void *)cfg_buf, -1);
1156
1157         lcfg = (struct lustre_cfg *)cfg_buf;
1158         CDEBUG(D_INFO, "idx=%d, rc=%d, len=%d, cmd %x %s %s\n",
1159                rec->lrh_index, rc, rec->lrh_len, lcfg->lcfg_command,
1160                lustre_cfg_string(lcfg, 0), lustre_cfg_string(lcfg, 1));
1161
1162         RETURN(rc);
1163 }
1164
1165 /* Copy a remote log locally */
1166 static int mgc_copy_llog(struct obd_device *obd, struct llog_ctxt *rctxt,
1167                          struct llog_ctxt *lctxt, char *logname)
1168 {
1169         struct llog_handle *local_llh, *remote_llh;
1170         struct obd_uuid *uuid;
1171         char *temp_log;
1172         int rc, rc2;
1173         ENTRY;
1174
1175         /* Write new log to a temp name, then vfs_rename over logname
1176            upon successful completion. */
1177
1178         OBD_ALLOC(temp_log, strlen(logname) + 1);
1179         if (!temp_log)
1180                 RETURN(-ENOMEM);
1181         sprintf(temp_log, "%sT", logname);
1182
1183         /* Make sure there's no old temp log */
1184         rc = llog_create(lctxt, &local_llh, NULL, temp_log);
1185         if (rc)
1186                 GOTO(out, rc);
1187         rc = llog_init_handle(local_llh, LLOG_F_IS_PLAIN, NULL);
1188         if (rc)
1189                 GOTO(out, rc);
1190         rc = llog_destroy(local_llh);
1191         llog_free_handle(local_llh);
1192         if (rc)
1193                 GOTO(out, rc);
1194
1195         /* open local log */
1196         rc = llog_create(lctxt, &local_llh, NULL, temp_log);
1197         if (rc)
1198                 GOTO(out, rc);
1199
1200         /* set the log header uuid for fun */
1201         OBD_ALLOC_PTR(uuid);
1202         obd_str2uuid(uuid, logname);
1203         rc = llog_init_handle(local_llh, LLOG_F_IS_PLAIN, uuid);
1204         OBD_FREE_PTR(uuid);
1205         if (rc)
1206                 GOTO(out_closel, rc);
1207
1208         /* open remote log */
1209         rc = llog_create(rctxt, &remote_llh, NULL, logname);
1210         if (rc)
1211                 GOTO(out_closel, rc);
1212         rc = llog_init_handle(remote_llh, LLOG_F_IS_PLAIN, NULL);
1213         if (rc)
1214                 GOTO(out_closer, rc);
1215
1216         /* Copy remote log */
1217         rc = llog_process(remote_llh, mgc_copy_handler,(void *)local_llh, NULL);
1218
1219 out_closer:
1220         rc2 = llog_close(remote_llh);
1221         if (!rc)
1222                 rc = rc2;
1223 out_closel:
1224         rc2 = llog_close(local_llh);
1225         if (!rc)
1226                 rc = rc2;
1227
1228         /* We've copied the remote log to the local temp log, now
1229            replace the old local log with the temp log. */
1230         if (!rc) {
1231                 struct client_obd *cli = &obd->u.cli;
1232                 LASSERT(cli);
1233                 LASSERT(cli->cl_mgc_configs_dir);
1234                 rc = lustre_rename(cli->cl_mgc_configs_dir, cli->cl_mgc_vfsmnt,
1235                                    temp_log, logname);
1236         }
1237         CDEBUG(D_MGC, "Copied remote log %s (%d)\n", logname, rc);
1238 out:
1239         if (rc)
1240                 CERROR("Failed to copy remote log %s (%d)\n", logname, rc);
1241         OBD_FREE(temp_log, strlen(logname) + 1);
1242         RETURN(rc);
1243 }
1244
1245 /* local_only means it cannot get remote llogs */
1246 static int mgc_process_cfg_log(struct obd_device *mgc,
1247                                struct config_llog_data *cld,
1248                                int local_only)
1249 {
1250         struct llog_ctxt *ctxt, *lctxt = NULL;
1251         struct client_obd *cli = &mgc->u.cli;
1252         struct lvfs_run_ctxt *saved_ctxt;
1253         struct lustre_sb_info *lsi = NULL;
1254         int rc = 0, must_pop = 0;
1255         bool sptlrpc_started = false;
1256
1257         ENTRY;
1258
1259         LASSERT(cld);
1260         LASSERT(cfs_mutex_is_locked(&cld->cld_lock));
1261
1262         /*
1263          * local copy of sptlrpc log is controlled elsewhere, don't try to
1264          * read it up here.
1265          */
1266         if (cld_is_sptlrpc(cld) && local_only)
1267                 RETURN(0);
1268
1269         if (cld->cld_cfg.cfg_sb)
1270                 lsi = s2lsi(cld->cld_cfg.cfg_sb);
1271
1272         ctxt = llog_get_context(mgc, LLOG_CONFIG_REPL_CTXT);
1273         if (!ctxt) {
1274                 CERROR("missing llog context\n");
1275                 RETURN(-EINVAL);
1276         }
1277
1278         OBD_ALLOC_PTR(saved_ctxt);
1279         if (saved_ctxt == NULL)
1280                 RETURN(-ENOMEM);
1281
1282         lctxt = llog_get_context(mgc, LLOG_CONFIG_ORIG_CTXT);
1283
1284         /* Copy the setup log locally if we can. Don't mess around if we're
1285            running an MGS though (logs are already local). */
1286         if (lctxt && lsi && (lsi->lsi_flags & LSI_SERVER) &&
1287             (lsi->lsi_srv_mnt == cli->cl_mgc_vfsmnt) &&
1288             !IS_MGS(lsi->lsi_ldd)) {
1289                 push_ctxt(saved_ctxt, &mgc->obd_lvfs_ctxt, NULL);
1290                 must_pop++;
1291                 if (!local_only)
1292                         /* Only try to copy log if we have the lock. */
1293                         rc = mgc_copy_llog(mgc, ctxt, lctxt, cld->cld_logname);
1294                 if (local_only || rc) {
1295                         if (mgc_llog_is_empty(mgc, lctxt, cld->cld_logname)) {
1296                                 LCONSOLE_ERROR_MSG(0x13a, "Failed to get MGS "
1297                                                    "log %s and no local copy."
1298                                                    "\n", cld->cld_logname);
1299                                 GOTO(out_pop, rc = -ENOTCONN);
1300                         }
1301                         CDEBUG(D_MGC, "Failed to get MGS log %s, using local "
1302                                "copy for now, will try to update later.\n",
1303                                cld->cld_logname);
1304                 }
1305                 /* Now, whether we copied or not, start using the local llog.
1306                    If we failed to copy, we'll start using whatever the old
1307                    log has. */
1308                 llog_ctxt_put(ctxt);
1309                 ctxt = lctxt;
1310                 lctxt = NULL;
1311         } else if (local_only) { /* no local log at client side */
1312                 GOTO(out_pop, rc = -EIO);
1313         }
1314
1315         if (cld_is_sptlrpc(cld)) {
1316                 sptlrpc_conf_log_update_begin(cld->cld_logname);
1317                 sptlrpc_started = true;
1318         }
1319
1320         /* logname and instance info should be the same, so use our
1321            copy of the instance for the update.  The cfg_last_idx will
1322            be updated here. */
1323         rc = class_config_parse_llog(ctxt, cld->cld_logname, &cld->cld_cfg);
1324         EXIT;
1325
1326 out_pop:
1327         llog_ctxt_put(ctxt);
1328         if (lctxt)
1329                 llog_ctxt_put(lctxt);
1330         if (must_pop)
1331                 pop_ctxt(saved_ctxt, &mgc->obd_lvfs_ctxt, NULL);
1332
1333         OBD_FREE_PTR(saved_ctxt);
1334         /*
1335          * update settings on existing OBDs. doing it inside
1336          * of llog_process_lock so no device is attaching/detaching
1337          * in parallel.
1338          * the logname must be <fsname>-sptlrpc
1339          */
1340         if (sptlrpc_started) {
1341                 LASSERT(cld_is_sptlrpc(cld));
1342                 sptlrpc_conf_log_update_end(cld->cld_logname);
1343                 class_notify_sptlrpc_conf(cld->cld_logname,
1344                                           strlen(cld->cld_logname) -
1345                                           strlen("-sptlrpc"));
1346         }
1347
1348         RETURN(rc);
1349 }
1350
1351 /** Get a config log from the MGS and process it.
1352  * This func is called for both clients and servers.
1353  * Copy the log locally before parsing it if appropriate (non-MGS server)
1354  */
1355 int mgc_process_log(struct obd_device *mgc, struct config_llog_data *cld)
1356 {
1357         struct lustre_handle lockh = { 0 };
1358         int rc = 0, rcl, flags = 0;
1359         ENTRY;
1360
1361         LASSERT(cld);
1362
1363         /* I don't want multiple processes running process_log at once --
1364            sounds like badness.  It actually might be fine, as long as
1365            we're not trying to update from the same log
1366            simultaneously (in which case we should use a per-log sem.) */
1367         cfs_mutex_lock(&cld->cld_lock);
1368         if (cld->cld_stopping) {
1369                 cfs_mutex_unlock(&cld->cld_lock);
1370                 RETURN(0);
1371         }
1372
1373         OBD_FAIL_TIMEOUT(OBD_FAIL_MGC_PAUSE_PROCESS_LOG, 20);
1374
1375         CDEBUG(D_MGC, "Process log %s:%p from %d\n", cld->cld_logname,
1376                cld->cld_cfg.cfg_instance, cld->cld_cfg.cfg_last_idx + 1);
1377
1378         /* Get the cfg lock on the llog */
1379         rcl = mgc_enqueue(mgc->u.cli.cl_mgc_mgsexp, NULL, LDLM_PLAIN, NULL,
1380                           LCK_CR, &flags, NULL, NULL, NULL,
1381                           cld, 0, NULL, &lockh);
1382         if (rcl == 0) {
1383                 /* Get the cld, it will be released in mgc_blocking_ast. */
1384                 config_log_get(cld);
1385                 rc = ldlm_lock_set_data(&lockh, (void *)cld);
1386                 LASSERT(rc == 0);
1387         } else {
1388                 CDEBUG(D_MGC, "Can't get cfg lock: %d\n", rcl);
1389
1390                 /* mark cld_lostlock so that it will requeue
1391                  * after MGC becomes available. */
1392                 cld->cld_lostlock = 1;
1393                 /* Get extra reference, it will be put in requeue thread */
1394                 config_log_get(cld);
1395         }
1396
1397         rc = mgc_process_cfg_log(mgc, cld, rcl != 0);
1398
1399         CDEBUG(D_MGC, "%s: configuration from log '%s' %sed (%d).\n",
1400                mgc->obd_name, cld->cld_logname, rc ? "fail" : "succeed", rc);
1401
1402         cfs_mutex_unlock(&cld->cld_lock);
1403
1404         /* Now drop the lock so MGS can revoke it */
1405         if (!rcl) {
1406                 rcl = mgc_cancel(mgc->u.cli.cl_mgc_mgsexp, NULL,
1407                                  LCK_CR, &lockh);
1408                 if (rcl)
1409                         CERROR("Can't drop cfg lock: %d\n", rcl);
1410         }
1411
1412         RETURN(rc);
1413 }
1414
1415
1416 /** Called from lustre_process_log.
1417  * LCFG_LOG_START gets the config log from the MGS, processes it to start
1418  * any services, and adds it to the list logs to watch (follow).
1419  */
1420 static int mgc_process_config(struct obd_device *obd, obd_count len, void *buf)
1421 {
1422         struct lustre_cfg *lcfg = buf;
1423         struct config_llog_instance *cfg = NULL;
1424         char *logname;
1425         int rc = 0;
1426         ENTRY;
1427
1428         switch(lcfg->lcfg_command) {
1429         case LCFG_LOV_ADD_OBD: {
1430                 /* Overloading this cfg command: register a new target */
1431                 struct mgs_target_info *mti;
1432
1433                 if (LUSTRE_CFG_BUFLEN(lcfg, 1) !=
1434                     sizeof(struct mgs_target_info))
1435                         GOTO(out, rc = -EINVAL);
1436
1437                 mti = (struct mgs_target_info *)lustre_cfg_buf(lcfg, 1);
1438                 CDEBUG(D_MGC, "add_target %s %#x\n",
1439                        mti->mti_svname, mti->mti_flags);
1440                 rc = mgc_target_register(obd->u.cli.cl_mgc_mgsexp, mti);
1441                 break;
1442         }
1443         case LCFG_LOV_DEL_OBD:
1444                 /* Unregister has no meaning at the moment. */
1445                 CERROR("lov_del_obd unimplemented\n");
1446                 rc = -ENOSYS;
1447                 break;
1448         case LCFG_SPTLRPC_CONF: {
1449                 rc = sptlrpc_process_config(lcfg);
1450                 break;
1451         }
1452         case LCFG_LOG_START: {
1453                 struct config_llog_data *cld;
1454                 struct super_block *sb;
1455
1456                 logname = lustre_cfg_string(lcfg, 1);
1457                 cfg = (struct config_llog_instance *)lustre_cfg_buf(lcfg, 2);
1458                 sb = *(struct super_block **)lustre_cfg_buf(lcfg, 3);
1459
1460                 CDEBUG(D_MGC, "parse_log %s from %d\n", logname,
1461                        cfg->cfg_last_idx);
1462
1463                 /* We're only called through here on the initial mount */
1464                 rc = config_log_add(obd, logname, cfg, sb);
1465                 if (rc)
1466                         break;
1467                 cld = config_log_find(logname, cfg);
1468                 if (cld == NULL) {
1469                         rc = -ENOENT;
1470                         break;
1471                 }
1472
1473                 /* COMPAT_146 */
1474                 /* FIXME only set this for old logs!  Right now this forces
1475                    us to always skip the "inside markers" check */
1476                 cld->cld_cfg.cfg_flags |= CFG_F_COMPAT146;
1477
1478                 rc = mgc_process_log(obd, cld);
1479                 config_log_put(cld);
1480
1481                 break;
1482         }
1483         case LCFG_LOG_END: {
1484                 logname = lustre_cfg_string(lcfg, 1);
1485
1486                 if (lcfg->lcfg_bufcount >= 2)
1487                         cfg = (struct config_llog_instance *)lustre_cfg_buf(
1488                                 lcfg, 2);
1489                 rc = config_log_end(logname, cfg);
1490                 break;
1491         }
1492         default: {
1493                 CERROR("Unknown command: %d\n", lcfg->lcfg_command);
1494                 GOTO(out, rc = -EINVAL);
1495
1496         }
1497         }
1498 out:
1499         RETURN(rc);
1500 }
1501
1502 struct obd_ops mgc_obd_ops = {
1503         .o_owner        = THIS_MODULE,
1504         .o_setup        = mgc_setup,
1505         .o_precleanup   = mgc_precleanup,
1506         .o_cleanup      = mgc_cleanup,
1507         .o_add_conn     = client_import_add_conn,
1508         .o_del_conn     = client_import_del_conn,
1509         .o_connect      = client_connect_import,
1510         .o_disconnect   = client_disconnect_export,
1511         //.o_enqueue      = mgc_enqueue,
1512         .o_cancel       = mgc_cancel,
1513         //.o_iocontrol    = mgc_iocontrol,
1514         .o_set_info_async = mgc_set_info_async,
1515         .o_import_event = mgc_import_event,
1516         .o_llog_init    = mgc_llog_init,
1517         .o_llog_finish  = mgc_llog_finish,
1518         .o_process_config = mgc_process_config,
1519 };
1520
1521 int __init mgc_init(void)
1522 {
1523         return class_register_type(&mgc_obd_ops, NULL, NULL,
1524                                    LUSTRE_MGC_NAME, NULL);
1525 }
1526
1527 #ifdef __KERNEL__
1528 static void /*__exit*/ mgc_exit(void)
1529 {
1530         class_unregister_type(LUSTRE_MGC_NAME);
1531 }
1532
1533 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
1534 MODULE_DESCRIPTION("Lustre Management Client");
1535 MODULE_LICENSE("GPL");
1536
1537 module_init(mgc_init);
1538 module_exit(mgc_exit);
1539 #endif