drbd: Refuse to change network options online when...
[linux-block.git] / drivers / block / drbd / drbd_nl.c
1 /*
2    drbd_nl.c
3
4    This file is part of DRBD by Philipp Reisner and Lars Ellenberg.
5
6    Copyright (C) 2001-2008, LINBIT Information Technologies GmbH.
7    Copyright (C) 1999-2008, Philipp Reisner <philipp.reisner@linbit.com>.
8    Copyright (C) 2002-2008, Lars Ellenberg <lars.ellenberg@linbit.com>.
9
10    drbd is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2, or (at your option)
13    any later version.
14
15    drbd is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with drbd; see the file COPYING.  If not, write to
22    the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23
24  */
25
26 #include <linux/module.h>
27 #include <linux/drbd.h>
28 #include <linux/in.h>
29 #include <linux/fs.h>
30 #include <linux/file.h>
31 #include <linux/slab.h>
32 #include <linux/blkpg.h>
33 #include <linux/cpumask.h>
34 #include "drbd_int.h"
35 #include "drbd_req.h"
36 #include "drbd_wrappers.h"
37 #include <asm/unaligned.h>
38 #include <linux/drbd_limits.h>
39 #include <linux/kthread.h>
40
41 #include <net/genetlink.h>
42
43 /* .doit */
44 // int drbd_adm_create_resource(struct sk_buff *skb, struct genl_info *info);
45 // int drbd_adm_delete_resource(struct sk_buff *skb, struct genl_info *info);
46
47 int drbd_adm_add_minor(struct sk_buff *skb, struct genl_info *info);
48 int drbd_adm_delete_minor(struct sk_buff *skb, struct genl_info *info);
49
50 int drbd_adm_create_connection(struct sk_buff *skb, struct genl_info *info);
51 int drbd_adm_delete_connection(struct sk_buff *skb, struct genl_info *info);
52 int drbd_adm_down(struct sk_buff *skb, struct genl_info *info);
53
54 int drbd_adm_set_role(struct sk_buff *skb, struct genl_info *info);
55 int drbd_adm_attach(struct sk_buff *skb, struct genl_info *info);
56 int drbd_adm_disk_opts(struct sk_buff *skb, struct genl_info *info);
57 int drbd_adm_detach(struct sk_buff *skb, struct genl_info *info);
58 int drbd_adm_connect(struct sk_buff *skb, struct genl_info *info);
59 int drbd_adm_net_opts(struct sk_buff *skb, struct genl_info *info);
60 int drbd_adm_resize(struct sk_buff *skb, struct genl_info *info);
61 int drbd_adm_start_ov(struct sk_buff *skb, struct genl_info *info);
62 int drbd_adm_new_c_uuid(struct sk_buff *skb, struct genl_info *info);
63 int drbd_adm_disconnect(struct sk_buff *skb, struct genl_info *info);
64 int drbd_adm_invalidate(struct sk_buff *skb, struct genl_info *info);
65 int drbd_adm_invalidate_peer(struct sk_buff *skb, struct genl_info *info);
66 int drbd_adm_pause_sync(struct sk_buff *skb, struct genl_info *info);
67 int drbd_adm_resume_sync(struct sk_buff *skb, struct genl_info *info);
68 int drbd_adm_suspend_io(struct sk_buff *skb, struct genl_info *info);
69 int drbd_adm_resume_io(struct sk_buff *skb, struct genl_info *info);
70 int drbd_adm_outdate(struct sk_buff *skb, struct genl_info *info);
71 int drbd_adm_resource_opts(struct sk_buff *skb, struct genl_info *info);
72 int drbd_adm_get_status(struct sk_buff *skb, struct genl_info *info);
73 int drbd_adm_get_timeout_type(struct sk_buff *skb, struct genl_info *info);
74 /* .dumpit */
75 int drbd_adm_get_status_all(struct sk_buff *skb, struct netlink_callback *cb);
76
77 #include <linux/drbd_genl_api.h>
78 #include <linux/genl_magic_func.h>
79
80 /* used blkdev_get_by_path, to claim our meta data device(s) */
81 static char *drbd_m_holder = "Hands off! this is DRBD's meta data device.";
82
83 /* Configuration is strictly serialized, because generic netlink message
84  * processing is strictly serialized by the genl_lock().
85  * Which means we can use one static global drbd_config_context struct.
86  */
87 static struct drbd_config_context {
88         /* assigned from drbd_genlmsghdr */
89         unsigned int minor;
90         /* assigned from request attributes, if present */
91         unsigned int volume;
92 #define VOLUME_UNSPECIFIED              (-1U)
93         /* pointer into the request skb,
94          * limited lifetime! */
95         char *conn_name;
96
97         /* reply buffer */
98         struct sk_buff *reply_skb;
99         /* pointer into reply buffer */
100         struct drbd_genlmsghdr *reply_dh;
101         /* resolved from attributes, if possible */
102         struct drbd_conf *mdev;
103         struct drbd_tconn *tconn;
104 } adm_ctx;
105
106 static void drbd_adm_send_reply(struct sk_buff *skb, struct genl_info *info)
107 {
108         genlmsg_end(skb, genlmsg_data(nlmsg_data(nlmsg_hdr(skb))));
109         if (genlmsg_reply(skb, info))
110                 printk(KERN_ERR "drbd: error sending genl reply\n");
111 }
112
113 /* Used on a fresh "drbd_adm_prepare"d reply_skb, this cannot fail: The only
114  * reason it could fail was no space in skb, and there are 4k available. */
115 int drbd_msg_put_info(const char *info)
116 {
117         struct sk_buff *skb = adm_ctx.reply_skb;
118         struct nlattr *nla;
119         int err = -EMSGSIZE;
120
121         if (!info || !info[0])
122                 return 0;
123
124         nla = nla_nest_start(skb, DRBD_NLA_CFG_REPLY);
125         if (!nla)
126                 return err;
127
128         err = nla_put_string(skb, T_info_text, info);
129         if (err) {
130                 nla_nest_cancel(skb, nla);
131                 return err;
132         } else
133                 nla_nest_end(skb, nla);
134         return 0;
135 }
136
137 /* This would be a good candidate for a "pre_doit" hook,
138  * and per-family private info->pointers.
139  * But we need to stay compatible with older kernels.
140  * If it returns successfully, adm_ctx members are valid.
141  */
142 #define DRBD_ADM_NEED_MINOR     1
143 #define DRBD_ADM_NEED_CONN      2
144 static int drbd_adm_prepare(struct sk_buff *skb, struct genl_info *info,
145                 unsigned flags)
146 {
147         struct drbd_genlmsghdr *d_in = info->userhdr;
148         const u8 cmd = info->genlhdr->cmd;
149         int err;
150
151         memset(&adm_ctx, 0, sizeof(adm_ctx));
152
153         /* genl_rcv_msg only checks for CAP_NET_ADMIN on "GENL_ADMIN_PERM" :( */
154         if (cmd != DRBD_ADM_GET_STATUS
155         && security_netlink_recv(skb, CAP_SYS_ADMIN))
156                return -EPERM;
157
158         adm_ctx.reply_skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
159         if (!adm_ctx.reply_skb)
160                 goto fail;
161
162         adm_ctx.reply_dh = genlmsg_put_reply(adm_ctx.reply_skb,
163                                         info, &drbd_genl_family, 0, cmd);
164         /* put of a few bytes into a fresh skb of >= 4k will always succeed.
165          * but anyways */
166         if (!adm_ctx.reply_dh)
167                 goto fail;
168
169         adm_ctx.reply_dh->minor = d_in->minor;
170         adm_ctx.reply_dh->ret_code = NO_ERROR;
171
172         if (info->attrs[DRBD_NLA_CFG_CONTEXT]) {
173                 struct nlattr *nla;
174                 /* parse and validate only */
175                 err = drbd_cfg_context_from_attrs(NULL, info);
176                 if (err)
177                         goto fail;
178
179                 /* It was present, and valid,
180                  * copy it over to the reply skb. */
181                 err = nla_put_nohdr(adm_ctx.reply_skb,
182                                 info->attrs[DRBD_NLA_CFG_CONTEXT]->nla_len,
183                                 info->attrs[DRBD_NLA_CFG_CONTEXT]);
184                 if (err)
185                         goto fail;
186
187                 /* and assign stuff to the global adm_ctx */
188                 nla = nested_attr_tb[__nla_type(T_ctx_volume)];
189                 adm_ctx.volume = nla ? nla_get_u32(nla) : VOLUME_UNSPECIFIED;
190                 nla = nested_attr_tb[__nla_type(T_ctx_conn_name)];
191                 if (nla)
192                         adm_ctx.conn_name = nla_data(nla);
193         } else
194                 adm_ctx.volume = VOLUME_UNSPECIFIED;
195
196         adm_ctx.minor = d_in->minor;
197         adm_ctx.mdev = minor_to_mdev(d_in->minor);
198         adm_ctx.tconn = conn_get_by_name(adm_ctx.conn_name);
199
200         if (!adm_ctx.mdev && (flags & DRBD_ADM_NEED_MINOR)) {
201                 drbd_msg_put_info("unknown minor");
202                 return ERR_MINOR_INVALID;
203         }
204         if (!adm_ctx.tconn && (flags & DRBD_ADM_NEED_CONN)) {
205                 drbd_msg_put_info("unknown connection");
206                 return ERR_INVALID_REQUEST;
207         }
208
209         /* some more paranoia, if the request was over-determined */
210         if (adm_ctx.mdev && adm_ctx.tconn &&
211             adm_ctx.mdev->tconn != adm_ctx.tconn) {
212                 pr_warning("request: minor=%u, conn=%s; but that minor belongs to connection %s\n",
213                                 adm_ctx.minor, adm_ctx.conn_name, adm_ctx.mdev->tconn->name);
214                 drbd_msg_put_info("minor exists in different connection");
215                 return ERR_INVALID_REQUEST;
216         }
217         if (adm_ctx.mdev &&
218             adm_ctx.volume != VOLUME_UNSPECIFIED &&
219             adm_ctx.volume != adm_ctx.mdev->vnr) {
220                 pr_warning("request: minor=%u, volume=%u; but that minor is volume %u in %s\n",
221                                 adm_ctx.minor, adm_ctx.volume,
222                                 adm_ctx.mdev->vnr, adm_ctx.mdev->tconn->name);
223                 drbd_msg_put_info("minor exists as different volume");
224                 return ERR_INVALID_REQUEST;
225         }
226
227         return NO_ERROR;
228
229 fail:
230         nlmsg_free(adm_ctx.reply_skb);
231         adm_ctx.reply_skb = NULL;
232         return -ENOMEM;
233 }
234
235 static int drbd_adm_finish(struct genl_info *info, int retcode)
236 {
237         struct nlattr *nla;
238         const char *conn_name = NULL;
239
240         if (adm_ctx.tconn) {
241                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
242                 adm_ctx.tconn = NULL;
243         }
244
245         if (!adm_ctx.reply_skb)
246                 return -ENOMEM;
247
248         adm_ctx.reply_dh->ret_code = retcode;
249
250         nla = info->attrs[DRBD_NLA_CFG_CONTEXT];
251         if (nla) {
252                 nla = nla_find_nested(nla, __nla_type(T_ctx_conn_name));
253                 if (nla)
254                         conn_name = nla_data(nla);
255         }
256
257         drbd_adm_send_reply(adm_ctx.reply_skb, info);
258         return 0;
259 }
260
261 static void setup_khelper_env(struct drbd_tconn *tconn, char **envp)
262 {
263         char *afs;
264         struct net_conf *nc;
265
266         rcu_read_lock();
267         nc = rcu_dereference(tconn->net_conf);
268         if (nc) {
269                 switch (((struct sockaddr *)nc->peer_addr)->sa_family) {
270                 case AF_INET6:
271                         afs = "ipv6";
272                         snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI6",
273                                  &((struct sockaddr_in6 *)nc->peer_addr)->sin6_addr);
274                         break;
275                 case AF_INET:
276                         afs = "ipv4";
277                         snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI4",
278                                  &((struct sockaddr_in *)nc->peer_addr)->sin_addr);
279                         break;
280                 default:
281                         afs = "ssocks";
282                         snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI4",
283                                  &((struct sockaddr_in *)nc->peer_addr)->sin_addr);
284                 }
285                 snprintf(envp[3], 20, "DRBD_PEER_AF=%s", afs);
286         }
287         rcu_read_unlock();
288 }
289
290 int drbd_khelper(struct drbd_conf *mdev, char *cmd)
291 {
292         char *envp[] = { "HOME=/",
293                         "TERM=linux",
294                         "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
295                          (char[20]) { }, /* address family */
296                          (char[60]) { }, /* address */
297                         NULL };
298         char mb[12];
299         char *argv[] = {usermode_helper, cmd, mb, NULL };
300         struct sib_info sib;
301         int ret;
302
303         snprintf(mb, 12, "minor-%d", mdev_to_minor(mdev));
304         setup_khelper_env(mdev->tconn, envp);
305
306         /* The helper may take some time.
307          * write out any unsynced meta data changes now */
308         drbd_md_sync(mdev);
309
310         dev_info(DEV, "helper command: %s %s %s\n", usermode_helper, cmd, mb);
311         sib.sib_reason = SIB_HELPER_PRE;
312         sib.helper_name = cmd;
313         drbd_bcast_event(mdev, &sib);
314         ret = call_usermodehelper(usermode_helper, argv, envp, 1);
315         if (ret)
316                 dev_warn(DEV, "helper command: %s %s %s exit code %u (0x%x)\n",
317                                 usermode_helper, cmd, mb,
318                                 (ret >> 8) & 0xff, ret);
319         else
320                 dev_info(DEV, "helper command: %s %s %s exit code %u (0x%x)\n",
321                                 usermode_helper, cmd, mb,
322                                 (ret >> 8) & 0xff, ret);
323         sib.sib_reason = SIB_HELPER_POST;
324         sib.helper_exit_code = ret;
325         drbd_bcast_event(mdev, &sib);
326
327         if (ret < 0) /* Ignore any ERRNOs we got. */
328                 ret = 0;
329
330         return ret;
331 }
332
333 static void conn_md_sync(struct drbd_tconn *tconn)
334 {
335         struct drbd_conf *mdev;
336         int vnr;
337
338         rcu_read_lock();
339         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
340                 kref_get(&mdev->kref);
341                 rcu_read_unlock();
342                 drbd_md_sync(mdev);
343                 kref_put(&mdev->kref, &drbd_minor_destroy);
344                 rcu_read_lock();
345         }
346         rcu_read_unlock();
347 }
348
349 int conn_khelper(struct drbd_tconn *tconn, char *cmd)
350 {
351         char *envp[] = { "HOME=/",
352                         "TERM=linux",
353                         "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
354                          (char[20]) { }, /* address family */
355                          (char[60]) { }, /* address */
356                         NULL };
357         char *argv[] = {usermode_helper, cmd, tconn->name, NULL };
358         int ret;
359
360         setup_khelper_env(tconn, envp);
361         conn_md_sync(tconn);
362
363         conn_info(tconn, "helper command: %s %s %s\n", usermode_helper, cmd, tconn->name);
364         /* TODO: conn_bcast_event() ?? */
365
366         ret = call_usermodehelper(usermode_helper, argv, envp, 1);
367         if (ret)
368                 conn_warn(tconn, "helper command: %s %s %s exit code %u (0x%x)\n",
369                           usermode_helper, cmd, tconn->name,
370                           (ret >> 8) & 0xff, ret);
371         else
372                 conn_info(tconn, "helper command: %s %s %s exit code %u (0x%x)\n",
373                           usermode_helper, cmd, tconn->name,
374                           (ret >> 8) & 0xff, ret);
375         /* TODO: conn_bcast_event() ?? */
376
377         if (ret < 0) /* Ignore any ERRNOs we got. */
378                 ret = 0;
379
380         return ret;
381 }
382
383 static enum drbd_fencing_p highest_fencing_policy(struct drbd_tconn *tconn)
384 {
385         enum drbd_fencing_p fp = FP_NOT_AVAIL;
386         struct drbd_conf *mdev;
387         int vnr;
388
389         rcu_read_lock();
390         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
391                 if (get_ldev_if_state(mdev, D_CONSISTENT)) {
392                         fp = max_t(enum drbd_fencing_p, fp,
393                                    rcu_dereference(mdev->ldev->disk_conf)->fencing);
394                         put_ldev(mdev);
395                 }
396         }
397         rcu_read_unlock();
398
399         return fp;
400 }
401
402 bool conn_try_outdate_peer(struct drbd_tconn *tconn)
403 {
404         union drbd_state mask = { };
405         union drbd_state val = { };
406         enum drbd_fencing_p fp;
407         char *ex_to_string;
408         int r;
409
410         if (tconn->cstate >= C_WF_REPORT_PARAMS) {
411                 conn_err(tconn, "Expected cstate < C_WF_REPORT_PARAMS\n");
412                 return false;
413         }
414
415         fp = highest_fencing_policy(tconn);
416         switch (fp) {
417         case FP_NOT_AVAIL:
418                 conn_warn(tconn, "Not fencing peer, I'm not even Consistent myself.\n");
419                 goto out;
420         case FP_DONT_CARE:
421                 return true;
422         default: ;
423         }
424
425         r = conn_khelper(tconn, "fence-peer");
426
427         switch ((r>>8) & 0xff) {
428         case 3: /* peer is inconsistent */
429                 ex_to_string = "peer is inconsistent or worse";
430                 mask.pdsk = D_MASK;
431                 val.pdsk = D_INCONSISTENT;
432                 break;
433         case 4: /* peer got outdated, or was already outdated */
434                 ex_to_string = "peer was fenced";
435                 mask.pdsk = D_MASK;
436                 val.pdsk = D_OUTDATED;
437                 break;
438         case 5: /* peer was down */
439                 if (conn_highest_disk(tconn) == D_UP_TO_DATE) {
440                         /* we will(have) create(d) a new UUID anyways... */
441                         ex_to_string = "peer is unreachable, assumed to be dead";
442                         mask.pdsk = D_MASK;
443                         val.pdsk = D_OUTDATED;
444                 } else {
445                         ex_to_string = "peer unreachable, doing nothing since disk != UpToDate";
446                 }
447                 break;
448         case 6: /* Peer is primary, voluntarily outdate myself.
449                  * This is useful when an unconnected R_SECONDARY is asked to
450                  * become R_PRIMARY, but finds the other peer being active. */
451                 ex_to_string = "peer is active";
452                 conn_warn(tconn, "Peer is primary, outdating myself.\n");
453                 mask.disk = D_MASK;
454                 val.disk = D_OUTDATED;
455                 break;
456         case 7:
457                 if (fp != FP_STONITH)
458                         conn_err(tconn, "fence-peer() = 7 && fencing != Stonith !!!\n");
459                 ex_to_string = "peer was stonithed";
460                 mask.pdsk = D_MASK;
461                 val.pdsk = D_OUTDATED;
462                 break;
463         default:
464                 /* The script is broken ... */
465                 conn_err(tconn, "fence-peer helper broken, returned %d\n", (r>>8)&0xff);
466                 return false; /* Eventually leave IO frozen */
467         }
468
469         conn_info(tconn, "fence-peer helper returned %d (%s)\n",
470                   (r>>8) & 0xff, ex_to_string);
471
472  out:
473
474         /* Not using
475            conn_request_state(tconn, mask, val, CS_VERBOSE);
476            here, because we might were able to re-establish the connection in the
477            meantime. */
478         spin_lock_irq(&tconn->req_lock);
479         if (tconn->cstate < C_WF_REPORT_PARAMS)
480                 _conn_request_state(tconn, mask, val, CS_VERBOSE);
481         spin_unlock_irq(&tconn->req_lock);
482
483         return conn_highest_pdsk(tconn) <= D_OUTDATED;
484 }
485
486 static int _try_outdate_peer_async(void *data)
487 {
488         struct drbd_tconn *tconn = (struct drbd_tconn *)data;
489
490         conn_try_outdate_peer(tconn);
491
492         kref_put(&tconn->kref, &conn_destroy);
493         return 0;
494 }
495
496 void conn_try_outdate_peer_async(struct drbd_tconn *tconn)
497 {
498         struct task_struct *opa;
499
500         kref_get(&tconn->kref);
501         opa = kthread_run(_try_outdate_peer_async, tconn, "drbd_async_h");
502         if (IS_ERR(opa)) {
503                 conn_err(tconn, "out of mem, failed to invoke fence-peer helper\n");
504                 kref_put(&tconn->kref, &conn_destroy);
505         }
506 }
507
508 enum drbd_state_rv
509 drbd_set_role(struct drbd_conf *mdev, enum drbd_role new_role, int force)
510 {
511         const int max_tries = 4;
512         enum drbd_state_rv rv = SS_UNKNOWN_ERROR;
513         struct net_conf *nc;
514         int try = 0;
515         int forced = 0;
516         union drbd_state mask, val;
517
518         if (new_role == R_PRIMARY)
519                 request_ping(mdev->tconn); /* Detect a dead peer ASAP */
520
521         mutex_lock(mdev->state_mutex);
522
523         mask.i = 0; mask.role = R_MASK;
524         val.i  = 0; val.role  = new_role;
525
526         while (try++ < max_tries) {
527                 rv = _drbd_request_state(mdev, mask, val, CS_WAIT_COMPLETE);
528
529                 /* in case we first succeeded to outdate,
530                  * but now suddenly could establish a connection */
531                 if (rv == SS_CW_FAILED_BY_PEER && mask.pdsk != 0) {
532                         val.pdsk = 0;
533                         mask.pdsk = 0;
534                         continue;
535                 }
536
537                 if (rv == SS_NO_UP_TO_DATE_DISK && force &&
538                     (mdev->state.disk < D_UP_TO_DATE &&
539                      mdev->state.disk >= D_INCONSISTENT)) {
540                         mask.disk = D_MASK;
541                         val.disk  = D_UP_TO_DATE;
542                         forced = 1;
543                         continue;
544                 }
545
546                 if (rv == SS_NO_UP_TO_DATE_DISK &&
547                     mdev->state.disk == D_CONSISTENT && mask.pdsk == 0) {
548                         D_ASSERT(mdev->state.pdsk == D_UNKNOWN);
549
550                         if (conn_try_outdate_peer(mdev->tconn)) {
551                                 val.disk = D_UP_TO_DATE;
552                                 mask.disk = D_MASK;
553                         }
554                         continue;
555                 }
556
557                 if (rv == SS_NOTHING_TO_DO)
558                         goto out;
559                 if (rv == SS_PRIMARY_NOP && mask.pdsk == 0) {
560                         if (!conn_try_outdate_peer(mdev->tconn) && force) {
561                                 dev_warn(DEV, "Forced into split brain situation!\n");
562                                 mask.pdsk = D_MASK;
563                                 val.pdsk  = D_OUTDATED;
564
565                         }
566                         continue;
567                 }
568                 if (rv == SS_TWO_PRIMARIES) {
569                         /* Maybe the peer is detected as dead very soon...
570                            retry at most once more in this case. */
571                         int timeo;
572                         rcu_read_lock();
573                         nc = rcu_dereference(mdev->tconn->net_conf);
574                         timeo = nc ? (nc->ping_timeo + 1) * HZ / 10 : 1;
575                         rcu_read_unlock();
576                         schedule_timeout_interruptible(timeo);
577                         if (try < max_tries)
578                                 try = max_tries - 1;
579                         continue;
580                 }
581                 if (rv < SS_SUCCESS) {
582                         rv = _drbd_request_state(mdev, mask, val,
583                                                 CS_VERBOSE + CS_WAIT_COMPLETE);
584                         if (rv < SS_SUCCESS)
585                                 goto out;
586                 }
587                 break;
588         }
589
590         if (rv < SS_SUCCESS)
591                 goto out;
592
593         if (forced)
594                 dev_warn(DEV, "Forced to consider local data as UpToDate!\n");
595
596         /* Wait until nothing is on the fly :) */
597         wait_event(mdev->misc_wait, atomic_read(&mdev->ap_pending_cnt) == 0);
598
599         if (new_role == R_SECONDARY) {
600                 set_disk_ro(mdev->vdisk, true);
601                 if (get_ldev(mdev)) {
602                         mdev->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
603                         put_ldev(mdev);
604                 }
605         } else {
606                 mutex_lock(&mdev->tconn->conf_update);
607                 nc = mdev->tconn->net_conf;
608                 if (nc)
609                         nc->discard_my_data = 0; /* without copy; single bit op is atomic */
610                 mutex_unlock(&mdev->tconn->conf_update);
611
612                 set_disk_ro(mdev->vdisk, false);
613                 if (get_ldev(mdev)) {
614                         if (((mdev->state.conn < C_CONNECTED ||
615                                mdev->state.pdsk <= D_FAILED)
616                               && mdev->ldev->md.uuid[UI_BITMAP] == 0) || forced)
617                                 drbd_uuid_new_current(mdev);
618
619                         mdev->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
620                         put_ldev(mdev);
621                 }
622         }
623
624         /* writeout of activity log covered areas of the bitmap
625          * to stable storage done in after state change already */
626
627         if (mdev->state.conn >= C_WF_REPORT_PARAMS) {
628                 /* if this was forced, we should consider sync */
629                 if (forced)
630                         drbd_send_uuids(mdev);
631                 drbd_send_state(mdev);
632         }
633
634         drbd_md_sync(mdev);
635
636         kobject_uevent(&disk_to_dev(mdev->vdisk)->kobj, KOBJ_CHANGE);
637 out:
638         mutex_unlock(mdev->state_mutex);
639         return rv;
640 }
641
642 static const char *from_attrs_err_to_txt(int err)
643 {
644         return  err == -ENOMSG ? "required attribute missing" :
645                 err == -EOPNOTSUPP ? "unknown mandatory attribute" :
646                 err == -EEXIST ? "can not change invariant setting" :
647                 "invalid attribute value";
648 }
649
650 int drbd_adm_set_role(struct sk_buff *skb, struct genl_info *info)
651 {
652         struct set_role_parms parms;
653         int err;
654         enum drbd_ret_code retcode;
655
656         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
657         if (!adm_ctx.reply_skb)
658                 return retcode;
659         if (retcode != NO_ERROR)
660                 goto out;
661
662         memset(&parms, 0, sizeof(parms));
663         if (info->attrs[DRBD_NLA_SET_ROLE_PARMS]) {
664                 err = set_role_parms_from_attrs(&parms, info);
665                 if (err) {
666                         retcode = ERR_MANDATORY_TAG;
667                         drbd_msg_put_info(from_attrs_err_to_txt(err));
668                         goto out;
669                 }
670         }
671
672         if (info->genlhdr->cmd == DRBD_ADM_PRIMARY)
673                 retcode = drbd_set_role(adm_ctx.mdev, R_PRIMARY, parms.assume_uptodate);
674         else
675                 retcode = drbd_set_role(adm_ctx.mdev, R_SECONDARY, 0);
676 out:
677         drbd_adm_finish(info, retcode);
678         return 0;
679 }
680
681 /* initializes the md.*_offset members, so we are able to find
682  * the on disk meta data */
683 static void drbd_md_set_sector_offsets(struct drbd_conf *mdev,
684                                        struct drbd_backing_dev *bdev)
685 {
686         sector_t md_size_sect = 0;
687         int meta_dev_idx;
688
689         rcu_read_lock();
690         meta_dev_idx = rcu_dereference(bdev->disk_conf)->meta_dev_idx;
691
692         switch (meta_dev_idx) {
693         default:
694                 /* v07 style fixed size indexed meta data */
695                 bdev->md.md_size_sect = MD_RESERVED_SECT;
696                 bdev->md.md_offset = drbd_md_ss__(mdev, bdev);
697                 bdev->md.al_offset = MD_AL_OFFSET;
698                 bdev->md.bm_offset = MD_BM_OFFSET;
699                 break;
700         case DRBD_MD_INDEX_FLEX_EXT:
701                 /* just occupy the full device; unit: sectors */
702                 bdev->md.md_size_sect = drbd_get_capacity(bdev->md_bdev);
703                 bdev->md.md_offset = 0;
704                 bdev->md.al_offset = MD_AL_OFFSET;
705                 bdev->md.bm_offset = MD_BM_OFFSET;
706                 break;
707         case DRBD_MD_INDEX_INTERNAL:
708         case DRBD_MD_INDEX_FLEX_INT:
709                 bdev->md.md_offset = drbd_md_ss__(mdev, bdev);
710                 /* al size is still fixed */
711                 bdev->md.al_offset = -MD_AL_SECTORS;
712                 /* we need (slightly less than) ~ this much bitmap sectors: */
713                 md_size_sect = drbd_get_capacity(bdev->backing_bdev);
714                 md_size_sect = ALIGN(md_size_sect, BM_SECT_PER_EXT);
715                 md_size_sect = BM_SECT_TO_EXT(md_size_sect);
716                 md_size_sect = ALIGN(md_size_sect, 8);
717
718                 /* plus the "drbd meta data super block",
719                  * and the activity log; */
720                 md_size_sect += MD_BM_OFFSET;
721
722                 bdev->md.md_size_sect = md_size_sect;
723                 /* bitmap offset is adjusted by 'super' block size */
724                 bdev->md.bm_offset   = -md_size_sect + MD_AL_OFFSET;
725                 break;
726         }
727         rcu_read_unlock();
728 }
729
730 /* input size is expected to be in KB */
731 char *ppsize(char *buf, unsigned long long size)
732 {
733         /* Needs 9 bytes at max including trailing NUL:
734          * -1ULL ==> "16384 EB" */
735         static char units[] = { 'K', 'M', 'G', 'T', 'P', 'E' };
736         int base = 0;
737         while (size >= 10000 && base < sizeof(units)-1) {
738                 /* shift + round */
739                 size = (size >> 10) + !!(size & (1<<9));
740                 base++;
741         }
742         sprintf(buf, "%u %cB", (unsigned)size, units[base]);
743
744         return buf;
745 }
746
747 /* there is still a theoretical deadlock when called from receiver
748  * on an D_INCONSISTENT R_PRIMARY:
749  *  remote READ does inc_ap_bio, receiver would need to receive answer
750  *  packet from remote to dec_ap_bio again.
751  *  receiver receive_sizes(), comes here,
752  *  waits for ap_bio_cnt == 0. -> deadlock.
753  * but this cannot happen, actually, because:
754  *  R_PRIMARY D_INCONSISTENT, and peer's disk is unreachable
755  *  (not connected, or bad/no disk on peer):
756  *  see drbd_fail_request_early, ap_bio_cnt is zero.
757  *  R_PRIMARY D_INCONSISTENT, and C_SYNC_TARGET:
758  *  peer may not initiate a resize.
759  */
760 /* Note these are not to be confused with
761  * drbd_adm_suspend_io/drbd_adm_resume_io,
762  * which are (sub) state changes triggered by admin (drbdsetup),
763  * and can be long lived.
764  * This changes an mdev->flag, is triggered by drbd internals,
765  * and should be short-lived. */
766 void drbd_suspend_io(struct drbd_conf *mdev)
767 {
768         set_bit(SUSPEND_IO, &mdev->flags);
769         if (drbd_suspended(mdev))
770                 return;
771         wait_event(mdev->misc_wait, !atomic_read(&mdev->ap_bio_cnt));
772 }
773
774 void drbd_resume_io(struct drbd_conf *mdev)
775 {
776         clear_bit(SUSPEND_IO, &mdev->flags);
777         wake_up(&mdev->misc_wait);
778 }
779
780 /**
781  * drbd_determine_dev_size() -  Sets the right device size obeying all constraints
782  * @mdev:       DRBD device.
783  *
784  * Returns 0 on success, negative return values indicate errors.
785  * You should call drbd_md_sync() after calling this function.
786  */
787 enum determine_dev_size drbd_determine_dev_size(struct drbd_conf *mdev, enum dds_flags flags) __must_hold(local)
788 {
789         sector_t prev_first_sect, prev_size; /* previous meta location */
790         sector_t la_size, u_size;
791         sector_t size;
792         char ppb[10];
793
794         int md_moved, la_size_changed;
795         enum determine_dev_size rv = unchanged;
796
797         /* race:
798          * application request passes inc_ap_bio,
799          * but then cannot get an AL-reference.
800          * this function later may wait on ap_bio_cnt == 0. -> deadlock.
801          *
802          * to avoid that:
803          * Suspend IO right here.
804          * still lock the act_log to not trigger ASSERTs there.
805          */
806         drbd_suspend_io(mdev);
807
808         /* no wait necessary anymore, actually we could assert that */
809         wait_event(mdev->al_wait, lc_try_lock(mdev->act_log));
810
811         prev_first_sect = drbd_md_first_sector(mdev->ldev);
812         prev_size = mdev->ldev->md.md_size_sect;
813         la_size = mdev->ldev->md.la_size_sect;
814
815         /* TODO: should only be some assert here, not (re)init... */
816         drbd_md_set_sector_offsets(mdev, mdev->ldev);
817
818         rcu_read_lock();
819         u_size = rcu_dereference(mdev->ldev->disk_conf)->disk_size;
820         rcu_read_unlock();
821         size = drbd_new_dev_size(mdev, mdev->ldev, u_size, flags & DDSF_FORCED);
822
823         if (drbd_get_capacity(mdev->this_bdev) != size ||
824             drbd_bm_capacity(mdev) != size) {
825                 int err;
826                 err = drbd_bm_resize(mdev, size, !(flags & DDSF_NO_RESYNC));
827                 if (unlikely(err)) {
828                         /* currently there is only one error: ENOMEM! */
829                         size = drbd_bm_capacity(mdev)>>1;
830                         if (size == 0) {
831                                 dev_err(DEV, "OUT OF MEMORY! "
832                                     "Could not allocate bitmap!\n");
833                         } else {
834                                 dev_err(DEV, "BM resizing failed. "
835                                     "Leaving size unchanged at size = %lu KB\n",
836                                     (unsigned long)size);
837                         }
838                         rv = dev_size_error;
839                 }
840                 /* racy, see comments above. */
841                 drbd_set_my_capacity(mdev, size);
842                 mdev->ldev->md.la_size_sect = size;
843                 dev_info(DEV, "size = %s (%llu KB)\n", ppsize(ppb, size>>1),
844                      (unsigned long long)size>>1);
845         }
846         if (rv == dev_size_error)
847                 goto out;
848
849         la_size_changed = (la_size != mdev->ldev->md.la_size_sect);
850
851         md_moved = prev_first_sect != drbd_md_first_sector(mdev->ldev)
852                 || prev_size       != mdev->ldev->md.md_size_sect;
853
854         if (la_size_changed || md_moved) {
855                 int err;
856
857                 drbd_al_shrink(mdev); /* All extents inactive. */
858                 dev_info(DEV, "Writing the whole bitmap, %s\n",
859                          la_size_changed && md_moved ? "size changed and md moved" :
860                          la_size_changed ? "size changed" : "md moved");
861                 /* next line implicitly does drbd_suspend_io()+drbd_resume_io() */
862                 err = drbd_bitmap_io(mdev, &drbd_bm_write,
863                                 "size changed", BM_LOCKED_MASK);
864                 if (err) {
865                         rv = dev_size_error;
866                         goto out;
867                 }
868                 drbd_md_mark_dirty(mdev);
869         }
870
871         if (size > la_size)
872                 rv = grew;
873         if (size < la_size)
874                 rv = shrunk;
875 out:
876         lc_unlock(mdev->act_log);
877         wake_up(&mdev->al_wait);
878         drbd_resume_io(mdev);
879
880         return rv;
881 }
882
883 sector_t
884 drbd_new_dev_size(struct drbd_conf *mdev, struct drbd_backing_dev *bdev,
885                   sector_t u_size, int assume_peer_has_space)
886 {
887         sector_t p_size = mdev->p_size;   /* partner's disk size. */
888         sector_t la_size = bdev->md.la_size_sect; /* last agreed size. */
889         sector_t m_size; /* my size */
890         sector_t size = 0;
891
892         m_size = drbd_get_max_capacity(bdev);
893
894         if (mdev->state.conn < C_CONNECTED && assume_peer_has_space) {
895                 dev_warn(DEV, "Resize while not connected was forced by the user!\n");
896                 p_size = m_size;
897         }
898
899         if (p_size && m_size) {
900                 size = min_t(sector_t, p_size, m_size);
901         } else {
902                 if (la_size) {
903                         size = la_size;
904                         if (m_size && m_size < size)
905                                 size = m_size;
906                         if (p_size && p_size < size)
907                                 size = p_size;
908                 } else {
909                         if (m_size)
910                                 size = m_size;
911                         if (p_size)
912                                 size = p_size;
913                 }
914         }
915
916         if (size == 0)
917                 dev_err(DEV, "Both nodes diskless!\n");
918
919         if (u_size) {
920                 if (u_size > size)
921                         dev_err(DEV, "Requested disk size is too big (%lu > %lu)\n",
922                             (unsigned long)u_size>>1, (unsigned long)size>>1);
923                 else
924                         size = u_size;
925         }
926
927         return size;
928 }
929
930 /**
931  * drbd_check_al_size() - Ensures that the AL is of the right size
932  * @mdev:       DRBD device.
933  *
934  * Returns -EBUSY if current al lru is still used, -ENOMEM when allocation
935  * failed, and 0 on success. You should call drbd_md_sync() after you called
936  * this function.
937  */
938 static int drbd_check_al_size(struct drbd_conf *mdev, struct disk_conf *dc)
939 {
940         struct lru_cache *n, *t;
941         struct lc_element *e;
942         unsigned int in_use;
943         int i;
944
945         if (mdev->act_log &&
946             mdev->act_log->nr_elements == dc->al_extents)
947                 return 0;
948
949         in_use = 0;
950         t = mdev->act_log;
951         n = lc_create("act_log", drbd_al_ext_cache, AL_UPDATES_PER_TRANSACTION,
952                 dc->al_extents, sizeof(struct lc_element), 0);
953
954         if (n == NULL) {
955                 dev_err(DEV, "Cannot allocate act_log lru!\n");
956                 return -ENOMEM;
957         }
958         spin_lock_irq(&mdev->al_lock);
959         if (t) {
960                 for (i = 0; i < t->nr_elements; i++) {
961                         e = lc_element_by_index(t, i);
962                         if (e->refcnt)
963                                 dev_err(DEV, "refcnt(%d)==%d\n",
964                                     e->lc_number, e->refcnt);
965                         in_use += e->refcnt;
966                 }
967         }
968         if (!in_use)
969                 mdev->act_log = n;
970         spin_unlock_irq(&mdev->al_lock);
971         if (in_use) {
972                 dev_err(DEV, "Activity log still in use!\n");
973                 lc_destroy(n);
974                 return -EBUSY;
975         } else {
976                 if (t)
977                         lc_destroy(t);
978         }
979         drbd_md_mark_dirty(mdev); /* we changed mdev->act_log->nr_elemens */
980         return 0;
981 }
982
983 static void drbd_setup_queue_param(struct drbd_conf *mdev, unsigned int max_bio_size)
984 {
985         struct request_queue * const q = mdev->rq_queue;
986         int max_hw_sectors = max_bio_size >> 9;
987         int max_segments = 0;
988
989         if (get_ldev_if_state(mdev, D_ATTACHING)) {
990                 struct request_queue * const b = mdev->ldev->backing_bdev->bd_disk->queue;
991
992                 max_hw_sectors = min(queue_max_hw_sectors(b), max_bio_size >> 9);
993                 rcu_read_lock();
994                 max_segments = rcu_dereference(mdev->ldev->disk_conf)->max_bio_bvecs;
995                 rcu_read_unlock();
996                 put_ldev(mdev);
997         }
998
999         blk_queue_logical_block_size(q, 512);
1000         blk_queue_max_hw_sectors(q, max_hw_sectors);
1001         /* This is the workaround for "bio would need to, but cannot, be split" */
1002         blk_queue_max_segments(q, max_segments ? max_segments : BLK_MAX_SEGMENTS);
1003         blk_queue_segment_boundary(q, PAGE_CACHE_SIZE-1);
1004
1005         if (get_ldev_if_state(mdev, D_ATTACHING)) {
1006                 struct request_queue * const b = mdev->ldev->backing_bdev->bd_disk->queue;
1007
1008                 blk_queue_stack_limits(q, b);
1009
1010                 if (q->backing_dev_info.ra_pages != b->backing_dev_info.ra_pages) {
1011                         dev_info(DEV, "Adjusting my ra_pages to backing device's (%lu -> %lu)\n",
1012                                  q->backing_dev_info.ra_pages,
1013                                  b->backing_dev_info.ra_pages);
1014                         q->backing_dev_info.ra_pages = b->backing_dev_info.ra_pages;
1015                 }
1016                 put_ldev(mdev);
1017         }
1018 }
1019
1020 void drbd_reconsider_max_bio_size(struct drbd_conf *mdev)
1021 {
1022         int now, new, local, peer;
1023
1024         now = queue_max_hw_sectors(mdev->rq_queue) << 9;
1025         local = mdev->local_max_bio_size; /* Eventually last known value, from volatile memory */
1026         peer = mdev->peer_max_bio_size; /* Eventually last known value, from meta data */
1027
1028         if (get_ldev_if_state(mdev, D_ATTACHING)) {
1029                 local = queue_max_hw_sectors(mdev->ldev->backing_bdev->bd_disk->queue) << 9;
1030                 mdev->local_max_bio_size = local;
1031                 put_ldev(mdev);
1032         }
1033
1034         /* We may ignore peer limits if the peer is modern enough.
1035            Because new from 8.3.8 onwards the peer can use multiple
1036            BIOs for a single peer_request */
1037         if (mdev->state.conn >= C_CONNECTED) {
1038                 if (mdev->tconn->agreed_pro_version < 94)
1039                         peer = mdev->peer_max_bio_size;
1040                 else if (mdev->tconn->agreed_pro_version == 94)
1041                         peer = DRBD_MAX_SIZE_H80_PACKET;
1042                 else /* drbd 8.3.8 onwards */
1043                         peer = DRBD_MAX_BIO_SIZE;
1044         }
1045
1046         new = min_t(int, local, peer);
1047
1048         if (mdev->state.role == R_PRIMARY && new < now)
1049                 dev_err(DEV, "ASSERT FAILED new < now; (%d < %d)\n", new, now);
1050
1051         if (new != now)
1052                 dev_info(DEV, "max BIO size = %u\n", new);
1053
1054         drbd_setup_queue_param(mdev, new);
1055 }
1056
1057 /* Starts the worker thread */
1058 static void conn_reconfig_start(struct drbd_tconn *tconn)
1059 {
1060         drbd_thread_start(&tconn->worker);
1061         conn_flush_workqueue(tconn);
1062 }
1063
1064 /* if still unconfigured, stops worker again. */
1065 static void conn_reconfig_done(struct drbd_tconn *tconn)
1066 {
1067         bool stop_threads;
1068         spin_lock_irq(&tconn->req_lock);
1069         stop_threads = conn_all_vols_unconf(tconn);
1070         spin_unlock_irq(&tconn->req_lock);
1071         if (stop_threads) {
1072                 /* asender is implicitly stopped by receiver
1073                  * in conn_disconnect() */
1074                 drbd_thread_stop(&tconn->receiver);
1075                 drbd_thread_stop(&tconn->worker);
1076         }
1077 }
1078
1079 /* Make sure IO is suspended before calling this function(). */
1080 static void drbd_suspend_al(struct drbd_conf *mdev)
1081 {
1082         int s = 0;
1083
1084         if (!lc_try_lock(mdev->act_log)) {
1085                 dev_warn(DEV, "Failed to lock al in drbd_suspend_al()\n");
1086                 return;
1087         }
1088
1089         drbd_al_shrink(mdev);
1090         spin_lock_irq(&mdev->tconn->req_lock);
1091         if (mdev->state.conn < C_CONNECTED)
1092                 s = !test_and_set_bit(AL_SUSPENDED, &mdev->flags);
1093         spin_unlock_irq(&mdev->tconn->req_lock);
1094         lc_unlock(mdev->act_log);
1095
1096         if (s)
1097                 dev_info(DEV, "Suspended AL updates\n");
1098 }
1099
1100
1101 static bool should_set_defaults(struct genl_info *info)
1102 {
1103         unsigned flags = ((struct drbd_genlmsghdr*)info->userhdr)->flags;
1104         return 0 != (flags & DRBD_GENL_F_SET_DEFAULTS);
1105 }
1106
1107 static void enforce_disk_conf_limits(struct disk_conf *dc)
1108 {
1109         if (dc->al_extents < DRBD_AL_EXTENTS_MIN)
1110                 dc->al_extents = DRBD_AL_EXTENTS_MIN;
1111         if (dc->al_extents > DRBD_AL_EXTENTS_MAX)
1112                 dc->al_extents = DRBD_AL_EXTENTS_MAX;
1113
1114         if (dc->c_plan_ahead > DRBD_C_PLAN_AHEAD_MAX)
1115                 dc->c_plan_ahead = DRBD_C_PLAN_AHEAD_MAX;
1116 }
1117
1118 int drbd_adm_disk_opts(struct sk_buff *skb, struct genl_info *info)
1119 {
1120         enum drbd_ret_code retcode;
1121         struct drbd_conf *mdev;
1122         struct disk_conf *new_disk_conf, *old_disk_conf;
1123         struct fifo_buffer *old_plan = NULL, *new_plan = NULL;
1124         int err, fifo_size;
1125
1126         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1127         if (!adm_ctx.reply_skb)
1128                 return retcode;
1129         if (retcode != NO_ERROR)
1130                 goto out;
1131
1132         mdev = adm_ctx.mdev;
1133
1134         /* we also need a disk
1135          * to change the options on */
1136         if (!get_ldev(mdev)) {
1137                 retcode = ERR_NO_DISK;
1138                 goto out;
1139         }
1140
1141         new_disk_conf = kmalloc(sizeof(struct disk_conf), GFP_KERNEL);
1142         if (!new_disk_conf) {
1143                 retcode = ERR_NOMEM;
1144                 goto fail;
1145         }
1146
1147         mutex_lock(&mdev->tconn->conf_update);
1148         old_disk_conf = mdev->ldev->disk_conf;
1149         *new_disk_conf = *old_disk_conf;
1150         if (should_set_defaults(info))
1151                 set_disk_conf_defaults(new_disk_conf);
1152
1153         err = disk_conf_from_attrs_for_change(new_disk_conf, info);
1154         if (err) {
1155                 retcode = ERR_MANDATORY_TAG;
1156                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1157         }
1158
1159         if (!expect(new_disk_conf->resync_rate >= 1))
1160                 new_disk_conf->resync_rate = 1;
1161
1162         enforce_disk_conf_limits(new_disk_conf);
1163
1164         fifo_size = (new_disk_conf->c_plan_ahead * 10 * SLEEP_TIME) / HZ;
1165         if (fifo_size != mdev->rs_plan_s->size) {
1166                 new_plan = fifo_alloc(fifo_size);
1167                 if (!new_plan) {
1168                         dev_err(DEV, "kmalloc of fifo_buffer failed");
1169                         retcode = ERR_NOMEM;
1170                         goto fail_unlock;
1171                 }
1172         }
1173
1174         wait_event(mdev->al_wait, lc_try_lock(mdev->act_log));
1175         drbd_al_shrink(mdev);
1176         err = drbd_check_al_size(mdev, new_disk_conf);
1177         lc_unlock(mdev->act_log);
1178         wake_up(&mdev->al_wait);
1179
1180         if (err) {
1181                 retcode = ERR_NOMEM;
1182                 goto fail_unlock;
1183         }
1184
1185         write_lock_irq(&global_state_lock);
1186         retcode = drbd_resync_after_valid(mdev, new_disk_conf->resync_after);
1187         if (retcode == NO_ERROR) {
1188                 rcu_assign_pointer(mdev->ldev->disk_conf, new_disk_conf);
1189                 drbd_resync_after_changed(mdev);
1190         }
1191         write_unlock_irq(&global_state_lock);
1192
1193         if (retcode != NO_ERROR)
1194                 goto fail_unlock;
1195
1196         if (new_plan) {
1197                 old_plan = mdev->rs_plan_s;
1198                 rcu_assign_pointer(mdev->rs_plan_s, new_plan);
1199         }
1200
1201         mutex_unlock(&mdev->tconn->conf_update);
1202         drbd_md_sync(mdev);
1203
1204         if (mdev->state.conn >= C_CONNECTED)
1205                 drbd_send_sync_param(mdev);
1206
1207         synchronize_rcu();
1208         kfree(old_disk_conf);
1209         kfree(old_plan);
1210         goto success;
1211
1212 fail_unlock:
1213         mutex_unlock(&mdev->tconn->conf_update);
1214  fail:
1215         kfree(new_disk_conf);
1216         kfree(new_plan);
1217 success:
1218         put_ldev(mdev);
1219  out:
1220         drbd_adm_finish(info, retcode);
1221         return 0;
1222 }
1223
1224 int drbd_adm_attach(struct sk_buff *skb, struct genl_info *info)
1225 {
1226         struct drbd_conf *mdev;
1227         int err;
1228         enum drbd_ret_code retcode;
1229         enum determine_dev_size dd;
1230         sector_t max_possible_sectors;
1231         sector_t min_md_device_sectors;
1232         struct drbd_backing_dev *nbc = NULL; /* new_backing_conf */
1233         struct disk_conf *new_disk_conf = NULL;
1234         struct block_device *bdev;
1235         struct lru_cache *resync_lru = NULL;
1236         struct fifo_buffer *new_plan = NULL;
1237         union drbd_state ns, os;
1238         enum drbd_state_rv rv;
1239         struct net_conf *nc;
1240         int cp_discovered = 0;
1241
1242         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1243         if (!adm_ctx.reply_skb)
1244                 return retcode;
1245         if (retcode != NO_ERROR)
1246                 goto finish;
1247
1248         mdev = adm_ctx.mdev;
1249         conn_reconfig_start(mdev->tconn);
1250
1251         /* if you want to reconfigure, please tear down first */
1252         if (mdev->state.disk > D_DISKLESS) {
1253                 retcode = ERR_DISK_CONFIGURED;
1254                 goto fail;
1255         }
1256         /* It may just now have detached because of IO error.  Make sure
1257          * drbd_ldev_destroy is done already, we may end up here very fast,
1258          * e.g. if someone calls attach from the on-io-error handler,
1259          * to realize a "hot spare" feature (not that I'd recommend that) */
1260         wait_event(mdev->misc_wait, !atomic_read(&mdev->local_cnt));
1261
1262         /* allocation not in the IO path, drbdsetup context */
1263         nbc = kzalloc(sizeof(struct drbd_backing_dev), GFP_KERNEL);
1264         if (!nbc) {
1265                 retcode = ERR_NOMEM;
1266                 goto fail;
1267         }
1268         new_disk_conf = kzalloc(sizeof(struct disk_conf), GFP_KERNEL);
1269         if (!new_disk_conf) {
1270                 retcode = ERR_NOMEM;
1271                 goto fail;
1272         }
1273         nbc->disk_conf = new_disk_conf;
1274
1275         set_disk_conf_defaults(new_disk_conf);
1276         err = disk_conf_from_attrs(new_disk_conf, info);
1277         if (err) {
1278                 retcode = ERR_MANDATORY_TAG;
1279                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1280                 goto fail;
1281         }
1282
1283         enforce_disk_conf_limits(new_disk_conf);
1284
1285         new_plan = fifo_alloc((new_disk_conf->c_plan_ahead * 10 * SLEEP_TIME) / HZ);
1286         if (!new_plan) {
1287                 retcode = ERR_NOMEM;
1288                 goto fail;
1289         }
1290
1291         if (new_disk_conf->meta_dev_idx < DRBD_MD_INDEX_FLEX_INT) {
1292                 retcode = ERR_MD_IDX_INVALID;
1293                 goto fail;
1294         }
1295
1296         rcu_read_lock();
1297         nc = rcu_dereference(mdev->tconn->net_conf);
1298         if (nc) {
1299                 if (new_disk_conf->fencing == FP_STONITH && nc->wire_protocol == DRBD_PROT_A) {
1300                         rcu_read_unlock();
1301                         retcode = ERR_STONITH_AND_PROT_A;
1302                         goto fail;
1303                 }
1304         }
1305         rcu_read_unlock();
1306
1307         bdev = blkdev_get_by_path(new_disk_conf->backing_dev,
1308                                   FMODE_READ | FMODE_WRITE | FMODE_EXCL, mdev);
1309         if (IS_ERR(bdev)) {
1310                 dev_err(DEV, "open(\"%s\") failed with %ld\n", new_disk_conf->backing_dev,
1311                         PTR_ERR(bdev));
1312                 retcode = ERR_OPEN_DISK;
1313                 goto fail;
1314         }
1315         nbc->backing_bdev = bdev;
1316
1317         /*
1318          * meta_dev_idx >= 0: external fixed size, possibly multiple
1319          * drbd sharing one meta device.  TODO in that case, paranoia
1320          * check that [md_bdev, meta_dev_idx] is not yet used by some
1321          * other drbd minor!  (if you use drbd.conf + drbdadm, that
1322          * should check it for you already; but if you don't, or
1323          * someone fooled it, we need to double check here)
1324          */
1325         bdev = blkdev_get_by_path(new_disk_conf->meta_dev,
1326                                   FMODE_READ | FMODE_WRITE | FMODE_EXCL,
1327                                   (new_disk_conf->meta_dev_idx < 0) ?
1328                                   (void *)mdev : (void *)drbd_m_holder);
1329         if (IS_ERR(bdev)) {
1330                 dev_err(DEV, "open(\"%s\") failed with %ld\n", new_disk_conf->meta_dev,
1331                         PTR_ERR(bdev));
1332                 retcode = ERR_OPEN_MD_DISK;
1333                 goto fail;
1334         }
1335         nbc->md_bdev = bdev;
1336
1337         if ((nbc->backing_bdev == nbc->md_bdev) !=
1338             (new_disk_conf->meta_dev_idx == DRBD_MD_INDEX_INTERNAL ||
1339              new_disk_conf->meta_dev_idx == DRBD_MD_INDEX_FLEX_INT)) {
1340                 retcode = ERR_MD_IDX_INVALID;
1341                 goto fail;
1342         }
1343
1344         resync_lru = lc_create("resync", drbd_bm_ext_cache,
1345                         1, 61, sizeof(struct bm_extent),
1346                         offsetof(struct bm_extent, lce));
1347         if (!resync_lru) {
1348                 retcode = ERR_NOMEM;
1349                 goto fail;
1350         }
1351
1352         /* RT - for drbd_get_max_capacity() DRBD_MD_INDEX_FLEX_INT */
1353         drbd_md_set_sector_offsets(mdev, nbc);
1354
1355         if (drbd_get_max_capacity(nbc) < new_disk_conf->disk_size) {
1356                 dev_err(DEV, "max capacity %llu smaller than disk size %llu\n",
1357                         (unsigned long long) drbd_get_max_capacity(nbc),
1358                         (unsigned long long) new_disk_conf->disk_size);
1359                 retcode = ERR_DISK_TO_SMALL;
1360                 goto fail;
1361         }
1362
1363         if (new_disk_conf->meta_dev_idx < 0) {
1364                 max_possible_sectors = DRBD_MAX_SECTORS_FLEX;
1365                 /* at least one MB, otherwise it does not make sense */
1366                 min_md_device_sectors = (2<<10);
1367         } else {
1368                 max_possible_sectors = DRBD_MAX_SECTORS;
1369                 min_md_device_sectors = MD_RESERVED_SECT * (new_disk_conf->meta_dev_idx + 1);
1370         }
1371
1372         if (drbd_get_capacity(nbc->md_bdev) < min_md_device_sectors) {
1373                 retcode = ERR_MD_DISK_TO_SMALL;
1374                 dev_warn(DEV, "refusing attach: md-device too small, "
1375                      "at least %llu sectors needed for this meta-disk type\n",
1376                      (unsigned long long) min_md_device_sectors);
1377                 goto fail;
1378         }
1379
1380         /* Make sure the new disk is big enough
1381          * (we may currently be R_PRIMARY with no local disk...) */
1382         if (drbd_get_max_capacity(nbc) <
1383             drbd_get_capacity(mdev->this_bdev)) {
1384                 retcode = ERR_DISK_TO_SMALL;
1385                 goto fail;
1386         }
1387
1388         nbc->known_size = drbd_get_capacity(nbc->backing_bdev);
1389
1390         if (nbc->known_size > max_possible_sectors) {
1391                 dev_warn(DEV, "==> truncating very big lower level device "
1392                         "to currently maximum possible %llu sectors <==\n",
1393                         (unsigned long long) max_possible_sectors);
1394                 if (new_disk_conf->meta_dev_idx >= 0)
1395                         dev_warn(DEV, "==>> using internal or flexible "
1396                                       "meta data may help <<==\n");
1397         }
1398
1399         drbd_suspend_io(mdev);
1400         /* also wait for the last barrier ack. */
1401         wait_event(mdev->misc_wait, !atomic_read(&mdev->ap_pending_cnt) || drbd_suspended(mdev));
1402         /* and for any other previously queued work */
1403         drbd_flush_workqueue(mdev);
1404
1405         rv = _drbd_request_state(mdev, NS(disk, D_ATTACHING), CS_VERBOSE);
1406         retcode = rv;  /* FIXME: Type mismatch. */
1407         drbd_resume_io(mdev);
1408         if (rv < SS_SUCCESS)
1409                 goto fail;
1410
1411         if (!get_ldev_if_state(mdev, D_ATTACHING))
1412                 goto force_diskless;
1413
1414         drbd_md_set_sector_offsets(mdev, nbc);
1415
1416         if (!mdev->bitmap) {
1417                 if (drbd_bm_init(mdev)) {
1418                         retcode = ERR_NOMEM;
1419                         goto force_diskless_dec;
1420                 }
1421         }
1422
1423         retcode = drbd_md_read(mdev, nbc);
1424         if (retcode != NO_ERROR)
1425                 goto force_diskless_dec;
1426
1427         if (mdev->state.conn < C_CONNECTED &&
1428             mdev->state.role == R_PRIMARY &&
1429             (mdev->ed_uuid & ~((u64)1)) != (nbc->md.uuid[UI_CURRENT] & ~((u64)1))) {
1430                 dev_err(DEV, "Can only attach to data with current UUID=%016llX\n",
1431                     (unsigned long long)mdev->ed_uuid);
1432                 retcode = ERR_DATA_NOT_CURRENT;
1433                 goto force_diskless_dec;
1434         }
1435
1436         /* Since we are diskless, fix the activity log first... */
1437         if (drbd_check_al_size(mdev, new_disk_conf)) {
1438                 retcode = ERR_NOMEM;
1439                 goto force_diskless_dec;
1440         }
1441
1442         /* Prevent shrinking of consistent devices ! */
1443         if (drbd_md_test_flag(nbc, MDF_CONSISTENT) &&
1444             drbd_new_dev_size(mdev, nbc, nbc->disk_conf->disk_size, 0) < nbc->md.la_size_sect) {
1445                 dev_warn(DEV, "refusing to truncate a consistent device\n");
1446                 retcode = ERR_DISK_TO_SMALL;
1447                 goto force_diskless_dec;
1448         }
1449
1450         if (!drbd_al_read_log(mdev, nbc)) {
1451                 retcode = ERR_IO_MD_DISK;
1452                 goto force_diskless_dec;
1453         }
1454
1455         /* Reset the "barriers don't work" bits here, then force meta data to
1456          * be written, to ensure we determine if barriers are supported. */
1457         if (new_disk_conf->md_flushes)
1458                 clear_bit(MD_NO_FUA, &mdev->flags);
1459         else
1460                 set_bit(MD_NO_FUA, &mdev->flags);
1461
1462         /* Point of no return reached.
1463          * Devices and memory are no longer released by error cleanup below.
1464          * now mdev takes over responsibility, and the state engine should
1465          * clean it up somewhere.  */
1466         D_ASSERT(mdev->ldev == NULL);
1467         mdev->ldev = nbc;
1468         mdev->resync = resync_lru;
1469         mdev->rs_plan_s = new_plan;
1470         nbc = NULL;
1471         resync_lru = NULL;
1472         new_disk_conf = NULL;
1473         new_plan = NULL;
1474
1475         mdev->write_ordering = WO_bdev_flush;
1476         drbd_bump_write_ordering(mdev, WO_bdev_flush);
1477
1478         if (drbd_md_test_flag(mdev->ldev, MDF_CRASHED_PRIMARY))
1479                 set_bit(CRASHED_PRIMARY, &mdev->flags);
1480         else
1481                 clear_bit(CRASHED_PRIMARY, &mdev->flags);
1482
1483         if (drbd_md_test_flag(mdev->ldev, MDF_PRIMARY_IND) &&
1484             !(mdev->state.role == R_PRIMARY && mdev->tconn->susp_nod)) {
1485                 set_bit(CRASHED_PRIMARY, &mdev->flags);
1486                 cp_discovered = 1;
1487         }
1488
1489         mdev->send_cnt = 0;
1490         mdev->recv_cnt = 0;
1491         mdev->read_cnt = 0;
1492         mdev->writ_cnt = 0;
1493
1494         drbd_reconsider_max_bio_size(mdev);
1495
1496         /* If I am currently not R_PRIMARY,
1497          * but meta data primary indicator is set,
1498          * I just now recover from a hard crash,
1499          * and have been R_PRIMARY before that crash.
1500          *
1501          * Now, if I had no connection before that crash
1502          * (have been degraded R_PRIMARY), chances are that
1503          * I won't find my peer now either.
1504          *
1505          * In that case, and _only_ in that case,
1506          * we use the degr-wfc-timeout instead of the default,
1507          * so we can automatically recover from a crash of a
1508          * degraded but active "cluster" after a certain timeout.
1509          */
1510         clear_bit(USE_DEGR_WFC_T, &mdev->flags);
1511         if (mdev->state.role != R_PRIMARY &&
1512              drbd_md_test_flag(mdev->ldev, MDF_PRIMARY_IND) &&
1513             !drbd_md_test_flag(mdev->ldev, MDF_CONNECTED_IND))
1514                 set_bit(USE_DEGR_WFC_T, &mdev->flags);
1515
1516         dd = drbd_determine_dev_size(mdev, 0);
1517         if (dd == dev_size_error) {
1518                 retcode = ERR_NOMEM_BITMAP;
1519                 goto force_diskless_dec;
1520         } else if (dd == grew)
1521                 set_bit(RESYNC_AFTER_NEG, &mdev->flags);
1522
1523         if (drbd_md_test_flag(mdev->ldev, MDF_FULL_SYNC)) {
1524                 dev_info(DEV, "Assuming that all blocks are out of sync "
1525                      "(aka FullSync)\n");
1526                 if (drbd_bitmap_io(mdev, &drbd_bmio_set_n_write,
1527                         "set_n_write from attaching", BM_LOCKED_MASK)) {
1528                         retcode = ERR_IO_MD_DISK;
1529                         goto force_diskless_dec;
1530                 }
1531         } else {
1532                 if (drbd_bitmap_io(mdev, &drbd_bm_read,
1533                         "read from attaching", BM_LOCKED_MASK)) {
1534                         retcode = ERR_IO_MD_DISK;
1535                         goto force_diskless_dec;
1536                 }
1537         }
1538
1539         if (cp_discovered) {
1540                 drbd_al_apply_to_bm(mdev);
1541                 if (drbd_bitmap_io(mdev, &drbd_bm_write,
1542                         "crashed primary apply AL", BM_LOCKED_MASK)) {
1543                         retcode = ERR_IO_MD_DISK;
1544                         goto force_diskless_dec;
1545                 }
1546         }
1547
1548         if (_drbd_bm_total_weight(mdev) == drbd_bm_bits(mdev))
1549                 drbd_suspend_al(mdev); /* IO is still suspended here... */
1550
1551         spin_lock_irq(&mdev->tconn->req_lock);
1552         os = drbd_read_state(mdev);
1553         ns = os;
1554         /* If MDF_CONSISTENT is not set go into inconsistent state,
1555            otherwise investigate MDF_WasUpToDate...
1556            If MDF_WAS_UP_TO_DATE is not set go into D_OUTDATED disk state,
1557            otherwise into D_CONSISTENT state.
1558         */
1559         if (drbd_md_test_flag(mdev->ldev, MDF_CONSISTENT)) {
1560                 if (drbd_md_test_flag(mdev->ldev, MDF_WAS_UP_TO_DATE))
1561                         ns.disk = D_CONSISTENT;
1562                 else
1563                         ns.disk = D_OUTDATED;
1564         } else {
1565                 ns.disk = D_INCONSISTENT;
1566         }
1567
1568         if (drbd_md_test_flag(mdev->ldev, MDF_PEER_OUT_DATED))
1569                 ns.pdsk = D_OUTDATED;
1570
1571         rcu_read_lock();
1572         if (ns.disk == D_CONSISTENT &&
1573             (ns.pdsk == D_OUTDATED || rcu_dereference(mdev->ldev->disk_conf)->fencing == FP_DONT_CARE))
1574                 ns.disk = D_UP_TO_DATE;
1575         rcu_read_unlock();
1576
1577         /* All tests on MDF_PRIMARY_IND, MDF_CONNECTED_IND,
1578            MDF_CONSISTENT and MDF_WAS_UP_TO_DATE must happen before
1579            this point, because drbd_request_state() modifies these
1580            flags. */
1581
1582         /* In case we are C_CONNECTED postpone any decision on the new disk
1583            state after the negotiation phase. */
1584         if (mdev->state.conn == C_CONNECTED) {
1585                 mdev->new_state_tmp.i = ns.i;
1586                 ns.i = os.i;
1587                 ns.disk = D_NEGOTIATING;
1588
1589                 /* We expect to receive up-to-date UUIDs soon.
1590                    To avoid a race in receive_state, free p_uuid while
1591                    holding req_lock. I.e. atomic with the state change */
1592                 kfree(mdev->p_uuid);
1593                 mdev->p_uuid = NULL;
1594         }
1595
1596         rv = _drbd_set_state(mdev, ns, CS_VERBOSE, NULL);
1597         spin_unlock_irq(&mdev->tconn->req_lock);
1598
1599         if (rv < SS_SUCCESS)
1600                 goto force_diskless_dec;
1601
1602         if (mdev->state.role == R_PRIMARY)
1603                 mdev->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
1604         else
1605                 mdev->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
1606
1607         drbd_md_mark_dirty(mdev);
1608         drbd_md_sync(mdev);
1609
1610         kobject_uevent(&disk_to_dev(mdev->vdisk)->kobj, KOBJ_CHANGE);
1611         put_ldev(mdev);
1612         conn_reconfig_done(mdev->tconn);
1613         drbd_adm_finish(info, retcode);
1614         return 0;
1615
1616  force_diskless_dec:
1617         put_ldev(mdev);
1618  force_diskless:
1619         drbd_force_state(mdev, NS(disk, D_FAILED));
1620         drbd_md_sync(mdev);
1621  fail:
1622         conn_reconfig_done(mdev->tconn);
1623         if (nbc) {
1624                 if (nbc->backing_bdev)
1625                         blkdev_put(nbc->backing_bdev,
1626                                    FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1627                 if (nbc->md_bdev)
1628                         blkdev_put(nbc->md_bdev,
1629                                    FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1630                 kfree(nbc);
1631         }
1632         kfree(new_disk_conf);
1633         lc_destroy(resync_lru);
1634         kfree(new_plan);
1635
1636  finish:
1637         drbd_adm_finish(info, retcode);
1638         return 0;
1639 }
1640
1641 static int adm_detach(struct drbd_conf *mdev)
1642 {
1643         enum drbd_state_rv retcode;
1644         int ret;
1645         drbd_suspend_io(mdev); /* so no-one is stuck in drbd_al_begin_io */
1646         retcode = drbd_request_state(mdev, NS(disk, D_FAILED));
1647         /* D_FAILED will transition to DISKLESS. */
1648         ret = wait_event_interruptible(mdev->misc_wait,
1649                         mdev->state.disk != D_FAILED);
1650         drbd_resume_io(mdev);
1651         if ((int)retcode == (int)SS_IS_DISKLESS)
1652                 retcode = SS_NOTHING_TO_DO;
1653         if (ret)
1654                 retcode = ERR_INTR;
1655         return retcode;
1656 }
1657
1658 /* Detaching the disk is a process in multiple stages.  First we need to lock
1659  * out application IO, in-flight IO, IO stuck in drbd_al_begin_io.
1660  * Then we transition to D_DISKLESS, and wait for put_ldev() to return all
1661  * internal references as well.
1662  * Only then we have finally detached. */
1663 int drbd_adm_detach(struct sk_buff *skb, struct genl_info *info)
1664 {
1665         enum drbd_ret_code retcode;
1666
1667         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1668         if (!adm_ctx.reply_skb)
1669                 return retcode;
1670         if (retcode != NO_ERROR)
1671                 goto out;
1672
1673         retcode = adm_detach(adm_ctx.mdev);
1674 out:
1675         drbd_adm_finish(info, retcode);
1676         return 0;
1677 }
1678
1679 static bool conn_resync_running(struct drbd_tconn *tconn)
1680 {
1681         struct drbd_conf *mdev;
1682         bool rv = false;
1683         int vnr;
1684
1685         rcu_read_lock();
1686         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
1687                 if (mdev->state.conn == C_SYNC_SOURCE ||
1688                     mdev->state.conn == C_SYNC_TARGET ||
1689                     mdev->state.conn == C_PAUSED_SYNC_S ||
1690                     mdev->state.conn == C_PAUSED_SYNC_T) {
1691                         rv = true;
1692                         break;
1693                 }
1694         }
1695         rcu_read_unlock();
1696
1697         return rv;
1698 }
1699
1700 static bool conn_ov_running(struct drbd_tconn *tconn)
1701 {
1702         struct drbd_conf *mdev;
1703         bool rv = false;
1704         int vnr;
1705
1706         rcu_read_lock();
1707         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
1708                 if (mdev->state.conn == C_VERIFY_S ||
1709                     mdev->state.conn == C_VERIFY_T) {
1710                         rv = true;
1711                         break;
1712                 }
1713         }
1714         rcu_read_unlock();
1715
1716         return rv;
1717 }
1718
1719 static enum drbd_ret_code
1720 _check_net_options(struct drbd_tconn *tconn, struct net_conf *old_conf, struct net_conf *new_conf)
1721 {
1722         struct drbd_conf *mdev;
1723         int i;
1724
1725         if (old_conf && tconn->cstate == C_WF_REPORT_PARAMS && tconn->agreed_pro_version < 100) {
1726                 if (new_conf->wire_protocol != old_conf->wire_protocol)
1727                         return ERR_NEED_APV_100;
1728
1729                 if (new_conf->two_primaries != old_conf->two_primaries)
1730                         return ERR_NEED_APV_100;
1731
1732                 if (!new_conf->integrity_alg != !old_conf->integrity_alg)
1733                         return ERR_NEED_APV_100;
1734
1735                 if (strcmp(new_conf->integrity_alg, old_conf->integrity_alg))
1736                         return ERR_NEED_APV_100;
1737         }
1738
1739         if (!new_conf->two_primaries &&
1740             conn_highest_role(tconn) == R_PRIMARY &&
1741             conn_highest_peer(tconn) == R_PRIMARY)
1742                 return ERR_NEED_ALLOW_TWO_PRI;
1743
1744         if (new_conf->two_primaries &&
1745             (new_conf->wire_protocol != DRBD_PROT_C))
1746                 return ERR_NOT_PROTO_C;
1747
1748         idr_for_each_entry(&tconn->volumes, mdev, i) {
1749                 if (get_ldev(mdev)) {
1750                         enum drbd_fencing_p fp = rcu_dereference(mdev->ldev->disk_conf)->fencing;
1751                         put_ldev(mdev);
1752                         if (new_conf->wire_protocol == DRBD_PROT_A && fp == FP_STONITH)
1753                                 return ERR_STONITH_AND_PROT_A;
1754                 }
1755                 if (mdev->state.role == R_PRIMARY && new_conf->discard_my_data)
1756                         return ERR_DISCARD;
1757         }
1758
1759         if (new_conf->on_congestion != OC_BLOCK && new_conf->wire_protocol != DRBD_PROT_A)
1760                 return ERR_CONG_NOT_PROTO_A;
1761
1762         return NO_ERROR;
1763 }
1764
1765 static enum drbd_ret_code
1766 check_net_options(struct drbd_tconn *tconn, struct net_conf *new_conf)
1767 {
1768         static enum drbd_ret_code rv;
1769         struct drbd_conf *mdev;
1770         int i;
1771
1772         rcu_read_lock();
1773         rv = _check_net_options(tconn, rcu_dereference(tconn->net_conf), new_conf);
1774         rcu_read_unlock();
1775
1776         /* tconn->volumes protected by genl_lock() here */
1777         idr_for_each_entry(&tconn->volumes, mdev, i) {
1778                 if (!mdev->bitmap) {
1779                         if(drbd_bm_init(mdev))
1780                                 return ERR_NOMEM;
1781                 }
1782         }
1783
1784         return rv;
1785 }
1786
1787 struct crypto {
1788         struct crypto_hash *verify_tfm;
1789         struct crypto_hash *csums_tfm;
1790         struct crypto_hash *cram_hmac_tfm;
1791         struct crypto_hash *integrity_tfm;
1792         void *int_dig_in;
1793         void *int_dig_vv;
1794 };
1795
1796 static int
1797 alloc_hash(struct crypto_hash **tfm, char *tfm_name, int err_alg)
1798 {
1799         if (!tfm_name[0])
1800                 return NO_ERROR;
1801
1802         *tfm = crypto_alloc_hash(tfm_name, 0, CRYPTO_ALG_ASYNC);
1803         if (IS_ERR(*tfm)) {
1804                 *tfm = NULL;
1805                 return err_alg;
1806         }
1807
1808         return NO_ERROR;
1809 }
1810
1811 static enum drbd_ret_code
1812 alloc_crypto(struct crypto *crypto, struct net_conf *new_conf)
1813 {
1814         char hmac_name[CRYPTO_MAX_ALG_NAME];
1815         enum drbd_ret_code rv;
1816         int hash_size;
1817
1818         rv = alloc_hash(&crypto->csums_tfm, new_conf->csums_alg,
1819                        ERR_CSUMS_ALG);
1820         if (rv != NO_ERROR)
1821                 return rv;
1822         rv = alloc_hash(&crypto->verify_tfm, new_conf->verify_alg,
1823                        ERR_VERIFY_ALG);
1824         if (rv != NO_ERROR)
1825                 return rv;
1826         rv = alloc_hash(&crypto->integrity_tfm, new_conf->integrity_alg,
1827                        ERR_INTEGRITY_ALG);
1828         if (rv != NO_ERROR)
1829                 return rv;
1830         if (new_conf->cram_hmac_alg[0] != 0) {
1831                 snprintf(hmac_name, CRYPTO_MAX_ALG_NAME, "hmac(%s)",
1832                          new_conf->cram_hmac_alg);
1833
1834                 rv = alloc_hash(&crypto->cram_hmac_tfm, hmac_name,
1835                                ERR_AUTH_ALG);
1836         }
1837         if (crypto->integrity_tfm) {
1838                 hash_size = crypto_hash_digestsize(crypto->integrity_tfm);
1839                 crypto->int_dig_in = kmalloc(hash_size, GFP_KERNEL);
1840                 if (!crypto->int_dig_in)
1841                         return ERR_NOMEM;
1842                 crypto->int_dig_vv = kmalloc(hash_size, GFP_KERNEL);
1843                 if (!crypto->int_dig_vv)
1844                         return ERR_NOMEM;
1845         }
1846
1847         return rv;
1848 }
1849
1850 static void free_crypto(struct crypto *crypto)
1851 {
1852         kfree(crypto->int_dig_in);
1853         kfree(crypto->int_dig_vv);
1854         crypto_free_hash(crypto->cram_hmac_tfm);
1855         crypto_free_hash(crypto->integrity_tfm);
1856         crypto_free_hash(crypto->csums_tfm);
1857         crypto_free_hash(crypto->verify_tfm);
1858 }
1859
1860 int drbd_adm_net_opts(struct sk_buff *skb, struct genl_info *info)
1861 {
1862         enum drbd_ret_code retcode;
1863         struct drbd_tconn *tconn;
1864         struct net_conf *old_conf, *new_conf = NULL;
1865         int err;
1866         int ovr; /* online verify running */
1867         int rsr; /* re-sync running */
1868         struct crypto crypto = { };
1869         bool change_integrity_alg;
1870
1871         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONN);
1872         if (!adm_ctx.reply_skb)
1873                 return retcode;
1874         if (retcode != NO_ERROR)
1875                 goto out;
1876
1877         tconn = adm_ctx.tconn;
1878
1879         new_conf = kzalloc(sizeof(struct net_conf), GFP_KERNEL);
1880         if (!new_conf) {
1881                 retcode = ERR_NOMEM;
1882                 goto out;
1883         }
1884
1885         conn_reconfig_start(tconn);
1886
1887         mutex_lock(&tconn->data.mutex);
1888         mutex_lock(&tconn->conf_update);
1889         old_conf = tconn->net_conf;
1890
1891         if (!old_conf) {
1892                 drbd_msg_put_info("net conf missing, try connect");
1893                 retcode = ERR_INVALID_REQUEST;
1894                 goto fail;
1895         }
1896
1897         *new_conf = *old_conf;
1898         if (should_set_defaults(info))
1899                 set_net_conf_defaults(new_conf);
1900
1901         err = net_conf_from_attrs_for_change(new_conf, info);
1902         if (err) {
1903                 retcode = ERR_MANDATORY_TAG;
1904                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1905                 goto fail;
1906         }
1907
1908         retcode = check_net_options(tconn, new_conf);
1909         if (retcode != NO_ERROR)
1910                 goto fail;
1911
1912         /* re-sync running */
1913         rsr = conn_resync_running(tconn);
1914         if (rsr && strcmp(new_conf->csums_alg, old_conf->csums_alg)) {
1915                 retcode = ERR_CSUMS_RESYNC_RUNNING;
1916                 goto fail;
1917         }
1918
1919         /* online verify running */
1920         ovr = conn_ov_running(tconn);
1921         if (ovr && strcmp(new_conf->verify_alg, old_conf->verify_alg)) {
1922                 retcode = ERR_VERIFY_RUNNING;
1923                 goto fail;
1924         }
1925
1926         change_integrity_alg = strcmp(old_conf->integrity_alg,
1927                                       new_conf->integrity_alg);
1928
1929         retcode = alloc_crypto(&crypto, new_conf);
1930         if (retcode != NO_ERROR)
1931                 goto fail;
1932
1933         rcu_assign_pointer(tconn->net_conf, new_conf);
1934
1935         if (!rsr) {
1936                 crypto_free_hash(tconn->csums_tfm);
1937                 tconn->csums_tfm = crypto.csums_tfm;
1938                 crypto.csums_tfm = NULL;
1939         }
1940         if (!ovr) {
1941                 crypto_free_hash(tconn->verify_tfm);
1942                 tconn->verify_tfm = crypto.verify_tfm;
1943                 crypto.verify_tfm = NULL;
1944         }
1945
1946         kfree(tconn->int_dig_in);
1947         tconn->int_dig_in = crypto.int_dig_in;
1948         kfree(tconn->int_dig_vv);
1949         tconn->int_dig_vv = crypto.int_dig_vv;
1950         crypto_free_hash(tconn->integrity_tfm);
1951         tconn->integrity_tfm = crypto.integrity_tfm;
1952         if (change_integrity_alg) {
1953                 /* Do this without trying to take tconn->data.mutex again.  */
1954                 if (__drbd_send_protocol(tconn))
1955                         goto fail;
1956         }
1957
1958         /* FIXME Changing cram_hmac while the connection is established is useless */
1959         crypto_free_hash(tconn->cram_hmac_tfm);
1960         tconn->cram_hmac_tfm = crypto.cram_hmac_tfm;
1961
1962         mutex_unlock(&tconn->conf_update);
1963         mutex_unlock(&tconn->data.mutex);
1964         synchronize_rcu();
1965         kfree(old_conf);
1966
1967         if (tconn->cstate >= C_WF_REPORT_PARAMS)
1968                 drbd_send_sync_param(minor_to_mdev(conn_lowest_minor(tconn)));
1969
1970         goto done;
1971
1972  fail:
1973         mutex_unlock(&tconn->conf_update);
1974         mutex_unlock(&tconn->data.mutex);
1975         free_crypto(&crypto);
1976         kfree(new_conf);
1977  done:
1978         conn_reconfig_done(tconn);
1979  out:
1980         drbd_adm_finish(info, retcode);
1981         return 0;
1982 }
1983
1984 int drbd_adm_connect(struct sk_buff *skb, struct genl_info *info)
1985 {
1986         struct drbd_conf *mdev;
1987         struct net_conf *old_conf, *new_conf = NULL;
1988         struct crypto crypto = { };
1989         struct drbd_tconn *oconn;
1990         struct drbd_tconn *tconn;
1991         struct sockaddr *new_my_addr, *new_peer_addr, *taken_addr;
1992         enum drbd_ret_code retcode;
1993         int i;
1994         int err;
1995
1996         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONN);
1997         if (!adm_ctx.reply_skb)
1998                 return retcode;
1999         if (retcode != NO_ERROR)
2000                 goto out;
2001
2002         tconn = adm_ctx.tconn;
2003         conn_reconfig_start(tconn);
2004
2005         if (tconn->cstate > C_STANDALONE) {
2006                 retcode = ERR_NET_CONFIGURED;
2007                 goto fail;
2008         }
2009
2010         /* allocation not in the IO path, cqueue thread context */
2011         new_conf = kzalloc(sizeof(*new_conf), GFP_KERNEL);
2012         if (!new_conf) {
2013                 retcode = ERR_NOMEM;
2014                 goto fail;
2015         }
2016
2017         set_net_conf_defaults(new_conf);
2018
2019         err = net_conf_from_attrs(new_conf, info);
2020         if (err) {
2021                 retcode = ERR_MANDATORY_TAG;
2022                 drbd_msg_put_info(from_attrs_err_to_txt(err));
2023                 goto fail;
2024         }
2025
2026         retcode = check_net_options(tconn, new_conf);
2027         if (retcode != NO_ERROR)
2028                 goto fail;
2029
2030         retcode = NO_ERROR;
2031
2032         new_my_addr = (struct sockaddr *)&new_conf->my_addr;
2033         new_peer_addr = (struct sockaddr *)&new_conf->peer_addr;
2034
2035         /* No need for _rcu here. All reconfiguration is
2036          * strictly serialized on genl_lock(). We are protected against
2037          * concurrent reconfiguration/addition/deletion */
2038         list_for_each_entry(oconn, &drbd_tconns, all_tconn) {
2039                 struct net_conf *nc;
2040                 if (oconn == tconn)
2041                         continue;
2042
2043                 rcu_read_lock();
2044                 nc = rcu_dereference(oconn->net_conf);
2045                 if (nc) {
2046                         taken_addr = (struct sockaddr *)&nc->my_addr;
2047                         if (new_conf->my_addr_len == nc->my_addr_len &&
2048                             !memcmp(new_my_addr, taken_addr, new_conf->my_addr_len))
2049                                 retcode = ERR_LOCAL_ADDR;
2050
2051                         taken_addr = (struct sockaddr *)&nc->peer_addr;
2052                         if (new_conf->peer_addr_len == nc->peer_addr_len &&
2053                             !memcmp(new_peer_addr, taken_addr, new_conf->peer_addr_len))
2054                                 retcode = ERR_PEER_ADDR;
2055                 }
2056                 rcu_read_unlock();
2057                 if (retcode != NO_ERROR)
2058                         goto fail;
2059         }
2060
2061         retcode = alloc_crypto(&crypto, new_conf);
2062         if (retcode != NO_ERROR)
2063                 goto fail;
2064
2065         ((char *)new_conf->shared_secret)[SHARED_SECRET_MAX-1] = 0;
2066
2067         conn_flush_workqueue(tconn);
2068
2069         mutex_lock(&tconn->conf_update);
2070         old_conf = tconn->net_conf;
2071         if (old_conf) {
2072                 retcode = ERR_NET_CONFIGURED;
2073                 mutex_unlock(&tconn->conf_update);
2074                 goto fail;
2075         }
2076         rcu_assign_pointer(tconn->net_conf, new_conf);
2077
2078         conn_free_crypto(tconn);
2079         tconn->int_dig_in = crypto.int_dig_in;
2080         tconn->int_dig_vv = crypto.int_dig_vv;
2081         tconn->cram_hmac_tfm = crypto.cram_hmac_tfm;
2082         tconn->integrity_tfm = crypto.integrity_tfm;
2083         tconn->csums_tfm = crypto.csums_tfm;
2084         tconn->verify_tfm = crypto.verify_tfm;
2085
2086         mutex_unlock(&tconn->conf_update);
2087
2088         rcu_read_lock();
2089         idr_for_each_entry(&tconn->volumes, mdev, i) {
2090                 mdev->send_cnt = 0;
2091                 mdev->recv_cnt = 0;
2092         }
2093         rcu_read_unlock();
2094
2095         retcode = conn_request_state(tconn, NS(conn, C_UNCONNECTED), CS_VERBOSE);
2096
2097         conn_reconfig_done(tconn);
2098         drbd_adm_finish(info, retcode);
2099         return 0;
2100
2101 fail:
2102         free_crypto(&crypto);
2103         kfree(new_conf);
2104
2105         conn_reconfig_done(tconn);
2106 out:
2107         drbd_adm_finish(info, retcode);
2108         return 0;
2109 }
2110
2111 static enum drbd_state_rv conn_try_disconnect(struct drbd_tconn *tconn, bool force)
2112 {
2113         enum drbd_state_rv rv;
2114
2115         rv = conn_request_state(tconn, NS(conn, C_DISCONNECTING),
2116                         force ? CS_HARD : 0);
2117
2118         switch (rv) {
2119         case SS_NOTHING_TO_DO:
2120                 break;
2121         case SS_ALREADY_STANDALONE:
2122                 return SS_SUCCESS;
2123         case SS_PRIMARY_NOP:
2124                 /* Our state checking code wants to see the peer outdated. */
2125                 rv = conn_request_state(tconn, NS2(conn, C_DISCONNECTING,
2126                                                 pdsk, D_OUTDATED), CS_VERBOSE);
2127                 break;
2128         case SS_CW_FAILED_BY_PEER:
2129                 /* The peer probably wants to see us outdated. */
2130                 rv = conn_request_state(tconn, NS2(conn, C_DISCONNECTING,
2131                                                         disk, D_OUTDATED), 0);
2132                 if (rv == SS_IS_DISKLESS || rv == SS_LOWER_THAN_OUTDATED) {
2133                         rv = conn_request_state(tconn, NS(conn, C_DISCONNECTING),
2134                                         CS_HARD);
2135                 }
2136                 break;
2137         default:;
2138                 /* no special handling necessary */
2139         }
2140
2141         if (rv >= SS_SUCCESS) {
2142                 enum drbd_state_rv rv2;
2143                 /* No one else can reconfigure the network while I am here.
2144                  * The state handling only uses drbd_thread_stop_nowait(),
2145                  * we want to really wait here until the receiver is no more.
2146                  */
2147                 drbd_thread_stop(&adm_ctx.tconn->receiver);
2148
2149                 /* Race breaker.  This additional state change request may be
2150                  * necessary, if this was a forced disconnect during a receiver
2151                  * restart.  We may have "killed" the receiver thread just
2152                  * after drbdd_init() returned.  Typically, we should be
2153                  * C_STANDALONE already, now, and this becomes a no-op.
2154                  */
2155                 rv2 = conn_request_state(tconn, NS(conn, C_STANDALONE),
2156                                 CS_VERBOSE | CS_HARD);
2157                 if (rv2 < SS_SUCCESS)
2158                         conn_err(tconn,
2159                                 "unexpected rv2=%d in conn_try_disconnect()\n",
2160                                 rv2);
2161         }
2162         return rv;
2163 }
2164
2165 int drbd_adm_disconnect(struct sk_buff *skb, struct genl_info *info)
2166 {
2167         struct disconnect_parms parms;
2168         struct drbd_tconn *tconn;
2169         enum drbd_state_rv rv;
2170         enum drbd_ret_code retcode;
2171         int err;
2172
2173         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONN);
2174         if (!adm_ctx.reply_skb)
2175                 return retcode;
2176         if (retcode != NO_ERROR)
2177                 goto fail;
2178
2179         tconn = adm_ctx.tconn;
2180         memset(&parms, 0, sizeof(parms));
2181         if (info->attrs[DRBD_NLA_DISCONNECT_PARMS]) {
2182                 err = disconnect_parms_from_attrs(&parms, info);
2183                 if (err) {
2184                         retcode = ERR_MANDATORY_TAG;
2185                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2186                         goto fail;
2187                 }
2188         }
2189
2190         rv = conn_try_disconnect(tconn, parms.force_disconnect);
2191         if (rv < SS_SUCCESS)
2192                 retcode = rv;  /* FIXME: Type mismatch. */
2193         else
2194                 retcode = NO_ERROR;
2195  fail:
2196         drbd_adm_finish(info, retcode);
2197         return 0;
2198 }
2199
2200 void resync_after_online_grow(struct drbd_conf *mdev)
2201 {
2202         int iass; /* I am sync source */
2203
2204         dev_info(DEV, "Resync of new storage after online grow\n");
2205         if (mdev->state.role != mdev->state.peer)
2206                 iass = (mdev->state.role == R_PRIMARY);
2207         else
2208                 iass = test_bit(DISCARD_CONCURRENT, &mdev->tconn->flags);
2209
2210         if (iass)
2211                 drbd_start_resync(mdev, C_SYNC_SOURCE);
2212         else
2213                 _drbd_request_state(mdev, NS(conn, C_WF_SYNC_UUID), CS_VERBOSE + CS_SERIALIZE);
2214 }
2215
2216 int drbd_adm_resize(struct sk_buff *skb, struct genl_info *info)
2217 {
2218         struct disk_conf *old_disk_conf, *new_disk_conf = NULL;
2219         struct resize_parms rs;
2220         struct drbd_conf *mdev;
2221         enum drbd_ret_code retcode;
2222         enum determine_dev_size dd;
2223         enum dds_flags ddsf;
2224         sector_t u_size;
2225         int err;
2226
2227         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2228         if (!adm_ctx.reply_skb)
2229                 return retcode;
2230         if (retcode != NO_ERROR)
2231                 goto fail;
2232
2233         memset(&rs, 0, sizeof(struct resize_parms));
2234         if (info->attrs[DRBD_NLA_RESIZE_PARMS]) {
2235                 err = resize_parms_from_attrs(&rs, info);
2236                 if (err) {
2237                         retcode = ERR_MANDATORY_TAG;
2238                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2239                         goto fail;
2240                 }
2241         }
2242
2243         mdev = adm_ctx.mdev;
2244         if (mdev->state.conn > C_CONNECTED) {
2245                 retcode = ERR_RESIZE_RESYNC;
2246                 goto fail;
2247         }
2248
2249         if (mdev->state.role == R_SECONDARY &&
2250             mdev->state.peer == R_SECONDARY) {
2251                 retcode = ERR_NO_PRIMARY;
2252                 goto fail;
2253         }
2254
2255         if (!get_ldev(mdev)) {
2256                 retcode = ERR_NO_DISK;
2257                 goto fail;
2258         }
2259
2260         if (rs.no_resync && mdev->tconn->agreed_pro_version < 93) {
2261                 retcode = ERR_NEED_APV_93;
2262                 goto fail;
2263         }
2264
2265         rcu_read_lock();
2266         u_size = rcu_dereference(mdev->ldev->disk_conf)->disk_size;
2267         rcu_read_unlock();
2268         if (u_size != (sector_t)rs.resize_size) {
2269                 new_disk_conf = kmalloc(sizeof(struct disk_conf), GFP_KERNEL);
2270                 if (!new_disk_conf) {
2271                         retcode = ERR_NOMEM;
2272                         goto fail;
2273                 }
2274         }
2275
2276         if (mdev->ldev->known_size != drbd_get_capacity(mdev->ldev->backing_bdev))
2277                 mdev->ldev->known_size = drbd_get_capacity(mdev->ldev->backing_bdev);
2278
2279         if (new_disk_conf) {
2280                 mutex_lock(&mdev->tconn->conf_update);
2281                 old_disk_conf = mdev->ldev->disk_conf;
2282                 *new_disk_conf = *old_disk_conf;
2283                 new_disk_conf->disk_size = (sector_t)rs.resize_size;
2284                 rcu_assign_pointer(mdev->ldev->disk_conf, new_disk_conf);
2285                 mutex_unlock(&mdev->tconn->conf_update);
2286                 synchronize_rcu();
2287                 kfree(old_disk_conf);
2288         }
2289
2290         ddsf = (rs.resize_force ? DDSF_FORCED : 0) | (rs.no_resync ? DDSF_NO_RESYNC : 0);
2291         dd = drbd_determine_dev_size(mdev, ddsf);
2292         drbd_md_sync(mdev);
2293         put_ldev(mdev);
2294         if (dd == dev_size_error) {
2295                 retcode = ERR_NOMEM_BITMAP;
2296                 goto fail;
2297         }
2298
2299         if (mdev->state.conn == C_CONNECTED) {
2300                 if (dd == grew)
2301                         set_bit(RESIZE_PENDING, &mdev->flags);
2302
2303                 drbd_send_uuids(mdev);
2304                 drbd_send_sizes(mdev, 1, ddsf);
2305         }
2306
2307  fail:
2308         drbd_adm_finish(info, retcode);
2309         return 0;
2310 }
2311
2312 void drbd_set_res_opts_defaults(struct res_opts *r)
2313 {
2314         return set_res_opts_defaults(r);
2315 }
2316
2317 int drbd_adm_resource_opts(struct sk_buff *skb, struct genl_info *info)
2318 {
2319         enum drbd_ret_code retcode;
2320         cpumask_var_t new_cpu_mask;
2321         struct drbd_tconn *tconn;
2322         struct res_opts res_opts;
2323         int err;
2324
2325         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONN);
2326         if (!adm_ctx.reply_skb)
2327                 return retcode;
2328         if (retcode != NO_ERROR)
2329                 goto fail;
2330         tconn = adm_ctx.tconn;
2331
2332         if (!zalloc_cpumask_var(&new_cpu_mask, GFP_KERNEL)) {
2333                 retcode = ERR_NOMEM;
2334                 drbd_msg_put_info("unable to allocate cpumask");
2335                 goto fail;
2336         }
2337
2338         res_opts = tconn->res_opts;
2339         if (should_set_defaults(info))
2340                 set_res_opts_defaults(&res_opts);
2341
2342         err = res_opts_from_attrs(&res_opts, info);
2343         if (err) {
2344                 retcode = ERR_MANDATORY_TAG;
2345                 drbd_msg_put_info(from_attrs_err_to_txt(err));
2346                 goto fail;
2347         }
2348
2349         /* silently ignore cpu mask on UP kernel */
2350         if (nr_cpu_ids > 1 && res_opts.cpu_mask[0] != 0) {
2351                 err = __bitmap_parse(res_opts.cpu_mask, 32, 0,
2352                                 cpumask_bits(new_cpu_mask), nr_cpu_ids);
2353                 if (err) {
2354                         conn_warn(tconn, "__bitmap_parse() failed with %d\n", err);
2355                         retcode = ERR_CPU_MASK_PARSE;
2356                         goto fail;
2357                 }
2358         }
2359
2360
2361         tconn->res_opts = res_opts;
2362
2363         if (!cpumask_equal(tconn->cpu_mask, new_cpu_mask)) {
2364                 cpumask_copy(tconn->cpu_mask, new_cpu_mask);
2365                 drbd_calc_cpu_mask(tconn);
2366                 tconn->receiver.reset_cpu_mask = 1;
2367                 tconn->asender.reset_cpu_mask = 1;
2368                 tconn->worker.reset_cpu_mask = 1;
2369         }
2370
2371 fail:
2372         free_cpumask_var(new_cpu_mask);
2373
2374         drbd_adm_finish(info, retcode);
2375         return 0;
2376 }
2377
2378 int drbd_adm_invalidate(struct sk_buff *skb, struct genl_info *info)
2379 {
2380         struct drbd_conf *mdev;
2381         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
2382
2383         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2384         if (!adm_ctx.reply_skb)
2385                 return retcode;
2386         if (retcode != NO_ERROR)
2387                 goto out;
2388
2389         mdev = adm_ctx.mdev;
2390
2391         /* If there is still bitmap IO pending, probably because of a previous
2392          * resync just being finished, wait for it before requesting a new resync. */
2393         wait_event(mdev->misc_wait, !test_bit(BITMAP_IO, &mdev->flags));
2394
2395         retcode = _drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T), CS_ORDERED);
2396
2397         if (retcode < SS_SUCCESS && retcode != SS_NEED_CONNECTION)
2398                 retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T));
2399
2400         while (retcode == SS_NEED_CONNECTION) {
2401                 spin_lock_irq(&mdev->tconn->req_lock);
2402                 if (mdev->state.conn < C_CONNECTED)
2403                         retcode = _drbd_set_state(_NS(mdev, disk, D_INCONSISTENT), CS_VERBOSE, NULL);
2404                 spin_unlock_irq(&mdev->tconn->req_lock);
2405
2406                 if (retcode != SS_NEED_CONNECTION)
2407                         break;
2408
2409                 retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T));
2410         }
2411
2412 out:
2413         drbd_adm_finish(info, retcode);
2414         return 0;
2415 }
2416
2417 static int drbd_bmio_set_susp_al(struct drbd_conf *mdev)
2418 {
2419         int rv;
2420
2421         rv = drbd_bmio_set_n_write(mdev);
2422         drbd_suspend_al(mdev);
2423         return rv;
2424 }
2425
2426 static int drbd_adm_simple_request_state(struct sk_buff *skb, struct genl_info *info,
2427                 union drbd_state mask, union drbd_state val)
2428 {
2429         enum drbd_ret_code retcode;
2430
2431         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2432         if (!adm_ctx.reply_skb)
2433                 return retcode;
2434         if (retcode != NO_ERROR)
2435                 goto out;
2436
2437         retcode = drbd_request_state(adm_ctx.mdev, mask, val);
2438 out:
2439         drbd_adm_finish(info, retcode);
2440         return 0;
2441 }
2442
2443 int drbd_adm_invalidate_peer(struct sk_buff *skb, struct genl_info *info)
2444 {
2445         return drbd_adm_simple_request_state(skb, info, NS(conn, C_STARTING_SYNC_S));
2446 }
2447
2448 int drbd_adm_pause_sync(struct sk_buff *skb, struct genl_info *info)
2449 {
2450         enum drbd_ret_code retcode;
2451
2452         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2453         if (!adm_ctx.reply_skb)
2454                 return retcode;
2455         if (retcode != NO_ERROR)
2456                 goto out;
2457
2458         if (drbd_request_state(adm_ctx.mdev, NS(user_isp, 1)) == SS_NOTHING_TO_DO)
2459                 retcode = ERR_PAUSE_IS_SET;
2460 out:
2461         drbd_adm_finish(info, retcode);
2462         return 0;
2463 }
2464
2465 int drbd_adm_resume_sync(struct sk_buff *skb, struct genl_info *info)
2466 {
2467         union drbd_dev_state s;
2468         enum drbd_ret_code retcode;
2469
2470         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2471         if (!adm_ctx.reply_skb)
2472                 return retcode;
2473         if (retcode != NO_ERROR)
2474                 goto out;
2475
2476         if (drbd_request_state(adm_ctx.mdev, NS(user_isp, 0)) == SS_NOTHING_TO_DO) {
2477                 s = adm_ctx.mdev->state;
2478                 if (s.conn == C_PAUSED_SYNC_S || s.conn == C_PAUSED_SYNC_T) {
2479                         retcode = s.aftr_isp ? ERR_PIC_AFTER_DEP :
2480                                   s.peer_isp ? ERR_PIC_PEER_DEP : ERR_PAUSE_IS_CLEAR;
2481                 } else {
2482                         retcode = ERR_PAUSE_IS_CLEAR;
2483                 }
2484         }
2485
2486 out:
2487         drbd_adm_finish(info, retcode);
2488         return 0;
2489 }
2490
2491 int drbd_adm_suspend_io(struct sk_buff *skb, struct genl_info *info)
2492 {
2493         return drbd_adm_simple_request_state(skb, info, NS(susp, 1));
2494 }
2495
2496 int drbd_adm_resume_io(struct sk_buff *skb, struct genl_info *info)
2497 {
2498         struct drbd_conf *mdev;
2499         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
2500
2501         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2502         if (!adm_ctx.reply_skb)
2503                 return retcode;
2504         if (retcode != NO_ERROR)
2505                 goto out;
2506
2507         mdev = adm_ctx.mdev;
2508         if (test_bit(NEW_CUR_UUID, &mdev->flags)) {
2509                 drbd_uuid_new_current(mdev);
2510                 clear_bit(NEW_CUR_UUID, &mdev->flags);
2511         }
2512         drbd_suspend_io(mdev);
2513         retcode = drbd_request_state(mdev, NS3(susp, 0, susp_nod, 0, susp_fen, 0));
2514         if (retcode == SS_SUCCESS) {
2515                 if (mdev->state.conn < C_CONNECTED)
2516                         tl_clear(mdev->tconn);
2517                 if (mdev->state.disk == D_DISKLESS || mdev->state.disk == D_FAILED)
2518                         tl_restart(mdev->tconn, FAIL_FROZEN_DISK_IO);
2519         }
2520         drbd_resume_io(mdev);
2521
2522 out:
2523         drbd_adm_finish(info, retcode);
2524         return 0;
2525 }
2526
2527 int drbd_adm_outdate(struct sk_buff *skb, struct genl_info *info)
2528 {
2529         return drbd_adm_simple_request_state(skb, info, NS(disk, D_OUTDATED));
2530 }
2531
2532 int nla_put_drbd_cfg_context(struct sk_buff *skb, const char *conn_name, unsigned vnr)
2533 {
2534         struct nlattr *nla;
2535         nla = nla_nest_start(skb, DRBD_NLA_CFG_CONTEXT);
2536         if (!nla)
2537                 goto nla_put_failure;
2538         if (vnr != VOLUME_UNSPECIFIED)
2539                 NLA_PUT_U32(skb, T_ctx_volume, vnr);
2540         NLA_PUT_STRING(skb, T_ctx_conn_name, conn_name);
2541         nla_nest_end(skb, nla);
2542         return 0;
2543
2544 nla_put_failure:
2545         if (nla)
2546                 nla_nest_cancel(skb, nla);
2547         return -EMSGSIZE;
2548 }
2549
2550 int nla_put_status_info(struct sk_buff *skb, struct drbd_conf *mdev,
2551                 const struct sib_info *sib)
2552 {
2553         struct state_info *si = NULL; /* for sizeof(si->member); */
2554         struct net_conf *nc;
2555         struct nlattr *nla;
2556         int got_ldev;
2557         int err = 0;
2558         int exclude_sensitive;
2559
2560         /* If sib != NULL, this is drbd_bcast_event, which anyone can listen
2561          * to.  So we better exclude_sensitive information.
2562          *
2563          * If sib == NULL, this is drbd_adm_get_status, executed synchronously
2564          * in the context of the requesting user process. Exclude sensitive
2565          * information, unless current has superuser.
2566          *
2567          * NOTE: for drbd_adm_get_status_all(), this is a netlink dump, and
2568          * relies on the current implementation of netlink_dump(), which
2569          * executes the dump callback successively from netlink_recvmsg(),
2570          * always in the context of the receiving process */
2571         exclude_sensitive = sib || !capable(CAP_SYS_ADMIN);
2572
2573         got_ldev = get_ldev(mdev);
2574
2575         /* We need to add connection name and volume number information still.
2576          * Minor number is in drbd_genlmsghdr. */
2577         if (nla_put_drbd_cfg_context(skb, mdev->tconn->name, mdev->vnr))
2578                 goto nla_put_failure;
2579
2580         if (res_opts_to_skb(skb, &mdev->tconn->res_opts, exclude_sensitive))
2581                 goto nla_put_failure;
2582
2583         rcu_read_lock();
2584         if (got_ldev)
2585                 if (disk_conf_to_skb(skb, rcu_dereference(mdev->ldev->disk_conf), exclude_sensitive))
2586                         goto nla_put_failure;
2587
2588         nc = rcu_dereference(mdev->tconn->net_conf);
2589         if (nc)
2590                 err = net_conf_to_skb(skb, nc, exclude_sensitive);
2591         rcu_read_unlock();
2592         if (err)
2593                 goto nla_put_failure;
2594
2595         nla = nla_nest_start(skb, DRBD_NLA_STATE_INFO);
2596         if (!nla)
2597                 goto nla_put_failure;
2598         NLA_PUT_U32(skb, T_sib_reason, sib ? sib->sib_reason : SIB_GET_STATUS_REPLY);
2599         NLA_PUT_U32(skb, T_current_state, mdev->state.i);
2600         NLA_PUT_U64(skb, T_ed_uuid, mdev->ed_uuid);
2601         NLA_PUT_U64(skb, T_capacity, drbd_get_capacity(mdev->this_bdev));
2602
2603         if (got_ldev) {
2604                 NLA_PUT_U32(skb, T_disk_flags, mdev->ldev->md.flags);
2605                 NLA_PUT(skb, T_uuids, sizeof(si->uuids), mdev->ldev->md.uuid);
2606                 NLA_PUT_U64(skb, T_bits_total, drbd_bm_bits(mdev));
2607                 NLA_PUT_U64(skb, T_bits_oos, drbd_bm_total_weight(mdev));
2608                 if (C_SYNC_SOURCE <= mdev->state.conn &&
2609                     C_PAUSED_SYNC_T >= mdev->state.conn) {
2610                         NLA_PUT_U64(skb, T_bits_rs_total, mdev->rs_total);
2611                         NLA_PUT_U64(skb, T_bits_rs_failed, mdev->rs_failed);
2612                 }
2613         }
2614
2615         if (sib) {
2616                 switch(sib->sib_reason) {
2617                 case SIB_SYNC_PROGRESS:
2618                 case SIB_GET_STATUS_REPLY:
2619                         break;
2620                 case SIB_STATE_CHANGE:
2621                         NLA_PUT_U32(skb, T_prev_state, sib->os.i);
2622                         NLA_PUT_U32(skb, T_new_state, sib->ns.i);
2623                         break;
2624                 case SIB_HELPER_POST:
2625                         NLA_PUT_U32(skb,
2626                                 T_helper_exit_code, sib->helper_exit_code);
2627                         /* fall through */
2628                 case SIB_HELPER_PRE:
2629                         NLA_PUT_STRING(skb, T_helper, sib->helper_name);
2630                         break;
2631                 }
2632         }
2633         nla_nest_end(skb, nla);
2634
2635         if (0)
2636 nla_put_failure:
2637                 err = -EMSGSIZE;
2638         if (got_ldev)
2639                 put_ldev(mdev);
2640         return err;
2641 }
2642
2643 int drbd_adm_get_status(struct sk_buff *skb, struct genl_info *info)
2644 {
2645         enum drbd_ret_code retcode;
2646         int err;
2647
2648         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2649         if (!adm_ctx.reply_skb)
2650                 return retcode;
2651         if (retcode != NO_ERROR)
2652                 goto out;
2653
2654         err = nla_put_status_info(adm_ctx.reply_skb, adm_ctx.mdev, NULL);
2655         if (err) {
2656                 nlmsg_free(adm_ctx.reply_skb);
2657                 return err;
2658         }
2659 out:
2660         drbd_adm_finish(info, retcode);
2661         return 0;
2662 }
2663
2664 int get_one_status(struct sk_buff *skb, struct netlink_callback *cb)
2665 {
2666         struct drbd_conf *mdev;
2667         struct drbd_genlmsghdr *dh;
2668         struct drbd_tconn *pos = (struct drbd_tconn*)cb->args[0];
2669         struct drbd_tconn *tconn = NULL;
2670         struct drbd_tconn *tmp;
2671         unsigned volume = cb->args[1];
2672
2673         /* Open coded, deferred, iteration:
2674          * list_for_each_entry_safe(tconn, tmp, &drbd_tconns, all_tconn) {
2675          *      idr_for_each_entry(&tconn->volumes, mdev, i) {
2676          *        ...
2677          *      }
2678          * }
2679          * where tconn is cb->args[0];
2680          * and i is cb->args[1];
2681          *
2682          * cb->args[2] indicates if we shall loop over all resources,
2683          * or just dump all volumes of a single resource.
2684          *
2685          * This may miss entries inserted after this dump started,
2686          * or entries deleted before they are reached.
2687          *
2688          * We need to make sure the mdev won't disappear while
2689          * we are looking at it, and revalidate our iterators
2690          * on each iteration.
2691          */
2692
2693         /* synchronize with conn_create()/conn_destroy() */
2694         rcu_read_lock();
2695         /* revalidate iterator position */
2696         list_for_each_entry_rcu(tmp, &drbd_tconns, all_tconn) {
2697                 if (pos == NULL) {
2698                         /* first iteration */
2699                         pos = tmp;
2700                         tconn = pos;
2701                         break;
2702                 }
2703                 if (tmp == pos) {
2704                         tconn = pos;
2705                         break;
2706                 }
2707         }
2708         if (tconn) {
2709 next_tconn:
2710                 mdev = idr_get_next(&tconn->volumes, &volume);
2711                 if (!mdev) {
2712                         /* No more volumes to dump on this tconn.
2713                          * Advance tconn iterator. */
2714                         pos = list_entry_rcu(tconn->all_tconn.next,
2715                                              struct drbd_tconn, all_tconn);
2716                         /* Did we dump any volume on this tconn yet? */
2717                         if (volume != 0) {
2718                                 /* If we reached the end of the list,
2719                                  * or only a single resource dump was requested,
2720                                  * we are done. */
2721                                 if (&pos->all_tconn == &drbd_tconns || cb->args[2])
2722                                         goto out;
2723                                 volume = 0;
2724                                 tconn = pos;
2725                                 goto next_tconn;
2726                         }
2727                 }
2728
2729                 dh = genlmsg_put(skb, NETLINK_CB(cb->skb).pid,
2730                                 cb->nlh->nlmsg_seq, &drbd_genl_family,
2731                                 NLM_F_MULTI, DRBD_ADM_GET_STATUS);
2732                 if (!dh)
2733                         goto out;
2734
2735                 if (!mdev) {
2736                         /* this is a tconn without a single volume */
2737                         dh->minor = -1U;
2738                         dh->ret_code = NO_ERROR;
2739                         if (nla_put_drbd_cfg_context(skb, tconn->name, VOLUME_UNSPECIFIED))
2740                                 genlmsg_cancel(skb, dh);
2741                         else
2742                                 genlmsg_end(skb, dh);
2743                         goto out;
2744                 }
2745
2746                 D_ASSERT(mdev->vnr == volume);
2747                 D_ASSERT(mdev->tconn == tconn);
2748
2749                 dh->minor = mdev_to_minor(mdev);
2750                 dh->ret_code = NO_ERROR;
2751
2752                 if (nla_put_status_info(skb, mdev, NULL)) {
2753                         genlmsg_cancel(skb, dh);
2754                         goto out;
2755                 }
2756                 genlmsg_end(skb, dh);
2757         }
2758
2759 out:
2760         rcu_read_unlock();
2761         /* where to start the next iteration */
2762         cb->args[0] = (long)pos;
2763         cb->args[1] = (pos == tconn) ? volume + 1 : 0;
2764
2765         /* No more tconns/volumes/minors found results in an empty skb.
2766          * Which will terminate the dump. */
2767         return skb->len;
2768 }
2769
2770 /*
2771  * Request status of all resources, or of all volumes within a single resource.
2772  *
2773  * This is a dump, as the answer may not fit in a single reply skb otherwise.
2774  * Which means we cannot use the family->attrbuf or other such members, because
2775  * dump is NOT protected by the genl_lock().  During dump, we only have access
2776  * to the incoming skb, and need to opencode "parsing" of the nlattr payload.
2777  *
2778  * Once things are setup properly, we call into get_one_status().
2779  */
2780 int drbd_adm_get_status_all(struct sk_buff *skb, struct netlink_callback *cb)
2781 {
2782         const unsigned hdrlen = GENL_HDRLEN + GENL_MAGIC_FAMILY_HDRSZ;
2783         struct nlattr *nla;
2784         const char *conn_name;
2785         struct drbd_tconn *tconn;
2786
2787         /* Is this a followup call? */
2788         if (cb->args[0]) {
2789                 /* ... of a single resource dump,
2790                  * and the resource iterator has been advanced already? */
2791                 if (cb->args[2] && cb->args[2] != cb->args[0])
2792                         return 0; /* DONE. */
2793                 goto dump;
2794         }
2795
2796         /* First call (from netlink_dump_start).  We need to figure out
2797          * which resource(s) the user wants us to dump. */
2798         nla = nla_find(nlmsg_attrdata(cb->nlh, hdrlen),
2799                         nlmsg_attrlen(cb->nlh, hdrlen),
2800                         DRBD_NLA_CFG_CONTEXT);
2801
2802         /* No explicit context given.  Dump all. */
2803         if (!nla)
2804                 goto dump;
2805         nla = nla_find_nested(nla, __nla_type(T_ctx_conn_name));
2806         /* context given, but no name present? */
2807         if (!nla)
2808                 return -EINVAL;
2809         conn_name = nla_data(nla);
2810         tconn = conn_get_by_name(conn_name);
2811
2812         if (!tconn)
2813                 return -ENODEV;
2814
2815         kref_put(&tconn->kref, &conn_destroy); /* get_one_status() (re)validates tconn by itself */
2816
2817         /* prime iterators, and set "filter" mode mark:
2818          * only dump this tconn. */
2819         cb->args[0] = (long)tconn;
2820         /* cb->args[1] = 0; passed in this way. */
2821         cb->args[2] = (long)tconn;
2822
2823 dump:
2824         return get_one_status(skb, cb);
2825 }
2826
2827 int drbd_adm_get_timeout_type(struct sk_buff *skb, struct genl_info *info)
2828 {
2829         enum drbd_ret_code retcode;
2830         struct timeout_parms tp;
2831         int err;
2832
2833         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2834         if (!adm_ctx.reply_skb)
2835                 return retcode;
2836         if (retcode != NO_ERROR)
2837                 goto out;
2838
2839         tp.timeout_type =
2840                 adm_ctx.mdev->state.pdsk == D_OUTDATED ? UT_PEER_OUTDATED :
2841                 test_bit(USE_DEGR_WFC_T, &adm_ctx.mdev->flags) ? UT_DEGRADED :
2842                 UT_DEFAULT;
2843
2844         err = timeout_parms_to_priv_skb(adm_ctx.reply_skb, &tp);
2845         if (err) {
2846                 nlmsg_free(adm_ctx.reply_skb);
2847                 return err;
2848         }
2849 out:
2850         drbd_adm_finish(info, retcode);
2851         return 0;
2852 }
2853
2854 int drbd_adm_start_ov(struct sk_buff *skb, struct genl_info *info)
2855 {
2856         struct drbd_conf *mdev;
2857         enum drbd_ret_code retcode;
2858
2859         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2860         if (!adm_ctx.reply_skb)
2861                 return retcode;
2862         if (retcode != NO_ERROR)
2863                 goto out;
2864
2865         mdev = adm_ctx.mdev;
2866         if (info->attrs[DRBD_NLA_START_OV_PARMS]) {
2867                 /* resume from last known position, if possible */
2868                 struct start_ov_parms parms =
2869                         { .ov_start_sector = mdev->ov_start_sector };
2870                 int err = start_ov_parms_from_attrs(&parms, info);
2871                 if (err) {
2872                         retcode = ERR_MANDATORY_TAG;
2873                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2874                         goto out;
2875                 }
2876                 /* w_make_ov_request expects position to be aligned */
2877                 mdev->ov_start_sector = parms.ov_start_sector & ~BM_SECT_PER_BIT;
2878         }
2879         /* If there is still bitmap IO pending, e.g. previous resync or verify
2880          * just being finished, wait for it before requesting a new resync. */
2881         wait_event(mdev->misc_wait, !test_bit(BITMAP_IO, &mdev->flags));
2882         retcode = drbd_request_state(mdev,NS(conn,C_VERIFY_S));
2883 out:
2884         drbd_adm_finish(info, retcode);
2885         return 0;
2886 }
2887
2888
2889 int drbd_adm_new_c_uuid(struct sk_buff *skb, struct genl_info *info)
2890 {
2891         struct drbd_conf *mdev;
2892         enum drbd_ret_code retcode;
2893         int skip_initial_sync = 0;
2894         int err;
2895         struct new_c_uuid_parms args;
2896
2897         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2898         if (!adm_ctx.reply_skb)
2899                 return retcode;
2900         if (retcode != NO_ERROR)
2901                 goto out_nolock;
2902
2903         mdev = adm_ctx.mdev;
2904         memset(&args, 0, sizeof(args));
2905         if (info->attrs[DRBD_NLA_NEW_C_UUID_PARMS]) {
2906                 err = new_c_uuid_parms_from_attrs(&args, info);
2907                 if (err) {
2908                         retcode = ERR_MANDATORY_TAG;
2909                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2910                         goto out_nolock;
2911                 }
2912         }
2913
2914         mutex_lock(mdev->state_mutex); /* Protects us against serialized state changes. */
2915
2916         if (!get_ldev(mdev)) {
2917                 retcode = ERR_NO_DISK;
2918                 goto out;
2919         }
2920
2921         /* this is "skip initial sync", assume to be clean */
2922         if (mdev->state.conn == C_CONNECTED && mdev->tconn->agreed_pro_version >= 90 &&
2923             mdev->ldev->md.uuid[UI_CURRENT] == UUID_JUST_CREATED && args.clear_bm) {
2924                 dev_info(DEV, "Preparing to skip initial sync\n");
2925                 skip_initial_sync = 1;
2926         } else if (mdev->state.conn != C_STANDALONE) {
2927                 retcode = ERR_CONNECTED;
2928                 goto out_dec;
2929         }
2930
2931         drbd_uuid_set(mdev, UI_BITMAP, 0); /* Rotate UI_BITMAP to History 1, etc... */
2932         drbd_uuid_new_current(mdev); /* New current, previous to UI_BITMAP */
2933
2934         if (args.clear_bm) {
2935                 err = drbd_bitmap_io(mdev, &drbd_bmio_clear_n_write,
2936                         "clear_n_write from new_c_uuid", BM_LOCKED_MASK);
2937                 if (err) {
2938                         dev_err(DEV, "Writing bitmap failed with %d\n",err);
2939                         retcode = ERR_IO_MD_DISK;
2940                 }
2941                 if (skip_initial_sync) {
2942                         drbd_send_uuids_skip_initial_sync(mdev);
2943                         _drbd_uuid_set(mdev, UI_BITMAP, 0);
2944                         drbd_print_uuids(mdev, "cleared bitmap UUID");
2945                         spin_lock_irq(&mdev->tconn->req_lock);
2946                         _drbd_set_state(_NS2(mdev, disk, D_UP_TO_DATE, pdsk, D_UP_TO_DATE),
2947                                         CS_VERBOSE, NULL);
2948                         spin_unlock_irq(&mdev->tconn->req_lock);
2949                 }
2950         }
2951
2952         drbd_md_sync(mdev);
2953 out_dec:
2954         put_ldev(mdev);
2955 out:
2956         mutex_unlock(mdev->state_mutex);
2957 out_nolock:
2958         drbd_adm_finish(info, retcode);
2959         return 0;
2960 }
2961
2962 static enum drbd_ret_code
2963 drbd_check_conn_name(const char *name)
2964 {
2965         if (!name || !name[0]) {
2966                 drbd_msg_put_info("connection name missing");
2967                 return ERR_MANDATORY_TAG;
2968         }
2969         /* if we want to use these in sysfs/configfs/debugfs some day,
2970          * we must not allow slashes */
2971         if (strchr(name, '/')) {
2972                 drbd_msg_put_info("invalid connection name");
2973                 return ERR_INVALID_REQUEST;
2974         }
2975         return NO_ERROR;
2976 }
2977
2978 int drbd_adm_create_connection(struct sk_buff *skb, struct genl_info *info)
2979 {
2980         enum drbd_ret_code retcode;
2981
2982         retcode = drbd_adm_prepare(skb, info, 0);
2983         if (!adm_ctx.reply_skb)
2984                 return retcode;
2985         if (retcode != NO_ERROR)
2986                 goto out;
2987
2988         retcode = drbd_check_conn_name(adm_ctx.conn_name);
2989         if (retcode != NO_ERROR)
2990                 goto out;
2991
2992         if (adm_ctx.tconn) {
2993                 if (info->nlhdr->nlmsg_flags & NLM_F_EXCL) {
2994                         retcode = ERR_INVALID_REQUEST;
2995                         drbd_msg_put_info("connection exists");
2996                 }
2997                 /* else: still NO_ERROR */
2998                 goto out;
2999         }
3000
3001         if (!conn_create(adm_ctx.conn_name))
3002                 retcode = ERR_NOMEM;
3003 out:
3004         drbd_adm_finish(info, retcode);
3005         return 0;
3006 }
3007
3008 int drbd_adm_add_minor(struct sk_buff *skb, struct genl_info *info)
3009 {
3010         struct drbd_genlmsghdr *dh = info->userhdr;
3011         enum drbd_ret_code retcode;
3012
3013         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONN);
3014         if (!adm_ctx.reply_skb)
3015                 return retcode;
3016         if (retcode != NO_ERROR)
3017                 goto out;
3018
3019         /* FIXME drop minor_count parameter, limit to MINORMASK */
3020         if (dh->minor >= minor_count) {
3021                 drbd_msg_put_info("requested minor out of range");
3022                 retcode = ERR_INVALID_REQUEST;
3023                 goto out;
3024         }
3025         if (adm_ctx.volume > DRBD_VOLUME_MAX) {
3026                 drbd_msg_put_info("requested volume id out of range");
3027                 retcode = ERR_INVALID_REQUEST;
3028                 goto out;
3029         }
3030
3031         /* drbd_adm_prepare made sure already
3032          * that mdev->tconn and mdev->vnr match the request. */
3033         if (adm_ctx.mdev) {
3034                 if (info->nlhdr->nlmsg_flags & NLM_F_EXCL)
3035                         retcode = ERR_MINOR_EXISTS;
3036                 /* else: still NO_ERROR */
3037                 goto out;
3038         }
3039
3040         retcode = conn_new_minor(adm_ctx.tconn, dh->minor, adm_ctx.volume);
3041 out:
3042         drbd_adm_finish(info, retcode);
3043         return 0;
3044 }
3045
3046 static enum drbd_ret_code adm_delete_minor(struct drbd_conf *mdev)
3047 {
3048         if (mdev->state.disk == D_DISKLESS &&
3049             /* no need to be mdev->state.conn == C_STANDALONE &&
3050              * we may want to delete a minor from a live replication group.
3051              */
3052             mdev->state.role == R_SECONDARY) {
3053                 idr_remove(&mdev->tconn->volumes, mdev->vnr);
3054                 idr_remove(&minors, mdev_to_minor(mdev));
3055                 del_gendisk(mdev->vdisk);
3056                 synchronize_rcu();
3057                 kref_put(&mdev->kref, &drbd_minor_destroy);
3058                 return NO_ERROR;
3059         } else
3060                 return ERR_MINOR_CONFIGURED;
3061 }
3062
3063 int drbd_adm_delete_minor(struct sk_buff *skb, struct genl_info *info)
3064 {
3065         enum drbd_ret_code retcode;
3066
3067         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
3068         if (!adm_ctx.reply_skb)
3069                 return retcode;
3070         if (retcode != NO_ERROR)
3071                 goto out;
3072
3073         retcode = adm_delete_minor(adm_ctx.mdev);
3074 out:
3075         drbd_adm_finish(info, retcode);
3076         return 0;
3077 }
3078
3079 int drbd_adm_down(struct sk_buff *skb, struct genl_info *info)
3080 {
3081         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
3082         struct drbd_conf *mdev;
3083         unsigned i;
3084
3085         retcode = drbd_adm_prepare(skb, info, 0);
3086         if (!adm_ctx.reply_skb)
3087                 return retcode;
3088         if (retcode != NO_ERROR)
3089                 goto out;
3090
3091         if (!adm_ctx.tconn) {
3092                 retcode = ERR_CONN_NOT_KNOWN;
3093                 goto out;
3094         }
3095
3096         /* demote */
3097         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3098                 retcode = drbd_set_role(mdev, R_SECONDARY, 0);
3099                 if (retcode < SS_SUCCESS) {
3100                         drbd_msg_put_info("failed to demote");
3101                         goto out;
3102                 }
3103         }
3104
3105         retcode = conn_try_disconnect(adm_ctx.tconn, 0);
3106         if (retcode < SS_SUCCESS) {
3107                 drbd_msg_put_info("failed to disconnect");
3108                 goto out;
3109         }
3110
3111         /* detach */
3112         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3113                 retcode = adm_detach(mdev);
3114                 if (retcode < SS_SUCCESS) {
3115                         drbd_msg_put_info("failed to detach");
3116                         goto out;
3117                 }
3118         }
3119
3120         /* If we reach this, all volumes (of this tconn) are Secondary,
3121          * Disconnected, Diskless, aka Unconfigured. Make sure all threads have
3122          * actually stopped, state handling only does drbd_thread_stop_nowait(). */
3123         drbd_thread_stop(&adm_ctx.tconn->worker);
3124
3125         /* Now, nothing can fail anymore */
3126
3127         /* delete volumes */
3128         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3129                 retcode = adm_delete_minor(mdev);
3130                 if (retcode != NO_ERROR) {
3131                         /* "can not happen" */
3132                         drbd_msg_put_info("failed to delete volume");
3133                         goto out;
3134                 }
3135         }
3136
3137         /* delete connection */
3138         if (conn_lowest_minor(adm_ctx.tconn) < 0) {
3139                 list_del_rcu(&adm_ctx.tconn->all_tconn);
3140                 synchronize_rcu();
3141                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
3142
3143                 retcode = NO_ERROR;
3144         } else {
3145                 /* "can not happen" */
3146                 retcode = ERR_CONN_IN_USE;
3147                 drbd_msg_put_info("failed to delete connection");
3148         }
3149         goto out;
3150 out:
3151         drbd_adm_finish(info, retcode);
3152         return 0;
3153 }
3154
3155 int drbd_adm_delete_connection(struct sk_buff *skb, struct genl_info *info)
3156 {
3157         enum drbd_ret_code retcode;
3158
3159         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONN);
3160         if (!adm_ctx.reply_skb)
3161                 return retcode;
3162         if (retcode != NO_ERROR)
3163                 goto out;
3164
3165         if (conn_lowest_minor(adm_ctx.tconn) < 0) {
3166                 list_del_rcu(&adm_ctx.tconn->all_tconn);
3167                 synchronize_rcu();
3168                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
3169
3170                 retcode = NO_ERROR;
3171         } else {
3172                 retcode = ERR_CONN_IN_USE;
3173         }
3174
3175         if (retcode == NO_ERROR)
3176                 drbd_thread_stop(&adm_ctx.tconn->worker);
3177 out:
3178         drbd_adm_finish(info, retcode);
3179         return 0;
3180 }
3181
3182 void drbd_bcast_event(struct drbd_conf *mdev, const struct sib_info *sib)
3183 {
3184         static atomic_t drbd_genl_seq = ATOMIC_INIT(2); /* two. */
3185         struct sk_buff *msg;
3186         struct drbd_genlmsghdr *d_out;
3187         unsigned seq;
3188         int err = -ENOMEM;
3189
3190         seq = atomic_inc_return(&drbd_genl_seq);
3191         msg = genlmsg_new(NLMSG_GOODSIZE, GFP_NOIO);
3192         if (!msg)
3193                 goto failed;
3194
3195         err = -EMSGSIZE;
3196         d_out = genlmsg_put(msg, 0, seq, &drbd_genl_family, 0, DRBD_EVENT);
3197         if (!d_out) /* cannot happen, but anyways. */
3198                 goto nla_put_failure;
3199         d_out->minor = mdev_to_minor(mdev);
3200         d_out->ret_code = NO_ERROR;
3201
3202         if (nla_put_status_info(msg, mdev, sib))
3203                 goto nla_put_failure;
3204         genlmsg_end(msg, d_out);
3205         err = drbd_genl_multicast_events(msg, 0);
3206         /* msg has been consumed or freed in netlink_broadcast() */
3207         if (err && err != -ESRCH)
3208                 goto failed;
3209
3210         return;
3211
3212 nla_put_failure:
3213         nlmsg_free(msg);
3214 failed:
3215         dev_err(DEV, "Error %d while broadcasting event. "
3216                         "Event seq:%u sib_reason:%u\n",
3217                         err, seq, sib->sib_reason);
3218 }