Whamcloud - gitweb
347590f972bc6f3f8eb83fa05ab59ff3606fdf24
[fs/lustre-release.git] / lustre / mgc / mgc_request.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2013, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/mgc/mgc_request.c
37  *
38  * Author: Nathan Rutman <nathan@clusterfs.com>
39  */
40
41 #define DEBUG_SUBSYSTEM S_MGC
42 #define D_MGC D_CONFIG /*|D_WARNING*/
43
44 #include <linux/module.h>
45 #include <obd_class.h>
46 #include <lustre_dlm.h>
47 #include <lprocfs_status.h>
48 #include <lustre_log.h>
49 #include <lustre_disk.h>
50 #include <dt_object.h>
51
52 #include "mgc_internal.h"
53
54 static int mgc_name2resid(char *name, int len, struct ldlm_res_id *res_id,
55                           int type)
56 {
57         __u64 resname = 0;
58
59         if (len > sizeof(resname)) {
60                 CERROR("name too long: %s\n", name);
61                 return -EINVAL;
62         }
63         if (len <= 0) {
64                 CERROR("missing name: %s\n", name);
65                 return -EINVAL;
66         }
67         memcpy(&resname, name, len);
68
69         /* Always use the same endianness for the resid */
70         memset(res_id, 0, sizeof(*res_id));
71         res_id->name[0] = cpu_to_le64(resname);
72         /* XXX: unfortunately, sptlprc and config llog share one lock */
73         switch(type) {
74         case CONFIG_T_CONFIG:
75         case CONFIG_T_SPTLRPC:
76                 resname = 0;
77                 break;
78         case CONFIG_T_RECOVER:
79         case CONFIG_T_PARAMS:
80                 resname = type;
81                 break;
82         default:
83                 LBUG();
84         }
85         res_id->name[1] = cpu_to_le64(resname);
86         CDEBUG(D_MGC, "log %s to resid "LPX64"/"LPX64" (%.8s)\n", name,
87                res_id->name[0], res_id->name[1], (char *)&res_id->name[0]);
88         return 0;
89 }
90
91 int mgc_fsname2resid(char *fsname, struct ldlm_res_id *res_id, int type)
92 {
93         /* fsname is at most 8 chars long, maybe contain "-".
94          * e.g. "lustre", "SUN-000" */
95         return mgc_name2resid(fsname, strlen(fsname), res_id, type);
96 }
97 EXPORT_SYMBOL(mgc_fsname2resid);
98
99 int mgc_logname2resid(char *logname, struct ldlm_res_id *res_id, int type)
100 {
101         char *name_end;
102         int len;
103
104         /* logname consists of "fsname-nodetype".
105          * e.g. "lustre-MDT0001", "SUN-000-client"
106          * there is an exception: llog "params" */
107         name_end = strrchr(logname, '-');
108         if (!name_end)
109                 len = strlen(logname);
110         else
111                 len = name_end - logname;
112         return mgc_name2resid(logname, len, res_id, type);
113 }
114
115 /********************** config llog list **********************/
116 static struct list_head config_llog_list = LIST_HEAD_INIT(config_llog_list);
117 static DEFINE_SPINLOCK(config_list_lock);
118
119 /* Take a reference to a config log */
120 static int config_log_get(struct config_llog_data *cld)
121 {
122         ENTRY;
123         atomic_inc(&cld->cld_refcount);
124         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
125                 atomic_read(&cld->cld_refcount));
126         RETURN(0);
127 }
128
129 /* Drop a reference to a config log.  When no longer referenced,
130    we can free the config log data */
131 static void config_log_put(struct config_llog_data *cld)
132 {
133         ENTRY;
134
135         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
136                 atomic_read(&cld->cld_refcount));
137         LASSERT(atomic_read(&cld->cld_refcount) > 0);
138
139         /* spinlock to make sure no item with 0 refcount in the list */
140         if (atomic_dec_and_lock(&cld->cld_refcount, &config_list_lock)) {
141                 list_del(&cld->cld_list_chain);
142                 spin_unlock(&config_list_lock);
143
144                 CDEBUG(D_MGC, "dropping config log %s\n", cld->cld_logname);
145
146                 if (cld->cld_recover)
147                         config_log_put(cld->cld_recover);
148                 if (cld->cld_sptlrpc)
149                         config_log_put(cld->cld_sptlrpc);
150                 if (cld->cld_params)
151                         config_log_put(cld->cld_params);
152                 if (cld_is_sptlrpc(cld))
153                         sptlrpc_conf_log_stop(cld->cld_logname);
154
155                 class_export_put(cld->cld_mgcexp);
156                 OBD_FREE(cld, sizeof(*cld) + strlen(cld->cld_logname) + 1);
157         }
158
159         EXIT;
160 }
161
162 /* Find a config log by name */
163 static
164 struct config_llog_data *config_log_find(char *logname,
165                                          struct config_llog_instance *cfg)
166 {
167         struct config_llog_data *cld;
168         struct config_llog_data *found = NULL;
169         void *                   instance;
170         ENTRY;
171
172         LASSERT(logname != NULL);
173
174         instance = cfg ? cfg->cfg_instance : NULL;
175         spin_lock(&config_list_lock);
176         list_for_each_entry(cld, &config_llog_list, cld_list_chain) {
177                 /* check if instance equals */
178                 if (instance != cld->cld_cfg.cfg_instance)
179                         continue;
180
181                 /* instance may be NULL, should check name */
182                 if (strcmp(logname, cld->cld_logname) == 0) {
183                         found = cld;
184                         break;
185                 }
186         }
187         if (found) {
188                 atomic_inc(&found->cld_refcount);
189                 LASSERT(found->cld_stopping == 0 || cld_is_sptlrpc(found) == 0);
190         }
191         spin_unlock(&config_list_lock);
192         RETURN(found);
193 }
194
195 static
196 struct config_llog_data *do_config_log_add(struct obd_device *obd,
197                                            char *logname,
198                                            int type,
199                                            struct config_llog_instance *cfg,
200                                            struct super_block *sb)
201 {
202         struct config_llog_data *cld;
203         int                      rc;
204         ENTRY;
205
206         CDEBUG(D_MGC, "do adding config log %s:%p\n", logname,
207                cfg ? cfg->cfg_instance : 0);
208
209         OBD_ALLOC(cld, sizeof(*cld) + strlen(logname) + 1);
210         if (!cld)
211                 RETURN(ERR_PTR(-ENOMEM));
212
213         strcpy(cld->cld_logname, logname);
214         if (cfg)
215                 cld->cld_cfg = *cfg;
216         else
217                 cld->cld_cfg.cfg_callback = class_config_llog_handler;
218         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         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         spin_lock(&config_list_lock);
236         list_add(&cld->cld_list_chain, &config_llog_list);
237         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 && rc != -ENOENT)
247                         CERROR("failed processing sptlrpc log: %d\n", rc);
248         }
249
250         RETURN(cld);
251 }
252
253 static struct config_llog_data *config_recover_log_add(struct obd_device *obd,
254         char *fsname,
255         struct config_llog_instance *cfg,
256         struct super_block *sb)
257 {
258         struct config_llog_instance lcfg = *cfg;
259         struct lustre_sb_info *lsi = s2lsi(sb);
260         struct config_llog_data *cld;
261         char logname[32];
262
263         if (IS_OST(lsi))
264                 return NULL;
265
266         /* for osp-on-ost, see lustre_start_osp() */
267         if (IS_MDT(lsi) && lcfg.cfg_instance)
268                 return NULL;
269
270         /* we have to use different llog for clients and mdts for cmd
271          * where only clients are notified if one of cmd server restarts */
272         LASSERT(strlen(fsname) < sizeof(logname) / 2);
273         strcpy(logname, fsname);
274         if (IS_SERVER(lsi)) { /* mdt */
275                 LASSERT(lcfg.cfg_instance == NULL);
276                 lcfg.cfg_instance = sb;
277                 strcat(logname, "-mdtir");
278         } else {
279                 LASSERT(lcfg.cfg_instance != NULL);
280                 strcat(logname, "-cliir");
281         }
282
283         cld = do_config_log_add(obd, logname, CONFIG_T_RECOVER, &lcfg, sb);
284         return cld;
285 }
286
287 static struct config_llog_data *config_params_log_add(struct obd_device *obd,
288         struct config_llog_instance *cfg, struct super_block *sb)
289 {
290         struct config_llog_instance     lcfg = *cfg;
291         struct config_llog_data         *cld;
292
293         lcfg.cfg_instance = sb;
294
295         cld = do_config_log_add(obd, PARAMS_FILENAME, CONFIG_T_PARAMS,
296                                 &lcfg, sb);
297
298         return cld;
299 }
300
301 /** Add this log to the list of active logs watched by an MGC.
302  * Active means we're watching for updates.
303  * We have one active log per "mount" - client instance or servername.
304  * Each instance may be at a different point in the log.
305  */
306 static int config_log_add(struct obd_device *obd, char *logname,
307                           struct config_llog_instance *cfg,
308                           struct super_block *sb)
309 {
310         struct lustre_sb_info   *lsi = s2lsi(sb);
311         struct config_llog_data *cld;
312         struct config_llog_data *sptlrpc_cld;
313         struct config_llog_data *params_cld;
314         char                    seclogname[32];
315         char                    *ptr;
316         int                     rc;
317         ENTRY;
318
319         CDEBUG(D_MGC, "adding config log %s:%p\n", logname, cfg->cfg_instance);
320
321         /*
322          * for each regular log, the depended sptlrpc log name is
323          * <fsname>-sptlrpc. multiple regular logs may share one sptlrpc log.
324          */
325         ptr = strrchr(logname, '-');
326         if (ptr == NULL || ptr - logname > 8) {
327                 CERROR("logname %s is too long\n", logname);
328                 RETURN(-EINVAL);
329         }
330
331         memcpy(seclogname, logname, ptr - logname);
332         strcpy(seclogname + (ptr - logname), "-sptlrpc");
333
334         sptlrpc_cld = config_log_find(seclogname, NULL);
335         if (sptlrpc_cld == NULL) {
336                 sptlrpc_cld = do_config_log_add(obd, seclogname,
337                                                 CONFIG_T_SPTLRPC, NULL, NULL);
338                 if (IS_ERR(sptlrpc_cld)) {
339                         CERROR("can't create sptlrpc log: %s\n", seclogname);
340                         GOTO(out_err, rc = PTR_ERR(sptlrpc_cld));
341                 }
342         }
343         params_cld = config_params_log_add(obd, cfg, sb);
344         if (IS_ERR(params_cld)) {
345                 rc = PTR_ERR(params_cld);
346                 CERROR("%s: can't create params log: rc = %d\n",
347                        obd->obd_name, rc);
348                 GOTO(out_err1, rc);
349         }
350
351         cld = do_config_log_add(obd, logname, CONFIG_T_CONFIG, cfg, sb);
352         if (IS_ERR(cld)) {
353                 CERROR("can't create log: %s\n", logname);
354                 GOTO(out_err2, rc = PTR_ERR(cld));
355         }
356
357         cld->cld_sptlrpc = sptlrpc_cld;
358         cld->cld_params = params_cld;
359
360         LASSERT(lsi->lsi_lmd);
361         if (!(lsi->lsi_lmd->lmd_flags & LMD_FLG_NOIR)) {
362                 struct config_llog_data *recover_cld;
363                 ptr = strrchr(seclogname, '-');
364                 if (ptr != NULL) {
365                         *ptr = 0;
366                 }
367                 else {
368                         CERROR("%s: sptlrpc log name not correct, %s: "
369                                "rc = %d\n", obd->obd_name, seclogname, -EINVAL);
370                         config_log_put(cld);
371                         RETURN(-EINVAL);
372                 }
373                 recover_cld = config_recover_log_add(obd, seclogname, cfg, sb);
374                 if (IS_ERR(recover_cld))
375                         GOTO(out_err3, rc = PTR_ERR(recover_cld));
376                 cld->cld_recover = recover_cld;
377         }
378
379         RETURN(0);
380
381 out_err3:
382         config_log_put(cld);
383
384 out_err2:
385         config_log_put(params_cld);
386
387 out_err1:
388         config_log_put(sptlrpc_cld);
389
390 out_err:
391         RETURN(rc);
392 }
393
394 DEFINE_MUTEX(llog_process_lock);
395
396 /** Stop watching for updates on this log.
397  */
398 static int config_log_end(char *logname, struct config_llog_instance *cfg)
399 {
400         struct config_llog_data *cld;
401         struct config_llog_data *cld_sptlrpc = NULL;
402         struct config_llog_data *cld_params = NULL;
403         struct config_llog_data *cld_recover = NULL;
404         int rc = 0;
405         ENTRY;
406
407         cld = config_log_find(logname, cfg);
408         if (cld == NULL)
409                 RETURN(-ENOENT);
410
411         mutex_lock(&cld->cld_lock);
412         /*
413          * if cld_stopping is set, it means we didn't start the log thus
414          * not owning the start ref. this can happen after previous umount:
415          * the cld still hanging there waiting for lock cancel, and we
416          * remount again but failed in the middle and call log_end without
417          * calling start_log.
418          */
419         if (unlikely(cld->cld_stopping)) {
420                 mutex_unlock(&cld->cld_lock);
421                 /* drop the ref from the find */
422                 config_log_put(cld);
423                 RETURN(rc);
424         }
425
426         cld->cld_stopping = 1;
427
428         cld_recover = cld->cld_recover;
429         cld->cld_recover = NULL;
430         mutex_unlock(&cld->cld_lock);
431
432         if (cld_recover) {
433                 mutex_lock(&cld_recover->cld_lock);
434                 cld_recover->cld_stopping = 1;
435                 mutex_unlock(&cld_recover->cld_lock);
436                 config_log_put(cld_recover);
437         }
438
439         spin_lock(&config_list_lock);
440         cld_sptlrpc = cld->cld_sptlrpc;
441         cld->cld_sptlrpc = NULL;
442         cld_params = cld->cld_params;
443         cld->cld_params = NULL;
444         spin_unlock(&config_list_lock);
445
446         if (cld_sptlrpc)
447                 config_log_put(cld_sptlrpc);
448
449         if (cld_params) {
450                 mutex_lock(&cld_params->cld_lock);
451                 cld_params->cld_stopping = 1;
452                 mutex_unlock(&cld_params->cld_lock);
453                 config_log_put(cld_params);
454         }
455
456         /* drop the ref from the find */
457         config_log_put(cld);
458         /* drop the start ref */
459         config_log_put(cld);
460
461         CDEBUG(D_MGC, "end config log %s (%d)\n", logname ? logname : "client",
462                rc);
463         RETURN(rc);
464 }
465
466 #ifdef LPROCFS
467 int lprocfs_mgc_rd_ir_state(struct seq_file *m, void *data)
468 {
469         struct obd_device       *obd = data;
470         struct obd_import       *imp;
471         struct obd_connect_data *ocd;
472         struct config_llog_data *cld;
473         ENTRY;
474
475         LASSERT(obd != NULL);
476         LPROCFS_CLIMP_CHECK(obd);
477         imp = obd->u.cli.cl_import;
478         ocd = &imp->imp_connect_data;
479
480         seq_printf(m, "imperative_recovery: %s\n",
481                    OCD_HAS_FLAG(ocd, IMP_RECOV) ? "ENABLED" : "DISABLED");
482         seq_printf(m, "client_state:\n");
483
484         spin_lock(&config_list_lock);
485         list_for_each_entry(cld, &config_llog_list, cld_list_chain) {
486                 if (cld->cld_recover == NULL)
487                         continue;
488                 seq_printf(m,  "    - { client: %s, nidtbl_version: %u }\n",
489                                cld->cld_logname,
490                                cld->cld_recover->cld_cfg.cfg_last_idx);
491         }
492         spin_unlock(&config_list_lock);
493
494         LPROCFS_CLIMP_EXIT(obd);
495         RETURN(0);
496 }
497 #endif
498
499 /* reenqueue any lost locks */
500 #define RQ_RUNNING      0x1
501 #define RQ_NOW          0x2
502 #define RQ_LATER        0x4
503 #define RQ_STOP         0x8
504 #define RQ_PRECLEANUP   0x10
505 static int                    rq_state = 0;
506 static wait_queue_head_t      rq_waitq;
507 static DECLARE_COMPLETION(rq_exit);
508 static DECLARE_COMPLETION(rq_start);
509
510 static void do_requeue(struct config_llog_data *cld)
511 {
512         int rc = 0;
513         ENTRY;
514
515         LASSERT(atomic_read(&cld->cld_refcount) > 0);
516
517         /* Do not run mgc_process_log on a disconnected export or an
518          * export which is being disconnected. Take the client
519          * semaphore to make the check non-racy. */
520         down_read(&cld->cld_mgcexp->exp_obd->u.cli.cl_sem);
521         if (cld->cld_mgcexp->exp_obd->u.cli.cl_conn_count != 0) {
522                 CDEBUG(D_MGC, "updating log %s\n", cld->cld_logname);
523                 rc = mgc_process_log(cld->cld_mgcexp->exp_obd, cld);
524                 if (rc && rc != -ENOENT)
525                         CERROR("failed processing log: %d\n", rc);
526         } else {
527                 CDEBUG(D_MGC, "disconnecting, won't update log %s\n",
528                        cld->cld_logname);
529         }
530         up_read(&cld->cld_mgcexp->exp_obd->u.cli.cl_sem);
531
532         EXIT;
533 }
534
535 /* this timeout represents how many seconds MGC should wait before
536  * requeue config and recover lock to the MGS. We need to randomize this
537  * in order to not flood the MGS.
538  */
539 #define MGC_TIMEOUT_MIN_SECONDS   5
540 #define MGC_TIMEOUT_RAND_CENTISEC 0x1ff /* ~500 */
541
542 static int mgc_requeue_thread(void *data)
543 {
544         int rc = 0;
545         bool first = true;
546         ENTRY;
547
548         CDEBUG(D_MGC, "Starting requeue thread\n");
549
550         /* Keep trying failed locks periodically */
551         spin_lock(&config_list_lock);
552         rq_state |= RQ_RUNNING;
553         while (1) {
554                 struct l_wait_info lwi;
555                 struct config_llog_data *cld, *cld_prev;
556                 int rand = cfs_rand() & MGC_TIMEOUT_RAND_CENTISEC;
557                 int stopped = !!(rq_state & RQ_STOP);
558                 int to;
559
560                 /* Any new or requeued lostlocks will change the state */
561                 rq_state &= ~(RQ_NOW | RQ_LATER);
562                 spin_unlock(&config_list_lock);
563
564                 if (first) {
565                         first = false;
566                         complete(&rq_start);
567                 }
568
569                 /* Always wait a few seconds to allow the server who
570                    caused the lock revocation to finish its setup, plus some
571                    random so everyone doesn't try to reconnect at once. */
572                 to = msecs_to_jiffies(MGC_TIMEOUT_MIN_SECONDS * MSEC_PER_SEC);
573                 /* rand is centi-seconds */
574                 to += msecs_to_jiffies(rand * MSEC_PER_SEC / 100);
575                 lwi = LWI_TIMEOUT(to, NULL, NULL);
576                 l_wait_event(rq_waitq, rq_state & (RQ_STOP | RQ_PRECLEANUP),
577                              &lwi);
578
579                 /*
580                  * iterate & processing through the list. for each cld, process
581                  * its depending sptlrpc cld firstly (if any) and then itself.
582                  *
583                  * it's guaranteed any item in the list must have
584                  * reference > 0; and if cld_lostlock is set, at
585                  * least one reference is taken by the previous enqueue.
586                  */
587                 cld_prev = NULL;
588
589                 spin_lock(&config_list_lock);
590                 rq_state &= ~RQ_PRECLEANUP;
591                 list_for_each_entry(cld, &config_llog_list,
592                                         cld_list_chain) {
593                         if (!cld->cld_lostlock)
594                                 continue;
595
596                         spin_unlock(&config_list_lock);
597
598                         LASSERT(atomic_read(&cld->cld_refcount) > 0);
599
600                         /* Whether we enqueued again or not in mgc_process_log,
601                          * we're done with the ref from the old enqueue */
602                         if (cld_prev)
603                                 config_log_put(cld_prev);
604                         cld_prev = cld;
605
606                         cld->cld_lostlock = 0;
607                         if (likely(!stopped))
608                                 do_requeue(cld);
609
610                         spin_lock(&config_list_lock);
611                 }
612                 spin_unlock(&config_list_lock);
613                 if (cld_prev)
614                         config_log_put(cld_prev);
615
616                 /* break after scanning the list so that we can drop
617                  * refcount to losing lock clds */
618                 if (unlikely(stopped)) {
619                         spin_lock(&config_list_lock);
620                         break;
621                 }
622
623                 /* Wait a bit to see if anyone else needs a requeue */
624                 lwi = (struct l_wait_info) { 0 };
625                 l_wait_event(rq_waitq, rq_state & (RQ_NOW | RQ_STOP),
626                              &lwi);
627                 spin_lock(&config_list_lock);
628         }
629         /* spinlock and while guarantee RQ_NOW and RQ_LATER are not set */
630         rq_state &= ~RQ_RUNNING;
631         spin_unlock(&config_list_lock);
632
633         complete(&rq_exit);
634
635         CDEBUG(D_MGC, "Ending requeue thread\n");
636         RETURN(rc);
637 }
638
639 /* Add a cld to the list to requeue.  Start the requeue thread if needed.
640    We are responsible for dropping the config log reference from here on out. */
641 static void mgc_requeue_add(struct config_llog_data *cld)
642 {
643         ENTRY;
644
645         CDEBUG(D_INFO, "log %s: requeue (r=%d sp=%d st=%x)\n",
646                 cld->cld_logname, atomic_read(&cld->cld_refcount),
647                 cld->cld_stopping, rq_state);
648         LASSERT(atomic_read(&cld->cld_refcount) > 0);
649
650         mutex_lock(&cld->cld_lock);
651         if (cld->cld_stopping || cld->cld_lostlock) {
652                 mutex_unlock(&cld->cld_lock);
653                 RETURN_EXIT;
654         }
655         /* this refcount will be released in mgc_requeue_thread. */
656         config_log_get(cld);
657         cld->cld_lostlock = 1;
658         mutex_unlock(&cld->cld_lock);
659
660         /* Hold lock for rq_state */
661         spin_lock(&config_list_lock);
662         if (rq_state & RQ_STOP) {
663                 spin_unlock(&config_list_lock);
664                 cld->cld_lostlock = 0;
665                 config_log_put(cld);
666         } else {
667                 rq_state |= RQ_NOW;
668                 spin_unlock(&config_list_lock);
669                 wake_up(&rq_waitq);
670         }
671         EXIT;
672 }
673
674 /********************** class fns **********************/
675 static int mgc_local_llog_init(const struct lu_env *env,
676                                struct obd_device *obd,
677                                struct obd_device *disk)
678 {
679         struct llog_ctxt        *ctxt;
680         int                      rc;
681
682         ENTRY;
683
684         rc = llog_setup(env, obd, &obd->obd_olg, LLOG_CONFIG_ORIG_CTXT, disk,
685                         &llog_osd_ops);
686         if (rc)
687                 RETURN(rc);
688
689         ctxt = llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT);
690         LASSERT(ctxt);
691         ctxt->loc_dir = obd->u.cli.cl_mgc_configs_dir;
692         llog_ctxt_put(ctxt);
693
694         RETURN(0);
695 }
696
697 static int mgc_local_llog_fini(const struct lu_env *env,
698                                struct obd_device *obd)
699 {
700         struct llog_ctxt *ctxt;
701
702         ENTRY;
703
704         ctxt = llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT);
705         llog_cleanup(env, ctxt);
706
707         RETURN(0);
708 }
709
710 static int mgc_fs_setup(struct obd_device *obd, struct super_block *sb)
711 {
712         struct lustre_sb_info   *lsi = s2lsi(sb);
713         struct client_obd       *cli = &obd->u.cli;
714         struct lu_fid            rfid, fid;
715         struct dt_object        *root, *dto;
716         struct lu_env           *env;
717         int                      rc = 0;
718
719         ENTRY;
720
721         LASSERT(lsi);
722         LASSERT(lsi->lsi_dt_dev);
723
724         OBD_ALLOC_PTR(env);
725         if (env == NULL)
726                 RETURN(-ENOMEM);
727
728         /* The mgc fs exclusion mutex. Only one fs can be setup at a time. */
729         mutex_lock(&cli->cl_mgc_mutex);
730
731         /* Setup the configs dir */
732         rc = lu_env_init(env, LCT_MG_THREAD);
733         if (rc)
734                 GOTO(out_err, rc);
735
736         fid.f_seq = FID_SEQ_LOCAL_NAME;
737         fid.f_oid = 1;
738         fid.f_ver = 0;
739         rc = local_oid_storage_init(env, lsi->lsi_dt_dev, &fid,
740                                     &cli->cl_mgc_los);
741         if (rc)
742                 GOTO(out_env, rc);
743
744         rc = dt_root_get(env, lsi->lsi_dt_dev, &rfid);
745         if (rc)
746                 GOTO(out_env, rc);
747
748         root = dt_locate_at(env, lsi->lsi_dt_dev, &rfid,
749                             &cli->cl_mgc_los->los_dev->dd_lu_dev, NULL);
750         if (unlikely(IS_ERR(root)))
751                 GOTO(out_los, rc = PTR_ERR(root));
752
753         dto = local_file_find_or_create(env, cli->cl_mgc_los, root,
754                                         MOUNT_CONFIGS_DIR,
755                                         S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO);
756         lu_object_put_nocache(env, &root->do_lu);
757         if (IS_ERR(dto))
758                 GOTO(out_los, rc = PTR_ERR(dto));
759
760         cli->cl_mgc_configs_dir = dto;
761
762         LASSERT(lsi->lsi_osd_exp->exp_obd->obd_lvfs_ctxt.dt);
763         rc = mgc_local_llog_init(env, obd, lsi->lsi_osd_exp->exp_obd);
764         if (rc)
765                 GOTO(out_llog, rc);
766
767         /* We take an obd ref to insure that we can't get to mgc_cleanup
768          * without calling mgc_fs_cleanup first. */
769         class_incref(obd, "mgc_fs", obd);
770
771         /* We keep the cl_mgc_sem until mgc_fs_cleanup */
772         EXIT;
773 out_llog:
774         if (rc) {
775                 lu_object_put(env, &cli->cl_mgc_configs_dir->do_lu);
776                 cli->cl_mgc_configs_dir = NULL;
777         }
778 out_los:
779         if (rc < 0) {
780                 local_oid_storage_fini(env, cli->cl_mgc_los);
781                 cli->cl_mgc_los = NULL;
782                 mutex_unlock(&cli->cl_mgc_mutex);
783         }
784 out_env:
785         lu_env_fini(env);
786 out_err:
787         OBD_FREE_PTR(env);
788         return rc;
789 }
790
791 static int mgc_fs_cleanup(struct obd_device *obd)
792 {
793         struct lu_env            env;
794         struct client_obd       *cli = &obd->u.cli;
795         int                      rc;
796
797         ENTRY;
798
799         LASSERT(cli->cl_mgc_los != NULL);
800
801         rc = lu_env_init(&env, LCT_MG_THREAD);
802         if (rc)
803                 GOTO(unlock, rc);
804
805         mgc_local_llog_fini(&env, obd);
806
807         lu_object_put_nocache(&env, &cli->cl_mgc_configs_dir->do_lu);
808         cli->cl_mgc_configs_dir = NULL;
809
810         local_oid_storage_fini(&env, cli->cl_mgc_los);
811         cli->cl_mgc_los = NULL;
812         lu_env_fini(&env);
813
814 unlock:
815         class_decref(obd, "mgc_fs", obd);
816         mutex_unlock(&cli->cl_mgc_mutex);
817
818         RETURN(0);
819 }
820
821 static int mgc_llog_init(const struct lu_env *env, struct obd_device *obd)
822 {
823         struct llog_ctxt        *ctxt;
824         int                      rc;
825
826         ENTRY;
827
828         /* setup only remote ctxt, the local disk context is switched per each
829          * filesystem during mgc_fs_setup() */
830         rc = llog_setup(env, obd, &obd->obd_olg, LLOG_CONFIG_REPL_CTXT, obd,
831                         &llog_client_ops);
832         if (rc)
833                 RETURN(rc);
834
835         ctxt = llog_get_context(obd, LLOG_CONFIG_REPL_CTXT);
836         LASSERT(ctxt);
837
838         llog_initiator_connect(ctxt);
839         llog_ctxt_put(ctxt);
840
841         RETURN(0);
842 }
843
844 static int mgc_llog_fini(const struct lu_env *env, struct obd_device *obd)
845 {
846         struct llog_ctxt *ctxt;
847
848         ENTRY;
849
850         ctxt = llog_get_context(obd, LLOG_CONFIG_REPL_CTXT);
851         if (ctxt)
852                 llog_cleanup(env, ctxt);
853
854         RETURN(0);
855 }
856
857
858 static atomic_t mgc_count = ATOMIC_INIT(0);
859 static int mgc_precleanup(struct obd_device *obd, enum obd_cleanup_stage stage)
860 {
861         int rc = 0;
862         int temp;
863         ENTRY;
864
865         switch (stage) {
866         case OBD_CLEANUP_EARLY:
867                 break;
868         case OBD_CLEANUP_EXPORTS:
869                 if (atomic_dec_and_test(&mgc_count)) {
870                         LASSERT(rq_state & RQ_RUNNING);
871                         /* stop requeue thread */
872                         temp = RQ_STOP;
873                 } else {
874                         /* wakeup requeue thread to clean our cld */
875                         temp = RQ_NOW | RQ_PRECLEANUP;
876                 }
877                 spin_lock(&config_list_lock);
878                 rq_state |= temp;
879                 spin_unlock(&config_list_lock);
880                 wake_up(&rq_waitq);
881                 if (temp & RQ_STOP)
882                         wait_for_completion(&rq_exit);
883                 obd_cleanup_client_import(obd);
884                 rc = mgc_llog_fini(NULL, obd);
885                 if (rc != 0)
886                         CERROR("failed to cleanup llogging subsystems\n");
887                 break;
888         }
889         RETURN(rc);
890 }
891
892 static int mgc_cleanup(struct obd_device *obd)
893 {
894         int rc;
895         ENTRY;
896
897         /* COMPAT_146 - old config logs may have added profiles we don't
898            know about */
899         if (obd->obd_type->typ_refcnt <= 1)
900                 /* Only for the last mgc */
901                 class_del_profiles();
902
903         lprocfs_obd_cleanup(obd);
904         ptlrpcd_decref();
905
906         rc = client_obd_cleanup(obd);
907         RETURN(rc);
908 }
909
910 static int mgc_setup(struct obd_device *obd, struct lustre_cfg *lcfg)
911 {
912         struct task_struct      *task;
913         int                      rc;
914         ENTRY;
915
916         rc = ptlrpcd_addref();
917         if (rc < 0)
918                 RETURN(rc);
919
920         rc = client_obd_setup(obd, lcfg);
921         if (rc)
922                 GOTO(err_decref, rc);
923
924         rc = mgc_llog_init(NULL, obd);
925         if (rc) {
926                 CERROR("failed to setup llogging subsystems\n");
927                 GOTO(err_cleanup, rc);
928         }
929
930 #ifdef LPROCFS
931         obd->obd_vars = lprocfs_mgc_obd_vars;
932         lprocfs_obd_setup(obd);
933 #endif
934         sptlrpc_lprocfs_cliobd_attach(obd);
935
936         if (atomic_inc_return(&mgc_count) == 1) {
937                 rq_state = 0;
938                 init_waitqueue_head(&rq_waitq);
939
940                 /* start requeue thread */
941                 task = kthread_run(mgc_requeue_thread, NULL, "ll_cfg_requeue");
942                 if (IS_ERR(task)) {
943                         rc = PTR_ERR(task);
944                         CERROR("%s: cannot start requeue thread: rc = %d; "
945                                "no more log updates\n",
946                                obd->obd_name, rc);
947                         GOTO(err_cleanup, rc);
948                 }
949                 /* rc is the task_struct pointer of mgc_requeue_thread. */
950                 rc = 0;
951                 wait_for_completion(&rq_start);
952         }
953
954         RETURN(rc);
955
956 err_cleanup:
957         client_obd_cleanup(obd);
958 err_decref:
959         ptlrpcd_decref();
960         RETURN(rc);
961 }
962
963 /* based on ll_mdc_blocking_ast */
964 static int mgc_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
965                             void *data, int flag)
966 {
967         struct lustre_handle lockh;
968         struct config_llog_data *cld = (struct config_llog_data *)data;
969         int rc = 0;
970         ENTRY;
971
972         switch (flag) {
973         case LDLM_CB_BLOCKING:
974                 /* mgs wants the lock, give it up... */
975                 LDLM_DEBUG(lock, "MGC blocking CB");
976                 ldlm_lock2handle(lock, &lockh);
977                 rc = ldlm_cli_cancel(&lockh, LCF_ASYNC);
978                 break;
979         case LDLM_CB_CANCELING:
980                 /* We've given up the lock, prepare ourselves to update. */
981                 LDLM_DEBUG(lock, "MGC cancel CB");
982
983                 CDEBUG(D_MGC, "Lock res "DLDLMRES" (%.8s)\n",
984                        PLDLMRES(lock->l_resource),
985                        (char *)&lock->l_resource->lr_name.name[0]);
986
987                 if (!cld) {
988                         CDEBUG(D_INFO, "missing data, won't requeue\n");
989                         break;
990                 }
991
992                 /* held at mgc_process_log(). */
993                 LASSERT(atomic_read(&cld->cld_refcount) > 0);
994                 /* Are we done with this log? */
995                 if (cld->cld_stopping) {
996                         CDEBUG(D_MGC, "log %s: stopping, won't requeue\n",
997                                 cld->cld_logname);
998                         config_log_put(cld);
999                         break;
1000                 }
1001                 /* Make sure not to re-enqueue when the mgc is stopping
1002                    (we get called from client_disconnect_export) */
1003                 if (!lock->l_conn_export ||
1004                     !lock->l_conn_export->exp_obd->u.cli.cl_conn_count) {
1005                         CDEBUG(D_MGC, "log %.8s: disconnecting, won't requeue\n",
1006                                 cld->cld_logname);
1007                         config_log_put(cld);
1008                         break;
1009                 }
1010
1011                 /* Re-enqueue now */
1012                 mgc_requeue_add(cld);
1013                 config_log_put(cld);
1014                 break;
1015         default:
1016                 LBUG();
1017         }
1018
1019         RETURN(rc);
1020 }
1021
1022 /* Not sure where this should go... */
1023 /* This is the timeout value for MGS_CONNECT request plus a ping interval, such
1024  * that we can have a chance to try the secondary MGS if any. */
1025 #define  MGC_ENQUEUE_LIMIT (INITIAL_CONNECT_TIMEOUT + (AT_OFF ? 0 : at_min) \
1026                                 + PING_INTERVAL)
1027 #define  MGC_TARGET_REG_LIMIT 10
1028 #define  MGC_SEND_PARAM_LIMIT 10
1029
1030 /* Send parameter to MGS*/
1031 static int mgc_set_mgs_param(struct obd_export *exp,
1032                              struct mgs_send_param *msp)
1033 {
1034         struct ptlrpc_request *req;
1035         struct mgs_send_param *req_msp, *rep_msp;
1036         int rc;
1037         ENTRY;
1038
1039         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
1040                                         &RQF_MGS_SET_INFO, LUSTRE_MGS_VERSION,
1041                                         MGS_SET_INFO);
1042         if (!req)
1043                 RETURN(-ENOMEM);
1044
1045         req_msp = req_capsule_client_get(&req->rq_pill, &RMF_MGS_SEND_PARAM);
1046         if (!req_msp) {
1047                 ptlrpc_req_finished(req);
1048                 RETURN(-ENOMEM);
1049         }
1050
1051         memcpy(req_msp, msp, sizeof(*req_msp));
1052         ptlrpc_request_set_replen(req);
1053
1054         /* Limit how long we will wait for the enqueue to complete */
1055         req->rq_delay_limit = MGC_SEND_PARAM_LIMIT;
1056         rc = ptlrpc_queue_wait(req);
1057         if (!rc) {
1058                 rep_msp = req_capsule_server_get(&req->rq_pill, &RMF_MGS_SEND_PARAM);
1059                 memcpy(msp, rep_msp, sizeof(*rep_msp));
1060         }
1061
1062         ptlrpc_req_finished(req);
1063
1064         RETURN(rc);
1065 }
1066
1067 /* Take a config lock so we can get cancel notifications */
1068 static int mgc_enqueue(struct obd_export *exp, struct lov_stripe_md *lsm,
1069                        __u32 type, ldlm_policy_data_t *policy, __u32 mode,
1070                        __u64 *flags, void *bl_cb, void *cp_cb, void *gl_cb,
1071                        void *data, __u32 lvb_len, void *lvb_swabber,
1072                        struct lustre_handle *lockh)
1073 {
1074         struct config_llog_data *cld = (struct config_llog_data *)data;
1075         struct ldlm_enqueue_info einfo = {
1076                 .ei_type        = type,
1077                 .ei_mode        = mode,
1078                 .ei_cb_bl       = mgc_blocking_ast,
1079                 .ei_cb_cp       = ldlm_completion_ast,
1080         };
1081         struct ptlrpc_request *req;
1082         int short_limit = cld_is_sptlrpc(cld);
1083         int rc;
1084         ENTRY;
1085
1086         CDEBUG(D_MGC, "Enqueue for %s (res "LPX64")\n", cld->cld_logname,
1087                cld->cld_resid.name[0]);
1088
1089         /* We need a callback for every lockholder, so don't try to
1090            ldlm_lock_match (see rev 1.1.2.11.2.47) */
1091         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
1092                                         &RQF_LDLM_ENQUEUE, LUSTRE_DLM_VERSION,
1093                                         LDLM_ENQUEUE);
1094         if (req == NULL)
1095                 RETURN(-ENOMEM);
1096
1097         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER, 0);
1098         ptlrpc_request_set_replen(req);
1099
1100         /* check if this is server or client */
1101         if (cld->cld_cfg.cfg_sb) {
1102                 struct lustre_sb_info *lsi = s2lsi(cld->cld_cfg.cfg_sb);
1103                 if (lsi && IS_SERVER(lsi))
1104                         short_limit = 1;
1105         }
1106         /* Limit how long we will wait for the enqueue to complete */
1107         req->rq_delay_limit = short_limit ? 5 : MGC_ENQUEUE_LIMIT;
1108         rc = ldlm_cli_enqueue(exp, &req, &einfo, &cld->cld_resid, NULL, flags,
1109                               NULL, 0, LVB_T_NONE, lockh, 0);
1110         /* A failed enqueue should still call the mgc_blocking_ast,
1111            where it will be requeued if needed ("grant failed"). */
1112         ptlrpc_req_finished(req);
1113         RETURN(rc);
1114 }
1115
1116 static int mgc_cancel(struct obd_export *exp, ldlm_mode_t mode,
1117                       struct lustre_handle *lockh)
1118 {
1119         ENTRY;
1120
1121         ldlm_lock_decref(lockh, mode);
1122
1123         RETURN(0);
1124 }
1125
1126 static void mgc_notify_active(struct obd_device *unused)
1127 {
1128         /* wakeup mgc_requeue_thread to requeue mgc lock */
1129         spin_lock(&config_list_lock);
1130         rq_state |= RQ_NOW;
1131         spin_unlock(&config_list_lock);
1132         wake_up(&rq_waitq);
1133
1134         /* TODO: Help the MGS rebuild nidtbl. -jay */
1135 }
1136
1137 /* Send target_reg message to MGS */
1138 static int mgc_target_register(struct obd_export *exp,
1139                                struct mgs_target_info *mti)
1140 {
1141         struct ptlrpc_request  *req;
1142         struct mgs_target_info *req_mti, *rep_mti;
1143         int                     rc;
1144         ENTRY;
1145
1146         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
1147                                         &RQF_MGS_TARGET_REG, LUSTRE_MGS_VERSION,
1148                                         MGS_TARGET_REG);
1149         if (req == NULL)
1150                 RETURN(-ENOMEM);
1151
1152         req_mti = req_capsule_client_get(&req->rq_pill, &RMF_MGS_TARGET_INFO);
1153         if (!req_mti) {
1154                 ptlrpc_req_finished(req);
1155                 RETURN(-ENOMEM);
1156         }
1157
1158         memcpy(req_mti, mti, sizeof(*req_mti));
1159         ptlrpc_request_set_replen(req);
1160         CDEBUG(D_MGC, "register %s\n", mti->mti_svname);
1161         /* Limit how long we will wait for the enqueue to complete */
1162         req->rq_delay_limit = MGC_TARGET_REG_LIMIT;
1163
1164         rc = ptlrpc_queue_wait(req);
1165         if (!rc) {
1166                 rep_mti = req_capsule_server_get(&req->rq_pill,
1167                                                  &RMF_MGS_TARGET_INFO);
1168                 memcpy(mti, rep_mti, sizeof(*rep_mti));
1169                 CDEBUG(D_MGC, "register %s got index = %d\n",
1170                        mti->mti_svname, mti->mti_stripe_index);
1171         }
1172         ptlrpc_req_finished(req);
1173
1174         RETURN(rc);
1175 }
1176
1177 int mgc_set_info_async(const struct lu_env *env, struct obd_export *exp,
1178                        obd_count keylen, void *key, obd_count vallen,
1179                        void *val, struct ptlrpc_request_set *set)
1180 {
1181         int rc = -EINVAL;
1182         ENTRY;
1183
1184         /* Turn off initial_recov after we try all backup servers once */
1185         if (KEY_IS(KEY_INIT_RECOV_BACKUP)) {
1186                 struct obd_import *imp = class_exp2cliimp(exp);
1187                 int value;
1188                 if (vallen != sizeof(int))
1189                         RETURN(-EINVAL);
1190                 value = *(int *)val;
1191                 CDEBUG(D_MGC, "InitRecov %s %d/d%d:i%d:r%d:or%d:%s\n",
1192                        imp->imp_obd->obd_name, value,
1193                        imp->imp_deactive, imp->imp_invalid,
1194                        imp->imp_replayable, imp->imp_obd->obd_replayable,
1195                        ptlrpc_import_state_name(imp->imp_state));
1196                 /* Resurrect if we previously died */
1197                 if ((imp->imp_state != LUSTRE_IMP_FULL &&
1198                      imp->imp_state != LUSTRE_IMP_NEW) || value > 1)
1199                         ptlrpc_reconnect_import(imp);
1200                 RETURN(0);
1201         }
1202         /* FIXME move this to mgc_process_config */
1203         if (KEY_IS(KEY_REGISTER_TARGET)) {
1204                 struct mgs_target_info *mti;
1205                 if (vallen != sizeof(struct mgs_target_info))
1206                         RETURN(-EINVAL);
1207                 mti = (struct mgs_target_info *)val;
1208                 CDEBUG(D_MGC, "register_target %s %#x\n",
1209                        mti->mti_svname, mti->mti_flags);
1210                 rc =  mgc_target_register(exp, mti);
1211                 RETURN(rc);
1212         }
1213         if (KEY_IS(KEY_SET_FS)) {
1214                 struct super_block *sb = (struct super_block *)val;
1215
1216                 if (vallen != sizeof(struct super_block))
1217                         RETURN(-EINVAL);
1218
1219                 rc = mgc_fs_setup(exp->exp_obd, sb);
1220                 RETURN(rc);
1221         }
1222         if (KEY_IS(KEY_CLEAR_FS)) {
1223                 if (vallen != 0)
1224                         RETURN(-EINVAL);
1225                 rc = mgc_fs_cleanup(exp->exp_obd);
1226                 RETURN(rc);
1227         }
1228         if (KEY_IS(KEY_SET_INFO)) {
1229                 struct mgs_send_param *msp;
1230
1231                 msp = (struct mgs_send_param *)val;
1232                 rc =  mgc_set_mgs_param(exp, msp);
1233                 RETURN(rc);
1234         }
1235         if (KEY_IS(KEY_MGSSEC)) {
1236                 struct client_obd     *cli = &exp->exp_obd->u.cli;
1237                 struct sptlrpc_flavor  flvr;
1238
1239                 /*
1240                  * empty string means using current flavor, if which haven't
1241                  * been set yet, set it as null.
1242                  *
1243                  * if flavor has been set previously, check the asking flavor
1244                  * must match the existing one.
1245                  */
1246                 if (vallen == 0) {
1247                         if (cli->cl_flvr_mgc.sf_rpc != SPTLRPC_FLVR_INVALID)
1248                                 RETURN(0);
1249                         val = "null";
1250                         vallen = 4;
1251                 }
1252
1253                 rc = sptlrpc_parse_flavor(val, &flvr);
1254                 if (rc) {
1255                         CERROR("invalid sptlrpc flavor %s to MGS\n",
1256                                (char *) val);
1257                         RETURN(rc);
1258                 }
1259
1260                 /*
1261                  * caller already hold a mutex
1262                  */
1263                 if (cli->cl_flvr_mgc.sf_rpc == SPTLRPC_FLVR_INVALID) {
1264                         cli->cl_flvr_mgc = flvr;
1265                 } else if (memcmp(&cli->cl_flvr_mgc, &flvr,
1266                                   sizeof(flvr)) != 0) {
1267                         char    str[20];
1268
1269                         sptlrpc_flavor2name(&cli->cl_flvr_mgc,
1270                                             str, sizeof(str));
1271                         LCONSOLE_ERROR("asking sptlrpc flavor %s to MGS but "
1272                                        "currently %s is in use\n",
1273                                        (char *) val, str);
1274                         rc = -EPERM;
1275                 }
1276                 RETURN(rc);
1277         }
1278
1279         RETURN(rc);
1280 }
1281
1282 static int mgc_get_info(const struct lu_env *env, struct obd_export *exp,
1283                         __u32 keylen, void *key, __u32 *vallen, void *val,
1284                         struct lov_stripe_md *unused)
1285 {
1286         int rc = -EINVAL;
1287
1288         if (KEY_IS(KEY_CONN_DATA)) {
1289                 struct obd_import *imp = class_exp2cliimp(exp);
1290                 struct obd_connect_data *data = val;
1291
1292                 if (*vallen == sizeof(*data)) {
1293                         *data = imp->imp_connect_data;
1294                         rc = 0;
1295                 }
1296         }
1297
1298         return rc;
1299 }
1300
1301 static int mgc_import_event(struct obd_device *obd,
1302                             struct obd_import *imp,
1303                             enum obd_import_event event)
1304 {
1305         int rc = 0;
1306
1307         LASSERT(imp->imp_obd == obd);
1308         CDEBUG(D_MGC, "import event %#x\n", event);
1309
1310         switch (event) {
1311         case IMP_EVENT_DISCON:
1312                 /* MGC imports should not wait for recovery */
1313                 if (OCD_HAS_FLAG(&imp->imp_connect_data, IMP_RECOV))
1314                         ptlrpc_pinger_ir_down();
1315                 break;
1316         case IMP_EVENT_INACTIVE:
1317                 break;
1318         case IMP_EVENT_INVALIDATE: {
1319                 struct ldlm_namespace *ns = obd->obd_namespace;
1320                 ldlm_namespace_cleanup(ns, LDLM_FL_LOCAL_ONLY);
1321                 break;
1322         }
1323         case IMP_EVENT_ACTIVE:
1324                 CDEBUG(D_INFO, "%s: Reactivating import\n", obd->obd_name);
1325                 /* Clearing obd_no_recov allows us to continue pinging */
1326                 obd->obd_no_recov = 0;
1327                 mgc_notify_active(obd);
1328                 if (OCD_HAS_FLAG(&imp->imp_connect_data, IMP_RECOV))
1329                         ptlrpc_pinger_ir_up();
1330                 break;
1331         case IMP_EVENT_OCD:
1332                 break;
1333         case IMP_EVENT_DEACTIVATE:
1334         case IMP_EVENT_ACTIVATE:
1335                 break;
1336         default:
1337                 CERROR("Unknown import event %#x\n", event);
1338                 LBUG();
1339         }
1340         RETURN(rc);
1341 }
1342
1343 enum {
1344         CONFIG_READ_NRPAGES_INIT = 1 << (20 - PAGE_CACHE_SHIFT),
1345         CONFIG_READ_NRPAGES      = 4
1346 };
1347
1348 static int mgc_apply_recover_logs(struct obd_device *mgc,
1349                                   struct config_llog_data *cld,
1350                                   __u64 max_version,
1351                                   void *data, int datalen, bool mne_swab)
1352 {
1353         struct config_llog_instance *cfg = &cld->cld_cfg;
1354         struct lustre_sb_info       *lsi = s2lsi(cfg->cfg_sb);
1355         struct mgs_nidtbl_entry *entry;
1356         struct lustre_cfg       *lcfg;
1357         struct lustre_cfg_bufs   bufs;
1358         u64   prev_version = 0;
1359         char *inst;
1360         char *buf;
1361         int   bufsz;
1362         int   pos;
1363         int   rc  = 0;
1364         int   off = 0;
1365         ENTRY;
1366
1367         LASSERT(cfg->cfg_instance != NULL);
1368         LASSERT(cfg->cfg_sb == cfg->cfg_instance);
1369
1370         OBD_ALLOC(inst, PAGE_CACHE_SIZE);
1371         if (inst == NULL)
1372                 RETURN(-ENOMEM);
1373
1374         if (!IS_SERVER(lsi)) {
1375                 pos = snprintf(inst, PAGE_CACHE_SIZE, "%p", cfg->cfg_instance);
1376                 if (pos >= PAGE_CACHE_SIZE) {
1377                         OBD_FREE(inst, PAGE_CACHE_SIZE);
1378                         return -E2BIG;
1379                 }
1380         } else {
1381                 LASSERT(IS_MDT(lsi));
1382                 rc = server_name2svname(lsi->lsi_svname, inst, NULL,
1383                                         PAGE_CACHE_SIZE);
1384                 if (rc) {
1385                         OBD_FREE(inst, PAGE_CACHE_SIZE);
1386                         RETURN(-EINVAL);
1387                 }
1388                 pos = strlen(inst);
1389         }
1390
1391         ++pos;
1392         buf   = inst + pos;
1393         bufsz = PAGE_CACHE_SIZE - pos;
1394
1395         while (datalen > 0) {
1396                 int   entry_len = sizeof(*entry);
1397                 int   is_ost, i;
1398                 struct obd_device *obd;
1399                 char *obdname;
1400                 char *cname;
1401                 char *params;
1402                 char *uuid;
1403
1404                 rc = -EINVAL;
1405                 if (datalen < sizeof(*entry))
1406                         break;
1407
1408                 entry = (typeof(entry))(data + off);
1409
1410                 /* sanity check */
1411                 if (entry->mne_nid_type != 0) /* only support type 0 for ipv4 */
1412                         break;
1413                 if (entry->mne_nid_count == 0) /* at least one nid entry */
1414                         break;
1415                 if (entry->mne_nid_size != sizeof(lnet_nid_t))
1416                         break;
1417
1418                 entry_len += entry->mne_nid_count * entry->mne_nid_size;
1419                 if (datalen < entry_len) /* must have entry_len at least */
1420                         break;
1421
1422                 /* Keep this swab for normal mixed endian handling. LU-1644 */
1423                 if (mne_swab)
1424                         lustre_swab_mgs_nidtbl_entry(entry);
1425                 if (entry->mne_length > PAGE_CACHE_SIZE) {
1426                         CERROR("MNE too large (%u)\n", entry->mne_length);
1427                         break;
1428                 }
1429
1430                 if (entry->mne_length < entry_len)
1431                         break;
1432
1433                 off     += entry->mne_length;
1434                 datalen -= entry->mne_length;
1435                 if (datalen < 0)
1436                         break;
1437
1438                 if (entry->mne_version > max_version) {
1439                         CERROR("entry index(%lld) is over max_index(%lld)\n",
1440                                entry->mne_version, max_version);
1441                         break;
1442                 }
1443
1444                 if (prev_version >= entry->mne_version) {
1445                         CERROR("index unsorted, prev %lld, now %lld\n",
1446                                prev_version, entry->mne_version);
1447                         break;
1448                 }
1449                 prev_version = entry->mne_version;
1450
1451                 /*
1452                  * Write a string with format "nid::instance" to
1453                  * lustre/<osc|mdc>/<target>-<osc|mdc>-<instance>/import.
1454                  */
1455
1456                 is_ost = entry->mne_type == LDD_F_SV_TYPE_OST;
1457                 memset(buf, 0, bufsz);
1458                 obdname = buf;
1459                 pos = 0;
1460
1461                 /* lustre-OST0001-osc-<instance #> */
1462                 strcpy(obdname, cld->cld_logname);
1463                 cname = strrchr(obdname, '-');
1464                 if (cname == NULL) {
1465                         CERROR("mgc %s: invalid logname %s\n",
1466                                mgc->obd_name, obdname);
1467                         break;
1468                 }
1469
1470                 pos = cname - obdname;
1471                 obdname[pos] = 0;
1472                 pos += sprintf(obdname + pos, "-%s%04x",
1473                                   is_ost ? "OST" : "MDT", entry->mne_index);
1474
1475                 cname = is_ost ? "osc" : "mdc",
1476                 pos += sprintf(obdname + pos, "-%s-%s", cname, inst);
1477                 lustre_cfg_bufs_reset(&bufs, obdname);
1478
1479                 /* find the obd by obdname */
1480                 obd = class_name2obd(obdname);
1481                 if (obd == NULL) {
1482                         CDEBUG(D_INFO, "mgc %s: cannot find obdname %s\n",
1483                                mgc->obd_name, obdname);
1484                         rc = 0;
1485                         /* this is a safe race, when the ost is starting up...*/
1486                         continue;
1487                 }
1488
1489                 /* osc.import = "connection=<Conn UUID>::<target instance>" */
1490                 ++pos;
1491                 params = buf + pos;
1492                 pos += sprintf(params, "%s.import=%s", cname, "connection=");
1493                 uuid = buf + pos;
1494
1495                 down_read(&obd->u.cli.cl_sem);
1496                 if (obd->u.cli.cl_import == NULL) {
1497                         /* client does not connect to the OST yet */
1498                         up_read(&obd->u.cli.cl_sem);
1499                         rc = 0;
1500                         continue;
1501                 }
1502
1503                 /* iterate all nids to find one */
1504                 /* find uuid by nid */
1505                 rc = -ENOENT;
1506                 for (i = 0; i < entry->mne_nid_count; i++) {
1507                         rc = client_import_find_conn(obd->u.cli.cl_import,
1508                                                      entry->u.nids[i],
1509                                                      (struct obd_uuid *)uuid);
1510                         if (rc == 0)
1511                                 break;
1512                 }
1513
1514                 up_read(&obd->u.cli.cl_sem);
1515                 if (rc < 0) {
1516                         CERROR("mgc: cannot find uuid by nid %s\n",
1517                                libcfs_nid2str(entry->u.nids[0]));
1518                         break;
1519                 }
1520
1521                 CDEBUG(D_INFO, "Find uuid %s by nid %s\n",
1522                        uuid, libcfs_nid2str(entry->u.nids[0]));
1523
1524                 pos += strlen(uuid);
1525                 pos += sprintf(buf + pos, "::%u", entry->mne_instance);
1526                 LASSERT(pos < bufsz);
1527
1528                 lustre_cfg_bufs_set_string(&bufs, 1, params);
1529
1530                 rc = -ENOMEM;
1531                 lcfg = lustre_cfg_new(LCFG_PARAM, &bufs);
1532                 if (lcfg == NULL) {
1533                         CERROR("mgc: cannot allocate memory\n");
1534                         break;
1535                 }
1536
1537                 CDEBUG(D_INFO, "ir apply logs "LPD64"/"LPD64" for %s -> %s\n",
1538                        prev_version, max_version, obdname, params);
1539
1540                 rc = class_process_config(lcfg);
1541                 lustre_cfg_free(lcfg);
1542                 if (rc)
1543                         CDEBUG(D_INFO, "process config for %s error %d\n",
1544                                obdname, rc);
1545
1546                 /* continue, even one with error */
1547         }
1548
1549         OBD_FREE(inst, PAGE_CACHE_SIZE);
1550         RETURN(rc);
1551 }
1552
1553 /**
1554  * This function is called if this client was notified for target restarting
1555  * by the MGS. A CONFIG_READ RPC is going to send to fetch recovery logs.
1556  */
1557 static int mgc_process_recover_log(struct obd_device *obd,
1558                                    struct config_llog_data *cld)
1559 {
1560         struct ptlrpc_request *req = NULL;
1561         struct config_llog_instance *cfg = &cld->cld_cfg;
1562         struct mgs_config_body *body;
1563         struct mgs_config_res  *res;
1564         struct ptlrpc_bulk_desc *desc;
1565         struct page **pages;
1566         int nrpages;
1567         bool eof = true;
1568         bool mne_swab = false;
1569         int i;
1570         int ealen;
1571         int rc;
1572         ENTRY;
1573
1574         /* allocate buffer for bulk transfer.
1575          * if this is the first time for this mgs to read logs,
1576          * CONFIG_READ_NRPAGES_INIT will be used since it will read all logs
1577          * once; otherwise, it only reads increment of logs, this should be
1578          * small and CONFIG_READ_NRPAGES will be used.
1579          */
1580         nrpages = CONFIG_READ_NRPAGES;
1581         if (cfg->cfg_last_idx == 0) /* the first time */
1582                 nrpages = CONFIG_READ_NRPAGES_INIT;
1583
1584         OBD_ALLOC(pages, sizeof(*pages) * nrpages);
1585         if (pages == NULL)
1586                 GOTO(out, rc = -ENOMEM);
1587
1588         for (i = 0; i < nrpages; i++) {
1589                 pages[i] = alloc_page(GFP_IOFS);
1590                 if (pages[i] == NULL)
1591                         GOTO(out, rc = -ENOMEM);
1592         }
1593
1594 again:
1595         LASSERT(cld_is_recover(cld));
1596         LASSERT(mutex_is_locked(&cld->cld_lock));
1597         req = ptlrpc_request_alloc(class_exp2cliimp(cld->cld_mgcexp),
1598                                    &RQF_MGS_CONFIG_READ);
1599         if (req == NULL)
1600                 GOTO(out, rc = -ENOMEM);
1601
1602         rc = ptlrpc_request_pack(req, LUSTRE_MGS_VERSION, MGS_CONFIG_READ);
1603         if (rc)
1604                 GOTO(out, rc);
1605
1606         /* pack request */
1607         body = req_capsule_client_get(&req->rq_pill, &RMF_MGS_CONFIG_BODY);
1608         LASSERT(body != NULL);
1609         LASSERT(sizeof(body->mcb_name) > strlen(cld->cld_logname));
1610         if (strlcpy(body->mcb_name, cld->cld_logname, sizeof(body->mcb_name))
1611             >= sizeof(body->mcb_name))
1612                 GOTO(out, rc = -E2BIG);
1613         body->mcb_offset = cfg->cfg_last_idx + 1;
1614         body->mcb_type   = cld->cld_type;
1615         body->mcb_bits   = PAGE_CACHE_SHIFT;
1616         body->mcb_units  = nrpages;
1617
1618         /* allocate bulk transfer descriptor */
1619         desc = ptlrpc_prep_bulk_imp(req, nrpages, 1, BULK_PUT_SINK,
1620                                     MGS_BULK_PORTAL);
1621         if (desc == NULL)
1622                 GOTO(out, rc = -ENOMEM);
1623
1624         for (i = 0; i < nrpages; i++)
1625                 ptlrpc_prep_bulk_page_pin(desc, pages[i], 0, PAGE_CACHE_SIZE);
1626
1627         ptlrpc_request_set_replen(req);
1628         rc = ptlrpc_queue_wait(req);
1629         if (rc)
1630                 GOTO(out, rc);
1631
1632         res = req_capsule_server_get(&req->rq_pill, &RMF_MGS_CONFIG_RES);
1633         if (res->mcr_size < res->mcr_offset)
1634                 GOTO(out, rc = -EINVAL);
1635
1636         /* always update the index even though it might have errors with
1637          * handling the recover logs */
1638         cfg->cfg_last_idx = res->mcr_offset;
1639         eof = res->mcr_offset == res->mcr_size;
1640
1641         CDEBUG(D_INFO, "Latest version "LPD64", more %d.\n",
1642                res->mcr_offset, eof == false);
1643
1644         ealen = sptlrpc_cli_unwrap_bulk_read(req, req->rq_bulk, 0);
1645         if (ealen < 0)
1646                 GOTO(out, rc = ealen);
1647
1648         if (ealen > nrpages << PAGE_CACHE_SHIFT)
1649                 GOTO(out, rc = -EINVAL);
1650
1651         if (ealen == 0) { /* no logs transferred */
1652                 if (!eof)
1653                         rc = -EINVAL;
1654                 GOTO(out, rc);
1655         }
1656
1657         mne_swab = !!ptlrpc_rep_need_swab(req);
1658 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
1659         /* This import flag means the server did an extra swab of IR MNE
1660          * records (fixed in LU-1252), reverse it here if needed. LU-1644 */
1661         if (unlikely(req->rq_import->imp_need_mne_swab))
1662                 mne_swab = !mne_swab;
1663 #endif
1664
1665         for (i = 0; i < nrpages && ealen > 0; i++) {
1666                 int rc2;
1667                 void *ptr;
1668
1669                 ptr = kmap(pages[i]);
1670                 rc2 = mgc_apply_recover_logs(obd, cld, res->mcr_offset, ptr,
1671                                              min_t(int, ealen, PAGE_CACHE_SIZE),
1672                                              mne_swab);
1673                 kunmap(pages[i]);
1674                 if (rc2 < 0) {
1675                         CWARN("Process recover log %s error %d\n",
1676                               cld->cld_logname, rc2);
1677                         break;
1678                 }
1679
1680                 ealen -= PAGE_CACHE_SIZE;
1681         }
1682
1683 out:
1684         if (req)
1685                 ptlrpc_req_finished(req);
1686
1687         if (rc == 0 && !eof)
1688                 goto again;
1689
1690         if (pages) {
1691                 for (i = 0; i < nrpages; i++) {
1692                         if (pages[i] == NULL)
1693                                 break;
1694                         __free_page(pages[i]);
1695                 }
1696                 OBD_FREE(pages, sizeof(*pages) * nrpages);
1697         }
1698         return rc;
1699 }
1700
1701 /* Copy a remote log locally */
1702 static int mgc_llog_local_copy(const struct lu_env *env,
1703                                struct obd_device *obd,
1704                                struct llog_ctxt *rctxt,
1705                                struct llog_ctxt *lctxt, char *logname)
1706 {
1707         char    *temp_log;
1708         int      rc;
1709
1710         ENTRY;
1711
1712         /*
1713          * - copy it to backup using llog_backup()
1714          * - copy remote llog to logname using llog_backup()
1715          * - if failed then move bakup to logname again
1716          */
1717
1718         OBD_ALLOC(temp_log, strlen(logname) + 1);
1719         if (!temp_log)
1720                 RETURN(-ENOMEM);
1721         sprintf(temp_log, "%sT", logname);
1722
1723         /* make a copy of local llog at first */
1724         rc = llog_backup(env, obd, lctxt, lctxt, logname, temp_log);
1725         if (rc < 0 && rc != -ENOENT)
1726                 GOTO(out, rc);
1727         /* copy remote llog to the local copy */
1728         rc = llog_backup(env, obd, rctxt, lctxt, logname, logname);
1729         if (rc == -ENOENT) {
1730                 /* no remote llog, delete local one too */
1731                 llog_erase(env, lctxt, NULL, logname);
1732         } else if (rc < 0) {
1733                 /* error during backup, get local one back from the copy */
1734                 llog_backup(env, obd, lctxt, lctxt, temp_log, logname);
1735 out:
1736                 CERROR("%s: failed to copy remote log %s: rc = %d\n",
1737                        obd->obd_name, logname, rc);
1738         }
1739         llog_erase(env, lctxt, NULL, temp_log);
1740         OBD_FREE(temp_log, strlen(logname) + 1);
1741         return rc;
1742 }
1743
1744 /* local_only means it cannot get remote llogs */
1745 static int mgc_process_cfg_log(struct obd_device *mgc,
1746                                struct config_llog_data *cld, int local_only)
1747 {
1748         struct llog_ctxt        *ctxt, *lctxt = NULL;
1749         struct client_obd       *cli = &mgc->u.cli;
1750         struct lustre_sb_info   *lsi = NULL;
1751         int                      rc = 0;
1752         bool                     sptlrpc_started = false;
1753         struct lu_env           *env;
1754
1755         ENTRY;
1756
1757         LASSERT(cld);
1758         LASSERT(mutex_is_locked(&cld->cld_lock));
1759
1760         /*
1761          * local copy of sptlrpc log is controlled elsewhere, don't try to
1762          * read it up here.
1763          */
1764         if (cld_is_sptlrpc(cld) && local_only)
1765                 RETURN(0);
1766
1767         if (cld->cld_cfg.cfg_sb)
1768                 lsi = s2lsi(cld->cld_cfg.cfg_sb);
1769
1770         OBD_ALLOC_PTR(env);
1771         if (env == NULL)
1772                 RETURN(-ENOMEM);
1773
1774         rc = lu_env_init(env, LCT_MG_THREAD);
1775         if (rc)
1776                 GOTO(out_free, rc);
1777
1778         ctxt = llog_get_context(mgc, LLOG_CONFIG_REPL_CTXT);
1779         LASSERT(ctxt);
1780
1781         lctxt = llog_get_context(mgc, LLOG_CONFIG_ORIG_CTXT);
1782
1783         /* Copy the setup log locally if we can. Don't mess around if we're
1784          * running an MGS though (logs are already local). */
1785         if (lctxt && lsi && IS_SERVER(lsi) && !IS_MGS(lsi) &&
1786             cli->cl_mgc_configs_dir != NULL &&
1787             lu2dt_dev(cli->cl_mgc_configs_dir->do_lu.lo_dev) ==
1788             lsi->lsi_dt_dev) {
1789                 if (!local_only)
1790                         /* Only try to copy log if we have the lock. */
1791                         rc = mgc_llog_local_copy(env, mgc, ctxt, lctxt,
1792                                                  cld->cld_logname);
1793                 if (local_only || rc) {
1794                         if (strcmp(cld->cld_logname, PARAMS_FILENAME) != 0 &&
1795                             llog_is_empty(env, lctxt, cld->cld_logname)) {
1796                                 LCONSOLE_ERROR_MSG(0x13a, "Failed to get MGS "
1797                                                    "log %s and no local copy."
1798                                                    "\n", cld->cld_logname);
1799                                 GOTO(out_pop, rc = -ENOENT);
1800                         }
1801                         CDEBUG(D_MGC, "Failed to get MGS log %s, using local "
1802                                "copy for now, will try to update later.\n",
1803                                cld->cld_logname);
1804                         rc = 0;
1805                 }
1806                 /* Now, whether we copied or not, start using the local llog.
1807                  * If we failed to copy, we'll start using whatever the old
1808                  * log has. */
1809                 llog_ctxt_put(ctxt);
1810                 ctxt = lctxt;
1811                 lctxt = NULL;
1812         } else {
1813                 if (local_only) /* no local log at client side */
1814                         GOTO(out_pop, rc = -EIO);
1815         }
1816
1817         if (cld_is_sptlrpc(cld)) {
1818                 sptlrpc_conf_log_update_begin(cld->cld_logname);
1819                 sptlrpc_started = true;
1820         }
1821
1822         /* logname and instance info should be the same, so use our
1823          * copy of the instance for the update.  The cfg_last_idx will
1824          * be updated here. */
1825         rc = class_config_parse_llog(env, ctxt, cld->cld_logname,
1826                                      &cld->cld_cfg);
1827         EXIT;
1828
1829 out_pop:
1830         __llog_ctxt_put(env, ctxt);
1831         if (lctxt)
1832                 __llog_ctxt_put(env, lctxt);
1833
1834         /*
1835          * update settings on existing OBDs. doing it inside
1836          * of llog_process_lock so no device is attaching/detaching
1837          * in parallel.
1838          * the logname must be <fsname>-sptlrpc
1839          */
1840         if (sptlrpc_started) {
1841                 LASSERT(cld_is_sptlrpc(cld));
1842                 sptlrpc_conf_log_update_end(cld->cld_logname);
1843                 class_notify_sptlrpc_conf(cld->cld_logname,
1844                                           strlen(cld->cld_logname) -
1845                                           strlen("-sptlrpc"));
1846         }
1847
1848         lu_env_fini(env);
1849 out_free:
1850         OBD_FREE_PTR(env);
1851         return rc;
1852 }
1853
1854 /** Get a config log from the MGS and process it.
1855  * This func is called for both clients and servers.
1856  * Copy the log locally before parsing it if appropriate (non-MGS server)
1857  */
1858 int mgc_process_log(struct obd_device *mgc, struct config_llog_data *cld)
1859 {
1860         struct lustre_handle lockh = { 0 };
1861         __u64 flags = LDLM_FL_NO_LRU;
1862         int rc = 0, rcl;
1863         ENTRY;
1864
1865         LASSERT(cld);
1866
1867         /* I don't want multiple processes running process_log at once --
1868            sounds like badness.  It actually might be fine, as long as
1869            we're not trying to update from the same log
1870            simultaneously (in which case we should use a per-log sem.) */
1871         mutex_lock(&cld->cld_lock);
1872         if (cld->cld_stopping) {
1873                 mutex_unlock(&cld->cld_lock);
1874                 RETURN(0);
1875         }
1876
1877         OBD_FAIL_TIMEOUT(OBD_FAIL_MGC_PAUSE_PROCESS_LOG, 20);
1878
1879         CDEBUG(D_MGC, "Process log %s:%p from %d\n", cld->cld_logname,
1880                cld->cld_cfg.cfg_instance, cld->cld_cfg.cfg_last_idx + 1);
1881
1882         /* Get the cfg lock on the llog */
1883         rcl = mgc_enqueue(mgc->u.cli.cl_mgc_mgsexp, NULL, LDLM_PLAIN, NULL,
1884                           LCK_CR, &flags, NULL, NULL, NULL,
1885                           cld, 0, NULL, &lockh);
1886         if (rcl == 0) {
1887                 /* Get the cld, it will be released in mgc_blocking_ast. */
1888                 config_log_get(cld);
1889                 rc = ldlm_lock_set_data(&lockh, (void *)cld);
1890                 LASSERT(rc == 0);
1891         } else {
1892                 CDEBUG(D_MGC, "Can't get cfg lock: %d\n", rcl);
1893
1894                 /* mark cld_lostlock so that it will requeue
1895                  * after MGC becomes available. */
1896                 cld->cld_lostlock = 1;
1897                 /* Get extra reference, it will be put in requeue thread */
1898                 config_log_get(cld);
1899         }
1900
1901
1902         if (cld_is_recover(cld)) {
1903                 rc = 0; /* this is not a fatal error for recover log */
1904                 if (rcl == 0)
1905                         rc = mgc_process_recover_log(mgc, cld);
1906         } else {
1907                 rc = mgc_process_cfg_log(mgc, cld, rcl != 0);
1908         }
1909
1910         CDEBUG(D_MGC, "%s: configuration from log '%s' %sed (%d).\n",
1911                mgc->obd_name, cld->cld_logname, rc ? "fail" : "succeed", rc);
1912
1913         mutex_unlock(&cld->cld_lock);
1914
1915         /* Now drop the lock so MGS can revoke it */
1916         if (!rcl) {
1917                 rcl = mgc_cancel(mgc->u.cli.cl_mgc_mgsexp, LCK_CR, &lockh);
1918                 if (rcl)
1919                         CERROR("Can't drop cfg lock: %d\n", rcl);
1920         }
1921
1922         RETURN(rc);
1923 }
1924
1925
1926 /** Called from lustre_process_log.
1927  * LCFG_LOG_START gets the config log from the MGS, processes it to start
1928  * any services, and adds it to the list logs to watch (follow).
1929  */
1930 static int mgc_process_config(struct obd_device *obd, obd_count len, void *buf)
1931 {
1932         struct lustre_cfg *lcfg = buf;
1933         struct config_llog_instance *cfg = NULL;
1934         char *logname;
1935         int rc = 0;
1936         ENTRY;
1937
1938         switch(lcfg->lcfg_command) {
1939         case LCFG_LOV_ADD_OBD: {
1940                 /* Overloading this cfg command: register a new target */
1941                 struct mgs_target_info *mti;
1942
1943                 if (LUSTRE_CFG_BUFLEN(lcfg, 1) !=
1944                     sizeof(struct mgs_target_info))
1945                         GOTO(out, rc = -EINVAL);
1946
1947                 mti = (struct mgs_target_info *)lustre_cfg_buf(lcfg, 1);
1948                 CDEBUG(D_MGC, "add_target %s %#x\n",
1949                        mti->mti_svname, mti->mti_flags);
1950                 rc = mgc_target_register(obd->u.cli.cl_mgc_mgsexp, mti);
1951                 break;
1952         }
1953         case LCFG_LOV_DEL_OBD:
1954                 /* Unregister has no meaning at the moment. */
1955                 CERROR("lov_del_obd unimplemented\n");
1956                 rc = -ENOSYS;
1957                 break;
1958         case LCFG_SPTLRPC_CONF: {
1959                 rc = sptlrpc_process_config(lcfg);
1960                 break;
1961         }
1962         case LCFG_LOG_START: {
1963                 struct config_llog_data *cld;
1964                 struct super_block *sb;
1965
1966                 logname = lustre_cfg_string(lcfg, 1);
1967                 cfg = (struct config_llog_instance *)lustre_cfg_buf(lcfg, 2);
1968                 sb = *(struct super_block **)lustre_cfg_buf(lcfg, 3);
1969
1970                 CDEBUG(D_MGC, "parse_log %s from %d\n", logname,
1971                        cfg->cfg_last_idx);
1972
1973                 /* We're only called through here on the initial mount */
1974                 rc = config_log_add(obd, logname, cfg, sb);
1975                 if (rc)
1976                         break;
1977                 cld = config_log_find(logname, cfg);
1978                 if (cld == NULL) {
1979                         rc = -ENOENT;
1980                         break;
1981                 }
1982
1983                 /* COMPAT_146 */
1984                 /* FIXME only set this for old logs!  Right now this forces
1985                    us to always skip the "inside markers" check */
1986                 cld->cld_cfg.cfg_flags |= CFG_F_COMPAT146;
1987
1988                 rc = mgc_process_log(obd, cld);
1989                 if (rc == 0 && cld->cld_recover != NULL) {
1990                         if (OCD_HAS_FLAG(&obd->u.cli.cl_import->
1991                                          imp_connect_data, IMP_RECOV)) {
1992                                 rc = mgc_process_log(obd, cld->cld_recover);
1993                         } else {
1994                                 struct config_llog_data *cir = cld->cld_recover;
1995                                 cld->cld_recover = NULL;
1996                                 config_log_put(cir);
1997                         }
1998                         if (rc)
1999                                 CERROR("Cannot process recover llog %d\n", rc);
2000                 }
2001
2002                 if (rc == 0 && cld->cld_params != NULL) {
2003                         rc = mgc_process_log(obd, cld->cld_params);
2004                         if (rc == -ENOENT) {
2005                                 CDEBUG(D_MGC, "There is no params "
2006                                               "config file yet\n");
2007                                 rc = 0;
2008                         }
2009                         /* params log is optional */
2010                         if (rc)
2011                                 CERROR("%s: can't process params llog: rc = %d\n",
2012                                        obd->obd_name, rc);
2013                 }
2014                 config_log_put(cld);
2015
2016                 break;
2017         }
2018         case LCFG_LOG_END: {
2019                 logname = lustre_cfg_string(lcfg, 1);
2020
2021                 if (lcfg->lcfg_bufcount >= 2)
2022                         cfg = (struct config_llog_instance *)lustre_cfg_buf(
2023                                 lcfg, 2);
2024                 rc = config_log_end(logname, cfg);
2025                 break;
2026         }
2027         default: {
2028                 CERROR("Unknown command: %d\n", lcfg->lcfg_command);
2029                 GOTO(out, rc = -EINVAL);
2030
2031         }
2032         }
2033 out:
2034         RETURN(rc);
2035 }
2036
2037 struct obd_ops mgc_obd_ops = {
2038         .o_owner        = THIS_MODULE,
2039         .o_setup        = mgc_setup,
2040         .o_precleanup   = mgc_precleanup,
2041         .o_cleanup      = mgc_cleanup,
2042         .o_add_conn     = client_import_add_conn,
2043         .o_del_conn     = client_import_del_conn,
2044         .o_connect      = client_connect_import,
2045         .o_disconnect   = client_disconnect_export,
2046         .o_set_info_async = mgc_set_info_async,
2047         .o_get_info       = mgc_get_info,
2048         .o_import_event = mgc_import_event,
2049         .o_process_config = mgc_process_config,
2050 };
2051
2052 int __init mgc_init(void)
2053 {
2054         return class_register_type(&mgc_obd_ops, NULL, true, NULL,
2055                                    LUSTRE_MGC_NAME, NULL);
2056 }
2057
2058 static void /*__exit*/ mgc_exit(void)
2059 {
2060         class_unregister_type(LUSTRE_MGC_NAME);
2061 }
2062
2063 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
2064 MODULE_DESCRIPTION("Lustre Management Client");
2065 MODULE_LICENSE("GPL");
2066
2067 module_init(mgc_init);
2068 module_exit(mgc_exit);